actioncomm.class.php 88 KB

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