PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/HelpDesk/HelpDesk.php

https://bitbucket.org/yousef_fadila/vtiger
PHP | 834 lines | 603 code | 101 blank | 130 comment | 106 complexity | 8c528f76014fafb1af6afcba9a6d2b12 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. /*********************************************************************************
  3. * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
  4. * ("License"); You may not use this file except in compliance with the
  5. * License. You may obtain a copy of txhe License at http://www.sugarcrm.com/SPL
  6. * Software distributed under the License is distributed on an "AS IS" basis,
  7. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
  8. * the specific language governing rights and limitations under the License.
  9. * The Original Code is: SugarCRM Open Source
  10. * The Initial Developer of the Original Code is SugarCRM, Inc.
  11. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
  12. * All Rights Reserved.
  13. * Contributor(s): ______________________________________.
  14. ********************************************************************************/
  15. include_once('config.php');
  16. require_once('include/logging.php');
  17. require_once('include/utils/utils.php');
  18. require_once('user_privileges/default_module_view.php');
  19. class HelpDesk extends CRMEntity {
  20. var $log;
  21. var $db;
  22. var $table_name = "vtiger_troubletickets";
  23. var $table_index= 'ticketid';
  24. var $tab_name = Array('vtiger_crmentity','vtiger_troubletickets','vtiger_ticketcf');
  25. var $tab_name_index = Array('vtiger_crmentity'=>'crmid','vtiger_troubletickets'=>'ticketid','vtiger_ticketcf'=>'ticketid','vtiger_ticketcomments'=>'ticketid');
  26. /**
  27. * Mandatory table for supporting custom fields.
  28. */
  29. var $customFieldTable = Array('vtiger_ticketcf', 'ticketid');
  30. var $column_fields = Array();
  31. //Pavani: Assign value to entity_table
  32. var $entity_table = "vtiger_crmentity";
  33. var $sortby_fields = Array('title','status','priority','crmid','firstname','smownerid');
  34. var $list_fields = Array(
  35. //Module Sequence Numbering
  36. //'Ticket ID'=>Array('crmentity'=>'crmid'),
  37. 'Ticket No'=>Array('troubletickets'=>'ticket_no'),
  38. // END
  39. 'Subject'=>Array('troubletickets'=>'title'),
  40. 'Related to'=>Array('troubletickets'=>'parent_id'),
  41. 'Status'=>Array('troubletickets'=>'status'),
  42. 'Priority'=>Array('troubletickets'=>'priority'),
  43. 'Assigned To'=>Array('crmentity','smownerid')
  44. );
  45. var $list_fields_name = Array(
  46. 'Ticket No'=>'ticket_no',
  47. 'Subject'=>'ticket_title',
  48. 'Related to'=>'parent_id',
  49. 'Status'=>'ticketstatus',
  50. 'Priority'=>'ticketpriorities',
  51. 'Assigned To'=>'assigned_user_id'
  52. );
  53. var $list_link_field= 'ticket_title';
  54. var $range_fields = Array(
  55. 'ticketid',
  56. 'title',
  57. 'firstname',
  58. 'lastname',
  59. 'parent_id',
  60. 'productid',
  61. 'productname',
  62. 'priority',
  63. 'severity',
  64. 'status',
  65. 'category',
  66. 'description',
  67. 'solution',
  68. 'modifiedtime',
  69. 'createdtime'
  70. );
  71. var $search_fields = Array(
  72. //'Ticket ID' => Array('vtiger_crmentity'=>'crmid'),
  73. 'Ticket No' =>Array('vtiger_troubletickets'=>'ticket_no'),
  74. 'Title' => Array('vtiger_troubletickets'=>'title')
  75. );
  76. var $search_fields_name = Array(
  77. 'Ticket No' => 'ticket_no',
  78. 'Title'=>'ticket_title',
  79. );
  80. //Specify Required fields
  81. var $required_fields = array();
  82. // Used when enabling/disabling the mandatory fields for the module.
  83. // Refers to vtiger_field.fieldname values.
  84. var $mandatory_fields = Array('assigned_user_id', 'createdtime', 'modifiedtime', 'ticket_title', 'update_log');
  85. //Added these variables which are used as default order by and sortorder in ListView
  86. var $default_order_by = 'title';
  87. var $default_sort_order = 'DESC';
  88. // For Alphabetical search
  89. var $def_basicsearch_col = 'ticket_title';
  90. //var $groupTable = Array('vtiger_ticketgrouprelation','ticketid');
  91. /** Constructor which will set the column_fields in this object
  92. */
  93. function HelpDesk()
  94. {
  95. $this->log =LoggerManager::getLogger('helpdesk');
  96. $this->log->debug("Entering HelpDesk() method ...");
  97. $this->db = PearDatabase::getInstance();
  98. $this->column_fields = getColumnFields('HelpDesk');
  99. $this->log->debug("Exiting HelpDesk method ...");
  100. }
  101. function save_module($module)
  102. {
  103. //Inserting into Ticket Comment Table
  104. $this->insertIntoTicketCommentTable("vtiger_ticketcomments",$module);
  105. //Inserting into vtiger_attachments
  106. $this->insertIntoAttachment($this->id,$module);
  107. //service contract update
  108. $return_action = $_REQUEST['return_action'];
  109. $for_module = $_REQUEST['return_module'];
  110. $for_crmid = $_REQUEST['return_id'];
  111. if ($return_action && $for_module && $for_crmid) {
  112. if ($for_module == 'ServiceContracts') {
  113. $on_focus = CRMEntity::getInstance($for_module);
  114. $on_focus->save_related_module($for_module, $for_crmid, $module, $this->id);
  115. }
  116. }
  117. }
  118. function save_related_module($module, $crmid, $with_module, $with_crmid) {
  119. parent::save_related_module($module, $crmid, $with_module, $with_crmid);
  120. if ($with_module == 'ServiceContracts') {
  121. $serviceContract = CRMEntity::getInstance("ServiceContracts");
  122. $serviceContract->updateHelpDeskRelatedTo($with_crmid,$crmid);
  123. $serviceContract->updateServiceContractState($with_crmid);
  124. }
  125. }
  126. /** Function to insert values in vtiger_ticketcomments for the specified tablename and module
  127. * @param $table_name -- table name:: Type varchar
  128. * @param $module -- module:: Type varchar
  129. */
  130. function insertIntoTicketCommentTable($table_name, $module)
  131. {
  132. global $log;
  133. $log->info("in insertIntoTicketCommentTable ".$table_name." module is ".$module);
  134. global $adb;
  135. global $current_user;
  136. $current_time = $adb->formatDate(date('Y-m-d H:i:s'), true);
  137. if ($this->column_fields['from_portal'] != 1) {
  138. $ownertype = 'user';
  139. $ownerId = $current_user->id;
  140. } else {
  141. $ownertype = 'customer';
  142. $ownerId = $this->column_fields['parent_id'];
  143. }
  144. $comment = $this->column_fields['comments'];
  145. if ($comment != '') {
  146. $sql = "insert into vtiger_ticketcomments values(?,?,?,?,?,?)";
  147. $params = array('', $this->id, from_html($comment), $ownerId, $ownertype, $current_time);
  148. $adb->pquery($sql, $params);
  149. }
  150. }
  151. /**
  152. * This function is used to add the vtiger_attachments. This will call the function uploadAndSaveFile which will upload the attachment into the server and save that attachment information in the database.
  153. * @param int $id - entity id to which the vtiger_files to be uploaded
  154. * @param string $module - the current module name
  155. */
  156. function insertIntoAttachment($id,$module)
  157. {
  158. global $log, $adb;
  159. $log->debug("Entering into insertIntoAttachment($id,$module) method.");
  160. $file_saved = false;
  161. foreach($_FILES as $fileindex => $files)
  162. {
  163. if($files['name'] != '' && $files['size'] > 0)
  164. {
  165. $files['original_name'] = vtlib_purify($_REQUEST[$fileindex.'_hidden']);
  166. $file_saved = $this->uploadAndSaveFile($id,$module,$files);
  167. }
  168. }
  169. $log->debug("Exiting from insertIntoAttachment($id,$module) method.");
  170. }
  171. /** Function to form the query to get the list of activities
  172. * @param int $id - ticket id
  173. * @return array - return an array which will be returned from the function GetRelatedList
  174. **/
  175. function get_activities($id, $cur_tab_id, $rel_tab_id, $actions=false) {
  176. global $log, $singlepane_view,$currentModule,$current_user;
  177. $log->debug("Entering get_activities(".$id.") method ...");
  178. $this_module = $currentModule;
  179. $related_module = vtlib_getModuleNameById($rel_tab_id);
  180. require_once("modules/$related_module/Activity.php");
  181. $other = new Activity();
  182. vtlib_setup_modulevars($related_module, $other);
  183. $singular_modname = vtlib_toSingular($related_module);
  184. $parenttab = getParentTab();
  185. if($singlepane_view == 'true')
  186. $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
  187. else
  188. $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
  189. $button = '';
  190. $button .= '<input type="hidden" name="activity_mode">';
  191. if($actions) {
  192. if(is_string($actions)) $actions = explode(',', strtoupper($actions));
  193. if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
  194. if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id', 'readwrite') == '0') {
  195. $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
  196. " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Task\";' type='submit' name='button'" .
  197. " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_TODO', $related_module) ."'>&nbsp;";
  198. }
  199. if(getFieldVisibilityPermission('Events',$current_user->id,'parent_id', 'readwrite') == '0') {
  200. $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
  201. " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Events\";' type='submit' name='button'" .
  202. " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_EVENT', $related_module) ."'>";
  203. }
  204. }
  205. }
  206. $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
  207. 'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
  208. $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name," .
  209. " vtiger_activity.*, vtiger_cntactivityrel.contactid, vtiger_contactdetails.lastname, vtiger_contactdetails.firstname," .
  210. " vtiger_crmentity.crmid, vtiger_recurringevents.recurringtype, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime," .
  211. " vtiger_seactivityrel.crmid as parent_id " .
  212. " from vtiger_activity inner join vtiger_seactivityrel on vtiger_seactivityrel.activityid=vtiger_activity.activityid" .
  213. " inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid" .
  214. " left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid = vtiger_activity.activityid " .
  215. " left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid" .
  216. " left outer join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid" .
  217. " left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid" .
  218. " left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid" .
  219. " where vtiger_seactivityrel.crmid=".$id." and vtiger_crmentity.deleted=0 and (activitytype NOT IN ('Emails'))" .
  220. " AND ( vtiger_activity.status is NULL OR vtiger_activity.status != 'Completed' )" .
  221. " and ( vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus != 'Held') ";
  222. $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
  223. if($return_value == null) $return_value = Array();
  224. $return_value['CUSTOM_BUTTON'] = $button;
  225. $log->debug("Exiting get_activities method ...");
  226. return $return_value;
  227. }
  228. /** Function to get the Ticket History information as in array format
  229. * @param int $ticketid - ticket id
  230. * @return array - return an array with title and the ticket history informations in the following format
  231. array(
  232. header=>array('0'=>'title'),
  233. entries=>array('0'=>'info1','1'=>'info2',etc.,)
  234. )
  235. */
  236. function get_ticket_history($ticketid)
  237. {
  238. global $log, $adb;
  239. $log->debug("Entering into get_ticket_history($ticketid) method ...");
  240. $query="select title,update_log from vtiger_troubletickets where ticketid=?";
  241. $result=$adb->pquery($query, array($ticketid));
  242. $update_log = $adb->query_result($result,0,"update_log");
  243. $splitval = split('--//--',trim($update_log,'--//--'));
  244. $header[] = $adb->query_result($result,0,"title");
  245. $return_value = Array('header'=>$header,'entries'=>$splitval);
  246. $log->debug("Exiting from get_ticket_history($ticketid) method ...");
  247. return $return_value;
  248. }
  249. /** Function to get the ticket comments as a array
  250. * @param int $ticketid - ticketid
  251. * @return array $output - array(
  252. [$i][comments] => comments
  253. [$i][owner] => name of the user or customer who made the comment
  254. [$i][createdtime] => the comment created time
  255. )
  256. where $i = 0,1,..n which are all made for the ticket
  257. **/
  258. function get_ticket_comments_list($ticketid)
  259. {
  260. global $log;
  261. $log->debug("Entering get_ticket_comments_list(".$ticketid.") method ...");
  262. $sql = "select * from vtiger_ticketcomments where ticketid=? order by createdtime DESC";
  263. $result = $this->db->pquery($sql, array($ticketid));
  264. $noofrows = $this->db->num_rows($result);
  265. for($i=0;$i<$noofrows;$i++)
  266. {
  267. $ownerid = $this->db->query_result($result,$i,"ownerid");
  268. $ownertype = $this->db->query_result($result,$i,"ownertype");
  269. if($ownertype == 'user')
  270. $name = getUserFullName($ownerid);
  271. elseif($ownertype == 'customer')
  272. {
  273. $sql1 = 'select * from vtiger_portalinfo where id=?';
  274. $name = $this->db->query_result($this->db->pquery($sql1, array($ownerid)),0,'user_name');
  275. }
  276. $output[$i]['comments'] = nl2br($this->db->query_result($result,$i,"comments"));
  277. $output[$i]['owner'] = $name;
  278. $output[$i]['createdtime'] = $this->db->query_result($result,$i,"createdtime");
  279. }
  280. $log->debug("Exiting get_ticket_comments_list method ...");
  281. return $output;
  282. }
  283. /** Function to process the list query and return the result with number of rows
  284. * @param string $query - query
  285. * @return array $response - array( list => array(
  286. $i => array(key => val)
  287. ),
  288. row_count => '',
  289. next_offset => '',
  290. previous_offset =>''
  291. )
  292. where $i=0,1,..n & key = ticketid, title, firstname, ..etc(range_fields) & val = value of the key from db retrieved row
  293. **/
  294. function process_list_query($query)
  295. {
  296. global $log;
  297. $log->debug("Entering process_list_query(".$query.") method ...");
  298. $result =& $this->db->query($query,true,"Error retrieving $this->object_name list: ");
  299. $list = Array();
  300. $rows_found = $this->db->getRowCount($result);
  301. if($rows_found != 0)
  302. {
  303. $ticket = Array();
  304. for($index = 0 , $row = $this->db->fetchByAssoc($result, $index); $row && $index <$rows_found;$index++, $row = $this->db->fetchByAssoc($result, $index))
  305. {
  306. foreach($this->range_fields as $columnName)
  307. {
  308. if (isset($row[$columnName]))
  309. {
  310. $ticket[$columnName] = $row[$columnName];
  311. }
  312. else
  313. {
  314. $ticket[$columnName] = "";
  315. }
  316. }
  317. $list[] = $ticket;
  318. }
  319. }
  320. $response = Array();
  321. $response['list'] = $list;
  322. $response['row_count'] = $rows_found;
  323. $response['next_offset'] = $next_offset;
  324. $response['previous_offset'] = $previous_offset;
  325. $log->debug("Exiting process_list_query method ...");
  326. return $response;
  327. }
  328. /** Function to get the HelpDesk field labels in caps letters without space
  329. * @return array $mergeflds - array( key => val ) where key=0,1,2..n & val = ASSIGNEDTO,RELATEDTO, .,etc
  330. **/
  331. function getColumnNames_Hd()
  332. {
  333. global $log,$current_user;
  334. $log->debug("Entering getColumnNames_Hd() method ...");
  335. require('user_privileges/user_privileges_'.$current_user->id.'.php');
  336. if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0)
  337. {
  338. $sql1 = "select fieldlabel from vtiger_field where tabid=13 and block <> 30 and vtiger_field.uitype <> '61' and vtiger_field.presence in (0,2)";
  339. $params1 = array();
  340. }else
  341. {
  342. $profileList = getCurrentUserProfileList();
  343. $sql1 = "select vtiger_field.fieldid,fieldlabel from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid=13 and vtiger_field.block <> 30 and vtiger_field.uitype <> '61' and vtiger_field.displaytype in (1,2,3,4) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)";
  344. $params1 = array();
  345. if (count($profileList) > 0) {
  346. $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .") group by fieldid";
  347. array_push($params1, $profileList);
  348. }
  349. }
  350. $result = $this->db->pquery($sql1, $params1);
  351. $numRows = $this->db->num_rows($result);
  352. for($i=0; $i < $numRows;$i++)
  353. {
  354. $custom_fields[$i] = $this->db->query_result($result,$i,"fieldlabel");
  355. $custom_fields[$i] = preg_replace("/\s+/","",$custom_fields[$i]);
  356. $custom_fields[$i] = strtoupper($custom_fields[$i]);
  357. }
  358. $mergeflds = $custom_fields;
  359. $log->debug("Exiting getColumnNames_Hd method ...");
  360. return $mergeflds;
  361. }
  362. /** Function to get the list of comments for the given ticket id
  363. * @param int $ticketid - Ticket id
  364. * @return list $list - return the list of comments and comment informations as a html output where as these comments and comments informations will be formed in div tag.
  365. **/
  366. function getCommentInformation($ticketid)
  367. {
  368. global $log;
  369. $log->debug("Entering getCommentInformation(".$ticketid.") method ...");
  370. global $adb;
  371. global $mod_strings, $default_charset;
  372. $sql = "select * from vtiger_ticketcomments where ticketid=?";
  373. $result = $adb->pquery($sql, array($ticketid));
  374. $noofrows = $adb->num_rows($result);
  375. //In ajax save we should not add this div
  376. if($_REQUEST['action'] != 'HelpDeskAjax')
  377. {
  378. $list .= '<div id="comments_div" style="overflow: auto;height:200px;width:100%;">';
  379. $enddiv = '</div>';
  380. }
  381. for($i=0;$i<$noofrows;$i++)
  382. {
  383. if($adb->query_result($result,$i,'comments') != '')
  384. {
  385. //this div is to display the comment
  386. $comment = $adb->query_result($result,$i,'comments');
  387. // Asha: Fix for ticket #4478 . Need to escape html tags during ajax save.
  388. if($_REQUEST['action'] == 'HelpDeskAjax') {
  389. $comment = htmlentities($comment, ENT_QUOTES, $default_charset);
  390. }
  391. $list .= '<div valign="top" style="width:99%;padding-top:10px;" class="dataField">';
  392. $list .= make_clickable(nl2br($comment));
  393. $list .= '</div>';
  394. //this div is to display the author and time
  395. $list .= '<div valign="top" style="width:99%;border-bottom:1px dotted #CCCCCC;padding-bottom:5px;" class="dataLabel"><font color=darkred>';
  396. $list .= $mod_strings['LBL_AUTHOR'].' : ';
  397. if($adb->query_result($result,$i,'ownertype') == 'user')
  398. $list .= getUserFullName($adb->query_result($result,$i,'ownerid'));
  399. elseif($adb->query_result($result,$i,'ownertype') == 'customer') {
  400. $contactid = $adb->query_result($result,$i,'ownerid');
  401. $displayValueArray = getEntityName('Contacts', $contactid);
  402. if (!empty($displayValueArray)) {
  403. foreach ($displayValueArray as $key => $field_value) {
  404. $contact_name = $field_value;
  405. }
  406. } else {
  407. $contact_name='';
  408. }
  409. $list .= $contact_name;
  410. }
  411. $list .= ' on '.$adb->query_result($result,$i,'createdtime').' &nbsp;';
  412. $list .= '</font></div>';
  413. }
  414. }
  415. $list .= $enddiv;
  416. $log->debug("Exiting getCommentInformation method ...");
  417. return $list;
  418. }
  419. /** Function to get the Customer Name who has made comment to the ticket from the customer portal
  420. * @param int $id - Ticket id
  421. * @return string $customername - The contact name
  422. **/
  423. function getCustomerName($id)
  424. {
  425. global $log;
  426. $log->debug("Entering getCustomerName(".$id.") method ...");
  427. global $adb;
  428. $sql = "select * from vtiger_portalinfo inner join vtiger_troubletickets on vtiger_troubletickets.parent_id = vtiger_portalinfo.id where vtiger_troubletickets.ticketid=?";
  429. $result = $adb->pquery($sql, array($id));
  430. $customername = $adb->query_result($result,0,'user_name');
  431. $log->debug("Exiting getCustomerName method ...");
  432. return $customername;
  433. }
  434. //Pavani: Function to create, export query for helpdesk module
  435. /** Function to export the ticket records in CSV Format
  436. * @param reference variable - where condition is passed when the query is executed
  437. * Returns Export Tickets Query.
  438. */
  439. function create_export_query($where)
  440. {
  441. global $log;
  442. global $current_user;
  443. $log->debug("Entering create_export_query(".$where.") method ...");
  444. include("include/utils/ExportUtils.php");
  445. //To get the Permitted fields query and the permitted fields list
  446. $sql = getPermittedFieldsQuery("HelpDesk", "detail_view");
  447. $fields_list = getFieldsListFromQuery($sql);
  448. //Ticket changes--5198
  449. $fields_list = str_replace(",vtiger_ticketcomments.comments as 'Add Comment'",' ',$fields_list);
  450. $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
  451. 'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
  452. $query = "SELECT $fields_list,case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
  453. FROM ".$this->entity_table. "
  454. INNER JOIN vtiger_troubletickets
  455. ON vtiger_troubletickets.ticketid =vtiger_crmentity.crmid
  456. LEFT JOIN vtiger_crmentity vtiger_crmentityRelatedTo
  457. ON vtiger_crmentityRelatedTo.crmid = vtiger_troubletickets.parent_id
  458. LEFT JOIN vtiger_account
  459. ON vtiger_account.accountid = vtiger_troubletickets.parent_id
  460. LEFT JOIN vtiger_contactdetails
  461. ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id
  462. LEFT JOIN vtiger_ticketcf
  463. ON vtiger_ticketcf.ticketid=vtiger_troubletickets.ticketid
  464. LEFT JOIN vtiger_groups
  465. ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  466. LEFT JOIN vtiger_users
  467. ON vtiger_users.id=vtiger_crmentity.smownerid and vtiger_users.status='Active'
  468. LEFT JOIN vtiger_seattachmentsrel
  469. ON vtiger_seattachmentsrel.crmid =vtiger_troubletickets.ticketid
  470. LEFT JOIN vtiger_attachments
  471. ON vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid
  472. LEFT JOIN vtiger_products
  473. ON vtiger_products.productid=vtiger_troubletickets.product_id";
  474. //end
  475. $query .= getNonAdminAccessControlQuery('HelpDesk',$current_user);
  476. $where_auto=" vtiger_crmentity.deleted = 0 ";
  477. if($where != "")
  478. $query .= " WHERE ($where) AND ".$where_auto;
  479. else
  480. $query .= " WHERE ".$where_auto;
  481. $log->debug("Exiting create_export_query method ...");
  482. return $query;
  483. }
  484. /** Function used to get the Activity History
  485. * @param int $id - ticket id to which we want to display the activity history
  486. * @return array - return an array which will be returned from the function getHistory
  487. */
  488. function get_history($id)
  489. {
  490. global $log;
  491. $log->debug("Entering get_history(".$id.") method ...");
  492. $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
  493. 'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
  494. $query = "SELECT vtiger_activity.activityid, vtiger_activity.subject, vtiger_activity.status, vtiger_activity.eventstatus, vtiger_activity.date_start, vtiger_activity.due_date,vtiger_activity.time_start,vtiger_activity.time_end,vtiger_activity.activitytype, vtiger_troubletickets.ticketid, vtiger_troubletickets.title, vtiger_crmentity.modifiedtime,vtiger_crmentity.createdtime, vtiger_crmentity.description,
  495. case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
  496. from vtiger_activity
  497. inner join vtiger_seactivityrel on vtiger_seactivityrel.activityid= vtiger_activity.activityid
  498. inner join vtiger_troubletickets on vtiger_troubletickets.ticketid = vtiger_seactivityrel.crmid
  499. inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
  500. left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid
  501. left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid
  502. where (vtiger_activity.activitytype != 'Emails')
  503. and (vtiger_activity.status = 'Completed' or vtiger_activity.status = 'Deferred' or (vtiger_activity.eventstatus = 'Held' and vtiger_activity.eventstatus != ''))
  504. and vtiger_seactivityrel.crmid=".$id."
  505. and vtiger_crmentity.deleted = 0";
  506. //Don't add order by, because, for security, one more condition will be added with this query in include/RelatedListView.php
  507. $log->debug("Entering get_history method ...");
  508. return getHistory('HelpDesk',$query,$id);
  509. }
  510. /** Function to get the update ticket history for the specified ticketid
  511. * @param $id -- $ticketid:: Type Integer
  512. */
  513. function constructUpdateLog($focus, $mode, $assigned_group_name, $assigntype)
  514. {
  515. global $adb;
  516. global $current_user;
  517. if($mode != 'edit')//this will be updated when we create new ticket
  518. {
  519. $updatelog = "Ticket created. Assigned to ";
  520. if(!empty($assigned_group_name) && $assigntype == 'T')
  521. {
  522. $updatelog .= " group ".(is_array($assigned_group_name)? $assigned_group_name[0] : $assigned_group_name);
  523. }
  524. elseif($focus->column_fields['assigned_user_id'] != '')
  525. {
  526. $updatelog .= " user ".getUserFullName($focus->column_fields['assigned_user_id']);
  527. }
  528. else
  529. {
  530. $updatelog .= " user ".getUserFullName($current_user->id);
  531. }
  532. $fldvalue = date("l dS F Y h:i:s A").' by '.$current_user->user_name;
  533. $updatelog .= " -- ".$fldvalue."--//--";
  534. }
  535. else
  536. {
  537. $ticketid = $focus->id;
  538. //First retrieve the existing information
  539. $tktresult = $adb->pquery("select * from vtiger_troubletickets where ticketid=?", array($ticketid));
  540. $crmresult = $adb->pquery("select * from vtiger_crmentity where crmid=?", array($ticketid));
  541. $updatelog = decode_html($adb->query_result($tktresult,0,"update_log"));
  542. $old_owner_id = $adb->query_result($crmresult,0,"smownerid");
  543. $old_status = $adb->query_result($tktresult,0,"status");
  544. $old_priority = $adb->query_result($tktresult,0,"priority");
  545. $old_severity = $adb->query_result($tktresult,0,"severity");
  546. $old_category = $adb->query_result($tktresult,0,"category");
  547. //Assigned to change log
  548. if($focus->column_fields['assigned_user_id'] != $old_owner_id)
  549. {
  550. $owner_name = getOwnerName($focus->column_fields['assigned_user_id']);
  551. if($assigntype == 'T')
  552. $updatelog .= ' Transferred to group '.$owner_name.'\.';
  553. else
  554. $updatelog .= ' Transferred to user '.decode_html($owner_name).'\.'; // Need to decode UTF characters which are migrated from versions < 5.0.4.
  555. }
  556. //Status change log
  557. if($old_status != $focus->column_fields['ticketstatus'] && $focus->column_fields['ticketstatus'] != '')
  558. {
  559. $updatelog .= ' Status Changed to '.$focus->column_fields['ticketstatus'].'\.';
  560. }
  561. //Priority change log
  562. if($old_priority != $focus->column_fields['ticketpriorities'] && $focus->column_fields['ticketpriorities'] != '')
  563. {
  564. $updatelog .= ' Priority Changed to '.$focus->column_fields['ticketpriorities'].'\.';
  565. }
  566. //Severity change log
  567. if($old_severity != $focus->column_fields['ticketseverities'] && $focus->column_fields['ticketseverities'] != '')
  568. {
  569. $updatelog .= ' Severity Changed to '.$focus->column_fields['ticketseverities'].'\.';
  570. }
  571. //Category change log
  572. if($old_category != $focus->column_fields['ticketcategories'] && $focus->column_fields['ticketcategories'] != '')
  573. {
  574. $updatelog .= ' Category Changed to '.$focus->column_fields['ticketcategories'].'\.';
  575. }
  576. $updatelog .= ' -- '.date("l dS F Y h:i:s A").' by '.$current_user->user_name.'--//--';
  577. }
  578. return $updatelog;
  579. }
  580. /**
  581. * Move the related records of the specified list of id's to the given record.
  582. * @param String This module name
  583. * @param Array List of Entity Id's from which related records need to be transfered
  584. * @param Integer Id of the the Record to which the related records are to be moved
  585. */
  586. function transferRelatedRecords($module, $transferEntityIds, $entityId) {
  587. global $adb,$log;
  588. $log->debug("Entering function transferRelatedRecords ($module, $transferEntityIds, $entityId)");
  589. $rel_table_arr = Array("Activities"=>"vtiger_seactivityrel","Attachments"=>"vtiger_seattachmentsrel","Documents"=>"vtiger_senotesrel");
  590. $tbl_field_arr = Array("vtiger_seactivityrel"=>"activityid","vtiger_seattachmentsrel"=>"attachmentsid","vtiger_senotesrel"=>"notesid");
  591. $entity_tbl_field_arr = Array("vtiger_seactivityrel"=>"crmid","vtiger_seattachmentsrel"=>"crmid","vtiger_senotesrel"=>"crmid");
  592. foreach($transferEntityIds as $transferId) {
  593. foreach($rel_table_arr as $rel_module=>$rel_table) {
  594. $id_field = $tbl_field_arr[$rel_table];
  595. $entity_id_field = $entity_tbl_field_arr[$rel_table];
  596. // IN clause to avoid duplicate entries
  597. $sel_result = $adb->pquery("select $id_field from $rel_table where $entity_id_field=? " .
  598. " and $id_field not in (select $id_field from $rel_table where $entity_id_field=?)",
  599. array($transferId,$entityId));
  600. $res_cnt = $adb->num_rows($sel_result);
  601. if($res_cnt > 0) {
  602. for($i=0;$i<$res_cnt;$i++) {
  603. $id_field_value = $adb->query_result($sel_result,$i,$id_field);
  604. $adb->pquery("update $rel_table set $entity_id_field=? where $entity_id_field=? and $id_field=?",
  605. array($entityId,$transferId,$id_field_value));
  606. }
  607. }
  608. }
  609. }
  610. $log->debug("Exiting transferRelatedRecords...");
  611. }
  612. /*
  613. * Function to get the secondary query part of a report
  614. * @param - $module primary module name
  615. * @param - $secmodule secondary module name
  616. * returns the query string formed on fetching the related data for report for secondary module
  617. */
  618. function generateReportsSecQuery($module,$secmodule){
  619. $query = $this->getRelationQuery($module,$secmodule,"vtiger_troubletickets","ticketid");
  620. $query .=" left join vtiger_crmentity as vtiger_crmentityHelpDesk on vtiger_crmentityHelpDesk.crmid=vtiger_troubletickets.ticketid and vtiger_crmentityHelpDesk.deleted=0
  621. left join vtiger_ticketcf on vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid
  622. left join vtiger_crmentity as vtiger_crmentityRelHelpDesk on vtiger_crmentityRelHelpDesk.crmid = vtiger_troubletickets.parent_id
  623. left join vtiger_account as vtiger_accountRelHelpDesk on vtiger_accountRelHelpDesk.accountid=vtiger_crmentityRelHelpDesk.crmid
  624. left join vtiger_contactdetails as vtiger_contactdetailsRelHelpDesk on vtiger_contactdetailsRelHelpDesk.contactid= vtiger_crmentityRelHelpDesk.crmid
  625. left join vtiger_products as vtiger_productsRel on vtiger_productsRel.productid = vtiger_troubletickets.product_id
  626. left join vtiger_groups as vtiger_groupsHelpDesk on vtiger_groupsHelpDesk.groupid = vtiger_crmentityHelpDesk.smownerid
  627. left join vtiger_users as vtiger_usersHelpDesk on vtiger_usersHelpDesk.id = vtiger_crmentityHelpDesk.smownerid
  628. left join vtiger_users as vtiger_lastModifiedByHelpDesk on vtiger_lastModifiedByHelpDesk.id = vtiger_crmentityHelpDesk.modifiedby ";
  629. return $query;
  630. }
  631. /*
  632. * Function to get the relation tables for related modules
  633. * @param - $secmodule secondary module name
  634. * returns the array with table names and fieldnames storing relations between module and this module
  635. */
  636. function setRelationTables($secmodule){
  637. $rel_tables = array (
  638. "Calendar" => array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_troubletickets"=>"ticketid"),
  639. "Documents" => array("vtiger_senotesrel"=>array("crmid","notesid"),"vtiger_troubletickets"=>"ticketid"),
  640. "Products" => array("vtiger_troubletickets"=>array("ticketid","product_id")),
  641. "Services" => array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"vtiger_troubletickets"=>"ticketid"),
  642. );
  643. return $rel_tables[$secmodule];
  644. }
  645. // Function to unlink an entity with given Id from another entity
  646. function unlinkRelationship($id, $return_module, $return_id) {
  647. global $log;
  648. if(empty($return_module) || empty($return_id)) return;
  649. if($return_module == 'Contacts' || $return_module == 'Accounts') {
  650. $sql = 'UPDATE vtiger_troubletickets SET parent_id=? WHERE ticketid=?';
  651. $this->db->pquery($sql, array(null, $id));
  652. $se_sql= 'DELETE FROM vtiger_seticketsrel WHERE ticketid=?';
  653. $this->db->pquery($se_sql, array($id));
  654. } elseif($return_module == 'Products') {
  655. $sql = 'UPDATE vtiger_troubletickets SET product_id=? WHERE ticketid=?';
  656. $this->db->pquery($sql, array(null, $id));
  657. } else {
  658. $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
  659. $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
  660. $this->db->pquery($sql, $params);
  661. }
  662. }
  663. public static function getTicketEmailContents($entityData) {
  664. $adb = PearDatabase::getInstance();
  665. $moduleName = $entityData->getModuleName();
  666. $wsId = $entityData->getId();
  667. $parts = explode('x', $wsId);
  668. $entityId = $parts[1];
  669. $isNew = $entityData->isNew();
  670. if (!$isNew) {
  671. $reply = getTranslatedString("replied", $moduleName);
  672. $temp = getTranslatedString("Re", $moduleName);
  673. } else {
  674. $reply = getTranslatedString("created", $moduleName);
  675. $temp = " ";
  676. }
  677. $wsParentId = $entityData->get('parent_id');
  678. $parentIdParts = explode('x', $wsParentId);
  679. $parentId = $parentIdParts[1];
  680. $desc = getTranslatedString('Ticket ID', $moduleName) . ' : ' . $entityId . '<br>'
  681. . getTranslatedString('Ticket Title', $moduleName) . ' : ' . $temp . ' '
  682. . $entityData->get('ticket_title');
  683. $desc .= "<br><br>" . getTranslatedString('Hi', $moduleName) . " " . getParentName($parentId) . ",<br><br>"
  684. . getTranslatedString('LBL_PORTAL_BODY_MAILINFO', $moduleName) . " " . $reply . " " . getTranslatedString('LBL_DETAIL', $moduleName) . "<br>";
  685. $desc .= "<br>" . getTranslatedString('Ticket No', $moduleName) . " : " . $entityData->get('ticket_no');
  686. $desc .= "<br>" . getTranslatedString('Status', $moduleName) . " : " . $entityData->get('ticketstatus');
  687. $desc .= "<br>" . getTranslatedString('Category', $moduleName) . " : " . $entityData->get('ticketcategories');
  688. $desc .= "<br>" . getTranslatedString('Severity', $moduleName) . " : " . $entityData->get('ticketseverities');
  689. $desc .= "<br>" . getTranslatedString('Priority', $moduleName) . " : " . $entityData->get('ticketpriorities');
  690. $desc .= "<br><br>" . getTranslatedString('Description', $moduleName) . " : <br>" . $entityData->get('description');
  691. $desc .= "<br><br>" . getTranslatedString('Solution', $moduleName) . " : <br>" . $entityData->get('solution');
  692. $desc .= getTicketComments($entityId);
  693. $sql = "SELECT * FROM vtiger_ticketcf WHERE ticketid = ?";
  694. $result = $adb->pquery($sql, array($id));
  695. $cffields = $adb->getFieldsArray($result);
  696. foreach ($cffields as $cfOneField) {
  697. if ($cfOneField != 'ticketid') {
  698. $cfData = $adb->query_result($result, 0, $cfOneField);
  699. $sql = "SELECT fieldlabel FROM vtiger_field WHERE columnname = ? and vtiger_field.presence in (0,2)";
  700. $cfLabel = $adb->query_result($adb->pquery($sql, array($cfOneField)), 0, 'fieldlabel');
  701. $desc .= '<br><br>' . $cfLabel . ' : <br>' . $cfData;
  702. }
  703. }
  704. // end of contribution
  705. $desc .= '<br><br><br>';
  706. $desc .= '<br>' . getTranslatedString("LBL_REGARDS", $moduleName) . ',<br>' . getTranslatedString("LBL_TEAM", $moduleName) . '.<br>';
  707. return $desc;
  708. }
  709. public static function getPortalTicketEmailContents($entityData) {
  710. require_once 'config.inc.php';
  711. global $PORTAL_URL;
  712. $moduleName = $entityData->getModuleName();
  713. $wsId = $entityData->getId();
  714. $parts = explode('x', $wsId);
  715. $entityId = $parts[1];
  716. $wsParentId = $entityData->get('parent_id');
  717. $parentIdParts = explode('x', $wsParentId);
  718. $parentId = $parentIdParts[1];
  719. $portalUrl = "<a href='" . $PORTAL_URL . "/index.php?module=HelpDesk&action=index&ticketid=" . $entityId . "&fun=detail'>"
  720. . getTranslatedString('LBL_TICKET_DETAILS', $moduleName) . "</a>";
  721. $contents = getTranslatedString('Dear', $moduleName) . " " . getParentName(parentId) . ",<br><br>";
  722. $contents .= getTranslatedString('reply', $moduleName) . ' <b>' . $entityData->get('ticket_title')
  723. . '</b>' . getTranslatedString('customer_portal', $moduleName);
  724. $contents .= getTranslatedString("link", $moduleName) . '<br>';
  725. $contents .= $portalUrl;
  726. $contents .= '<br><br>' . getTranslatedString("Thanks", $moduleName) . '<br><br>' . getTranslatedString("Support_team", $moduleName);
  727. return $contents;
  728. }
  729. function clearSingletonSaveFields() {
  730. $this->column_fields['comments'] = '';
  731. }
  732. }
  733. ?>