task.class.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  1. <?php
  2. /* Copyright (C) 2008-2014 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2010-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
  5. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  6. * Copyright (C) 2020 Juanjo Menent <jmenent@2byte.es>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/projet/class/task.class.php
  23. * \ingroup project
  24. * \brief This file is a CRUD class file for Task (Create/Read/Update/Delete)
  25. */
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  28. /**
  29. * Class to manage tasks
  30. */
  31. class Task extends CommonObject
  32. {
  33. /**
  34. * @var string ID to identify managed object
  35. */
  36. public $element = 'project_task';
  37. /**
  38. * @var string Name of table without prefix where object is stored
  39. */
  40. public $table_element = 'projet_task';
  41. /**
  42. * @var string Field with ID of parent key if this field has a parent
  43. */
  44. public $fk_element = 'fk_task';
  45. /**
  46. * @var string String with name of icon for myobject.
  47. */
  48. public $picto = 'projecttask';
  49. /**
  50. * @var array List of child tables. To test if we can delete object.
  51. */
  52. protected $childtables = array('projet_task_time');
  53. /**
  54. * @var int ID parent task
  55. */
  56. public $fk_task_parent = 0;
  57. /**
  58. * @var string Label of task
  59. */
  60. public $label;
  61. /**
  62. * @var string description
  63. */
  64. public $description;
  65. public $duration_effective; // total of time spent on this task
  66. public $planned_workload;
  67. public $date_c;
  68. public $date_start;
  69. public $date_end;
  70. public $progress;
  71. /**
  72. * @var int ID
  73. */
  74. public $fk_statut;
  75. public $priority;
  76. /**
  77. * @var int ID
  78. */
  79. public $fk_user_creat;
  80. /**
  81. * @var int ID
  82. */
  83. public $fk_user_valid;
  84. public $rang;
  85. public $timespent_min_date;
  86. public $timespent_max_date;
  87. public $timespent_total_duration;
  88. public $timespent_total_amount;
  89. public $timespent_nblinesnull;
  90. public $timespent_nblines;
  91. // For detail of lines of timespent record, there is the property ->lines in common
  92. // Var used to call method addTimeSpent(). Bad practice.
  93. public $timespent_id;
  94. public $timespent_duration;
  95. public $timespent_old_duration;
  96. public $timespent_date;
  97. public $timespent_datehour; // More accurate start date (same than timespent_date but includes hours, minutes and seconds)
  98. public $timespent_withhour; // 1 = we entered also start hours for timesheet line
  99. public $timespent_fk_user;
  100. public $timespent_note;
  101. public $comments = array();
  102. public $oldcopy;
  103. /**
  104. * Constructor
  105. *
  106. * @param DoliDB $db Database handler
  107. */
  108. public function __construct($db)
  109. {
  110. $this->db = $db;
  111. }
  112. /**
  113. * Create into database
  114. *
  115. * @param User $user User that create
  116. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  117. * @return int <0 if KO, Id of created object if OK
  118. */
  119. public function create($user, $notrigger = 0)
  120. {
  121. global $conf, $langs;
  122. //For the date
  123. $now = dol_now();
  124. $error = 0;
  125. // Clean parameters
  126. $this->label = trim($this->label);
  127. $this->description = trim($this->description);
  128. // Check parameters
  129. // Put here code to add control on parameters values
  130. // Insert request
  131. $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
  132. $sql .= "entity";
  133. $sql .= ", fk_projet";
  134. $sql .= ", ref";
  135. $sql .= ", fk_task_parent";
  136. $sql .= ", label";
  137. $sql .= ", description";
  138. $sql .= ", datec";
  139. $sql .= ", fk_user_creat";
  140. $sql .= ", dateo";
  141. $sql .= ", datee";
  142. $sql .= ", planned_workload";
  143. $sql .= ", progress";
  144. $sql .= ") VALUES (";
  145. $sql .= $conf->entity;
  146. $sql .= ", ".$this->fk_project;
  147. $sql .= ", ".(!empty($this->ref) ? "'".$this->db->escape($this->ref)."'" : 'null');
  148. $sql .= ", ".$this->fk_task_parent;
  149. $sql .= ", '".$this->db->escape($this->label)."'";
  150. $sql .= ", '".$this->db->escape($this->description)."'";
  151. $sql .= ", '".$this->db->idate($now)."'";
  152. $sql .= ", ".$user->id;
  153. $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
  154. $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
  155. $sql .= ", ".(($this->planned_workload != '' && $this->planned_workload >= 0) ? $this->planned_workload : 'null');
  156. $sql .= ", ".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null');
  157. $sql .= ")";
  158. $this->db->begin();
  159. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  160. $resql = $this->db->query($sql);
  161. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  162. if (!$error)
  163. {
  164. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task");
  165. if (!$notrigger)
  166. {
  167. // Call trigger
  168. $result = $this->call_trigger('TASK_CREATE', $user);
  169. if ($result < 0) { $error++; }
  170. // End call triggers
  171. }
  172. }
  173. // Update extrafield
  174. if (!$error)
  175. {
  176. if (!$error)
  177. {
  178. $result = $this->insertExtraFields();
  179. if ($result < 0)
  180. {
  181. $error++;
  182. }
  183. }
  184. }
  185. // Commit or rollback
  186. if ($error)
  187. {
  188. foreach ($this->errors as $errmsg)
  189. {
  190. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  191. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  192. }
  193. $this->db->rollback();
  194. return -1 * $error;
  195. } else {
  196. $this->db->commit();
  197. return $this->id;
  198. }
  199. }
  200. /**
  201. * Load object in memory from database
  202. *
  203. * @param int $id Id object
  204. * @param int $ref ref object
  205. * @param int $loadparentdata Also load parent data
  206. * @return int <0 if KO, 0 if not found, >0 if OK
  207. */
  208. public function fetch($id, $ref = '', $loadparentdata = 0)
  209. {
  210. global $langs, $conf;
  211. $sql = "SELECT";
  212. $sql .= " t.rowid,";
  213. $sql .= " t.ref,";
  214. $sql .= " t.fk_projet as fk_project,";
  215. $sql .= " t.fk_task_parent,";
  216. $sql .= " t.label,";
  217. $sql .= " t.description,";
  218. $sql .= " t.duration_effective,";
  219. $sql .= " t.planned_workload,";
  220. $sql .= " t.datec,";
  221. $sql .= " t.dateo,";
  222. $sql .= " t.datee,";
  223. $sql .= " t.fk_user_creat,";
  224. $sql .= " t.fk_user_valid,";
  225. $sql .= " t.fk_statut,";
  226. $sql .= " t.progress,";
  227. $sql .= " t.priority,";
  228. $sql .= " t.note_private,";
  229. $sql .= " t.note_public,";
  230. $sql .= " t.rang";
  231. if (!empty($loadparentdata))
  232. {
  233. $sql .= ", t2.ref as task_parent_ref";
  234. $sql .= ", t2.rang as task_parent_position";
  235. }
  236. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t";
  237. if (!empty($loadparentdata)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t2 ON t.fk_task_parent = t2.rowid";
  238. $sql .= " WHERE ";
  239. if (!empty($ref)) {
  240. $sql .= "t.ref = '".$this->db->escape($ref)."'";
  241. } else {
  242. $sql .= "t.rowid = ".$id;
  243. }
  244. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  245. $resql = $this->db->query($sql);
  246. if ($resql)
  247. {
  248. $num_rows = $this->db->num_rows($resql);
  249. if ($num_rows)
  250. {
  251. $obj = $this->db->fetch_object($resql);
  252. $this->id = $obj->rowid;
  253. $this->ref = $obj->ref;
  254. $this->fk_project = $obj->fk_project;
  255. $this->fk_task_parent = $obj->fk_task_parent;
  256. $this->label = $obj->label;
  257. $this->description = $obj->description;
  258. $this->duration_effective = $obj->duration_effective;
  259. $this->planned_workload = $obj->planned_workload;
  260. $this->date_c = $this->db->jdate($obj->datec);
  261. $this->date_start = $this->db->jdate($obj->dateo);
  262. $this->date_end = $this->db->jdate($obj->datee);
  263. $this->fk_user_creat = $obj->fk_user_creat;
  264. $this->fk_user_valid = $obj->fk_user_valid;
  265. $this->fk_statut = $obj->fk_statut;
  266. $this->progress = $obj->progress;
  267. $this->priority = $obj->priority;
  268. $this->note_private = $obj->note_private;
  269. $this->note_public = $obj->note_public;
  270. $this->rang = $obj->rang;
  271. if (!empty($loadparentdata))
  272. {
  273. $this->task_parent_ref = $obj->task_parent_ref;
  274. $this->task_parent_position = $obj->task_parent_position;
  275. }
  276. // Retrieve all extrafield
  277. $this->fetch_optionals();
  278. }
  279. $this->db->free($resql);
  280. if ($num_rows)
  281. {
  282. return 1;
  283. } else {
  284. return 0;
  285. }
  286. } else {
  287. $this->error = "Error ".$this->db->lasterror();
  288. return -1;
  289. }
  290. }
  291. /**
  292. * Update database
  293. *
  294. * @param User $user User that modify
  295. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  296. * @return int <=0 if KO, >0 if OK
  297. */
  298. public function update($user = null, $notrigger = 0)
  299. {
  300. global $conf, $langs;
  301. $error = 0;
  302. // Clean parameters
  303. if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project);
  304. if (isset($this->ref)) $this->ref = trim($this->ref);
  305. if (isset($this->fk_task_parent)) $this->fk_task_parent = (int) $this->fk_task_parent;
  306. if (isset($this->label)) $this->label = trim($this->label);
  307. if (isset($this->description)) $this->description = trim($this->description);
  308. if (isset($this->duration_effective)) $this->duration_effective = trim($this->duration_effective);
  309. if (isset($this->planned_workload)) $this->planned_workload = trim($this->planned_workload);
  310. // Check parameters
  311. // Put here code to add control on parameters values
  312. // Update request
  313. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
  314. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
  315. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "'".$this->db->escape($this->id)."'").",";
  316. $sql .= " fk_task_parent=".(isset($this->fk_task_parent) ? $this->fk_task_parent : "null").",";
  317. $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  318. $sql .= " description=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
  319. $sql .= " duration_effective=".(isset($this->duration_effective) ? $this->duration_effective : "null").",";
  320. $sql .= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '') ? $this->planned_workload : "null").",";
  321. $sql .= " dateo=".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null').",";
  322. $sql .= " datee=".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null').",";
  323. $sql .= " progress=".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null').",";
  324. $sql .= " rang=".((!empty($this->rang)) ? $this->rang : "0");
  325. $sql .= " WHERE rowid=".$this->id;
  326. $this->db->begin();
  327. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  328. $resql = $this->db->query($sql);
  329. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  330. // Update extrafield
  331. if (!$error) {
  332. if (!$error)
  333. {
  334. $result = $this->insertExtraFields();
  335. if ($result < 0)
  336. {
  337. $error++;
  338. }
  339. }
  340. }
  341. if (!$error)
  342. {
  343. if (!$notrigger)
  344. {
  345. // Call trigger
  346. $result = $this->call_trigger('TASK_MODIFY', $user);
  347. if ($result < 0) { $error++; }
  348. // End call triggers
  349. }
  350. }
  351. if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref))
  352. {
  353. // We remove directory
  354. if ($conf->projet->dir_output)
  355. {
  356. $project = new Project($this->db);
  357. $project->fetch($this->fk_project);
  358. $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref);
  359. $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref);
  360. if (file_exists($olddir))
  361. {
  362. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  363. $res = dol_move($olddir, $newdir);
  364. if (!$res)
  365. {
  366. $langs->load("errors");
  367. $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
  368. $error++;
  369. }
  370. }
  371. }
  372. }
  373. // Commit or rollback
  374. if ($error)
  375. {
  376. foreach ($this->errors as $errmsg)
  377. {
  378. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  379. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  380. }
  381. $this->db->rollback();
  382. return -1 * $error;
  383. } else {
  384. $this->db->commit();
  385. return 1;
  386. }
  387. }
  388. /**
  389. * Delete task from database
  390. *
  391. * @param User $user User that delete
  392. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  393. * @return int <0 if KO, >0 if OK
  394. */
  395. public function delete($user, $notrigger = 0)
  396. {
  397. global $conf, $langs;
  398. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  399. $error = 0;
  400. $this->db->begin();
  401. if ($this->hasChildren() > 0)
  402. {
  403. dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING);
  404. $this->error = 'ErrorRecordHasSubTasks';
  405. $this->db->rollback();
  406. return 0;
  407. }
  408. $objectisused = $this->isObjectUsed($this->id);
  409. if (!empty($objectisused))
  410. {
  411. dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING);
  412. $this->error = 'ErrorRecordHasChildren';
  413. $this->db->rollback();
  414. return 0;
  415. }
  416. if (!$error)
  417. {
  418. // Delete linked contacts
  419. $res = $this->delete_linked_contact();
  420. if ($res < 0)
  421. {
  422. $this->error = 'ErrorFailToDeleteLinkedContact';
  423. //$error++;
  424. $this->db->rollback();
  425. return 0;
  426. }
  427. }
  428. if (!$error)
  429. {
  430. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
  431. $sql .= " WHERE fk_task=".$this->id;
  432. $resql = $this->db->query($sql);
  433. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  434. }
  435. if (!$error)
  436. {
  437. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields";
  438. $sql .= " WHERE fk_object=".$this->id;
  439. $resql = $this->db->query($sql);
  440. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  441. }
  442. if (!$error)
  443. {
  444. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task";
  445. $sql .= " WHERE rowid=".$this->id;
  446. $resql = $this->db->query($sql);
  447. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  448. }
  449. if (!$error)
  450. {
  451. if (!$notrigger)
  452. {
  453. // Call trigger
  454. $result = $this->call_trigger('TASK_DELETE', $user);
  455. if ($result < 0) { $error++; }
  456. // End call triggers
  457. }
  458. }
  459. // Commit or rollback
  460. if ($error)
  461. {
  462. foreach ($this->errors as $errmsg)
  463. {
  464. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  465. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  466. }
  467. $this->db->rollback();
  468. return -1 * $error;
  469. } else {
  470. //Delete associated link file
  471. if ($conf->projet->dir_output)
  472. {
  473. $projectstatic = new Project($this->db);
  474. $projectstatic->fetch($this->fk_project);
  475. $dir = $conf->projet->dir_output."/".dol_sanitizeFileName($projectstatic->ref).'/'.dol_sanitizeFileName($this->id);
  476. dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG);
  477. if (file_exists($dir))
  478. {
  479. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  480. $res = @dol_delete_dir_recursive($dir);
  481. if (!$res)
  482. {
  483. $this->error = 'ErrorFailToDeleteDir';
  484. $this->db->rollback();
  485. return 0;
  486. }
  487. }
  488. }
  489. $this->db->commit();
  490. return 1;
  491. }
  492. }
  493. /**
  494. * Return nb of children
  495. *
  496. * @return int <0 if KO, 0 if no children, >0 if OK
  497. */
  498. public function hasChildren()
  499. {
  500. $error = 0;
  501. $ret = 0;
  502. $sql = "SELECT COUNT(*) as nb";
  503. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task";
  504. $sql .= " WHERE fk_task_parent=".$this->id;
  505. dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
  506. $resql = $this->db->query($sql);
  507. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } else {
  508. $obj = $this->db->fetch_object($resql);
  509. if ($obj) $ret = $obj->nb;
  510. $this->db->free($resql);
  511. }
  512. if (!$error)
  513. {
  514. return $ret;
  515. } else {
  516. return -1;
  517. }
  518. }
  519. /**
  520. * Return nb of time spent
  521. *
  522. * @return int <0 if KO, 0 if no children, >0 if OK
  523. */
  524. public function hasTimeSpent()
  525. {
  526. $error = 0;
  527. $ret = 0;
  528. $sql = "SELECT COUNT(*) as nb";
  529. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time";
  530. $sql .= " WHERE fk_task=".$this->id;
  531. dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
  532. $resql = $this->db->query($sql);
  533. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } else {
  534. $obj = $this->db->fetch_object($resql);
  535. if ($obj) $ret = $obj->nb;
  536. $this->db->free($resql);
  537. }
  538. if (!$error)
  539. {
  540. return $ret;
  541. } else {
  542. return -1;
  543. }
  544. }
  545. /**
  546. * Return clicable name (with picto eventually)
  547. *
  548. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  549. * @param string $option 'withproject' or ''
  550. * @param string $mode Mode 'task', 'time', 'contact', 'note', document' define page to link to.
  551. * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string
  552. * @param string $sep Separator between ref and label if option addlabel is set
  553. * @param int $notooltip 1=Disable tooltip
  554. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  555. * @return string Chaine avec URL
  556. */
  557. public function getNomUrl($withpicto = 0, $option = '', $mode = 'task', $addlabel = 0, $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1)
  558. {
  559. global $conf, $langs, $user;
  560. if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
  561. $result = '';
  562. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Task").'</u>';
  563. if (!empty($this->ref))
  564. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  565. if (!empty($this->label))
  566. $label .= '<br><b>'.$langs->trans('LabelTask').':</b> '.$this->label;
  567. if ($this->date_start || $this->date_end)
  568. {
  569. $label .= "<br>".get_date_range($this->date_start, $this->date_end, '', $langs, 0);
  570. }
  571. $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option == 'withproject' ? '&withproject=1' : '');
  572. // Add param to save lastsearch_values or not
  573. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  574. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  575. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  576. $linkclose = '';
  577. if (empty($notooltip))
  578. {
  579. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  580. {
  581. $label = $langs->trans("ShowTask");
  582. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  583. }
  584. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  585. $linkclose .= ' class="classfortooltip nowraponall"';
  586. } else {
  587. $linkclose .= ' class="nowraponall"';
  588. }
  589. $linkstart = '<a href="'.$url.'"';
  590. $linkstart .= $linkclose.'>';
  591. $linkend = '</a>';
  592. $picto = 'projecttask';
  593. $result .= $linkstart;
  594. if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  595. if ($withpicto != 2) $result .= $this->ref;
  596. $result .= $linkend;
  597. if ($withpicto != 2) $result .= (($addlabel && $this->label) ? $sep.dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  598. return $result;
  599. }
  600. /**
  601. * Initialise an instance with random values.
  602. * Used to build previews or test instances.
  603. * id must be 0 if object instance is a specimen.
  604. *
  605. * @return void
  606. */
  607. public function initAsSpecimen()
  608. {
  609. $this->id = 0;
  610. $this->fk_project = '';
  611. $this->ref = 'TK01';
  612. $this->fk_task_parent = null;
  613. $this->label = 'Specimen task TK01';
  614. $this->duration_effective = '';
  615. $this->fk_user_creat = null;
  616. $this->progress = '25';
  617. $this->fk_statut = null;
  618. $this->note = 'This is a specimen task not';
  619. }
  620. /**
  621. * Return list of tasks for all projects or for one particular project
  622. * Sort order is on project, then on position of task, and last on start date of first level task
  623. *
  624. * @param User $usert Object user to limit tasks affected to a particular user
  625. * @param User $userp Object user to limit projects of a particular user and public projects
  626. * @param int $projectid Project id
  627. * @param int $socid Third party id
  628. * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists
  629. * @param string $filteronproj Filter on project ref or label
  630. * @param string $filteronprojstatus Filter on project status ('-1'=no filter, '0,1'=Draft+Validated only)
  631. * @param string $morewherefilter Add more filter into where SQL request (must start with ' AND ...')
  632. * @param string $filteronprojuser Filter on user that is a contact of project
  633. * @param string $filterontaskuser Filter on user assigned to task
  634. * @param array $extrafields Show additional column from project or task
  635. * @param int $includebilltime Calculate also the time to bill and billed
  636. * @param array $search_array_options Array of search
  637. * @return array Array of tasks
  638. */
  639. public function getTasksArray($usert = null, $userp = null, $projectid = 0, $socid = 0, $mode = 0, $filteronproj = '', $filteronprojstatus = '-1', $morewherefilter = '', $filteronprojuser = 0, $filterontaskuser = 0, $extrafields = array(), $includebilltime = 0, $search_array_options = array())
  640. {
  641. global $conf, $hookmanager;
  642. $tasks = array();
  643. //print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'<br>';
  644. // List of tasks (does not care about permissions. Filtering will be done later)
  645. $sql = "SELECT ";
  646. if ($filteronprojuser > 0 || $filterontaskuser > 0) $sql .= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task
  647. $sql .= " p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus, p.usage_bill_time,";
  648. $sql .= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
  649. $sql .= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,";
  650. $sql .= " t.description, ";
  651. $sql .= " s.rowid as thirdparty_id, s.nom as thirdparty_name, s.email as thirdparty_email,";
  652. $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount";
  653. if (!empty($extrafields->attributes['projet']['label']))
  654. {
  655. foreach ($extrafields->attributes['projet']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key.' as options_'.$key : '');
  656. }
  657. if (!empty($extrafields->attributes['projet_task']['label']))
  658. {
  659. foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key.' as options_'.$key : '');
  660. }
  661. if ($includebilltime)
  662. {
  663. $sql .= ", SUM(tt.task_duration * ".$this->db->ifsql("invoice_id IS NULL", "1", "0").") as tobill, SUM(tt.task_duration * ".$this->db->ifsql("invoice_id IS NULL", "0", "1").") as billed";
  664. }
  665. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  666. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
  667. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_extrafields as efp ON (p.rowid = efp.fk_object)";
  668. if ($mode == 0)
  669. {
  670. if ($filteronprojuser > 0)
  671. {
  672. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
  673. $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
  674. }
  675. $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
  676. if ($includebilltime)
  677. {
  678. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid";
  679. }
  680. if ($filterontaskuser > 0)
  681. {
  682. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
  683. $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
  684. }
  685. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON (t.rowid = efpt.fk_object)";
  686. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  687. $sql .= " AND t.fk_projet = p.rowid";
  688. } elseif ($mode == 1)
  689. {
  690. if ($filteronprojuser > 0)
  691. {
  692. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
  693. $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
  694. }
  695. if ($filterontaskuser > 0)
  696. {
  697. $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
  698. if ($includebilltime)
  699. {
  700. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid";
  701. }
  702. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
  703. $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
  704. } else {
  705. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
  706. if ($includebilltime)
  707. {
  708. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid";
  709. }
  710. }
  711. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON (t.rowid = efpt.fk_object)";
  712. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  713. } else return 'BadValueForParameterMode';
  714. if ($filteronprojuser > 0)
  715. {
  716. $sql .= " AND p.rowid = ec.element_id";
  717. $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
  718. $sql .= " AND ctc.element = 'project'";
  719. $sql .= " AND ec.fk_socpeople = ".$filteronprojuser;
  720. $sql .= " AND ec.statut = 4";
  721. $sql .= " AND ctc.source = 'internal'";
  722. }
  723. if ($filterontaskuser > 0)
  724. {
  725. $sql .= " AND t.fk_projet = p.rowid";
  726. $sql .= " AND p.rowid = ec2.element_id";
  727. $sql .= " AND ctc2.rowid = ec2.fk_c_type_contact";
  728. $sql .= " AND ctc2.element = 'project_task'";
  729. $sql .= " AND ec2.fk_socpeople = ".$filterontaskuser;
  730. $sql .= " AND ec2.statut = 4";
  731. $sql .= " AND ctc2.source = 'internal'";
  732. }
  733. if ($socid) $sql .= " AND p.fk_soc = ".$socid;
  734. if ($projectid) $sql .= " AND p.rowid in (".$projectid.")";
  735. if ($filteronproj) $sql .= natural_search(array("p.ref", "p.title"), $filteronproj);
  736. if ($filteronprojstatus && $filteronprojstatus != '-1') $sql .= " AND p.fk_statut IN (".$filteronprojstatus.")";
  737. if ($morewherefilter) $sql .= $morewherefilter;
  738. // Add where from extra fields
  739. $extrafieldsobjectkey = 'projet_task';
  740. $extrafieldsobjectprefix = 'efpt.';
  741. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
  742. // Add where from hooks
  743. $parameters = array();
  744. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
  745. $sql .= $hookmanager->resPrint;
  746. if ($includebilltime)
  747. {
  748. $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public, p.fk_statut, p.usage_bill_time,";
  749. $sql .= " t.datec, t.dateo, t.datee, t.tms,";
  750. $sql .= " t.rowid, t.ref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut,";
  751. $sql .= " t.dateo, t.datee, t.planned_workload, t.rang,";
  752. $sql .= " t.description, ";
  753. $sql .= " s.rowid, s.nom, s.email,";
  754. $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount";
  755. if (!empty($extrafields->attributes['projet']['label']))
  756. {
  757. foreach ($extrafields->attributes['projet']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key : '');
  758. }
  759. if (!empty($extrafields->attributes['projet_task']['label']))
  760. {
  761. foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key : '');
  762. }
  763. }
  764. $sql .= " ORDER BY p.ref, t.rang, t.dateo";
  765. //print $sql;exit;
  766. dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG);
  767. $resql = $this->db->query($sql);
  768. if ($resql)
  769. {
  770. $num = $this->db->num_rows($resql);
  771. $i = 0;
  772. // Loop on each record found, so each couple (project id, task id)
  773. while ($i < $num)
  774. {
  775. $error = 0;
  776. $obj = $this->db->fetch_object($resql);
  777. if ((!$obj->public) && (is_object($userp))) // If not public project and we ask a filter on project owned by a user
  778. {
  779. if (!$this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
  780. {
  781. $error++;
  782. }
  783. }
  784. if (is_object($usert)) // If we ask a filter on a user affected to a task
  785. {
  786. if (!$this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
  787. {
  788. $error++;
  789. }
  790. }
  791. if (!$error)
  792. {
  793. $tasks[$i] = new Task($this->db);
  794. $tasks[$i]->id = $obj->taskid;
  795. $tasks[$i]->ref = $obj->taskref;
  796. $tasks[$i]->fk_project = $obj->projectid;
  797. $tasks[$i]->projectref = $obj->ref;
  798. $tasks[$i]->projectlabel = $obj->plabel;
  799. $tasks[$i]->projectstatus = $obj->projectstatus;
  800. $tasks[$i]->fk_opp_status = $obj->fk_opp_status;
  801. $tasks[$i]->opp_amount = $obj->opp_amount;
  802. $tasks[$i]->opp_percent = $obj->opp_percent;
  803. $tasks[$i]->budget_amount = $obj->budget_amount;
  804. $tasks[$i]->usage_bill_time = $obj->usage_bill_time;
  805. $tasks[$i]->label = $obj->label;
  806. $tasks[$i]->description = $obj->description;
  807. $tasks[$i]->fk_parent = $obj->fk_task_parent; // deprecated
  808. $tasks[$i]->fk_task_parent = $obj->fk_task_parent;
  809. $tasks[$i]->duration = $obj->duration_effective;
  810. $tasks[$i]->planned_workload = $obj->planned_workload;
  811. if ($includebilltime) {
  812. $tasks[$i]->tobill = $obj->tobill;
  813. $tasks[$i]->billed = $obj->billed;
  814. }
  815. $tasks[$i]->progress = $obj->progress;
  816. $tasks[$i]->fk_statut = $obj->status;
  817. $tasks[$i]->public = $obj->public;
  818. $tasks[$i]->date_start = $this->db->jdate($obj->date_start);
  819. $tasks[$i]->date_end = $this->db->jdate($obj->date_end);
  820. $tasks[$i]->rang = $obj->rang;
  821. $tasks[$i]->socid = $obj->thirdparty_id; // For backward compatibility
  822. $tasks[$i]->thirdparty_id = $obj->thirdparty_id;
  823. $tasks[$i]->thirdparty_name = $obj->thirdparty_name;
  824. $tasks[$i]->thirdparty_email = $obj->thirdparty_email;
  825. if (!empty($extrafields->attributes['projet']['label']))
  826. {
  827. foreach ($extrafields->attributes['projet']['label'] as $key => $val)
  828. {
  829. if ($extrafields->attributes['projet']['type'][$key] != 'separate')
  830. $tasks[$i]->{'options_'.$key} = $obj->{'options_'.$key};
  831. }
  832. }
  833. if (!empty($extrafields->attributes['projet_task']['label']))
  834. {
  835. foreach ($extrafields->attributes['projet_task']['label'] as $key => $val)
  836. {
  837. if ($extrafields->attributes['projet_task']['type'][$key] != 'separate')
  838. $tasks[$i]->{'options_'.$key} = $obj->{'options_'.$key};
  839. }
  840. }
  841. }
  842. $i++;
  843. }
  844. $this->db->free($resql);
  845. } else {
  846. dol_print_error($this->db);
  847. }
  848. return $tasks;
  849. }
  850. /**
  851. * Return list of roles for a user for each projects or each tasks (or a particular project or a particular task).
  852. *
  853. * @param User $userp Return roles on project for this internal user. If set, usert and taskid must not be defined.
  854. * @param User $usert Return roles on task for this internal user. If set userp must NOT be defined. -1 means no filter.
  855. * @param int $projectid Project id list separated with , to filter on project
  856. * @param int $taskid Task id to filter on a task
  857. * @param integer $filteronprojstatus Filter on project status if userp is set. Not used if userp not defined.
  858. * @return array Array (projectid => 'list of roles for project' or taskid => 'list of roles for task')
  859. */
  860. public function getUserRolesForProjectsOrTasks($userp, $usert, $projectid = '', $taskid = 0, $filteronprojstatus = -1)
  861. {
  862. $arrayroles = array();
  863. dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid);
  864. // We want role of user for a projet or role of user for a task. Both are not possible.
  865. if (empty($userp) && empty($usert))
  866. {
  867. $this->error = "CallWithWrongParameters";
  868. return -1;
  869. }
  870. if (!empty($userp) && !empty($usert))
  871. {
  872. $this->error = "CallWithWrongParameters";
  873. return -1;
  874. }
  875. /* Liste des taches et role sur les projets ou taches */
  876. $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source";
  877. if ($userp) $sql .= " FROM ".MAIN_DB_PREFIX."projet as pt";
  878. if ($usert && $filteronprojstatus > -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
  879. if ($usert && $filteronprojstatus <= -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
  880. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
  881. $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
  882. $sql .= " WHERE pt.rowid = ec.element_id";
  883. if ($userp && $filteronprojstatus > -1) $sql .= " AND pt.fk_statut = ".$filteronprojstatus;
  884. if ($usert && $filteronprojstatus > -1) $sql .= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
  885. if ($userp) $sql .= " AND ctc.element = 'project'";
  886. if ($usert) $sql .= " AND ctc.element = 'project_task'";
  887. $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
  888. if ($userp) $sql .= " AND ec.fk_socpeople = ".$userp->id;
  889. if ($usert) $sql .= " AND ec.fk_socpeople = ".$usert->id;
  890. $sql .= " AND ec.statut = 4";
  891. $sql .= " AND ctc.source = 'internal'";
  892. if ($projectid)
  893. {
  894. if ($userp) $sql .= " AND pt.rowid in (".$projectid.")";
  895. if ($usert) $sql .= " AND pt.fk_projet in (".$projectid.")";
  896. }
  897. if ($taskid)
  898. {
  899. if ($userp) $sql .= " ERROR SHOULD NOT HAPPENS";
  900. if ($usert) $sql .= " AND pt.rowid = ".$taskid;
  901. }
  902. //print $sql;
  903. dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG);
  904. $resql = $this->db->query($sql);
  905. if ($resql)
  906. {
  907. $num = $this->db->num_rows($resql);
  908. $i = 0;
  909. while ($i < $num)
  910. {
  911. $obj = $this->db->fetch_object($resql);
  912. if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code;
  913. else $arrayroles[$obj->pid] .= ','.$obj->code;
  914. $i++;
  915. }
  916. $this->db->free($resql);
  917. } else {
  918. dol_print_error($this->db);
  919. }
  920. return $arrayroles;
  921. }
  922. /**
  923. * Return list of id of contacts of task
  924. *
  925. * @param string $source Source
  926. * @return array Array of id of contacts
  927. */
  928. public function getListContactId($source = 'internal')
  929. {
  930. $contactAlreadySelected = array();
  931. $tab = $this->liste_contact(-1, $source);
  932. //var_dump($tab);
  933. $num = count($tab);
  934. $i = 0;
  935. while ($i < $num)
  936. {
  937. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  938. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  939. $i++;
  940. }
  941. return $contactAlreadySelected;
  942. }
  943. /**
  944. * Add time spent
  945. *
  946. * @param User $user User object
  947. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  948. * @return int <=0 if KO, >0 if OK
  949. */
  950. public function addTimeSpent($user, $notrigger = 0)
  951. {
  952. global $conf, $langs;
  953. dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
  954. $ret = 0;
  955. // Check parameters
  956. if (!is_object($user))
  957. {
  958. dol_print_error('', "Method addTimeSpent was called with wrong parameter user");
  959. return -1;
  960. }
  961. // Clean parameters
  962. if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
  963. if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
  964. $this->db->begin();
  965. $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time (";
  966. $sql .= "fk_task";
  967. $sql .= ", task_date";
  968. $sql .= ", task_datehour";
  969. $sql .= ", task_date_withhour";
  970. $sql .= ", task_duration";
  971. $sql .= ", fk_user";
  972. $sql .= ", note";
  973. $sql .= ") VALUES (";
  974. $sql .= $this->id;
  975. $sql .= ", '".$this->db->idate($this->timespent_date)."'";
  976. $sql .= ", '".$this->db->idate($this->timespent_datehour)."'";
  977. $sql .= ", ".(empty($this->timespent_withhour) ? 0 : 1);
  978. $sql .= ", ".$this->timespent_duration;
  979. $sql .= ", ".$this->timespent_fk_user;
  980. $sql .= ", ".(isset($this->timespent_note) ? "'".$this->db->escape($this->timespent_note)."'" : "null");
  981. $sql .= ")";
  982. $resql = $this->db->query($sql);
  983. if ($resql)
  984. {
  985. $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time");
  986. $ret = $tasktime_id;
  987. $this->timespent_id = $ret;
  988. if (!$notrigger)
  989. {
  990. // Call trigger
  991. $result = $this->call_trigger('TASK_TIMESPENT_CREATE', $user);
  992. if ($result < 0) { $ret = -1; }
  993. // End call triggers
  994. }
  995. } else {
  996. $this->error = $this->db->lasterror();
  997. $ret = -1;
  998. }
  999. if ($ret > 0)
  1000. {
  1001. // Recalculate amount of time spent for task and update denormalized field
  1002. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
  1003. $sql .= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
  1004. if (isset($this->progress)) $sql .= ", progress = ".$this->progress; // Do not overwrite value if not provided
  1005. $sql .= " WHERE rowid = ".$this->id;
  1006. dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
  1007. if (!$this->db->query($sql))
  1008. {
  1009. $this->error = $this->db->lasterror();
  1010. $ret = -2;
  1011. }
  1012. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time";
  1013. $sql .= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")"; // set average hour rate of user
  1014. $sql .= " WHERE rowid = ".$tasktime_id;
  1015. dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
  1016. if (!$this->db->query($sql))
  1017. {
  1018. $this->error = $this->db->lasterror();
  1019. $ret = -2;
  1020. }
  1021. }
  1022. if ($ret > 0)
  1023. {
  1024. $this->db->commit();
  1025. } else {
  1026. $this->db->rollback();
  1027. }
  1028. return $ret;
  1029. }
  1030. /**
  1031. * Calculate total of time spent for task
  1032. *
  1033. * @param User|int $userobj Filter on user. null or 0=No filter
  1034. * @param string $morewherefilter Add more filter into where SQL request (must start with ' AND ...')
  1035. * @return array Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull')
  1036. */
  1037. public function getSummaryOfTimeSpent($userobj = null, $morewherefilter = '')
  1038. {
  1039. global $langs;
  1040. if (is_object($userobj)) $userid = $userobj->id;
  1041. else $userid = $userobj; // old method
  1042. $id = $this->id;
  1043. if (empty($id) && empty($userid))
  1044. {
  1045. dol_syslog("getSummaryOfTimeSpent called on a not loaded task without user param defined", LOG_ERR);
  1046. return -1;
  1047. }
  1048. $result = array();
  1049. $sql = "SELECT";
  1050. $sql .= " MIN(t.task_datehour) as min_date,";
  1051. $sql .= " MAX(t.task_datehour) as max_date,";
  1052. $sql .= " SUM(t.task_duration) as total_duration,";
  1053. $sql .= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,";
  1054. $sql .= " COUNT(t.rowid) as nblines,";
  1055. $sql .= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
  1056. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
  1057. $sql .= " WHERE 1 = 1";
  1058. if ($morewherefilter) $sql .= $morewherefilter;
  1059. if ($id > 0) $sql .= " AND t.fk_task = ".$id;
  1060. if ($userid > 0) $sql .= " AND t.fk_user = ".$userid;
  1061. dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
  1062. $resql = $this->db->query($sql);
  1063. if ($resql)
  1064. {
  1065. $obj = $this->db->fetch_object($resql);
  1066. $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead
  1067. $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead
  1068. $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead
  1069. $this->timespent_min_date = $this->db->jdate($obj->min_date);
  1070. $this->timespent_max_date = $this->db->jdate($obj->max_date);
  1071. $this->timespent_total_duration = $obj->total_duration;
  1072. $this->timespent_total_amount = $obj->total_amount;
  1073. $this->timespent_nblinesnull = ($obj->nblinesnull ? $obj->nblinesnull : 0);
  1074. $this->timespent_nblines = ($obj->nblines ? $obj->nblines : 0);
  1075. $this->db->free($resql);
  1076. } else {
  1077. dol_print_error($this->db);
  1078. }
  1079. return $result;
  1080. }
  1081. /**
  1082. * Calculate quantity and value of time consumed using the thm (hourly amount value of work for user entering time)
  1083. *
  1084. * @param User $fuser Filter on a dedicated user
  1085. * @param string $dates Start date (ex 00:00:00)
  1086. * @param string $datee End date (ex 23:59:59)
  1087. * @return array Array of info for task array('amount','nbseconds','nblinesnull')
  1088. */
  1089. public function getSumOfAmount($fuser = '', $dates = '', $datee = '')
  1090. {
  1091. global $langs;
  1092. if (empty($id)) $id = $this->id;
  1093. $result = array();
  1094. $sql = "SELECT";
  1095. $sql .= " SUM(t.task_duration) as nbseconds,";
  1096. $sql .= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
  1097. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
  1098. $sql .= " WHERE t.fk_task = ".$id;
  1099. if (is_object($fuser) && $fuser->id > 0)
  1100. {
  1101. $sql .= " AND fk_user = ".$fuser->id;
  1102. }
  1103. if ($dates > 0)
  1104. {
  1105. $datefieldname = "task_datehour";
  1106. $sql .= " AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)";
  1107. }
  1108. if ($datee > 0)
  1109. {
  1110. $datefieldname = "task_datehour";
  1111. $sql .= " AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)";
  1112. }
  1113. //print $sql;
  1114. dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
  1115. $resql = $this->db->query($sql);
  1116. if ($resql)
  1117. {
  1118. $obj = $this->db->fetch_object($resql);
  1119. $result['amount'] = $obj->amount;
  1120. $result['nbseconds'] = $obj->nbseconds;
  1121. $result['nblinesnull'] = $obj->nblinesnull;
  1122. $this->db->free($resql);
  1123. return $result;
  1124. } else {
  1125. dol_print_error($this->db);
  1126. return $result;
  1127. }
  1128. }
  1129. /**
  1130. * Load one record of time spent
  1131. *
  1132. * @param int $id Id object
  1133. * @return int <0 if KO, >0 if OK
  1134. */
  1135. public function fetchTimeSpent($id)
  1136. {
  1137. global $langs;
  1138. $sql = "SELECT";
  1139. $sql .= " t.rowid,";
  1140. $sql .= " t.fk_task,";
  1141. $sql .= " t.task_date,";
  1142. $sql .= " t.task_datehour,";
  1143. $sql .= " t.task_date_withhour,";
  1144. $sql .= " t.task_duration,";
  1145. $sql .= " t.fk_user,";
  1146. $sql .= " t.thm,";
  1147. $sql .= " t.note";
  1148. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
  1149. $sql .= " WHERE t.rowid = ".$id;
  1150. dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
  1151. $resql = $this->db->query($sql);
  1152. if ($resql)
  1153. {
  1154. if ($this->db->num_rows($resql))
  1155. {
  1156. $obj = $this->db->fetch_object($resql);
  1157. $this->timespent_id = $obj->rowid;
  1158. $this->id = $obj->fk_task;
  1159. $this->timespent_date = $this->db->jdate($obj->task_date);
  1160. $this->timespent_datehour = $this->db->jdate($obj->task_datehour);
  1161. $this->timespent_withhour = $obj->task_date_withhour;
  1162. $this->timespent_duration = $obj->task_duration;
  1163. $this->timespent_fk_user = $obj->fk_user;
  1164. $this->timespent_thm = $obj->thm; // hourly rate
  1165. $this->timespent_note = $obj->note;
  1166. }
  1167. $this->db->free($resql);
  1168. return 1;
  1169. } else {
  1170. $this->error = "Error ".$this->db->lasterror();
  1171. return -1;
  1172. }
  1173. }
  1174. /**
  1175. * Load all records of time spent
  1176. *
  1177. * @param User $userobj User object
  1178. * @param string $morewherefilter Add more filter into where SQL request (must start with ' AND ...')
  1179. * @return int <0 if KO, array of time spent if OK
  1180. */
  1181. public function fetchAllTimeSpent(User $userobj, $morewherefilter = '')
  1182. {
  1183. global $langs;
  1184. $arrayres = array();
  1185. $sql = "SELECT";
  1186. $sql .= " s.rowid as socid,";
  1187. $sql .= " s.nom as thirdparty_name,";
  1188. $sql .= " s.email as thirdparty_email,";
  1189. $sql .= " ptt.rowid,";
  1190. $sql .= " ptt.fk_task,";
  1191. $sql .= " ptt.task_date,";
  1192. $sql .= " ptt.task_datehour,";
  1193. $sql .= " ptt.task_date_withhour,";
  1194. $sql .= " ptt.task_duration,";
  1195. $sql .= " ptt.fk_user,";
  1196. $sql .= " ptt.note,";
  1197. $sql .= " pt.rowid as task_id,";
  1198. $sql .= " pt.ref as task_ref,";
  1199. $sql .= " pt.label as task_label,";
  1200. $sql .= " p.rowid as project_id,";
  1201. $sql .= " p.ref as project_ref,";
  1202. $sql .= " p.title as project_label,";
  1203. $sql .= " p.public as public";
  1204. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as ptt, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet as p";
  1205. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
  1206. $sql .= " WHERE ptt.fk_task = pt.rowid AND pt.fk_projet = p.rowid";
  1207. $sql .= " AND ptt.fk_user = ".$userobj->id;
  1208. $sql .= " AND pt.entity IN (".getEntity('project').")";
  1209. if ($morewherefilter) $sql .= $morewherefilter;
  1210. dol_syslog(get_class($this)."::fetchAllTimeSpent", LOG_DEBUG);
  1211. $resql = $this->db->query($sql);
  1212. if ($resql)
  1213. {
  1214. $num = $this->db->num_rows($resql);
  1215. $i = 0;
  1216. while ($i < $num)
  1217. {
  1218. $obj = $this->db->fetch_object($resql);
  1219. $newobj = new stdClass();
  1220. $newobj->socid = $obj->socid;
  1221. $newobj->thirdparty_name = $obj->thirdparty_name;
  1222. $newobj->thirdparty_email = $obj->thirdparty_email;
  1223. $newobj->fk_project = $obj->project_id;
  1224. $newobj->project_ref = $obj->project_ref;
  1225. $newobj->project_label = $obj->project_label;
  1226. $newobj->public = $obj->project_public;
  1227. $newobj->fk_task = $obj->task_id;
  1228. $newobj->task_ref = $obj->task_ref;
  1229. $newobj->task_label = $obj->task_label;
  1230. $newobj->timespent_id = $obj->rowid;
  1231. $newobj->timespent_date = $this->db->jdate($obj->task_date);
  1232. $newobj->timespent_datehour = $this->db->jdate($obj->task_datehour);
  1233. $newobj->timespent_withhour = $obj->task_date_withhour;
  1234. $newobj->timespent_duration = $obj->task_duration;
  1235. $newobj->timespent_fk_user = $obj->fk_user;
  1236. $newobj->timespent_note = $obj->note;
  1237. $arrayres[] = $newobj;
  1238. $i++;
  1239. }
  1240. $this->db->free($resql);
  1241. } else {
  1242. dol_print_error($this->db);
  1243. $this->error = "Error ".$this->db->lasterror();
  1244. return -1;
  1245. }
  1246. return $arrayres;
  1247. }
  1248. /**
  1249. * Update time spent
  1250. *
  1251. * @param User $user User id
  1252. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1253. * @return int <0 if KO, >0 if OK
  1254. */
  1255. public function updateTimeSpent($user, $notrigger = 0)
  1256. {
  1257. global $conf, $langs;
  1258. $ret = 0;
  1259. // Check parameters
  1260. if ($this->timespent_date == '')
  1261. {
  1262. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Date"));
  1263. return -1;
  1264. }
  1265. if (!($this->timespent_fk_user > 0))
  1266. {
  1267. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("User"));
  1268. return -1;
  1269. }
  1270. // Clean parameters
  1271. if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
  1272. if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
  1273. $this->db->begin();
  1274. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
  1275. $sql .= " task_date = '".$this->db->idate($this->timespent_date)."',";
  1276. $sql .= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',";
  1277. $sql .= " task_date_withhour = ".(empty($this->timespent_withhour) ? 0 : 1).",";
  1278. $sql .= " task_duration = ".$this->timespent_duration.",";
  1279. $sql .= " fk_user = ".$this->timespent_fk_user.",";
  1280. $sql .= " note = ".(isset($this->timespent_note) ? "'".$this->db->escape($this->timespent_note)."'" : "null");
  1281. $sql .= " WHERE rowid = ".$this->timespent_id;
  1282. dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
  1283. if ($this->db->query($sql))
  1284. {
  1285. if (!$notrigger)
  1286. {
  1287. // Call trigger
  1288. $result = $this->call_trigger('TASK_TIMESPENT_MODIFY', $user);
  1289. if ($result < 0)
  1290. {
  1291. $this->db->rollback();
  1292. $ret = -1;
  1293. } else $ret = 1;
  1294. // End call triggers
  1295. } else $ret = 1;
  1296. } else {
  1297. $this->error = $this->db->lasterror();
  1298. $this->db->rollback();
  1299. $ret = -1;
  1300. }
  1301. if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration))
  1302. {
  1303. $newDuration = $this->timespent_duration - $this->timespent_old_duration;
  1304. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
  1305. $sql .= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")";
  1306. $sql .= " WHERE rowid = ".$this->id;
  1307. dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
  1308. if (!$this->db->query($sql))
  1309. {
  1310. $this->error = $this->db->lasterror();
  1311. $this->db->rollback();
  1312. $ret = -2;
  1313. }
  1314. }
  1315. if ($ret >= 0) $this->db->commit();
  1316. return $ret;
  1317. }
  1318. /**
  1319. * Delete time spent
  1320. *
  1321. * @param User $user User that delete
  1322. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1323. * @return int <0 if KO, >0 if OK
  1324. */
  1325. public function delTimeSpent($user, $notrigger = 0)
  1326. {
  1327. global $conf, $langs;
  1328. $error = 0;
  1329. $this->db->begin();
  1330. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
  1331. $sql .= " WHERE rowid = ".$this->timespent_id;
  1332. dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
  1333. $resql = $this->db->query($sql);
  1334. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  1335. if (!$error)
  1336. {
  1337. if (!$notrigger)
  1338. {
  1339. // Call trigger
  1340. $result = $this->call_trigger('TASK_TIMESPENT_DELETE', $user);
  1341. if ($result < 0) { $error++; }
  1342. // End call triggers
  1343. }
  1344. }
  1345. if (!$error)
  1346. {
  1347. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
  1348. $sql .= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration ? $this->timespent_duration : 0);
  1349. $sql .= " WHERE rowid = ".$this->id;
  1350. dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
  1351. if ($this->db->query($sql))
  1352. {
  1353. $result = 0;
  1354. } else {
  1355. $this->error = $this->db->lasterror();
  1356. $result = -2;
  1357. }
  1358. }
  1359. // Commit or rollback
  1360. if ($error)
  1361. {
  1362. foreach ($this->errors as $errmsg)
  1363. {
  1364. dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
  1365. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1366. }
  1367. $this->db->rollback();
  1368. return -1 * $error;
  1369. } else {
  1370. $this->db->commit();
  1371. return 1;
  1372. }
  1373. }
  1374. /** Load an object from its id and create a new one in database
  1375. *
  1376. * @param User $user User making the clone
  1377. * @param int $fromid Id of object to clone
  1378. * @param int $project_id Id of project to attach clone task
  1379. * @param int $parent_task_id Id of task to attach clone task
  1380. * @param bool $clone_change_dt recalculate date of task regarding new project start date
  1381. * @param bool $clone_affectation clone affectation of project
  1382. * @param bool $clone_time clone time of project
  1383. * @param bool $clone_file clone file of project
  1384. * @param bool $clone_note clone note of project
  1385. * @param bool $clone_prog clone progress of project
  1386. * @return int New id of clone
  1387. */
  1388. public function createFromClone(User $user, $fromid, $project_id, $parent_task_id, $clone_change_dt = false, $clone_affectation = false, $clone_time = false, $clone_file = false, $clone_note = false, $clone_prog = false)
  1389. {
  1390. global $langs, $conf;
  1391. $error = 0;
  1392. //Use 00:00 of today if time is use on task.
  1393. $now = dol_mktime(0, 0, 0, dol_print_date(dol_now(), '%m'), dol_print_date(dol_now(), '%d'), dol_print_date(dol_now(), '%Y'));
  1394. $datec = $now;
  1395. $clone_task = new Task($this->db);
  1396. $origin_task = new Task($this->db);
  1397. $clone_task->context['createfromclone'] = 'createfromclone';
  1398. $this->db->begin();
  1399. // Load source object
  1400. $clone_task->fetch($fromid);
  1401. $clone_task->fetch_optionals();
  1402. //var_dump($clone_task->array_options);exit;
  1403. $origin_task->fetch($fromid);
  1404. $defaultref = '';
  1405. $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
  1406. if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
  1407. {
  1408. require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
  1409. $modTask = new $obj;
  1410. $defaultref = $modTask->getNextValue(0, $clone_task);
  1411. }
  1412. $ori_project_id = $clone_task->fk_project;
  1413. $clone_task->id = 0;
  1414. $clone_task->ref = $defaultref;
  1415. $clone_task->fk_project = $project_id;
  1416. $clone_task->fk_task_parent = $parent_task_id;
  1417. $clone_task->date_c = $datec;
  1418. $clone_task->planned_workload = $origin_task->planned_workload;
  1419. $clone_task->rang = $origin_task->rang;
  1420. //Manage Task Date
  1421. if ($clone_change_dt)
  1422. {
  1423. $projectstatic = new Project($this->db);
  1424. $projectstatic->fetch($ori_project_id);
  1425. //Origin project strat date
  1426. $orign_project_dt_start = $projectstatic->date_start;
  1427. //Calcultate new task start date with difference between origin proj start date and origin task start date
  1428. if (!empty($clone_task->date_start))
  1429. {
  1430. $clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start;
  1431. }
  1432. //Calcultate new task end date with difference between origin proj end date and origin task end date
  1433. if (!empty($clone_task->date_end))
  1434. {
  1435. $clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start;
  1436. }
  1437. }
  1438. if (!$clone_prog)
  1439. {
  1440. $clone_task->progress = 0;
  1441. }
  1442. // Create clone
  1443. $result = $clone_task->create($user);
  1444. // Other options
  1445. if ($result < 0)
  1446. {
  1447. $this->error = $clone_task->error;
  1448. $error++;
  1449. }
  1450. // End
  1451. if (!$error)
  1452. {
  1453. $clone_task_id = $clone_task->id;
  1454. $clone_task_ref = $clone_task->ref;
  1455. //Note Update
  1456. if (!$clone_note)
  1457. {
  1458. $clone_task->note_private = '';
  1459. $clone_task->note_public = '';
  1460. } else {
  1461. $this->db->begin();
  1462. $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES | ENT_HTML5), '_public');
  1463. if ($res < 0)
  1464. {
  1465. $this->error .= $clone_task->error;
  1466. $error++;
  1467. $this->db->rollback();
  1468. } else {
  1469. $this->db->commit();
  1470. }
  1471. $this->db->begin();
  1472. $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES | ENT_HTML5), '_private');
  1473. if ($res < 0)
  1474. {
  1475. $this->error .= $clone_task->error;
  1476. $error++;
  1477. $this->db->rollback();
  1478. } else {
  1479. $this->db->commit();
  1480. }
  1481. }
  1482. //Duplicate file
  1483. if ($clone_file)
  1484. {
  1485. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1486. //retrieve project origin ref to know folder to copy
  1487. $projectstatic = new Project($this->db);
  1488. $projectstatic->fetch($ori_project_id);
  1489. $ori_project_ref = $projectstatic->ref;
  1490. if ($ori_project_id != $project_id)
  1491. {
  1492. $projectstatic->fetch($project_id);
  1493. $clone_project_ref = $projectstatic->ref;
  1494. } else {
  1495. $clone_project_ref = $ori_project_ref;
  1496. }
  1497. $clone_task_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($clone_project_ref)."/".dol_sanitizeFileName($clone_task_ref);
  1498. $ori_task_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($ori_project_ref)."/".dol_sanitizeFileName($fromid);
  1499. $filearray = dol_dir_list($ori_task_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
  1500. foreach ($filearray as $key => $file)
  1501. {
  1502. if (!file_exists($clone_task_dir))
  1503. {
  1504. if (dol_mkdir($clone_task_dir) < 0)
  1505. {
  1506. $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
  1507. $error++;
  1508. }
  1509. }
  1510. $rescopy = dol_copy($ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name'], 0, 1);
  1511. if (is_numeric($rescopy) && $rescopy < 0)
  1512. {
  1513. $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name']);
  1514. $error++;
  1515. }
  1516. }
  1517. }
  1518. // clone affectation
  1519. if ($clone_affectation)
  1520. {
  1521. $origin_task = new Task($this->db);
  1522. $origin_task->fetch($fromid);
  1523. foreach (array('internal', 'external') as $source)
  1524. {
  1525. $tab = $origin_task->liste_contact(-1, $source);
  1526. $num = count($tab);
  1527. $i = 0;
  1528. while ($i < $num)
  1529. {
  1530. $clone_task->add_contact($tab[$i]['id'], $tab[$i]['code'], $tab[$i]['source']);
  1531. if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  1532. {
  1533. $langs->load("errors");
  1534. $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
  1535. $error++;
  1536. } else {
  1537. if ($clone_task->error != '')
  1538. {
  1539. $this->error .= $clone_task->error;
  1540. $error++;
  1541. }
  1542. }
  1543. $i++;
  1544. }
  1545. }
  1546. }
  1547. if ($clone_time)
  1548. {
  1549. //TODO clone time of affectation
  1550. }
  1551. }
  1552. unset($clone_task->context['createfromclone']);
  1553. if (!$error)
  1554. {
  1555. $this->db->commit();
  1556. return $clone_task_id;
  1557. } else {
  1558. $this->db->rollback();
  1559. dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
  1560. return -1;
  1561. }
  1562. }
  1563. /**
  1564. * Return status label of object
  1565. *
  1566. * @param integer $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1567. * @return string Label
  1568. */
  1569. public function getLibStatut($mode = 0)
  1570. {
  1571. return $this->LibStatut($this->fk_statut, $mode);
  1572. }
  1573. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1574. /**
  1575. * Return status label for an object
  1576. *
  1577. * @param int $status Id status
  1578. * @param integer $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1579. * @return string Label
  1580. */
  1581. public function LibStatut($status, $mode = 0)
  1582. {
  1583. // phpcs:enable
  1584. global $langs;
  1585. // list of Statut of the task
  1586. $this->statuts[0] = 'Draft';
  1587. $this->statuts[1] = 'ToDo';
  1588. $this->statuts[2] = 'Running';
  1589. $this->statuts[3] = 'Finish';
  1590. $this->statuts[4] = 'Transfered';
  1591. $this->statuts_short[0] = 'Draft';
  1592. $this->statuts_short[1] = 'ToDo';
  1593. $this->statuts_short[2] = 'Running';
  1594. $this->statuts_short[3] = 'Completed';
  1595. $this->statuts_short[4] = 'Transfered';
  1596. if ($mode == 0)
  1597. {
  1598. return $langs->trans($this->statuts[$status]);
  1599. } elseif ($mode == 1)
  1600. {
  1601. return $langs->trans($this->statuts_short[$status]);
  1602. } elseif ($mode == 2)
  1603. {
  1604. if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts_short[$status]);
  1605. elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts_short[$status]);
  1606. elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts_short[$status]);
  1607. elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]);
  1608. elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]);
  1609. elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts_short[$status]);
  1610. } elseif ($mode == 3)
  1611. {
  1612. if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0');
  1613. elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1');
  1614. elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3');
  1615. elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6');
  1616. elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6');
  1617. elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5');
  1618. } elseif ($mode == 4)
  1619. {
  1620. if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]);
  1621. elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts[$status]);
  1622. elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts[$status]);
  1623. elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]);
  1624. elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]);
  1625. elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts[$status]);
  1626. } elseif ($mode == 5)
  1627. {
  1628. /*if ($status==0) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut0');
  1629. elseif ($status==1) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut1');
  1630. elseif ($status==2) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut3');
  1631. elseif ($status==3) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut6');
  1632. elseif ($status==4) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut6');
  1633. elseif ($status==5) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut5');
  1634. */
  1635. //else return $this->progress.' %';
  1636. return '&nbsp;';
  1637. } elseif ($mode == 6)
  1638. {
  1639. /*if ($status==0) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut0');
  1640. elseif ($status==1) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut1');
  1641. elseif ($status==2) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut3');
  1642. elseif ($status==3) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut6');
  1643. elseif ($status==4) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut6');
  1644. elseif ($status==5) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut5');
  1645. */
  1646. //else return $this->progress.' %';
  1647. return '&nbsp;';
  1648. }
  1649. }
  1650. /**
  1651. * Create an intervention document on disk using template defined into PROJECT_TASK_ADDON_PDF
  1652. *
  1653. * @param string $modele force le modele a utiliser ('' par defaut)
  1654. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1655. * @param int $hidedetails Hide details of lines
  1656. * @param int $hidedesc Hide description
  1657. * @param int $hideref Hide ref
  1658. * @return int 0 if KO, 1 if OK
  1659. */
  1660. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1661. {
  1662. global $conf;
  1663. $outputlangs->load("projects");
  1664. if (!dol_strlen($modele)) {
  1665. $modele = 'nodefault';
  1666. if (!empty($this->model_pdf)) {
  1667. $modele = $this->model_pdf;
  1668. } elseif (!empty($this->modelpdf)) { // deprecated
  1669. $modele = $this->modelpdf;
  1670. } elseif (!empty($conf->global->PROJECT_TASK_ADDON_PDF)) {
  1671. $modele = $conf->global->PROJECT_TASK_ADDON_PDF;
  1672. }
  1673. }
  1674. $modelpath = "core/modules/project/task/doc/";
  1675. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1676. }
  1677. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1678. /**
  1679. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1680. *
  1681. * @param User $user Objet user
  1682. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1683. */
  1684. public function load_board($user)
  1685. {
  1686. // phpcs:enable
  1687. global $conf, $langs;
  1688. // For external user, no check is done on company because readability is managed by public status of project and assignement.
  1689. //$socid=$user->socid;
  1690. $projectstatic = new Project($this->db);
  1691. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
  1692. // List of tasks (does not care about permissions. Filtering will be done later)
  1693. $sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,";
  1694. $sql .= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,";
  1695. $sql .= " t.dateo as date_start, t.datee as datee";
  1696. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1697. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
  1698. //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
  1699. $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
  1700. $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
  1701. $sql .= " AND p.fk_statut = 1";
  1702. $sql .= " AND t.fk_projet = p.rowid";
  1703. $sql .= " AND (t.progress IS NULL OR t.progress < 100)"; // tasks to do
  1704. if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")";
  1705. // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
  1706. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
  1707. if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
  1708. // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
  1709. // if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
  1710. //print $sql;
  1711. $resql = $this->db->query($sql);
  1712. if ($resql)
  1713. {
  1714. $task_static = new Task($this->db);
  1715. $response = new WorkboardResponse();
  1716. $response->warning_delay = $conf->projet->task->warning_delay / 60 / 60 / 24;
  1717. $response->label = $langs->trans("OpenedTasks");
  1718. if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
  1719. else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
  1720. $response->img = img_object('', "task");
  1721. // This assignment in condition is not a bug. It allows walking the results.
  1722. while ($obj = $this->db->fetch_object($resql))
  1723. {
  1724. $response->nbtodo++;
  1725. $task_static->projectstatus = $obj->projectstatus;
  1726. $task_static->progress = $obj->progress;
  1727. $task_static->fk_statut = $obj->status;
  1728. $task_static->date_end = $this->db->jdate($obj->datee);
  1729. if ($task_static->hasDelay()) {
  1730. $response->nbtodolate++;
  1731. }
  1732. }
  1733. return $response;
  1734. } else {
  1735. $this->error = $this->db->error();
  1736. return -1;
  1737. }
  1738. }
  1739. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1740. /**
  1741. * Charge indicateurs this->nb de tableau de bord
  1742. *
  1743. * @return int <0 if ko, >0 if ok
  1744. */
  1745. public function load_state_board()
  1746. {
  1747. // phpcs:enable
  1748. global $user;
  1749. $mine = 0; $socid = $user->socid;
  1750. $projectstatic = new Project($this->db);
  1751. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine, 1, $socid);
  1752. // List of tasks (does not care about permissions. Filtering will be done later)
  1753. $sql = "SELECT count(p.rowid) as nb";
  1754. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1755. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
  1756. if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
  1757. $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
  1758. $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
  1759. $sql .= " AND t.fk_projet = p.rowid"; // tasks to do
  1760. if ($mine || !$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")";
  1761. // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
  1762. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
  1763. if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
  1764. if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id.") OR (s.rowid IS NULL))";
  1765. $resql = $this->db->query($sql);
  1766. if ($resql)
  1767. {
  1768. // This assignment in condition is not a bug. It allows walking the results.
  1769. while ($obj = $this->db->fetch_object($resql))
  1770. {
  1771. $this->nb["tasks"] = $obj->nb;
  1772. }
  1773. $this->db->free($resql);
  1774. return 1;
  1775. } else {
  1776. dol_print_error($this->db);
  1777. $this->error = $this->db->error();
  1778. return -1;
  1779. }
  1780. }
  1781. /**
  1782. * Is the task delayed?
  1783. *
  1784. * @return bool
  1785. */
  1786. public function hasDelay()
  1787. {
  1788. global $conf;
  1789. if (!($this->progress >= 0 && $this->progress < 100)) {
  1790. return false;
  1791. }
  1792. $now = dol_now();
  1793. $datetouse = ($this->date_end > 0) ? $this->date_end : ($this->datee > 0 ? $this->datee : 0);
  1794. return ($datetouse > 0 && ($datetouse < ($now - $conf->projet->task->warning_delay)));
  1795. }
  1796. }