project.class.php 76 KB

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