project.class.php 87 KB

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