ticket.class.php 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148
  1. <?php
  2. /* Copyright (C) 2013-2018 Jean-François Ferry <hello@librethic.io>
  3. * Copyright (C) 2016 Christophe Battarel <christophe@altairis.fr>
  4. * Copyright (C) 2019-2020 Frédéric France <frederic.france@netlogic.fr>
  5. * Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file ticket/class/ticket.class.php
  22. * \ingroup ticket
  23. * \brief Class file for object ticket
  24. */
  25. // Put here all includes required by your class file
  26. require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
  27. require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  29. /**
  30. * Class to manage ticket
  31. */
  32. class Ticket extends CommonObject
  33. {
  34. /**
  35. * @var string ID to identify managed object
  36. */
  37. public $element = 'ticket';
  38. /**
  39. * @var string Name of table without prefix where object is stored
  40. */
  41. public $table_element = 'ticket';
  42. /**
  43. * @var string Name of field for link to tickets
  44. */
  45. public $fk_element = 'fk_ticket';
  46. /**
  47. * @var int Does ticketcore support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  48. */
  49. public $ismultientitymanaged = 1;
  50. /**
  51. * @var int Does ticketcore support extrafields ? 0=No, 1=Yes
  52. */
  53. public $isextrafieldmanaged = 1;
  54. /**
  55. * @var string String with name of icon for ticketcore. Must be the part after the 'object_' into object_ticketcore.png
  56. */
  57. public $picto = 'ticket';
  58. /**
  59. * @var string Hash to identify ticket publically
  60. */
  61. public $track_id;
  62. /**
  63. * @var int Thirdparty ID
  64. */
  65. public $fk_soc;
  66. /**
  67. * @var int Project ID
  68. */
  69. public $fk_project;
  70. /**
  71. * @var string Person email who have create ticket
  72. */
  73. public $origin_email;
  74. /**
  75. * @var int User id who have create ticket
  76. */
  77. public $fk_user_create;
  78. /**
  79. * @var int User id who have ticket assigned
  80. */
  81. public $fk_user_assign;
  82. /**
  83. * var string Ticket subject
  84. */
  85. public $subject;
  86. /**
  87. * @var string Ticket message
  88. */
  89. public $message;
  90. /**
  91. * @var int Ticket statut
  92. * @deprecated
  93. */
  94. public $fk_statut;
  95. /**
  96. * @var int Ticket status
  97. */
  98. public $status;
  99. /**
  100. * @var string State resolution
  101. */
  102. public $resolution;
  103. /**
  104. * @var int Progress in percent
  105. */
  106. public $progress;
  107. /**
  108. * @var string Duration for ticket
  109. */
  110. public $timing;
  111. /**
  112. * @var string Type code
  113. */
  114. public $type_code;
  115. /**
  116. * @var string Category code
  117. */
  118. public $category_code;
  119. /**
  120. * @var string Severity code
  121. */
  122. public $severity_code;
  123. /**
  124. * Type label
  125. */
  126. public $type_label;
  127. /**
  128. * Category label
  129. */
  130. public $category_label;
  131. /**
  132. * Severity label
  133. */
  134. public $severity_label;
  135. /**
  136. * Email from user
  137. */
  138. public $email_from;
  139. /**
  140. * @var int Creation date
  141. */
  142. public $datec = '';
  143. /**
  144. * @var int Read date
  145. */
  146. public $date_read = '';
  147. /**
  148. * @var int Close ticket date
  149. */
  150. public $date_close = '';
  151. /**
  152. * @var array cache_types_tickets
  153. */
  154. public $cache_types_tickets;
  155. /**
  156. * @var array tickets categories
  157. */
  158. public $cache_category_tickets;
  159. /**
  160. * @var int Notify thirdparty at create
  161. */
  162. public $notify_tiers_at_create;
  163. /**
  164. * @var string msgid
  165. */
  166. public $email_msgid;
  167. public $lines;
  168. /**
  169. * @var string Regex pour les images
  170. */
  171. public $regeximgext = '\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff';
  172. /**
  173. * Status
  174. */
  175. const STATUS_NOT_READ = 0;
  176. const STATUS_READ = 1;
  177. const STATUS_ASSIGNED = 2;
  178. const STATUS_IN_PROGRESS = 3;
  179. const STATUS_NEED_MORE_INFO = 5;
  180. const STATUS_WAITING = 7; // on hold
  181. const STATUS_CLOSED = 8;
  182. const STATUS_CANCELED = 9;
  183. /**
  184. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  185. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  186. * 'label' the translation key.
  187. * 'picto' is code of a picto to show before value in forms
  188. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  189. * 'position' is the sort order of field.
  190. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  191. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  192. * 'noteditable' says if field is not editable (1 or 0)
  193. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  194. * 'index' if we want an index in database.
  195. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  196. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  197. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  198. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200'
  199. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  200. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  201. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  202. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  203. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  204. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  205. *
  206. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  207. */
  208. // BEGIN MODULEBUILDER PROPERTIES
  209. public $fields = array(
  210. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'position'=>1, 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id"),
  211. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>5, 'notnull'=>1, 'index'=>1),
  212. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
  213. 'track_id' => array('type'=>'varchar(255)', 'label'=>'TicketTrackId', 'visible'=>-2, 'enabled'=>1, 'position'=>11, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text"),
  214. 'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>15, 'notnull'=>1, 'css'=>'tdoverflowmax125 maxwidth150onsmartphone'),
  215. 'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>-2, 'enabled'=>1, 'position'=>16, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>'tdoverflowmax150'),
  216. 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>18, 'notnull'=>-1, 'searchall'=>1, 'help'=>"", 'css'=>'maxwidth200 tdoverflowmax200', 'autofocusoncreate'=>1),
  217. 'type_code' => array('type'=>'varchar(32)', 'label'=>'Type', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth125 tdoverflowmax50'),
  218. 'category_code' => array('type'=>'varchar(32)', 'label'=>'TicketCategory', 'visible'=>-1, 'enabled'=>1, 'position'=>21, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth100'),
  219. 'severity_code' => array('type'=>'varchar(32)', 'label'=>'Severity', 'visible'=>1, 'enabled'=>1, 'position'=>22, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth100'),
  220. 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>'$conf->societe->enabled', 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToThirparty", 'css'=>'tdoverflowmax150 maxwidth150onsmartphone'),
  221. 'notify_tiers_at_create' => array('type'=>'integer', 'label'=>'NotifyThirdparty', 'visible'=>-1, 'enabled'=>0, 'position'=>51, 'notnull'=>1, 'index'=>1),
  222. 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php', 'label'=>'Project', 'visible'=>-1, 'enabled'=>1, 'position'=>52, 'notnull'=>-1, 'index'=>1, 'help'=>"LinkToProject"),
  223. 'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'help'=>""),
  224. 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>1, 'enabled'=>1, 'position'=>500, 'notnull'=>1),
  225. 'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>-1, 'enabled'=>1, 'position'=>501, 'notnull'=>1),
  226. 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AssignedTo', 'visible'=>1, 'enabled'=>1, 'position'=>505, 'notnull'=>1, 'css'=>'tdoverflowmax125'),
  227. 'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-1, 'enabled'=>1, 'position'=>510, 'notnull'=>1),
  228. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>520, 'notnull'=>1),
  229. 'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>540, 'notnull'=>-1,),
  230. 'email_msgid' => array('type'=>'varchar(255)', 'label'=>'EmailMsgID', 'visible'=>-2, 'enabled'=>1, 'position'=>540, 'notnull'=>-1, 'help'=>'EmailMsgIDDesc'),
  231. 'progress' => array('type'=>'varchar(100)', 'label'=>'Progression', 'visible'=>-1, 'enabled'=>1, 'position'=>540, 'notnull'=>-1, 'css'=>'right', 'help'=>"", 'isameasure'=>1),
  232. 'resolution' => array('type'=>'integer', 'label'=>'Resolution', 'visible'=>-1, 'enabled'=>1, 'position'=>550, 'notnull'=>1),
  233. 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'Unread', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')),
  234. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
  235. );
  236. // END MODULEBUILDER PROPERTIES
  237. /**
  238. * Constructor
  239. *
  240. * @param DoliDb $db Database handler
  241. */
  242. public function __construct($db)
  243. {
  244. $this->db = $db;
  245. $this->statuts_short = array(
  246. self::STATUS_NOT_READ => 'Unread',
  247. self::STATUS_READ => 'Read',
  248. self::STATUS_ASSIGNED => 'Assigned',
  249. self::STATUS_IN_PROGRESS => 'InProgress',
  250. self::STATUS_WAITING => 'OnHold',
  251. self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation',
  252. self::STATUS_CLOSED => 'Closed',
  253. self::STATUS_CANCELED => 'Canceled'
  254. );
  255. $this->statuts = array(
  256. self::STATUS_NOT_READ => 'Unread',
  257. self::STATUS_READ => 'Read',
  258. self::STATUS_ASSIGNED => 'Assigned',
  259. self::STATUS_IN_PROGRESS => 'InProgress',
  260. self::STATUS_WAITING => 'OnHold',
  261. self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation',
  262. self::STATUS_CLOSED => 'Closed',
  263. self::STATUS_CANCELED => 'Canceled'
  264. );
  265. }
  266. /**
  267. * Check properties of ticket are ok (like ref, track_id, ...).
  268. * All properties must be already loaded on object (this->ref, this->track_id, ...).
  269. *
  270. * @return int 0 if OK, <0 if KO
  271. */
  272. private function verify()
  273. {
  274. $this->errors = array();
  275. $result = 0;
  276. // Clean parameters
  277. if (isset($this->ref)) {
  278. $this->ref = trim($this->ref);
  279. }
  280. if (isset($this->track_id)) {
  281. $this->track_id = trim($this->track_id);
  282. }
  283. if (isset($this->fk_soc)) {
  284. $this->fk_soc = (int) $this->fk_soc;
  285. }
  286. if (isset($this->fk_project)) {
  287. $this->fk_project = (int) $this->fk_project;
  288. }
  289. if (isset($this->origin_email)) {
  290. $this->origin_email = trim($this->origin_email);
  291. }
  292. if (isset($this->fk_user_create)) {
  293. $this->fk_user_create = (int) $this->fk_user_create;
  294. }
  295. if (isset($this->fk_user_assign)) {
  296. $this->fk_user_assign = (int) $this->fk_user_assign;
  297. }
  298. if (isset($this->subject)) {
  299. $this->subject = trim($this->subject);
  300. }
  301. if (isset($this->message)) {
  302. $this->message = trim($this->message);
  303. }
  304. if (isset($this->fk_statut)) {
  305. $this->fk_statut = (int) $this->fk_statut;
  306. }
  307. if (isset($this->resolution)) {
  308. $this->resolution = trim($this->resolution);
  309. }
  310. if (isset($this->progress)) {
  311. $this->progress = trim($this->progress);
  312. }
  313. if (isset($this->timing)) {
  314. $this->timing = trim($this->timing);
  315. }
  316. if (isset($this->type_code)) {
  317. $this->type_code = trim($this->type_code);
  318. }
  319. if (isset($this->category_code)) {
  320. $this->category_code = trim($this->category_code);
  321. }
  322. if (isset($this->severity_code)) {
  323. $this->severity_code = trim($this->severity_code);
  324. }
  325. if (empty($this->ref)) {
  326. $this->errors[] = 'ErrorTicketRefRequired';
  327. dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
  328. $result = -1;
  329. }
  330. return $result;
  331. }
  332. /**
  333. * Create object into database
  334. *
  335. * @param User $user User that creates
  336. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  337. * @return int <0 if KO, Id of created object if OK
  338. */
  339. public function create($user, $notrigger = 0)
  340. {
  341. global $conf, $langs;
  342. $error = 0;
  343. // Clean parameters
  344. $this->datec = dol_now();
  345. if (empty($this->track_id)) {
  346. $this->track_id = generate_random_id(16);
  347. }
  348. // Check more parameters
  349. // If error, this->errors[] is filled
  350. $result = $this->verify();
  351. if ($result >= 0) {
  352. // Insert request
  353. $sql = "INSERT INTO ".MAIN_DB_PREFIX."ticket(";
  354. $sql .= "ref,";
  355. $sql .= "track_id,";
  356. $sql .= "fk_soc,";
  357. $sql .= "fk_project,";
  358. $sql .= "origin_email,";
  359. $sql .= "fk_user_create,";
  360. $sql .= "fk_user_assign,";
  361. $sql .= "email_msgid,";
  362. $sql .= "subject,";
  363. $sql .= "message,";
  364. $sql .= "fk_statut,";
  365. $sql .= "resolution,";
  366. $sql .= "progress,";
  367. $sql .= "timing,";
  368. $sql .= "type_code,";
  369. $sql .= "category_code,";
  370. $sql .= "severity_code,";
  371. $sql .= "datec,";
  372. $sql .= "date_read,";
  373. $sql .= "date_close,";
  374. $sql .= "entity,";
  375. $sql .= "notify_tiers_at_create";
  376. $sql .= ") VALUES (";
  377. $sql .= " ".(!isset($this->ref) ? '' : "'".$this->db->escape($this->ref)."'").",";
  378. $sql .= " ".(!isset($this->track_id) ? 'NULL' : "'".$this->db->escape($this->track_id)."'").",";
  379. $sql .= " ".($this->fk_soc > 0 ? $this->db->escape($this->fk_soc) : "null").",";
  380. $sql .= " ".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "null").",";
  381. $sql .= " ".(!isset($this->origin_email) ? 'NULL' : "'".$this->db->escape($this->origin_email)."'").",";
  382. $sql .= " ".($this->fk_user_create > 0 ? $this->fk_user_create : ($user->id > 0 ? $user->id : 'NULL')).",";
  383. $sql .= " ".($this->fk_user_assign > 0 ? $this->fk_user_assign : 'NULL').",";
  384. $sql .= " ".(empty($this->email_msgid) ? 'NULL' : "'".$this->db->escape($this->email_msgid)."'").",";
  385. $sql .= " ".(!isset($this->subject) ? 'NULL' : "'".$this->db->escape($this->subject)."'").",";
  386. $sql .= " ".(!isset($this->message) ? 'NULL' : "'".$this->db->escape($this->message)."'").",";
  387. $sql .= " ".(!isset($this->fk_statut) ? '0' : "'".$this->db->escape($this->fk_statut)."'").",";
  388. $sql .= " ".(!isset($this->resolution) ? 'NULL' : "'".$this->db->escape($this->resolution)."'").",";
  389. $sql .= " ".(!isset($this->progress) ? '0' : "'".$this->db->escape($this->progress)."'").",";
  390. $sql .= " ".(!isset($this->timing) ? 'NULL' : "'".$this->db->escape($this->timing)."'").",";
  391. $sql .= " ".(!isset($this->type_code) ? 'NULL' : "'".$this->db->escape($this->type_code)."'").",";
  392. $sql .= " ".(!isset($this->category_code) ? 'NULL' : "'".$this->db->escape($this->category_code)."'").",";
  393. $sql .= " ".(!isset($this->severity_code) ? 'NULL' : "'".$this->db->escape($this->severity_code)."'").",";
  394. $sql .= " ".(!isset($this->datec) || dol_strlen($this->datec) == 0 ? 'NULL' : "'".$this->db->idate($this->datec)."'").",";
  395. $sql .= " ".(!isset($this->date_read) || dol_strlen($this->date_read) == 0 ? 'NULL' : "'".$this->db->idate($this->date_read)."'").",";
  396. $sql .= " ".(!isset($this->date_close) || dol_strlen($this->date_close) == 0 ? 'NULL' : "'".$this->db->idate($this->date_close)."'")."";
  397. $sql .= ", ".$conf->entity;
  398. $sql .= ", ".(!isset($this->notify_tiers_at_create) ? '1' : "'".$this->db->escape($this->notify_tiers_at_create)."'");
  399. $sql .= ")";
  400. $this->db->begin();
  401. dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
  402. $resql = $this->db->query($sql);
  403. if (!$resql) {
  404. $error++;
  405. $this->errors[] = "Error ".$this->db->lasterror();
  406. }
  407. if (!$error) {
  408. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ticket");
  409. if (!$notrigger) {
  410. // Call trigger
  411. $result = $this->call_trigger('TICKET_CREATE', $user);
  412. if ($result < 0) {
  413. $error++;
  414. }
  415. // End call triggers
  416. }
  417. }
  418. //Update extrafield
  419. if (!$error) {
  420. $result = $this->insertExtraFields();
  421. if ($result < 0) {
  422. $error++;
  423. }
  424. }
  425. // Commit or rollback
  426. if ($error) {
  427. foreach ($this->errors as $errmsg) {
  428. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  429. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  430. }
  431. $this->db->rollback();
  432. return -1 * $error;
  433. } else {
  434. $this->db->commit();
  435. return $this->id;
  436. }
  437. } else {
  438. $this->db->rollback();
  439. dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
  440. return -3;
  441. }
  442. }
  443. /**
  444. * Load object in memory from the database
  445. *
  446. * @param int $id Id object
  447. * @param string $ref Ref
  448. * @param string $track_id Track id, a hash like ref
  449. * @param string $email_msgid Email msgid
  450. * @return int <0 if KO, >0 if OK
  451. */
  452. public function fetch($id = '', $ref = '', $track_id = '', $email_msgid = '')
  453. {
  454. global $langs;
  455. // Check parameters
  456. if (!$id && !$track_id && !$ref && !$email_msgid) {
  457. $this->error = 'ErrorWrongParameters';
  458. dol_print_error(get_class($this)."::fetch ".$this->error);
  459. return -1;
  460. }
  461. $sql = "SELECT";
  462. $sql .= " t.rowid,";
  463. $sql .= " t.entity,";
  464. $sql .= " t.ref,";
  465. $sql .= " t.track_id,";
  466. $sql .= " t.fk_soc,";
  467. $sql .= " t.fk_project,";
  468. $sql .= " t.origin_email,";
  469. $sql .= " t.fk_user_create,";
  470. $sql .= " t.fk_user_assign,";
  471. $sql .= " t.email_msgid,";
  472. $sql .= " t.subject,";
  473. $sql .= " t.message,";
  474. $sql .= " t.fk_statut as status,";
  475. $sql .= " t.resolution,";
  476. $sql .= " t.progress,";
  477. $sql .= " t.timing,";
  478. $sql .= " t.type_code,";
  479. $sql .= " t.category_code,";
  480. $sql .= " t.severity_code,";
  481. $sql .= " t.datec,";
  482. $sql .= " t.date_read,";
  483. $sql .= " t.date_close,";
  484. $sql .= " t.tms";
  485. $sql .= ", type.code as type_code, type.label as type_label, category.code as category_code, category.label as category_label, severity.code as severity_code, severity.label as severity_label";
  486. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
  487. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
  488. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
  489. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
  490. if ($id) {
  491. $sql .= " WHERE t.rowid = ".((int) $id);
  492. } else {
  493. $sql .= " WHERE t.entity IN (".getEntity($this->element, 1).")";
  494. if (!empty($ref)) {
  495. $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
  496. } elseif ($track_id) {
  497. $sql .= " AND t.track_id = '".$this->db->escape($track_id)."'";
  498. } else {
  499. $sql .= " AND t.email_msgid = '".$this->db->escape($email_msgid)."'";
  500. }
  501. }
  502. dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
  503. $resql = $this->db->query($sql);
  504. if ($resql) {
  505. if ($this->db->num_rows($resql)) {
  506. $obj = $this->db->fetch_object($resql);
  507. $this->id = $obj->rowid;
  508. $this->ref = $obj->ref;
  509. $this->track_id = $obj->track_id;
  510. $this->fk_soc = $obj->fk_soc;
  511. $this->socid = $obj->fk_soc; // for fetch_thirdparty() method
  512. $this->fk_project = $obj->fk_project;
  513. $this->origin_email = $obj->origin_email;
  514. $this->fk_user_create = $obj->fk_user_create;
  515. $this->fk_user_assign = $obj->fk_user_assign;
  516. $this->email_msgid = $obj->email_msgid;
  517. $this->subject = $obj->subject;
  518. $this->message = $obj->message;
  519. $this->status = $obj->status;
  520. $this->fk_statut = $this->status; // For backward compatibility
  521. $this->resolution = $obj->resolution;
  522. $this->progress = $obj->progress;
  523. $this->timing = $obj->timing;
  524. $this->type_code = $obj->type_code;
  525. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  526. $label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != ("TicketTypeShort".$obj->type_code) ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
  527. $this->type_label = $label_type;
  528. $this->category_code = $obj->category_code;
  529. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  530. $label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != ("TicketCategoryShort".$obj->category_code) ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
  531. $this->category_label = $label_category;
  532. $this->severity_code = $obj->severity_code;
  533. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  534. $label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != ("TicketSeverityShort".$obj->severity_code) ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
  535. $this->severity_label = $label_severity;
  536. $this->datec = $this->db->jdate($obj->datec);
  537. $this->date_creation = $this->db->jdate($obj->datec);
  538. $this->date_read = $this->db->jdate($obj->date_read);
  539. $this->date_validation = $this->db->jdate($obj->date_read);
  540. $this->date_close = $this->db->jdate($obj->date_close);
  541. $this->tms = $this->db->jdate($obj->tms);
  542. $this->date_modification = $this->db->jdate($obj->tms);
  543. $this->fetch_optionals();
  544. $this->db->free($resql);
  545. return 1;
  546. } else {
  547. return 0;
  548. }
  549. } else {
  550. $this->error = "Error ".$this->db->lasterror();
  551. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  552. return -1;
  553. }
  554. }
  555. /**
  556. * Load all objects in memory from database
  557. *
  558. * @param User $user User for action
  559. * @param string $sortorder Sort order
  560. * @param string $sortfield Sort field
  561. * @param int $limit page number
  562. * @param int $offset Offset for query
  563. * @param int $arch archive or not (not used)
  564. * @param array $filter Filter for query
  565. * output
  566. * @return int <0 if KO, >0 if OK
  567. */
  568. public function fetchAll($user, $sortorder = 'ASC', $sortfield = 't.datec', $limit = '', $offset = 0, $arch = '', $filter = '')
  569. {
  570. global $langs;
  571. $extrafields = new ExtraFields($this->db);
  572. // fetch optionals attributes and labels
  573. $extrafields->fetch_name_optionals_label($this->table_element);
  574. $sql = "SELECT";
  575. $sql .= " t.rowid,";
  576. $sql .= " t.ref,";
  577. $sql .= " t.track_id,";
  578. $sql .= " t.fk_soc,";
  579. $sql .= " t.fk_project,";
  580. $sql .= " t.origin_email,";
  581. $sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,";
  582. $sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,";
  583. $sql .= " t.subject,";
  584. $sql .= " t.message,";
  585. $sql .= " t.fk_statut,";
  586. $sql .= " t.resolution,";
  587. $sql .= " t.progress,";
  588. $sql .= " t.timing,";
  589. $sql .= " t.type_code,";
  590. $sql .= " t.category_code,";
  591. $sql .= " t.severity_code,";
  592. $sql .= " t.datec,";
  593. $sql .= " t.date_read,";
  594. $sql .= " t.date_close,";
  595. $sql .= " t.tms";
  596. $sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label";
  597. // Add fields for extrafields
  598. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  599. $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
  600. }
  601. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
  602. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
  603. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
  604. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
  605. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=t.fk_soc";
  606. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as uc ON uc.rowid=t.fk_user_create";
  607. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as ua ON ua.rowid=t.fk_user_assign";
  608. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
  609. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ticket_extrafields as ef on (t.rowid = ef.fk_object)";
  610. }
  611. if (!$user->rights->societe->client->voir && !$user->socid) {
  612. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  613. }
  614. $sql .= " WHERE t.entity IN (".getEntity('ticket').")";
  615. // Manage filter
  616. if (!empty($filter)) {
  617. foreach ($filter as $key => $value) {
  618. if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year
  619. $sql .= ' AND '.$key." = '".$this->db->escape($value)."'";
  620. } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) {
  621. $sql .= " AND ".$key." = '".$this->db->escape($value)."'";
  622. } elseif ($key == 't.fk_statut') {
  623. if (is_array($value) && count($value) > 0) {
  624. $sql .= 'AND '.$key.' IN ('.$this->db->sanitize(implode(',', $value)).')';
  625. } else {
  626. $sql .= ' AND '.$key.' = '.((int) $value);
  627. }
  628. } else {
  629. $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\'';
  630. }
  631. }
  632. }
  633. if (!$user->rights->societe->client->voir && !$user->socid) {
  634. $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
  635. } elseif ($user->socid) {
  636. $sql .= " AND t.fk_soc = ".$user->socid;
  637. }
  638. $sql .= " ORDER BY ".$sortfield.' '.$sortorder;
  639. if (!empty($limit)) {
  640. $sql .= ' '.$this->db->plimit($limit + 1, $offset);
  641. }
  642. dol_syslog(get_class($this)."::fetch_all sql=".$sql, LOG_DEBUG);
  643. $resql = $this->db->query($sql);
  644. if ($resql) {
  645. $this->lines = array();
  646. $num = $this->db->num_rows($resql);
  647. $i = 0;
  648. if ($num) {
  649. while ($i < $num) {
  650. $obj = $this->db->fetch_object($resql);
  651. $line = new TicketsLine();
  652. $line->id = $obj->rowid;
  653. $line->rowid = $obj->rowid;
  654. $line->ref = $obj->ref;
  655. $line->track_id = $obj->track_id;
  656. $line->fk_soc = $obj->fk_soc;
  657. $line->fk_project = $obj->fk_project;
  658. $line->origin_email = $obj->origin_email;
  659. $line->fk_user_create = $obj->fk_user_create;
  660. $line->user_create_lastname = $obj->user_create_lastname;
  661. $line->user_create_firstname = $obj->user_create_firstname;
  662. $line->fk_user_assign = $obj->fk_user_assign;
  663. $line->user_assign_lastname = $obj->user_assign_lastname;
  664. $line->user_assign_firstname = $obj->user_assign_firstname;
  665. $line->subject = $obj->subject;
  666. $line->message = $obj->message;
  667. $line->fk_statut = $obj->fk_statut;
  668. $line->resolution = $obj->resolution;
  669. $line->progress = $obj->progress;
  670. $line->timing = $obj->timing;
  671. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  672. $label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != ("TicketTypeShort".$obj->type_code) ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
  673. $line->type_label = $label_type;
  674. $this->category_code = $obj->category_code;
  675. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  676. $label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != ("TicketCategoryShort".$obj->category_code) ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
  677. $line->category_label = $label_category;
  678. $this->severity_code = $obj->severity_code;
  679. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  680. $label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != ("TicketSeverityShort".$obj->severity_code) ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
  681. $line->severity_label = $label_severity;
  682. $line->datec = $this->db->jdate($obj->datec);
  683. $line->date_read = $this->db->jdate($obj->date_read);
  684. $line->date_close = $this->db->jdate($obj->date_close);
  685. // Extra fields
  686. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
  687. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  688. $tmpkey = 'options_'.$key;
  689. $line->{$tmpkey} = $obj->$tmpkey;
  690. }
  691. }
  692. $this->lines[$i] = $line;
  693. $i++;
  694. }
  695. }
  696. $this->db->free($resql);
  697. return $num;
  698. } else {
  699. $this->error = "Error ".$this->db->lasterror();
  700. dol_syslog(get_class($this)."::fetch_all ".$this->error, LOG_ERR);
  701. return -1;
  702. }
  703. }
  704. /**
  705. * Update object into database
  706. *
  707. * @param User $user User that modifies
  708. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  709. * @return int <0 if KO, >0 if OK
  710. */
  711. public function update($user = 0, $notrigger = 0)
  712. {
  713. global $conf, $langs, $hookmanager;
  714. $error = 0;
  715. // Clean parameters
  716. if (isset($this->ref)) {
  717. $this->ref = trim($this->ref);
  718. }
  719. if (isset($this->track_id)) {
  720. $this->track_id = trim($this->track_id);
  721. }
  722. if (isset($this->fk_soc)) {
  723. $this->fk_soc = (int) $this->fk_soc;
  724. }
  725. if (isset($this->fk_project)) {
  726. $this->fk_project = (int) $this->fk_project;
  727. }
  728. if (isset($this->origin_email)) {
  729. $this->origin_email = trim($this->origin_email);
  730. }
  731. if (isset($this->fk_user_create)) {
  732. $this->fk_user_create = (int) $this->fk_user_create;
  733. }
  734. if (isset($this->fk_user_assign)) {
  735. $this->fk_user_assign = (int) $this->fk_user_assign;
  736. }
  737. if (isset($this->subject)) {
  738. $this->subject = trim($this->subject);
  739. }
  740. if (isset($this->message)) {
  741. $this->message = trim($this->message);
  742. }
  743. if (isset($this->fk_statut)) {
  744. $this->fk_statut = (int) $this->fk_statut;
  745. }
  746. if (isset($this->resolution)) {
  747. $this->resolution = trim($this->resolution);
  748. }
  749. if (isset($this->progress)) {
  750. $this->progress = trim($this->progress);
  751. }
  752. if (isset($this->timing)) {
  753. $this->timing = trim($this->timing);
  754. }
  755. if (isset($this->type_code)) {
  756. $this->timing = trim($this->type_code);
  757. }
  758. if (isset($this->category_code)) {
  759. $this->timing = trim($this->category_code);
  760. }
  761. if (isset($this->severity_code)) {
  762. $this->timing = trim($this->severity_code);
  763. }
  764. // Check parameters
  765. // Put here code to add a control on parameters values
  766. // Update request
  767. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket SET";
  768. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "").",";
  769. $sql .= " track_id=".(isset($this->track_id) ? "'".$this->db->escape($this->track_id)."'" : "null").",";
  770. $sql .= " fk_soc=".(isset($this->fk_soc) ? "'".$this->db->escape($this->fk_soc)."'" : "null").",";
  771. $sql .= " fk_project=".(isset($this->fk_project) ? "'".$this->db->escape($this->fk_project)."'" : "null").",";
  772. $sql .= " origin_email=".(isset($this->origin_email) ? "'".$this->db->escape($this->origin_email)."'" : "null").",";
  773. $sql .= " fk_user_create=".(isset($this->fk_user_create) ? $this->fk_user_create : "null").",";
  774. $sql .= " fk_user_assign=".(isset($this->fk_user_assign) ? $this->fk_user_assign : "null").",";
  775. $sql .= " subject=".(isset($this->subject) ? "'".$this->db->escape($this->subject)."'" : "null").",";
  776. $sql .= " message=".(isset($this->message) ? "'".$this->db->escape($this->message)."'" : "null").",";
  777. $sql .= " fk_statut=".(isset($this->fk_statut) ? $this->fk_statut : "null").",";
  778. $sql .= " resolution=".(isset($this->resolution) ? $this->resolution : "null").",";
  779. $sql .= " progress=".(isset($this->progress) ? "'".$this->db->escape($this->progress)."'" : "null").",";
  780. $sql .= " timing=".(isset($this->timing) ? "'".$this->db->escape($this->timing)."'" : "null").",";
  781. $sql .= " type_code=".(isset($this->type_code) ? "'".$this->db->escape($this->type_code)."'" : "null").",";
  782. $sql .= " category_code=".(isset($this->category_code) ? "'".$this->db->escape($this->category_code)."'" : "null").",";
  783. $sql .= " severity_code=".(isset($this->severity_code) ? "'".$this->db->escape($this->severity_code)."'" : "null").",";
  784. $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
  785. $sql .= " date_read=".(dol_strlen($this->date_read) != 0 ? "'".$this->db->idate($this->date_read)."'" : 'null').",";
  786. $sql .= " date_close=".(dol_strlen($this->date_close) != 0 ? "'".$this->db->idate($this->date_close)."'" : 'null')."";
  787. $sql .= " WHERE rowid=".((int) $this->id);
  788. $this->db->begin();
  789. $resql = $this->db->query($sql);
  790. if (!$resql) {
  791. $error++;
  792. $this->errors[] = "Error ".$this->db->lasterror();
  793. }
  794. if (!$error) {
  795. // Update extrafields
  796. $result = $this->insertExtraFields();
  797. if ($result < 0) {
  798. $error++;
  799. }
  800. }
  801. if (!$error && !$notrigger) {
  802. // Call trigger
  803. $result = $this->call_trigger('TICKET_MODIFY', $user);
  804. if ($result < 0) {
  805. $error++;
  806. }
  807. // End call triggers
  808. }
  809. // Commit or rollback
  810. if ($error) {
  811. foreach ($this->errors as $errmsg) {
  812. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  813. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  814. }
  815. $this->db->rollback();
  816. return -1 * $error;
  817. } else {
  818. $this->db->commit();
  819. return 1;
  820. }
  821. }
  822. /**
  823. * Delete object in database
  824. *
  825. * @param User $user User that deletes
  826. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  827. * @return int <0 if KO, >0 if OK
  828. */
  829. public function delete($user, $notrigger = 0)
  830. {
  831. global $conf, $langs;
  832. $error = 0;
  833. $this->db->begin();
  834. if (!$error) {
  835. if (!$notrigger) {
  836. // Call trigger
  837. $result = $this->call_trigger('TICKET_DELETE', $user);
  838. if ($result < 0) {
  839. $error++;
  840. }
  841. // End call triggers
  842. }
  843. }
  844. if (!$error) {
  845. // Delete linked contacts
  846. $res = $this->delete_linked_contact();
  847. if ($res < 0) {
  848. dol_syslog(get_class($this)."::delete error", LOG_ERR);
  849. $error++;
  850. }
  851. }
  852. if (!$error) {
  853. // Delete linked object
  854. $res = $this->deleteObjectLinked();
  855. if ($res < 0) {
  856. $error++;
  857. }
  858. }
  859. // Removed extrafields
  860. if (!$error) {
  861. $result = $this->deleteExtraFields();
  862. if ($result < 0) {
  863. $error++;
  864. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  865. }
  866. }
  867. if (!$error) {
  868. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ticket";
  869. $sql .= " WHERE rowid=".((int) $this->id);
  870. dol_syslog(get_class($this)."::delete sql=".$sql);
  871. $resql = $this->db->query($sql);
  872. if (!$resql) {
  873. $error++;
  874. $this->errors[] = "Error ".$this->db->lasterror();
  875. }
  876. }
  877. // Commit or rollback
  878. if ($error) {
  879. foreach ($this->errors as $errmsg) {
  880. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  881. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  882. }
  883. $this->db->rollback();
  884. return -1 * $error;
  885. } else {
  886. $this->db->commit();
  887. return 1;
  888. }
  889. }
  890. /**
  891. * Load an object from its id and create a new one in database
  892. *
  893. * @param User $user User that clone
  894. * @param int $fromid Id of object to clone
  895. * @return int New id of clone
  896. */
  897. public function createFromClone(User $user, $fromid)
  898. {
  899. $error = 0;
  900. $object = new Ticket($this->db);
  901. $this->db->begin();
  902. // Load source object
  903. $object->fetch($fromid);
  904. $object->id = 0;
  905. $object->statut = 0;
  906. // Clear fields
  907. // ...
  908. // Create clone
  909. $object->context['createfromclone'] = 'createfromclone';
  910. $result = $object->create($user);
  911. // Other options
  912. if ($result < 0) {
  913. $this->error = $object->error;
  914. $error++;
  915. }
  916. if (!$error) {
  917. }
  918. unset($object->context['createfromclone']);
  919. // End
  920. if (!$error) {
  921. $this->db->commit();
  922. return $object->id;
  923. } else {
  924. $this->db->rollback();
  925. return -1;
  926. }
  927. }
  928. /**
  929. * Initialise object with example values
  930. * Id must be 0 if object instance is a specimen
  931. *
  932. * @return int
  933. */
  934. public function initAsSpecimen()
  935. {
  936. $this->id = 0;
  937. $this->entity = 1;
  938. $this->ref = 'TI0501-001';
  939. $this->track_id = 'XXXXaaaa';
  940. $this->origin_email = 'email@email.com';
  941. $this->fk_project = 1;
  942. $this->fk_user_create = 1;
  943. $this->fk_user_assign = 1;
  944. $this->subject = 'Subject of ticket';
  945. $this->message = 'Message of ticket';
  946. $this->status = 0;
  947. $this->resolution = '1';
  948. $this->progress = '10';
  949. $this->timing = '30';
  950. $this->type_code = 'TYPECODE';
  951. $this->category_code = 'CATEGORYCODE';
  952. $this->severity_code = 'SEVERITYCODE';
  953. $this->datec = '';
  954. $this->date_read = '';
  955. $this->date_close = '';
  956. $this->tms = '';
  957. return 1;
  958. }
  959. /**
  960. * Print selected status
  961. *
  962. * @param string $selected Selected status
  963. * @return void
  964. */
  965. public function printSelectStatus($selected = "")
  966. {
  967. print Form::selectarray('search_fk_statut', $this->statuts_short, $selected, $show_empty = 1, $key_in_label = 0, $value_as_key = 0, $option = '', $translate = 1, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '');
  968. }
  969. /**
  970. * Load into a cache the types of tickets (setup done into dictionaries)
  971. *
  972. * @return int Number of lines loaded, 0 if already loaded, <0 if KO
  973. */
  974. public function loadCacheTypesTickets()
  975. {
  976. global $langs;
  977. if (!empty($this->cache_types_tickets) && count($this->cache_types_tickets)) {
  978. return 0;
  979. }
  980. // Cache deja charge
  981. $sql = "SELECT rowid, code, label, use_default, pos, description";
  982. $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type";
  983. $sql .= " WHERE active > 0";
  984. $sql .= " ORDER BY pos";
  985. dol_syslog(get_class($this)."::load_cache_type_tickets sql=".$sql, LOG_DEBUG);
  986. $resql = $this->db->query($sql);
  987. if ($resql) {
  988. $num = $this->db->num_rows($resql);
  989. $i = 0;
  990. while ($i < $num) {
  991. $obj = $this->db->fetch_object($resql);
  992. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  993. $label = ($langs->trans("TicketTypeShort".$obj->code) != ("TicketTypeShort".$obj->code) ? $langs->trans("TicketTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  994. $this->cache_types_tickets[$obj->rowid]['code'] = $obj->code;
  995. $this->cache_types_tickets[$obj->rowid]['label'] = $label;
  996. $this->cache_types_tickets[$obj->rowid]['use_default'] = $obj->use_default;
  997. $this->cache_types_tickets[$obj->rowid]['pos'] = $obj->pos;
  998. $i++;
  999. }
  1000. return $num;
  1001. } else {
  1002. dol_print_error($this->db);
  1003. return -1;
  1004. }
  1005. }
  1006. /**
  1007. * Charge dans cache la liste des catégories de tickets (paramétrable dans dictionnaire)
  1008. *
  1009. * @return int Number of lines loaded, 0 if already loaded, <0 if KO
  1010. */
  1011. public function loadCacheCategoriesTickets()
  1012. {
  1013. global $langs;
  1014. if (!empty($this->cache_category_ticket) && count($this->cache_category_tickets)) {
  1015. return 0;
  1016. }
  1017. // Cache deja charge
  1018. $sql = "SELECT rowid, code, label, use_default, pos, description, public, active";
  1019. $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category";
  1020. $sql .= " WHERE active > 0";
  1021. $sql .= " ORDER BY pos";
  1022. dol_syslog(get_class($this)."::load_cache_categories_tickets sql=".$sql, LOG_DEBUG);
  1023. $resql = $this->db->query($sql);
  1024. if ($resql) {
  1025. $num = $this->db->num_rows($resql);
  1026. $i = 0;
  1027. while ($i < $num) {
  1028. $obj = $this->db->fetch_object($resql);
  1029. $this->cache_category_tickets[$obj->rowid]['code'] = $obj->code;
  1030. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1031. $label = ($langs->trans("TicketCategoryShort".$obj->code) != ("TicketCategoryShort".$obj->code) ? $langs->trans("TicketCategoryShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  1032. $this->cache_category_tickets[$obj->rowid]['label'] = $label;
  1033. $this->cache_category_tickets[$obj->rowid]['use_default'] = $obj->use_default;
  1034. $this->cache_category_tickets[$obj->rowid]['pos'] = $obj->pos;
  1035. $this->cache_category_tickets[$obj->rowid]['public'] = $obj->public;
  1036. $this->cache_category_tickets[$obj->rowid]['active'] = $obj->active;
  1037. $i++;
  1038. }
  1039. return $num;
  1040. } else {
  1041. dol_print_error($this->db);
  1042. return -1;
  1043. }
  1044. }
  1045. /**
  1046. * Charge dans cache la liste des sévérité de tickets (paramétrable dans dictionnaire)
  1047. *
  1048. * @return int Number of lines loaded, 0 if already loaded, <0 if KO
  1049. */
  1050. public function loadCacheSeveritiesTickets()
  1051. {
  1052. global $langs;
  1053. if (!empty($this->cache_severity_tickets) && count($this->cache_severity_tickets)) {
  1054. return 0;
  1055. }
  1056. // Cache deja charge
  1057. $sql = "SELECT rowid, code, label, use_default, pos, description";
  1058. $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity";
  1059. $sql .= " WHERE active > 0";
  1060. $sql .= " ORDER BY pos";
  1061. dol_syslog(get_class($this)."::loadCacheSeveritiesTickets sql=".$sql, LOG_DEBUG);
  1062. $resql = $this->db->query($sql);
  1063. if ($resql) {
  1064. $num = $this->db->num_rows($resql);
  1065. $i = 0;
  1066. while ($i < $num) {
  1067. $obj = $this->db->fetch_object($resql);
  1068. $this->cache_severity_tickets[$obj->rowid]['code'] = $obj->code;
  1069. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1070. $label = ($langs->trans("TicketSeverityShort".$obj->code) != ("TicketSeverityShort".$obj->code) ? $langs->trans("TicketSeverityShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  1071. $this->cache_severity_tickets[$obj->rowid]['label'] = $label;
  1072. $this->cache_severity_tickets[$obj->rowid]['use_default'] = $obj->use_default;
  1073. $this->cache_severity_tickets[$obj->rowid]['pos'] = $obj->pos;
  1074. $i++;
  1075. }
  1076. return $num;
  1077. } else {
  1078. dol_print_error($this->db);
  1079. return -1;
  1080. }
  1081. }
  1082. /**
  1083. * Return status label of object
  1084. *
  1085. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1086. * @return string Label
  1087. */
  1088. public function getLibStatut($mode = 0)
  1089. {
  1090. return $this->libStatut($this->fk_statut, $mode);
  1091. }
  1092. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1093. /**
  1094. * Return status label of object
  1095. *
  1096. * @param string $status Id status
  1097. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1098. * @param int $notooltip 1=No tooltip
  1099. * @return string Label
  1100. */
  1101. public function LibStatut($status, $mode = 0, $notooltip = 0)
  1102. {
  1103. // phpcs:enable
  1104. global $langs;
  1105. $labelStatus = $this->statuts[$status];
  1106. $labelStatusShort = $this->statuts_short[$status];
  1107. if ($status == self::STATUS_NOT_READ) {
  1108. $statusType = 'status0';
  1109. } elseif ($status == self::STATUS_READ) {
  1110. $statusType = 'status1';
  1111. } elseif ($status == self::STATUS_ASSIGNED) {
  1112. $statusType = 'status2';
  1113. } elseif ($status == self::STATUS_IN_PROGRESS) {
  1114. $statusType = 'status4';
  1115. } elseif ($status == self::STATUS_WAITING) {
  1116. $statusType = 'status7';
  1117. } elseif ($status == self::STATUS_NEED_MORE_INFO) {
  1118. $statusType = 'status3';
  1119. } elseif ($status == self::STATUS_CANCELED) {
  1120. $statusType = 'status9';
  1121. } elseif ($status == self::STATUS_CLOSED) {
  1122. $statusType = 'status6';
  1123. } else {
  1124. $labelStatus = $langs->trans('Unknown');
  1125. $labelStatusShort = $langs->trans('Unknown');
  1126. $statusType = 'status0';
  1127. $mode = 0;
  1128. }
  1129. $params = array();
  1130. if ($notooltip) {
  1131. $params = array('tooltip' => 'no');
  1132. }
  1133. return dolGetStatus($langs->trans($labelStatus), $langs->trans($labelStatusShort), '', $statusType, $mode, '', $params);
  1134. }
  1135. /**
  1136. * Return a link to the object card (with optionaly the picto)
  1137. *
  1138. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1139. * @param string $option On what the link point to ('nolink', ...)
  1140. * @param int $notooltip 1=Disable tooltip
  1141. * @param string $morecss Add more css on link
  1142. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1143. * @return string String with URL
  1144. */
  1145. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1146. {
  1147. global $db, $conf, $langs;
  1148. global $dolibarr_main_authentication, $dolibarr_main_demo;
  1149. global $menumanager;
  1150. if (!empty($conf->dol_no_mouse_hover)) {
  1151. $notooltip = 1; // Force disable tooltips
  1152. }
  1153. $result = '';
  1154. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Ticket").'</u>';
  1155. $label .= ' '.$this->getLibStatut(4);
  1156. $label .= '<br>';
  1157. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
  1158. $label .= '<b>'.$langs->trans('TicketTrackId').':</b> '.$this->track_id.'<br>';
  1159. $label .= '<b>'.$langs->trans('Subject').':</b> '.$this->subject;
  1160. $url = dol_buildpath('/ticket/card.php', 1).'?id='.$this->id;
  1161. if ($option != 'nolink') {
  1162. // Add param to save lastsearch_values or not
  1163. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1164. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1165. $add_save_lastsearch_values = 1;
  1166. }
  1167. if ($add_save_lastsearch_values) {
  1168. $url .= '&save_lastsearch_values=1';
  1169. }
  1170. }
  1171. $linkclose = '';
  1172. if (empty($notooltip)) {
  1173. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1174. $label = $langs->trans("ShowTicket");
  1175. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1176. }
  1177. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1178. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1179. } else {
  1180. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1181. }
  1182. $linkstart = '<a href="'.$url.'"';
  1183. $linkstart .= $linkclose.'>';
  1184. $linkend = '</a>';
  1185. $result .= $linkstart;
  1186. if ($withpicto) {
  1187. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1188. }
  1189. if ($withpicto != 2) {
  1190. $result .= $this->ref;
  1191. }
  1192. $result .= $linkend;
  1193. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1194. return $result;
  1195. }
  1196. /**
  1197. * Mark a message as read
  1198. *
  1199. * @param User $user Object user
  1200. * @param int $notrigger No trigger
  1201. * @return int <0 if KO, >0 if OK
  1202. */
  1203. public function markAsRead($user, $notrigger = 0)
  1204. {
  1205. global $conf, $langs;
  1206. $error = 0;
  1207. if ($this->statut != self::STATUS_CANCELED) { // no closed
  1208. $this->db->begin();
  1209. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
  1210. $sql .= " SET fk_statut = ".Ticket::STATUS_READ.", date_read='".$this->db->idate(dol_now())."'";
  1211. $sql .= " WHERE rowid = ".$this->id;
  1212. dol_syslog(get_class($this)."::markAsRead");
  1213. $resql = $this->db->query($sql);
  1214. if ($resql) {
  1215. $this->actionmsg = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
  1216. $this->actionmsg2 = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
  1217. if (!$error && !$notrigger) {
  1218. // Call trigger
  1219. $result = $this->call_trigger('TICKET_MODIFY', $user);
  1220. if ($result < 0) {
  1221. $error++;
  1222. }
  1223. // End call triggers
  1224. }
  1225. if (!$error) {
  1226. $this->db->commit();
  1227. return 1;
  1228. } else {
  1229. $this->db->rollback();
  1230. $this->error = join(',', $this->errors);
  1231. dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
  1232. return -1;
  1233. }
  1234. } else {
  1235. $this->db->rollback();
  1236. $this->error = $this->db->lasterror();
  1237. dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
  1238. return -1;
  1239. }
  1240. }
  1241. }
  1242. /**
  1243. * Mark a message as read
  1244. *
  1245. * @param User $user Object user
  1246. * @param int $id_assign_user ID of user assigned
  1247. * @param int $notrigger Disable trigger
  1248. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1249. */
  1250. public function assignUser($user, $id_assign_user, $notrigger = 0)
  1251. {
  1252. global $conf, $langs;
  1253. $error = 0;
  1254. $this->db->begin();
  1255. $this->oldcopy = dol_clone($this);
  1256. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
  1257. if ($id_assign_user > 0) {
  1258. $sql .= " SET fk_user_assign=".((int) $id_assign_user).", fk_statut = ".Ticket::STATUS_ASSIGNED;
  1259. } else {
  1260. $sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ;
  1261. }
  1262. $sql .= " WHERE rowid = ".$this->id;
  1263. dol_syslog(get_class($this)."::assignUser sql=".$sql);
  1264. $resql = $this->db->query($sql);
  1265. if ($resql) {
  1266. $this->fk_user_assign = $id_assign_user; // May be used by trigger
  1267. if (!$notrigger) {
  1268. // Call trigger
  1269. $result = $this->call_trigger('TICKET_ASSIGNED', $user);
  1270. if ($result < 0) {
  1271. $error++;
  1272. }
  1273. // End call triggers
  1274. }
  1275. if (!$error) {
  1276. $this->db->commit();
  1277. return 1;
  1278. } else {
  1279. $this->db->rollback();
  1280. $this->error = join(',', $this->errors);
  1281. dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
  1282. return -1;
  1283. }
  1284. } else {
  1285. $this->db->rollback();
  1286. $this->error = $this->db->lasterror();
  1287. dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
  1288. return -1;
  1289. }
  1290. }
  1291. /**
  1292. * Send notification of changes by email
  1293. *
  1294. * @param User $user User that create
  1295. * @param string $message Log message
  1296. * @return int <0 if KO, >0 if OK (number of emails sent)
  1297. */
  1298. private function sendLogByEmail($user, $message)
  1299. {
  1300. global $conf, $langs;
  1301. $nb_sent = 0;
  1302. $langs->load('ticket');
  1303. // Retrieve email of all contacts (internal and external)
  1304. $contacts = $this->listeContact(-1, 'internal');
  1305. $contacts = array_merge($contacts, $this->listeContact(-1, 'external'));
  1306. /* If origin_email and no socid, we add email to the list * */
  1307. if (!empty($this->origin_email) && empty($this->fk_soc)) {
  1308. $array_ext = array(array('firstname' => '', 'lastname' => '', 'email' => $this->origin_email, 'libelle' => $langs->transnoentities('TicketEmailOriginIssuer'), 'socid' => "-1"));
  1309. $contacts = array_merge($contacts, $array_ext);
  1310. }
  1311. if (!empty($this->fk_soc)) {
  1312. $this->fetch_thirdparty($this->fk_soc);
  1313. $array_company = array(array('firstname' => '', 'lastname' => $this->client->name, 'email' => $this->client->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->client->id));
  1314. $contacts = array_merge($contacts, $array_company);
  1315. }
  1316. // foreach contact send email with notification message
  1317. if (count($contacts) > 0) {
  1318. foreach ($contacts as $key => $info_sendto) {
  1319. $message = '';
  1320. $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNotificationEmailSubject', $this->track_id);
  1321. $message .= $langs->transnoentities('TicketNotificationEmailBody', $this->track_id)."\n\n";
  1322. $message .= $langs->transnoentities('Title').' : '.$this->subject."\n";
  1323. $recipient_name = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1');
  1324. $recipient = (!empty($recipient_name) ? $recipient_name : $info_sendto['email']).' ('.strtolower($info_sendto['libelle']).')';
  1325. $message .= $langs->transnoentities('TicketNotificationRecipient').' : '.$recipient."\n";
  1326. $message .= "\n";
  1327. $message .= '* '.$langs->transnoentities('TicketNotificationLogMessage').' *'."\n";
  1328. $message .= dol_html_entity_decode($log_message, ENT_QUOTES | ENT_HTML5)."\n";
  1329. if ($info_sendto['source'] == 'internal') {
  1330. $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$this->track_id;
  1331. $message .= "\n".$langs->transnoentities('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$this->track_id.'</a>'."\n";
  1332. } else {
  1333. $url_public_ticket = ($conf->global->TICKET_URL_PUBLIC_INTERFACE ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/' : dol_buildpath('/public/ticket/view.php', 2)).'?track_id='.$this->track_id;
  1334. $message .= "\n".$langs->transnoentities('TicketNewEmailBodyInfosTrackUrlCustomer').' : <a href="'.$url_public_ticket.'">'.$this->track_id.'</a>'."\n";
  1335. }
  1336. $message .= "\n";
  1337. $message .= $langs->transnoentities('TicketEmailPleaseDoNotReplyToThisEmail')."\n";
  1338. $from = $conf->global->MAIN_INFO_SOCIETE_NOM.'<'.$conf->global->TICKET_NOTIFICATION_EMAIL_FROM.'>';
  1339. $replyto = $from;
  1340. // Init to avoid errors
  1341. $filepath = array();
  1342. $filename = array();
  1343. $mimetype = array();
  1344. $message = dol_nl2br($message);
  1345. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  1346. $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
  1347. $conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
  1348. }
  1349. include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1350. $sendtocc = '';
  1351. $deliveryreceipt = 0;
  1352. $mailfile = new CMailFile($subject, $info_sendto['email'], $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, 0);
  1353. if ($mailfile->error || $mailfile->errors) {
  1354. setEventMessages($mailfile->error, $mailfile->errors, 'errors');
  1355. } else {
  1356. $result = $mailfile->sendfile();
  1357. if ($result > 0) {
  1358. $nb_sent++;
  1359. }
  1360. }
  1361. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  1362. $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
  1363. }
  1364. }
  1365. setEventMessages($langs->trans('TicketNotificationNumberEmailSent', $nb_sent), null, 'mesgs');
  1366. }
  1367. return $nb_sent;
  1368. }
  1369. /**
  1370. * Charge la liste des actions sur le ticket
  1371. *
  1372. * @return int Number of lines loaded, 0 if already loaded, <0 if KO
  1373. */
  1374. public function loadCacheLogsTicket()
  1375. {
  1376. global $langs;
  1377. if (is_array($this->cache_logs_ticket) && count($this->cache_logs_ticket)) {
  1378. return 0;
  1379. }
  1380. // Cache deja charge
  1381. // TODO Read the table llx_actioncomm
  1382. /*
  1383. $sql = "SELECT rowid, fk_user_create, datec, message";
  1384. $sql .= " FROM " . MAIN_DB_PREFIX . "ticket_logs";
  1385. $sql .= " WHERE fk_track_id ='" . $this->db->escape($this->track_id) . "'";
  1386. $sql .= " ORDER BY datec DESC";
  1387. $resql = $this->db->query($sql);
  1388. if ($resql) {
  1389. $num = $this->db->num_rows($resql);
  1390. $i = 0;
  1391. while ($i < $num) {
  1392. $obj = $this->db->fetch_object($resql);
  1393. $this->cache_logs_ticket[$i]['id'] = $obj->rowid;
  1394. $this->cache_logs_ticket[$i]['fk_user_create'] = $obj->fk_user_create;
  1395. $this->cache_logs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
  1396. $this->cache_logs_ticket[$i]['message'] = $obj->message;
  1397. $i++;
  1398. }
  1399. return $num;
  1400. } else {
  1401. $this->error = "Error " . $this->db->lasterror();
  1402. dol_syslog(get_class($this) . "::loadCacheLogsTicket " . $this->error, LOG_ERR);
  1403. return -1;
  1404. }*/
  1405. return 0;
  1406. }
  1407. /**
  1408. * Add message into database
  1409. *
  1410. * @param User $user User that creates
  1411. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1412. * @param array $filename_list List of files to attach (full path of filename on file system)
  1413. * @param array $mimetype_list List of MIME type of attached files
  1414. * @param array $mimefilename_list List of attached file name in message
  1415. * @return int <0 if KO, >0 if OK
  1416. */
  1417. public function createTicketMessage($user, $notrigger = 0, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array())
  1418. {
  1419. global $conf, $langs;
  1420. $error = 0;
  1421. $now = dol_now();
  1422. // Clean parameters
  1423. if (isset($this->fk_track_id)) {
  1424. $this->fk_track_id = trim($this->fk_track_id);
  1425. }
  1426. if (isset($this->message)) {
  1427. $this->message = trim($this->message);
  1428. }
  1429. $this->db->begin();
  1430. // Insert entry into agenda with code 'TICKET_MSG'
  1431. include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  1432. $actioncomm = new ActionComm($this->db);
  1433. $actioncomm->type_code = 'AC_OTH';
  1434. $actioncomm->code = 'TICKET_MSG';
  1435. if ($this->private) {
  1436. $actioncomm->code = 'TICKET_MSG_PRIVATE';
  1437. }
  1438. $actioncomm->socid = $this->socid;
  1439. $actioncomm->label = $this->subject;
  1440. $actioncomm->note_private = $this->message;
  1441. $actioncomm->userassigned = array($user->id);
  1442. $actioncomm->userownerid = $user->id;
  1443. $actioncomm->datep = $now;
  1444. $actioncomm->percentage = 100;
  1445. $actioncomm->elementtype = 'ticket';
  1446. $actioncomm->fk_element = $this->id;
  1447. $attachedfiles = array();
  1448. $attachedfiles['paths'] = $filename_list;
  1449. $attachedfiles['names'] = $mimefilename_list;
  1450. $attachedfiles['mimes'] = $mimetype_list;
  1451. if (is_array($attachedfiles) && count($attachedfiles) > 0) {
  1452. $actioncomm->attachedfiles = $attachedfiles;
  1453. }
  1454. if (!empty($mimefilename_list) && is_array($mimefilename_list)) {
  1455. $actioncomm->note_private = dol_concatdesc($actioncomm->note_private, "\n".$langs->transnoentities("AttachedFiles").': '.join(';', $mimefilename_list));
  1456. }
  1457. $actionid = $actioncomm->create($user);
  1458. if ($actionid <= 0) {
  1459. $error++;
  1460. $this->error = $actioncomm->error;
  1461. $this->errors = $actioncomm->errors;
  1462. }
  1463. // Commit or rollback
  1464. if ($error) {
  1465. $this->db->rollback();
  1466. return -1 * $error;
  1467. } else {
  1468. $this->db->commit();
  1469. return 1;
  1470. }
  1471. }
  1472. /**
  1473. * Load the list of event on ticket into ->cache_msgs_ticket
  1474. *
  1475. * @return int Number of lines loaded, 0 if already loaded, <0 if KO
  1476. */
  1477. public function loadCacheMsgsTicket()
  1478. {
  1479. if (is_array($this->cache_msgs_ticket) && count($this->cache_msgs_ticket)) {
  1480. return 0;
  1481. }
  1482. // Cache already loaded
  1483. $sql = "SELECT id as rowid, fk_user_author, datec, label, note as message, code";
  1484. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm";
  1485. $sql .= " WHERE fk_element = ".(int) $this->id;
  1486. $sql .= " AND elementtype = 'ticket'";
  1487. $sql .= " ORDER BY datec DESC";
  1488. dol_syslog(get_class($this)."::load_cache_actions_ticket sql=".$sql, LOG_DEBUG);
  1489. $resql = $this->db->query($sql);
  1490. if ($resql) {
  1491. $num = $this->db->num_rows($resql);
  1492. $i = 0;
  1493. while ($i < $num) {
  1494. $obj = $this->db->fetch_object($resql);
  1495. $this->cache_msgs_ticket[$i]['id'] = $obj->rowid;
  1496. $this->cache_msgs_ticket[$i]['fk_user_author'] = $obj->fk_user_author;
  1497. $this->cache_msgs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
  1498. $this->cache_msgs_ticket[$i]['subject'] = $obj->label;
  1499. $this->cache_msgs_ticket[$i]['message'] = $obj->message;
  1500. $this->cache_msgs_ticket[$i]['private'] = ($obj->code == 'TICKET_MSG_PRIVATE' ? 1 : 0);
  1501. $i++;
  1502. }
  1503. return $num;
  1504. } else {
  1505. $this->error = "Error ".$this->db->lasterror();
  1506. dol_syslog(get_class($this)."::load_cache_actions_ticket ".$this->error, LOG_ERR);
  1507. return -1;
  1508. }
  1509. }
  1510. /**
  1511. * Close a ticket
  1512. *
  1513. * @param User $user User that close
  1514. * @return int <0 if KO, >0 if OK
  1515. */
  1516. public function close(User $user)
  1517. {
  1518. global $conf, $langs;
  1519. if ($this->fk_statut != Ticket::STATUS_CLOSED) { // not closed
  1520. $this->db->begin();
  1521. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
  1522. $sql .= " SET fk_statut=".Ticket::STATUS_CLOSED.", progress=100, date_close='".$this->db->idate(dol_now())."'";
  1523. $sql .= " WHERE rowid = ".$this->id;
  1524. dol_syslog(get_class($this)."::close sql=".$sql);
  1525. $resql = $this->db->query($sql);
  1526. if ($resql) {
  1527. $error = 0;
  1528. // Valid and close fichinter linked
  1529. if (!empty($conf->ficheinter->enabled) && !empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) {
  1530. dol_syslog("We have closed the ticket, so we close all linked interventions");
  1531. $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter');
  1532. if ($this->linkedObjectsIds) {
  1533. foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) {
  1534. $fichinter = new Fichinter($this->db);
  1535. $fichinter->fetch($fichinter_id);
  1536. if ($fichinter->statut == 0) {
  1537. $result = $fichinter->setValid($user);
  1538. if (!$result) {
  1539. $this->errors[] = $fichinter->error;
  1540. $error++;
  1541. }
  1542. }
  1543. if ($fichinter->statut < 3) {
  1544. $result = $fichinter->setStatut(3);
  1545. if (!$result) {
  1546. $this->errors[] = $fichinter->error;
  1547. $error++;
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. // Call trigger
  1554. $result = $this->call_trigger('TICKET_CLOSE', $user);
  1555. if ($result < 0) {
  1556. $error++;
  1557. }
  1558. // End call triggers
  1559. if (!$error) {
  1560. $this->db->commit();
  1561. return 1;
  1562. } else {
  1563. $this->db->rollback();
  1564. $this->error = join(',', $this->errors);
  1565. dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
  1566. return -1;
  1567. }
  1568. } else {
  1569. $this->db->rollback();
  1570. $this->error = $this->db->lasterror();
  1571. dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
  1572. return -1;
  1573. }
  1574. }
  1575. }
  1576. /**
  1577. * Search and fetch thirparties by email
  1578. *
  1579. * @param string $email Email
  1580. * @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
  1581. * @param array $filters Array of couple field name/value to filter the companies with the same name
  1582. * @param string $clause Clause for filters
  1583. * @return array Array of thirdparties object
  1584. */
  1585. public function searchSocidByEmail($email, $type = '0', $filters = array(), $clause = 'AND')
  1586. {
  1587. $thirdparties = array();
  1588. $exact = 0;
  1589. // Generation requete recherche
  1590. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
  1591. $sql .= " WHERE entity IN (".getEntity('ticket', 1).")";
  1592. if (!empty($type)) {
  1593. if ($type == 1 || $type == 2) {
  1594. $sql .= " AND client = ".((int) $type);
  1595. } elseif ($type == 3) {
  1596. $sql .= " AND fournisseur = 1";
  1597. }
  1598. }
  1599. if (!empty($email)) {
  1600. if (empty($exact)) {
  1601. $regs = array();
  1602. if (preg_match('/^([\*])?[^*]+([\*])?$/', $email, $regs) && count($regs) > 1) {
  1603. $email = str_replace('*', '%', $email);
  1604. } else {
  1605. $email = '%'.$email.'%';
  1606. }
  1607. }
  1608. $sql .= " AND ";
  1609. if (is_array($filters) && !empty($filters)) {
  1610. $sql .= "(";
  1611. }
  1612. $sql .= "email LIKE '".$this->db->escape($email)."'";
  1613. }
  1614. if (is_array($filters) && !empty($filters)) {
  1615. foreach ($filters as $field => $value) {
  1616. $sql .= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
  1617. }
  1618. if (!empty($email)) {
  1619. $sql .= ")";
  1620. }
  1621. }
  1622. $res = $this->db->query($sql);
  1623. if ($res) {
  1624. while ($rec = $this->db->fetch_array($res)) {
  1625. $soc = new Societe($this->db);
  1626. $soc->fetch($rec['rowid']);
  1627. $thirdparties[] = $soc;
  1628. }
  1629. return $thirdparties;
  1630. } else {
  1631. $this->error = $this->db->error().' sql='.$sql;
  1632. dol_syslog(get_class($this)."::searchSocidByEmail ".$this->error, LOG_ERR);
  1633. return -1;
  1634. }
  1635. }
  1636. /**
  1637. * Search and fetch contacts by email
  1638. *
  1639. * @param string $email Email
  1640. * @param array $socid Limit to a thirdparty
  1641. * @param string $case Respect case
  1642. * @return array Array of contacts object
  1643. */
  1644. public function searchContactByEmail($email, $socid = '', $case = '')
  1645. {
  1646. $contacts = array();
  1647. // Generation requete recherche
  1648. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople";
  1649. $sql .= " WHERE entity IN (".getEntity('socpeople').")";
  1650. if (!empty($socid)) {
  1651. $sql .= " AND fk_soc='".$this->db->escape($socid)."'";
  1652. }
  1653. if (!empty($email)) {
  1654. $sql .= " AND ";
  1655. if (!$case) {
  1656. $sql .= "email LIKE '".$this->db->escape($email)."'";
  1657. } else {
  1658. $sql .= "email LIKE BINARY '".$this->db->escape($email)."'";
  1659. }
  1660. }
  1661. $res = $this->db->query($sql);
  1662. if ($res) {
  1663. while ($rec = $this->db->fetch_array($res)) {
  1664. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1665. $contactstatic = new Contact($this->db);
  1666. $contactstatic->fetch($rec['rowid']);
  1667. $contacts[] = $contactstatic;
  1668. }
  1669. return $contacts;
  1670. } else {
  1671. $this->error = $this->db->error().' sql='.$sql;
  1672. dol_syslog(get_class($this)."::searchContactByEmail ".$this->error, LOG_ERR);
  1673. return -1;
  1674. }
  1675. }
  1676. /**
  1677. * Define parent commany of current ticket
  1678. *
  1679. * @param int $id Id of thirdparty to set or '' to remove
  1680. * @return int <0 if KO, >0 if OK
  1681. */
  1682. public function setCustomer($id)
  1683. {
  1684. if ($this->id) {
  1685. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
  1686. $sql .= " SET fk_soc = ".($id > 0 ? $id : "null");
  1687. $sql .= " WHERE rowid = ".$this->id;
  1688. dol_syslog(get_class($this).'::setCustomer sql='.$sql);
  1689. $resql = $this->db->query($sql);
  1690. if ($resql) {
  1691. return 1;
  1692. } else {
  1693. return -1;
  1694. }
  1695. } else {
  1696. return -1;
  1697. }
  1698. }
  1699. /**
  1700. * Define progression of current ticket
  1701. *
  1702. * @param int $percent Progression percent
  1703. * @return int <0 if KO, >0 if OK
  1704. */
  1705. public function setProgression($percent)
  1706. {
  1707. if ($this->id) {
  1708. $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
  1709. $sql .= " SET progress = ".($percent > 0 ? $percent : "null");
  1710. $sql .= " WHERE rowid = ".$this->id;
  1711. dol_syslog(get_class($this).'::set_progression sql='.$sql);
  1712. $resql = $this->db->query($sql);
  1713. if ($resql) {
  1714. return 1;
  1715. } else {
  1716. return -1;
  1717. }
  1718. } else {
  1719. return -1;
  1720. }
  1721. }
  1722. /**
  1723. * Link element with a project
  1724. * Override core function because of key name 'fk_project' used for this module
  1725. *
  1726. * @param int $projectid Project id to link element to
  1727. * @return int <0 if KO, >0 if OK
  1728. */
  1729. public function setProject($projectid)
  1730. {
  1731. if (!$this->table_element) {
  1732. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1733. return -1;
  1734. }
  1735. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1736. if ($projectid) {
  1737. $sql .= ' SET fk_project = '.((int) $projectid);
  1738. } else {
  1739. $sql .= ' SET fk_project = NULL';
  1740. }
  1741. $sql .= ' WHERE rowid = '.((int) $this->id);
  1742. dol_syslog(get_class($this)."::setProject sql=".$sql);
  1743. if ($this->db->query($sql)) {
  1744. $this->fk_project = ((int) $projectid);
  1745. return 1;
  1746. } else {
  1747. dol_print_error($this->db);
  1748. return -1;
  1749. }
  1750. }
  1751. /**
  1752. * Link element with a contract
  1753. *
  1754. * @param int $contractid Contract id to link element to
  1755. * @return int <0 if KO, >0 if OK
  1756. */
  1757. public function setContract($contractid)
  1758. {
  1759. if (!$this->table_element) {
  1760. dol_syslog(get_class($this)."::setContract was called on objet with property table_element not defined", LOG_ERR);
  1761. return -1;
  1762. }
  1763. $result = $this->add_object_linked('contrat', $contractid);
  1764. if ($result) {
  1765. $this->fk_contract = $contractid;
  1766. return 1;
  1767. } else {
  1768. dol_print_error($this->db);
  1769. return -1;
  1770. }
  1771. }
  1772. /* gestion des contacts d'un ticket */
  1773. /**
  1774. * Return id des contacts interne de suivi
  1775. *
  1776. * @return array Liste des id contacts suivi ticket
  1777. */
  1778. public function getIdTicketInternalContact()
  1779. {
  1780. return $this->getIdContact('internal', 'SUPPORTTEC');
  1781. }
  1782. /**
  1783. * Retrieve informations about internal contacts
  1784. *
  1785. * @return array Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status
  1786. */
  1787. public function getInfosTicketInternalContact()
  1788. {
  1789. return $this->listeContact(-1, 'internal');
  1790. }
  1791. /**
  1792. * Return id des contacts clients pour le suivi ticket
  1793. *
  1794. * @return array Liste des id contacts suivi ticket
  1795. */
  1796. public function getIdTicketCustomerContact()
  1797. {
  1798. return $this->getIdContact('external', 'SUPPORTCLI');
  1799. }
  1800. /**
  1801. * Retrieve informations about external contacts
  1802. *
  1803. * @return array Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status
  1804. */
  1805. public function getInfosTicketExternalContact()
  1806. {
  1807. return $this->listeContact(-1, 'external');
  1808. }
  1809. /**
  1810. * Return id des contacts clients des intervenants
  1811. *
  1812. * @return array Liste des id contacts intervenants
  1813. */
  1814. public function getIdTicketInternalInvolvedContact()
  1815. {
  1816. return $this->getIdContact('internal', 'CONTRIBUTOR');
  1817. }
  1818. /**
  1819. * Return id des contacts clients des intervenants
  1820. *
  1821. * @return array Liste des id contacts intervenants
  1822. */
  1823. public function getIdTicketCustomerInvolvedContact()
  1824. {
  1825. return $this->getIdContact('external', 'CONTRIBUTOR');
  1826. }
  1827. /**
  1828. * Return id of all contacts for ticket
  1829. *
  1830. * @return array Array of contacts for tickets
  1831. */
  1832. public function getTicketAllContacts()
  1833. {
  1834. $array_contact = array();
  1835. $array_contact = $this->getIdTicketInternalContact($exclude_self);
  1836. $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self));
  1837. $array_contact = array_merge($array_contact, $this->getIdTicketInternalInvolvedContact($exclude_self));
  1838. $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self));
  1839. return $array_contact;
  1840. }
  1841. /**
  1842. * Return id of all contacts for ticket
  1843. *
  1844. * @return array Array of contacts
  1845. */
  1846. public function getTicketAllCustomerContacts()
  1847. {
  1848. $array_contact = array();
  1849. $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self));
  1850. $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self));
  1851. return $array_contact;
  1852. }
  1853. /**
  1854. * Send message
  1855. *
  1856. * @param string $subject Subject
  1857. * @param string $texte Message to send
  1858. * @return int <0 if KO, or number of changes if OK
  1859. */
  1860. public function messageSend($subject, $texte)
  1861. {
  1862. global $conf, $langs, $mysoc, $dolibarr_main_url_root;
  1863. $langs->load("other");
  1864. dol_syslog(get_class($this)."::message_send action=$action, socid=$socid, texte=$texte, objet_type=$objet_type, objet_id=$objet_id, file=$file");
  1865. $internal_contacts = $this->getIdContact('internal', 'SUPPORTTEC');
  1866. $external_contacts = $this->getIdContact('external', 'SUPPORTTEC');
  1867. if ($result) {
  1868. $num = $this->db->num_rows($result);
  1869. $i = 0;
  1870. while ($i < $num) { // For each notification couple defined (third party/actioncode)
  1871. $obj = $this->db->fetch_object($result);
  1872. $sendto = $obj->firstname." ".$obj->lastname." <".$obj->email.">";
  1873. $actiondefid = $obj->adid;
  1874. if (dol_strlen($sendto)) {
  1875. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1876. $application = ($conf->global->MAIN_APPLICATION_TITLE ? $conf->global->MAIN_APPLICATION_TITLE : 'Dolibarr ERP/CRM');
  1877. $subject = '['.$application.'] '.$langs->transnoentitiesnoconv("DolibarrNotification");
  1878. $message = $langs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name)."\n";
  1879. $message .= $langs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name)."\n";
  1880. $message .= "\n";
  1881. $message .= $texte;
  1882. // Add link
  1883. $link = '';
  1884. switch ($objet_type) {
  1885. case 'ficheinter':
  1886. $link = '/fichinter/card.php?id='.$objet_id;
  1887. break;
  1888. case 'propal':
  1889. $link = '/comm/propal.php?id='.$objet_id;
  1890. break;
  1891. case 'facture':
  1892. $link = '/compta/facture/card.php?facid='.$objet_id;
  1893. break;
  1894. case 'order':
  1895. $link = '/commande/card.php?facid='.$objet_id;
  1896. break;
  1897. case 'order_supplier':
  1898. $link = '/fourn/commande/card.php?facid='.$objet_id;
  1899. break;
  1900. }
  1901. // Define $urlwithroot
  1902. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1903. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1904. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1905. if ($link) {
  1906. $message .= "\n".$urlwithroot.$link;
  1907. }
  1908. $filename = basename($file);
  1909. $mimefile = dol_mimetype($file);
  1910. $msgishtml = 0;
  1911. $replyto = $conf->notification->email_from;
  1912. $message = dol_nl2br($message);
  1913. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  1914. $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
  1915. $conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
  1916. }
  1917. $mailfile = new CMailFile(
  1918. $subject,
  1919. $sendto,
  1920. $replyto,
  1921. $message,
  1922. array($file),
  1923. array($mimefile),
  1924. array($filename[count($filename) - 1]),
  1925. '',
  1926. '',
  1927. 0,
  1928. $msgishtml
  1929. );
  1930. if ($mailfile->sendfile()) {
  1931. $now = dol_now();
  1932. $sendto = htmlentities($sendto);
  1933. $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_contact, objet_type, objet_id, email)";
  1934. $sql .= " VALUES ('".$this->db->idate($now)."', ".$actiondefid.", ".$obj->cid.", '".$this->db->escape($objet_type)."', ".$objet_id.", '".$this->db->escape($obj->email)."')";
  1935. dol_syslog("Notify::send sql=".$sql);
  1936. if (!$this->db->query($sql)) {
  1937. dol_print_error($this->db);
  1938. }
  1939. } else {
  1940. $this->error = $mailfile->error;
  1941. //dol_syslog("Notify::send ".$this->error, LOG_ERR);
  1942. }
  1943. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  1944. $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
  1945. }
  1946. }
  1947. $i++;
  1948. }
  1949. return $i;
  1950. } else {
  1951. $this->error = $this->db->error();
  1952. return -1;
  1953. }
  1954. }
  1955. /**
  1956. * Get array of all contacts for a ticket
  1957. * Override method of file commonobject.class.php to add phone number
  1958. *
  1959. * @param int $status Status of lines to get (-1=all)
  1960. * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
  1961. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1962. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1963. * @return array Array of contacts
  1964. */
  1965. public function listeContact($status = -1, $source = 'external', $list = 0, $code = '')
  1966. {
  1967. global $langs;
  1968. $tab = array();
  1969. $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
  1970. if ($source == 'internal') {
  1971. $sql .= ", '-1' as socid, t.statut as statuscontact";
  1972. }
  1973. if ($source == 'external' || $source == 'thirdparty') {
  1974. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1975. }
  1976. $sql .= ", t.civility, t.lastname as lastname, t.firstname, t.email";
  1977. if ($source == 'internal') {
  1978. $sql .= ", t.office_phone as phone, t.user_mobile as phone_mobile";
  1979. }
  1980. if ($source == 'external') {
  1981. $sql .= ", t.phone as phone, t.phone_mobile as phone_mobile, t.phone_perso as phone_perso";
  1982. }
  1983. $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_contact_label";
  1984. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1985. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1986. if ($source == 'internal') {
  1987. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1988. }
  1989. if ($source == 'external' || $source == 'thirdparty') {
  1990. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1991. }
  1992. $sql .= " WHERE ec.element_id =".$this->id;
  1993. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1994. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1995. if ($source == 'internal') {
  1996. $sql .= " AND tc.source = 'internal'";
  1997. }
  1998. if ($source == 'external' || $source == 'thirdparty') {
  1999. $sql .= " AND tc.source = 'external'";
  2000. }
  2001. $sql .= " AND tc.active=1";
  2002. if ($status >= 0) {
  2003. $sql .= " AND ec.statut = ".((int) $status);
  2004. }
  2005. $sql .= " ORDER BY t.lastname ASC";
  2006. $resql = $this->db->query($sql);
  2007. if ($resql) {
  2008. $num = $this->db->num_rows($resql);
  2009. $i = 0;
  2010. while ($i < $num) {
  2011. $obj = $this->db->fetch_object($resql);
  2012. if (!$list) {
  2013. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  2014. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_contact_label);
  2015. $tab[$i] = array(
  2016. 'source' => $obj->source,
  2017. 'socid' => $obj->socid,
  2018. 'id' => $obj->id,
  2019. 'nom' => $obj->lastname, // For backward compatibility
  2020. 'civility' => $obj->civility,
  2021. 'lastname' => $obj->lastname,
  2022. 'firstname' => $obj->firstname,
  2023. 'email' => $obj->email,
  2024. 'rowid' => $obj->rowid,
  2025. 'code' => $obj->code,
  2026. 'libelle' => $libelle_type,
  2027. 'status' => $obj->statuslink,
  2028. 'statuscontact'=>$obj->statuscontact,
  2029. 'fk_c_type_contact' => $obj->fk_c_type_contact,
  2030. 'phone' => $obj->phone,
  2031. 'phone_mobile' => $obj->phone_mobile);
  2032. } else {
  2033. $tab[$i] = $obj->id;
  2034. }
  2035. $i++;
  2036. }
  2037. return $tab;
  2038. } else {
  2039. $this->error = $this->db->error();
  2040. dol_print_error($this->db);
  2041. return -1;
  2042. }
  2043. }
  2044. /**
  2045. * Get a default reference.
  2046. *
  2047. * @param Societe $thirdparty Thirdparty
  2048. * @return string Reference
  2049. */
  2050. public function getDefaultRef($thirdparty = '')
  2051. {
  2052. global $conf;
  2053. $defaultref = '';
  2054. $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
  2055. // Search template files
  2056. $file = '';
  2057. $classname = '';
  2058. $filefound = 0;
  2059. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2060. foreach ($dirmodels as $reldir) {
  2061. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2062. if (file_exists($file)) {
  2063. $filefound = 1;
  2064. $classname = $modele;
  2065. break;
  2066. }
  2067. }
  2068. if ($filefound) {
  2069. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2070. $modTicket = new $classname;
  2071. $defaultref = $modTicket->getNextValue($thirdparty, $this);
  2072. }
  2073. if (is_numeric($defaultref) && $defaultref <= 0) {
  2074. $defaultref = '';
  2075. }
  2076. return $defaultref;
  2077. }
  2078. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2079. /**
  2080. * Return if at least one photo is available
  2081. *
  2082. * @param string $sdir Directory to scan
  2083. * @return boolean True if at least one photo is available, False if not
  2084. */
  2085. public function is_photo_available($sdir)
  2086. {
  2087. // phpcs:enable
  2088. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2089. global $conf;
  2090. $dir = $sdir.'/';
  2091. $nbphoto = 0;
  2092. $dir_osencoded = dol_osencode($dir);
  2093. if (file_exists($dir_osencoded)) {
  2094. $handle = opendir($dir_osencoded);
  2095. if (is_resource($handle)) {
  2096. while (($file = readdir($handle)) !== false) {
  2097. if (!utf8_check($file)) {
  2098. $file = utf8_encode($file);
  2099. }
  2100. // To be sure data is stored in UTF8 in memory
  2101. if (dol_is_file($dir.$file)) {
  2102. return true;
  2103. }
  2104. }
  2105. }
  2106. }
  2107. return false;
  2108. }
  2109. /**
  2110. * Copy files defined into $_SESSION array into the ticket directory of attached files.
  2111. * Used for files linked into messages.
  2112. * Files may be renamed during copy to avoid overwriting existing files.
  2113. *
  2114. * @return array Array with final path/name/mime of files.
  2115. */
  2116. public function copyFilesForTicket()
  2117. {
  2118. global $conf;
  2119. // Create form object
  2120. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  2121. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2122. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  2123. $maxwidthsmall = 270;
  2124. $maxheightsmall = 150;
  2125. $maxwidthmini = 128;
  2126. $maxheightmini = 72;
  2127. $formmail = new FormMail($this->db);
  2128. $attachedfiles = $formmail->get_attached_files();
  2129. $filepath = $attachedfiles['paths'];
  2130. $filename = $attachedfiles['names'];
  2131. $mimetype = $attachedfiles['mimes'];
  2132. // Copy files into ticket directory
  2133. $destdir = $conf->ticket->dir_output.'/'.$this->ref;
  2134. if (!dol_is_dir($destdir)) {
  2135. dol_mkdir($destdir);
  2136. }
  2137. $listofpaths = array();
  2138. $listofnames = array();
  2139. foreach ($filename as $i => $val) {
  2140. $destfile = $destdir.'/'.$filename[$i];
  2141. // If destination file already exists, we add a suffix to avoid to overwrite
  2142. if (is_file($destfile)) {
  2143. $pathinfo = pathinfo($filename[$i]);
  2144. $now = dol_now();
  2145. $destfile = $destdir.'/'.$pathinfo['filename'].' - '.dol_print_date($now, 'dayhourlog').'.'.$pathinfo['extension'];
  2146. }
  2147. $res = dol_move($filepath[$i], $destfile, 0, 1);
  2148. if (image_format_supported($destfile) == 1) {
  2149. // Create small thumbs for image (Ratio is near 16/9)
  2150. // Used on logon for example
  2151. $imgThumbSmall = vignette($destfile, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  2152. // Create mini thumbs for image (Ratio is near 16/9)
  2153. // Used on menu or for setup page for example
  2154. $imgThumbMini = vignette($destfile, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  2155. }
  2156. $formmail->remove_attached_files($i);
  2157. // Fill array with new names
  2158. $listofpaths[$i] = $destfile;
  2159. $listofnames[$i] = basename($destfile);
  2160. }
  2161. return array('listofpaths'=>$listofpaths, 'listofnames'=>$listofnames, 'listofmimes'=>$mimetype);
  2162. }
  2163. /**
  2164. * Add new message on a ticket (private/public area). Can also send it be email if GETPOST('send_email', 'int') is set.
  2165. *
  2166. * @param User $user User for action
  2167. * @param string $action Action string
  2168. * @param int $private 1=Message is private. TODO Implement this. What does this means ?
  2169. * @param int $public_area 1=Is the public area
  2170. * @return int
  2171. */
  2172. public function newMessage($user, &$action, $private = 1, $public_area = 0)
  2173. {
  2174. global $mysoc, $conf, $langs;
  2175. $error = 0;
  2176. $object = new Ticket($this->db);
  2177. $ret = $object->fetch('', '', GETPOST('track_id', 'alpha'));
  2178. $object->socid = $object->fk_soc;
  2179. $object->fetch_thirdparty();
  2180. if ($ret < 0) {
  2181. $error++;
  2182. array_push($this->errors, $langs->trans("ErrorTicketIsNotValid"));
  2183. $action = '';
  2184. }
  2185. if (!GETPOST("message")) {
  2186. $error++;
  2187. array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message")));
  2188. $action = 'add_message';
  2189. }
  2190. if (!$error) {
  2191. $object->subject = GETPOST('subject', 'alphanohtml');
  2192. $object->message = GETPOST("message", "restricthtml");
  2193. $object->private = GETPOST("private_message", "alpha");
  2194. $send_email = GETPOST('send_email', 'int');
  2195. // Copy attached files (saved into $_SESSION) as linked files to ticket. Return array with final name used.
  2196. $resarray = $object->copyFilesForTicket();
  2197. $listofpaths = $resarray['listofpaths'];
  2198. $listofnames = $resarray['listofnames'];
  2199. $listofmimes = $resarray['listofmimes'];
  2200. $id = $object->createTicketMessage($user, 0, $listofpaths, $listofmimes, $listofnames);
  2201. if ($id <= 0) {
  2202. $error++;
  2203. $this->error = $object->error;
  2204. $this->errors = $object->errors;
  2205. $action = 'add_message';
  2206. }
  2207. if (!$error && $id > 0) {
  2208. setEventMessages($langs->trans('TicketMessageSuccessfullyAdded'), null, 'mesgs');
  2209. //var_dump($_SESSION); var_dump($listofpaths);exit;
  2210. /*
  2211. * Public area
  2212. */
  2213. if (!empty($public_area)) {
  2214. /*
  2215. * Send emails to assigned users (public area notification)
  2216. */
  2217. if (!empty($conf->global->TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_ENABLED)) {
  2218. $assigned_user_dont_have_email = '';
  2219. $sendto = array();
  2220. if ($this->fk_user_assign > 0) {
  2221. $assigned_user = new User($this->db);
  2222. $assigned_user->fetch($this->fk_user_assign);
  2223. if (!empty($assigned_user->email)) {
  2224. $sendto[] = $assigned_user->getFullName($langs)." <".$assigned_user->email.">";
  2225. } else {
  2226. $assigned_user_dont_have_email = $assigned_user->getFullName($langs);
  2227. }
  2228. }
  2229. if (empty($sendto)) {
  2230. if (!empty($conf->global->TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL)) {
  2231. $sendto[] = $conf->global->TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL;
  2232. } elseif (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) {
  2233. $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
  2234. }
  2235. }
  2236. // Add global email address recipient
  2237. if (!empty($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS) &&
  2238. !empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO) && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)
  2239. ) {
  2240. $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
  2241. }
  2242. if (!empty($sendto)) {
  2243. $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
  2244. $subject = '['.$label_title.'- ticket #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
  2245. // Message send
  2246. $message = $langs->trans('TicketMessageMailIntroText');
  2247. $message .= '<br><br>';
  2248. $messagePost = GETPOST('message', 'restricthtml');
  2249. if (!dol_textishtml($messagePost)) {
  2250. $messagePost = dol_nl2br($messagePost);
  2251. }
  2252. $message .= $messagePost;
  2253. // Customer company infos
  2254. $message .= '<br><br>';
  2255. $message .= "==============================================";
  2256. $message .= !empty($object->thirdparty->name) ? '<br>'.$langs->trans('Thirdparty')." : ".$object->thirdparty->name : '';
  2257. $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
  2258. $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
  2259. // Email send to
  2260. $message .= '<br><br>';
  2261. if (!empty($assigned_user_dont_have_email)) {
  2262. $message .= '<br>'.$langs->trans('NoEMail').' : '.$assigned_user_dont_have_email;
  2263. }
  2264. foreach ($sendto as $val) {
  2265. $message .= '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$val;
  2266. }
  2267. // URL ticket
  2268. $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
  2269. $message .= '<br><br>';
  2270. $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a>';
  2271. $this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
  2272. }
  2273. }
  2274. } else {
  2275. /*
  2276. * Private area
  2277. */
  2278. /*
  2279. * Send emails to internal users (linked contacts)
  2280. */
  2281. if ($send_email > 0) {
  2282. // Retrieve internal contact datas
  2283. $internal_contacts = $object->getInfosTicketInternalContact();
  2284. $sendto = array();
  2285. if (is_array($internal_contacts) && count($internal_contacts) > 0) {
  2286. // altairis: set default subject
  2287. $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
  2288. $subject = GETPOST('subject', 'nohtml') ? GETPOST('subject', 'nohtml') : '['.$label_title.'- ticket #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
  2289. $message_intro = $langs->trans('TicketNotificationEmailBody', "#".$object->id);
  2290. $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
  2291. $message = $langs->trans('TicketMessageMailIntroText');
  2292. $message .= '<br><br>';
  2293. $messagePost = GETPOST('message', 'restricthtml');
  2294. if (!dol_textishtml($messagePost)) {
  2295. $messagePost = dol_nl2br($messagePost);
  2296. }
  2297. $message .= $messagePost;
  2298. // Coordonnées client
  2299. $message .= '<br><br>';
  2300. $message .= "==============================================<br>";
  2301. $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty')." : ".$object->thirdparty->name : '';
  2302. $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
  2303. $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
  2304. // Build array to display recipient list
  2305. foreach ($internal_contacts as $key => $info_sendto) {
  2306. // altairis: avoid duplicate notifications
  2307. if ($info_sendto['id'] == $user->id) {
  2308. continue;
  2309. }
  2310. if ($info_sendto['email'] != '') {
  2311. if (!empty($info_sendto['email'])) {
  2312. $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
  2313. }
  2314. //Contact type
  2315. $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
  2316. $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
  2317. }
  2318. }
  2319. $message .= '<br>';
  2320. // URL ticket
  2321. $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
  2322. // altairis: make html link on url
  2323. $message .= '<br>'.$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a><br>';
  2324. // Add global email address recipient
  2325. if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) {
  2326. if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) {
  2327. $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
  2328. }
  2329. }
  2330. // altairis: dont try to send email if no recipient
  2331. if (!empty($sendto)) {
  2332. $this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
  2333. }
  2334. }
  2335. /*
  2336. * Send emails for externals users if not private (linked contacts)
  2337. */
  2338. if (empty($object->private)) {
  2339. // Retrieve email of all contacts (external)
  2340. $external_contacts = $object->getInfosTicketExternalContact();
  2341. // If no contact, get email from thirdparty
  2342. if (is_array($external_contacts) && count($external_contacts) === 0) {
  2343. if (!empty($object->fk_soc)) {
  2344. $object->fetch_thirdparty($object->fk_soc);
  2345. $array_company = array(array('firstname' => '', 'lastname' => $object->thirdparty->name, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
  2346. $external_contacts = array_merge($external_contacts, $array_company);
  2347. } elseif (empty($object->fk_soc) && !empty($object->origin_email)) {
  2348. $array_external = array(array('firstname' => '', 'lastname' => $object->origin_email, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
  2349. $external_contacts = array_merge($external_contacts, $array_external);
  2350. }
  2351. }
  2352. $sendto = array();
  2353. if (is_array($external_contacts) && count($external_contacts) > 0) {
  2354. // altairis: get default subject for email to external contacts
  2355. $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
  2356. $subject = GETPOST('subject') ? GETPOST('subject') : '['.$label_title.'- ticket #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
  2357. $message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro', 'restricthtml') : $conf->global->TICKET_MESSAGE_MAIL_INTRO;
  2358. $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature', 'restricthtml') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
  2359. if (!dol_textishtml($message_intro)) {
  2360. $message_intro = dol_nl2br($message_intro);
  2361. }
  2362. if (!dol_textishtml($message_signature)) {
  2363. $message_signature = dol_nl2br($message_signature);
  2364. }
  2365. // We put intro after
  2366. $messagePost = GETPOST('message', 'restricthtml');
  2367. if (!dol_textishtml($messagePost)) {
  2368. $messagePost = dol_nl2br($messagePost);
  2369. }
  2370. $message = $messagePost;
  2371. $message .= '<br><br>';
  2372. foreach ($external_contacts as $key => $info_sendto) {
  2373. // altairis: avoid duplicate emails to external contacts
  2374. if ($info_sendto['id'] == $user->contact_id) {
  2375. continue;
  2376. }
  2377. if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) {
  2378. if (!empty($info_sendto['email'])) {
  2379. $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
  2380. }
  2381. $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
  2382. $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
  2383. }
  2384. }
  2385. // If public interface is not enable, use link to internal page into mail
  2386. $url_public_ticket = (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE) ?
  2387. (!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)).'?track_id='.$object->track_id;
  2388. $message .= '<br>'.$langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer').' : <a href="'.$url_public_ticket.'">'.$object->track_id.'</a><br>';
  2389. // Build final message
  2390. $message = $message_intro.'<br><br>'.$message;
  2391. // Add signature
  2392. $message .= '<br>'.$message_signature;
  2393. if (!empty($object->origin_email)) {
  2394. $sendto[] = $object->origin_email;
  2395. }
  2396. if ($object->fk_soc > 0 && !in_array($object->origin_email, $sendto)) {
  2397. $object->socid = $object->fk_soc;
  2398. $object->fetch_thirdparty();
  2399. if (!empty($object->thirdparty->email)) {
  2400. $sendto[] = $object->thirdparty->email;
  2401. }
  2402. }
  2403. // altairis: Add global email address reciepient
  2404. if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) {
  2405. if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) {
  2406. $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
  2407. }
  2408. }
  2409. // altairis: dont try to send email when no recipient
  2410. if (!empty($sendto)) {
  2411. $this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. }
  2417. // Set status to "answered" if not set yet, but only if internal user
  2418. if ($object->fk_statut < 3 && !$user->socid) {
  2419. $object->setStatut(3);
  2420. }
  2421. return 1;
  2422. } else {
  2423. setEventMessages($object->error, $object->errors, 'errors');
  2424. return -1;
  2425. }
  2426. } else {
  2427. setEventMessages($this->error, $this->errors, 'errors');
  2428. return -1;
  2429. }
  2430. }
  2431. /**
  2432. * Send ticket by email to linked contacts
  2433. *
  2434. * @param string $subject Email subject
  2435. * @param string $message Email message
  2436. * @param int $send_internal_cc Receive a copy on internal email ($conf->global->TICKET_NOTIFICATION_EMAIL_FROM)
  2437. * @param array $array_receiver Array of receiver. exemple array('name' => 'John Doe', 'email' => 'john@doe.com', etc...)
  2438. * @param array $filename_list List of files to attach (full path of filename on file system)
  2439. * @param array $mimetype_list List of MIME type of attached files
  2440. * @param array $mimefilename_list List of attached file name in message
  2441. * @return void
  2442. */
  2443. public function sendTicketMessageByEmail($subject, $message, $send_internal_cc = 0, $array_receiver = array(), $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array())
  2444. {
  2445. global $conf, $langs;
  2446. if ($conf->global->TICKET_DISABLE_ALL_MAILS) {
  2447. dol_syslog(get_class($this).'::sendTicketMessageByEmail: Emails are disable into ticket setup by option TICKET_DISABLE_ALL_MAILS', LOG_WARNING);
  2448. return '';
  2449. }
  2450. $langs->load("mails");
  2451. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  2452. //$contactstatic = new Contact($this->db);
  2453. // If no receiver defined, load all ticket linked contacts
  2454. if (!is_array($array_receiver) || !count($array_receiver) > 0) {
  2455. $array_receiver = $this->getInfosTicketInternalContact();
  2456. $array_receiver = array_merge($array_receiver, $this->getInfosTicketExternalContact());
  2457. }
  2458. if ($send_internal_cc) {
  2459. $sendtocc = $conf->global->TICKET_NOTIFICATION_EMAIL_FROM;
  2460. }
  2461. $from = $conf->global->TICKET_NOTIFICATION_EMAIL_FROM;
  2462. if (is_array($array_receiver) && count($array_receiver) > 0) {
  2463. foreach ($array_receiver as $key => $receiver) {
  2464. $deliveryreceipt = 0;
  2465. $filepath = $filename_list;
  2466. $filename = $mimefilename_list;
  2467. $mimetype = $mimetype_list;
  2468. // Envoi du mail
  2469. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  2470. $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
  2471. $conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
  2472. }
  2473. include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  2474. $trackid = "tic".$this->id;
  2475. $mailfile = new CMailFile($subject, $receiver, $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1, '', '', $trackid, '', 'ticket');
  2476. if ($mailfile->error) {
  2477. setEventMessages($mailfile->error, null, 'errors');
  2478. } else {
  2479. $result = $mailfile->sendfile();
  2480. if ($result) {
  2481. setEventMessages($langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($receiver, 2)), null, 'mesgs');
  2482. } else {
  2483. $langs->load("other");
  2484. if ($mailfile->error) {
  2485. setEventMessages($langs->trans('ErrorFailedToSendMail', $from, $receiver), null, 'errors');
  2486. dol_syslog($langs->trans('ErrorFailedToSendMail', $from, $receiver).' : '.$mailfile->error);
  2487. } else {
  2488. setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'errors');
  2489. }
  2490. }
  2491. }
  2492. if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
  2493. $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
  2494. }
  2495. }
  2496. } else {
  2497. $langs->load("other");
  2498. setEventMessages($langs->trans('ErrorMailRecipientIsEmptyForSendTicketMessage'), null, 'warnings');
  2499. }
  2500. }
  2501. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2502. /**
  2503. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2504. *
  2505. * @param User $user Object user
  2506. * @param int $mode "opened" for askprice to close, "signed" for proposal to invoice
  2507. * @return int <0 if KO, >0 if OK
  2508. */
  2509. public function load_board($user, $mode)
  2510. {
  2511. // phpcs:enable
  2512. global $conf, $user, $langs;
  2513. $now = dol_now();
  2514. $delay_warning = 0;
  2515. $this->nbtodo = $this->nbtodolate = 0;
  2516. $clause = " WHERE";
  2517. $sql = "SELECT p.rowid, p.ref, p.datec as datec";
  2518. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
  2519. if ($conf->societe->enabled && !$user->rights->societe->client->voir && !$user->socid) {
  2520. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
  2521. $sql .= " WHERE sc.fk_user = ".$user->id;
  2522. $clause = " AND";
  2523. }
  2524. $sql .= $clause." p.entity IN (".getEntity('ticket').")";
  2525. if ($mode == 'opened') {
  2526. $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")";
  2527. }
  2528. if ($user->socid) {
  2529. $sql .= " AND p.fk_soc = ".$user->socid;
  2530. }
  2531. $resql = $this->db->query($sql);
  2532. if ($resql) {
  2533. $label = $labelShort = '';
  2534. $status = '';
  2535. if ($mode == 'opened') {
  2536. $status = 'openall';
  2537. //$delay_warning = $conf->ticket->warning_delay;
  2538. $delay_warning = 0;
  2539. $label = $langs->trans("MenuListNonClosed");
  2540. $labelShort = $langs->trans("MenuListNonClosed");
  2541. }
  2542. $response = new WorkboardResponse();
  2543. //$response->warning_delay = $delay_warning / 60 / 60 / 24;
  2544. $response->label = $label;
  2545. $response->labelShort = $labelShort;
  2546. $response->url = DOL_URL_ROOT.'/ticket/list.php?search_fk_statut[]='.$status;
  2547. $response->img = img_object('', "ticket");
  2548. // This assignment in condition is not a bug. It allows walking the results.
  2549. while ($obj = $this->db->fetch_object($resql)) {
  2550. $response->nbtodo++;
  2551. if ($mode == 'opened') {
  2552. $datelimit = $this->db->jdate($obj->datec) + $delay_warning;
  2553. if ($datelimit < $now) {
  2554. //$response->nbtodolate++;
  2555. }
  2556. }
  2557. }
  2558. return $response;
  2559. } else {
  2560. $this->error = $this->db->lasterror();
  2561. return -1;
  2562. }
  2563. }
  2564. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2565. /**
  2566. * Load indicator this->nb of global stats widget
  2567. *
  2568. * @return int <0 if ko, >0 if ok
  2569. */
  2570. public function load_state_board()
  2571. {
  2572. // phpcs:enable
  2573. global $conf, $user;
  2574. $this->nb = array();
  2575. $clause = "WHERE";
  2576. $sql = "SELECT count(p.rowid) as nb";
  2577. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
  2578. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
  2579. if (!$user->rights->societe->client->voir && !$user->socid) {
  2580. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  2581. $sql .= " WHERE sc.fk_user = ".$user->id;
  2582. $clause = "AND";
  2583. }
  2584. $sql .= " ".$clause." p.entity IN (".getEntity('ticket').")";
  2585. $resql = $this->db->query($sql);
  2586. if ($resql) {
  2587. // This assignment in condition is not a bug. It allows walking the results.
  2588. while ($obj = $this->db->fetch_object($resql)) {
  2589. $this->nb["ticket"] = $obj->nb;
  2590. }
  2591. $this->db->free($resql);
  2592. return 1;
  2593. } else {
  2594. dol_print_error($this->db);
  2595. $this->error = $this->db->lasterror();
  2596. return -1;
  2597. }
  2598. }
  2599. /**
  2600. * Function used to replace a thirdparty id with another one.
  2601. *
  2602. * @param DoliDB $db Database handler
  2603. * @param int $origin_id Old thirdparty id
  2604. * @param int $dest_id New thirdparty id
  2605. * @return bool
  2606. */
  2607. public static function replaceThirdparty($db, $origin_id, $dest_id)
  2608. {
  2609. $tables = array('ticket');
  2610. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  2611. }
  2612. }
  2613. /**
  2614. * Ticket line Class
  2615. */
  2616. class TicketsLine
  2617. {
  2618. /**
  2619. * @var int ID
  2620. * @deprecated
  2621. */
  2622. public $rowid;
  2623. /**
  2624. * @var int ID
  2625. */
  2626. public $id;
  2627. /**
  2628. * @var string $ref Ticket reference
  2629. */
  2630. public $ref;
  2631. /**
  2632. * Hash to identify ticket
  2633. */
  2634. public $track_id;
  2635. /**
  2636. * @var int Thirdparty ID
  2637. */
  2638. public $fk_soc;
  2639. /**
  2640. * Project ID
  2641. */
  2642. public $fk_project;
  2643. /**
  2644. * Person email who have create ticket
  2645. */
  2646. public $origin_email;
  2647. /**
  2648. * User id who have create ticket
  2649. */
  2650. public $fk_user_create;
  2651. /**
  2652. * User id who have ticket assigned
  2653. */
  2654. public $fk_user_assign;
  2655. /**
  2656. * Ticket subject
  2657. */
  2658. public $subject;
  2659. /**
  2660. * Ticket message
  2661. */
  2662. public $message;
  2663. /**
  2664. * Ticket statut
  2665. */
  2666. public $fk_statut;
  2667. /**
  2668. * State resolution
  2669. */
  2670. public $resolution;
  2671. /**
  2672. * Progress in percent
  2673. */
  2674. public $progress;
  2675. /**
  2676. * Duration for ticket
  2677. */
  2678. public $timing;
  2679. /**
  2680. * Type code
  2681. */
  2682. public $type_code;
  2683. /**
  2684. * Category code
  2685. */
  2686. public $category_code;
  2687. /**
  2688. * Severity code
  2689. */
  2690. public $severity_code;
  2691. /**
  2692. * Type label
  2693. */
  2694. public $type_label;
  2695. /**
  2696. * Category label
  2697. */
  2698. public $category_label;
  2699. /**
  2700. * Severity label
  2701. */
  2702. public $severity_label;
  2703. /**
  2704. * Creation date
  2705. */
  2706. public $datec = '';
  2707. /**
  2708. * Read date
  2709. */
  2710. public $date_read = '';
  2711. /**
  2712. * Close ticket date
  2713. */
  2714. public $date_close = '';
  2715. }