ticket.class.php 104 KB

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