ticket.class.php 102 KB

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