ticket.class.php 106 KB

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