[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/HelpDesk/ -> HelpDesk.php (source)

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


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1