actioncomm.class.php 79 KB

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