actioncomm.class.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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 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 = dol_htmlcleanlastbr(trim($this->note));
  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 .= "fk_soc,";
  383. $sql .= "fk_project,";
  384. $sql .= "note,";
  385. $sql .= "fk_contact,";
  386. $sql .= "fk_user_author,";
  387. $sql .= "fk_user_action,";
  388. $sql .= "fk_user_done,";
  389. $sql .= "label,percent,priority,fulldayevent,location,punctual,";
  390. $sql .= "transparency,";
  391. $sql .= "fk_element,";
  392. $sql .= "elementtype,";
  393. $sql .= "entity,";
  394. $sql .= "extraparams,";
  395. // Fields emails
  396. $sql .= "email_msgid,";
  397. $sql .= "email_from,";
  398. $sql .= "email_sender,";
  399. $sql .= "email_to,";
  400. $sql .= "email_tocc,";
  401. $sql .= "email_tobcc,";
  402. $sql .= "email_subject,";
  403. $sql .= "errors_to";
  404. $sql .= ") VALUES (";
  405. $sql .= "'".$this->db->idate($now)."', ";
  406. $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", ";
  407. $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", ";
  408. $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated
  409. $sql .= (isset($this->type_id) ? $this->type_id : "null").",";
  410. $sql .= ($code ? ("'".$code."'") : "null").", ";
  411. $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", ";
  412. $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", ";
  413. $sql .= " '".$this->db->escape($this->note_private ? $this->note_private : $this->note)."', ";
  414. $sql .= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid : "null").", ";
  415. $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", ";
  416. $sql .= ($userownerid > 0 ? $userownerid : "null").", ";
  417. $sql .= ($userdoneid > 0 ? $userdoneid : "null").", ";
  418. $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)."', ";
  419. $sql .= "'".$this->db->escape($this->transparency)."', ";
  420. $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", ";
  421. $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", ";
  422. $sql .= $conf->entity.",";
  423. $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", ";
  424. // Fields emails
  425. $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", ";
  426. $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", ";
  427. $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", ";
  428. $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", ";
  429. $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", ";
  430. $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", ";
  431. $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", ";
  432. $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null");
  433. $sql .= ")";
  434. dol_syslog(get_class($this)."::add", LOG_DEBUG);
  435. $resql = $this->db->query($sql);
  436. if ($resql)
  437. {
  438. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
  439. // Now insert assigned users
  440. if (!$error)
  441. {
  442. //dol_syslog(var_export($this->userassigned, true));
  443. foreach ($this->userassigned as $key => $val)
  444. {
  445. if (!is_array($val)) // For backward compatibility when val=id
  446. {
  447. $val = array('id'=>$val);
  448. }
  449. if ($val['id'] > 0)
  450. {
  451. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  452. $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']).")";
  453. $resql = $this->db->query($sql);
  454. if (!$resql)
  455. {
  456. $error++;
  457. dol_syslog('Error to process userassigned: '.$this->db->lasterror(), LOG_ERR);
  458. $this->errors[] = $this->db->lasterror();
  459. }
  460. //var_dump($sql);exit;
  461. }
  462. }
  463. }
  464. if (!$error)
  465. {
  466. if (!empty($this->socpeopleassigned))
  467. {
  468. foreach ($this->socpeopleassigned as $id => $val)
  469. {
  470. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  471. $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
  472. $resql = $this->db->query($sql);
  473. if (!$resql)
  474. {
  475. $error++;
  476. dol_syslog('Error to process socpeopleassigned: '.$this->db->lasterror(), LOG_ERR);
  477. $this->errors[] = $this->db->lasterror();
  478. }
  479. }
  480. }
  481. }
  482. if (!$error)
  483. {
  484. // Actions on extra fields
  485. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  486. {
  487. $result = $this->insertExtraFields();
  488. if ($result < 0)
  489. {
  490. $error++;
  491. }
  492. }
  493. }
  494. if (!$error && !$notrigger)
  495. {
  496. // Call trigger
  497. $result = $this->call_trigger('ACTION_CREATE', $user);
  498. if ($result < 0) { $error++; }
  499. // End call triggers
  500. }
  501. if (!$error)
  502. {
  503. $this->db->commit();
  504. return $this->id;
  505. }
  506. else
  507. {
  508. $this->db->rollback();
  509. return -1;
  510. }
  511. }
  512. else
  513. {
  514. $this->db->rollback();
  515. $this->error = $this->db->lasterror();
  516. return -1;
  517. }
  518. }
  519. /**
  520. * Load an object from its id and create a new one in database
  521. *
  522. * @param User $fuser Object user making action
  523. * @param int $socid Id of thirdparty
  524. * @return int New id of clone
  525. */
  526. public function createFromClone(User $fuser, $socid)
  527. {
  528. global $db, $conf, $hookmanager;
  529. $error = 0;
  530. $now = dol_now();
  531. $this->db->begin();
  532. // Load source object
  533. $objFrom = clone $this;
  534. // Retreive all extrafield
  535. // fetch optionals attributes and labels
  536. $this->fetch_optionals();
  537. //$this->fetch_userassigned();
  538. $this->fetchResources();
  539. $this->id = 0;
  540. // Create clone
  541. $this->context['createfromclone'] = 'createfromclone';
  542. $result = $this->create($fuser);
  543. if ($result < 0) $error++;
  544. if (!$error)
  545. {
  546. // Hook of thirdparty module
  547. if (is_object($hookmanager))
  548. {
  549. $parameters = array('objFrom'=>$objFrom);
  550. $action = '';
  551. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  552. if ($reshook < 0) $error++;
  553. }
  554. // Call trigger
  555. $result = $this->call_trigger('ACTION_CLONE', $fuser);
  556. if ($result < 0) { $error++; }
  557. // End call triggers
  558. }
  559. unset($this->context['createfromclone']);
  560. // End
  561. if (!$error)
  562. {
  563. $this->db->commit();
  564. return $this->id;
  565. }
  566. else
  567. {
  568. $this->db->rollback();
  569. return -1;
  570. }
  571. }
  572. /**
  573. * Load object from database
  574. *
  575. * @param int $id Id of action to get
  576. * @param string $ref Ref of action to get
  577. * @param string $ref_ext Ref ext to get
  578. * @return int <0 if KO, >0 if OK
  579. */
  580. public function fetch($id, $ref = '', $ref_ext = '')
  581. {
  582. global $langs;
  583. $sql = "SELECT a.id,";
  584. $sql .= " a.id as ref,";
  585. $sql .= " a.entity,";
  586. $sql .= " a.ref_ext,";
  587. $sql .= " a.datep,";
  588. $sql .= " a.datep2,";
  589. $sql .= " a.durationp,"; // deprecated
  590. $sql .= " a.datec,";
  591. $sql .= " a.tms as datem,";
  592. $sql .= " a.code, a.label, a.note,";
  593. $sql .= " a.fk_soc,";
  594. $sql .= " a.fk_project,";
  595. $sql .= " a.fk_user_author, a.fk_user_mod,";
  596. $sql .= " a.fk_user_action, a.fk_user_done,";
  597. $sql .= " a.fk_contact, a.percent as percentage,";
  598. $sql .= " a.fk_element as elementid, a.elementtype,";
  599. $sql .= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
  600. $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,";
  601. $sql .= " s.nom as socname,";
  602. $sql .= " u.firstname, u.lastname as lastname";
  603. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
  604. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
  605. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
  606. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
  607. $sql .= " WHERE ";
  608. if ($ref) $sql .= " a.id=".$ref; // No field ref, we use id
  609. elseif ($ref_ext) $sql .= " a.ref_ext='".$this->db->escape($ref_ext)."'";
  610. else $sql .= " a.id=".$id;
  611. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  612. $resql = $this->db->query($sql);
  613. if ($resql)
  614. {
  615. $num = $this->db->num_rows($resql);
  616. if ($num)
  617. {
  618. $obj = $this->db->fetch_object($resql);
  619. $this->id = $obj->id;
  620. $this->entity = $obj->entity;
  621. $this->ref = $obj->ref;
  622. $this->ref_ext = $obj->ref_ext;
  623. // Properties of parent table llx_c_actioncomm
  624. $this->type_id = $obj->type_id;
  625. $this->type_code = $obj->type_code;
  626. $this->type_color = $obj->type_color;
  627. $this->type_picto = $obj->type_picto;
  628. $transcode = $langs->trans("Action".$obj->type_code);
  629. $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label);
  630. $transcode = $langs->trans("Action".$obj->type_code.'Short');
  631. $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : '');
  632. $this->code = $obj->code;
  633. $this->label = $obj->label;
  634. $this->datep = $this->db->jdate($obj->datep);
  635. $this->datef = $this->db->jdate($obj->datep2);
  636. $this->datec = $this->db->jdate($obj->datec);
  637. $this->datem = $this->db->jdate($obj->datem);
  638. $this->note = $obj->note;
  639. $this->note_private = $obj->note;
  640. $this->percentage = $obj->percentage;
  641. $this->authorid = $obj->fk_user_author;
  642. $this->usermodid = $obj->fk_user_mod;
  643. if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
  644. $this->author->id = $obj->fk_user_author; // deprecated
  645. $this->author->firstname = $obj->firstname; // deprecated
  646. $this->author->lastname = $obj->lastname; // deprecated
  647. if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
  648. $this->usermod->id = $obj->fk_user_mod; // deprecated
  649. $this->userownerid = $obj->fk_user_action;
  650. $this->userdoneid = $obj->fk_user_done;
  651. $this->priority = $obj->priority;
  652. $this->fulldayevent = $obj->fulldayevent;
  653. $this->location = $obj->location;
  654. $this->transparency = $obj->transparency;
  655. $this->punctual = $obj->punctual; // deprecated
  656. $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
  657. $this->contactid = $obj->fk_contact; // To have fetch_contact method working
  658. $this->fk_project = $obj->fk_project; // To have fetch_projet method working
  659. //$this->societe->id = $obj->fk_soc; // deprecated
  660. //$this->contact->id = $obj->fk_contact; // deprecated
  661. $this->fk_element = $obj->elementid;
  662. $this->elementid = $obj->elementid;
  663. $this->elementtype = $obj->elementtype;
  664. $this->fetchResources();
  665. }
  666. $this->db->free($resql);
  667. }
  668. else
  669. {
  670. $this->error = $this->db->lasterror();
  671. return -1;
  672. }
  673. return $num;
  674. }
  675. /**
  676. * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event
  677. *
  678. * @return int <0 if KO, >0 if OK
  679. */
  680. public function fetchResources()
  681. {
  682. $this->userassigned = array();
  683. $this->socpeopleassigned = array();
  684. $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
  685. $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
  686. $sql .= ' WHERE fk_actioncomm = '.$this->id;
  687. $sql .= " AND element_type IN ('user', 'socpeople')";
  688. $resql = $this->db->query($sql);
  689. if ($resql)
  690. {
  691. // If owner is known, we must but id first into list
  692. if ($this->userownerid > 0) $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); // Set first so will be first into list.
  693. while ($obj = $this->db->fetch_object($resql))
  694. {
  695. if ($obj->fk_element > 0)
  696. {
  697. switch ($obj->element_type) {
  698. case 'user':
  699. $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
  700. if (empty($this->userownerid)) $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this)
  701. break;
  702. case 'socpeople':
  703. $this->socpeopleassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
  704. break;
  705. }
  706. }
  707. }
  708. return 1;
  709. }
  710. else
  711. {
  712. dol_print_error($this->db);
  713. return -1;
  714. }
  715. }
  716. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  717. /**
  718. * Initialize this->userassigned array with list of id of user assigned to event
  719. *
  720. * @param bool $override Override $this->userownerid when empty. TODO This should be false by default. True is here to fix corrupted data.
  721. * @return int <0 if KO, >0 if OK
  722. */
  723. public function fetch_userassigned($override = true)
  724. {
  725. // phpcs:enable
  726. $sql ="SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
  727. $sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources";
  728. $sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
  729. $resql2=$this->db->query($sql);
  730. if ($resql2)
  731. {
  732. $this->userassigned = array();
  733. // If owner is known, we must but id first into list
  734. if ($this->userownerid > 0)
  735. {
  736. // Set first so will be first into list.
  737. $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid);
  738. }
  739. while ($obj = $this->db->fetch_object($resql2))
  740. {
  741. if ($obj->fk_element > 0)
  742. {
  743. $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element,
  744. 'mandatory'=>$obj->mandatory,
  745. 'answer_status'=>$obj->answer_status,
  746. 'transparency'=>$obj->transparency);
  747. }
  748. if ($override === true)
  749. {
  750. // If not defined (should not happened, we fix this)
  751. if (empty($this->userownerid))
  752. {
  753. $this->userownerid = $obj->fk_element;
  754. }
  755. }
  756. }
  757. return 1;
  758. }
  759. else
  760. {
  761. dol_print_error($this->db);
  762. return -1;
  763. }
  764. }
  765. /**
  766. * Delete event from database
  767. *
  768. * @param int $notrigger 1 = disable triggers, 0 = enable triggers
  769. * @return int <0 if KO, >0 if OK
  770. */
  771. public function delete($notrigger = 0)
  772. {
  773. global $user;
  774. $error=0;
  775. $this->db->begin();
  776. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
  777. $sql.= " WHERE id=".$this->id;
  778. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  779. $res=$this->db->query($sql);
  780. if (!$res) {
  781. $this->error=$this->db->lasterror();
  782. $error++;
  783. }
  784. if (! $error) {
  785. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
  786. $sql.= " WHERE fk_actioncomm=".$this->id;
  787. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  788. $res=$this->db->query($sql);
  789. if (!$res) {
  790. $this->error=$this->db->lasterror();
  791. $error++;
  792. }
  793. }
  794. // Removed extrafields
  795. if (! $error) {
  796. $result=$this->deleteExtraFields();
  797. if ($result < 0)
  798. {
  799. $error++;
  800. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  801. }
  802. }
  803. if (!$error)
  804. {
  805. if (!$notrigger)
  806. {
  807. // Call trigger
  808. $result = $this->call_trigger('ACTION_DELETE', $user);
  809. if ($result < 0) { $error++; }
  810. // End call triggers
  811. }
  812. if (!$error)
  813. {
  814. $this->db->commit();
  815. return 1;
  816. }
  817. else
  818. {
  819. $this->db->rollback();
  820. return -2;
  821. }
  822. }
  823. else
  824. {
  825. $this->db->rollback();
  826. $this->error = $this->db->lasterror();
  827. return -1;
  828. }
  829. }
  830. /**
  831. * Update action into database
  832. * If percentage = 100, on met a jour date 100%
  833. *
  834. * @param User $user Object user making change
  835. * @param int $notrigger 1 = disable triggers, 0 = enable triggers
  836. * @return int <0 if KO, >0 if OK
  837. */
  838. public function update($user, $notrigger = 0)
  839. {
  840. global $langs, $conf, $hookmanager;
  841. $error = 0;
  842. // Clean parameters
  843. $this->label = trim($this->label);
  844. $this->note = trim($this->note);
  845. if (empty($this->percentage)) $this->percentage = 0;
  846. if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0;
  847. if (empty($this->transparency)) $this->transparency = 0;
  848. if (empty($this->fulldayevent)) $this->fulldayevent = 0;
  849. if ($this->percentage > 100) $this->percentage = 100;
  850. //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
  851. if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated
  852. //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date);
  853. if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep;
  854. //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
  855. if ($this->fk_project < 0) $this->fk_project = 0;
  856. // Check parameters
  857. if ($this->percentage == 0 && $this->userdoneid > 0)
  858. {
  859. $this->error = "ErrorCantSaveADoneUserWithZeroPercentage";
  860. return -1;
  861. }
  862. $socid = (($this->socid > 0) ? $this->socid : 0);
  863. $contactid = (($this->contactid > 0) ? $this->contactid : 0);
  864. $userownerid = ($this->userownerid ? $this->userownerid : 0);
  865. $userdoneid = ($this->userdoneid ? $this->userdoneid : 0);
  866. $this->db->begin();
  867. $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
  868. $sql .= " SET percent = '".$this->db->escape($this->percentage)."'";
  869. if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'";
  870. $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null");
  871. $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null');
  872. $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null');
  873. $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated
  874. $sql .= ", note = '".$this->db->escape($this->note_private ? $this->note_private : $this->note)."'";
  875. $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null");
  876. $sql .= ", fk_soc =".($socid > 0 ? $socid : "null");
  877. $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null");
  878. $sql .= ", priority = '".$this->db->escape($this->priority)."'";
  879. $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'";
  880. $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null");
  881. $sql .= ", transparency = '".$this->db->escape($this->transparency)."'";
  882. $sql .= ", fk_user_mod = ".$user->id;
  883. $sql .= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'" : "null");
  884. $sql .= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'" : "null");
  885. if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null");
  886. if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null");
  887. $sql .= " WHERE id=".$this->id;
  888. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  889. if ($this->db->query($sql))
  890. {
  891. $action = 'update';
  892. // Actions on extra fields
  893. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  894. {
  895. $result = $this->insertExtraFields();
  896. if ($result < 0)
  897. {
  898. $error++;
  899. }
  900. }
  901. // Now insert assignedusers
  902. if (!$error)
  903. {
  904. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'";
  905. $resql = $this->db->query($sql);
  906. foreach ($this->userassigned as $key => $val)
  907. {
  908. if (!is_array($val)) // For backward compatibility when val=id
  909. {
  910. $val = array('id'=>$val);
  911. }
  912. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  913. $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']).")";
  914. $resql = $this->db->query($sql);
  915. if (!$resql)
  916. {
  917. $error++;
  918. $this->errors[] = $this->db->lasterror();
  919. }
  920. //var_dump($sql);exit;
  921. }
  922. }
  923. if (!$error)
  924. {
  925. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'";
  926. $resql = $this->db->query($sql);
  927. if (!empty($this->socpeopleassigned))
  928. {
  929. foreach (array_keys($this->socpeopleassigned) as $id)
  930. {
  931. $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
  932. $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
  933. $resql = $this->db->query($sql);
  934. if (!$resql)
  935. {
  936. $error++;
  937. $this->errors[] = $this->db->lasterror();
  938. }
  939. }
  940. }
  941. }
  942. if (!$error && !$notrigger)
  943. {
  944. // Call trigger
  945. $result = $this->call_trigger('ACTION_MODIFY', $user);
  946. if ($result < 0) { $error++; }
  947. // End call triggers
  948. }
  949. if (!$error)
  950. {
  951. $this->db->commit();
  952. return 1;
  953. }
  954. else
  955. {
  956. $this->db->rollback();
  957. dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR);
  958. return -2;
  959. }
  960. }
  961. else
  962. {
  963. $this->db->rollback();
  964. $this->error = $this->db->lasterror();
  965. return -1;
  966. }
  967. }
  968. /**
  969. * Load all objects with filters.
  970. * @todo WARNING: This make a fetch on all records instead of making one request with a join.
  971. *
  972. * @param DoliDb $db Database handler
  973. * @param int $socid Filter by thirdparty
  974. * @param int $fk_element Id of element action is linked to
  975. * @param string $elementtype Type of element action is linked to
  976. * @param string $filter Other filter
  977. * @param string $sortfield Sort on this field
  978. * @param string $sortorder ASC or DESC
  979. * @param string $limit Limit number of answers
  980. * @return array|string Error string if KO, array with actions if OK
  981. */
  982. public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
  983. {
  984. global $conf, $langs;
  985. $resarray = array();
  986. dol_syslog(get_class()."::getActions", LOG_DEBUG);
  987. $sql = "SELECT a.id";
  988. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  989. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  990. if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid;
  991. if (!empty($elementtype))
  992. {
  993. if ($elementtype == 'project') $sql .= ' AND a.fk_project = '.$fk_element;
  994. else $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'";
  995. }
  996. if (!empty($filter)) $sql .= $filter;
  997. if ($sortorder && $sortfield) $sql .= $db->order($sortfield, $sortorder);
  998. $sql .= $db->plimit($limit, 0);
  999. $resql = $db->query($sql);
  1000. if ($resql)
  1001. {
  1002. $num = $db->num_rows($resql);
  1003. if ($num)
  1004. {
  1005. for ($i = 0; $i < $num; $i++)
  1006. {
  1007. $obj = $db->fetch_object($resql);
  1008. $actioncommstatic = new ActionComm($db);
  1009. $actioncommstatic->fetch($obj->id);
  1010. $resarray[$i] = $actioncommstatic;
  1011. }
  1012. }
  1013. $db->free($resql);
  1014. return $resarray;
  1015. }
  1016. else
  1017. {
  1018. return $db->lasterror();
  1019. }
  1020. }
  1021. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1022. /**
  1023. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1024. *
  1025. * @param User $user Objet user
  1026. * @param int $load_state_board Charge indicateurs this->nb de tableau de bord
  1027. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1028. */
  1029. public function load_board($user, $load_state_board = 0)
  1030. {
  1031. // phpcs:enable
  1032. global $conf, $langs;
  1033. if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp";
  1034. else {
  1035. $this->nb=array();
  1036. $sql = "SELECT count(a.id) as nb";
  1037. }
  1038. $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  1039. 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";
  1040. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
  1041. $sql.= " WHERE 1 = 1";
  1042. if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100";
  1043. $sql.= " AND a.entity IN (".getEntity('agenda').")";
  1044. if (! $user->rights->societe->client->voir && ! $user->socid) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")";
  1045. if ($user->socid) $sql.=" AND a.fk_soc = ".$user->socid;
  1046. 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 . ")";
  1047. $resql=$this->db->query($sql);
  1048. if ($resql)
  1049. {
  1050. if(empty($load_state_board)) {
  1051. $agenda_static = new ActionComm($this->db);
  1052. $response = new WorkboardResponse();
  1053. $response->warning_delay = $conf->agenda->warning_delay/60/60/24;
  1054. $response->label = $langs->trans("ActionsToDo");
  1055. $response->labelShort = $langs->trans("ActionsToDoShort");
  1056. $response->url = DOL_URL_ROOT.'/comm/action/list.php?actioncode=0&amp;status=todo&amp;mainmenu=agenda';
  1057. if ($user->rights->agenda->allactions->read) $response->url.='&amp;filtert=-1';
  1058. $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
  1059. }
  1060. // This assignment in condition is not a bug. It allows walking the results.
  1061. while ($obj=$this->db->fetch_object($resql))
  1062. {
  1063. if(empty($load_state_board)) {
  1064. $response->nbtodo++;
  1065. $agenda_static->datep = $this->db->jdate($obj->dp);
  1066. if ($agenda_static->hasDelay()) $response->nbtodolate++;
  1067. } else $this->nb["actionscomm"]=$obj->nb;
  1068. }
  1069. $this->db->free($resql);
  1070. if(empty($load_state_board)) return $response;
  1071. else return 1;
  1072. }
  1073. else
  1074. {
  1075. dol_print_error($this->db);
  1076. $this->error=$this->db->error();
  1077. return -1;
  1078. }
  1079. }
  1080. /**
  1081. * Charge les informations d'ordre info dans l'objet facture
  1082. *
  1083. * @param int $id Id de la facture a charger
  1084. * @return void
  1085. */
  1086. public function info($id)
  1087. {
  1088. $sql = 'SELECT ';
  1089. $sql .= ' a.id,';
  1090. $sql .= ' datec,';
  1091. $sql .= ' tms as datem,';
  1092. $sql .= ' fk_user_author,';
  1093. $sql .= ' fk_user_mod';
  1094. $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
  1095. $sql .= ' WHERE a.id = '.$id;
  1096. dol_syslog(get_class($this)."::info", LOG_DEBUG);
  1097. $result = $this->db->query($sql);
  1098. if ($result)
  1099. {
  1100. if ($this->db->num_rows($result))
  1101. {
  1102. $obj = $this->db->fetch_object($result);
  1103. $this->id = $obj->id;
  1104. if ($obj->fk_user_author)
  1105. {
  1106. $cuser = new User($this->db);
  1107. $cuser->fetch($obj->fk_user_author);
  1108. $this->user_creation = $cuser;
  1109. }
  1110. if ($obj->fk_user_mod)
  1111. {
  1112. $muser = new User($this->db);
  1113. $muser->fetch($obj->fk_user_mod);
  1114. $this->user_modification = $muser;
  1115. }
  1116. $this->date_creation = $this->db->jdate($obj->datec);
  1117. if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem);
  1118. }
  1119. $this->db->free($result);
  1120. }
  1121. else
  1122. {
  1123. dol_print_error($this->db);
  1124. }
  1125. }
  1126. /**
  1127. * Return label of status
  1128. *
  1129. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1130. * @param int $hidenastatus 1=Show nothing if status is "Not applicable"
  1131. * @return string String with status
  1132. */
  1133. public function getLibStatut($mode, $hidenastatus = 0)
  1134. {
  1135. return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Return label of action status
  1140. *
  1141. * @param int $percent Percent
  1142. * @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
  1143. * @param int $hidenastatus 1=Show nothing if status is "Not applicable"
  1144. * @param int $datestart Date start of event
  1145. * @return string Label
  1146. */
  1147. public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
  1148. {
  1149. // phpcs:enable
  1150. global $langs;
  1151. if ($mode == 0)
  1152. {
  1153. if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable');
  1154. elseif ($percent == 0) return $langs->trans('StatusActionToDo').' (0%)';
  1155. elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%)';
  1156. elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%)';
  1157. }
  1158. elseif ($mode == 1)
  1159. {
  1160. if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable');
  1161. elseif ($percent == 0) return $langs->trans('StatusActionToDo');
  1162. elseif ($percent > 0 && $percent < 100) return $percent.'%';
  1163. elseif ($percent >= 100) return $langs->trans('StatusActionDone');
  1164. }
  1165. elseif ($mode == 2)
  1166. {
  1167. if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
  1168. elseif ($percent == 0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo');
  1169. elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '.$percent.'%';
  1170. elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone');
  1171. }
  1172. elseif ($mode == 3)
  1173. {
  1174. if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans("Status").': '.$langs->trans('StatusNotApplicable'), 'statut9');
  1175. elseif ($percent == 0) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionToDo').' (0%)', 'statut1');
  1176. elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)', 'statut3');
  1177. elseif ($percent >= 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionDone').' (100%)', 'statut6');
  1178. }
  1179. elseif ($mode == 4)
  1180. {
  1181. if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
  1182. elseif ($percent == 0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo').' (0%)';
  1183. elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)';
  1184. elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone').' (100%)';
  1185. }
  1186. elseif ($mode == 5)
  1187. {
  1188. if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
  1189. elseif ($percent == 0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
  1190. elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
  1191. elseif ($percent >= 100) return $langs->trans('StatusActionDone').' '.img_picto($langs->trans('StatusActionDone'), 'statut6');
  1192. }
  1193. elseif ($mode == 6)
  1194. {
  1195. if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
  1196. elseif ($percent == 0) return $langs->trans('StatusActionToDo').' (0%) '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
  1197. elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%) '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
  1198. elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%) '.img_picto($langs->trans('StatusActionDone'), 'statut6');
  1199. }
  1200. elseif ($mode == 7)
  1201. {
  1202. if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
  1203. elseif ($percent == 0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
  1204. elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
  1205. elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6');
  1206. }
  1207. return '';
  1208. }
  1209. /**
  1210. * Return URL of event
  1211. * Use $this->id, $this->type_code, $this->label and $this->type_label
  1212. *
  1213. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1214. * @param int $maxlength Max number of charaters into label. If negative, use the ref as label.
  1215. * @param string $classname Force style class on a link
  1216. * @param string $option ''=Link to action, 'birthday'=Link to contact
  1217. * @param int $overwritepicto 1=Overwrite picto
  1218. * @param int $notooltip 1=Disable tooltip
  1219. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1220. * @return string Chaine avec URL
  1221. */
  1222. public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
  1223. {
  1224. global $conf, $langs, $user, $hookmanager, $action;
  1225. if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
  1226. $canread = 0;
  1227. if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1; // Can read my event
  1228. if ($user->rights->agenda->myactions->read && array_key_exists($user->id, $this->userassigned)) $canread = 1; // Can read my event i am assigned
  1229. if ($user->rights->agenda->allactions->read) $canread = 1; // Can read all event of other
  1230. if (! $canread)
  1231. {
  1232. $option = 'nolink';
  1233. }
  1234. $label = $this->label;
  1235. if (empty($label)) $label = $this->libelle; // For backward compatibility
  1236. $result = '';
  1237. // Set label of type
  1238. $labeltype = '';
  1239. if ($this->type_code)
  1240. {
  1241. $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label;
  1242. }
  1243. if (empty($conf->global->AGENDA_USE_EVENT_TYPE))
  1244. {
  1245. if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL');
  1246. }
  1247. $tooltip = '<u>'.$langs->trans('ShowAction').'</u>';
  1248. if (!empty($this->ref))
  1249. $tooltip .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1250. if (!empty($label))
  1251. $tooltip .= '<br><b>'.$langs->trans('Title').':</b> '.$label;
  1252. if (!empty($labeltype))
  1253. $tooltip .= '<br><b>'.$langs->trans('Type').':</b> '.$labeltype;
  1254. if (!empty($this->location))
  1255. $tooltip .= '<br><b>'.$langs->trans('Location').':</b> '.$this->location;
  1256. if (!empty($this->note))
  1257. $tooltip .= '<br><b>'.$langs->trans('Note').':</b> '.(dol_textishtml($this->note) ? str_replace(array("\r", "\n"), "", $this->note) : str_replace(array("\r", "\n"), '<br>', $this->note));
  1258. $linkclose = '';
  1259. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color)
  1260. $linkclose = ' style="background-color:#'.$this->type_color.'"';
  1261. if (empty($notooltip))
  1262. {
  1263. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1264. {
  1265. $label = $langs->trans("ShowAction");
  1266. $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"';
  1267. }
  1268. $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"';
  1269. $linkclose .= ' class="'.$classname.' classfortooltip"';
  1270. /*
  1271. $hookmanager->initHooks(array('actiondao'));
  1272. $parameters=array('id'=>$this->id);
  1273. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1274. $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose);
  1275. */
  1276. }
  1277. else $linkclose .= ' class="'.$classname.'"';
  1278. $url = '';
  1279. if ($option == 'birthday')
  1280. $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id;
  1281. else
  1282. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id;
  1283. if ($option !== 'nolink')
  1284. {
  1285. // Add param to save lastsearch_values or not
  1286. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1287. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  1288. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  1289. }
  1290. $linkstart = '<a href="'.$url.'"';
  1291. $linkstart .= $linkclose.'>';
  1292. $linkend = '</a>';
  1293. if ($option == 'nolink') {
  1294. $linkstart = '';
  1295. $linkend = '';
  1296. }
  1297. if ($withpicto == 2)
  1298. {
  1299. $libelle = $label;
  1300. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype;
  1301. $libelleshort = '';
  1302. }
  1303. else
  1304. {
  1305. $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : ''));
  1306. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype;
  1307. if ($maxlength < 0) $libelleshort = $this->ref;
  1308. else $libelleshort = dol_trunc($libelle, $maxlength);
  1309. }
  1310. if ($withpicto)
  1311. {
  1312. if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into ()
  1313. {
  1314. if ($labeltype)
  1315. {
  1316. $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')');
  1317. }
  1318. }
  1319. }
  1320. $result .= $linkstart;
  1321. if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip ? 0 : 1);
  1322. $result .= $libelleshort;
  1323. $result .= $linkend;
  1324. global $action;
  1325. $hookmanager->initHooks(array('actiondao'));
  1326. $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
  1327. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1328. if ($reshook > 0) $result = $hookmanager->resPrint;
  1329. else $result .= $hookmanager->resPrint;
  1330. return $result;
  1331. }
  1332. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1333. /**
  1334. * Export events from database into a cal file.
  1335. *
  1336. * @param string $format 'vcal', 'ical/ics', 'rss'
  1337. * @param string $type 'event' or 'journal'
  1338. * @param int $cachedelay Do not rebuild file if date older than cachedelay seconds
  1339. * @param string $filename Force filename
  1340. * @param array $filters Array of filters. Exemple array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...)
  1341. * @return int <0 if error, nb of events in new file if ok
  1342. */
  1343. public function build_exportfile($format, $type, $cachedelay, $filename, $filters)
  1344. {
  1345. global $hookmanager;
  1346. // phpcs:enable
  1347. global $conf, $langs, $dolibarr_main_url_root, $mysoc;
  1348. require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
  1349. require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
  1350. require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
  1351. dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
  1352. // Check parameters
  1353. if (empty($format)) return -1;
  1354. // Clean parameters
  1355. if (!$filename)
  1356. {
  1357. $extension = 'vcs';
  1358. if ($format == 'ical') $extension = 'ics';
  1359. $filename = $format.'.'.$extension;
  1360. }
  1361. // Create dir and define output file (definitive and temporary)
  1362. $result = dol_mkdir($conf->agenda->dir_temp);
  1363. $outputfile = $conf->agenda->dir_temp.'/'.$filename;
  1364. $result = 0;
  1365. $buildfile = true;
  1366. $login = ''; $logina = ''; $logind = ''; $logint = '';
  1367. $now = dol_now();
  1368. if ($cachedelay)
  1369. {
  1370. $nowgmt = dol_now();
  1371. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1372. if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay))
  1373. {
  1374. dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
  1375. $buildfile = false;
  1376. }
  1377. }
  1378. if ($buildfile)
  1379. {
  1380. // Build event array
  1381. $eventarray=array();
  1382. $sql = "SELECT a.id,";
  1383. $sql.= " a.datep,"; // Start
  1384. $sql.= " a.datep2,"; // End
  1385. $sql.= " a.durationp,"; // deprecated
  1386. $sql.= " a.datec, a.tms as datem,";
  1387. $sql.= " a.label, a.code, a.note, a.fk_action as type_id,";
  1388. $sql.= " a.fk_soc,";
  1389. $sql.= " a.fk_user_author, a.fk_user_mod,";
  1390. $sql.= " a.fk_user_action,";
  1391. $sql.= " a.fk_contact, a.percent as percentage,";
  1392. $sql.= " a.fk_element, a.elementtype,";
  1393. $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
  1394. $sql.= " u.firstname, u.lastname, u.email,";
  1395. $sql.= " s.nom as socname,";
  1396. $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label";
  1397. $sql.= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
  1398. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
  1399. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
  1400. $parameters=array('filters' => $filters);
  1401. $reshook=$hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
  1402. $sql.=$hookmanager->resPrint;
  1403. // We must filter on assignement table
  1404. if ($filters['logint']) $sql.=", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
  1405. $sql.= " WHERE a.fk_action=c.id";
  1406. $sql.= " AND a.entity IN (".getEntity('agenda').")";
  1407. foreach ($filters as $key => $value)
  1408. {
  1409. if ($key == 'notolderthan' && $value != '') $sql.=" AND a.datep >= '".$this->db->idate($now-($value*24*60*60))."'";
  1410. 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))."'";
  1411. if ($key == 'id') $sql.=" AND a.id=".(is_numeric($value)?$value:0);
  1412. if ($key == 'idfrom') $sql.=" AND a.id >= ".(is_numeric($value)?$value:0);
  1413. if ($key == 'idto') $sql.=" AND a.id <= ".(is_numeric($value)?$value:0);
  1414. if ($key == 'project') $sql.=" AND a.fk_project=".(is_numeric($value)?$value:0);
  1415. if ($key == 'actiontype') $sql.=" AND c.type = '".$this->db->escape($value)."'";
  1416. if ($key == 'notactiontype') $sql.=" AND c.type <> '".$this->db->escape($value)."'";
  1417. // We must filter on assignement table
  1418. if ($key == 'logint') $sql.= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
  1419. if ($key == 'logina')
  1420. {
  1421. $logina=$value;
  1422. $condition='=';
  1423. if (preg_match('/^!/', $logina))
  1424. {
  1425. $logina=preg_replace('/^!/', '', $logina);
  1426. $condition='<>';
  1427. }
  1428. $userforfilter=new User($this->db);
  1429. $result=$userforfilter->fetch('', $logina);
  1430. if ($result > 0) $sql.= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
  1431. elseif ($result < 0 || $condition == '=') $sql.= " AND a.fk_user_author = 0";
  1432. }
  1433. if ($key == 'logint')
  1434. {
  1435. $logint=$value;
  1436. $condition='=';
  1437. if (preg_match('/^!/', $logint))
  1438. {
  1439. $logint=preg_replace('/^!/', '', $logint);
  1440. $condition='<>';
  1441. }
  1442. $userforfilter=new User($this->db);
  1443. $result=$userforfilter->fetch('', $logint);
  1444. if ($result > 0) $sql.= " AND ar.fk_element = ".$userforfilter->id;
  1445. elseif ($result < 0 || $condition == '=') $sql.= " AND ar.fk_element = 0";
  1446. }
  1447. }
  1448. $sql.= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
  1449. $parameters=array('filters' => $filters);
  1450. $reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1451. $sql.=$hookmanager->resPrint;
  1452. $sql.= " ORDER by datep";
  1453. //print $sql;exit;
  1454. dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG);
  1455. $resql=$this->db->query($sql);
  1456. if ($resql)
  1457. {
  1458. // Note: Output of sql request is encoded in $conf->file->character_set_client
  1459. // This assignment in condition is not a bug. It allows walking the results.
  1460. $diff = 0;
  1461. while ($obj=$this->db->fetch_object($resql))
  1462. {
  1463. $qualified=true;
  1464. // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
  1465. $event=array();
  1466. $event['uid']='dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
  1467. $event['type']=$type;
  1468. $datestart=$this->db->jdate($obj->datep)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
  1469. // fix for -> Warning: A non-numeric value encountered
  1470. if(is_numeric($this->db->jdate($obj->datep2)))
  1471. {
  1472. $dateend = $this->db->jdate($obj->datep2)
  1473. - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
  1474. }
  1475. else
  1476. {
  1477. // use start date as fall-back to avoid import erros on empty end date
  1478. $dateend = $datestart;
  1479. }
  1480. $duration=($datestart && $dateend)?($dateend - $datestart):0;
  1481. $event['summary']=$obj->label.($obj->socname?" (".$obj->socname.")":"");
  1482. $event['desc']=$obj->note;
  1483. $event['startdate']=$datestart;
  1484. $event['enddate']=$dateend; // Not required with type 'journal'
  1485. $event['duration']=$duration; // Not required with type 'journal'
  1486. $event['author']=dolGetFirstLastname($obj->firstname, $obj->lastname);
  1487. $event['priority']=$obj->priority;
  1488. $event['fulldayevent']=$obj->fulldayevent;
  1489. $event['location']=$obj->location;
  1490. $event['transparency']=(($obj->transparency > 0)?'OPAQUE':'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
  1491. $event['punctual']=$obj->punctual;
  1492. $event['category']=$obj->type_label;
  1493. $event['email']=$obj->email;
  1494. // Define $urlwithroot
  1495. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1496. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1497. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1498. $url=$urlwithroot.'/comm/action/card.php?id='.$obj->id;
  1499. $event['url']=$url;
  1500. $event['created']=$this->db->jdate($obj->datec)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
  1501. $event['modified']=$this->db->jdate($obj->datem)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
  1502. // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
  1503. $this->id = $obj->id;
  1504. $this->fetch_userassigned(false);
  1505. $assignedUserArray = array();
  1506. foreach($this->userassigned as $key => $value)
  1507. {
  1508. $assignedUser = new User($this->db);
  1509. $assignedUser->fetch($value['id']);
  1510. $assignedUserArray[$key]=$assignedUser;
  1511. }
  1512. $event['assignedUsers']=$assignedUserArray;
  1513. if ($qualified && $datestart)
  1514. {
  1515. $eventarray[]=$event;
  1516. }
  1517. $diff++;
  1518. }
  1519. }
  1520. else
  1521. {
  1522. $this->error=$this->db->lasterror();
  1523. return -1;
  1524. }
  1525. $langs->load("agenda");
  1526. // Define title and desc
  1527. $more='';
  1528. if ($login) $more=$langs->transnoentities("User").' '.$login;
  1529. if ($logina) $more=$langs->transnoentities("ActionsAskedBy").' '.$logina;
  1530. if ($logint) $more=$langs->transnoentities("ActionsToDoBy").' '.$logint;
  1531. if ($logind) $more=$langs->transnoentities("ActionsDoneBy").' '.$logind;
  1532. if ($more)
  1533. {
  1534. $title='Dolibarr actions '.$mysoc->name.' - '.$more;
  1535. $desc=$more;
  1536. $desc.=' ('.$mysoc->name.' - built by Dolibarr)';
  1537. }
  1538. else
  1539. {
  1540. $title='Dolibarr actions '.$mysoc->name;
  1541. $desc=$langs->transnoentities('ListOfActions');
  1542. $desc.=' ('.$mysoc->name.' - built by Dolibarr)';
  1543. }
  1544. // Create temp file
  1545. $outputfiletmp=tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
  1546. @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
  1547. // Write file
  1548. if ($format == 'vcal') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1549. elseif ($format == 'ical') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1550. elseif ($format == 'rss') $result=build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
  1551. if ($result >= 0)
  1552. {
  1553. if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result=1;
  1554. else
  1555. {
  1556. $this->error='Failed to rename '.$outputfiletmp.' into '.$outputfile;
  1557. dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
  1558. dol_delete_file($outputfiletmp, 0, 1);
  1559. $result=-1;
  1560. }
  1561. }
  1562. else
  1563. {
  1564. dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
  1565. dol_delete_file($outputfiletmp, 0, 1);
  1566. $langs->load("errors");
  1567. $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
  1568. }
  1569. }
  1570. return $result;
  1571. }
  1572. /**
  1573. * Initialise an instance with random values.
  1574. * Used to build previews or test instances.
  1575. * id must be 0 if object instance is a specimen.
  1576. *
  1577. * @return int >0 if ok
  1578. */
  1579. public function initAsSpecimen()
  1580. {
  1581. global $user;
  1582. $now = dol_now();
  1583. // Initialise parametres
  1584. $this->id = 0;
  1585. $this->specimen = 1;
  1586. $this->type_code = 'AC_OTH';
  1587. $this->code = 'AC_SPECIMEN_CODE';
  1588. $this->label = 'Label of event Specimen';
  1589. $this->datec = $now;
  1590. $this->datem = $now;
  1591. $this->datep = $now;
  1592. $this->datef = $now;
  1593. $this->author = $user;
  1594. $this->usermod = $user;
  1595. $this->usertodo = $user;
  1596. $this->fulldayevent = 0;
  1597. $this->punctual = 0;
  1598. $this->percentage = 0;
  1599. $this->location = 'Location';
  1600. $this->transparency = 1; // 1 means opaque
  1601. $this->priority = 1;
  1602. $this->note = "This is a 'public' note";
  1603. $this->note_public = "This is a 'public' note.";
  1604. $this->note_private = "This is a 'private' note.";
  1605. $this->userownerid = $user->id;
  1606. $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1);
  1607. return 1;
  1608. }
  1609. /**
  1610. * Function used to replace a thirdparty id with another one.
  1611. *
  1612. * @param DoliDB $db Database handler
  1613. * @param int $origin_id Old thirdparty id
  1614. * @param int $dest_id New thirdparty id
  1615. * @return bool
  1616. */
  1617. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1618. {
  1619. $tables = array(
  1620. 'actioncomm'
  1621. );
  1622. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1623. }
  1624. /**
  1625. * Is the action delayed?
  1626. *
  1627. * @return bool
  1628. */
  1629. public function hasDelay()
  1630. {
  1631. global $conf;
  1632. $now = dol_now();
  1633. return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
  1634. }
  1635. /**
  1636. * Send reminders by emails
  1637. * CAN BE A CRON TASK
  1638. *
  1639. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1640. */
  1641. public function sendEmailsReminder()
  1642. {
  1643. global $conf, $langs;
  1644. $error = 0;
  1645. $this->output = '';
  1646. $this->error = '';
  1647. if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible.
  1648. {
  1649. $langs->load("agenda");
  1650. $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
  1651. return 0;
  1652. }
  1653. if (empty($conf->global->AGENDA_REMINDER_EMAIL))
  1654. {
  1655. $langs->load("agenda");
  1656. $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
  1657. return 0;
  1658. }
  1659. $now = dol_now();
  1660. dol_syslog(__METHOD__, LOG_DEBUG);
  1661. $this->db->begin();
  1662. // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done
  1663. // Delete also very old past events (we do not keep more than 1 month record in past)
  1664. $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'";
  1665. $this->db->query($sql);
  1666. $this->db->commit();
  1667. return $error;
  1668. }
  1669. }