ticket.class.php 101 KB

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