project.class.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554
  1. <?php
  2. /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  6. * Copyright (C) 2014-2017 Marcos García <marcosgdf@gmail.com>
  7. * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
  8. * Copyright (C) 2019 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  10. * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/projet/class/project.class.php
  27. * \ingroup projet
  28. * \brief File of class to manage projects
  29. */
  30. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  31. /**
  32. * Class to manage projects
  33. */
  34. class Project extends CommonObject
  35. {
  36. /**
  37. * @var string ID to identify managed object
  38. */
  39. public $element = 'project';
  40. /**
  41. * @var string Name of table without prefix where object is stored
  42. */
  43. public $table_element = 'projet';
  44. /**
  45. * @var string Name of subtable line
  46. */
  47. public $table_element_line = 'projet_task';
  48. /**
  49. * @var string Name of field date
  50. */
  51. public $table_element_date;
  52. /**
  53. * @var string Field with ID of parent key if this field has a parent
  54. */
  55. public $fk_element = 'fk_projet';
  56. /**
  57. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  58. * @var int
  59. */
  60. public $ismultientitymanaged = 1;
  61. /**
  62. * @var int Does object support extrafields ? 0=No, 1=Yes
  63. */
  64. public $isextrafieldmanaged = 1;
  65. /**
  66. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  67. */
  68. public $picto = 'project';
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected $table_ref_field = 'ref';
  73. /**
  74. * @var int parent project
  75. */
  76. public $fk_project;
  77. /**
  78. * @var string description
  79. */
  80. public $description;
  81. /**
  82. * @var string
  83. */
  84. public $title;
  85. /**
  86. * @var int Date start
  87. * @deprecated
  88. * @see $date_start
  89. */
  90. public $dateo;
  91. /**
  92. * @var int Date start
  93. */
  94. public $date_start;
  95. /**
  96. * @var int Date end
  97. * @deprecated
  98. * @see $date_end
  99. */
  100. public $datee;
  101. /**
  102. * @var int Date end
  103. */
  104. public $date_end;
  105. /**
  106. * @var int Date start event
  107. */
  108. public $date_start_event;
  109. /**
  110. * @var int Date end event
  111. */
  112. public $date_end_event;
  113. /**
  114. * @var string Location
  115. */
  116. public $location;
  117. /**
  118. * @var int Date close
  119. */
  120. public $date_close;
  121. public $socid; // To store id of thirdparty
  122. public $thirdparty_name; // To store name of thirdparty (defined only in some cases)
  123. public $user_author_id; //!< Id of project creator. Not defined if shared project.
  124. /**
  125. * @var int user close id
  126. */
  127. public $fk_user_close;
  128. public $public; //!< Tell if this is a public or private project
  129. /**
  130. * @var float budget Amount
  131. */
  132. public $budget_amount;
  133. /**
  134. * @var integer Can use projects to follow opportunities
  135. */
  136. public $usage_opportunity;
  137. /**
  138. * @var integer Can follow tasks on project and enter time spent on it
  139. */
  140. public $usage_task;
  141. /**
  142. * @var integer Use to bill task spend time
  143. */
  144. public $usage_bill_time; // Is the time spent on project must be invoiced or not
  145. /**
  146. * @var integer Event organization: Use Event Organization
  147. */
  148. public $usage_organize_event;
  149. /**
  150. * @var integer Event organization: Allow unknown people to suggest new conferences
  151. */
  152. public $accept_conference_suggestions;
  153. /**
  154. * @var integer Event organization: Allow unknown people to suggest new booth
  155. */
  156. public $accept_booth_suggestions;
  157. /**
  158. * @var float Event organization: registration price
  159. */
  160. public $price_registration;
  161. /**
  162. * @var float Event organization: booth price
  163. */
  164. public $price_booth;
  165. /**
  166. * @var float Max attendees
  167. */
  168. public $max_attendees;
  169. public $labelStatusShort;
  170. public $labelStatus;
  171. public $statut; // 0=draft, 1=opened, 2=closed
  172. public $opp_status; // opportunity status, into table llx_c_lead_status
  173. public $opp_status_code;
  174. public $fk_opp_status; // opportunity status, into table llx_c_lead_status
  175. public $opp_amount; // opportunity amount
  176. public $opp_percent; // opportunity probability
  177. public $opp_weighted_amount; // opportunity weighted amount
  178. public $email_msgid;
  179. public $oldcopy;
  180. public $weekWorkLoad; // Used to store workload details of a projet
  181. public $weekWorkLoadPerTask; // Used to store workload details of tasks of a projet
  182. /**
  183. * @var array Used to store workload details of a projet
  184. */
  185. public $monthWorkLoad;
  186. /**
  187. * @var array Used to store workload details of tasks of a projet
  188. */
  189. public $monthWorkLoadPerTask;
  190. /**
  191. * @var int Creation date
  192. * @deprecated
  193. * @see $date_c
  194. */
  195. public $datec;
  196. /**
  197. * @var int Creation date
  198. */
  199. public $date_c;
  200. /**
  201. * @var int Modification date
  202. * @deprecated
  203. * @see $date_m
  204. */
  205. public $datem;
  206. /**
  207. * @var int Modification date
  208. */
  209. public $date_m;
  210. /**
  211. * @var string Ip address
  212. */
  213. public $ip;
  214. /**
  215. * @var Task[]
  216. */
  217. public $lines;
  218. /**
  219. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  220. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  221. * 'label' the translation key.
  222. * 'enabled' is a condition when the field must be managed.
  223. * 'position' is the sort order of field.
  224. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  225. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  226. * 'noteditable' says if field is not editable (1 or 0)
  227. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  228. * 'index' if we want an index in database.
  229. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  230. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  231. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  232. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  233. * 'help' is a string visible as a tooltip on field
  234. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  235. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  236. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  237. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  238. *
  239. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  240. */
  241. // BEGIN MODULEBUILDER PROPERTIES
  242. /**
  243. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  244. */
  245. public $fields = array(
  246. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  247. 'fk_project' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'position'=>12),
  248. 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'showoncombobox'=>1, 'position'=>15, 'searchall'=>1),
  249. 'title' =>array('type'=>'varchar(255)', 'label'=>'ProjectLabel', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>17, 'showoncombobox'=>2, 'searchall'=>1),
  250. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>19),
  251. 'fk_soc' =>array('type'=>'integer', 'label'=>'Thirdparty', 'enabled'=>1, 'visible'=>0, 'position'=>20),
  252. 'dateo' =>array('type'=>'date', 'label'=>'DateStart', 'enabled'=>1, 'visible'=>1, 'position'=>30),
  253. 'datee' =>array('type'=>'date', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>1, 'position'=>35),
  254. 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>55, 'searchall'=>1),
  255. 'public' =>array('type'=>'integer', 'label'=>'Visibility', 'enabled'=>1, 'visible'=>1, 'position'=>65),
  256. 'fk_opp_status' =>array('type'=>'integer', 'label'=>'OpportunityStatusShort', 'enabled'=>'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible'=>1, 'position'=>75),
  257. 'opp_percent' =>array('type'=>'double(5,2)', 'label'=>'OpportunityProbabilityShort', 'enabled'=>'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible'=>1, 'position'=>80),
  258. 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>85, 'searchall'=>1),
  259. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>90, 'searchall'=>1),
  260. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>95),
  261. 'date_close' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>0, 'position'=>105),
  262. 'fk_user_close' =>array('type'=>'integer', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>0, 'position'=>110),
  263. 'opp_amount' =>array('type'=>'double(24,8)', 'label'=>'OpportunityAmountShort', 'enabled'=>1, 'visible'=>'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'position'=>115),
  264. 'budget_amount' =>array('type'=>'double(24,8)', 'label'=>'Budget', 'enabled'=>1, 'visible'=>-1, 'position'=>119),
  265. 'usage_opportunity' =>array('type'=>'integer', 'label'=>'UsageOpportunity', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  266. 'usage_task' =>array('type'=>'integer', 'label'=>'UsageTasks', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  267. 'usage_bill_time' =>array('type'=>'integer', 'label'=>'UsageBillTimeShort', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  268. 'usage_organize_event' =>array('type'=>'integer', 'label'=>'UsageOrganizeEvent', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  269. // Properties for event organization
  270. 'date_start_event' =>array('type'=>'date', 'label'=>'DateStartEvent', 'enabled'=>"isModEnabled('eventorganization')", 'visible'=>1, 'position'=>200),
  271. 'date_end_event' =>array('type'=>'date', 'label'=>'DateEndEvent', 'enabled'=>"isModEnabled('eventorganization')", 'visible'=>1, 'position'=>201),
  272. 'location' =>array('type'=>'text', 'label'=>'Location', 'enabled'=>1, 'visible'=>3, 'position'=>55, 'searchall'=>202),
  273. 'accept_conference_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestConf', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  274. 'accept_booth_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>211),
  275. 'price_registration' =>array('type'=>'double(24,8)', 'label'=>'PriceOfRegistration', 'enabled'=>1, 'visible'=>-1, 'position'=>212),
  276. 'price_booth' =>array('type'=>'double(24,8)', 'label'=>'PriceOfBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  277. 'max_attendees' =>array('type'=>'integer', 'label'=>'MaxNbOfAttendees', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  278. // Generic
  279. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>-2, 'position'=>400),
  280. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>405),
  281. 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>410),
  282. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>0, 'position'=>415),
  283. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>420),
  284. 'email_msgid'=>array('type'=>'varchar(255)', 'label'=>'EmailMsgID', 'enabled'=>1, 'visible'=>-1, 'position'=>450, 'help'=>'EmailMsgIDWhenSourceisEmail', 'csslist'=>'tdoverflowmax125'),
  285. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500),
  286. );
  287. // END MODULEBUILDER PROPERTIES
  288. /**
  289. * Draft status
  290. */
  291. const STATUS_DRAFT = 0;
  292. /**
  293. * Open/Validated status
  294. */
  295. const STATUS_VALIDATED = 1;
  296. /**
  297. * Closed status
  298. */
  299. const STATUS_CLOSED = 2;
  300. /**
  301. * Constructor
  302. *
  303. * @param DoliDB $db Database handler
  304. */
  305. public function __construct($db)
  306. {
  307. global $conf;
  308. $this->db = $db;
  309. $this->labelStatusShort = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
  310. $this->labelStatus = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
  311. global $conf;
  312. if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID')) {
  313. $this->fields['rowid']['visible'] = 0;
  314. }
  315. if (!getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
  316. $this->fields['fk_opp_status']['enabled'] = 0;
  317. $this->fields['opp_percent']['enabled'] = 0;
  318. $this->fields['opp_amount']['enabled'] = 0;
  319. $this->fields['usage_opportunity']['enabled'] = 0;
  320. }
  321. if (getDolGlobalString('PROJECT_HIDE_TASKS')) {
  322. $this->fields['usage_bill_time']['visible'] = 0;
  323. $this->fields['usage_task']['visible'] = 0;
  324. }
  325. if (empty($conf->eventorganization->enabled)) {
  326. $this->fields['usage_organize_event']['visible'] = 0;
  327. $this->fields['accept_conference_suggestions']['enabled'] = 0;
  328. $this->fields['accept_booth_suggestions']['enabled'] = 0;
  329. $this->fields['price_registration']['enabled'] = 0;
  330. $this->fields['price_booth']['enabled'] = 0;
  331. $this->fields['max_attendees']['enabled'] = 0;
  332. }
  333. }
  334. /**
  335. * Create a project into database
  336. *
  337. * @param User $user User making creation
  338. * @param int $notrigger Disable triggers
  339. * @return int Return integer <0 if KO, id of created project if OK
  340. */
  341. public function create($user, $notrigger = 0)
  342. {
  343. global $conf, $langs;
  344. $error = 0;
  345. $ret = 0;
  346. $now = dol_now();
  347. // Clean parameters
  348. $this->note_private = dol_substr($this->note_private, 0, 65535);
  349. $this->note_public = dol_substr($this->note_public, 0, 65535);
  350. // Check parameters
  351. if (!trim($this->ref)) {
  352. $this->error = 'ErrorFieldsRequired';
  353. dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
  354. return -1;
  355. }
  356. if (getDolGlobalString('PROJECT_THIRDPARTY_REQUIRED') && !($this->socid > 0)) {
  357. $this->error = 'ErrorFieldsRequired';
  358. dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR);
  359. return -1;
  360. }
  361. // Create project
  362. $this->db->begin();
  363. $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet (";
  364. $sql .= "ref";
  365. $sql .= ", fk_project";
  366. $sql .= ", title";
  367. $sql .= ", description";
  368. $sql .= ", fk_soc";
  369. $sql .= ", fk_user_creat";
  370. $sql .= ", fk_statut";
  371. $sql .= ", fk_opp_status";
  372. $sql .= ", opp_percent";
  373. $sql .= ", public";
  374. $sql .= ", datec";
  375. $sql .= ", dateo";
  376. $sql .= ", datee";
  377. $sql .= ", opp_amount";
  378. $sql .= ", budget_amount";
  379. $sql .= ", usage_opportunity";
  380. $sql .= ", usage_task";
  381. $sql .= ", usage_bill_time";
  382. $sql .= ", usage_organize_event";
  383. $sql .= ", accept_conference_suggestions";
  384. $sql .= ", accept_booth_suggestions";
  385. $sql .= ", price_registration";
  386. $sql .= ", price_booth";
  387. $sql .= ", max_attendees";
  388. $sql .= ", date_start_event";
  389. $sql .= ", date_end_event";
  390. $sql .= ", location";
  391. $sql .= ", email_msgid";
  392. $sql .= ", note_private";
  393. $sql .= ", note_public";
  394. $sql .= ", entity";
  395. $sql .= ", ip";
  396. $sql .= ") VALUES (";
  397. $sql .= "'".$this->db->escape($this->ref)."'";
  398. $sql .= ", ".($this->fk_project ? ((int) $this->fk_project) : "null");
  399. $sql .= ", '".$this->db->escape($this->title)."'";
  400. $sql .= ", '".$this->db->escape($this->description)."'";
  401. $sql .= ", ".($this->socid > 0 ? $this->socid : "null");
  402. $sql .= ", ".((int) $user->id);
  403. $sql .= ", ".(is_numeric($this->statut) ? ((int) $this->statut) : '0');
  404. $sql .= ", ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? ((int) $this->opp_status) : 'NULL');
  405. $sql .= ", ".(is_numeric($this->opp_percent) ? ((int) $this->opp_percent) : 'NULL');
  406. $sql .= ", ".($this->public ? 1 : 0);
  407. $sql .= ", '".$this->db->idate($now)."'";
  408. $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
  409. $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
  410. $sql .= ", ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : 'null');
  411. $sql .= ", ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : 'null');
  412. $sql .= ", ".($this->usage_opportunity ? 1 : 0);
  413. $sql .= ", ".($this->usage_task ? 1 : 0);
  414. $sql .= ", ".($this->usage_bill_time ? 1 : 0);
  415. $sql .= ", ".($this->usage_organize_event ? 1 : 0);
  416. $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
  417. $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
  418. $sql .= ", ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : 'null');
  419. $sql .= ", ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : 'null');
  420. $sql .= ", ".(strcmp($this->max_attendees, '') ? ((int) $this->max_attendees) : 'null');
  421. $sql .= ", ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
  422. $sql .= ", ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
  423. $sql .= ", ".($this->location ? "'".$this->db->escape($this->location)."'" : 'null');
  424. $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
  425. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
  426. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
  427. $sql .= ", ".((int) $conf->entity);
  428. $sql .= ", ".(!isset($this->ip) ? 'NULL' : "'".$this->db->escape($this->ip)."'");
  429. $sql .= ")";
  430. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  431. $resql = $this->db->query($sql);
  432. if ($resql) {
  433. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet");
  434. $ret = $this->id;
  435. if (!$notrigger) {
  436. // Call trigger
  437. $result = $this->call_trigger('PROJECT_CREATE', $user);
  438. if ($result < 0) {
  439. $error++;
  440. }
  441. // End call triggers
  442. }
  443. } else {
  444. $this->error = $this->db->lasterror();
  445. $error++;
  446. }
  447. // Update extrafield
  448. if (!$error) {
  449. $result = $this->insertExtraFields();
  450. if ($result < 0) {
  451. $error++;
  452. }
  453. }
  454. if (!$error && (getDolGlobalString('MAIN_DISABLEDRAFTSTATUS') || getDolGlobalString('MAIN_DISABLEDRAFTSTATUS_PROJECT'))) {
  455. $res = $this->setValid($user);
  456. if ($res < 0) {
  457. $error++;
  458. }
  459. }
  460. if (!$error) {
  461. $this->db->commit();
  462. return $ret;
  463. } else {
  464. $this->db->rollback();
  465. return -1;
  466. }
  467. }
  468. /**
  469. * Update a project
  470. *
  471. * @param User $user User object of making update
  472. * @param int $notrigger 1=Disable all triggers
  473. * @return int Return integer <=0 if KO, >0 if OK
  474. */
  475. public function update($user, $notrigger = 0)
  476. {
  477. global $langs, $conf;
  478. $error = 0;
  479. // Clean parameters
  480. $this->title = trim($this->title);
  481. $this->description = trim($this->description);
  482. if ($this->opp_amount < 0) {
  483. $this->opp_amount = '';
  484. }
  485. if ($this->opp_percent < 0) {
  486. $this->opp_percent = '';
  487. }
  488. if ($this->date_end && $this->date_end < $this->date_start) {
  489. $this->error = $langs->trans("ErrorDateEndLowerThanDateStart");
  490. $this->errors[] = $this->error;
  491. $this->db->rollback();
  492. dol_syslog(get_class($this)."::update error -3 ".$this->error, LOG_ERR);
  493. return -3;
  494. }
  495. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  496. if (dol_strlen(trim($this->ref)) > 0) {
  497. $this->db->begin();
  498. $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET";
  499. $sql .= " ref='".$this->db->escape($this->ref)."'";
  500. $sql .= ", fk_project=".($this->fk_project ? ((int) $this->fk_project) : "null");
  501. $sql .= ", title = '".$this->db->escape($this->title)."'";
  502. $sql .= ", description = '".$this->db->escape($this->description)."'";
  503. $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : "null");
  504. $sql .= ", fk_statut = ".((int) $this->statut);
  505. $sql .= ", fk_opp_status = ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? $this->opp_status : 'null');
  506. $sql .= ", opp_percent = ".((is_numeric($this->opp_percent) && $this->opp_percent != '') ? $this->opp_percent : 'null');
  507. $sql .= ", public = ".($this->public ? 1 : 0);
  508. $sql .= ", datec = ".($this->date_c != '' ? "'".$this->db->idate($this->date_c)."'" : 'null');
  509. $sql .= ", dateo = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
  510. $sql .= ", datee = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
  511. $sql .= ", date_close = ".($this->date_close != '' ? "'".$this->db->idate($this->date_close)."'" : 'null');
  512. $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
  513. $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
  514. $sql .= ", fk_user_close = ".($this->fk_user_close > 0 ? $this->fk_user_close : "null");
  515. $sql .= ", opp_amount = ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null");
  516. $sql .= ", budget_amount = ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null");
  517. $sql .= ", fk_user_modif = ".$user->id;
  518. $sql .= ", usage_opportunity = ".($this->usage_opportunity ? 1 : 0);
  519. $sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
  520. $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
  521. $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
  522. $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
  523. $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
  524. $sql .= ", price_registration = ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
  525. $sql .= ", price_booth = ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : "null");
  526. $sql .= ", max_attendees = ".(strcmp($this->max_attendees, '') ? price2num($this->max_attendees) : "null");
  527. $sql .= ", date_start_event = ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
  528. $sql .= ", date_end_event = ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
  529. $sql .= ", location = '".$this->db->escape($this->location)."'";
  530. $sql .= ", entity = ".((int) $this->entity);
  531. $sql .= " WHERE rowid = ".((int) $this->id);
  532. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  533. $resql = $this->db->query($sql);
  534. if ($resql) {
  535. // Update extrafield
  536. if (!$error) {
  537. $result = $this->insertExtraFields();
  538. if ($result < 0) {
  539. $error++;
  540. }
  541. }
  542. if (!$error && !$notrigger) {
  543. // Call trigger
  544. $result = $this->call_trigger('PROJECT_MODIFY', $user);
  545. if ($result < 0) {
  546. $error++;
  547. }
  548. // End call triggers
  549. }
  550. if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
  551. // We remove directory
  552. if ($conf->project->dir_output) {
  553. $olddir = $conf->project->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
  554. $newdir = $conf->project->dir_output."/".dol_sanitizeFileName($this->ref);
  555. if (file_exists($olddir)) {
  556. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  557. $res = @rename($olddir, $newdir);
  558. if (!$res) {
  559. $langs->load("errors");
  560. $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
  561. $error++;
  562. }
  563. }
  564. }
  565. }
  566. if (!$error) {
  567. $this->db->commit();
  568. $result = 1;
  569. } else {
  570. $this->db->rollback();
  571. $result = -1;
  572. }
  573. } else {
  574. $this->error = $this->db->lasterror();
  575. $this->errors[] = $this->error;
  576. $this->db->rollback();
  577. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  578. $result = -4;
  579. } else {
  580. $result = -2;
  581. }
  582. dol_syslog(get_class($this)."::update error ".$result." ".$this->error, LOG_ERR);
  583. }
  584. } else {
  585. dol_syslog(get_class($this)."::update ref null");
  586. $result = -1;
  587. }
  588. return $result;
  589. }
  590. /**
  591. * Get object from database
  592. *
  593. * @param int $id Id of object to load
  594. * @param string $ref Ref of project
  595. * @param string $ref_ext Ref ext of project
  596. * @param string $email_msgid Email msgid
  597. * @return int >0 if OK, 0 if not found, <0 if KO
  598. */
  599. public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
  600. {
  601. if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
  602. dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
  603. return -1;
  604. }
  605. $sql = "SELECT rowid, entity, fk_project, ref, title, description, public, datec, opp_amount, budget_amount,";
  606. $sql .= " tms, dateo as date_start, datee as date_end, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,";
  607. $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
  608. $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth, max_attendees, date_start_event, date_end_event, location, extraparams";
  609. $sql .= " FROM ".MAIN_DB_PREFIX."projet";
  610. if (!empty($id)) {
  611. $sql .= " WHERE rowid = ".((int) $id);
  612. } else {
  613. $sql .= " WHERE entity IN (".getEntity('project').")";
  614. if (!empty($ref)) {
  615. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  616. } elseif (!empty($ref_ext)) {
  617. $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
  618. } else {
  619. $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
  620. }
  621. }
  622. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  623. $resql = $this->db->query($sql);
  624. if ($resql) {
  625. $num_rows = $this->db->num_rows($resql);
  626. if ($num_rows) {
  627. $obj = $this->db->fetch_object($resql);
  628. $this->id = $obj->rowid;
  629. $this->entity = $obj->entity;
  630. $this->ref = $obj->ref;
  631. $this->fk_project = $obj->fk_project;
  632. $this->title = $obj->title;
  633. $this->description = $obj->description;
  634. $this->date_c = $this->db->jdate($obj->datec);
  635. $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
  636. $this->date_m = $this->db->jdate($obj->tms);
  637. $this->datem = $this->db->jdate($obj->tms); // TODO deprecated
  638. $this->date_start = $this->db->jdate($obj->date_start);
  639. $this->date_end = $this->db->jdate($obj->date_end);
  640. $this->date_close = $this->db->jdate($obj->date_close);
  641. $this->note_private = $obj->note_private;
  642. $this->note_public = $obj->note_public;
  643. $this->socid = $obj->fk_soc;
  644. $this->user_author_id = $obj->fk_user_creat;
  645. $this->user_modification_id = $obj->fk_user_modif;
  646. $this->user_closing_id = $obj->fk_user_close;
  647. $this->public = $obj->public;
  648. $this->statut = $obj->status; // deprecated
  649. $this->status = $obj->status;
  650. $this->opp_status = $obj->fk_opp_status;
  651. $this->opp_amount = $obj->opp_amount;
  652. $this->opp_percent = $obj->opp_percent;
  653. $this->budget_amount = $obj->budget_amount;
  654. $this->model_pdf = $obj->model_pdf;
  655. $this->usage_opportunity = (int) $obj->usage_opportunity;
  656. $this->usage_task = (int) $obj->usage_task;
  657. $this->usage_bill_time = (int) $obj->usage_bill_time;
  658. $this->usage_organize_event = (int) $obj->usage_organize_event;
  659. $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
  660. $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
  661. $this->price_registration = $obj->price_registration;
  662. $this->price_booth = $obj->price_booth;
  663. $this->max_attendees = $obj->max_attendees;
  664. $this->date_start_event = $this->db->jdate($obj->date_start_event);
  665. $this->date_end_event = $this->db->jdate($obj->date_end_event);
  666. $this->location = $obj->location;
  667. $this->email_msgid = $obj->email_msgid;
  668. $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
  669. $this->db->free($resql);
  670. // Retrieve all extrafield
  671. // fetch optionals attributes and labels
  672. $this->fetch_optionals();
  673. return 1;
  674. }
  675. $this->db->free($resql);
  676. return 0;
  677. } else {
  678. $this->error = $this->db->lasterror();
  679. $this->errors[] = $this->db->lasterror();
  680. return -1;
  681. }
  682. }
  683. /**
  684. * Fetch object and substitute key
  685. *
  686. * @param int $id Project id
  687. * @param string $key Key to substitute
  688. * @param bool $fetched [=false] Not already fetched
  689. * @return string Substitute key
  690. */
  691. public function fetchAndSetSubstitution($id, $key, $fetched = false)
  692. {
  693. $substitution = '';
  694. if ($fetched === false) {
  695. $res = $this->fetch($id);
  696. if ($res > 0) {
  697. $fetched = true;
  698. }
  699. }
  700. if ($fetched === true) {
  701. if ($key == '__PROJECT_ID__') {
  702. $substitution = ($this->id > 0 ? $this->id : '');
  703. } elseif ($key == '__PROJECT_REF__') {
  704. $substitution = $this->ref;
  705. } elseif ($key == '__PROJECT_NAME__') {
  706. $substitution = $this->title;
  707. }
  708. }
  709. return $substitution;
  710. }
  711. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  712. /**
  713. * Return list of elements for type, linked to a project
  714. *
  715. * @param string $type 'propal','order','invoice','order_supplier','invoice_supplier',...
  716. * @param string $tablename name of table associated of the type
  717. * @param string $datefieldname name of date field for filter
  718. * @param int $date_start Start date
  719. * @param int $date_end End date
  720. * @param string $projectkey Equivalent key to fk_projet for actual type
  721. * @return mixed Array list of object ids linked to project, < 0 or string if error
  722. */
  723. public function get_element_list($type, $tablename, $datefieldname = '', $date_start = '', $date_end = '', $projectkey = 'fk_projet')
  724. {
  725. // phpcs:enable
  726. global $hookmanager;
  727. $elements = array();
  728. if ($this->id <= 0) {
  729. return $elements;
  730. }
  731. $ids = $this->id;
  732. if ($type == 'agenda') {
  733. $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity('agenda').")";
  734. } elseif ($type == 'expensereport') {
  735. $sql = "SELECT ed.rowid FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet IN (".$this->db->sanitize($ids).")";
  736. } elseif ($type == 'project_task') {
  737. $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$this->db->sanitize($ids).")";
  738. } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
  739. $sql = "SELECT DISTINCT pt.rowid, ptt.fk_user FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."element_time as ptt WHERE pt.rowid = ptt.fk_element AND ptt.elementtype = 'task' AND pt.fk_projet IN (".$this->db->sanitize($ids).")";
  740. } elseif ($type == 'stocktransfer_stocktransfer') {
  741. $sql = "SELECT ms.rowid, ms.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."stocktransfer_stocktransfer as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin IN (".$this->db->sanitize($ids).") AND ms.type_mouvement = 1";
  742. } elseif ($type == 'loan') {
  743. $sql = "SELECT l.rowid, l.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet IN (".$this->db->sanitize($ids).")";
  744. } else {
  745. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity($type).")";
  746. }
  747. if ($date_start > 0 && $type == 'loan') {
  748. $sql .= " AND (dateend > '".$this->db->idate($date_start)."' OR dateend IS NULL)";
  749. } elseif ($date_start > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
  750. if (empty($datefieldname) && !empty($this->table_element_date)) {
  751. $datefieldname = $this->table_element_date;
  752. }
  753. if (empty($datefieldname)) {
  754. return 'Error this object has no date field defined';
  755. }
  756. $sql .= " AND (".$datefieldname." >= '".$this->db->idate($date_start)."' OR ".$datefieldname." IS NULL)";
  757. }
  758. if ($date_end > 0 && $type == 'loan') {
  759. $sql .= " AND (datestart < '".$this->db->idate($date_end)."' OR datestart IS NULL)";
  760. } elseif ($date_end > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
  761. if (empty($datefieldname) && !empty($this->table_element_date)) {
  762. $datefieldname = $this->table_element_date;
  763. }
  764. if (empty($datefieldname)) {
  765. return 'Error this object has no date field defined';
  766. }
  767. $sql .= " AND (".$datefieldname." <= '".$this->db->idate($date_end)."' OR ".$datefieldname." IS NULL)";
  768. }
  769. $parameters = array(
  770. 'sql'=>$sql,
  771. 'type' => $type,
  772. 'tablename' => $tablename,
  773. 'datefieldname' => $datefieldname,
  774. 'dates' => $date_start,
  775. 'datee' => $date_end,
  776. 'fk_projet' => $projectkey,
  777. 'ids' => $ids,
  778. );
  779. $reshook = $hookmanager->executeHooks('getElementList', $parameters);
  780. if ($reshook > 0) {
  781. $sql = $hookmanager->resPrint;
  782. } else {
  783. $sql .= $hookmanager->resPrint;
  784. }
  785. if (!$sql) {
  786. return -1;
  787. }
  788. //print $sql;
  789. dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG);
  790. $result = $this->db->query($sql);
  791. if ($result) {
  792. $nump = $this->db->num_rows($result);
  793. if ($nump) {
  794. $i = 0;
  795. while ($i < $nump) {
  796. $obj = $this->db->fetch_object($result);
  797. $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user);
  798. $i++;
  799. }
  800. $this->db->free($result);
  801. }
  802. /* Return array even if empty*/
  803. return $elements;
  804. } else {
  805. dol_print_error($this->db);
  806. }
  807. }
  808. /**
  809. * Delete a project from database
  810. *
  811. * @param User $user User
  812. * @param int $notrigger Disable triggers
  813. * @return int Return integer <0 if KO, 0 if not possible, >0 if OK
  814. */
  815. public function delete($user, $notrigger = 0)
  816. {
  817. global $langs, $conf;
  818. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  819. $error = 0;
  820. $this->db->begin();
  821. if (!$error) {
  822. // Delete linked contacts
  823. $res = $this->delete_linked_contact();
  824. if ($res < 0) {
  825. $this->error = 'ErrorFailToDeleteLinkedContact';
  826. //$error++;
  827. $this->db->rollback();
  828. return 0;
  829. }
  830. }
  831. // Set fk_projet into elements to null
  832. $listoftables = array(
  833. 'propal'=>'fk_projet', 'commande'=>'fk_projet', 'facture'=>'fk_projet',
  834. 'supplier_proposal'=>'fk_projet', 'commande_fournisseur'=>'fk_projet', 'facture_fourn'=>'fk_projet',
  835. 'expensereport_det'=>'fk_projet', 'contrat'=>'fk_projet',
  836. 'fichinter'=>'fk_projet',
  837. 'don'=>array('field'=>'fk_projet', 'module'=>'don'),
  838. 'actioncomm'=>'fk_project',
  839. 'mrp_mo'=>'fk_project',
  840. 'entrepot'=>'fk_project'
  841. );
  842. foreach ($listoftables as $key => $value) {
  843. if (is_array($value)) {
  844. if (!isModEnabled($value['module'])) {
  845. continue;
  846. }
  847. $fieldname = $value['field'];
  848. } else {
  849. $fieldname = $value;
  850. }
  851. $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$fieldname." = NULL where ".$fieldname." = ".((int) $this->id);
  852. $resql = $this->db->query($sql);
  853. if (!$resql) {
  854. $this->errors[] = $this->db->lasterror();
  855. $error++;
  856. break;
  857. }
  858. }
  859. // Remove linked categories.
  860. if (!$error) {
  861. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_project";
  862. $sql .= " WHERE fk_project = ".((int) $this->id);
  863. $result = $this->db->query($sql);
  864. if (!$result) {
  865. $error++;
  866. $this->errors[] = $this->db->lasterror();
  867. }
  868. }
  869. // Fetch tasks
  870. $this->getLinesArray($user, 0);
  871. // Delete tasks
  872. $ret = $this->deleteTasks($user);
  873. if ($ret < 0) {
  874. $error++;
  875. }
  876. // Delete all child tables
  877. if (!$error) {
  878. $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete
  879. foreach ($elements as $table) {
  880. if (!$error) {
  881. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
  882. $sql .= " WHERE fk_project = ".((int) $this->id);
  883. $result = $this->db->query($sql);
  884. if (!$result) {
  885. $error++;
  886. $this->errors[] = $this->db->lasterror();
  887. }
  888. }
  889. }
  890. }
  891. if (!$error) {
  892. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields";
  893. $sql .= " WHERE fk_object = ".((int) $this->id);
  894. $resql = $this->db->query($sql);
  895. if (!$resql) {
  896. $this->errors[] = $this->db->lasterror();
  897. $error++;
  898. }
  899. }
  900. // Delete project
  901. if (!$error) {
  902. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet";
  903. $sql .= " WHERE rowid=".((int) $this->id);
  904. $resql = $this->db->query($sql);
  905. if (!$resql) {
  906. $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview"));
  907. $error++;
  908. }
  909. }
  910. if (empty($error)) {
  911. // We remove directory
  912. $projectref = dol_sanitizeFileName($this->ref);
  913. if ($conf->project->dir_output) {
  914. $dir = $conf->project->dir_output."/".$projectref;
  915. if (file_exists($dir)) {
  916. $res = @dol_delete_dir_recursive($dir);
  917. if (!$res) {
  918. $this->errors[] = 'ErrorFailToDeleteDir';
  919. $error++;
  920. }
  921. }
  922. }
  923. if (!$notrigger) {
  924. // Call trigger
  925. $result = $this->call_trigger('PROJECT_DELETE', $user);
  926. if ($result < 0) {
  927. $error++;
  928. }
  929. // End call triggers
  930. }
  931. }
  932. if (empty($error)) {
  933. $this->db->commit();
  934. return 1;
  935. } else {
  936. foreach ($this->errors as $errmsg) {
  937. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  938. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  939. }
  940. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  941. $this->db->rollback();
  942. return -1;
  943. }
  944. }
  945. /**
  946. * Return the count of a type of linked elements of this project
  947. *
  948. * @param string $type The type of the linked elements (e.g. 'propal', 'order', 'invoice', 'order_supplier', 'invoice_supplier')
  949. * @param string $tablename The name of table associated of the type
  950. * @param string $projectkey (optional) Equivalent key to fk_projet for actual type
  951. * @return integer The count of the linked elements (the count is zero on request error too)
  952. */
  953. public function getElementCount($type, $tablename, $projectkey = 'fk_projet')
  954. {
  955. if ($this->id <= 0) {
  956. return 0;
  957. }
  958. if ($type == 'agenda') {
  959. $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".((int) $this->id)." AND entity IN (".getEntity('agenda').")";
  960. } elseif ($type == 'expensereport') {
  961. $sql = "SELECT COUNT(ed.rowid) as nb FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet = ".((int) $this->id);
  962. } elseif ($type == 'project_task') {
  963. $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".((int) $this->id);
  964. } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
  965. $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."element_time as ptt WHERE pt.rowid = ptt.fk_element AND ptt.elementtype = 'task' AND pt.fk_projet = ".((int) $this->id);
  966. } elseif ($type == 'stock_mouvement') {
  967. $sql = "SELECT COUNT(ms.rowid) as nb FROM ".MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin = ".((int) $this->id)." AND ms.type_mouvement = 1";
  968. } elseif ($type == 'loan') {
  969. $sql = "SELECT COUNT(l.rowid) as nb FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet = ".((int) $this->id);
  970. } else {
  971. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".((int) $this->id)." AND entity IN (".getEntity($type).")";
  972. }
  973. $result = $this->db->query($sql);
  974. if (!$result) {
  975. return 0;
  976. }
  977. $obj = $this->db->fetch_object($result);
  978. $this->db->free($result);
  979. return $obj->nb;
  980. }
  981. /**
  982. * Delete tasks with no children first, then task with children recursively
  983. *
  984. * @param User $user User
  985. * @return int Return integer <0 if KO, 1 if OK
  986. */
  987. public function deleteTasks($user)
  988. {
  989. $countTasks = count($this->lines);
  990. $deleted = false;
  991. if ($countTasks) {
  992. foreach ($this->lines as $task) {
  993. if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them)
  994. $deleted = true;
  995. $ret = $task->delete($user);
  996. if ($ret <= 0) {
  997. $this->errors[] = $this->db->lasterror();
  998. return -1;
  999. }
  1000. }
  1001. }
  1002. }
  1003. $this->getLinesArray($user);
  1004. if ($deleted && count($this->lines) < $countTasks) {
  1005. if (count($this->lines)) {
  1006. $this->deleteTasks($this->lines);
  1007. }
  1008. }
  1009. return 1;
  1010. }
  1011. /**
  1012. * Validate a project
  1013. *
  1014. * @param User $user User that validate
  1015. * @param int $notrigger 1=Disable triggers
  1016. * @return int Return integer <0 if KO, 0=Nothing done, >0 if KO
  1017. */
  1018. public function setValid($user, $notrigger = 0)
  1019. {
  1020. global $langs, $conf;
  1021. $error = 0;
  1022. // Protection
  1023. if ($this->status == self::STATUS_VALIDATED) {
  1024. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  1025. return 0;
  1026. }
  1027. // Check parameters
  1028. if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) {
  1029. $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
  1030. return -1;
  1031. }
  1032. $this->db->begin();
  1033. $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
  1034. $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
  1035. $sql .= " WHERE rowid = ".((int) $this->id);
  1036. //$sql .= " AND entity = ".((int) $conf->entity); // Disabled, when we use the ID for the where, we must not add any other search condition
  1037. dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
  1038. $resql = $this->db->query($sql);
  1039. if ($resql) {
  1040. // Call trigger
  1041. if (empty($notrigger)) {
  1042. $result = $this->call_trigger('PROJECT_VALIDATE', $user);
  1043. if ($result < 0) {
  1044. $error++;
  1045. }
  1046. // End call triggers
  1047. }
  1048. if (!$error) {
  1049. $this->statut = 1;
  1050. $this->db->commit();
  1051. return 1;
  1052. } else {
  1053. $this->db->rollback();
  1054. $this->error = join(',', $this->errors);
  1055. dol_syslog(get_class($this)."::setValid ".$this->error, LOG_ERR);
  1056. return -1;
  1057. }
  1058. } else {
  1059. $this->db->rollback();
  1060. $this->error = $this->db->lasterror();
  1061. return -1;
  1062. }
  1063. }
  1064. /**
  1065. * Close a project
  1066. *
  1067. * @param User $user User that close project
  1068. * @return int Return integer <0 if KO, 0 if already closed, >0 if OK
  1069. */
  1070. public function setClose($user)
  1071. {
  1072. global $langs, $conf;
  1073. $now = dol_now();
  1074. $error = 0;
  1075. if ($this->statut != self::STATUS_CLOSED) {
  1076. $this->db->begin();
  1077. $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
  1078. $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", fk_user_close = ".((int) $user->id).", date_close = '".$this->db->idate($now)."'";
  1079. $sql .= " WHERE rowid = ".((int) $this->id);
  1080. $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
  1081. if (getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
  1082. // TODO What to do if fk_opp_status is not code 'WON' or 'LOST'
  1083. }
  1084. dol_syslog(get_class($this)."::setClose", LOG_DEBUG);
  1085. $resql = $this->db->query($sql);
  1086. if ($resql) {
  1087. // Call trigger
  1088. $result = $this->call_trigger('PROJECT_CLOSE', $user);
  1089. if ($result < 0) {
  1090. $error++;
  1091. }
  1092. // End call triggers
  1093. if (!$error) {
  1094. $this->statut = 2;
  1095. $this->db->commit();
  1096. return 1;
  1097. } else {
  1098. $this->db->rollback();
  1099. $this->error = join(',', $this->errors);
  1100. dol_syslog(get_class($this)."::setClose ".$this->error, LOG_ERR);
  1101. return -1;
  1102. }
  1103. } else {
  1104. $this->db->rollback();
  1105. $this->error = $this->db->lasterror();
  1106. return -1;
  1107. }
  1108. }
  1109. return 0;
  1110. }
  1111. /**
  1112. * Return status label of object
  1113. *
  1114. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1115. * @return string Label
  1116. */
  1117. public function getLibStatut($mode = 0)
  1118. {
  1119. return $this->LibStatut(isset($this->statut) ? $this->statut : $this->status, $mode);
  1120. }
  1121. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1122. /**
  1123. * Renvoi status label for a status
  1124. *
  1125. * @param int $status id status
  1126. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1127. * @return string Label
  1128. */
  1129. public function LibStatut($status, $mode = 0)
  1130. {
  1131. // phpcs:enable
  1132. global $langs;
  1133. if (is_null($status)) {
  1134. return '';
  1135. }
  1136. $statustrans = array(
  1137. 0 => 'status0',
  1138. 1 => 'status4',
  1139. 2 => 'status6',
  1140. );
  1141. $statusClass = 'status0';
  1142. if (!empty($statustrans[$status])) {
  1143. $statusClass = $statustrans[$status];
  1144. }
  1145. return dolGetStatus($langs->transnoentitiesnoconv($this->labelStatus[$status]), $langs->transnoentitiesnoconv($this->labelStatusShort[$status]), '', $statusClass, $mode);
  1146. }
  1147. /**
  1148. * getTooltipContentArray
  1149. *
  1150. * @param array $params ex option, infologin
  1151. * @since v18
  1152. * @return array
  1153. */
  1154. public function getTooltipContentArray($params)
  1155. {
  1156. global $conf, $langs;
  1157. $langs->load('projects');
  1158. $option = $params['option'] ?? '';
  1159. $moreinpopup = $params['morinpopup'] ?? '';
  1160. $datas = [];
  1161. if ($option != 'nolink') {
  1162. $datas['picto'] = img_picto('', $this->picto, 'class="pictofixedwidth"').' <u class="paddingrightonly">'.$langs->trans("Project").'</u>';
  1163. }
  1164. if (isset($this->status)) {
  1165. $datas['picto'] .= ' '.$this->getLibStatut(5);
  1166. }
  1167. $datas['ref'] = (isset($datas['picto']) ? '<br>' : '').'<b>'.$langs->trans('Ref').': </b>'.$this->ref; // The space must be after the : to not being explode when showing the title in img_picto
  1168. $datas['label'] = '<br><b>'.$langs->trans('Label').': </b>'.$this->title; // The space must be after the : to not being explode when showing the title in img_picto
  1169. if (isset($this->public)) {
  1170. $datas['visibility'] = '<br><b>'.$langs->trans("Visibility").":</b> ";
  1171. $datas['visibility'] .= ($this->public ? img_picto($langs->trans('SharedProject'), 'world', 'class="pictofixedwidth"').$langs->trans("SharedProject") : img_picto($langs->trans('PrivateProject'), 'private', 'class="pictofixedwidth"').$langs->trans("PrivateProject"));
  1172. }
  1173. if (!empty($this->thirdparty_name)) {
  1174. $datas['thirdparty'] = '<br><b>'.$langs->trans('ThirdParty').': </b>'.$this->thirdparty_name; // The space must be after the : to not being explode when showing the title in img_picto
  1175. }
  1176. if (!empty($this->date_start)) {
  1177. $datas['datestart'] = '<br><b>'.$langs->trans('DateStart').': </b>'.dol_print_date($this->date_start, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
  1178. }
  1179. if (!empty($this->date_end)) {
  1180. $datas['dateend'] = '<br><b>'.$langs->trans('DateEnd').': </b>'.dol_print_date($this->date_end, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
  1181. }
  1182. if ($moreinpopup) {
  1183. $datas['moreinpopup'] = '<br>'.$moreinpopup;
  1184. }
  1185. return $datas;
  1186. }
  1187. /**
  1188. * Return clickable name (with picto eventually)
  1189. *
  1190. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1191. * @param string $option Variant where the link point to ('', 'nolink')
  1192. * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string
  1193. * @param string $moreinpopup Text to add into popup
  1194. * @param string $sep Separator between ref and label if option addlabel is set
  1195. * @param int $notooltip 1=Disable tooltip
  1196. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1197. * @param string $morecss More css on a link
  1198. * @param string $save_pageforbacktolist Back to this page 'context:url'
  1199. * @return string String with URL
  1200. */
  1201. public function getNomUrl($withpicto = 0, $option = '', $addlabel = 0, $moreinpopup = '', $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1, $morecss = '', $save_pageforbacktolist = '')
  1202. {
  1203. global $conf, $langs, $user, $hookmanager;
  1204. if (!empty($conf->dol_no_mouse_hover)) {
  1205. $notooltip = 1; // Force disable tooltips
  1206. }
  1207. $result = '';
  1208. if (getDolGlobalString('PROJECT_OPEN_ALWAYS_ON_TAB')) {
  1209. $option = $conf->global->PROJECT_OPEN_ALWAYS_ON_TAB;
  1210. }
  1211. $params = [
  1212. 'id' => $this->id,
  1213. 'objecttype' => $this->element,
  1214. 'moreinpopup' => $moreinpopup,
  1215. 'option' => $option,
  1216. ];
  1217. $classfortooltip = 'classfortooltip';
  1218. $dataparams = '';
  1219. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1220. $classfortooltip = 'classforajaxtooltip';
  1221. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1222. $label = '';
  1223. } else {
  1224. $label = implode($this->getTooltipContentArray($params));
  1225. }
  1226. $url = '';
  1227. if ($option != 'nolink') {
  1228. if (preg_match('/\.php$/', $option)) {
  1229. $url = dol_buildpath($option, 1).'?id='.$this->id;
  1230. } elseif ($option == 'task') {
  1231. $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id;
  1232. } elseif ($option == 'preview') {
  1233. $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id;
  1234. } elseif ($option == 'eventorganization') {
  1235. $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id;
  1236. } else {
  1237. $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id;
  1238. }
  1239. // Add param to save lastsearch_values or not
  1240. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1241. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1242. $add_save_lastsearch_values = 1;
  1243. }
  1244. if ($add_save_lastsearch_values) {
  1245. $url .= '&save_lastsearch_values=1';
  1246. }
  1247. $add_save_backpagefor = ($save_pageforbacktolist ? 1 : 0);
  1248. if ($add_save_backpagefor) {
  1249. $url .= "&save_pageforbacktolist=".urlencode($save_pageforbacktolist);
  1250. }
  1251. }
  1252. $linkclose = '';
  1253. if (empty($notooltip) && $user->hasRight('projet', 'lire')) {
  1254. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  1255. $label = $langs->trans("ShowProject");
  1256. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1257. }
  1258. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1259. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  1260. } else {
  1261. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1262. }
  1263. $picto = 'projectpub';
  1264. if (!$this->public) {
  1265. $picto = 'project';
  1266. }
  1267. $linkstart = '<a href="'.$url.'"';
  1268. $linkstart .= $linkclose.'>';
  1269. $linkend = '</a>';
  1270. $result .= $linkstart;
  1271. if ($withpicto) {
  1272. $result .= img_object(($notooltip ? '' : $label), $picto, 'class="pictofixedwidth em088"', 0, 0, $notooltip ? 0 : 1);
  1273. }
  1274. if ($withpicto != 2) {
  1275. $result .= $this->ref;
  1276. }
  1277. $result .= $linkend;
  1278. if ($withpicto != 2) {
  1279. $result .= (($addlabel && $this->title) ? '<span class="opacitymedium">'.$sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)).'</span>' : '');
  1280. }
  1281. global $action;
  1282. $hookmanager->initHooks(array('projectdao'));
  1283. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1284. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1285. if ($reshook > 0) {
  1286. $result = $hookmanager->resPrint;
  1287. } else {
  1288. $result .= $hookmanager->resPrint;
  1289. }
  1290. return $result;
  1291. }
  1292. /**
  1293. * Initialise an instance with random values.
  1294. * Used to build previews or test instances.
  1295. * id must be 0 if object instance is a specimen.
  1296. *
  1297. * @return void
  1298. */
  1299. public function initAsSpecimen()
  1300. {
  1301. global $user, $langs, $conf;
  1302. $now = dol_now();
  1303. // Initialise parameters
  1304. $this->id = 0;
  1305. $this->ref = 'SPECIMEN';
  1306. $this->entity = $conf->entity;
  1307. $this->specimen = 1;
  1308. $this->socid = 1;
  1309. $this->date_c = $now;
  1310. $this->date_m = $now;
  1311. $this->date_start = $now;
  1312. $this->date_end = $now + (3600 * 24 * 365);
  1313. $this->note_public = 'SPECIMEN';
  1314. $this->fk_element = 20000;
  1315. $this->opp_amount = 20000;
  1316. $this->budget_amount = 10000;
  1317. $this->usage_opportunity = 1;
  1318. $this->usage_task = 1;
  1319. $this->usage_bill_time = 1;
  1320. $this->usage_organize_event = 1;
  1321. /*
  1322. $nbp = mt_rand(1, 9);
  1323. $xnbp = 0;
  1324. while ($xnbp < $nbp)
  1325. {
  1326. $line = new Task($this->db);
  1327. $line->fk_project = 0;
  1328. $line->label = $langs->trans("Label") . " " . $xnbp;
  1329. $line->description = $langs->trans("Description") . " " . $xnbp;
  1330. $this->lines[]=$line;
  1331. $xnbp++;
  1332. }
  1333. */
  1334. }
  1335. /**
  1336. * Check if user has permission on current project
  1337. *
  1338. * @param User $user Object user to evaluate
  1339. * @param string $mode Type of permission we want to know: 'read', 'write'
  1340. * @return int >0 if user has permission, <0 if user has no permission
  1341. */
  1342. public function restrictedProjectArea(User $user, $mode = 'read')
  1343. {
  1344. // To verify role of users
  1345. $userAccess = 0;
  1346. if (($mode == 'read' && $user->hasRight('projet', 'all', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'all', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'all', 'supprimer'))) {
  1347. $userAccess = 1;
  1348. } elseif ($this->public && (($mode == 'read' && $user->hasRight('projet', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'supprimer')))) {
  1349. $userAccess = 1;
  1350. } else { // No access due to permission to read all projects, so we check if we are a contact of project
  1351. foreach (array('internal', 'external') as $source) {
  1352. $userRole = $this->liste_contact(4, $source);
  1353. $num = count($userRole);
  1354. $nblinks = 0;
  1355. while ($nblinks < $num) {
  1356. if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
  1357. if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
  1358. $userAccess++;
  1359. }
  1360. if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
  1361. $userAccess++;
  1362. }
  1363. if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
  1364. $userAccess++;
  1365. }
  1366. }
  1367. if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
  1368. if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
  1369. $userAccess++;
  1370. }
  1371. if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
  1372. $userAccess++;
  1373. }
  1374. if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
  1375. $userAccess++;
  1376. }
  1377. }
  1378. $nblinks++;
  1379. }
  1380. }
  1381. //if (empty($nblinks)) // If nobody has permission, we grant creator
  1382. //{
  1383. // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
  1384. // {
  1385. // $userAccess = 1;
  1386. // }
  1387. //}
  1388. }
  1389. return ($userAccess ? $userAccess : -1);
  1390. }
  1391. /**
  1392. * Return array of projects a user has permission on, is affected to, or all projects
  1393. *
  1394. * @param User $user User object
  1395. * @param int $mode 0=All project I have permission on (assigned to me or public), 1=Projects assigned to me only, 2=Will return list of all projects with no test on contacts
  1396. * @param int $list 0=Return array, 1=Return string list
  1397. * @param int $socid 0=No filter on third party, id of third party
  1398. * @param string $filter additionnal filter on project (statut, ref, ...)
  1399. * @return array|string Array of projects id, or string with projects id separated with "," if list is 1
  1400. */
  1401. public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
  1402. {
  1403. $projects = array();
  1404. $temp = array();
  1405. $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
  1406. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1407. if ($mode == 0) {
  1408. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
  1409. } elseif ($mode == 1) {
  1410. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
  1411. } elseif ($mode == 2) {
  1412. // No filter. Use this if user has permission to see all project
  1413. }
  1414. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  1415. // Internal users must see project he is contact to even if project linked to a third party he can't see.
  1416. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1417. if ($socid > 0) {
  1418. $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1419. }
  1420. // Get id of types of contacts for projects (This list never contains a lot of elements)
  1421. $listofprojectcontacttype = array();
  1422. $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
  1423. $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
  1424. $sql2 .= " AND ctc.source = 'internal'";
  1425. $resql = $this->db->query($sql2);
  1426. if ($resql) {
  1427. while ($obj = $this->db->fetch_object($resql)) {
  1428. $listofprojectcontacttype[$obj->rowid] = $obj->code;
  1429. }
  1430. } else {
  1431. dol_print_error($this->db);
  1432. }
  1433. if (count($listofprojectcontacttype) == 0) {
  1434. $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
  1435. }
  1436. if ($mode == 0) {
  1437. $sql .= " AND ( p.public = 1";
  1438. $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
  1439. $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
  1440. $sql .= " )";
  1441. } elseif ($mode == 1) {
  1442. $sql .= " AND ec.element_id = p.rowid";
  1443. $sql .= " AND (";
  1444. $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
  1445. $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
  1446. $sql .= " )";
  1447. } elseif ($mode == 2) {
  1448. // No filter. Use this if user has permission to see all project
  1449. }
  1450. $sql .= $filter;
  1451. //print $sql;
  1452. $resql = $this->db->query($sql);
  1453. if ($resql) {
  1454. $num = $this->db->num_rows($resql);
  1455. $i = 0;
  1456. while ($i < $num) {
  1457. $row = $this->db->fetch_row($resql);
  1458. $projects[$row[0]] = $row[1];
  1459. $temp[] = $row[0];
  1460. $i++;
  1461. }
  1462. $this->db->free($resql);
  1463. if ($list) {
  1464. if (empty($temp)) {
  1465. return '0';
  1466. }
  1467. $result = implode(',', $temp);
  1468. return $result;
  1469. }
  1470. } else {
  1471. dol_print_error($this->db);
  1472. }
  1473. return $projects;
  1474. }
  1475. /**
  1476. * Load an object from its id and create a new one in database
  1477. *
  1478. * @param User $user User making the clone
  1479. * @param int $fromid Id of object to clone
  1480. * @param bool $clone_contact Clone contact of project
  1481. * @param bool $clone_task Clone task of project
  1482. * @param bool $clone_project_file Clone file of project
  1483. * @param bool $clone_task_file Clone file of task (if task are copied)
  1484. * @param bool $clone_note Clone note of project
  1485. * @param bool $move_date Move task date on clone
  1486. * @param integer $notrigger No trigger flag
  1487. * @param int $newthirdpartyid New thirdparty id
  1488. * @return int New id of clone
  1489. */
  1490. public function createFromClone(User $user, $fromid, $clone_contact = false, $clone_task = true, $clone_project_file = false, $clone_task_file = false, $clone_note = true, $move_date = true, $notrigger = 0, $newthirdpartyid = 0)
  1491. {
  1492. global $langs, $conf;
  1493. $error = 0;
  1494. dol_syslog("createFromClone clone_contact=".$clone_contact." clone_task=".$clone_task." clone_project_file=".$clone_project_file." clone_note=".$clone_note." move_date=".$move_date, LOG_DEBUG);
  1495. $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
  1496. $clone_project = new Project($this->db);
  1497. $clone_project->context['createfromclone'] = 'createfromclone';
  1498. $this->db->begin();
  1499. // Load source object
  1500. $clone_project->fetch($fromid);
  1501. $clone_project->fetch_optionals();
  1502. if ($newthirdpartyid > 0) {
  1503. $clone_project->socid = $newthirdpartyid;
  1504. }
  1505. $clone_project->fetch_thirdparty();
  1506. $orign_dt_start = $clone_project->date_start;
  1507. $orign_project_ref = $clone_project->ref;
  1508. $clone_project->id = 0;
  1509. if ($move_date) {
  1510. $clone_project->date_start = $now;
  1511. if (!(empty($clone_project->date_end))) {
  1512. $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start);
  1513. }
  1514. }
  1515. $clone_project->date_c = $now;
  1516. if (!$clone_note) {
  1517. $clone_project->note_private = '';
  1518. $clone_project->note_public = '';
  1519. }
  1520. //Generate next ref
  1521. $defaultref = '';
  1522. $obj = !getDolGlobalString('PROJECT_ADDON') ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
  1523. // Search template files
  1524. $file = '';
  1525. $classname = '';
  1526. $filefound = 0;
  1527. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1528. foreach ($dirmodels as $reldir) {
  1529. $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
  1530. if (file_exists($file)) {
  1531. $filefound = 1;
  1532. dol_include_once($reldir."core/modules/project/".$obj.'.php');
  1533. $modProject = new $obj();
  1534. $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
  1535. break;
  1536. }
  1537. }
  1538. if (is_numeric($defaultref) && $defaultref <= 0) {
  1539. $defaultref = '';
  1540. }
  1541. $clone_project->ref = $defaultref;
  1542. $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
  1543. // Create clone
  1544. $result = $clone_project->create($user, $notrigger);
  1545. // Other options
  1546. if ($result < 0) {
  1547. $this->error .= $clone_project->error;
  1548. $error++;
  1549. }
  1550. if (!$error) {
  1551. //Get the new project id
  1552. $clone_project_id = $clone_project->id;
  1553. //Note Update
  1554. if (!$clone_note) {
  1555. $clone_project->note_private = '';
  1556. $clone_project->note_public = '';
  1557. } else {
  1558. $this->db->begin();
  1559. $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
  1560. if ($res < 0) {
  1561. $this->error .= $clone_project->error;
  1562. $error++;
  1563. $this->db->rollback();
  1564. } else {
  1565. $this->db->commit();
  1566. }
  1567. $this->db->begin();
  1568. $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
  1569. if ($res < 0) {
  1570. $this->error .= $clone_project->error;
  1571. $error++;
  1572. $this->db->rollback();
  1573. } else {
  1574. $this->db->commit();
  1575. }
  1576. }
  1577. //Duplicate contact
  1578. if ($clone_contact) {
  1579. $origin_project = new Project($this->db);
  1580. $origin_project->fetch($fromid);
  1581. foreach (array('internal', 'external') as $source) {
  1582. $tab = $origin_project->liste_contact(-1, $source);
  1583. if (is_array($tab) && count($tab)>0) {
  1584. foreach ($tab as $contacttoadd) {
  1585. $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
  1586. if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1587. $langs->load("errors");
  1588. $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
  1589. $error++;
  1590. } else {
  1591. if ($clone_project->error != '') {
  1592. $this->error .= $clone_project->error;
  1593. $error++;
  1594. }
  1595. }
  1596. }
  1597. } elseif ($tab < 0) {
  1598. $this->error .= $origin_project->error;
  1599. $error++;
  1600. }
  1601. }
  1602. }
  1603. //Duplicate file
  1604. if ($clone_project_file) {
  1605. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1606. $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
  1607. $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
  1608. if (dol_mkdir($clone_project_dir) >= 0) {
  1609. $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
  1610. foreach ($filearray as $key => $file) {
  1611. $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1);
  1612. if (is_numeric($rescopy) && $rescopy < 0) {
  1613. $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
  1614. $error++;
  1615. }
  1616. }
  1617. } else {
  1618. $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
  1619. $error++;
  1620. }
  1621. }
  1622. //Duplicate task
  1623. if ($clone_task) {
  1624. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  1625. $taskstatic = new Task($this->db);
  1626. // Security check
  1627. $socid = 0;
  1628. if ($user->socid > 0) {
  1629. $socid = $user->socid;
  1630. }
  1631. $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0);
  1632. $tab_conv_child_parent = array();
  1633. // Loop on each task, to clone it
  1634. foreach ($tasksarray as $tasktoclone) {
  1635. $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_task_parent, $move_date, true, false, $clone_task_file, true, false);
  1636. if ($result_clone <= 0) {
  1637. $this->error .= $taskstatic->error;
  1638. $error++;
  1639. } else {
  1640. $new_task_id = $result_clone;
  1641. $taskstatic->fetch($tasktoclone->id);
  1642. //manage new parent clone task id
  1643. // if the current task has child we store the original task id and the equivalent clone task id
  1644. if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
  1645. $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
  1646. }
  1647. }
  1648. }
  1649. //Parse all clone node to be sure to update new parent
  1650. $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0);
  1651. foreach ($tasksarray as $task_cloned) {
  1652. $taskstatic->fetch($task_cloned->id);
  1653. if ($taskstatic->fk_task_parent != 0) {
  1654. $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
  1655. }
  1656. $res = $taskstatic->update($user, $notrigger);
  1657. if ($result_clone <= 0) {
  1658. $this->error .= $taskstatic->error;
  1659. $error++;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. unset($clone_project->context['createfromclone']);
  1665. if (!$error) {
  1666. $this->db->commit();
  1667. return $clone_project_id;
  1668. } else {
  1669. $this->db->rollback();
  1670. dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
  1671. return -1;
  1672. }
  1673. }
  1674. /**
  1675. * Shift project task date from current date to delta
  1676. *
  1677. * @param integer $old_project_dt_start Old project start date
  1678. * @return int 1 if OK or < 0 if KO
  1679. */
  1680. public function shiftTaskDate($old_project_dt_start)
  1681. {
  1682. global $user, $langs, $conf;
  1683. $error = 0;
  1684. $result = 0;
  1685. $taskstatic = new Task($this->db);
  1686. // Security check
  1687. $socid = 0;
  1688. if ($user->socid > 0) {
  1689. $socid = $user->socid;
  1690. }
  1691. $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0);
  1692. foreach ($tasksarray as $tasktoshiftdate) {
  1693. $to_update = false;
  1694. // Fetch only if update of date will be made
  1695. if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
  1696. //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
  1697. $to_update = true;
  1698. $task = new Task($this->db);
  1699. $result = $task->fetch($tasktoshiftdate->id);
  1700. if (!$result) {
  1701. $error++;
  1702. $this->error .= $task->error;
  1703. }
  1704. }
  1705. //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
  1706. //Calcultate new task start date with difference between old proj start date and origin task start date
  1707. if (!empty($tasktoshiftdate->date_start)) {
  1708. $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
  1709. }
  1710. //Calcultate new task end date with difference between origin proj end date and origin task end date
  1711. if (!empty($tasktoshiftdate->date_end)) {
  1712. $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
  1713. }
  1714. if ($to_update) {
  1715. $result = $task->update($user);
  1716. if (!$result) {
  1717. $error++;
  1718. $this->error .= $task->error;
  1719. }
  1720. }
  1721. }
  1722. if ($error != 0) {
  1723. return -1;
  1724. }
  1725. return $result;
  1726. }
  1727. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1728. /**
  1729. * Associate element to a project
  1730. *
  1731. * @param string $tableName Table of the element to update
  1732. * @param int $elementSelectId Key-rowid of the line of the element to update
  1733. * @return int 1 if OK or < 0 if KO
  1734. */
  1735. public function update_element($tableName, $elementSelectId)
  1736. {
  1737. // phpcs:enable
  1738. $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
  1739. if ($tableName == "actioncomm") {
  1740. $sql .= " SET fk_project=".$this->id;
  1741. $sql .= " WHERE id=".((int) $elementSelectId);
  1742. } elseif (in_array($tableName, ["entrepot","mrp_mo","stocktransfer_stocktransfer"])) {
  1743. $sql .= " SET fk_project=".$this->id;
  1744. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1745. } else {
  1746. $sql .= " SET fk_projet=".$this->id;
  1747. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1748. }
  1749. dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
  1750. $resql = $this->db->query($sql);
  1751. if (!$resql) {
  1752. $this->error = $this->db->lasterror();
  1753. return -1;
  1754. } else {
  1755. return 1;
  1756. }
  1757. }
  1758. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1759. /**
  1760. * Associate element to a project
  1761. *
  1762. * @param string $tableName Table of the element to update
  1763. * @param int $elementSelectId Key-rowid of the line of the element to update
  1764. * @param string $projectfield The column name that stores the link with the project
  1765. *
  1766. * @return int 1 if OK or < 0 if KO
  1767. */
  1768. public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
  1769. {
  1770. // phpcs:enable
  1771. $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
  1772. if ($tableName == "actioncomm") {
  1773. $sql .= " SET fk_project=NULL";
  1774. $sql .= " WHERE id=".((int) $elementSelectId);
  1775. } else {
  1776. $sql .= " SET ".$projectfield."=NULL";
  1777. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1778. }
  1779. dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
  1780. $resql = $this->db->query($sql);
  1781. if (!$resql) {
  1782. $this->error = $this->db->lasterror();
  1783. return -1;
  1784. } else {
  1785. return 1;
  1786. }
  1787. }
  1788. /**
  1789. * Create an intervention document on disk using template defined into PROJECT_ADDON_PDF
  1790. *
  1791. * @param string $modele Force template to use ('' by default)
  1792. * @param Translate $outputlangs Objet lang to use for translation
  1793. * @param int $hidedetails Hide details of lines
  1794. * @param int $hidedesc Hide description
  1795. * @param int $hideref Hide ref
  1796. * @return int 0 if KO, 1 if OK
  1797. */
  1798. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1799. {
  1800. global $conf, $langs;
  1801. $langs->load("projects");
  1802. if (!dol_strlen($modele)) {
  1803. $modele = 'baleine';
  1804. if ($this->model_pdf) {
  1805. $modele = $this->model_pdf;
  1806. } elseif (getDolGlobalString('PROJECT_ADDON_PDF')) {
  1807. $modele = $conf->global->PROJECT_ADDON_PDF;
  1808. }
  1809. }
  1810. $modelpath = "core/modules/project/doc/";
  1811. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1812. }
  1813. /**
  1814. * Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of project.
  1815. * Note: array weekWorkLoad and weekWorkLoadPerTask are reset and filled at each call.
  1816. *
  1817. * @param int $datestart First day of week (use dol_get_first_day to find this date)
  1818. * @param int $taskid Filter on a task id
  1819. * @param int $userid Time spent by a particular user
  1820. * @return int Return integer <0 if OK, >0 if KO
  1821. */
  1822. public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
  1823. {
  1824. $error = 0;
  1825. $this->weekWorkLoad = array();
  1826. $this->weekWorkLoadPerTask = array();
  1827. if (empty($datestart)) {
  1828. dol_print_error('', 'Error datestart parameter is empty');
  1829. }
  1830. $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
  1831. $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
  1832. $sql .= " WHERE ptt.fk_element = pt.rowid";
  1833. $sql .= " AND ptt.elementtype = 'task'";
  1834. $sql .= " AND pt.fk_projet = ".((int) $this->id);
  1835. $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
  1836. $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
  1837. if ($taskid) {
  1838. $sql .= " AND ptt.fk_element=".((int) $taskid);
  1839. }
  1840. if (is_numeric($userid)) {
  1841. $sql .= " AND ptt.fk_user=".((int) $userid);
  1842. }
  1843. //print $sql;
  1844. $resql = $this->db->query($sql);
  1845. if ($resql) {
  1846. $daylareadyfound = array();
  1847. $num = $this->db->num_rows($resql);
  1848. $i = 0;
  1849. // Loop on each record found, so each couple (project id, task id)
  1850. while ($i < $num) {
  1851. $obj = $this->db->fetch_object($resql);
  1852. $day = $this->db->jdate($obj->element_date); // task_date is date without hours
  1853. if (empty($daylareadyfound[$day])) {
  1854. $this->weekWorkLoad[$day] = $obj->element_duration;
  1855. $this->weekWorkLoadPerTask[$day][$obj->fk_element] = $obj->element_duration;
  1856. } else {
  1857. $this->weekWorkLoad[$day] += $obj->element_duration;
  1858. $this->weekWorkLoadPerTask[$day][$obj->fk_element] += $obj->element_duration;
  1859. }
  1860. $daylareadyfound[$day] = 1;
  1861. $i++;
  1862. }
  1863. $this->db->free($resql);
  1864. return 1;
  1865. } else {
  1866. $this->error = "Error ".$this->db->lasterror();
  1867. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  1868. return -1;
  1869. }
  1870. }
  1871. /**
  1872. * Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of project.
  1873. * Note: array weekWorkLoad and weekWorkLoadPerTask are reset and filled at each call.
  1874. *
  1875. * @param int $datestart First day of week (use dol_get_first_day to find this date)
  1876. * @param int $taskid Filter on a task id
  1877. * @param int $userid Time spent by a particular user
  1878. * @return int Return integer <0 if OK, >0 if KO
  1879. */
  1880. public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
  1881. {
  1882. $error = 0;
  1883. $this->monthWorkLoad = array();
  1884. $this->monthWorkLoadPerTask = array();
  1885. if (empty($datestart)) {
  1886. dol_print_error('', 'Error datestart parameter is empty');
  1887. }
  1888. $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
  1889. $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
  1890. $sql .= " WHERE ptt.fk_element = pt.rowid";
  1891. $sql .= " AND ptt.elementtype = 'task'";
  1892. $sql .= " AND pt.fk_projet = ".((int) $this->id);
  1893. $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
  1894. $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
  1895. if ($taskid) {
  1896. $sql .= " AND ptt.fk_element=".((int) $taskid);
  1897. }
  1898. if (is_numeric($userid)) {
  1899. $sql .= " AND ptt.fk_user=".((int) $userid);
  1900. }
  1901. //print $sql;
  1902. $resql = $this->db->query($sql);
  1903. if ($resql) {
  1904. $weekalreadyfound = array();
  1905. $num = $this->db->num_rows($resql);
  1906. $i = 0;
  1907. // Loop on each record found, so each couple (project id, task id)
  1908. while ($i < $num) {
  1909. $obj = $this->db->fetch_object($resql);
  1910. if (!empty($obj->element_date)) {
  1911. $date = explode('-', $obj->element_date);
  1912. $week_number = getWeekNumber($date[2], $date[1], $date[0]);
  1913. }
  1914. if (empty($weekalreadyfound[$week_number])) {
  1915. $this->monthWorkLoad[$week_number] = $obj->element_duration;
  1916. $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] = $obj->element_duration;
  1917. } else {
  1918. $this->monthWorkLoad[$week_number] += $obj->element_duration;
  1919. $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] += $obj->element_duration;
  1920. }
  1921. $weekalreadyfound[$week_number] = 1;
  1922. $i++;
  1923. }
  1924. $this->db->free($resql);
  1925. return 1;
  1926. } else {
  1927. $this->error = "Error ".$this->db->lasterror();
  1928. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  1929. return -1;
  1930. }
  1931. }
  1932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1933. /**
  1934. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1935. *
  1936. * @param User $user Objet user
  1937. * @return WorkboardResponse|int Return integer <0 if KO, WorkboardResponse if OK
  1938. */
  1939. public function load_board($user)
  1940. {
  1941. // phpcs:enable
  1942. global $conf, $langs;
  1943. // For external user, no check is done on company because readability is managed by public status of project and assignement.
  1944. //$socid=$user->socid;
  1945. $response = new WorkboardResponse();
  1946. $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
  1947. $response->label = $langs->trans("OpenedProjects");
  1948. $response->labelShort = $langs->trans("Opened");
  1949. $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
  1950. $response->img = img_object('', "projectpub");
  1951. $response->nbtodo = 0;
  1952. $response->nbtodolate = 0;
  1953. $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
  1954. $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
  1955. $sql .= ")";
  1956. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
  1957. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  1958. //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
  1959. $sql .= " WHERE p.fk_statut = 1";
  1960. $sql .= " AND p.entity IN (".getEntity('project').')';
  1961. $projectsListId = null;
  1962. if (!$user->hasRight("projet", "all", "lire")) {
  1963. $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
  1964. $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
  1965. if (empty($projectsListId)) {
  1966. return $response;
  1967. }
  1968. $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  1969. }
  1970. // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
  1971. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1972. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  1973. //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
  1974. //print $sql;
  1975. $resql = $this->db->query($sql);
  1976. if ($resql) {
  1977. $project_static = new Project($this->db);
  1978. // This assignment in condition is not a bug. It allows walking the results.
  1979. while ($obj = $this->db->fetch_object($resql)) {
  1980. $response->nbtodo++;
  1981. $project_static->statut = $obj->status;
  1982. $project_static->opp_status = $obj->fk_opp_status;
  1983. $project_static->date_end = $this->db->jdate($obj->datee);
  1984. if ($project_static->hasDelay()) {
  1985. $response->nbtodolate++;
  1986. }
  1987. }
  1988. return $response;
  1989. }
  1990. $this->error = $this->db->error();
  1991. return -1;
  1992. }
  1993. /**
  1994. * Function used to replace a thirdparty id with another one.
  1995. *
  1996. * @param DoliDB $dbs Database handler
  1997. * @param int $origin_id Old thirdparty id
  1998. * @param int $dest_id New thirdparty id
  1999. * @return bool
  2000. */
  2001. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  2002. {
  2003. $tables = array(
  2004. 'projet'
  2005. );
  2006. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
  2007. }
  2008. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2009. /**
  2010. * Charge indicateurs this->nb pour le tableau de bord
  2011. *
  2012. * @return int Return integer <0 if KO, >0 if OK
  2013. */
  2014. public function load_state_board()
  2015. {
  2016. // phpcs:enable
  2017. global $user;
  2018. $this->nb = array();
  2019. $sql = "SELECT count(p.rowid) as nb";
  2020. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  2021. $sql .= " WHERE";
  2022. $sql .= " p.entity IN (".getEntity('project').")";
  2023. if (!$user->hasRight('projet', 'all', 'lire')) {
  2024. $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
  2025. $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  2026. }
  2027. $resql = $this->db->query($sql);
  2028. if ($resql) {
  2029. while ($obj = $this->db->fetch_object($resql)) {
  2030. $this->nb["projects"] = $obj->nb;
  2031. }
  2032. $this->db->free($resql);
  2033. return 1;
  2034. } else {
  2035. dol_print_error($this->db);
  2036. $this->error = $this->db->error();
  2037. return -1;
  2038. }
  2039. }
  2040. /**
  2041. * Is the project delayed?
  2042. *
  2043. * @return bool
  2044. */
  2045. public function hasDelay()
  2046. {
  2047. global $conf;
  2048. if (!($this->statut == self::STATUS_VALIDATED)) {
  2049. return false;
  2050. }
  2051. if (!$this->date_end) {
  2052. return false;
  2053. }
  2054. $now = dol_now();
  2055. return ($this->date_end) < ($now - $conf->project->warning_delay);
  2056. }
  2057. /**
  2058. * Charge les informations d'ordre info dans l'objet commande
  2059. *
  2060. * @param int $id Id of order
  2061. * @return void
  2062. */
  2063. public function info($id)
  2064. {
  2065. $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
  2066. $sql .= ' date_close as datecloture,';
  2067. $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_user_cloture';
  2068. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
  2069. $sql .= ' WHERE c.rowid = '.((int) $id);
  2070. $result = $this->db->query($sql);
  2071. if ($result) {
  2072. if ($this->db->num_rows($result)) {
  2073. $obj = $this->db->fetch_object($result);
  2074. $this->id = $obj->rowid;
  2075. $this->user_creation_id = $obj->fk_user_author;
  2076. $this->user_closing_id = $obj->fk_user_cloture;
  2077. $this->date_creation = $this->db->jdate($obj->datec);
  2078. $this->date_modification = $this->db->jdate($obj->datem);
  2079. $this->date_cloture = $this->db->jdate($obj->datecloture);
  2080. }
  2081. $this->db->free($result);
  2082. } else {
  2083. dol_print_error($this->db);
  2084. }
  2085. }
  2086. /**
  2087. * Sets object to supplied categories.
  2088. *
  2089. * Deletes object from existing categories not supplied.
  2090. * Adds it to non existing supplied categories.
  2091. * Existing categories are left untouch.
  2092. *
  2093. * @param int[]|int $categories Category or categories IDs
  2094. * @return int Return integer <0 if KO, >0 if OK
  2095. */
  2096. public function setCategories($categories)
  2097. {
  2098. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  2099. return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
  2100. }
  2101. /**
  2102. * Create an array of tasks of current project
  2103. *
  2104. * @param User $user Object user we want project allowed to
  2105. * @param int $loadRoleMode 1= will test Roles on task; 0 used in delete project action
  2106. * @return int >0 if OK, <0 if KO
  2107. */
  2108. public function getLinesArray($user, $loadRoleMode = 1)
  2109. {
  2110. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  2111. $taskstatic = new Task($this->db);
  2112. $this->lines = $taskstatic->getTasksArray(0, $user, $this->id, 0, 0, '', '-1', '', 0, 0, array(), 0, array(), 0, $loadRoleMode);
  2113. return 1;
  2114. }
  2115. /**
  2116. * Function sending an email to the current member with the text supplied in parameter.
  2117. *
  2118. * @param string $text Content of message (not html entities encoded)
  2119. * @param string $subject Subject of message
  2120. * @param array $filename_list Array of attached files
  2121. * @param array $mimetype_list Array of mime types of attached files
  2122. * @param array $mimefilename_list Array of public names of attached files
  2123. * @param string $addr_cc Email cc
  2124. * @param string $addr_bcc Email bcc
  2125. * @param int $deliveryreceipt Ask a delivery receipt
  2126. * @param int $msgishtml 1=String IS already html, 0=String IS NOT html, -1=Unknown need autodetection
  2127. * @param string $errors_to erros to
  2128. * @param string $moreinheader Add more html headers
  2129. * @since V18
  2130. * @return int Return integer <0 if KO, >0 if OK
  2131. */
  2132. public function sendEmail($text, $subject, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = -1, $errors_to = '', $moreinheader = '')
  2133. {
  2134. global $conf, $langs;
  2135. // TODO EMAIL
  2136. return 1;
  2137. }
  2138. /**
  2139. * Return clicable link of object (with eventually picto)
  2140. *
  2141. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  2142. * @param array $arraydata Array of data
  2143. * @return string HTML Code for Kanban thumb.
  2144. */
  2145. public function getKanbanView($option = '', $arraydata = null)
  2146. {
  2147. global $langs;
  2148. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  2149. $return = '<div class="box-flex-item box-flex-grow-zero">';
  2150. $return .= '<div class="info-box info-box-sm">';
  2151. $return .= '<span class="info-box-icon bg-infobox-action">';
  2152. $return .= img_picto('', $this->public ? 'projectpub' : $this->picto);
  2153. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  2154. $return .= '</span>';
  2155. $return .= '<div class="info-box-content">';
  2156. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref);
  2157. if ($this->hasDelay()) {
  2158. $return .= img_warning($langs->trans('Late'));
  2159. }
  2160. $return .= '</span>';
  2161. if ($selected >= 0) {
  2162. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  2163. }
  2164. // Date
  2165. /*
  2166. if (property_exists($this, 'date_start') && $this->date_start) {
  2167. $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_start, 'day').'</>';
  2168. }
  2169. if (property_exists($this, 'date_end') && $this->date_end) {
  2170. if ($this->date_start) {
  2171. $return .= ' - ';
  2172. } else {
  2173. $return .= '<br>';
  2174. }
  2175. $return .= '<span class="info-box-label">'.dol_print_date($this->date_end, 'day').'</span>';
  2176. }*/
  2177. if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
  2178. $return .= '<br><div class="info-box-ref tdoverflowmax150 inline-block valignmiddle">'.$this->thirdparty->getNomUrl(1);
  2179. $return .= '</div><div class="inline-block valignmiddle">';
  2180. $return .= dol_print_phone($this->thirdparty->phone, $this->thirdparty->country_code, 0, $this->thirdparty->id, 'tel', 'hidenum', 'phone');
  2181. $return .='</div>';
  2182. }
  2183. if (!empty($arraydata['assignedusers'])) {
  2184. $return .= '<br>';
  2185. if ($this->public) {
  2186. $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('SharedProject'), 'world', 'class="paddingrightonly valignmiddle"');
  2187. //print $langs->trans('SharedProject');
  2188. } else {
  2189. $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('PrivateProject'), 'private', 'class="paddingrightonly valignmiddle"');
  2190. //print $langs->trans('PrivateProject');
  2191. }
  2192. $return .= ' <span class="small valignmiddle">'.$arraydata['assignedusers'].'</span>';
  2193. }
  2194. /*if (property_exists($this, 'user_author_id')) {
  2195. $return .= '<br><span class="info-box-label opacitymedium">'.$langs->trans("Author").'</span>';
  2196. $return .= '<span> : '.$user->getNomUrl(1).'</span>';
  2197. }*/
  2198. $return .= '<br><div>'; // start div line status
  2199. if ($this->usage_opportunity && $this->opp_status_code) {
  2200. //$return .= '<br><span class="info-bo-label opacitymedium">'.$langs->trans("OpportunityStatusShort").'</span>';
  2201. //$return .= '<div class="small inline-block">'.dol_trunc($langs->trans("OppStatus".$this->opp_status_code), 5).'</div>';
  2202. $return .= '<div class="opacitymedium small marginrightonly inline-block" title="'.dol_escape_htmltag($langs->trans("OppStatus".$this->opp_status_code)).'">'.round($this->opp_percent).'%</div>';
  2203. $return .= ' <div class="amount small marginrightonly inline-block">'.price($this->opp_amount).'</div>';
  2204. }
  2205. if (method_exists($this, 'getLibStatut')) {
  2206. $return .= '<div class="info-box-status small inline-block">'.$this->getLibStatut(3).'</div>';
  2207. }
  2208. $return .= '</div>'; // end div line status
  2209. $return .= '</div>';
  2210. $return .= '</div>';
  2211. $return .= '</div>';
  2212. return $return;
  2213. }
  2214. /**
  2215. * Return array of sub-projects of the current project
  2216. *
  2217. * @return array Children of this project as objects with rowid & title as members
  2218. */
  2219. public function getChildren()
  2220. {
  2221. $children = [];
  2222. $sql = 'SELECT rowid,title';
  2223. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet';
  2224. $sql .= ' WHERE fk_project = '.((int) $this->id);
  2225. $sql .= ' ORDER BY title';
  2226. $result = $this->db->query($sql);
  2227. if ($result) {
  2228. $n = $this->db->num_rows($result);
  2229. while ($n) {
  2230. $children[] = $this->db->fetch_object($result);
  2231. $n--;
  2232. }
  2233. $this->db->free($result);
  2234. } else {
  2235. dol_print_error($this->db);
  2236. }
  2237. return $children;
  2238. }
  2239. }