actioncomm.class.php 87 KB

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