actioncomm.class.php 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es>
  6. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  7. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  8. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  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/comm/action/class/actioncomm.class.php
  25. * \ingroup agenda
  26. * \brief File of class to manage agenda events (actions)
  27. */
  28. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  30. /**
  31. * Class to manage agenda events (actions)
  32. */
  33. class ActionComm extends CommonObject
  34. {
  35. /**
  36. * @var string ID to identify managed object
  37. */
  38. public $element = 'action';
  39. /**
  40. * @var string Name of table without prefix where object is stored
  41. */
  42. public $table_element = 'actioncomm';
  43. /**
  44. * @var string Name of id column
  45. */
  46. public $table_rowid = 'id';
  47. /**
  48. * @var string Name of icon for actioncomm object. Filename of icon is object_action.png
  49. */
  50. public $picto = 'action';
  51. /**
  52. * @var int 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  53. */
  54. public $ismultientitymanaged = 1;
  55. /**
  56. * @var integer 0=Default
  57. * 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  58. * 2=Same than 1 but accept record if fksoc is empty
  59. */
  60. public $restrictiononfksoc = 2;
  61. /**
  62. * @var int Id of the event
  63. */
  64. public $id;
  65. /**
  66. * @var int Id of the event. Use $id as possible
  67. */
  68. public $ref;
  69. /**
  70. * @var int Id into parent table llx_c_actioncomm (used only if option to use type is set)
  71. */
  72. public $type_id;
  73. /**
  74. * @var string Code into parent table llx_c_actioncomm (used only if option to use type is set). With default setup, should be AC_OTH_AUTO or AC_OTH.
  75. */
  76. public $type_code;
  77. /**
  78. * @var string Type label
  79. */
  80. public $type_label;
  81. /**
  82. * @var string Label into parent table llx_c_actioncomm (used only if option to use type is set)
  83. */
  84. public $type;
  85. /**
  86. * @var string Color into parent table llx_c_actioncomm (used only if option to use type is set)
  87. */
  88. public $type_color;
  89. /**
  90. * @var string Free code to identify action. Ie: Agenda trigger add here AC_TRIGGERNAME ('AC_COMPANY_CREATE', 'AC_PROPAL_VALIDATE', ...)
  91. */
  92. public $code;
  93. /**
  94. * @var string Agenda event label
  95. */
  96. public $label;
  97. /**
  98. * @var integer Date creation record (datec)
  99. */
  100. public $datec;
  101. /**
  102. * @var integer Date end record (datef)
  103. */
  104. public $datef;
  105. /**
  106. * @var integer Duration (duree)
  107. */
  108. public $duree;
  109. /**
  110. * @var integer Date modification record (tms)
  111. */
  112. public $datem;
  113. /**
  114. * @var User Object user that create action
  115. * @deprecated
  116. * @see $authorid
  117. */
  118. public $author;
  119. /**
  120. * @var User Object user that modified action
  121. * @deprecated
  122. * @see $usermodid
  123. */
  124. public $usermod;
  125. /**
  126. * @var int Id user that create action
  127. */
  128. public $authorid;
  129. /**
  130. * @var int Id user that modified action
  131. */
  132. public $usermodid;
  133. /**
  134. * @var integer Date action start (datep)
  135. */
  136. public $datep;
  137. /**
  138. * @var integer Date action end (datep2)
  139. */
  140. public $datep2;
  141. /**
  142. * @var int -1=Unkown duration
  143. * @deprecated
  144. */
  145. public $durationp = -1;
  146. /**
  147. * @var int 1=Event on full day
  148. */
  149. public $fulldayevent = 0;
  150. /**
  151. * @var int Milestone
  152. * @deprecated Milestone is already event with end date = start date
  153. */
  154. public $punctual = 1;
  155. /**
  156. * @var integer Percentage
  157. */
  158. public $percentage;
  159. /**
  160. * @var string Location
  161. */
  162. public $location;
  163. /**
  164. * @var int Transparency (ical standard). Used to say if people assigned to event are busy or not by event. 0=available, 1=busy, 2=busy (refused events)
  165. */
  166. public $transparency;
  167. /**
  168. * @var int (0 By default)
  169. */
  170. public $priority;
  171. /**
  172. * @var int[] Array of user ids
  173. */
  174. public $userassigned = array();
  175. /**
  176. * @var int Id of user owner = fk_user_action into table
  177. */
  178. public $userownerid;
  179. /**
  180. * @var int Id of user done (deprecated)
  181. * @deprecated
  182. */
  183. public $userdoneid;
  184. /**
  185. * @var int[] Array of contact ids
  186. */
  187. public $socpeopleassigned = array();
  188. /**
  189. * @var int[] Array of other contact emails (not user, not contact)
  190. */
  191. public $otherassigned = array();
  192. /**
  193. * @var User Object user of owner
  194. * @deprecated
  195. * @see $userownerid
  196. */
  197. public $usertodo;
  198. /**
  199. * @var User Object user that did action
  200. * @deprecated
  201. * @see $userdoneid
  202. */
  203. public $userdone;
  204. /**
  205. * @var int thirdparty id linked to action
  206. */
  207. public $socid;
  208. /**
  209. * @var int socpeople id linked to action
  210. */
  211. public $contactid;
  212. /**
  213. * @var Societe|null Company linked to action (optional)
  214. * @deprecated
  215. * @see $socid
  216. */
  217. public $societe;
  218. /**
  219. * @var Contact|null Contact linked to action (optional)
  220. * @deprecated
  221. * @see $contactid
  222. */
  223. public $contact;
  224. // Properties for links to other objects
  225. /**
  226. * @var int Id of linked object
  227. */
  228. public $fk_element; // Id of record
  229. /**
  230. * @var int Id of record alternative for API
  231. */
  232. public $elementid;
  233. /**
  234. * @var string Type of record. This if property ->element of object linked to.
  235. */
  236. public $elementtype;
  237. /**
  238. * @var string Ical name
  239. */
  240. public $icalname;
  241. /**
  242. * @var string Ical color
  243. */
  244. public $icalcolor;
  245. /**
  246. * @var string Extraparam
  247. */
  248. public $extraparams;
  249. /**
  250. * @var array Actions
  251. */
  252. public $actions = array();
  253. /**
  254. * @var string Email msgid
  255. */
  256. public $email_msgid;
  257. /**
  258. * @var string Email from
  259. */
  260. public $email_from;
  261. /**
  262. * @var string Email sender
  263. */
  264. public $email_sender;
  265. /**
  266. * @var string Email to
  267. */
  268. public $email_to;
  269. /**
  270. * @var string Email tocc
  271. */
  272. public $email_tocc;
  273. /**
  274. * @var string Email tobcc
  275. */
  276. public $email_tobcc;
  277. /**
  278. * @var string Email subject
  279. */
  280. public $email_subject;
  281. /**
  282. * @var string Email errors to
  283. */
  284. public $errors_to;
  285. /**
  286. * Constructor
  287. *
  288. * @param DoliDB $db Database handler
  289. */
  290. public function __construct(DoliDB $db)
  291. {
  292. $this->db = $db;
  293. }
  294. /**
  295. * Add an action/event into database.
  296. * $this->type_id OR $this->type_code must be set.
  297. *
  298. * @param User $user Object user making action
  299. * @param int $notrigger 1 = disable triggers, 0 = enable triggers
  300. * @return int Id of created event, < 0 if KO
  301. */
  302. public function create(User $user, $notrigger = 0)
  303. {
  304. global $langs, $conf, $hookmanager;
  305. $error = 0;
  306. $now = dol_now();
  307. // Check parameters
  308. if (!isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0
  309. {
  310. dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING);
  311. $this->errors[] = 'ErrorPropertyUserowneridNotDefined';
  312. return -1;
  313. }
  314. // Clean parameters
  315. $this->label = dol_trunc(trim($this->label), 128);
  316. $this->location = dol_trunc(trim($this->location), 128);
  317. $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private));
  318. if (empty($this->percentage)) $this->percentage = 0;
  319. if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0;
  320. if (empty($this->fulldayevent)) $this->fulldayevent = 0;
  321. if (empty($this->punctual)) $this->punctual = 0;
  322. if (empty($this->transparency)) $this->transparency = 0;
  323. if ($this->percentage > 100) $this->percentage = 100;
  324. //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
  325. if (!empty($this->datep) && !empty($this->datef)) $this->durationp = ($this->datef - $this->datep); // deprecated
  326. //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date);
  327. if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) $this->datef = $this->datep;
  328. //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date;
  329. if (!isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0;
  330. // For backward compatibility
  331. if ($this->elementtype == 'facture') $this->elementtype = 'invoice';
  332. if ($this->elementtype == 'commande') $this->elementtype = 'order';
  333. if ($this->elementtype == 'contrat') $this->elementtype = 'contract';
  334. if (!is_array($this->userassigned) && !empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array
  335. {
  336. $tmpid = $this->userassigned;
  337. $this->userassigned = array();
  338. $this->userassigned[$tmpid] = array('id'=>$tmpid, 'transparency'=>$this->transparency);
  339. }
  340. $userownerid = $this->userownerid;
  341. $userdoneid = $this->userdoneid;
  342. // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...).
  343. if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned))
  344. $this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency));
  345. if (!$this->type_id || !$this->type_code)
  346. {
  347. $key = empty($this->type_id) ? $this->type_code : $this->type_id;
  348. // Get id from code
  349. $cactioncomm = new CActionComm($this->db);
  350. $result = $cactioncomm->fetch($key);
  351. if ($result > 0)
  352. {
  353. $this->type_id = $cactioncomm->id;
  354. $this->type_code = $cactioncomm->code;
  355. }
  356. elseif ($result == 0)
  357. {
  358. $this->error = 'Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"';
  359. return -1;
  360. }
  361. else
  362. {
  363. $this->error = $cactioncomm->error;
  364. return -1;
  365. }
  366. }
  367. $code = empty($this->code) ? $this->type_code : $this->code;
  368. // Check parameters
  369. if (!$this->type_id)
  370. {
  371. $this->error = "ErrorWrongParameters";
  372. return -1;
  373. }
  374. $this->db->begin();
  375. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm";
  376. $sql .= "(datec,";
  377. $sql .= "datep,";
  378. $sql .= "datep2,";
  379. $sql .= "durationp,"; // deprecated
  380. $sql .= "fk_action,";
  381. $sql .= "code,";
  382. $sql .= "ref_ext,";
  383. $sql .= "fk_soc,";
  384. $sql .= "fk_project,";
  385. $sql .= "note,";
  386. $sql .= "fk_contact,";
  387. $sql .= "fk_user_author,";
  388. $sql .= "fk_user_action,";
  389. $sql .= "fk_user_done,";
  390. $sql .= "label,percent,priority,fulldayevent,location,punctual,";
  391. $sql .= "transparency,";
  392. $sql .= "fk_element,";
  393. $sql .= "elementtype,";
  394. $sql .= "entity,";
  395. $sql .= "extraparams,";
  396. // Fields emails
  397. $sql .= "email_msgid,";
  398. $sql .= "email_from,";
  399. $sql .= "email_sender,";
  400. $sql .= "email_to,";
  401. $sql .= "email_tocc,";
  402. $sql .= "email_tobcc,";
  403. $sql .= "email_subject,";
  404. $sql .= "errors_to";
  405. $sql .= ") VALUES (";
  406. $sql .= "'".$this->db->idate($now)."', ";
  407. $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", ";
  408. $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", ";
  409. $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated
  410. $sql .= (isset($this->type_id) ? $this->type_id : "null").",";
  411. $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", ";
  412. $sql .= ($this->ref_ext ? ("'".$this->db->idate($this->ref_ext)."'") : "null").", ";
  413. $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", ";
  414. $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", ";
  415. $sql .= " '".$this->db->escape($this->note_private)."', ";
  416. $sql .= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid : "null").", ";
  417. $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", ";
  418. $sql .= ($userownerid > 0 ? $userownerid : "null").", ";
  419. $sql .= ($userdoneid > 0 ? $userdoneid : "null").", ";
  420. $sql .= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."','".$this->db->escape($this->punctual)."', ";
  421. $sql .= "'".$this->db->escape($this->transparency)."', ";
  422. $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", ";
  423. $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", ";
  424. $sql .= $conf->entity.",";
  425. $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", ";
  426. // Fields emails
  427. $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", ";
  428. $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", ";
  429. $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", ";
  430. $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", ";
  431. $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", ";
  432. $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", ";
  433. $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", ";
  434. $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null");
  435. $sql .= ")";
  436. dol_syslog(get_class($this)."::add", LOG_DEBUG);
  437. $resql = $this->db->query($sql);
  438. if ($resql)
  439. {
  440. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
  441. // Now insert assigned users
  442. if (!$error)
  443. {
  444. //dol_syslog(var_export($this->userassigned, true));
  445. foreach ($this->userassigned as $key => $val)
  446. {
  447. if (!is_array($val)) // For backward compatibility when val=id
  448. {
  449. $val = array('id'=>$val);
  450. }
  451. if ($val['id'] > 0)
  452. {
  453. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  454. $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")";
  455. $resql = $this->db->query($sql);
  456. if (!$resql)
  457. {
  458. $error++;
  459. dol_syslog('Error to process userassigned: '.$this->db->lasterror(), LOG_ERR);
  460. $this->errors[] = $this->db->lasterror();
  461. }
  462. //var_dump($sql);exit;
  463. }
  464. }
  465. }
  466. if (!$error)
  467. {
  468. if (!empty($this->socpeopleassigned))
  469. {
  470. foreach ($this->socpeopleassigned as $id => $val)
  471. {
  472. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  473. $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
  474. $resql = $this->db->query($sql);
  475. if (!$resql)
  476. {
  477. $error++;
  478. dol_syslog('Error to process socpeopleassigned: '.$this->db->lasterror(), LOG_ERR);
  479. $this->errors[] = $this->db->lasterror();
  480. }
  481. }
  482. }
  483. }
  484. if (!$error)
  485. {
  486. // Actions on extra fields
  487. $result = $this->insertExtraFields();
  488. if ($result < 0)
  489. {
  490. $error++;
  491. }
  492. }
  493. if (!$error && !$notrigger)
  494. {
  495. // Call trigger
  496. $result = $this->call_trigger('ACTION_CREATE', $user);
  497. if ($result < 0) { $error++; }
  498. // End call triggers
  499. }
  500. if (!$error)
  501. {
  502. $this->db->commit();
  503. return $this->id;
  504. }
  505. else
  506. {
  507. $this->db->rollback();
  508. return -1;
  509. }
  510. }
  511. else
  512. {
  513. $this->db->rollback();
  514. $this->error = $this->db->lasterror();
  515. return -1;
  516. }
  517. }
  518. /**
  519. * Load an object from its id and create a new one in database
  520. *
  521. * @param User $fuser Object user making action
  522. * @param int $socid Id of thirdparty
  523. * @return int New id of clone
  524. */
  525. public function createFromClone(User $fuser, $socid)
  526. {
  527. global $db, $conf, $hookmanager;
  528. $error = 0;
  529. $now = dol_now();
  530. $this->db->begin();
  531. // Load source object
  532. $objFrom = clone $this;
  533. // Retreive all extrafield
  534. // fetch optionals attributes and labels
  535. $this->fetch_optionals();
  536. //$this->fetch_userassigned();
  537. $this->fetchResources();
  538. $this->id = 0;
  539. // Create clone
  540. $this->context['createfromclone'] = 'createfromclone';
  541. $result = $this->create($fuser);
  542. if ($result < 0) $error++;
  543. if (!$error)
  544. {
  545. // Hook of thirdparty module
  546. if (is_object($hookmanager))
  547. {
  548. $parameters = array('objFrom'=>$objFrom);
  549. $action = '';
  550. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  551. if ($reshook < 0) $error++;
  552. }
  553. // Call trigger
  554. $result = $this->call_trigger('ACTION_CLONE', $fuser);
  555. if ($result < 0) { $error++; }
  556. // End call triggers
  557. }
  558. unset($this->context['createfromclone']);
  559. // End
  560. if (!$error)
  561. {
  562. $this->db->commit();
  563. return $this->id;
  564. }
  565. else
  566. {
  567. $this->db->rollback();
  568. return -1;
  569. }
  570. }
  571. /**
  572. * Load object from database
  573. *
  574. * @param int $id Id of action to get
  575. * @param string $ref Ref of action to get
  576. * @param string $ref_ext Ref ext to get
  577. * @return int <0 if KO, >0 if OK
  578. */
  579. public function fetch($id, $ref = '', $ref_ext = '')
  580. {
  581. global $langs;
  582. $sql = "SELECT a.id,";
  583. $sql .= " a.id as ref,";
  584. $sql .= " a.entity,";
  585. $sql .= " a.ref_ext,";
  586. $sql .= " a.datep,";
  587. $sql .= " a.datep2,";
  588. $sql .= " a.durationp,"; // deprecated
  589. $sql .= " a.datec,";
  590. $sql .= " a.tms as datem,";
  591. $sql .= " a.code, a.label, a.note,";
  592. $sql .= " a.fk_soc,";
  593. $sql .= " a.fk_project,";
  594. $sql .= " a.fk_user_author, a.fk_user_mod,";
  595. $sql .= " a.fk_user_action, a.fk_user_done,";
  596. $sql .= " a.fk_contact, a.percent as percentage,";
  597. $sql .= " a.fk_element as elementid, a.elementtype,";
  598. $sql .= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
  599. $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,";
  600. $sql .= " s.nom as socname,";
  601. $sql .= " u.firstname, u.lastname as lastname";
  602. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
  603. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
  604. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
  605. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
  606. $sql .= " WHERE ";
  607. if ($ref) $sql .= " a.id=".$ref; // No field ref, we use id
  608. elseif ($ref_ext) $sql .= " a.ref_ext='".$this->db->escape($ref_ext)."'";
  609. else $sql .= " a.id=".$id;
  610. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  611. $resql = $this->db->query($sql);
  612. if ($resql)
  613. {
  614. $num = $this->db->num_rows($resql);
  615. if ($num)
  616. {
  617. $obj = $this->db->fetch_object($resql);
  618. $this->id = $obj->id;
  619. $this->entity = $obj->entity;
  620. $this->ref = $obj->ref;
  621. $this->ref_ext = $obj->ref_ext;
  622. // Properties of parent table llx_c_actioncomm
  623. $this->type_id = $obj->type_id;
  624. $this->type_code = $obj->type_code;
  625. $this->type_color = $obj->type_color;
  626. $this->type_picto = $obj->type_picto;
  627. $transcode = $langs->trans("Action".$obj->type_code);
  628. $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label);
  629. $transcode = $langs->trans("Action".$obj->type_code.'Short');
  630. $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : '');
  631. $this->code = $obj->code;
  632. $this->label = $obj->label;
  633. $this->datep = $this->db->jdate($obj->datep);
  634. $this->datef = $this->db->jdate($obj->datep2);
  635. $this->datec = $this->db->jdate($obj->datec);
  636. $this->datem = $this->db->jdate($obj->datem);
  637. $this->note = $obj->note; // deprecated
  638. $this->note_private = $obj->note;
  639. $this->percentage = $obj->percentage;
  640. $this->authorid = $obj->fk_user_author;
  641. $this->usermodid = $obj->fk_user_mod;
  642. if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
  643. $this->author->id = $obj->fk_user_author; // deprecated
  644. $this->author->firstname = $obj->firstname; // deprecated
  645. $this->author->lastname = $obj->lastname; // deprecated
  646. if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
  647. $this->usermod->id = $obj->fk_user_mod; // deprecated
  648. $this->userownerid = $obj->fk_user_action;
  649. $this->userdoneid = $obj->fk_user_done;
  650. $this->priority = $obj->priority;
  651. $this->fulldayevent = $obj->fulldayevent;
  652. $this->location = $obj->location;
  653. $this->transparency = $obj->transparency;
  654. $this->punctual = $obj->punctual; // deprecated
  655. $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
  656. $this->contactid = $obj->fk_contact; // To have fetch_contact method working
  657. $this->fk_project = $obj->fk_project; // To have fetch_projet method working
  658. //$this->societe->id = $obj->fk_soc; // deprecated
  659. //$this->contact->id = $obj->fk_contact; // deprecated
  660. $this->fk_element = $obj->elementid;
  661. $this->elementid = $obj->elementid;
  662. $this->elementtype = $obj->elementtype;
  663. $this->fetchResources();
  664. }
  665. $this->db->free($resql);
  666. }
  667. else
  668. {
  669. $this->error = $this->db->lasterror();
  670. return -1;
  671. }
  672. return $num;
  673. }
  674. /**
  675. * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event
  676. *
  677. * @return int <0 if KO, >0 if OK
  678. */
  679. public function fetchResources()
  680. {
  681. $this->userassigned = array();
  682. $this->socpeopleassigned = array();
  683. $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
  684. $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
  685. $sql .= ' WHERE fk_actioncomm = '.$this->id;
  686. $sql .= " AND element_type IN ('user', 'socpeople')";
  687. $resql = $this->db->query($sql);
  688. if ($resql)
  689. {
  690. // If owner is known, we must but id first into list
  691. if ($this->userownerid > 0) $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); // Set first so will be first into list.
  692. while ($obj = $this->db->fetch_object($resql))
  693. {
  694. if ($obj->fk_element > 0)
  695. {
  696. switch ($obj->element_type) {
  697. case 'user':
  698. $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
  699. if (empty($this->userownerid)) $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this)
  700. break;
  701. case 'socpeople':
  702. $this->socpeopleassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
  703. break;
  704. }
  705. }
  706. }
  707. return 1;
  708. }
  709. else
  710. {
  711. dol_print_error($this->db);
  712. return -1;
  713. }
  714. }
  715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  716. /**
  717. * Initialize this->userassigned array with list of id of user assigned to event
  718. *
  719. * @param bool $override Override $this->userownerid when empty. TODO This should be false by default. True is here to fix corrupted data.
  720. * @return int <0 if KO, >0 if OK
  721. */
  722. public function fetch_userassigned($override = true)
  723. {
  724. // phpcs:enable
  725. $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
  726. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources";
  727. $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
  728. $resql2 = $this->db->query($sql);
  729. if ($resql2)
  730. {
  731. $this->userassigned = array();
  732. // If owner is known, we must but id first into list
  733. if ($this->userownerid > 0)
  734. {
  735. // Set first so will be first into list.
  736. $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid);
  737. }
  738. while ($obj = $this->db->fetch_object($resql2))
  739. {
  740. if ($obj->fk_element > 0)
  741. {
  742. $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element,
  743. 'mandatory'=>$obj->mandatory,
  744. 'answer_status'=>$obj->answer_status,
  745. 'transparency'=>$obj->transparency);
  746. }
  747. if ($override === true)
  748. {
  749. // If not defined (should not happened, we fix this)
  750. if (empty($this->userownerid))
  751. {
  752. $this->userownerid = $obj->fk_element;
  753. }
  754. }
  755. }
  756. return 1;
  757. }
  758. else
  759. {
  760. dol_print_error($this->db);
  761. return -1;
  762. }
  763. }
  764. /**
  765. * Delete event from database
  766. *
  767. * @param int $notrigger 1 = disable triggers, 0 = enable triggers
  768. * @return int <0 if KO, >0 if OK
  769. */
  770. public function delete($notrigger = 0)
  771. {
  772. global $user;
  773. $error = 0;
  774. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  775. $this->db->begin();
  776. // remove categorie association
  777. if (!$error) {
  778. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_actioncomm";
  779. $sql .= " WHERE fk_actioncomm=".$this->id;
  780. $res = $this->db->query($sql);
  781. if (!$res) {
  782. $this->error = $this->db->lasterror();
  783. $error++;
  784. }
  785. }
  786. // remove actioncomm_resources
  787. if (!$error) {
  788. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
  789. $sql .= " WHERE fk_actioncomm=".$this->id;
  790. $res = $this->db->query($sql);
  791. if (!$res) {
  792. $this->error = $this->db->lasterror();
  793. $error++;
  794. }
  795. }
  796. // Removed extrafields
  797. if (!$error) {
  798. $result = $this->deleteExtraFields();
  799. if ($result < 0)
  800. {
  801. $error++;
  802. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  803. }
  804. }
  805. // remove actioncomm
  806. if (!$error) {
  807. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
  808. $sql .= " WHERE id=".$this->id;
  809. $res = $this->db->query($sql);
  810. if (!$res) {
  811. $this->error = $this->db->lasterror();
  812. $error++;
  813. }
  814. }
  815. if (!$error)
  816. {
  817. if (!$notrigger)
  818. {
  819. // Call trigger
  820. $result = $this->call_trigger('ACTION_DELETE', $user);
  821. if ($result < 0) { $error++; }
  822. // End call triggers
  823. }
  824. if (!$error)
  825. {
  826. $this->db->commit();
  827. return 1;
  828. }
  829. else
  830. {
  831. $this->db->rollback();
  832. return -2;
  833. }
  834. }
  835. else
  836. {
  837. $this->db->rollback();
  838. $this->error = $this->db->lasterror();
  839. return -1;
  840. }
  841. }
  842. /**
  843. * Update action into database
  844. * If percentage = 100, on met a jour date 100%
  845. *
  846. * @param User $user Object user making change
  847. * @param int $notrigger 1 = disable triggers, 0 = enable triggers
  848. * @return int <0 if KO, >0 if OK
  849. */
  850. public function update($user, $notrigger = 0)
  851. {
  852. global $langs, $conf, $hookmanager;
  853. $error = 0;
  854. // Clean parameters
  855. $this->label = trim($this->label);
  856. $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private));
  857. if (empty($this->percentage)) $this->percentage = 0;
  858. if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0;
  859. if (empty($this->transparency)) $this->transparency = 0;
  860. if (empty($this->fulldayevent)) $this->fulldayevent = 0;
  861. if ($this->percentage > 100) $this->percentage = 100;
  862. //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
  863. if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated
  864. //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date);
  865. if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep;
  866. //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
  867. if ($this->fk_project < 0) $this->fk_project = 0;
  868. // Check parameters
  869. if ($this->percentage == 0 && $this->userdoneid > 0)
  870. {
  871. $this->error = "ErrorCantSaveADoneUserWithZeroPercentage";
  872. return -1;
  873. }
  874. $socid = (($this->socid > 0) ? $this->socid : 0);
  875. $contactid = (($this->contactid > 0) ? $this->contactid : 0);
  876. $userownerid = ($this->userownerid ? $this->userownerid : 0);
  877. $userdoneid = ($this->userdoneid ? $this->userdoneid : 0);
  878. $this->db->begin();
  879. $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
  880. $sql .= " SET percent = '".$this->db->escape($this->percentage)."'";
  881. if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'";
  882. $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null");
  883. $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null');
  884. $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null');
  885. $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated
  886. $sql .= ", note = '".$this->db->escape($this->note_private)."'";
  887. $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null");
  888. $sql .= ", fk_soc =".($socid > 0 ? $socid : "null");
  889. $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null");
  890. $sql .= ", priority = '".$this->db->escape($this->priority)."'";
  891. $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'";
  892. $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null");
  893. $sql .= ", transparency = '".$this->db->escape($this->transparency)."'";
  894. $sql .= ", fk_user_mod = ".$user->id;
  895. $sql .= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'" : "null");
  896. $sql .= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'" : "null");
  897. if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null");
  898. if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null");
  899. $sql .= " WHERE id=".$this->id;
  900. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  901. if ($this->db->query($sql))
  902. {
  903. $action = 'update';
  904. // Actions on extra fields
  905. if (!$error)
  906. {
  907. $result = $this->insertExtraFields();
  908. if ($result < 0)
  909. {
  910. $error++;
  911. }
  912. }
  913. // Now insert assignedusers
  914. if (!$error)
  915. {
  916. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'";
  917. $resql = $this->db->query($sql);
  918. foreach ($this->userassigned as $key => $val)
  919. {
  920. if (!is_array($val)) // For backward compatibility when val=id
  921. {
  922. $val = array('id'=>$val);
  923. }
  924. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  925. $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")";
  926. $resql = $this->db->query($sql);
  927. if (!$resql)
  928. {
  929. $error++;
  930. $this->errors[] = $this->db->lasterror();
  931. }
  932. //var_dump($sql);exit;
  933. }
  934. }
  935. if (!$error)
  936. {
  937. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'";
  938. $resql = $this->db->query($sql);
  939. if (!empty($this->socpeopleassigned))
  940. {
  941. foreach (array_keys($this->socpeopleassigned) as $id)
  942. {
  943. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  944. $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
  945. $resql = $this->db->query($sql);
  946. if (!$resql)
  947. {
  948. $error++;
  949. $this->errors[] = $this->db->lasterror();
  950. }
  951. }
  952. }
  953. }
  954. if (!$error && !$notrigger)
  955. {
  956. // Call trigger
  957. $result = $this->call_trigger('ACTION_MODIFY', $user);
  958. if ($result < 0) { $error++; }
  959. // End call triggers
  960. }
  961. if (!$error)
  962. {
  963. $this->db->commit();
  964. return 1;
  965. }
  966. else
  967. {
  968. $this->db->rollback();
  969. dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR);
  970. return -2;
  971. }
  972. }
  973. else
  974. {
  975. $this->db->rollback();
  976. $this->error = $this->db->lasterror();
  977. return -1;
  978. }
  979. }
  980. /**
  981. * Load all objects with filters.
  982. * @todo WARNING: This make a fetch on all records instead of making one request with a join.
  983. *
  984. * @param DoliDb $db Database handler
  985. * @param int $socid Filter by thirdparty
  986. * @param int $fk_element Id of element action is linked to
  987. * @param string $elementtype Type of element action is linked to
  988. * @param string $filter Other filter
  989. * @param string $sortfield Sort on this field
  990. * @param string $sortorder ASC or DESC
  991. * @param string $limit Limit number of answers
  992. * @return array|string Error string if KO, array with actions if OK
  993. */
  994. public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
  995. {
  996. global $conf, $langs;
  997. $resarray = array();
  998. dol_syslog(get_class()."::getActions", LOG_DEBUG);
  999. $sql = "SELECT a.id";
  1000. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  1001. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  1002. if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid;
  1003. if (!empty($elementtype))
  1004. {
  1005. if ($elementtype == 'project') $sql .= ' AND a.fk_project = '.$fk_element;
  1006. else $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'";
  1007. }
  1008. if (!empty($filter)) $sql .= $filter;
  1009. if ($sortorder && $sortfield) $sql .= $db->order($sortfield, $sortorder);
  1010. $sql .= $db->plimit($limit, 0);
  1011. $resql = $db->query($sql);
  1012. if ($resql)
  1013. {
  1014. $num = $db->num_rows($resql);
  1015. if ($num)
  1016. {
  1017. for ($i = 0; $i < $num; $i++)
  1018. {
  1019. $obj = $db->fetch_object($resql);
  1020. $actioncommstatic = new ActionComm($db);
  1021. $actioncommstatic->fetch($obj->id);
  1022. $resarray[$i] = $actioncommstatic;
  1023. }
  1024. }
  1025. $db->free($resql);
  1026. return $resarray;
  1027. }
  1028. else
  1029. {
  1030. return $db->lasterror();
  1031. }
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1036. *
  1037. * @param User $user Objet user
  1038. * @param int $load_state_board Charge indicateurs this->nb de tableau de bord
  1039. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1040. */
  1041. public function load_board($user, $load_state_board = 0)
  1042. {
  1043. // phpcs:enable
  1044. global $conf, $langs;
  1045. if (empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp";
  1046. else {
  1047. $this->nb = array();
  1048. $sql = "SELECT count(a.id) as nb";
  1049. }
  1050. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  1051. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
  1052. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
  1053. $sql .= " WHERE 1 = 1";
  1054. if (empty($load_state_board)) $sql .= " AND a.percent >= 0 AND a.percent < 100";
  1055. $sql .= " AND a.entity IN (".getEntity('agenda').")";
  1056. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")";
  1057. if ($user->socid) $sql .= " AND a.fk_soc = ".$user->socid;
  1058. if (!$user->rights->agenda->allactions->read) $sql .= " AND (a.fk_user_author = ".$user->id." OR a.fk_user_action = ".$user->id." OR a.fk_user_done = ".$user->id.")";
  1059. $resql = $this->db->query($sql);
  1060. if ($resql)
  1061. {
  1062. if (empty($load_state_board)) {
  1063. $agenda_static = new ActionComm($this->db);
  1064. $response = new WorkboardResponse();
  1065. $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24;
  1066. $response->label = $langs->trans("ActionsToDo");
  1067. $response->labelShort = $langs->trans("ActionsToDoShort");
  1068. $response->url = DOL_URL_ROOT.'/comm/action/list.php?actioncode=0&amp;status=todo&amp;mainmenu=agenda';
  1069. if ($user->rights->agenda->allactions->read) $response->url .= '&amp;filtert=-1';
  1070. $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
  1071. }
  1072. // This assignment in condition is not a bug. It allows walking the results.
  1073. while ($obj = $this->db->fetch_object($resql))
  1074. {
  1075. if (empty($load_state_board)) {
  1076. $response->nbtodo++;
  1077. $agenda_static->datep = $this->db->jdate($obj->dp);
  1078. if ($agenda_static->hasDelay()) $response->nbtodolate++;
  1079. } else $this->nb["actionscomm"] = $obj->nb;
  1080. }
  1081. $this->db->free($resql);
  1082. if (empty($load_state_board)) return $response;
  1083. else return 1;
  1084. }
  1085. else
  1086. {
  1087. dol_print_error($this->db);
  1088. $this->error = $this->db->error();
  1089. return -1;
  1090. }
  1091. }
  1092. /**
  1093. * Charge les informations d'ordre info dans l'objet facture
  1094. *
  1095. * @param int $id Id de la facture a charger
  1096. * @return void
  1097. */
  1098. public function info($id)
  1099. {
  1100. $sql = 'SELECT ';
  1101. $sql .= ' a.id,';
  1102. $sql .= ' datec,';
  1103. $sql .= ' tms as datem,';
  1104. $sql .= ' fk_user_author,';
  1105. $sql .= ' fk_user_mod';
  1106. $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
  1107. $sql .= ' WHERE a.id = '.$id;
  1108. dol_syslog(get_class($this)."::info", LOG_DEBUG);
  1109. $result = $this->db->query($sql);
  1110. if ($result)
  1111. {
  1112. if ($this->db->num_rows($result))
  1113. {
  1114. $obj = $this->db->fetch_object($result);
  1115. $this->id = $obj->id;
  1116. if ($obj->fk_user_author)
  1117. {
  1118. $cuser = new User($this->db);
  1119. $cuser->fetch($obj->fk_user_author);
  1120. $this->user_creation = $cuser;
  1121. }
  1122. if ($obj->fk_user_mod)
  1123. {
  1124. $muser = new User($this->db);
  1125. $muser->fetch($obj->fk_user_mod);
  1126. $this->user_modification = $muser;
  1127. }
  1128. $this->date_creation = $this->db->jdate($obj->datec);
  1129. if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem);
  1130. }
  1131. $this->db->free($result);
  1132. }
  1133. else
  1134. {
  1135. dol_print_error($this->db);
  1136. }
  1137. }
  1138. /**
  1139. * Return label of status
  1140. *
  1141. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1142. * @param int $hidenastatus 1=Show nothing if status is "Not applicable"
  1143. * @return string String with status
  1144. */
  1145. public function getLibStatut($mode, $hidenastatus = 0)
  1146. {
  1147. return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
  1148. }
  1149. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1150. /**
  1151. * Return label of action status
  1152. *
  1153. * @param int $percent Percent
  1154. * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto
  1155. * @param int $hidenastatus 1=Show nothing if status is "Not applicable"
  1156. * @param int $datestart Date start of event
  1157. * @return string Label
  1158. */
  1159. public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
  1160. {
  1161. // phpcs:enable
  1162. global $langs;
  1163. $labelStatus = $langs->trans('StatusNotApplicable');
  1164. if ($percent == -1 && !$hidenastatus) $labelStatus = $langs->trans('StatusNotApplicable');
  1165. elseif ($percent == 0) $labelStatus = $langs->trans('StatusActionToDo').' (0%)';
  1166. elseif ($percent > 0 && $percent < 100) $labelStatus = $langs->trans('StatusActionInProcess').' ('.$percent.'%)';
  1167. elseif ($percent >= 100) $labelStatus = $langs->trans('StatusActionDone').' (100%)';
  1168. $labelStatusShort = $langs->trans('StatusNotApplicable');
  1169. if ($percent == -1 && !$hidenastatus) $labelStatusShort = $langs->trans('NA');
  1170. elseif ($percent == 0) $labelStatusShort = '0%';
  1171. elseif ($percent > 0 && $percent < 100) $labelStatusShort = $percent.'%';
  1172. elseif ($percent >= 100) $labelStatusShort = '100%';
  1173. $statusType = 'status9';
  1174. if ($percent == -1 && !$hidenastatus) $statusType = 'status9';
  1175. if ($percent == 0) $statusType = 'status1';
  1176. if ($percent > 0 && $percent < 100) $statusType = 'status3';
  1177. if ($percent >= 100) $statusType = 'status6';
  1178. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  1179. }
  1180. /**
  1181. * Return URL of event
  1182. * Use $this->id, $this->type_code, $this->label and $this->type_label
  1183. *
  1184. * @param int $withpicto 0 = No picto, 1 = Include picto into link, 2 = Only picto
  1185. * @param int $maxlength Max number of charaters into label. If negative, use the ref as label.
  1186. * @param string $classname Force style class on a link
  1187. * @param string $option '' = Link to action, 'birthday'= Link to contact, 'holiday' = Link to leave
  1188. * @param int $overwritepicto 1 = Overwrite picto
  1189. * @param int $notooltip 1 = Disable tooltip
  1190. * @param int $save_lastsearch_value -1 = Auto, 0 = No save of lastsearch_values when clicking, 1 = Save lastsearch_values whenclicking
  1191. * @return string Chaine avec URL
  1192. */
  1193. public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
  1194. {
  1195. global $conf, $langs, $user, $hookmanager, $action;
  1196. if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
  1197. $canread = 0;
  1198. if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1; // Can read my event
  1199. if ($user->rights->agenda->myactions->read && array_key_exists($user->id, $this->userassigned)) $canread = 1; // Can read my event i am assigned
  1200. if ($user->rights->agenda->allactions->read) $canread = 1; // Can read all event of other
  1201. if (!$canread)
  1202. {
  1203. $option = 'nolink';
  1204. }
  1205. $label = $this->label;
  1206. if (empty($label)) $label = $this->libelle; // For backward compatibility
  1207. $result = '';
  1208. // Set label of type
  1209. $labeltype = '';
  1210. if ($this->type_code)
  1211. {
  1212. $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label;
  1213. }
  1214. if (empty($conf->global->AGENDA_USE_EVENT_TYPE))
  1215. {
  1216. if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL');
  1217. }
  1218. $tooltip = '<u>'.$langs->trans('Action').'</u>';
  1219. if (!empty($this->ref))
  1220. $tooltip .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1221. if (!empty($label))
  1222. $tooltip .= '<br><b>'.$langs->trans('Title').':</b> '.$label;
  1223. if (!empty($labeltype))
  1224. $tooltip .= '<br><b>'.$langs->trans('Type').':</b> '.$labeltype;
  1225. if (!empty($this->location))
  1226. $tooltip .= '<br><b>'.$langs->trans('Location').':</b> '.$this->location;
  1227. if (!empty($this->note_private))
  1228. $tooltip .= '<br><b>'.$langs->trans('Note').':</b> '.(dol_textishtml($this->note_private) ? str_replace(array("\r", "\n"), "", $this->note_private) : str_replace(array("\r", "\n"), '<br>', $this->note_private));
  1229. $linkclose = '';
  1230. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color)
  1231. $linkclose = ' style="background-color:#'.$this->type_color.'"';
  1232. if (empty($notooltip))
  1233. {
  1234. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1235. {
  1236. $label = $langs->trans("ShowAction");
  1237. $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"';
  1238. }
  1239. $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"';
  1240. $linkclose .= ' class="'.$classname.' classfortooltip"';
  1241. /*
  1242. $hookmanager->initHooks(array('actiondao'));
  1243. $parameters=array('id'=>$this->id);
  1244. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1245. $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose);
  1246. */
  1247. }
  1248. else $linkclose .= ' class="'.$classname.'"';
  1249. $url = '';
  1250. if ($option == 'birthday')
  1251. $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id;
  1252. elseif ($option == 'holiday')
  1253. $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
  1254. else
  1255. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id;
  1256. if ($option !== 'nolink')
  1257. {
  1258. // Add param to save lastsearch_values or not
  1259. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1260. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  1261. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  1262. }
  1263. $linkstart = '<a href="'.$url.'"';
  1264. $linkstart .= $linkclose.'>';
  1265. $linkend = '</a>';
  1266. if ($option == 'nolink') {
  1267. $linkstart = '';
  1268. $linkend = '';
  1269. }
  1270. if ($withpicto == 2)
  1271. {
  1272. $libelle = $label;
  1273. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype;
  1274. $libelleshort = '';
  1275. }
  1276. else
  1277. {
  1278. $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : ''));
  1279. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype;
  1280. if ($maxlength < 0) $libelleshort = $this->ref;
  1281. else $libelleshort = dol_trunc($libelle, $maxlength);
  1282. }
  1283. if ($withpicto)
  1284. {
  1285. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into ()
  1286. {
  1287. if ($labeltype)
  1288. {
  1289. $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')');
  1290. }
  1291. }
  1292. }
  1293. $result .= $linkstart;
  1294. if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1295. $result .= $libelleshort;
  1296. $result .= $linkend;
  1297. global $action;
  1298. $hookmanager->initHooks(array('actiondao'));
  1299. $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
  1300. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1301. if ($reshook > 0) $result = $hookmanager->resPrint;
  1302. else $result .= $hookmanager->resPrint;
  1303. return $result;
  1304. }
  1305. /**
  1306. * Sets object to supplied categories.
  1307. *
  1308. * Deletes object from existing categories not supplied.
  1309. * Adds it to non existing supplied categories.
  1310. * Existing categories are left untouch.
  1311. *
  1312. * @param int[]|int $categories Category or categories IDs
  1313. * @return void
  1314. */
  1315. public function setCategories($categories)
  1316. {
  1317. // Handle single category
  1318. if (!is_array($categories)) {
  1319. $categories = array($categories);
  1320. }
  1321. // Get current categories
  1322. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1323. $c = new Categorie($this->db);
  1324. $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id');
  1325. // Diff
  1326. if (is_array($existing)) {
  1327. $to_del = array_diff($existing, $categories);
  1328. $to_add = array_diff($categories, $existing);
  1329. } else {
  1330. $to_del = array(); // Nothing to delete
  1331. $to_add = $categories;
  1332. }
  1333. // Process
  1334. foreach ($to_del as $del) {
  1335. if ($c->fetch($del) > 0) {
  1336. $c->del_type($this, Categorie::TYPE_ACTIONCOMM);
  1337. }
  1338. }
  1339. foreach ($to_add as $add) {
  1340. if ($c->fetch($add) > 0) {
  1341. $c->add_type($this, Categorie::TYPE_ACTIONCOMM);
  1342. }
  1343. }
  1344. return;
  1345. }
  1346. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1347. /**
  1348. * Export events from database into a cal file.
  1349. *
  1350. * @param string $format The format of the export 'vcal', 'ical/ics' or 'rss'
  1351. * @param string $type The type of the export 'event' or 'journal'
  1352. * @param integer $cachedelay Do not rebuild file if date older than cachedelay seconds
  1353. * @param string $filename The name for the exported file.
  1354. * @param array $filters Array of filters. Example array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...)
  1355. * @param integer $exportholiday 0 = don't integrate holidays into the export, 1 = integrate holidays into the export
  1356. * @return integer -1 = error on build export file, 0 = export okay
  1357. */
  1358. public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0)
  1359. {
  1360. global $hookmanager;
  1361. // phpcs:enable
  1362. global $conf, $langs, $dolibarr_main_url_root, $mysoc;
  1363. require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
  1364. require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
  1365. require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
  1366. dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
  1367. // Check parameters
  1368. if (empty($format)) return -1;
  1369. // Clean parameters
  1370. if (!$filename)
  1371. {
  1372. $extension = 'vcs';
  1373. if ($format == 'ical') $extension = 'ics';
  1374. $filename = $format.'.'.$extension;
  1375. }
  1376. // Create dir and define output file (definitive and temporary)
  1377. $result = dol_mkdir($conf->agenda->dir_temp);
  1378. $outputfile = $conf->agenda->dir_temp.'/'.$filename;
  1379. $result = 0;
  1380. $buildfile = true;
  1381. $login = ''; $logina = ''; $logind = ''; $logint = '';
  1382. $now = dol_now();
  1383. if ($cachedelay)
  1384. {
  1385. $nowgmt = dol_now();
  1386. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1387. if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay))
  1388. {
  1389. dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
  1390. $buildfile = false;
  1391. }
  1392. }
  1393. if ($buildfile)
  1394. {
  1395. // Build event array
  1396. $eventarray = array();
  1397. $sql = "SELECT a.id,";
  1398. $sql .= " a.datep,"; // Start
  1399. $sql .= " a.datep2,"; // End
  1400. $sql .= " a.durationp,"; // deprecated
  1401. $sql .= " a.datec, a.tms as datem,";
  1402. $sql .= " a.label, a.code, a.note, a.fk_action as type_id,";
  1403. $sql .= " a.fk_soc,";
  1404. $sql .= " a.fk_user_author, a.fk_user_mod,";
  1405. $sql .= " a.fk_user_action,";
  1406. $sql .= " a.fk_contact, a.percent as percentage,";
  1407. $sql .= " a.fk_element, a.elementtype,";
  1408. $sql .= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
  1409. $sql .= " u.firstname, u.lastname, u.email,";
  1410. $sql .= " s.nom as socname,";
  1411. $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label";
  1412. $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
  1413. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
  1414. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
  1415. $parameters = array('filters' => $filters);
  1416. $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
  1417. $sql .= $hookmanager->resPrint;
  1418. // We must filter on assignement table
  1419. if ($filters['logint']) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
  1420. $sql .= " WHERE a.fk_action=c.id";
  1421. $sql .= " AND a.entity IN (".getEntity('agenda').")";
  1422. foreach ($filters as $key => $value)
  1423. {
  1424. if ($key == 'notolderthan' && $value != '') $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
  1425. if ($key == 'year') $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
  1426. if ($key == 'id') $sql .= " AND a.id=".(is_numeric($value) ? $value : 0);
  1427. if ($key == 'idfrom') $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0);
  1428. if ($key == 'idto') $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0);
  1429. if ($key == 'project') $sql .= " AND a.fk_project=".(is_numeric($value) ? $value : 0);
  1430. if ($key == 'actiontype') $sql .= " AND c.type = '".$this->db->escape($value)."'";
  1431. if ($key == 'notactiontype') $sql .= " AND c.type <> '".$this->db->escape($value)."'";
  1432. // We must filter on assignement table
  1433. if ($key == 'logint') $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
  1434. if ($key == 'logina')
  1435. {
  1436. $logina = $value;
  1437. $condition = '=';
  1438. if (preg_match('/^!/', $logina))
  1439. {
  1440. $logina = preg_replace('/^!/', '', $logina);
  1441. $condition = '<>';
  1442. }
  1443. $userforfilter = new User($this->db);
  1444. $result = $userforfilter->fetch('', $logina);
  1445. if ($result > 0) $sql .= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
  1446. elseif ($result < 0 || $condition == '=') $sql .= " AND a.fk_user_author = 0";
  1447. }
  1448. if ($key == 'logint')
  1449. {
  1450. $logint = $value;
  1451. $condition = '=';
  1452. if (preg_match('/^!/', $logint))
  1453. {
  1454. $logint = preg_replace('/^!/', '', $logint);
  1455. $condition = '<>';
  1456. }
  1457. $userforfilter = new User($this->db);
  1458. $result = $userforfilter->fetch('', $logint);
  1459. if ($result > 0) $sql .= " AND ar.fk_element = ".$userforfilter->id;
  1460. elseif ($result < 0 || $condition == '=') $sql .= " AND ar.fk_element = 0";
  1461. }
  1462. }
  1463. $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
  1464. $parameters = array('filters' => $filters);
  1465. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1466. $sql .= $hookmanager->resPrint;
  1467. $sql .= " ORDER by datep";
  1468. //print $sql;exit;
  1469. dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG);
  1470. $resql = $this->db->query($sql);
  1471. if ($resql)
  1472. {
  1473. // Note: Output of sql request is encoded in $conf->file->character_set_client
  1474. // This assignment in condition is not a bug. It allows walking the results.
  1475. $diff = 0;
  1476. while ($obj = $this->db->fetch_object($resql))
  1477. {
  1478. $qualified = true;
  1479. // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
  1480. $event = array();
  1481. $event['uid'] = 'dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
  1482. $event['type'] = $type;
  1483. $datestart = $this->db->jdate($obj->datep) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
  1484. // fix for -> Warning: A non-numeric value encountered
  1485. if (is_numeric($this->db->jdate($obj->datep2)))
  1486. {
  1487. $dateend = $this->db->jdate($obj->datep2)
  1488. - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
  1489. }
  1490. else
  1491. {
  1492. // use start date as fall-back to avoid import erros on empty end date
  1493. $dateend = $datestart;
  1494. }
  1495. $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0;
  1496. $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : "");
  1497. $event['desc'] = $obj->note;
  1498. $event['startdate'] = $datestart;
  1499. $event['enddate'] = $dateend; // Not required with type 'journal'
  1500. $event['duration'] = $duration; // Not required with type 'journal'
  1501. $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
  1502. $event['priority'] = $obj->priority;
  1503. $event['fulldayevent'] = $obj->fulldayevent;
  1504. $event['location'] = $obj->location;
  1505. $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
  1506. $event['punctual'] = $obj->punctual;
  1507. $event['category'] = $obj->type_label;
  1508. $event['email'] = $obj->email;
  1509. // Define $urlwithroot
  1510. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1511. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1512. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1513. $url = $urlwithroot.'/comm/action/card.php?id='.$obj->id;
  1514. $event['url'] = $url;
  1515. $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
  1516. $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
  1517. // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
  1518. $this->id = $obj->id;
  1519. $this->fetch_userassigned(false);
  1520. $assignedUserArray = array();
  1521. foreach ($this->userassigned as $key => $value)
  1522. {
  1523. $assignedUser = new User($this->db);
  1524. $assignedUser->fetch($value['id']);
  1525. $assignedUserArray[$key] = $assignedUser;
  1526. }
  1527. $event['assignedUsers'] = $assignedUserArray;
  1528. if ($qualified && $datestart)
  1529. {
  1530. $eventarray[] = $event;
  1531. }
  1532. $diff++;
  1533. }
  1534. $parameters = array('filters' => $filters, 'eventarray' => &$eventarray);
  1535. $reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook
  1536. if ($reshook > 0)
  1537. {
  1538. $eventarray = $hookmanager->resArray;
  1539. }
  1540. }
  1541. else
  1542. {
  1543. $this->error = $this->db->lasterror();
  1544. return -1;
  1545. }
  1546. if ($exportholiday == 1)
  1547. {
  1548. $langs->load("holidays");
  1549. $title = $langs->trans("Holidays");
  1550. $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.email, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status";
  1551. $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
  1552. $sql .= " WHERE u.rowid = x.fk_user";
  1553. $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
  1554. $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
  1555. $resql = $this->db->query($sql);
  1556. if ($resql)
  1557. {
  1558. $num = $this->db->num_rows($resql);
  1559. $i = 0;
  1560. while ($i < $num)
  1561. {
  1562. $obj = $this->db->fetch_object($resql);
  1563. $event = array();
  1564. if ($obj->halfday == -1)
  1565. {
  1566. $event['fulldayevent'] = false;
  1567. $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
  1568. $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0);
  1569. }
  1570. elseif ($obj->halfday == 1)
  1571. {
  1572. $event['fulldayevent'] = false;
  1573. $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0);
  1574. $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
  1575. }
  1576. else
  1577. {
  1578. $event['fulldayevent'] = true;
  1579. $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
  1580. $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
  1581. }
  1582. if (!empty($conf->global->AGENDA_EXPORT_FIX_TZ))
  1583. {
  1584. $timestampStart = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600);
  1585. $timestampEnd = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600);
  1586. }
  1587. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1588. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  1589. $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid;
  1590. $event['uid'] = 'dolibarrholiday-'.$this->db->database_name.'-'.$obj->rowid."@".$_SERVER["SERVER_NAME"];
  1591. $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
  1592. $event['type'] = 'event';
  1593. $event['category'] = "Holiday";
  1594. $event['transparency'] = 'OPAQUE';
  1595. $event['email'] = $obj->email;
  1596. $event['created'] = $timestampStart;
  1597. $event['modified'] = $timestampStart;
  1598. $event['startdate'] = $timestampStart;
  1599. $event['enddate'] = $timestampEnd;
  1600. $event['duration'] = $timestampEnd - $timestampStart;
  1601. $event['url'] = $url;
  1602. if ($obj->status == 2)
  1603. {
  1604. // 2 = leave wait for approval
  1605. $event['summary'] = $title." - ".$obj->lastname." (wait for approval)";
  1606. }
  1607. else
  1608. {
  1609. // 3 = leave approved
  1610. $event['summary'] = $title." - ".$obj->lastname;
  1611. }
  1612. $eventarray[] = $event;
  1613. $i++;
  1614. }
  1615. }
  1616. }
  1617. $langs->load("agenda");
  1618. // Define title and desc
  1619. $more = '';
  1620. if ($login) $more = $langs->transnoentities("User").' '.$login;
  1621. if ($logina) $more = $langs->transnoentities("ActionsAskedBy").' '.$logina;
  1622. if ($logint) $more = $langs->transnoentities("ActionsToDoBy").' '.$logint;
  1623. if ($logind) $more = $langs->transnoentities("ActionsDoneBy").' '.$logind;
  1624. if ($more)
  1625. {
  1626. $title = 'Dolibarr actions '.$mysoc->name.' - '.$more;
  1627. $desc = $more;
  1628. $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
  1629. }
  1630. else
  1631. {
  1632. $title = 'Dolibarr actions '.$mysoc->name;
  1633. $desc = $langs->transnoentities('ListOfActions');
  1634. $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
  1635. }
  1636. // Create temp file
  1637. $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
  1638. @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
  1639. // Write file
  1640. if ($format == 'vcal') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1641. elseif ($format == 'ical') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1642. elseif ($format == 'rss') $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1643. if ($result >= 0)
  1644. {
  1645. if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1;
  1646. else
  1647. {
  1648. $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
  1649. dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
  1650. dol_delete_file($outputfiletmp, 0, 1);
  1651. $result = -1;
  1652. }
  1653. }
  1654. else
  1655. {
  1656. dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
  1657. dol_delete_file($outputfiletmp, 0, 1);
  1658. $langs->load("errors");
  1659. $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
  1660. }
  1661. }
  1662. return $result;
  1663. }
  1664. /**
  1665. * Initialise an instance with random values.
  1666. * Used to build previews or test instances.
  1667. * id must be 0 if object instance is a specimen.
  1668. *
  1669. * @return int >0 if ok
  1670. */
  1671. public function initAsSpecimen()
  1672. {
  1673. global $user;
  1674. $now = dol_now();
  1675. // Initialise parametres
  1676. $this->id = 0;
  1677. $this->specimen = 1;
  1678. $this->type_code = 'AC_OTH';
  1679. $this->code = 'AC_SPECIMEN_CODE';
  1680. $this->label = 'Label of event Specimen';
  1681. $this->datec = $now;
  1682. $this->datem = $now;
  1683. $this->datep = $now;
  1684. $this->datef = $now;
  1685. $this->author = $user;
  1686. $this->usermod = $user;
  1687. $this->usertodo = $user;
  1688. $this->fulldayevent = 0;
  1689. $this->punctual = 0;
  1690. $this->percentage = 0;
  1691. $this->location = 'Location';
  1692. $this->transparency = 1; // 1 means opaque
  1693. $this->priority = 1;
  1694. //$this->note_public = "This is a 'public' note.";
  1695. $this->note_private = "This is a 'private' note.";
  1696. $this->userownerid = $user->id;
  1697. $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1);
  1698. return 1;
  1699. }
  1700. /**
  1701. * Function used to replace a thirdparty id with another one.
  1702. *
  1703. * @param DoliDB $db Database handler
  1704. * @param int $origin_id Old thirdparty id
  1705. * @param int $dest_id New thirdparty id
  1706. * @return bool
  1707. */
  1708. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1709. {
  1710. $tables = array(
  1711. 'actioncomm'
  1712. );
  1713. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1714. }
  1715. /**
  1716. * Is the action delayed?
  1717. *
  1718. * @return bool
  1719. */
  1720. public function hasDelay()
  1721. {
  1722. global $conf;
  1723. $now = dol_now();
  1724. return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
  1725. }
  1726. /**
  1727. * Send reminders by emails
  1728. * CAN BE A CRON TASK
  1729. *
  1730. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1731. */
  1732. public function sendEmailsReminder()
  1733. {
  1734. global $conf, $langs;
  1735. $error = 0;
  1736. $this->output = '';
  1737. $this->error = '';
  1738. if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible.
  1739. {
  1740. $langs->load("agenda");
  1741. $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
  1742. return 0;
  1743. }
  1744. if (empty($conf->global->AGENDA_REMINDER_EMAIL))
  1745. {
  1746. $langs->load("agenda");
  1747. $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
  1748. return 0;
  1749. }
  1750. $now = dol_now();
  1751. dol_syslog(__METHOD__, LOG_DEBUG);
  1752. $this->db->begin();
  1753. // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done
  1754. // Delete also very old past events (we do not keep more than 1 month record in past)
  1755. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'";
  1756. $this->db->query($sql);
  1757. $this->db->commit();
  1758. return $error;
  1759. }
  1760. }