[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/soap/ -> customerportal.php (source)

   1  <?php
   2  /*********************************************************************************
   3   ** The contents of this file are subject to the vtiger CRM Public License Version 1.0
   4   * ("License"); You may not use this file except in compliance with the License
   5   * The Original Code is:  vtiger CRM Open Source
   6   * The Initial Developer of the Original Code is vtiger.
   7   * Portions created by vtiger are Copyright (C) vtiger.
   8   * All Rights Reserved.
   9   *
  10   ********************************************************************************/
  11  
  12  /**
  13   * URL Verfication - Required to overcome Apache mis-configuration and leading to shared setup mode.
  14   */
  15  require_once  'config.php';
  16  if (file_exists('config_override.php')) {
  17      include_once 'config_override.php';
  18  }
  19  
  20  include_once  'vtlib/Vtiger/Module.php';
  21  include_once  'includes/main/WebUI.php';
  22  
  23  require_once ('libraries/nusoap/nusoap.php');
  24  require_once ('modules/HelpDesk/HelpDesk.php');
  25  require_once ('modules/Emails/mail.php');
  26  require_once  'modules/Users/Users.php';
  27  
  28  
  29  /** Configure language for server response translation */
  30  global $default_language, $current_language;
  31  if(!isset($current_language)) $current_language = $default_language;
  32  
  33  $userid = getPortalUserid();
  34  $user = new Users();
  35  $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
  36  
  37  
  38  $log = &LoggerManager::getLogger('customerportal');
  39  
  40  error_reporting(0);
  41  
  42  $NAMESPACE = 'http://www.vtiger.com/products/crm';
  43  $server = new soap_server;
  44  
  45  $server->configureWSDL('customerportal');
  46  
  47  $server->wsdl->addComplexType(
  48      'common_array',
  49      'complexType',
  50      'array',
  51      '',
  52      array(
  53          'fieldname' => array('name'=>'fieldname','type'=>'xsd:string'),
  54      )
  55  );
  56  
  57  $server->wsdl->addComplexType(
  58      'common_array1',
  59      'complexType',
  60      'array',
  61      '',
  62      'SOAP-ENC:Array',
  63      array(),
  64      array(
  65          array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:common_array[]')
  66      ),
  67      'tns:common_array'
  68  );
  69  
  70  $server->wsdl->addComplexType(
  71      'add_contact_detail_array',
  72      'complexType',
  73      'array',
  74      '',
  75      array(
  76          'salutation' => array('name'=>'salutation','type'=>'xsd:string'),
  77          'firstname' => array('name'=>'firstname','type'=>'xsd:string'),
  78          'phone' => array('name'=>'phone','type'=>'xsd:string'),
  79          'lastname' => array('name'=>'lastname','type'=>'xsd:string'),
  80          'mobile' => array('name'=>'mobile','type'=>'xsd:string'),
  81          'accountid' => array('name'=>'accountid','type'=>'xsd:string'),
  82          'leadsource' => array('name'=>'leadsource','type'=>'xsd:string'),
  83      )
  84  );
  85  
  86  $server->wsdl->addComplexType(
  87      'field_details_array',
  88      'complexType',
  89      'array',
  90      '',
  91      array(
  92          'fieldlabel' => array('name'=>'fieldlabel','type'=>'xsd:string'),
  93          'fieldvalue' => array('name'=>'fieldvalue','type'=>'xsd:string'),
  94      )
  95  );
  96  $server->wsdl->addComplexType(
  97      'field_datalist_array',
  98      'complexType',
  99      'array',
 100      '',
 101      array(
 102          'fielddata' => array('name'=>'fielddata','type'=>'xsd:string'),
 103      )
 104  );
 105  
 106  $server->wsdl->addComplexType(
 107      'product_list_array',
 108      'complexType',
 109      'array',
 110      '',
 111      array(
 112          'productid' => array('name'=>'productid','type'=>'xsd:string'),
 113          'productname' => array('name'=>'productname','type'=>'xsd:string'),
 114          'productcode' => array('name'=>'productcode','type'=>'xsd:string'),
 115          'commissionrate' => array('name'=>'commissionrate','type'=>'xsd:string'),
 116          'qtyinstock' => array('name'=>'qtyinstock','type'=>'xsd:string'),
 117          'qty_per_unit' => array('name'=>'qty_per_unit','type'=>'xsd:string'),
 118          'unit_price' => array('name'=>'unit_price','type'=>'xsd:string'),
 119      )
 120  );
 121  
 122  $server->wsdl->addComplexType(
 123      'get_ticket_attachments_array',
 124      'complexType',
 125      'array',
 126      '',
 127      array(
 128          'files' => array(
 129              'fileid'=>'xsd:string','type'=>'tns:xsd:string',
 130              'filename'=>'xsd:string','type'=>'tns:xsd:string',
 131              'filesize'=>'xsd:string','type'=>'tns:xsd:string',
 132              'filetype'=>'xsd:string','type'=>'tns:xsd:string',
 133              'filecontents'=>'xsd:string','type'=>'tns:xsd:string'
 134          ),
 135      )
 136  );
 137  
 138  
 139  $server->register(
 140      'authenticate_user',
 141      array('fieldname'=>'tns:common_array'),
 142      array('return'=>'tns:common_array'),
 143      $NAMESPACE);
 144  
 145  $server->register(
 146      'change_password',
 147      array('fieldname'=>'tns:common_array'),
 148      array('return'=>'tns:common_array'),
 149      $NAMESPACE);
 150  
 151  $server->register(
 152      'create_ticket',
 153      array('fieldname'=>'tns:common_array'),
 154      array('return'=>'tns:common_array'),
 155      $NAMESPACE);
 156  
 157  //for a particular contact ticket list
 158  $server->register(
 159      'get_tickets_list',
 160      array('fieldname'=>'tns:common_array'),
 161      array('return'=>'tns:common_array'),
 162      $NAMESPACE);
 163  
 164  $server->register(
 165      'get_ticket_comments',
 166      array('fieldname'=>'tns:common_array'),
 167      array('return'=>'tns:common_array'),
 168      $NAMESPACE);
 169  
 170  $server->register(
 171      'get_combo_values',
 172      array('fieldname'=>'tns:common_array'),
 173      array('return'=>'tns:common_array'),
 174      $NAMESPACE);
 175  
 176  $server->register(
 177      'get_KBase_details',
 178      array('fieldname'=>'tns:common_array'),
 179      array('return'=>'tns:common_array1'),
 180      $NAMESPACE);
 181  
 182  $server->register(
 183      'save_faq_comment',
 184      array('fieldname'=>'tns:common_array'),
 185      array('return'=>'tns:common_array'),
 186      $NAMESPACE);
 187  
 188  $server->register(
 189      'update_ticket_comment',
 190      array('fieldname'=>'tns:common_array'),
 191      array('return'=>'tns:common_array'),
 192      $NAMESPACE);
 193  
 194  $server->register(
 195          'close_current_ticket',
 196      array('fieldname'=>'tns:common_array'),
 197      array('return'=>'xsd:string'),
 198      $NAMESPACE);
 199  
 200  $server->register(
 201      'update_login_details',
 202      array('fieldname'=>'tns:common_array'),
 203      array('return'=>'xsd:string'),
 204      $NAMESPACE);
 205  
 206  $server->register(
 207      'send_mail_for_password',
 208      array('email'=>'xsd:string'),
 209      array('return'=>'xsd:string'),
 210      $NAMESPACE);
 211  
 212  $server->register(
 213          'get_ticket_creator',
 214      array('fieldname'=>'tns:common_array'),
 215      array('return'=>'xsd:string'),
 216      $NAMESPACE);
 217  
 218  $server->register(
 219      'get_picklists',
 220      array('fieldname'=>'tns:common_array'),
 221      array('return'=>'tns:common_array'),
 222      $NAMESPACE);
 223  
 224  $server->register(
 225      'get_ticket_attachments',
 226      array('fieldname'=>'tns:common_array'),
 227      array('return'=>'tns:common_array'),
 228      $NAMESPACE);
 229  
 230  $server->register(
 231      'get_filecontent',
 232      array('fieldname'=>'tns:common_array'),
 233      array('return'=>'tns:common_array'),
 234      $NAMESPACE);
 235  
 236  $server->register(
 237      'add_ticket_attachment',
 238      array('fieldname'=>'tns:common_array'),
 239      array('return'=>'tns:common_array'),
 240      $NAMESPACE);
 241  
 242  $server->register(
 243      'get_cf_field_details',
 244      array('id'=>'xsd:string','contactid'=>'xsd:string','sessionid'=>'xsd:string'),
 245      array('return'=>'tns:field_details_array'),
 246      $NAMESPACE);
 247  
 248  $server->register(
 249          'get_check_account_id',
 250      array('id'=>'xsd:string'),
 251      array('return'=>'xsd:string'),
 252      $NAMESPACE);
 253  
 254          //to get details of quotes,invoices and documents
 255  $server->register(
 256      'get_details',
 257      array('id'=>'xsd:string','block'=>'xsd:string','contactid'=>'xsd:string','sessionid'=>'xsd:string'),
 258      array('return'=>'tns:field_details_array'),
 259      $NAMESPACE);
 260  
 261          //to get the products list for the entire account of a contact
 262  $server->register(
 263      'get_product_list_values',
 264      array('id'=>'xsd:string','block'=>'xsd:string','sessionid'=>'xsd:string','only_mine'=>'xsd:string'),
 265      array('return'=>'tns:field_details_array'),
 266      $NAMESPACE);
 267  
 268  $server->register(
 269      'get_list_values',
 270      array('id'=>'xsd:string','block'=>'xsd:string','sessionid'=>'xsd:string','only_mine'=>'xsd:string'),
 271      array('return'=>'tns:field_datalist_array'),
 272      $NAMESPACE);
 273  
 274  $server->register(
 275      'get_product_urllist',
 276      array('customerid'=>'xsd:string','productid'=>'xsd:string','block'=>'xsd:string'),
 277      array('return'=>'tns:field_datalist_array'),
 278      $NAMESPACE);
 279  
 280  $server->register(
 281      'get_pdf',
 282      array('id'=>'xsd:string','block'=>'xsd:string','contactid'=>'xsd:string','sessionid'=>'xsd:string'),
 283      array('return'=>'tns:field_datalist_array'),
 284      $NAMESPACE);
 285  
 286  $server->register(
 287      'get_filecontent_detail',
 288      array('id'=>'xsd:string','folderid'=>'xsd:string','block'=>'xsd:string','contactid'=>'xsd:string','sessionid'=>'xsd:string'),
 289      array('return'=>'tns:get_ticket_attachments_array'),
 290      $NAMESPACE);
 291  
 292  $server->register(
 293      'get_invoice_detail',
 294      array('id'=>'xsd:string','block'=>'xsd:string','contactid'=>'xsd:string','sessionid'=>'xsd:string'),
 295      array('return'=>'tns:field_details_array'),
 296      $NAMESPACE);
 297  
 298  $server->register(
 299      'get_modules',
 300      array(),
 301      array('return'=>'tns:field_details_array'),
 302      $NAMESPACE);
 303  
 304  $server->register(
 305      'show_all',
 306      array('module'=>'xsd:string'),
 307      array('return'=>'xsd:string'),
 308      $NAMESPACE);
 309  
 310  $server->register(
 311      'get_documents',
 312      array('id'=>'xsd:string','module'=>'xsd:string','customerid'=>'xsd:string','sessionid'=> 'xsd:string'),
 313      array('return'=>'tns:field_details_array'),
 314      $NAMESPACE);
 315  
 316  $server->register(
 317      'updateCount',
 318      array('id'=>'xsd:string'),
 319      array('return'=>'xsd:string'),
 320      $NAMESPACE);
 321  
 322  //to get the Services list for the entire account of a contact
 323  $server->register(
 324      'get_service_list_values',
 325      array('id'=>'xsd:string','module'=>'xsd:string','sessionid'=>'xsd:string','only_mine'=>'xsd:string'),
 326      array('return'=>'tns:field_details_array'),
 327      $NAMESPACE);
 328  
 329  //to get the Project Tasks for a given Project
 330  $server->register(
 331      'get_project_components',
 332      array('id'=>'xsd:string','module'=>'xsd:string','customerid'=>'xsd:string','sessionid'=>'xsd:string'),
 333      array('return'=>'tns:field_details_array'),
 334      $NAMESPACE);
 335  
 336  //to get the Project Tickets for a given Project
 337  $server->register(
 338      'get_project_tickets',
 339      array('id'=>'xsd:string','module'=>'xsd:string','customerid'=>'xsd:string','sessionid'=>'xsd:string'),
 340      array('return'=>'tns:field_details_array'),
 341      $NAMESPACE);
 342  
 343  /**
 344   * Helper class to provide functionality like caching etc...
 345   */
 346  class Vtiger_Soap_CustomerPortal {
 347  
 348      /** Preference value caching */
 349      static $_prefs_cache = array();
 350  	static function lookupPrefValue($key) {
 351          if(self::$_prefs_cache[$key]) {
 352              return self::$_prefs_cache[$key];
 353          }
 354          return false;
 355      }
 356  	static function updatePrefValue($key, $value) {
 357          self::$_prefs_cache[$key] = $value;
 358      }
 359  
 360      /** Sessionid caching for re-use */
 361      static $_sessionid = array();
 362  	static function lookupSessionId($key) {
 363          if(isset(self::$_sessionid[$key])) {
 364              return self::$_sessionid[$key];
 365          }
 366          return false;
 367      }
 368  	static function updateSessionId($key, $value) {
 369          self::$_sessionid[$key] = $value;
 370      }
 371  
 372      /** Store available module information */
 373      static $_modules = false;
 374  	static function lookupAllowedModules() {
 375          return self::$_modules;
 376      }
 377  	static function updateAllowedModules($modules) {
 378          self::$_modules = $modules;
 379      }
 380  
 381  }
 382  
 383  /**    function used to get the list of ticket comments
 384   * @param array $input_array - array which contains the following parameters
 385   * int $id - customer id
 386   * string $sessionid - session id
 387   * int $ticketid - ticket id
 388   * @return array $response - ticket comments and details as a array with elements comments, owner and createdtime which will be returned from the function get_ticket_comments_list
 389  */
 390  function get_ticket_comments($input_array)
 391  {
 392      global $adb,$log,$current_user;
 393      $adb->println("Entering customer portal function get_ticket_comments");
 394      $adb->println($input_array);
 395  
 396      $id = $input_array['id'];
 397      $sessionid = $input_array['sessionid'];
 398      $ticketid = (int) $input_array['ticketid'];
 399  
 400      if(!validateSession($id,$sessionid))
 401          return null;
 402  
 403      $userid = getPortalUserid();
 404      $user = new Users();
 405      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
 406  
 407      if(isPermitted('ModComments', 'DetailView')) {
 408          $response = _getTicketModComments($ticketid);
 409      }
 410      return $response;
 411  }
 412  
 413  /**
 414   * Function added to get the Tickets Comments
 415   * @global <PearDataBase> $adb
 416   * @param <Integer> $ticketId
 417   * @return <Array>
 418   */
 419  function _getTicketModComments($ticketId) {
 420      global $adb;
 421      $sql = "SELECT * FROM vtiger_modcomments
 422              INNER JOIN vtiger_crmentity ON vtiger_modcomments.modcommentsid = vtiger_crmentity.crmid AND deleted = 0
 423              WHERE related_to = ? ORDER BY createdtime DESC";
 424      $result = $adb->pquery($sql, array($ticketId));
 425      $rows = $adb->num_rows($result);
 426      $output = array();
 427  
 428      for($i=0; $i<$rows; $i++) {
 429          $customer = $adb->query_result($result, $i, 'customer');
 430          $owner = $adb->query_result($result, $i, 'smownerid');
 431  
 432          if(!empty($customer)) {
 433              $emailResult = $adb->pquery('SELECT * FROM vtiger_portalinfo WHERE id = ?', array($customer));
 434              $output[$i]['owner'] = $adb->query_result($emailResult, 0 ,'user_name');
 435          } else {
 436              $output[$i]['owner'] = getOwnerName($owner);
 437          }
 438  
 439          $output[$i]['comments'] = nl2br($adb->query_result($result, $i, 'commentcontent'));
 440          $output[$i]['createdtime'] = $adb->query_result($result, $i, 'createdtime');
 441      }
 442      return $output;
 443  }
 444  
 445  /**    function used to get the combo values ie., picklist values of the HelpDesk module and also the list of products
 446   *    @param array $input_array - array which contains the following parameters
 447   =>    int $id - customer id
 448      string $sessionid - session id
 449      *    return array $output - array which contains the product id, product name, ticketpriorities, ticketseverities, ticketcategories and module owners list
 450      */
 451  function get_combo_values($input_array)
 452  {
 453      global $adb,$log;
 454      $adb->println("Entering customer portal function get_combo_values");
 455      $adb->println($input_array);
 456  
 457      $id = $input_array['id'];
 458      $sessionid = $input_array['sessionid'];
 459  
 460      if(!validateSession($id,$sessionid))
 461          return null;
 462  
 463      $output = Array();
 464      $sql = "select  productid, productname from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0";
 465      $result = $adb->pquery($sql, array());
 466      $noofrows = $adb->num_rows($result);
 467      for($i=0;$i<$noofrows;$i++)
 468      {
 469          $check = checkModuleActive('Products');
 470          if($check == false){
 471              $output['productid']['productid']="#MODULE INACTIVE#";
 472              $output['productname']['productname']="#MODULE INACTIVE#";
 473              break;
 474          }
 475          $output['productid']['productid'][$i] = $adb->query_result($result,$i,"productid");
 476          $output['productname']['productname'][$i] = decode_html($adb->query_result($result,$i,"productname"));
 477      }
 478  
 479      $userid = getPortalUserid();
 480  
 481      //We are going to display the picklist entries associated with admin user (role is H2)
 482      $roleres = $adb->pquery("SELECT roleid from vtiger_user2role where userid = ?",array($userid));
 483      $RowCount = $adb->num_rows($roleres);
 484      if($RowCount > 0){
 485          $admin_role = $adb->query_result($roleres,0,'roleid');
 486      }
 487      $result1 = $adb->pquery("select vtiger_ticketpriorities.ticketpriorities from vtiger_ticketpriorities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketpriorities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array());
 488      for($i=0;$i<$adb->num_rows($result1);$i++)
 489      {
 490          $output['ticketpriorities']['ticketpriorities'][$i] = $adb->query_result($result1,$i,"ticketpriorities");
 491      }
 492  
 493      $result2 = $adb->pquery("select vtiger_ticketseverities.ticketseverities from vtiger_ticketseverities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketseverities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array());
 494      for($i=0;$i<$adb->num_rows($result2);$i++)
 495      {
 496          $output['ticketseverities']['ticketseverities'][$i] = $adb->query_result($result2,$i,"ticketseverities");
 497      }
 498  
 499      $result3 = $adb->pquery("select vtiger_ticketcategories.ticketcategories from vtiger_ticketcategories inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketcategories.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array());
 500      for($i=0;$i<$adb->num_rows($result3);$i++)
 501      {
 502          $output['ticketcategories']['ticketcategories'][$i] = $adb->query_result($result3,$i,"ticketcategories");
 503      }
 504  
 505      // Gather service contract information
 506      if(!vtlib_isModuleActive('ServiceContracts')) {
 507          $output['serviceid']['serviceid']="#MODULE INACTIVE#";
 508          $output['servicename']['servicename']="#MODULE INACTIVE#";
 509      } else {
 510          $servicequery = "SELECT vtiger_servicecontracts.servicecontractsid,vtiger_servicecontracts.subject
 511                              FROM vtiger_servicecontracts
 512                              INNER JOIN vtiger_crmentity on vtiger_crmentity.crmid=vtiger_servicecontracts.servicecontractsid
 513                                      AND vtiger_crmentity.deleted = 0
 514                              WHERE vtiger_servicecontracts.sc_related_to = ?";
 515          $params = array($id);
 516          $showAll = show_all('HelpDesk');
 517          if($showAll == 'true') {
 518              $servicequery .= ' OR vtiger_servicecontracts.sc_related_to = (SELECT accountid FROM vtiger_contactdetails WHERE contactid=? AND accountid <> 0)
 519                                  OR vtiger_servicecontracts.sc_related_to IN
 520                                              (SELECT contactid FROM vtiger_contactdetails WHERE accountid =
 521                                                      (SELECT accountid FROM vtiger_contactdetails WHERE contactid=? AND accountid <> 0))
 522                              ';
 523              array_push($params, $id);
 524              array_push($params, $id);
 525          }
 526          $serviceResult = $adb->pquery($servicequery,$params);
 527  
 528          for($i=0;$i < $adb->num_rows($serviceResult);$i++){
 529              $serviceid = $adb->query_result($serviceResult,$i,'servicecontractsid');
 530              $output['serviceid']['serviceid'][$i] = $serviceid;
 531              $output['servicename']['servicename'][$i] = $adb->query_result($serviceResult,$i,'subject');
 532          }
 533      }
 534  
 535      return $output;
 536  
 537  }
 538  
 539  /**    function to get the Knowledge base details
 540   *    @param array $input_array - array which contains the following parameters
 541   =>    int $id - customer id
 542      string $sessionid - session id
 543      *    return array $result - array which contains the faqcategory, all product ids , product names and all faq details
 544      */
 545  function get_KBase_details($input_array)
 546  {
 547      global $adb,$log;
 548      $adb->println("Entering customer portal function get_KBase_details");
 549      $adb->println($input_array);
 550  
 551      $id = $input_array['id'];
 552      $sessionid = $input_array['sessionid'];
 553  
 554      if(!validateSession($id,$sessionid))
 555          return null;
 556  
 557      $userid = getPortalUserid();
 558      $result['faqcategory'] = array();
 559      $result['product'] = array();
 560      $result['faq'] = array();
 561  
 562      //We are going to display the picklist entries associated with admin user (role is H2)
 563      $roleres = $adb->pquery("SELECT roleid from vtiger_user2role where userid = ?",array($userid));
 564      $RowCount = $adb->num_rows($roleres);
 565      if($RowCount > 0){
 566          $admin_role = $adb->query_result($roleres,0,'roleid');
 567      }
 568      $category_query = "select vtiger_faqcategories.faqcategories from vtiger_faqcategories inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_faqcategories.picklist_valueid and vtiger_role2picklist.roleid='$admin_role'";
 569      $category_result = $adb->pquery($category_query, array());
 570      $category_noofrows = $adb->num_rows($category_result);
 571      for($j=0;$j<$category_noofrows;$j++)
 572      {
 573          $faqcategory = $adb->query_result($category_result,$j,'faqcategories');
 574          $result['faqcategory'][$j] = $faqcategory;
 575      }
 576  
 577      $check = checkModuleActive('Products');
 578  
 579      if($check == true) {
 580          $product_query = "select productid, productname from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0";
 581          $product_result = $adb->pquery($product_query, array());
 582          $product_noofrows = $adb->num_rows($product_result);
 583          for($i=0;$i<$product_noofrows;$i++)
 584          {
 585              $productid = $adb->query_result($product_result,$i,'productid');
 586              $productname = $adb->query_result($product_result,$i,'productname');
 587              $result['product'][$i]['productid'] = $productid;
 588              $result['product'][$i]['productname'] = $productname;
 589          }
 590      }
 591      $faq_query = "select vtiger_faq.*, vtiger_crmentity.createdtime, vtiger_crmentity.modifiedtime from vtiger_faq " .
 592          "inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_faq.id " .
 593          "where vtiger_crmentity.deleted=0 and vtiger_faq.status='Published' order by vtiger_crmentity.modifiedtime DESC";
 594      $faq_result = $adb->pquery($faq_query, array());
 595      $faq_noofrows = $adb->num_rows($faq_result);
 596      for($k=0;$k<$faq_noofrows;$k++)
 597      {
 598          $faqid = $adb->query_result($faq_result,$k,'id');
 599          $moduleid = $adb->query_result($faq_result,$k,'faq_no');
 600          $result['faq'][$k]['faqno'] = $moduleid;
 601          $result['faq'][$k]['id'] = $faqid;
 602          if($check == true) {
 603              $result['faq'][$k]['product_id']  = $adb->query_result($faq_result,$k,'product_id');
 604          }
 605          $result['faq'][$k]['question'] =  nl2br($adb->query_result($faq_result,$k,'question'));
 606          $result['faq'][$k]['answer'] = nl2br($adb->query_result($faq_result,$k,'answer'));
 607          $result['faq'][$k]['category'] = $adb->query_result($faq_result,$k,'category');
 608          $result['faq'][$k]['faqcreatedtime'] = $adb->query_result($faq_result,$k,'createdtime');
 609          $result['faq'][$k]['faqmodifiedtime'] = $adb->query_result($faq_result,$k,'modifiedtime');
 610  
 611          $faq_comment_query = "select * from vtiger_faqcomments where faqid=? order by createdtime DESC";
 612          $faq_comment_result = $adb->pquery($faq_comment_query, array($faqid));
 613          $faq_comment_noofrows = $adb->num_rows($faq_comment_result);
 614          for($l=0;$l<$faq_comment_noofrows;$l++)
 615          {
 616              $faqcomments = nl2br($adb->query_result($faq_comment_result,$l,'comments'));
 617              $faqcreatedtime = $adb->query_result($faq_comment_result,$l,'createdtime');
 618              if($faqcomments != '')
 619              {
 620                  $result['faq'][$k]['comments'][$l] = $faqcomments;
 621                  $result['faq'][$k]['createdtime'][$l] = $faqcreatedtime;
 622              }
 623          }
 624      }
 625      $adb->println($result);
 626      return $result;
 627  }
 628  
 629  /**    function to save the faq comment
 630   *    @param array $input_array - array which contains the following values
 631   =>     int $id - Customer ie., Contact id
 632      int $sessionid - session id
 633      int $faqid - faq id
 634      string $comment - comment to be added with the FAQ
 635      *    return array $result - This function will call get_KBase_details and return that array
 636      */
 637  function save_faq_comment($input_array)
 638  {
 639      global $adb;
 640      $adb->println("Entering customer portal function save_faq_comment");
 641      $adb->println($input_array);
 642  
 643      $id = $input_array['id'];
 644      $sessionid = $input_array['sessionid'];
 645      $faqid = (int) $input_array['faqid'];
 646      $comment = $input_array['comment'];
 647  
 648      if(!validateSession($id,$sessionid))
 649          return null;
 650  
 651      $createdtime = $adb->formatDate(date('YmdHis'),true);
 652      if(trim($comment) != '')
 653      {
 654          $faq_query = "insert into vtiger_faqcomments values(?,?,?,?)";
 655          $adb->pquery($faq_query, array('', $faqid, $comment, $createdtime));
 656      }
 657  
 658      $params = Array('id'=>"$id", 'sessionid'=>"$sessionid");
 659      $result = get_KBase_details($input_array);
 660  
 661      return $result;
 662  }
 663  
 664  /** function to get a list of tickets and to search tickets
 665   * @param array $input_array - array which contains the following values
 666   =>     int $id - Customer ie., Contact id
 667      int $only_mine - if true it will display only tickets related to contact
 668      otherwise displays tickets related to account it belongs and all the contacts that are under the same account
 669      int $where - used for searching tickets
 670      string $match - used for matching tickets
 671      *    return array $result - This function will call get_KBase_details and return that array
 672      */
 673  
 674  
 675  function get_tickets_list($input_array) {
 676  
 677      //To avoid SQL injection we are type casting as well as bound the id variable.
 678      $id = (int) vtlib_purify($input_array['id']);
 679  
 680      $only_mine = $input_array['onlymine'];
 681      $where = vtlib_purifyForSql($input_array['where']); //addslashes is already added with where condition fields in portal itself
 682      $match = $input_array['match'];
 683      $sessionid = $input_array['sessionid'];
 684  
 685      if(!validateSession($id,$sessionid))
 686          return null;
 687  
 688      require_once ('modules/HelpDesk/HelpDesk.php');
 689      require_once ('include/utils/UserInfoUtil.php');
 690  
 691      global $adb,$log;
 692      global $current_user;
 693      $log->debug("Entering customer portal function get_ticket_list");
 694  
 695      $user = new Users();
 696      $userid = getPortalUserid();
 697  
 698      $show_all = show_all('HelpDesk');
 699      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
 700  
 701      // Prepare where conditions based on search query
 702      $join_type = '';
 703      $where_conditions = '';
 704      if(trim($where) != '') {
 705          if($match == 'all' || $match == '') {
 706              $join_type = " AND ";
 707          } elseif($match == 'any') {
 708              $join_type = " OR ";
 709          }
 710          $where = explode("&&&",$where);
 711          $where_conditions = implode($join_type, $where);
 712      }
 713  
 714      $entity_ids_list = array();
 715      if($only_mine == 'true' || $show_all == 'false')
 716      {
 717          array_push($entity_ids_list,$id);
 718      }
 719      else
 720      {
 721          $contactquery = "SELECT contactid, accountid FROM vtiger_contactdetails " .
 722              " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid" .
 723              " AND vtiger_crmentity.deleted = 0 " .
 724              " WHERE (accountid = (SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?)  AND accountid != 0) OR contactid = ?";
 725          $contactres = $adb->pquery($contactquery, array($id,$id));
 726          $no_of_cont = $adb->num_rows($contactres);
 727          for($i=0;$i<$no_of_cont;$i++)
 728          {
 729              $cont_id = $adb->query_result($contactres,$i,'contactid');
 730              $acc_id = $adb->query_result($contactres,$i,'accountid');
 731              if(!in_array($cont_id, $entity_ids_list))
 732                  $entity_ids_list[] = $cont_id;
 733              if(!in_array($acc_id, $entity_ids_list) && $acc_id != '0')
 734                  $entity_ids_list[] = $acc_id;
 735          }
 736      }
 737  
 738      $focus = new HelpDesk();
 739      $focus->filterInactiveFields('HelpDesk');
 740      foreach ($focus->list_fields as $fieldlabel => $values){
 741          foreach($values as $table => $fieldname){
 742              $fields_list[$fieldlabel] = $fieldname;
 743          }
 744      }
 745      $query = "SELECT vtiger_troubletickets.*, vtiger_crmentity.smownerid,vtiger_crmentity.createdtime, vtiger_crmentity.modifiedtime, '' AS setype
 746          FROM vtiger_troubletickets
 747          INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid AND vtiger_crmentity.deleted = 0
 748          WHERE (vtiger_troubletickets.contact_id IN (". generateQuestionMarks($entity_ids_list) .")";
 749      if($acc_id) {
 750          $query .= " OR vtiger_troubletickets.parent_id = $acc_id) ";
 751      } else {
 752          $query .= ')';
 753      }
 754      // Add conditions if there are any search parameters
 755      if ($join_type != '' && $where_conditions != '') {
 756          $query .= " AND (".$where_conditions.")";
 757      }
 758      $params = array($entity_ids_list);
 759  
 760  
 761      $TicketsfieldVisibilityByColumn = array();
 762      foreach($fields_list as $fieldlabel=> $fieldname) {
 763          $TicketsfieldVisibilityByColumn[$fieldname] =
 764              getColumnVisibilityPermission($current_user->id,$fieldname,'HelpDesk');
 765      }
 766  
 767      $res = $adb->pquery($query,$params);
 768      $noofdata = $adb->num_rows($res);
 769      for( $j= 0;$j < $noofdata; $j++)
 770      {
 771          $i=0;
 772          foreach($fields_list as $fieldlabel => $fieldname) {
 773              $fieldper = $TicketsfieldVisibilityByColumn[$fieldname]; //in troubletickets the list_fields has columns so we call this API
 774              if($fieldper == '1'){
 775                  continue;
 776              }
 777              $output[0]['head'][0][$i]['fielddata'] = $fieldlabel;
 778              $fieldvalue = $adb->query_result($res,$j,$fieldname);
 779              $ticketid = $adb->query_result($res,$j,'ticketid');
 780              if($fieldname == 'title'){
 781                  $fieldvalue = '<a href="index.php?module=HelpDesk&action=index&fun=detail&ticketid='.$ticketid.'">'.$fieldvalue.'</a>';
 782              }
 783              if($fieldname == 'parent_id') {
 784                  $crmid = $fieldvalue;
 785                  if ($crmid != '') {
 786                      $fieldvalues = getEntityName('Accounts', array($crmid));
 787                      $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
 788                  } else {
 789                      $fieldvalue = '';
 790                  }
 791              }
 792              if($fieldname == 'contact_id') {
 793                  if(!empty($fieldvalue)) {
 794                      $fieldvalues = getEntityName('Contacts', array($fieldvalue));
 795                      $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$fieldvalue.'">'.$fieldvalues[$fieldvalue].'</a>';
 796                  } else {
 797                      $fieldvalue = '';
 798                  }
 799              }
 800              if($fieldname == 'smownerid'){
 801                  $fieldvalue = getOwnerName($fieldvalue);
 802              }
 803              $output[1]['data'][$j][$i]['fielddata'] = $fieldvalue;
 804              $i++;
 805          }
 806      }
 807      $log->debug("Exiting customer portal function get_ticket_list");
 808      return $output;
 809  }
 810  
 811  /**    function used to create ticket which has been created from customer portal
 812   *    @param array $input_array - array which contains the following values
 813   =>     int $id - customer id
 814      int $sessionid - session id
 815      string $title - title of the ticket
 816      string $description - description of the ticket
 817      string $priority - priority of the ticket
 818      string $severity - severity of the ticket
 819      string $category - category of the ticket
 820      string $user_name - customer name
 821      int $parent_id - parent id ie., customer id as this customer is the parent for this ticket
 822      int $product_id - product id for the ticket
 823      string $module - module name where as based on this module we will get the module owner and assign this ticket to that corresponding user
 824      *    return array - currently created ticket array, if this is not created then all tickets list will be returned
 825      */
 826  function create_ticket($input_array)
 827  {
 828      global $adb,$log;
 829      $adb->println("Inside customer portal function create_ticket");
 830      $adb->println($input_array);
 831  
 832      $id = $input_array['id'];
 833      $sessionid = $input_array['sessionid'];
 834      $title = $input_array['title'];
 835      $description = $input_array['description'];
 836      $priority = $input_array['priority'];
 837      $severity = $input_array['severity'];
 838      $category = $input_array['category'];
 839      $user_name = $input_array['user_name'];
 840      $parent_id = (int) $input_array['parent_id'];
 841      $product_id = (int) $input_array['product_id'];
 842      $module = $input_array['module'];
 843      //$assigned_to = $input_array['assigned_to'];
 844      $servicecontractid = $input_array['serviceid'];
 845      $projectid = $input_array['projectid'];
 846  
 847      if(!validateSession($id,$sessionid))
 848          return null;
 849  
 850      $ticket = new HelpDesk();
 851  
 852      $ticket->column_fields[ticket_title] = vtlib_purify($title);
 853      $ticket->column_fields[description]= vtlib_purify($description);
 854      $ticket->column_fields[ticketpriorities]=$priority;
 855      $ticket->column_fields[ticketseverities]=$severity;
 856      $ticket->column_fields[ticketcategories]=$category;
 857      $ticket->column_fields[ticketstatus]='Open';
 858  
 859      $ticket->column_fields[contact_id]=$parent_id;
 860      $ticket->column_fields[product_id]=$product_id;
 861  
 862      $defaultAssignee = getDefaultAssigneeId();
 863  
 864      $ticket->column_fields['assigned_user_id']=$defaultAssignee;
 865      $ticket->column_fields['from_portal'] = 1;
 866  
 867      $accountResult = $adb->pquery('SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?', array($parent_id));
 868      $accountId = $adb->query_result($accountResult, 0, 'accountid');
 869      if(!empty($accountId)) $ticket->column_fields['parent_id'] = $accountId;
 870  
 871      $ticket->save("HelpDesk");
 872  
 873      $ticketresult = $adb->pquery("select vtiger_troubletickets.ticketid from vtiger_troubletickets
 874          inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_troubletickets.ticketid inner join vtiger_ticketcf on vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid
 875          where vtiger_crmentity.deleted=0 and vtiger_troubletickets.ticketid = ?", array($ticket->id));
 876      if($adb->num_rows($ticketresult) == 1)
 877      {
 878          $record_save = 1;
 879          $record_array[0]['new_ticket']['ticketid'] = $adb->query_result($ticketresult,0,'ticketid');
 880      }
 881      if($servicecontractid != ''){
 882          $res = $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)",
 883          array($servicecontractid, 'ServiceContracts', $ticket->id, 'HelpDesk'));
 884      }
 885      if($projectid != '') {
 886          $res = $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)",
 887          array($projectid, 'Project', $ticket->id, 'HelpDesk'));
 888      }
 889      if($record_save == 1)
 890      {
 891          $adb->println("Ticket from Portal is saved with id => ".$ticket->id);
 892          return $record_array;
 893      }
 894      else
 895      {
 896          $adb->println("There may be error in saving the ticket.");
 897          return null;
 898      }
 899  }
 900  
 901  /**    function used to update the ticket comment which is added from the customer portal
 902   *    @param array $input_array - array which contains the following values
 903   =>     int $id - customer id
 904      int $sessionid - session id
 905      int $ticketid - ticket id
 906      int $ownerid - customer ie., contact id who has added this ticket comment
 907      string $comments - comment which is added from the customer portal
 908      *    return void
 909      */
 910  function update_ticket_comment($input_array)
 911  {
 912      global $adb,$mod_strings,$current_user;
 913      $adb->println("Inside customer portal function update_ticket_comment");
 914      $adb->println($input_array);
 915  
 916      $id = $input_array['id'];
 917      $sessionid = $input_array['sessionid'];
 918      $ticketid = (int) $input_array['ticketid'];
 919      $ownerid = (int) $input_array['ownerid'];
 920      $comments = $input_array['comments'];
 921  
 922      $user = new Users();
 923      $userid = getPortalUserid();
 924      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
 925  
 926      if(!validateSession($id,$sessionid))
 927          return null;
 928  
 929      if(trim($comments) != '') {
 930          $modComments = CRMEntity::getInstance('ModComments');
 931          $modComments->column_fields['commentcontent'] = $comments;
 932          $modComments->column_fields['assigned_user_id'] =  $current_user->id;
 933          $modComments->column_fields['customer'] = $ownerid;
 934          $modComments->column_fields['related_to'] = $ticketid;
 935          $modComments->column_fields['from_portal'] = true;
 936          $modComments->save('ModComments');
 937      }
 938  }
 939  
 940  /**    function used to close the ticket
 941   *    @param array $input_array - array which contains the following values
 942   =>     int $id - customer id
 943      int $sessionid - session id
 944      int $ticketid - ticket id
 945      *    return string - success or failure message will be returned based on the ticket close update query
 946      */
 947  function close_current_ticket($input_array)
 948  {
 949      global $adb,$mod_strings,$log,$current_user;
 950      require_once ('modules/HelpDesk/HelpDesk.php');
 951      $adb->println("Inside customer portal function close_current_ticket");
 952      $adb->println($input_array);
 953  
 954      //foreach($input_array as $fieldname => $fieldvalue)$input_array[$fieldname] = mysql_real_escape_string($fieldvalue);
 955      $userid = getPortalUserid();
 956  
 957      $current_user->id = $userid;
 958      $id = $input_array['id'];
 959      $sessionid = $input_array['sessionid'];
 960      $ticketid = (int) $input_array['ticketid'];
 961  
 962      if(!validateSession($id,$sessionid))
 963          return null;
 964  
 965      $focus = new HelpDesk();
 966      $focus->id = $ticketid;
 967      $focus->retrieve_entity_info($focus->id,'HelpDesk');
 968      $focus->mode = 'edit';
 969      $focus->column_fields = array_map(decode_html, $focus->column_fields);
 970      $focus->column_fields['ticketstatus'] ='Closed';
 971      // Blank out the comments information to avoid un-necessary duplication
 972      $focus->column_fields['comments'] = '';
 973      $focus->column_fields['from_portal'] = 1;
 974      // END
 975      $focus->save("HelpDesk");
 976      return "closed";
 977  }
 978  
 979  /**    function used to authenticate whether the customer has access or not
 980   *    @param string $username - customer name for the customer portal
 981   *    @param string $password - password for the customer portal
 982   *    @param string $login - true or false. If true means function has been called for login process and we have to clear the session if any, false means not called during login and we should not unset the previous sessions
 983   *    return array $list - returns array with all the customer details
 984   */
 985  function authenticate_user($username,$password,$version,$login = 'true')
 986  {
 987      global $adb,$log;
 988      $adb->println("Inside customer portal function authenticate_user($username, $password, $login).");
 989      include ('vtigerversion.php');
 990      if(version_compare($version,'5.1.0','>=') == 0){
 991          $list[0] = "NOT COMPATIBLE";
 992            return $list;
 993      }
 994      $username = $adb->sql_escape_string($username);
 995      $password = $adb->sql_escape_string($password);
 996  
 997      $current_date = date("Y-m-d");
 998      $sql = "select id, user_name, user_password,last_login_time, support_start_date, support_end_date
 999                  from vtiger_portalinfo
1000                      inner join vtiger_customerdetails on vtiger_portalinfo.id=vtiger_customerdetails.customerid
1001                      inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_portalinfo.id
1002                  where vtiger_crmentity.deleted=0 and user_name=? and user_password = ?
1003                      and isactive=1 and vtiger_customerdetails.portal=1
1004                      and vtiger_customerdetails.support_start_date <= ? and vtiger_customerdetails.support_end_date >= ?";
1005      $result = $adb->pquery($sql, array($username, $password, $current_date, $current_date));
1006      $err[0]['err1'] = "MORE_THAN_ONE_USER";
1007      $err[1]['err1'] = "INVALID_USERNAME_OR_PASSWORD";
1008  
1009      $num_rows = $adb->num_rows($result);
1010  
1011      if($num_rows > 1)        return $err[0];//More than one user
1012      elseif($num_rows <= 0)        return $err[1];//No user
1013  
1014      $customerid = $adb->query_result($result,0,'id');
1015  
1016      $list[0]['id'] = $customerid;
1017      $list[0]['user_name'] = $adb->query_result($result,0,'user_name');
1018      $list[0]['user_password'] = $adb->query_result($result,0,'user_password');
1019      $list[0]['last_login_time'] = $adb->query_result($result,0,'last_login_time');
1020      $list[0]['support_start_date'] = $adb->query_result($result,0,'support_start_date');
1021      $list[0]['support_end_date'] = $adb->query_result($result,0,'support_end_date');
1022  
1023      //During login process we will pass the value true. Other times (change password) we will pass false
1024      if($login != 'false')
1025      {
1026          $sessionid = makeRandomPassword();
1027  
1028          unsetServerSessionId($customerid);
1029  
1030          $sql="insert into vtiger_soapservice values(?,?,?)";
1031          $result = $adb->pquery($sql, array($customerid,'customer' ,$sessionid));
1032  
1033          $list[0]['sessionid'] = $sessionid;
1034      }
1035  
1036      return $list;
1037  }
1038  
1039  /**    function used to change the password for the customer portal
1040   *    @param array $input_array - array which contains the following values
1041   =>     int $id - customer id
1042      int $sessionid - session id
1043      string $username - customer name
1044      string $password - new password to change
1045      *    return array $list - returns array with all the customer details
1046      */
1047  function change_password($input_array)
1048  {
1049      global $adb,$log;
1050      $log->debug("Entering customer portal function change_password");
1051      $adb->println($input_array);
1052  
1053      $id = (int) $input_array['id'];
1054      $sessionid = $input_array['sessionid'];
1055      $username = $input_array['username'];
1056      $password = $input_array['password'];
1057      $version = $input_array['version'];
1058  
1059      if(!validateSession($id,$sessionid))
1060          return null;
1061  
1062      $list = authenticate_user($username,$password,$version ,'false');
1063      if(!empty($list[0]['id'])){
1064          return array('MORE_THAN_ONE_USER');
1065      }
1066      $sql = "update vtiger_portalinfo set user_password=? where id=? and user_name=?";
1067      $result = $adb->pquery($sql, array($password, $id, $username));
1068  
1069      $log->debug("Exiting customer portal function change_password");
1070      return $list;
1071  }
1072  
1073  /**    function used to update the login details for the customer
1074   *    @param array $input_array - array which contains the following values
1075   =>     int $id - customer id
1076      int $sessionid - session id
1077      string $flag - login/logout, based on this flag, login or logout time will be updated for the customer
1078      *    return string $list - empty value
1079      */
1080  function update_login_details($input_array)
1081  {
1082      global $adb,$log;
1083      $log->debug("Entering customer portal function update_login_details");
1084      $adb->println("INPUT ARRAY for the function update_login_details");
1085      $adb->println($input_array);
1086  
1087      $id = $input_array['id'];
1088      $sessionid = $input_array['sessionid'];
1089      $flag = $input_array['flag'];
1090  
1091      if(!validateSession($id,$sessionid))
1092          return null;
1093  
1094      $current_time = $adb->formatDate(date('YmdHis'), true);
1095  
1096      if($flag == 'login')
1097      {
1098          $sql = "update vtiger_portalinfo set login_time=? where id=?";
1099          $result = $adb->pquery($sql, array($current_time, $id));
1100      }
1101      elseif($flag == 'logout')
1102      {
1103          $sql = "update vtiger_portalinfo set logout_time=?, last_login_time=login_time where id=?";
1104          $result = $adb->pquery($sql, array($current_time, $id));
1105      }
1106      $log->debug("Exiting customer portal function update_login_details");
1107  }
1108  
1109  /**    function used to send mail to the customer when he forgot the password and want to retrieve the password
1110   *    @param string $mailid - email address of the customer
1111   *    return message about the mail sending whether entered mail id is correct or not or is there any problem in mail sending
1112   */
1113  function send_mail_for_password($mailid)
1114  {
1115      global $adb,$mod_strings,$log;
1116      $log->debug("Entering customer portal function send_mail_for_password");
1117      $adb->println("Inside the function send_mail_for_password($mailid).");
1118  
1119      $sql = "select * from vtiger_portalinfo  where user_name = ? ";
1120      $res = $adb->pquery($sql, array($mailid));
1121      $user_name = $adb->query_result($res,0,'user_name');
1122      $password = $adb->query_result($res,0,'user_password');
1123      $isactive = $adb->query_result($res,0,'isactive');
1124  
1125      $fromquery = "select vtiger_users.user_name, vtiger_users.email1 from vtiger_users inner join vtiger_crmentity on vtiger_users.id = vtiger_crmentity.smownerid inner join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_crmentity.crmid where vtiger_contactdetails.email =?";
1126      $from_res = $adb->pquery($fromquery, array($mailid));
1127      $initialfrom = $adb->query_result($from_res,0,'user_name');
1128      $from = $adb->query_result($from_res,0,'email1');
1129  
1130      $contents = $mod_strings['LBL_LOGIN_DETAILS'];
1131      $contents .= "<br><br>".$mod_strings['LBL_USERNAME']." ".$user_name;
1132      $contents .= "<br>".$mod_strings['LBL_PASSWORD']." ".$password;
1133  
1134      $mail = new PHPMailer();
1135  
1136      $mail->Subject = $mod_strings['LBL_SUBJECT_PORTAL_LOGIN_DETAILS'];
1137      $mail->Body    = $contents;
1138      $mail->IsSMTP();
1139  
1140      $mailserverresult = $adb->pquery("select * from vtiger_systems where server_type=?", array('email'));
1141      $mail_server = $adb->query_result($mailserverresult,0,'server');
1142      $mail_server_username = $adb->query_result($mailserverresult,0,'server_username');
1143      $mail_server_password = $adb->query_result($mailserverresult,0,'server_password');
1144      $smtp_auth = $adb->query_result($mailserverresult,0,'smtp_auth');
1145  
1146      $mail->Host = $mail_server;
1147      if($smtp_auth == 'true')
1148      $mail->SMTPAuth = 'true';
1149      $mail->Username = $mail_server_username;
1150      $mail->Password = $mail_server_password;
1151      $mail->From = $from;
1152      $mail->FromName = $initialfrom;
1153  
1154      $mail->AddAddress($user_name);
1155      $mail->AddReplyTo($current_user->name);
1156      $mail->WordWrap = 50;
1157  
1158      $mail->IsHTML(true);
1159  
1160      $mail->AltBody = $mod_strings['LBL_ALTBODY'];
1161      if($mailid == '')
1162      {
1163          $ret_msg = "false@@@<b>".$mod_strings['LBL_GIVE_MAILID']."</b>";
1164      }
1165      elseif($user_name == '' && $password == '')
1166      {
1167          $ret_msg = "false@@@<b>".$mod_strings['LBL_CHECK_MAILID']."</b>";
1168      }
1169      elseif($isactive == 0)
1170      {
1171          $ret_msg = "false@@@<b>".$mod_strings['LBL_LOGIN_REVOKED']."</b>";
1172      }
1173      elseif(!$mail->Send())
1174      {
1175          $ret_msg = "false@@@<b>".$mod_strings['LBL_MAIL_COULDNOT_SENT']."</b>";
1176      }
1177      else
1178      {
1179          $ret_msg = "true@@@<b>".$mod_strings['LBL_MAIL_SENT']."</b>";
1180      }
1181  
1182      $adb->println("Exit from send_mail_for_password. $ret_msg");
1183      $log->debug("Exiting customer portal function send_mail_for_password");
1184      return $ret_msg;
1185  }
1186  
1187  /**    function used to get the ticket creater
1188   *    @param array $input_array - array which contains the following values
1189   =>    int $id - customer ie., contact id
1190      int $sessionid - session id
1191      int $ticketid - ticket id
1192      *    return int $creator - ticket created user id will be returned ie., smcreatorid from crmentity table
1193      */
1194  function get_ticket_creator($input_array)
1195  {
1196      global $adb,$log;
1197      $log->debug("Entering customer portal function get_ticket_creator");
1198      $adb->println("INPUT ARRAY for the function get_ticket_creator");
1199      $adb->println($input_array);
1200  
1201      $id = $input_array['id'];
1202      $sessionid = $input_array['sessionid'];
1203      $ticketid = (int) $input_array['ticketid'];
1204  
1205      if(!validateSession($id,$sessionid))
1206          return null;
1207  
1208      $res = $adb->pquery("select smcreatorid from vtiger_crmentity where crmid=?", array($ticketid));
1209      $creator = $adb->query_result($res,0,'smcreatorid');
1210      $log->debug("Exiting customer portal function get_ticket_creator");
1211      return $creator;
1212  }
1213  
1214  /**    function used to get the picklist values
1215   *    @param array $input_array - array which contains the following values
1216   =>    int $id - customer ie., contact id
1217      int $sessionid - session id
1218      string $picklist_name - picklist name you want to retrieve from database
1219      *    return array $picklist_array - all values of the corresponding picklist will be returned as a array
1220      */
1221  function get_picklists($input_array)
1222  {
1223      global $adb, $log;
1224      $log->debug("Entering customer portal function get_picklists");
1225      $adb->println("INPUT ARRAY for the function get_picklists");
1226      $adb->println($input_array);
1227  
1228      //To avoid SQL injection we are type casting as well as bound the id variable
1229      $id = (int) vtlib_purify($input_array['id']);
1230      $sessionid = $input_array['sessionid'];
1231      //To avoid SQL injection.
1232      $picklist_name = vtlib_purifyForSql($input_array['picklist_name']);
1233      if(empty($picklist_name)) return null;
1234  
1235      if(!validateSession($id,$sessionid))
1236      return null;
1237  
1238      $picklist_array = Array();
1239  
1240      $admin_role = 'H2';
1241      $userid = getPortalUserid();
1242      $roleres = $adb->pquery("SELECT roleid from vtiger_user2role where userid = ?", array($userid));
1243      $RowCount = $adb->num_rows($roleres);
1244      if($RowCount > 0){
1245          $admin_role = $adb->query_result($roleres,0,'roleid');
1246      }
1247  
1248      $res = $adb->pquery("select vtiger_". $picklist_name.".* from vtiger_". $picklist_name." inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_". $picklist_name.".picklist_valueid and vtiger_role2picklist.roleid='$admin_role'", array());
1249      for($i=0;$i<$adb->num_rows($res);$i++)
1250      {
1251          $picklist_val = $adb->query_result($res,$i,$picklist_name);
1252          $picklist_array[$i] = $picklist_val;
1253      }
1254  
1255      $adb->println($picklist_array);
1256      $log->debug("Exiting customer portal function get_picklists($picklist_name)");
1257      return $picklist_array;
1258  }
1259  
1260  /**    function to get the attachments of a ticket
1261   *    @param array $input_array - array which contains the following values
1262   =>    int $id - customer ie., contact id
1263      int $sessionid - session id
1264      int $ticketid - ticket id
1265      *    return array $output - This will return all the file details related to the ticket
1266      */
1267  function get_ticket_attachments($input_array)
1268  {
1269      global $adb,$log;
1270      $log->debug("Entering customer portal function get_ticket_attachments");
1271      $adb->println("INPUT ARRAY for the function get_ticket_attachments");
1272      $adb->println($input_array);
1273  
1274      $check = checkModuleActive('Documents');
1275      if($check == false){
1276          return array("#MODULE INACTIVE#");
1277      }
1278      $id = $input_array['id'];
1279      $sessionid = $input_array['sessionid'];
1280      $ticketid = $input_array['ticketid'];
1281  
1282      $isPermitted = check_permission($id,'HelpDesk',$ticketid);
1283      if($isPermitted == false) {
1284          return array("#NOT AUTHORIZED#");
1285      }
1286  
1287  
1288      if(!validateSession($id,$sessionid))
1289      return null;
1290  
1291      $query = "select vtiger_troubletickets.ticketid, vtiger_attachments.*,vtiger_notes.filename,vtiger_notes.filelocationtype from vtiger_troubletickets " .
1292          "left join vtiger_senotesrel on vtiger_senotesrel.crmid=vtiger_troubletickets.ticketid " .
1293          "left join vtiger_notes on vtiger_notes.notesid=vtiger_senotesrel.notesid " .
1294          "inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_notes.notesid " .
1295          "left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_notes.notesid " .
1296          "left join vtiger_attachments on vtiger_attachments.attachmentsid = vtiger_seattachmentsrel.attachmentsid " .
1297          "and vtiger_crmentity.deleted = 0 where vtiger_troubletickets.ticketid =?";
1298  
1299      $res = $adb->pquery($query, array($ticketid));
1300      $noofrows = $adb->num_rows($res);
1301      for($i=0;$i<$noofrows;$i++)
1302      {
1303          $filename = $adb->query_result($res,$i,'filename');
1304          $filepath = $adb->query_result($res,$i,'path');
1305  
1306          $fileid = $adb->query_result($res,$i,'attachmentsid');
1307          $filesize = filesize($filepath.$fileid."_".$filename);
1308          $filetype = $adb->query_result($res,$i,'type');
1309          $filelocationtype = $adb->query_result($res,$i,'filelocationtype');
1310          //Now we will not pass the file content to CP, when the customer click on the link we will retrieve
1311          //$filecontents = base64_encode(file_get_contents($filepath.$fileid."_".$filename));//fread(fopen($filepath.$filename, "r"), $filesize));
1312  
1313          $output[$i]['fileid'] = $fileid;
1314          $output[$i]['filename'] = $filename;
1315          $output[$i]['filetype'] = $filetype;
1316          $output[$i]['filesize'] = $filesize;
1317          $output[$i]['filelocationtype'] = $filelocationtype;
1318      }
1319      $log->debug("Exiting customer portal function get_ticket_attachments");
1320      return $output;
1321  }
1322  
1323  /**    function used to get the contents of a file
1324   *    @param array $input_array - array which contains the following values
1325   =>    int $id - customer ie., contact id
1326      int $sessionid - session id
1327      int $fileid - id of the file to which we want contents
1328      string $filename - name of the file to which we want contents
1329      *    return $filecontents array with single file contents like [fileid] => filecontent
1330      */
1331  function get_filecontent($input_array)
1332  {
1333      global $adb,$log;
1334      $log->debug("Entering customer portal function get_filecontent");
1335      $adb->println("INPUT ARRAY for the function get_filecontent");
1336      $adb->println($input_array);
1337      $id = $input_array['id'];
1338      $sessionid = $input_array['sessionid'];
1339      $fileid = $input_array['fileid'];
1340      $filename = $input_array['filename'];
1341      $ticketid = $input_array['ticketid'];
1342      if(!validateSession($id,$sessionid))
1343      return null;
1344  
1345      $query = 'SELECT vtiger_attachments.path FROM vtiger_attachments
1346      INNER JOIN vtiger_seattachmentsrel ON vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid
1347      INNER JOIN vtiger_notes ON vtiger_notes.notesid = vtiger_seattachmentsrel.crmid
1348      INNER JOIN vtiger_senotesrel ON vtiger_senotesrel.notesid = vtiger_notes.notesid
1349      INNER JOIN vtiger_troubletickets ON vtiger_troubletickets.ticketid = vtiger_senotesrel.crmid
1350      WHERE vtiger_troubletickets.ticketid = ? AND vtiger_attachments.name = ? AND vtiger_attachments.attachmentsid = ?';
1351      $res = $adb->pquery($query, array($ticketid, $filename,$fileid));
1352      if($adb->num_rows($res)>0)
1353      {
1354          $filenamewithpath = $adb->query_result($res,0,'path').$fileid."_".$filename;
1355          $filecontents[$fileid] = base64_encode(file_get_contents($filenamewithpath));
1356      }
1357      $log->debug("Exiting customer portal function get_filecontent ");
1358      return $filecontents;
1359  }
1360  
1361  /**    function to add attachment for a ticket ie., the passed contents will be write in a file and the details will be stored in database
1362   *    @param array $input_array - array which contains the following values
1363   =>    int $id - customer ie., contact id
1364      int $sessionid - session id
1365      int $ticketid - ticket id
1366      string $filename - file name to be attached with the ticket
1367      string $filetype - file type
1368      int $filesize - file size
1369      string $filecontents - file contents as base64 encoded format
1370      *    return void
1371      */
1372  function add_ticket_attachment($input_array)
1373  {
1374      global $adb,$log;
1375      global $root_directory, $upload_badext;
1376      $log->debug("Entering customer portal function add_ticket_attachment");
1377      $adb->println("INPUT ARRAY for the function add_ticket_attachment");
1378      $adb->println($input_array);
1379      $id = $input_array['id'];
1380      $sessionid = $input_array['sessionid'];
1381      $ticketid = $input_array['ticketid'];
1382      $filename = $input_array['filename'];
1383      $filetype = $input_array['filetype'];
1384      $filesize = $input_array['filesize'];
1385      $filecontents = $input_array['filecontents'];
1386  
1387      if(!validateSession($id,$sessionid))
1388      return null;
1389  
1390      //decide the file path where we should upload the file in the server
1391      $upload_filepath = decideFilePath();
1392  
1393      $attachmentid = $adb->getUniqueID("vtiger_crmentity");
1394  
1395      //fix for space in file name
1396      $filename = sanitizeUploadFileName($filename, $upload_badext);
1397      $new_filename = $attachmentid.'_'.$filename;
1398  
1399      $data = base64_decode($filecontents);
1400      $description = 'CustomerPortal Attachment';
1401  
1402      //write a file with the passed content
1403      $handle = @fopen($upload_filepath.$new_filename,'w');
1404      fputs($handle, $data);
1405      fclose($handle);
1406  
1407      //Now store this file information in db and relate with the ticket
1408      $date_var = $adb->formatDate(date('Y-m-d H:i:s'), true);
1409  
1410      $crmquery = "insert into vtiger_crmentity (crmid,setype,description,createdtime) values(?,?,?,?)";
1411      $crmresult = $adb->pquery($crmquery, array($attachmentid, 'HelpDesk Attachment', $description, $date_var));
1412  
1413      $attachmentquery = "insert into vtiger_attachments(attachmentsid,name,description,type,path) values(?,?,?,?,?)";
1414      $attachmentreulst = $adb->pquery($attachmentquery, array($attachmentid, $filename, $description, $filetype, $upload_filepath));
1415  
1416      $relatedquery = "insert into vtiger_seattachmentsrel values(?,?)";
1417      $relatedresult = $adb->pquery($relatedquery, array($ticketid, $attachmentid));
1418  
1419      $user_id = getDefaultAssigneeId();
1420  
1421      require_once ('modules/Documents/Documents.php');
1422      $focus = new Documents();
1423      $focus->column_fields['notes_title'] = $filename;
1424      $focus->column_fields['filename'] = $filename;
1425      $focus->column_fields['filetype'] = $filetype;
1426      $focus->column_fields['filesize'] = $filesize;
1427      $focus->column_fields['filelocationtype'] = 'I';
1428      $focus->column_fields['filedownloadcount']= 0;
1429      $focus->column_fields['filestatus'] = 1;
1430      $focus->column_fields['assigned_user_id'] = $user_id;
1431      $focus->column_fields['folderid'] = 1;
1432      $focus->parent_id = $ticketid;
1433      $focus->save('Documents');
1434  
1435      $related_doc = 'insert into vtiger_seattachmentsrel values (?,?)';
1436      $res = $adb->pquery($related_doc,array($focus->id,$attachmentid));
1437  
1438      $tic_doc = 'insert into vtiger_senotesrel values(?,?)';
1439      $res = $adb->pquery($tic_doc,array($ticketid,$focus->id));
1440      $log->debug("Exiting customer portal function add_ticket_attachment");
1441  }
1442  
1443  /**    Function used to validate the session
1444   *    @param int $id - contact id to which we want the session id
1445   *    @param string $sessionid - session id which will be passed from customerportal
1446   *    return true/false - return true if valid session otherwise return false
1447   **/
1448  function validateSession($id, $sessionid)
1449  {
1450      global $adb;
1451      $adb->println("Inside function validateSession($id, $sessionid)");
1452  
1453      if(empty($sessionid)) return false;
1454  
1455      $server_sessionid = getServerSessionId($id);
1456  
1457      $adb->println("Checking Server session id and customer input session id ==> $server_sessionid == $sessionid");
1458  
1459      if($server_sessionid == $sessionid) {
1460          $adb->println("Session id match. Authenticated to do the current operation.");
1461          return true;
1462      } else {
1463          $adb->println("Session id does not match. Not authenticated to do the current operation.");
1464          return false;
1465      }
1466  }
1467  
1468  
1469  /**    Function used to get the session id which was set during login time
1470   *    @param int $id - contact id to which we want the session id
1471   *    return string $sessionid - return the session id for the customer which is a random alphanumeric character string
1472   **/
1473  function getServerSessionId($id)
1474  {
1475      global $adb;
1476      $adb->println("Inside the function getServerSessionId($id)");
1477  
1478      //To avoid SQL injection we are type casting as well as bound the id variable. In each and every function we will call this function
1479      $id = (int) $id;
1480  
1481      $sessionid = Vtiger_Soap_CustomerPortal::lookupSessionId($id);
1482      if($sessionid === false) {
1483          $query = "select * from vtiger_soapservice where type='customer' and id=?";
1484          $result = $adb->pquery($query, array($id));
1485          if($adb->num_rows($result) > 0) {
1486              $sessionid = $adb->query_result($result,0,'sessionid');
1487              Vtiger_Soap_CustomerPortal::updateSessionId($id, $sessionid);
1488          }
1489      }
1490      return $sessionid;
1491  }
1492  
1493  /**    Function used to unset the server session id for the customer
1494   *    @param int $id - contact id to which customer we want to unset the session id
1495   **/
1496  function unsetServerSessionId($id)
1497  {
1498      global $adb,$log;
1499      $log->debug("Entering customer portal function unsetServerSessionId");
1500      $adb->println("Inside the function unsetServerSessionId");
1501  
1502      $id = (int) $id;
1503      Vtiger_Soap_CustomerPortal::updateSessionId($id, false);
1504  
1505      $adb->pquery("delete from vtiger_soapservice where type='customer' and id=?", array($id));
1506      $log->debug("Exiting customer portal function unsetServerSessionId");
1507      return;
1508  }
1509  
1510  
1511  /**    function used to get the Account name
1512   *    @param int $id - Account id
1513   *    return string $message - Account name returned
1514   */
1515  function get_account_name($accountid)
1516  {
1517      global $adb,$log;
1518      $log->debug("Entering customer portal function get_account_name");
1519      $res = $adb->pquery("select accountname from vtiger_account where accountid=?", array($accountid));
1520      $accountname=$adb->query_result($res,0,'accountname');
1521      $log->debug("Exiting customer portal function get_account_name");
1522      return $accountname;
1523  }
1524  
1525  /** function used to get the Contact name
1526   *  @param int $id -Contact id
1527   * return string $message -Contact name returned
1528   */
1529  function get_contact_name($contactid)
1530  {
1531      global $adb,$log;
1532      $log->debug("Entering customer portal function get_contact_name");
1533      $contact_name = '';
1534      if($contactid != '')
1535      {
1536          $sql = "select firstname,lastname from vtiger_contactdetails where contactid=?";
1537          $result = $adb->pquery($sql, array($contactid));
1538          $firstname = $adb->query_result($result,0,"firstname");
1539          $lastname = $adb->query_result($result,0,"lastname");
1540          $contact_name = $firstname." ".$lastname;
1541          return $contact_name;
1542      }
1543      $log->debug("Exiting customer portal function get_contact_name");
1544      return false;
1545  }
1546  
1547  /**     function used to get the Account id
1548   **      @param int $id - Contact id
1549   **      return string $message - Account id returned
1550   **/
1551  
1552  function get_check_account_id($id)
1553  {
1554      global $adb,$log;
1555      $log->debug("Entering customer portal function get_check_account_id");
1556      $res = $adb->pquery("select accountid from vtiger_contactdetails where contactid=?", array($id));
1557      $accountid=$adb->query_result($res,0,'accountid');
1558      $log->debug("Entering customer portal function get_check_account_id");
1559      return $accountid;
1560  }
1561  
1562  
1563  /**    function used to get the vendor name
1564   *    @param int $id - vendor id
1565   *    return string $name - Vendor name returned
1566   */
1567  
1568  function get_vendor_name($vendorid)
1569  {
1570      global $adb,$log;
1571      $log->debug("Entering customer portal function get_vendor_name");
1572      $res = $adb->pquery("select vendorname from vtiger_vendor where vendorid=?", array($vendorid));
1573      $name=$adb->query_result($res,0,'vendorname');
1574      $log->debug("Exiting customer portal function get_vendor_name");
1575      return $name;
1576  }
1577  
1578  
1579  /**    function used to get the Quotes/Invoice List
1580   *    @param int $id - id -Contactid
1581   *    return string $output - Quotes/Invoice list Array
1582   */
1583  
1584  function get_list_values($id,$module,$sessionid,$only_mine='true')
1585  {
1586      checkFileAccessForInclusion('modules/'.$module.'/'.$module.'.php');
1587      require_once('modules/'.$module.'/'.$module.'.php');
1588      require_once ('include/utils/UserInfoUtil.php');
1589      global $adb,$log,$current_user;
1590      $log->debug("Entering customer portal function get_list_values");
1591      $check = checkModuleActive($module);
1592      if($check == false){
1593          return array("#MODULE INACTIVE#");
1594      }
1595  
1596      //To avoid SQL injection we are type casting as well as bound the id variable.
1597      $id = (int) vtlib_purify($id);
1598      $user = new Users();
1599      $userid = getPortalUserid();
1600      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
1601      $focus = new $module();
1602      $focus->filterInactiveFields($module);
1603      foreach ($focus->list_fields as $fieldlabel => $values){
1604          foreach($values as $table => $fieldname){
1605              $fields_list[$fieldlabel] = $fieldname;
1606          }
1607      }
1608  
1609      if(!validateSession($id,$sessionid))
1610      return null;
1611  
1612      $entity_ids_list = array();
1613      $show_all=show_all($module);
1614      if($only_mine == 'true' || $show_all == 'false')
1615      {
1616          array_push($entity_ids_list,$id);
1617      }
1618      else
1619      {
1620          $contactquery = "SELECT contactid, accountid FROM vtiger_contactdetails " .
1621              " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid" .
1622              " AND vtiger_crmentity.deleted = 0 " .
1623              " WHERE (accountid = (SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?)  AND accountid != 0) OR contactid = ?";
1624          $contactres = $adb->pquery($contactquery, array($id,$id));
1625          $no_of_cont = $adb->num_rows($contactres);
1626          for($i=0;$i<$no_of_cont;$i++)
1627          {
1628              $cont_id = $adb->query_result($contactres,$i,'contactid');
1629              $acc_id = $adb->query_result($contactres,$i,'accountid');
1630              if(!in_array($cont_id, $entity_ids_list))
1631              $entity_ids_list[] = $cont_id;
1632              if(!in_array($acc_id, $entity_ids_list) && $acc_id != '0')
1633              $entity_ids_list[] = $acc_id;
1634          }
1635      }
1636      if($module == 'Quotes')
1637      {
1638          $query = "select distinct vtiger_quotes.*,vtiger_crmentity.smownerid,
1639          case when vtiger_quotes.contactid is not null then vtiger_quotes.contactid else vtiger_quotes.accountid end as entityid,
1640          case when vtiger_quotes.contactid is not null then 'Contacts' else 'Accounts' end as setype,
1641          vtiger_potential.potentialname,vtiger_account.accountid
1642          from vtiger_quotes left join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid
1643          LEFT OUTER JOIN vtiger_account
1644          ON vtiger_account.accountid = vtiger_quotes.accountid
1645          LEFT OUTER JOIN vtiger_potential
1646          ON vtiger_potential.potentialid = vtiger_quotes.potentialid
1647          where vtiger_crmentity.deleted=0 and (vtiger_quotes.accountid in  (". generateQuestionMarks($entity_ids_list) .") or contactid in (". generateQuestionMarks($entity_ids_list) ."))";
1648          $params = array($entity_ids_list,$entity_ids_list);
1649          $fields_list['Related To'] = 'entityid';
1650  
1651      }
1652      else if($module == 'Invoice')
1653      {
1654          $query ="select distinct vtiger_invoice.*,vtiger_crmentity.smownerid,
1655          case when vtiger_invoice.contactid !=0 then vtiger_invoice.contactid else vtiger_invoice.accountid end as entityid,
1656          case when vtiger_invoice.contactid !=0 then 'Contacts' else 'Accounts' end as setype
1657          from vtiger_invoice
1658          left join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid
1659          where vtiger_crmentity.deleted=0 and (accountid in (". generateQuestionMarks($entity_ids_list) .") or contactid in  (". generateQuestionMarks($entity_ids_list) ."))";
1660          $params = array($entity_ids_list,$entity_ids_list);
1661          $fields_list['Related To'] = 'entityid';
1662      }
1663      else if ($module == 'Documents')
1664      {
1665          $query ="select vtiger_notes.*, vtiger_crmentity.*, vtiger_senotesrel.crmid as entityid, '' as setype,vtiger_attachmentsfolder.foldername from vtiger_notes " .
1666          "inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_notes.notesid " .
1667          "left join vtiger_senotesrel on vtiger_senotesrel.notesid=vtiger_notes.notesid " .
1668          "LEFT JOIN vtiger_attachmentsfolder ON vtiger_attachmentsfolder.folderid = vtiger_notes.folderid " .
1669          "where vtiger_crmentity.deleted = 0 and  vtiger_senotesrel.crmid in (".generateQuestionMarks($entity_ids_list).")";
1670          $params = array($entity_ids_list);
1671          $fields_list['Related To'] = 'entityid';
1672      }else if ($module == 'Contacts'){
1673          $query = "select vtiger_contactdetails.*,vtiger_crmentity.smownerid from vtiger_contactdetails
1674           inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid
1675           where vtiger_crmentity.deleted = 0 and contactid IN (".generateQuestionMarks($entity_ids_list).")";
1676          $params = array($entity_ids_list);
1677      }else if ($module == 'Assets') {
1678          $accountRes = $adb->pquery("SELECT accountid FROM vtiger_contactdetails
1679                          INNER JOIN vtiger_crmentity ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
1680                          WHERE contactid = ? AND deleted = 0", array($id));
1681          $accountRow = $adb->num_rows($accountRes);
1682          if($accountRow) {
1683          $accountid = $adb->query_result($accountRes, 0, 'accountid');
1684          $query = "select vtiger_assets.*, vtiger_assets.account as entityid , vtiger_crmentity.smownerid from vtiger_assets
1685                          inner join vtiger_crmentity on vtiger_assets.assetsid = vtiger_crmentity.crmid
1686                          left join vtiger_account on vtiger_account.accountid = vtiger_assets.account
1687                          left join vtiger_products on vtiger_products.productid = vtiger_assets.product
1688                          where vtiger_crmentity.deleted = 0 and account = ?";
1689          $params = array($accountid);
1690          $fields_list['Related To'] = 'entityid';
1691          }
1692      }else if ($module == 'Project') {
1693          $query = "SELECT vtiger_project.*, vtiger_crmentity.smownerid
1694                      FROM vtiger_project
1695                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_project.projectid
1696                      WHERE vtiger_crmentity.deleted = 0 AND vtiger_project.linktoaccountscontacts IN (".generateQuestionMarks($entity_ids_list).")";
1697          $params = array($entity_ids_list);
1698          $fields_list['Related To'] = 'linktoaccountscontacts';
1699      }
1700  
1701      $res = $adb->pquery($query,$params);
1702      $noofdata = $adb->num_rows($res);
1703  
1704      $columnVisibilityByFieldnameInfo = array();
1705      if($noofdata) {
1706          foreach($fields_list as $fieldlabel =>$fieldname ) {
1707              $columnVisibilityByFieldnameInfo[$fieldname] = getColumnVisibilityPermission($current_user->id,$fieldname,$module);
1708          }
1709      }
1710  
1711  
1712      for( $j= 0;$j < $noofdata; $j++)
1713      {
1714          $i=0;
1715          foreach($fields_list as $fieldlabel =>$fieldname ) {
1716              $fieldper = $columnVisibilityByFieldnameInfo[$fieldname];
1717              if($fieldper == '1' && $fieldname != 'entityid'){
1718                  continue;
1719              }
1720              $fieldlabel = getTranslatedString($fieldlabel,$module);
1721  
1722              $output[0][$module]['head'][0][$i]['fielddata'] = $fieldlabel;
1723              $fieldvalue = $adb->query_result($res,$j,$fieldname);
1724              $fieldValuesToRound = array('total','subtotal','adjustment','discount_amount','s_h_amount','pre_tax_total','received','balance','unit_price');
1725  
1726              if($module == 'Quotes')
1727              {
1728                  if($fieldname =='subject'){
1729                      $fieldid = $adb->query_result($res,$j,'quoteid');
1730                      $filename = $fieldid.'_Quotes.pdf';
1731                      $fieldvalue = '<a href="index.php?&module=Quotes&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1732                  }
1733                  if(in_array($fieldname, $fieldValuesToRound)){
1734                      $fieldvalue = round($fieldvalue, 2);
1735                  }
1736                  if($fieldname == 'total'){
1737                      $sym = getCurrencySymbol($res,$j,'currency_id');
1738                      $fieldvalue = $sym.$fieldvalue;
1739                  }
1740              }
1741              if($module == 'Invoice')
1742              {
1743                  if($fieldname =='subject'){
1744                      $fieldid = $adb->query_result($res,$j,'invoiceid');
1745                      $filename = $fieldid.'_Invoice.pdf';
1746                      $fieldvalue = '<a href="index.php?&module=Invoice&action=index&status=true&id='.$fieldid.'">'.$fieldvalue.'</a>';
1747                  }
1748                  if(in_array($fieldname, $fieldValuesToRound)){
1749                      $fieldvalue = round($fieldvalue, 2);
1750                  }
1751                  if($fieldname == 'total'){
1752                      $sym = getCurrencySymbol($res,$j,'currency_id');
1753                      $fieldvalue = $sym.$fieldvalue;
1754                  }
1755              }
1756              if($module == 'Documents')
1757              {
1758                  if($fieldname == 'title'){
1759                      $fieldid = $adb->query_result($res,$j,'notesid');
1760                      $fieldvalue = '<a href="index.php?&module=Documents&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1761                  }
1762                  if( $fieldname == 'filename'){
1763                      $fieldid = $adb->query_result($res,$j,'notesid');
1764                      $filename = $fieldvalue;
1765                      $folderid = $adb->query_result($res,$j,'folderid');
1766                      $filename = $adb->query_result($res,$j,'filename');
1767                      $fileactive = $adb->query_result($res,$j,'filestatus');
1768                      $filetype = $adb->query_result($res,$j,'filelocationtype');
1769  
1770                      if($fileactive == 1){
1771                          if($filetype == 'I'){
1772                              $fieldvalue = '<a href="index.php?&downloadfile=true&folderid='.$folderid.'&filename='.$filename.'&module=Documents&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1773                          }
1774                          elseif($filetype == 'E'){
1775                              $fieldvalue = '<a target="_blank" href="'.$filename.'" onclick = "updateCount('.$fieldid.');">'.$filename.'</a>';
1776                          }
1777                      }else{
1778                          $fieldvalue = $filename;
1779                      }
1780                  }
1781                  if($fieldname == 'folderid'){
1782                      $fieldvalue = $adb->query_result($res,$j,'foldername');
1783                  }
1784              }
1785              if($module == 'Invoice' && $fieldname == 'salesorderid')
1786              {
1787                  if($fieldvalue != '')
1788                  $fieldvalue = get_salesorder_name($fieldvalue);
1789              }
1790  
1791              if($module == 'Services'){
1792                  if($fieldname == 'servicename'){
1793                      $fieldid = $adb->query_result($res,$j,'serviceid');
1794                      $fieldvalue = '<a href="index.php?module=Services&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1795                  }
1796                  if($fieldname == 'discontinued'){
1797                      if($fieldvalue == 1){
1798                          $fieldvalue = 'Yes';
1799                      }else{
1800                          $fieldvalue = 'No';
1801                      }
1802                  }
1803                  if(in_array($fieldname, $fieldValuesToRound)){
1804                      $fieldvalue = round($fieldvalue, 2);
1805                  }
1806                  if($fieldname == 'unit_price'){
1807                      $sym = getCurrencySymbol($res,$j,'currency_id');
1808                      $fieldvalue = $sym.$fieldvalue;
1809                  }
1810  
1811              }
1812              if($module == 'Contacts'){
1813                  if($fieldname == 'lastname' || $fieldname == 'firstname'){
1814                      $fieldid = $adb->query_result($res,$j,'contactid');
1815                      $fieldvalue ='<a href="index.php?module=Contacts&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1816                  }
1817              }
1818              if($module == 'Project'){
1819                  if($fieldname == 'projectname'){
1820                      $fieldid = $adb->query_result($res,$j,'projectid');
1821                      $fieldvalue = '<a href="index.php?module=Project&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
1822                  }
1823              }
1824              if($fieldname == 'entityid' || $fieldname == 'contactid' || $fieldname == 'accountid' || $fieldname == 'potentialid' || $fieldname == 'account' || $fieldname == 'linktoaccountscontacts') {
1825                  $crmid = $fieldvalue;
1826                  $modulename = getSalesEntityType($crmid);
1827                  if ($crmid != '' && $modulename != '') {
1828                      $fieldvalues = getEntityName($modulename, array($crmid));
1829                      if($modulename == 'Contacts')
1830                      $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
1831                      elseif($modulename == 'Accounts')
1832                      $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
1833                      elseif($modulename == 'Potentials'){
1834                          $fieldvalue = $adb->query_result($res,$j,'potentialname');
1835                      }
1836                  } else {
1837                      $fieldvalue = '';
1838                  }
1839              }
1840              if($module == 'Assets' && $fieldname == 'assetname') {
1841                      $assetname = $fieldvalue;
1842                      $assetid = $adb->query_result($res, $j, 'assetsid');
1843                      $fieldvalue = '<a href="index.php?module=Assets&action=index&id='.$assetid.'">'.$assetname.'</a>';
1844              }
1845              if($fieldname == 'product' && $module == 'Assets'){
1846                  $crmid= $adb->query_result($res,$j,'product');
1847                  $fres = $adb->pquery('select vtiger_products.productname from vtiger_products where productid=?',array($crmid));
1848                  $productname = $adb->query_result($fres,0,'productname');
1849                  $fieldvalue = '<a href="index.php?module=Products&action=index&id='.$crmid.'">'.$productname.'</a>';
1850              }
1851              if($fieldname == 'smownerid'){
1852                  $fieldvalue = getOwnerName($fieldvalue);
1853              }
1854              $output[1][$module]['data'][$j][$i]['fielddata'] = $fieldvalue;
1855              $i++;
1856          }
1857      }
1858      $log->debug("Exiting customer portal function get_list_values");
1859      return $output;
1860  
1861  }
1862  
1863  
1864  /**    function used to get the contents of a file
1865   *    @param int $id - customer ie., id
1866   *    return $filecontents array with single file contents like [fileid] => filecontent
1867   */
1868  function get_filecontent_detail($id,$folderid,$module,$customerid,$sessionid)
1869  {
1870      global $adb,$log;
1871      global $site_URL;
1872      $log->debug("Entering customer portal function get_filecontent_detail ");
1873      $isPermitted = check_permission($customerid,$module,$id);
1874      if($isPermitted == false) {
1875          return array("#NOT AUTHORIZED#");
1876      }
1877  
1878      if(!validateSession($customerid,$sessionid))
1879      return null;
1880  
1881      if($module == 'Documents')
1882      {
1883          $query="SELECT filetype FROM vtiger_notes WHERE notesid =?";
1884          $res = $adb->pquery($query, array($id));
1885          $filetype = $adb->query_result($res, 0, "filetype");
1886          updateDownloadCount($id);
1887  
1888          $fileidQuery = 'select attachmentsid from vtiger_seattachmentsrel where crmid = ?';
1889          $fileres = $adb->pquery($fileidQuery,array($id));
1890          $fileid = $adb->query_result($fileres,0,'attachmentsid');
1891  
1892          $filepathQuery = 'select path,name from vtiger_attachments where attachmentsid = ?';
1893          $fileres = $adb->pquery($filepathQuery,array($fileid));
1894          $filepath = $adb->query_result($fileres,0,'path');
1895          $filename = $adb->query_result($fileres,0,'name');
1896          $filename= decode_html($filename);
1897  
1898          $saved_filename =  $fileid."_".$filename;
1899          $filenamewithpath = $filepath.$saved_filename;
1900          $filesize = filesize($filenamewithpath );
1901      }
1902      else
1903      {
1904          $query ='select vtiger_attachments.*,vtiger_seattachmentsrel.* from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid=vtiger_attachments.attachmentsid where vtiger_seattachmentsrel.crmid =?';
1905  
1906          $res = $adb->pquery($query, array($id));
1907  
1908          $filename = $adb->query_result($res,0,'name');
1909          $filename = decode_html($filename);
1910          $filepath = $adb->query_result($res,0,'path');
1911          $fileid = $adb->query_result($res,0,'attachmentsid');
1912          $filesize = filesize($filepath.$fileid."_".$filename);
1913          $filetype = $adb->query_result($res,0,'type');
1914          $filenamewithpath=$filepath.$fileid.'_'.$filename;
1915  
1916      }
1917      $output[0]['fileid'] = $fileid;
1918      $output[0]['filename'] = $filename;
1919      $output[0]['filetype'] = $filetype;
1920      $output[0]['filesize'] = $filesize;
1921      $output[0]['filecontents']=base64_encode(file_get_contents($filenamewithpath));
1922      $log->debug("Exiting customer portal function get_filecontent_detail ");
1923      return $output;
1924  }
1925  
1926  /** Function that the client actually calls when a file is downloaded
1927   *
1928   */
1929  function updateCount($id){
1930      global $adb,$log;
1931      $log->debug("Entering customer portal function updateCount");
1932      $result = updateDownloadCount($id);
1933      $log->debug("Entering customer portal function updateCount");
1934      return $result;
1935  
1936  }
1937  
1938  /**
1939   * Function to update the download count of a file
1940   */
1941  function updateDownloadCount($id){
1942      global $adb,$log;
1943      $log->debug("Entering customer portal function updateDownloadCount");
1944      $updateDownloadCount = "UPDATE vtiger_notes SET filedownloadcount = filedownloadcount+1 WHERE notesid = ?";
1945      $countres = $adb->pquery($updateDownloadCount,array($id));
1946      $log->debug("Entering customer portal function updateDownloadCount");
1947      return true;
1948  }
1949  
1950  /**    function used to get the Quotes/Invoice pdf
1951   *    @param int $id - id -id
1952   *    return string $output - pd link value
1953   */
1954  
1955  function get_pdf($id,$block,$customerid,$sessionid)
1956  {
1957      global $adb;
1958      global $current_user,$log,$default_language;
1959      global $currentModule,$mod_strings,$app_strings,$app_list_strings;
1960      $log->debug("Entering customer portal function get_pdf");
1961      $isPermitted = check_permission($customerid,$block,$id);
1962      if($isPermitted == false) {
1963          return array("#NOT AUTHORIZED#");
1964      }
1965  
1966      if(!validateSession($customerid,$sessionid))
1967      return null;
1968  
1969      require_once ("config.inc.php");
1970      $current_user = Users::getActiveAdminUser();
1971  
1972      $currentModule = $block;
1973      $current_language = $default_language;
1974      $app_strings = return_application_language($current_language);
1975      $app_list_strings = return_app_list_strings_language($current_language);
1976      $mod_strings = return_module_language($current_language, $currentModule);
1977  
1978      $_REQUEST['record']= $id;
1979      $_REQUEST['savemode']= 'file';
1980      $sequenceNo = getModuleSequenceNumber($block, $id);
1981      $filenamewithpath='test/product/'.$id.'_'.$block.'_'.$sequenceNo.'.pdf';
1982      if (file_exists($filenamewithpath) && (filesize($filenamewithpath) != 0))
1983      unlink($filenamewithpath);
1984  
1985      checkFileAccessForInclusion("modules/$block/CreatePDF.php");
1986      include("modules/$block/CreatePDF.php");
1987  
1988      if (file_exists($filenamewithpath) && (filesize($filenamewithpath) != 0))
1989      {
1990          //we have to pass the file content
1991          $filecontents[] = base64_encode(file_get_contents($filenamewithpath));
1992          unlink($filenamewithpath);
1993          // TODO: Delete the file to avoid public access.
1994      }
1995      else
1996      {
1997          $filecontents = "failure";
1998      }
1999      $log->debug("Exiting customer portal function get_pdf");
2000      return $filecontents;
2001  }
2002  
2003  /**    function used to get the salesorder name
2004   *    @param int $id -  id
2005   *    return string $name - Salesorder name returned
2006   */
2007  
2008  function get_salesorder_name($id)
2009  {
2010      global $adb,$log;
2011      $log->debug("Entering customer portal function get_salesorder_name");
2012      $res = $adb->pquery(" select subject from vtiger_salesorder where salesorderid=?", array($id));
2013      $name=$adb->query_result($res,0,'subject');
2014      $log->debug("Exiting customer portal function get_salesorder_name");
2015      return $name;
2016  }
2017  
2018  function get_invoice_detail($id,$module,$customerid,$sessionid)
2019  {
2020      require_once ('include/utils/UserInfoUtil.php');
2021      require_once ('include/utils/utils.php');
2022  
2023      global $adb,$site_URL,$log,$current_user;
2024      $log->debug("Entering customer portal function get_invoice_details $id - $module - $customerid - $sessionid");
2025      $user = new Users();
2026      $userid = getPortalUserid();
2027      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
2028  
2029      $isPermitted = check_permission($customerid,$module,$id);
2030      if($isPermitted == false) {
2031          return array("#NOT AUTHORIZED#");
2032      }
2033  
2034      if(!validateSession($customerid,$sessionid))
2035      return null;
2036  
2037      $fieldquery = "SELECT fieldname, columnname, fieldlabel,block,uitype FROM vtiger_field WHERE tabid = ? AND displaytype in (1,2,4) ORDER BY block,sequence";
2038      $fieldres = $adb->pquery($fieldquery,array(getTabid($module)));
2039      $nooffields = $adb->num_rows($fieldres);
2040      $query = "select vtiger_invoice.*,vtiger_crmentity.* ,vtiger_invoicebillads.*,vtiger_invoiceshipads.*,
2041          vtiger_invoicecf.* from vtiger_invoice
2042          inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_invoice.invoiceid
2043          LEFT JOIN vtiger_invoicebillads ON vtiger_invoice.invoiceid = vtiger_invoicebillads.invoicebilladdressid
2044          LEFT JOIN vtiger_invoiceshipads ON vtiger_invoice.invoiceid = vtiger_invoiceshipads.invoiceshipaddressid
2045          INNER JOIN vtiger_invoicecf ON vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid
2046          where vtiger_invoice.invoiceid=?";
2047      $res = $adb->pquery($query, array($id));
2048  
2049      for($i=0;$i<$nooffields;$i++)
2050      {
2051          $fieldname = $adb->query_result($fieldres,$i,'columnname');
2052          $fieldlabel = getTranslatedString($adb->query_result($fieldres,$i,'fieldlabel'));
2053  
2054          $blockid = $adb->query_result($fieldres,$i,'block');
2055          $blocknameQuery = "select blocklabel from vtiger_blocks where blockid = ?";
2056          $blockPquery = $adb->pquery($blocknameQuery,array($blockid));
2057          $blocklabel = $adb->query_result($blockPquery,0,'blocklabel');
2058  
2059          $fieldper = getFieldVisibilityPermission($module,$current_user->id,$fieldname);
2060          if($fieldper == '1'){
2061              continue;
2062          }
2063  
2064          $fieldvalue = $adb->query_result($res,0,$fieldname);
2065          if($fieldname == 'subject' && $fieldvalue !='')
2066          {
2067              $fieldid = $adb->query_result($res,0,'invoiceid');
2068              //$fieldlabel = "(Download PDF)  ".$fieldlabel;
2069              $fieldvalue = '<a href="index.php?downloadfile=true&module=Invoice&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
2070          }
2071          if( $fieldname == 'salesorderid' || $fieldname == 'contactid' || $fieldname == 'accountid' || $fieldname == 'potentialid')
2072          {
2073              $crmid = $fieldvalue;
2074              $Entitymodule = getSalesEntityType($crmid);
2075              if ($crmid != '' && $Entitymodule != '') {
2076                  $fieldvalues = getEntityName($Entitymodule, array($crmid));
2077                  if($Entitymodule == 'Contacts')
2078                  $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2079                  elseif($Entitymodule == 'Accounts')
2080                  $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2081                  else
2082                  $fieldvalue = $fieldvalues[$crmid];
2083              } else {
2084                  $fieldvalue = '';
2085              }
2086          }
2087          if($fieldname == 'total'){
2088              $sym = getCurrencySymbol($res,0,'currency_id');
2089              $fieldvalue = $sym.$fieldvalue;
2090          }
2091          if($fieldname == 'smownerid'){
2092              $fieldvalue = getOwnerName($fieldvalue);
2093          }
2094          $output[0][$module][$i]['fieldlabel'] = $fieldlabel;
2095          $output[0][$module][$i]['fieldvalue'] = $fieldvalue;
2096          $output[0][$module][$i]['blockname'] = getTranslatedString($blocklabel,$module);
2097      }
2098      $log->debug("Entering customer portal function get_invoice_detail ..");
2099      return $output;
2100  }
2101  
2102  /* Function to get contactid's and account's product details'
2103   *
2104   */
2105  function get_product_list_values($id,$modulename,$sessionid,$only_mine='true')
2106  {
2107      require_once ('modules/Products/Products.php');
2108      require_once ('include/utils/UserInfoUtil.php');
2109      global $current_user,$adb,$log;
2110      $log->debug("Entering customer portal function get_product_list_values ..");
2111      $check = checkModuleActive($modulename);
2112      if($check == false){
2113          return array("#MODULE INACTIVE#");
2114      }
2115      $user = new Users();
2116      $userid = getPortalUserid();
2117      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
2118      $entity_ids_list = array();
2119      $show_all=show_all($modulename);
2120  
2121      if(!validateSession($id,$sessionid))
2122      return null;
2123  
2124      if($only_mine == 'true' || $show_all == 'false')
2125      {
2126          array_push($entity_ids_list,$id);
2127      }
2128      else
2129      {
2130          $contactquery = "SELECT contactid, accountid FROM vtiger_contactdetails " .
2131          " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid" .
2132          " AND vtiger_crmentity.deleted = 0 " .
2133          " WHERE (accountid = (SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?)  AND accountid != 0) OR contactid = ?";
2134          $contactres = $adb->pquery($contactquery, array($id,$id));
2135          $no_of_cont = $adb->num_rows($contactres);
2136          for($i=0;$i<$no_of_cont;$i++)
2137          {
2138              $cont_id = $adb->query_result($contactres,$i,'contactid');
2139              $acc_id = $adb->query_result($contactres,$i,'accountid');
2140              if(!in_array($cont_id, $entity_ids_list))
2141              $entity_ids_list[] = $cont_id;
2142              if(!in_array($acc_id, $entity_ids_list) && $acc_id != '0')
2143              $entity_ids_list[] = $acc_id;
2144          }
2145      }
2146  
2147      $focus = new Products();
2148      $focus->filterInactiveFields('Products');
2149      foreach ($focus->list_fields as $fieldlabel => $values){
2150          foreach($values as $table => $fieldname){
2151              $fields_list[$fieldlabel] = $fieldname;
2152          }
2153      }
2154      $fields_list['Related To'] = 'entityid';
2155      $query = array();
2156      $params = array();
2157      $query[] = "SELECT vtiger_products.*,vtiger_seproductsrel.crmid as entityid, vtiger_seproductsrel.setype FROM vtiger_products
2158          INNER JOIN vtiger_crmentity on vtiger_products.productid = vtiger_crmentity.crmid
2159          LEFT JOIN vtiger_seproductsrel on vtiger_seproductsrel.productid = vtiger_products.productid
2160          WHERE vtiger_seproductsrel.crmid in (". generateQuestionMarks($entity_ids_list).") and vtiger_crmentity.deleted = 0 ";
2161      $params[] = array($entity_ids_list);
2162  
2163      $checkQuotes = checkModuleActive('Quotes');
2164      if($checkQuotes == true){
2165          $query[] = "select distinct vtiger_products.*,
2166              case when vtiger_quotes.contactid is not null then vtiger_quotes.contactid else vtiger_quotes.accountid end as entityid,
2167              case when vtiger_quotes.contactid is not null then 'Contacts' else 'Accounts' end as setype
2168              from vtiger_quotes INNER join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid
2169              left join vtiger_inventoryproductrel on vtiger_inventoryproductrel.id=vtiger_quotes.quoteid
2170              left join vtiger_products on vtiger_products.productid = vtiger_inventoryproductrel.productid
2171              where vtiger_inventoryproductrel.productid = vtiger_products.productid AND vtiger_crmentity.deleted=0 and (accountid in  (". generateQuestionMarks($entity_ids_list) .") or contactid in (". generateQuestionMarks($entity_ids_list) ."))";
2172          $params[] = array($entity_ids_list,$entity_ids_list);
2173      }
2174      $checkInvoices = checkModuleActive('Invoice');
2175      if($checkInvoices == true){
2176          $query[] = "select distinct vtiger_products.*,
2177              case when vtiger_invoice.contactid !=0 then vtiger_invoice.contactid else vtiger_invoice.accountid end as entityid,
2178              case when vtiger_invoice.contactid !=0 then 'Contacts' else 'Accounts' end as setype
2179              from vtiger_invoice
2180              INNER join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid
2181              left join vtiger_inventoryproductrel on vtiger_inventoryproductrel.id=vtiger_invoice.invoiceid
2182              left join vtiger_products on vtiger_products.productid = vtiger_inventoryproductrel.productid
2183              where vtiger_inventoryproductrel.productid = vtiger_products.productid AND vtiger_crmentity.deleted=0 and (accountid in (". generateQuestionMarks($entity_ids_list) .") or contactid in  (". generateQuestionMarks($entity_ids_list) ."))";
2184          $params[] = array($entity_ids_list,$entity_ids_list);
2185      }
2186      $fieldValuesToRound = array('unit_price','weight','commissionrate','qtyinstock');
2187      for($k=0;$k<count($query);$k++)
2188      {
2189          $res[$k] = $adb->pquery($query[$k],$params[$k]);
2190          $noofdata[$k] = $adb->num_rows($res[$k]);
2191          if($noofdata[$k] == 0)
2192          $output[$k][$modulename]['data'] = '';
2193          for( $j= 0;$j < $noofdata[$k]; $j++)
2194          {
2195              $i=0;
2196              foreach($fields_list as $fieldlabel=> $fieldname) {
2197                  $fieldper = getFieldVisibilityPermission('Products',$current_user->id,$fieldname);
2198                  if($fieldper == '1' && $fieldname != 'entityid'){
2199                      continue;
2200                  }
2201                  $output[$k][$modulename]['head'][0][$i]['fielddata'] = $fieldlabel;
2202                  $fieldvalue = $adb->query_result($res[$k],$j,$fieldname);
2203                  $fieldid = $adb->query_result($res[$k],$j,'productid');
2204  
2205                  if(in_array($fieldname, $fieldValuesToRound)){
2206                      $fieldvalue = round($fieldvalue, 2);
2207                  }
2208                  if($fieldname == 'entityid') {
2209                      $crmid = $fieldvalue;
2210                      $module = $adb->query_result($res[$k],$j,'setype');
2211                      if ($crmid != '' && $module != '') {
2212                          $fieldvalues = getEntityName($module, array($crmid));
2213                          if($module == 'Contacts')
2214                          $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2215                          elseif($module == 'Accounts')
2216                          $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2217                      } else {
2218                          $fieldvalue = '';
2219                      }
2220                  }
2221  
2222                  if($fieldname == 'productname')
2223                  $fieldvalue = '<a href="index.php?module=Products&action=index&productid='.$fieldid.'">'.$fieldvalue.'</a>';
2224  
2225                  if($fieldname == 'unit_price'){
2226                      $sym = getCurrencySymbol($res[$k],$j,'currency_id');
2227                      $fieldvalue = $sym.$fieldvalue;
2228                  }
2229                  $output[$k][$modulename]['data'][$j][$i]['fielddata'] = $fieldvalue;
2230                  $i++;
2231              }
2232          }
2233      }
2234      $log->debug("Exiting function get_product_list_values.....");
2235      return $output;
2236  }
2237  
2238  /*function used to get details of tickets,quotes,documents,Products,Contacts,Accounts
2239   *    @param int $id - id of quotes or invoice or notes
2240   *    return string $message - Account informations will be returned from :Accountdetails table
2241   */
2242  function get_details($id,$module,$customerid,$sessionid)
2243  {
2244      global $adb,$log,$current_language,$default_language,$current_user;
2245      require_once ('include/utils/utils.php');
2246      require_once ('include/utils/UserInfoUtil.php');
2247      $log->debug("Entering customer portal function get_details ..");
2248  
2249      $user = new Users();
2250      $userid = getPortalUserid();
2251      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
2252  
2253      $current_language = $default_language;
2254      $isPermitted = check_permission($customerid,$module,$id);
2255      if($isPermitted == false) {
2256          return array("#NOT AUTHORIZED#");
2257      }
2258  
2259      if(!validateSession($customerid,$sessionid))
2260      return null;
2261  
2262      if($module == 'Quotes'){
2263          $query =  "SELECT
2264              vtiger_quotes.*,vtiger_crmentity.*,vtiger_quotesbillads.*,vtiger_quotesshipads.*,
2265              vtiger_quotescf.* FROM vtiger_quotes
2266              INNER JOIN vtiger_crmentity " .
2267                  "ON vtiger_crmentity.crmid = vtiger_quotes.quoteid
2268              INNER JOIN vtiger_quotesbillads
2269                  ON vtiger_quotes.quoteid = vtiger_quotesbillads.quotebilladdressid
2270              INNER JOIN vtiger_quotesshipads
2271                  ON vtiger_quotes.quoteid = vtiger_quotesshipads.quoteshipaddressid
2272              LEFT JOIN vtiger_quotescf
2273                  ON vtiger_quotes.quoteid = vtiger_quotescf.quoteid
2274              WHERE vtiger_quotes.quoteid=(". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted = 0";
2275  
2276      }
2277      else if($module == 'Documents'){
2278          $query =  "SELECT
2279              vtiger_notes.*,vtiger_crmentity.*,vtiger_attachmentsfolder.foldername,vtiger_notescf.*
2280              FROM vtiger_notes
2281              INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_notes.notesid
2282              LEFT JOIN vtiger_attachmentsfolder
2283                  ON vtiger_notes.folderid = vtiger_attachmentsfolder.folderid
2284              LEFT JOIN vtiger_notescf ON vtiger_notescf.notesid = vtiger_notes.notesid
2285              WHERE vtiger_notes.notesid=(". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted=0";
2286      }
2287      else if($module == 'HelpDesk'){
2288          $query ="SELECT
2289              vtiger_troubletickets.*,vtiger_crmentity.smownerid,vtiger_crmentity.createdtime,vtiger_crmentity.modifiedtime,
2290              vtiger_ticketcf.*,vtiger_crmentity.description  FROM vtiger_troubletickets
2291              INNER JOIN vtiger_crmentity on vtiger_crmentity.crmid = vtiger_troubletickets.ticketid
2292              INNER JOIN vtiger_ticketcf
2293                  ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid
2294              WHERE (vtiger_troubletickets.ticketid=(". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted = 0)";
2295      }
2296      else if($module == 'Services'){
2297          $query ="SELECT vtiger_service.*,vtiger_crmentity.*,vtiger_servicecf.*  FROM vtiger_service
2298              INNER JOIN vtiger_crmentity
2299                  ON vtiger_crmentity.crmid = vtiger_service.serviceid AND vtiger_crmentity.deleted = 0
2300              LEFT JOIN vtiger_servicecf
2301                  ON vtiger_service.serviceid = vtiger_servicecf.serviceid
2302              WHERE vtiger_service.serviceid= (". generateQuestionMarks($id) .")";
2303      }
2304      else if($module == 'Contacts'){
2305          $query = "SELECT vtiger_contactdetails.*,vtiger_contactaddress.*,vtiger_contactsubdetails.*,vtiger_contactscf.*" .
2306              " ,vtiger_crmentity.*,vtiger_customerdetails.*
2307               FROM vtiger_contactdetails
2308              INNER JOIN vtiger_crmentity
2309                  ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
2310              INNER JOIN vtiger_contactaddress
2311                  ON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid
2312              INNER JOIN vtiger_contactsubdetails
2313                  ON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid
2314              INNER JOIN vtiger_contactscf
2315                  ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid
2316              LEFT JOIN vtiger_customerdetails
2317                  ON vtiger_customerdetails.customerid = vtiger_contactdetails.contactid
2318              WHERE vtiger_contactdetails.contactid = (". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted = 0";
2319      }
2320      else if($module == 'Accounts'){
2321          $query = "SELECT vtiger_account.*,vtiger_accountbillads.*,vtiger_accountshipads.*,vtiger_accountscf.*,
2322              vtiger_crmentity.* FROM vtiger_account
2323              INNER JOIN vtiger_crmentity
2324                  ON vtiger_crmentity.crmid = vtiger_account.accountid
2325              INNER JOIN vtiger_accountbillads
2326                  ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid
2327              INNER JOIN vtiger_accountshipads
2328                  ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid
2329              INNER JOIN vtiger_accountscf
2330                  ON vtiger_account.accountid = vtiger_accountscf.accountid" .
2331          " WHERE vtiger_account.accountid = (". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted = 0";
2332      }
2333      else if ($module == 'Products'){
2334          $query = "SELECT vtiger_products.*,vtiger_productcf.*,vtiger_crmentity.* " .
2335          "FROM vtiger_products " .
2336          "INNER JOIN vtiger_crmentity " .
2337              "ON vtiger_crmentity.crmid = vtiger_products.productid " .
2338          "LEFT JOIN vtiger_productcf " .
2339              "ON vtiger_productcf.productid = vtiger_products.productid " .
2340          "LEFT JOIN vtiger_vendor
2341              ON vtiger_vendor.vendorid = vtiger_products.vendor_id " .
2342          "WHERE vtiger_products.productid = (". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted = 0";
2343      } else if($module == 'Assets') {
2344          $query = "SELECT vtiger_assets.*, vtiger_assetscf.*, vtiger_crmentity.*
2345          FROM vtiger_assets
2346          INNER JOIN vtiger_crmentity
2347          ON vtiger_assets.assetsid = vtiger_crmentity.crmid
2348          INNER JOIN vtiger_assetscf
2349          ON vtiger_assetscf.assetsid = vtiger_assets.assetsid
2350          WHERE vtiger_crmentity.deleted = 0 AND vtiger_assets.assetsid = (". generateQuestionMarks($id) .")";
2351      } else if ($module == 'Project') {
2352          $query = "SELECT vtiger_project.*, vtiger_projectcf.*, vtiger_crmentity.*
2353                      FROM vtiger_project
2354                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_project.projectid
2355                      LEFT JOIN vtiger_projectcf ON vtiger_projectcf.projectid = vtiger_project.projectid
2356                      WHERE vtiger_project.projectid = ? AND vtiger_crmentity.deleted = 0";
2357      }
2358  
2359      $params = array($id);
2360      $res = $adb->pquery($query,$params);
2361  
2362      $fieldquery = "SELECT fieldname,columnname,fieldlabel,blocklabel,uitype FROM vtiger_field
2363          INNER JOIN  vtiger_blocks on vtiger_blocks.blockid=vtiger_field.block WHERE vtiger_field.tabid = ? AND displaytype in (1,2,4)
2364          ORDER BY vtiger_field.block,vtiger_field.sequence";
2365  
2366      $fieldres = $adb->pquery($fieldquery,array(getTabid($module)));
2367      $nooffields = $adb->num_rows($fieldres);
2368  
2369      // Dummy instance to make sure column fields are initialized for futher processing
2370      $focus = CRMEntity::getInstance($module);
2371  
2372      for($i=0;$i<$nooffields;$i++)
2373      {
2374          $columnname = $adb->query_result($fieldres,$i,'columnname');
2375          $fieldname = $adb->query_result($fieldres,$i,'fieldname');
2376          $fieldid = $adb->query_result($fieldres,$i,'fieldid');
2377          $blockid = $adb->query_result($fieldres,$i,'block');
2378          $uitype = $adb->query_result($fieldres,$i,'uitype');
2379  
2380          $blocklabel = $adb->query_result($fieldres,$i,'blocklabel');
2381          $blockname = getTranslatedString($blocklabel,$module);
2382          if($blocklabel == 'LBL_COMMENTS' || $blocklabel == 'LBL_IMAGE_INFORMATION'){ // the comments block of tickets is hardcoded in customer portal,get_ticket_comments is used for it
2383              continue;
2384          }
2385          if($uitype == 83){ //for taxclass in products and services
2386              continue;
2387          }
2388          $fieldper = getFieldVisibilityPermission($module,$current_user->id,$fieldname);
2389          if($fieldper == '1'){
2390              continue;
2391          }
2392  
2393          $fieldlabel = getTranslatedString($adb->query_result($fieldres,$i,'fieldlabel'));
2394          $fieldvalue = $adb->query_result($res,0,$columnname);
2395  
2396          $output[0][$module][$i]['fieldlabel'] = $fieldlabel ;
2397          $output[0][$module][$i]['blockname'] = $blockname;
2398          if($columnname == 'title' || $columnname == 'description') {
2399              $fieldvalue = decode_html($fieldvalue);
2400          }
2401          if($uitype == 71 || $uitype == 72){
2402              $fieldvalue = number_format($fieldvalue, 5, '.', '');
2403          }
2404          if($columnname == 'parent_id' || $columnname == 'contactid' || $columnname == 'accountid' || $columnname == 'potentialid'
2405              || $fieldname == 'account_id' || $fieldname == 'contact_id' || $columnname == 'linktoaccountscontacts')
2406          {
2407              $crmid = $fieldvalue;
2408              $modulename = getSalesEntityType($crmid);
2409              if ($crmid != '' && $modulename != '') {
2410                  $fieldvalues = getEntityName($modulename, array($crmid));
2411                  if($modulename == 'Contacts')
2412                  $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2413                  elseif($modulename == 'Accounts')
2414                  $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
2415                  else
2416                  $fieldvalue = $fieldvalues[$crmid];
2417              } else {
2418                  $fieldvalue = '';
2419              }
2420          }
2421  
2422          if($module=='Quotes')
2423          {
2424              if($fieldname == 'subject' && $fieldvalue !=''){
2425                  $fieldid = $adb->query_result($res,0,'quoteid');
2426                  $fieldvalue = '<a href="index.php?downloadfile=true&module=Quotes&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
2427              }
2428              if($fieldname == 'total'){
2429                  $sym = getCurrencySymbol($res,0,'currency_id');
2430                  $fieldvalue = $sym.$fieldvalue;
2431              }
2432          }
2433          if($module == 'Documents')
2434          {
2435              $fieldid = $adb->query_result($res,0,'notesid');
2436              $filename = $fieldvalue;
2437              $folderid = $adb->query_result($res,0,'folderid');
2438              $filestatus = $adb->query_result($res,0,'filestatus');
2439              $filetype = $adb->query_result($res,0,'filelocationtype');
2440              if($fieldname == 'filename'){
2441                  if($filestatus == 1){
2442                      if($filetype == 'I'){
2443                          $fieldvalue = '<a href="index.php?downloadfile=true&folderid='.$folderid.'&filename='.$filename.'&module=Documents&action=index&id='.$fieldid.'" >'.$fieldvalue.'</a>';
2444                      }
2445                      elseif($filetype == 'E'){
2446                          $fieldvalue = '<a target="_blank" href="'.$filename.'" onclick = "updateCount('.$fieldid.');">'.$filename.'</a>';
2447                      }
2448                  }
2449              }
2450              if($fieldname == 'folderid'){
2451                  $fieldvalue = $adb->query_result($res,0,'foldername');
2452              }
2453              if($fieldname == 'filesize'){
2454                  if($filetype == 'I'){
2455                      $fieldvalue = $fieldvalue .' B';
2456                  }
2457                  elseif($filetype == 'E'){
2458                      $fieldvalue = '--';
2459                  }
2460              }
2461              if($fieldname == 'filelocationtype'){
2462                  if($fieldvalue == 'I'){
2463                      $fieldvalue = getTranslatedString('LBL_INTERNAL',$module);
2464                  }elseif($fieldvalue == 'E'){
2465                      $fieldvalue = getTranslatedString('LBL_EXTERNAL',$module);
2466                  }else{
2467                      $fieldvalue = '---';
2468                  }
2469              }
2470          }
2471          if($columnname == 'product_id') {
2472              $fieldvalues = getEntityName('Products', array($fieldvalue));
2473              $fieldvalue = '<a href="index.php?module=Products&action=index&productid='.$fieldvalue.'">'.$fieldvalues[$fieldvalue].'</a>';
2474          }
2475          if($module == 'Products'){
2476              if($fieldname == 'vendor_id'){
2477                  $fieldvalue = get_vendor_name($fieldvalue);
2478              }
2479          }
2480          if($module == 'Assets' ){
2481              if($fieldname == 'account'){
2482                  $accountid = $adb->query_result($res,0,'account');
2483                  $accountres = $adb->pquery("select vtiger_account.accountname from vtiger_account where accountid=?",array($accountid));
2484                  $accountname = $adb->query_result($accountres,0,'accountname');
2485                  $fieldvalue = $accountname;
2486              }
2487              if($fieldname == 'product'){
2488                  $productid = $adb->query_result($res,0,'product');
2489                  $productres = $adb->pquery("select vtiger_products.productname from vtiger_products where productid=?",array($productid));
2490                  $productname = $adb->query_result($productres,0,'productname');
2491                  $fieldvalue = $productname;
2492              }
2493              if($fieldname == 'invoiceid'){
2494                  $invoiceid = $adb->query_result($res,0,'invoiceid');
2495                  $invoiceres = $adb->pquery("select vtiger_invoice.subject from vtiger_invoice where invoiceid=?",array($invoiceid));
2496                  $invoicename = $adb->query_result($invoiceres,0,'subject');
2497                  $fieldvalue = $invoicename;
2498              }
2499          }
2500          if($fieldname == 'assigned_user_id' || $fieldname == 'assigned_user_id1'){
2501              $fieldvalue = getOwnerName($fieldvalue);
2502          }
2503          if($uitype == 56){
2504              if($fieldvalue == 1){
2505                  $fieldvalue = 'Yes';
2506              }else{
2507                  $fieldvalue = 'No';
2508              }
2509          }
2510          if($module == 'HelpDesk' && $fieldname == 'ticketstatus'){
2511                  $parentid = $adb->query_result($res,0,'parent_id');
2512                   $contactid = $adb->query_result($res,0,'contact_id');
2513                   $status = $adb->query_result($res,0,'status');
2514  
2515                   if($parentid!=0) {//allow contacts related to organization to close the ticket
2516                          $focus = CRMEntity::getInstance('Accounts');
2517                          $focus->id = $parentid;
2518                          $entityIds = $focus->getRelatedContactsIds();
2519                          if($contactid != 0 ) {
2520                                  if(in_array($customerid, $entityIds) && in_array($contactid, $entityIds))
2521                                          $fieldvalue = $status;
2522                                  else if($customerid == $contactid)
2523                                          $fieldvalue = $status;
2524                                  else
2525                                          $fieldvalue = '';
2526                          } else {
2527                                  if(in_array($customerid, $entityIds))
2528                                          $fieldvalue = $status;
2529                                  else
2530                                          $fieldvalue = '';
2531                          }
2532                  } else if($customerid != $contactid ) {//allow only the owner to close the ticket
2533                          $fieldvalue = '';
2534                  } else {
2535                          $fieldvalue = $status;
2536                  }
2537          }
2538          if($fieldname == 'unit_price'){
2539              $sym = getCurrencySymbol($res,0,'currency_id');
2540              $fieldvalue = round($fieldvalue, 2);
2541              $fieldvalue = $sym.$fieldvalue;
2542          }
2543          $output[0][$module][$i]['fieldvalue'] = $fieldvalue;
2544      }
2545  
2546      if($module == 'HelpDesk'){
2547          $ticketid = $adb->query_result($res,0,'ticketid');
2548          $sc_info = getRelatedServiceContracts($ticketid);
2549          if (!empty($sc_info)) {
2550              $modulename = 'ServiceContracts';
2551              $blocklable = getTranslatedString('LBL_SERVICE_CONTRACT_INFORMATION',$modulename);
2552              $j=$i;
2553              for($k=0;$k<count($sc_info);$k++){
2554                  foreach ($sc_info[$k] as $label => $value) {
2555                      $output[0][$module][$j]['fieldlabel']= getTranslatedString($label,$modulename);
2556                      $output[0][$module][$j]['fieldvalue']= $value;
2557                      $output[0][$module][$j]['blockname'] = $blocklable;
2558                      $j++;
2559                  }
2560              }
2561          }
2562      }
2563      $log->debug("Existing customer portal function get_details ..");
2564      return $output;
2565  }
2566  /* Function to check the permission if the customer can see the recorde details
2567   * @params $customerid :: INT contact's Id
2568   *             $module :: String modulename
2569   *             $entityid :: INT Records Id
2570   */
2571  function check_permission($customerid, $module, $entityid) {
2572      global $adb,$log;
2573      $log->debug("Entering customer portal function check_permission ..");
2574      $show_all= show_all($module);
2575      $allowed_contacts_and_accounts = array();
2576      $check = checkModuleActive($module);
2577      if($check == false){
2578          return false;
2579      }
2580  
2581      if($show_all == 'false')
2582      $allowed_contacts_and_accounts[] = $customerid;
2583      else {
2584  
2585          $contactquery = "SELECT contactid, accountid FROM vtiger_contactdetails " .
2586                      " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid" .
2587                      " AND vtiger_crmentity.deleted = 0 " .
2588                      " WHERE (accountid = (SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?) AND accountid != 0) OR contactid = ?";
2589          $contactres = $adb->pquery($contactquery, array($customerid,$customerid));
2590          $no_of_cont = $adb->num_rows($contactres);
2591          for($i=0;$i<$no_of_cont;$i++){
2592              $cont_id = $adb->query_result($contactres,$i,'contactid');
2593              $acc_id = $adb->query_result($contactres,$i,'accountid');
2594              if(!in_array($cont_id, $allowed_contacts_and_accounts))
2595              $allowed_contacts_and_accounts[] = $cont_id;
2596              if(!in_array($acc_id, $allowed_contacts_and_accounts) && $acc_id != '0')
2597              $allowed_contacts_and_accounts[] = $acc_id;
2598          }
2599      }
2600      if(in_array($entityid, $allowed_contacts_and_accounts)) { //for contact's,if they are present in the allowed list then send true
2601          return true;
2602      }
2603      $faqquery = "select id from vtiger_faq";
2604      $faqids = $adb->pquery($faqquery,array());
2605      $no_of_faq = $adb->num_rows($faqids);
2606      for($i=0;$i<$no_of_faq;$i++){
2607          $faq_id[] = $adb->query_result($faqids,$i,'id');
2608      }
2609      switch($module) {
2610          case 'Products'    :     $query = "SELECT vtiger_seproductsrel.productid FROM vtiger_seproductsrel
2611                                  INNER JOIN vtiger_crmentity
2612                                  ON vtiger_seproductsrel.productid=vtiger_crmentity.crmid
2613                                  WHERE vtiger_seproductsrel.crmid IN (". generateQuestionMarks($allowed_contacts_and_accounts).")
2614                                      AND vtiger_crmentity.deleted=0
2615                                      AND vtiger_seproductsrel.productid = ?";
2616                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $entityid));
2617                              if ($adb->num_rows($res) > 0) {
2618                                  return true;
2619                              }
2620                              $query = "SELECT vtiger_inventoryproductrel.productid, vtiger_inventoryproductrel.id
2621                                                      FROM vtiger_inventoryproductrel
2622                                                      INNER JOIN vtiger_crmentity
2623                                                      ON vtiger_inventoryproductrel.productid=vtiger_crmentity.crmid
2624                                                      LEFT JOIN vtiger_quotes
2625                                                      ON vtiger_inventoryproductrel.id = vtiger_quotes.quoteid
2626                                                      WHERE vtiger_crmentity.deleted=0
2627                                                          AND (vtiger_quotes.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_quotes.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2628                                                          AND vtiger_inventoryproductrel.productid = ?";
2629                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2630                              if ($adb->num_rows($res) > 0) {
2631                                  return true;
2632                              }
2633                              $query = "SELECT vtiger_inventoryproductrel.productid, vtiger_inventoryproductrel.id
2634                                                      FROM vtiger_inventoryproductrel
2635                                                      INNER JOIN vtiger_crmentity
2636                                                      ON vtiger_inventoryproductrel.productid=vtiger_crmentity.crmid
2637                                                      LEFT JOIN vtiger_invoice
2638                                                      ON vtiger_inventoryproductrel.id = vtiger_invoice.invoiceid
2639                                                      WHERE vtiger_crmentity.deleted=0
2640                                                          AND (vtiger_invoice.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_invoice.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2641                                                          AND vtiger_inventoryproductrel.productid = ?";
2642                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2643                              if ($adb->num_rows($res) > 0) {
2644                                  return true;
2645                              }
2646                              break;
2647  
2648          case 'Quotes'    :    $query = "SELECT vtiger_quotes.quoteid
2649                                  FROM vtiger_quotes
2650                                  INNER JOIN vtiger_crmentity
2651                                  ON vtiger_quotes.quoteid=vtiger_crmentity.crmid
2652                                  WHERE vtiger_crmentity.deleted=0
2653                                      AND (vtiger_quotes.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_quotes.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2654                                      AND vtiger_quotes.quoteid = ?";
2655                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2656                              if ($adb->num_rows($res) > 0) {
2657                                  return true;
2658                              }
2659                              break;
2660  
2661          case 'Invoice'    :    $query = "SELECT vtiger_invoice.invoiceid
2662                                  FROM vtiger_invoice
2663                                  INNER JOIN vtiger_crmentity
2664                                  ON vtiger_invoice.invoiceid=vtiger_crmentity.crmid
2665                                  WHERE vtiger_crmentity.deleted=0
2666                                      AND (vtiger_invoice.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_invoice.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2667                                      AND vtiger_invoice.invoiceid = ?";
2668                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2669                              if ($adb->num_rows($res) > 0) {
2670                                  return true;
2671                              }
2672                              break;
2673  
2674          case 'Documents'    :     $query = "SELECT vtiger_senotesrel.notesid FROM vtiger_senotesrel
2675                                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_senotesrel.notesid AND vtiger_crmentity.deleted = 0
2676                                      WHERE vtiger_senotesrel.crmid IN (". generateQuestionMarks($allowed_contacts_and_accounts) .")
2677                                      AND vtiger_senotesrel.notesid = ?";
2678                                  $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $entityid));
2679                                  if ($adb->num_rows($res) > 0) {
2680                                      return true;
2681                                  }
2682                                  if(checkModuleActive('Project')) {
2683                                      $query = "SELECT vtiger_senotesrel.notesid FROM vtiger_senotesrel
2684                                          INNER JOIN vtiger_project ON vtiger_project.projectid = vtiger_senotesrel.crmid
2685                                          WHERE vtiger_project.linktoaccountscontacts IN (". generateQuestionMarks($allowed_contacts_and_accounts) .")
2686                                          AND vtiger_senotesrel.notesid = ?";
2687                                      $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $entityid));
2688                                      if ($adb->num_rows($res) > 0) {
2689                                          return true;
2690                                      }
2691                                  }
2692  
2693                                  $query = "SELECT vtiger_senotesrel.notesid FROM vtiger_senotesrel
2694                                                              INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_senotesrel.notesid AND vtiger_crmentity.deleted = 0
2695                                                              WHERE vtiger_senotesrel.crmid IN (". generateQuestionMarks($faq_id) .")
2696                                                              AND vtiger_senotesrel.notesid = ?";
2697                                  $res = $adb->pquery($query, array($faq_id,$entityid));
2698                                  if ($adb->num_rows($res) > 0) {
2699                                      return true;
2700                                  }
2701                                  break;
2702  
2703          case 'HelpDesk'    :    if($acc_id) $accCondition = "OR vtiger_troubletickets.parent_id = $acc_id";
2704                              $query = "SELECT vtiger_troubletickets.ticketid FROM vtiger_troubletickets
2705                                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid AND vtiger_crmentity.deleted = 0
2706                                      WHERE (vtiger_troubletickets.contact_id IN (". generateQuestionMarks($allowed_contacts_and_accounts) .") $accCondition )
2707                                      AND vtiger_troubletickets.ticketid = ?";
2708                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $entityid));
2709                              if ($adb->num_rows($res) > 0) {
2710                                  return true;
2711                              }
2712  
2713                              $query = "SELECT vtiger_troubletickets.ticketid FROM vtiger_troubletickets
2714                                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid
2715                                      INNER JOIN vtiger_crmentityrel ON (vtiger_crmentityrel.relcrmid = vtiger_crmentity.crmid OR vtiger_crmentityrel.crmid = vtiger_crmentity.crmid)
2716                                      WHERE vtiger_crmentity.deleted = 0 AND
2717                                              (vtiger_crmentityrel.crmid IN
2718                                                  (SELECT projectid FROM vtiger_project WHERE linktoaccountscontacts
2719                                                      IN (". generateQuestionMarks($allowed_contacts_and_accounts) .") AND vtiger_crmentityrel.relcrmid = $entityid)
2720                                              OR vtiger_crmentityrel.relcrmid IN
2721                                                  (SELECT projectid FROM vtiger_project WHERE linktoaccountscontacts
2722                                                      IN (". generateQuestionMarks($allowed_contacts_and_accounts) .") AND vtiger_crmentityrel.crmid = $entityid)
2723                                          AND vtiger_troubletickets.ticketid = ?)";
2724  
2725                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2726                              if ($adb->num_rows($res) > 0) {
2727                                  return true;
2728                              }
2729  
2730                              break;
2731  
2732          case 'Services'    :    $query = "SELECT vtiger_service.serviceid FROM vtiger_service
2733                                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_service.serviceid AND vtiger_crmentity.deleted = 0
2734                                      LEFT JOIN vtiger_crmentityrel ON (vtiger_crmentityrel.relcrmid=vtiger_service.serviceid OR vtiger_crmentityrel.crmid=vtiger_service.serviceid)
2735                                      WHERE (vtiger_crmentityrel.crmid IN (". generateQuestionMarks($allowed_contacts_and_accounts) .")  OR " .
2736                                       "(vtiger_crmentityrel.relcrmid IN (".generateQuestionMarks($allowed_contacts_and_accounts).") AND vtiger_crmentityrel.module = 'Services'))
2737                                      AND vtiger_service.serviceid = ?";
2738                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts,$allowed_contacts_and_accounts, $entityid));
2739                              if ($adb->num_rows($res) > 0) {
2740                                  return true;
2741                              }
2742  
2743                              $query = "SELECT vtiger_inventoryproductrel.productid, vtiger_inventoryproductrel.id
2744                                      FROM vtiger_inventoryproductrel
2745                                      INNER JOIN vtiger_crmentity
2746                                      ON vtiger_inventoryproductrel.productid=vtiger_crmentity.crmid
2747                                      LEFT JOIN vtiger_quotes
2748                                      ON vtiger_inventoryproductrel.id = vtiger_quotes.quoteid
2749                                      WHERE vtiger_crmentity.deleted=0
2750                                      AND (vtiger_quotes.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_quotes.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2751                                      AND vtiger_inventoryproductrel.productid = ?";
2752                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2753                              if ($adb->num_rows($res) > 0) {
2754                                  return true;
2755                              }
2756  
2757                              $query = "SELECT vtiger_inventoryproductrel.productid, vtiger_inventoryproductrel.id
2758                                      FROM vtiger_inventoryproductrel
2759                                      INNER JOIN vtiger_crmentity
2760                                      ON vtiger_inventoryproductrel.productid=vtiger_crmentity.crmid
2761                                      LEFT JOIN vtiger_invoice
2762                                      ON vtiger_inventoryproductrel.id = vtiger_invoice.invoiceid
2763                                      WHERE vtiger_crmentity.deleted=0
2764                                          AND (vtiger_invoice.contactid IN (". generateQuestionMarks($allowed_contacts_and_accounts).") or vtiger_invoice.accountid IN (".generateQuestionMarks($allowed_contacts_and_accounts)."))
2765                                          AND vtiger_inventoryproductrel.productid = ?";
2766                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $allowed_contacts_and_accounts, $entityid));
2767                              if ($adb->num_rows($res) > 0) {
2768                                  return true;
2769                              }
2770                              break;
2771  
2772          case 'Accounts' :     $query = "SELECT vtiger_account.accountid FROM vtiger_account " .
2773                                      "INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid " .
2774                                      "INNER JOIN vtiger_contactdetails ON vtiger_contactdetails.accountid = vtiger_account.accountid " .
2775                                      "WHERE vtiger_crmentity.deleted = 0 and vtiger_contactdetails.contactid = ? and vtiger_contactdetails.accountid = ?";
2776                              $res = $adb->pquery($query,array($customerid,$entityid));
2777                              if ($adb->num_rows($res) > 0) {
2778                                  return true;
2779                              }
2780                              break;
2781  
2782          case 'Assets' : $query = "SELECT vtiger_assets.assetname FROM vtiger_assets
2783                                  INNER JOIN vtiger_crmentity ON  vtiger_assets.assetsid = vtiger_crmentity.crmid
2784                                  WHERE vtiger_crmentity.deleted = 0 and vtiger_assets.account = ? ";
2785                          $accountid = '';
2786                          $accountRes = $adb->pquery("SELECT accountid FROM vtiger_contactdetails
2787                                  INNER JOIN vtiger_crmentity ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
2788                                  WHERE contactid = ? AND deleted = 0", array($customerid));
2789                          $accountRow = $adb->num_rows($accountRes);
2790                          if($accountRow) {
2791                              $accountid = $adb->query_result($accountRes, 0, 'accountid');
2792                          }
2793                          $res = $adb->pquery($query,array($accountid));
2794                          if ($adb->num_rows($res) > 0) {
2795                              return true;
2796                          }
2797                          break;
2798  
2799          case 'Project'    :    $query = "SELECT vtiger_project.projectid FROM vtiger_project
2800                                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_project.projectid AND vtiger_crmentity.deleted = 0
2801                                      WHERE vtiger_project.linktoaccountscontacts IN (". generateQuestionMarks($allowed_contacts_and_accounts) .")
2802                                      AND vtiger_project.projectid = ?";
2803                              $res = $adb->pquery($query, array($allowed_contacts_and_accounts, $entityid));
2804                              if ($adb->num_rows($res) > 0) {
2805                                  return true;
2806                              }
2807                              break;
2808  
2809      }
2810      return false;
2811      $log->debug("Exiting customerportal function check_permission ..");
2812  }
2813  
2814  /* Function to get related Documents for faq
2815   *  @params $id :: INT parent's Id
2816   *             $module :: String modulename
2817   *             $customerid :: INT contact's Id'
2818   */
2819  function get_documents($id,$module,$customerid,$sessionid)
2820  {
2821      global $adb,$log;
2822      $log->debug("Entering customer portal function get_documents ..");
2823      $check = checkModuleActive($module);
2824      if($check == false){
2825          return array("#MODULE INACTIVE#");
2826      }
2827      $fields_list = array(
2828      'title' => 'Title',
2829      'filename' => 'FileName',
2830      'createdtime' => 'Created Time');
2831  
2832      if(!validateSession($customerid,$sessionid))
2833      return null;
2834  
2835      $query ="select vtiger_notes.title,'Documents' ActivityType, vtiger_notes.filename,
2836          crm2.createdtime,vtiger_notes.notesid,vtiger_notes.folderid,
2837          vtiger_notes.notecontent description, vtiger_users.user_name, vtiger_notes.filelocationtype
2838          from vtiger_notes
2839          LEFT join vtiger_senotesrel on vtiger_senotesrel.notesid= vtiger_notes.notesid
2840          INNER join vtiger_crmentity on vtiger_crmentity.crmid= vtiger_senotesrel.crmid
2841          LEFT join vtiger_crmentity crm2 on crm2.crmid=vtiger_notes.notesid and crm2.deleted=0
2842          LEFT JOIN vtiger_groups
2843          ON vtiger_groups.groupid = vtiger_crmentity.smownerid
2844          LEFT join vtiger_users on crm2.smownerid= vtiger_users.id
2845          where vtiger_crmentity.crmid=?";
2846      $res = $adb->pquery($query,array($id));
2847      $noofdata = $adb->num_rows($res);
2848      for( $j= 0;$j < $noofdata; $j++)
2849      {
2850          $i=0;
2851          foreach($fields_list as $fieldname => $fieldlabel) {
2852              $output[0][$module]['head'][0][$i]['fielddata'] = $fieldlabel; //$adb->query_result($fieldres,$i,'fieldlabel');
2853              $fieldvalue = $adb->query_result($res,$j,$fieldname);
2854              if($fieldname =='title') {
2855                  $fieldid = $adb->query_result($res,$j,'notesid');
2856                  $filename = $fieldvalue;
2857                  $fieldvalue = '<a href="index.php?&module=Documents&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
2858              }
2859              if($fieldname == 'filename'){
2860                  $fieldid = $adb->query_result($res,$j,'notesid');
2861                  $filename = $fieldvalue;
2862                  $folderid = $adb->query_result($res,$j,'folderid');
2863                  $filetype = $adb->query_result($res,$j,'filelocationtype');
2864                  if($filetype == 'I'){
2865                      $fieldvalue = '<a href="index.php?&downloadfile=true&folderid='.$folderid.'&filename='.$filename.'&module=Documents&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
2866                  }else{
2867                      $fieldvalue = '<a target="_blank" href="'.$filename.'">'.$filename.'</a>';
2868                  }
2869              }
2870              $output[1][$module]['data'][$j][$i]['fielddata'] = $fieldvalue;
2871              $i++;
2872          }
2873      }
2874      $log->debug("Exiting customerportal function  get_faq_document ..");
2875      return $output;
2876  }
2877  
2878  /* Function to get related projecttasks/projectmilestones for a Project
2879   *  @params $id :: INT Project's Id
2880   *             $module :: String modulename
2881   *             $customerid :: INT contact's Id'
2882   */
2883  function get_project_components($id,$module,$customerid,$sessionid) {
2884      checkFileAccessForInclusion("modules/$module/$module.php");
2885      require_once("modules/$module/$module.php");
2886      require_once ('include/utils/UserInfoUtil.php');
2887  
2888      global $adb,$log;
2889      $log->debug("Entering customer portal function get_project_components ..");
2890      $check = checkModuleActive($module);
2891      if($check == false) {
2892          return array("#MODULE INACTIVE#");
2893      }
2894  
2895      if(!validateSession($customerid,$sessionid))
2896          return null;
2897  
2898      $user = new Users();
2899      $userid = getPortalUserid();
2900      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
2901  
2902      $focus = new $module();
2903      $focus->filterInactiveFields($module);
2904      $componentfieldVisibilityByColumn = array();
2905      $fields_list = array();
2906  
2907      foreach ($focus->list_fields as $fieldlabel => $values){
2908          foreach($values as $table => $fieldname){
2909              $fields_list[$fieldlabel] = $fieldname;
2910              $componentfieldVisibilityByColumn[$fieldname] = getColumnVisibilityPermission($current_user->id,$fieldname,$module);
2911          }
2912      }
2913  
2914      if ($module == 'ProjectTask') {
2915          $query ="SELECT vtiger_projecttask.*, vtiger_crmentity.smownerid
2916                  FROM vtiger_projecttask
2917                  INNER JOIN vtiger_project ON vtiger_project.projectid = vtiger_projecttask.projectid AND vtiger_project.projectid = ?
2918                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_projecttask.projecttaskid AND vtiger_crmentity.deleted = 0";
2919      } elseif ($module == 'ProjectMilestone') {
2920          $query ="SELECT vtiger_projectmilestone.*, vtiger_crmentity.smownerid
2921                  FROM vtiger_projectmilestone
2922                  INNER JOIN vtiger_project ON vtiger_project.projectid = vtiger_projectmilestone.projectid AND vtiger_project.projectid = ?
2923                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_projectmilestone.projectmilestoneid AND vtiger_crmentity.deleted = 0";
2924      }
2925  
2926      $res = $adb->pquery($query,array(vtlib_purify($id)));
2927      $noofdata = $adb->num_rows($res);
2928  
2929      for( $j= 0;$j < $noofdata; ++$j) {
2930          $i=0;
2931          foreach($fields_list as $fieldlabel => $fieldname) {
2932              $fieldper = $componentfieldVisibilityByColumn[$fieldname];
2933              if($fieldper == '1'){
2934                  continue;
2935              }
2936              $output[0][$module]['head'][0][$i]['fielddata'] = $fieldlabel;
2937              $fieldvalue = $adb->query_result($res,$j,$fieldname);
2938              if($fieldname == 'smownerid'){
2939                  $fieldvalue = getOwnerName($fieldvalue);
2940              }
2941              $output[1][$module]['data'][$j][$i]['fielddata'] = $fieldvalue;
2942              $i++;
2943          }
2944      }
2945      $log->debug("Exiting customerportal function  get_project_components ..");
2946      return $output;
2947  }
2948  
2949  /* Function to get related tickets for a Project
2950   *  @params $id :: INT Project's Id
2951   *             $module :: String modulename
2952   *             $customerid :: INT contact's Id'
2953   */
2954  function get_project_tickets($id,$module,$customerid,$sessionid) {
2955      require_once ('modules/HelpDesk/HelpDesk.php');
2956      require_once ('include/utils/UserInfoUtil.php');
2957  
2958      global $adb,$log;
2959      $log->debug("Entering customer portal function get_project_tickets ..");
2960      $check = checkModuleActive($module);
2961      if($check == false) {
2962          return array("#MODULE INACTIVE#");
2963      }
2964  
2965      if(!validateSession($customerid,$sessionid))
2966          return null;
2967  
2968      $user = new Users();
2969      $userid = getPortalUserid();
2970      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
2971  
2972      $focus = new HelpDesk();
2973      $focus->filterInactiveFields('HelpDesk');
2974      $TicketsfieldVisibilityByColumn = array();
2975      $fields_list = array();
2976      foreach ($focus->list_fields as $fieldlabel => $values){
2977          foreach($values as $table => $fieldname){
2978              $fields_list[$fieldlabel] = $fieldname;
2979              $TicketsfieldVisibilityByColumn[$fieldname] = getColumnVisibilityPermission($current_user->id,$fieldname,'HelpDesk');
2980          }
2981      }
2982  
2983      $query = "SELECT vtiger_troubletickets.*, vtiger_crmentity.smownerid FROM vtiger_troubletickets
2984          INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid
2985          INNER JOIN vtiger_crmentityrel ON (vtiger_crmentityrel.relcrmid = vtiger_crmentity.crmid OR vtiger_crmentityrel.crmid = vtiger_crmentity.crmid)
2986          WHERE vtiger_crmentity.deleted = 0 AND (vtiger_crmentityrel.crmid = ? OR vtiger_crmentityrel.relcrmid = ?)";
2987  
2988      $params = array($id, $id);
2989      $res = $adb->pquery($query,$params);
2990      $noofdata = $adb->num_rows($res);
2991  
2992      for( $j= 0;$j < $noofdata; $j++) {
2993          $i=0;
2994          foreach($fields_list as $fieldlabel => $fieldname) {
2995              $fieldper = $TicketsfieldVisibilityByColumn[$fieldname]; //in troubletickets the list_fields has columns so we call this API
2996              if($fieldper == '1'){
2997                  continue;
2998              }
2999              $output[0][$module]['head'][0][$i]['fielddata'] = $fieldlabel;
3000              $fieldvalue = $adb->query_result($res,$j,$fieldname);
3001              $ticketid = $adb->query_result($res,$j,'ticketid');
3002              if($fieldname == 'title'){
3003                  $fieldvalue = '<a href="index.php?module=HelpDesk&action=index&fun=detail&ticketid='.$ticketid.'">'.$fieldvalue.'</a>';
3004              }
3005              if($fieldname == 'parent_id' || $fieldname == 'contact_id') {
3006                  $crmid = $fieldvalue;
3007                  $entitymodule = getSalesEntityType($crmid);
3008                  if ($crmid != '' && $entitymodule != '') {
3009                      $fieldvalues = getEntityName($entitymodule, array($crmid));
3010                      if($entitymodule == 'Contacts')
3011                      $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
3012                      elseif($entitymodule == 'Accounts')
3013                      $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
3014                  } else {
3015                      $fieldvalue = '';
3016                  }
3017              }
3018              if($fieldname == 'smownerid'){
3019                  $fieldvalue = getOwnerName($fieldvalue);
3020              }
3021              $output[1][$module]['data'][$j][$i]['fielddata'] = $fieldvalue;
3022              $i++;
3023          }
3024      }
3025      $log->debug("Exiting customerportal function  get_project_tickets ..");
3026      return $output;
3027  }
3028  
3029  /* Function to get contactid's and account's product details'
3030   *
3031   */
3032  function get_service_list_values($id,$modulename,$sessionid,$only_mine='true')
3033  {
3034      require_once ('modules/Services/Services.php');
3035      require_once ('include/utils/UserInfoUtil.php');
3036      global $current_user,$adb,$log;
3037      $log->debug("Entering customer portal Function get_service_list_values");
3038      $check = checkModuleActive($modulename);
3039      if($check == false){
3040          return array("#MODULE INACTIVE#");
3041      }
3042      $user = new Users();
3043      $userid = getPortalUserid();
3044      $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
3045      //To avoid SQL injection we are type casting as well as bound the id variable
3046      $id = (int) vtlib_purify($id);
3047      $entity_ids_list = array();
3048      $show_all=show_all($modulename);
3049  
3050      if(!validateSession($id,$sessionid))
3051      return null;
3052  
3053      if($only_mine == 'true' || $show_all == 'false')
3054      {
3055          array_push($entity_ids_list,$id);
3056      }
3057      else
3058      {
3059          $contactquery = "SELECT contactid, accountid FROM vtiger_contactdetails " .
3060          " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid" .
3061          " AND vtiger_crmentity.deleted = 0 " .
3062          " WHERE (accountid = (SELECT accountid FROM vtiger_contactdetails WHERE contactid = ?)  AND accountid != 0) OR contactid = ?";
3063          $contactres = $adb->pquery($contactquery, array($id,$id));
3064          $no_of_cont = $adb->num_rows($contactres);
3065          for($i=0;$i<$no_of_cont;$i++)
3066          {
3067              $cont_id = $adb->query_result($contactres,$i,'contactid');
3068              $acc_id = $adb->query_result($contactres,$i,'accountid');
3069              if(!in_array($cont_id, $entity_ids_list))
3070              $entity_ids_list[] = $cont_id;
3071              if(!in_array($acc_id, $entity_ids_list) && $acc_id != '0')
3072              $entity_ids_list[] = $acc_id;
3073          }
3074      }
3075  
3076      $focus = new Services();
3077      $focus->filterInactiveFields('Services');
3078      foreach ($focus->list_fields as $fieldlabel => $values){
3079          foreach($values as $table => $fieldname){
3080              $fields_list[$fieldlabel] = $fieldname;
3081          }
3082      }
3083      $fields_list['Related To'] = 'entityid';
3084      $query = array();
3085      $params = array();
3086  
3087      $query[] = "select vtiger_service.*," .
3088          "case when vtiger_crmentityrel.crmid != vtiger_service.serviceid then vtiger_crmentityrel.crmid else vtiger_crmentityrel.relcrmid end as entityid, " .
3089           "'' as setype from vtiger_service " .
3090           "inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_service.serviceid " .
3091           "left join vtiger_crmentityrel on (vtiger_crmentityrel.relcrmid=vtiger_service.serviceid or vtiger_crmentityrel.crmid=vtiger_service.serviceid) " .
3092           "where vtiger_crmentity.deleted = 0 and " .
3093           "( vtiger_crmentityrel.crmid in (".generateQuestionMarks($entity_ids_list).") OR " .
3094           "(vtiger_crmentityrel.relcrmid in (".generateQuestionMarks($entity_ids_list).") AND vtiger_crmentityrel.module = 'Services')" .
3095           ")";
3096  
3097      $params[] = array($entity_ids_list, $entity_ids_list);
3098  
3099      $checkQuotes = checkModuleActive('Quotes');
3100      if($checkQuotes == true){
3101          $query[] = "select distinct vtiger_service.*,
3102              case when vtiger_quotes.contactid is not null then vtiger_quotes.contactid else vtiger_quotes.accountid end as entityid,
3103              case when vtiger_quotes.contactid is not null then 'Contacts' else 'Accounts' end as setype
3104              from vtiger_quotes INNER join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid
3105              left join vtiger_inventoryproductrel on vtiger_inventoryproductrel.id=vtiger_quotes.quoteid
3106              left join vtiger_service on vtiger_service.serviceid = vtiger_inventoryproductrel.productid
3107              where vtiger_inventoryproductrel.productid = vtiger_service.serviceid AND vtiger_crmentity.deleted=0 and (accountid in  (". generateQuestionMarks($entity_ids_list) .") or contactid in (". generateQuestionMarks($entity_ids_list) ."))";
3108          $params[] = array($entity_ids_list,$entity_ids_list);
3109      }
3110      $checkInvoices = checkModuleActive('Invoice');
3111      if($checkInvoices == true){
3112          $query[] = "select distinct vtiger_service.*,
3113              case when vtiger_invoice.contactid !=0 then vtiger_invoice.contactid else vtiger_invoice.accountid end as entityid,
3114              case when vtiger_invoice.contactid !=0 then 'Contacts' else 'Accounts' end as setype
3115              from vtiger_invoice
3116              INNER join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid
3117              left join vtiger_inventoryproductrel on vtiger_inventoryproductrel.id=vtiger_invoice.invoiceid
3118              left join vtiger_service on vtiger_service.serviceid = vtiger_inventoryproductrel.productid
3119              where vtiger_inventoryproductrel.productid = vtiger_service.serviceid AND vtiger_crmentity.deleted=0 and (accountid in (". generateQuestionMarks($entity_ids_list) .") or contactid in  (". generateQuestionMarks($entity_ids_list) ."))";
3120          $params[] = array($entity_ids_list,$entity_ids_list);
3121      }
3122  
3123      $ServicesfieldVisibilityPermissions = array();
3124      foreach($fields_list as $fieldlabel=> $fieldname) {
3125          $ServicesfieldVisibilityPermissions[$fieldname] =
3126              getFieldVisibilityPermission('Services',$current_user->id,$fieldname);
3127      }
3128  
3129      $fieldValuesToRound = array('unit_price','commissionrate');
3130  
3131      for($k=0;$k<count($query);$k++)
3132      {
3133          $res[$k] = $adb->pquery($query[$k],$params[$k]);
3134          $noofdata[$k] = $adb->num_rows($res[$k]);
3135          if($noofdata[$k] == 0) {
3136              $output[$k][$modulename]['data'] = '';
3137          }
3138          for( $j= 0;$j < $noofdata[$k]; $j++)
3139          {
3140              $i=0;
3141              foreach($fields_list as $fieldlabel=> $fieldname) {
3142                  $fieldper = $ServicesfieldVisibilityPermissions[$fieldname];
3143                  if($fieldper == '1' && $fieldname != 'entityid'){
3144                      continue;
3145                  }
3146                  $output[$k][$modulename]['head'][0][$i]['fielddata'] = $fieldlabel;
3147                  $fieldvalue = $adb->query_result($res[$k],$j,$fieldname);
3148                  $fieldid = $adb->query_result($res[$k],$j,'serviceid');
3149  
3150                  if(in_array($fieldname, $fieldValuesToRound)){
3151                      $fieldvalue = round($fieldvalue, 2);
3152                  }
3153                  if($fieldname == 'entityid') {
3154                      $crmid = $fieldvalue;
3155                      $module = $adb->query_result($res[$k],$j,'setype');
3156                      if($module == ''){
3157                          $module = $adb->query_result($adb->pquery("SELECT setype FROM vtiger_crmentity WHERE crmid = ?", array($crmid)),0,'setype');
3158                      }
3159                      if ($crmid != '' && $module != '') {
3160                          $fieldvalues = getEntityName($module, array($crmid));
3161                          if($module == 'Contacts')
3162                          $fieldvalue = '<a href="index.php?module=Contacts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
3163                          elseif($module == 'Accounts')
3164                          $fieldvalue = '<a href="index.php?module=Accounts&action=index&id='.$crmid.'">'.$fieldvalues[$crmid].'</a>';
3165                      } else {
3166                          $fieldvalue = '';
3167                      }
3168                  }
3169  
3170                  if($fieldname == 'servicename')
3171                  $fieldvalue = '<a href="index.php?module=Services&action=index&id='.$fieldid.'">'.$fieldvalue.'</a>';
3172  
3173                  if($fieldname == 'unit_price'){
3174                      $sym = getCurrencySymbol($res[$k],$j,'currency_id');
3175                      $fieldvalue = $sym.$fieldvalue;
3176                  }
3177                  $output[$k][$modulename]['data'][$j][$i]['fielddata'] = $fieldvalue;
3178                  $i++;
3179              }
3180          }
3181      }
3182      $log->debug("Exiting customerportal function get_product_list_values.....");
3183      return $output;
3184  }
3185  
3186  
3187  /* Function to get the list of modules allowed for customer portal
3188   */
3189  function get_modules()
3190  {
3191      global $adb,$log;
3192      $log->debug("Entering customer portal Function get_modules");
3193  
3194      // Check if information is available in cache?
3195      $modules = Vtiger_Soap_CustomerPortal::lookupAllowedModules();
3196      if($modules === false) {
3197          $modules = array();
3198  
3199          $query = $adb->pquery("SELECT vtiger_customerportal_tabs.* FROM vtiger_customerportal_tabs
3200              INNER JOIN vtiger_tab ON vtiger_tab.tabid = vtiger_customerportal_tabs.tabid
3201              WHERE vtiger_tab.presence = 0 AND vtiger_customerportal_tabs.visible = 1", array());
3202          $norows = $adb->num_rows($query);
3203          if($norows) {
3204              while($resultrow = $adb->fetch_array($query)) {
3205                  $modules[(int)$resultrow['sequence']] = getTabModuleName($resultrow['tabid']);
3206              }
3207              ksort($modules); // Order via SQL might cost us, so handling it ourselves in this case
3208          }
3209          Vtiger_Soap_CustomerPortal::updateAllowedModules($modules);
3210      }
3211      $log->debug("Exiting customerportal function get_modules");
3212      return $modules;
3213  }
3214  
3215  /* Function to check if the module has the permission to show the related contact's and Account's information
3216   */
3217  function show_all($module){
3218  
3219      global $adb,$log;
3220      $log->debug("Entering customer portal Function show_all");
3221      $tabid = getTabid($module);
3222      if($module=='Tickets'){
3223          $tabid = getTabid('HelpDesk');
3224      }
3225      $query = $adb->pquery("SELECT prefvalue from vtiger_customerportal_prefs where tabid = ?", array($tabid));
3226      $norows = $adb->num_rows($query);
3227      if($norows > 0){
3228          if($adb->query_result($query,0,'prefvalue') == 1){
3229              return 'true';
3230          }else {
3231              return 'false';
3232          }
3233      }else {
3234          return 'false';
3235      }
3236      $log->debug("Exiting customerportal function show_all");
3237  }
3238  
3239  /* Function to get ServiceContracts information in the tickets module if the ticket is related to ServiceContracts
3240   */
3241  function getRelatedServiceContracts($crmid){
3242      global $adb,$log;
3243      $log->debug("Entering customer portal function getRelatedServiceContracts");
3244      $module = 'ServiceContracts';
3245      $sc_info = array();
3246      if(vtlib_isModuleActive($module) !== true){
3247          return $sc_info;
3248      }
3249      $query = "SELECT * FROM vtiger_servicecontracts " .
3250      "INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_servicecontracts.servicecontractsid AND vtiger_crmentity.deleted = 0 " .
3251      "LEFT JOIN vtiger_crmentityrel ON vtiger_crmentityrel.crmid = vtiger_servicecontracts.servicecontractsid " .
3252      "WHERE (vtiger_crmentityrel.relcrmid = ? and vtiger_crmentityrel.module= 'ServiceContracts')";
3253  
3254      $res = $adb->pquery($query,array($crmid));
3255      $rows = $adb->num_rows($res);
3256      for($i=0;$i<$rows;$i++){
3257          $sc_info[$i]['Subject'] = $adb->query_result($res,$i,'subject');
3258          $sc_info[$i]['Used Units'] = $adb->query_result($res,$i,'used_units');
3259          $sc_info[$i]['Total Units'] = $adb->query_result($res,$i,'total_units');
3260          $sc_info[$i]['Available Units'] = $adb->query_result($res,$i,'total_units')- $adb->query_result($res,$i,'used_units');
3261      }
3262      return $sc_info;
3263      $log->debug("Exiting customerportal function getRelatedServiceContracts");
3264  }
3265  
3266  
3267  function getPortalUserid() {
3268      global $adb,$log;
3269      $log->debug("Entering customer portal function getPortalUserid");
3270  
3271      // Look the value from cache first
3272      $userid = Vtiger_Soap_CustomerPortal::lookupPrefValue('userid');
3273      if($userid === false) {
3274          $res = $adb->pquery("SELECT prefvalue FROM vtiger_customerportal_prefs WHERE prefkey = 'userid' AND tabid = 0", array());
3275          $norows = $adb->num_rows($res);
3276          if($norows > 0) {
3277              $userid = $adb->query_result($res,0,'prefvalue');
3278              // Update the cache information now.
3279              Vtiger_Soap_CustomerPortal::updatePrefValue('userid', $userid);
3280          }
3281      }
3282      return $userid;
3283      $log->debug("Exiting customerportal function getPortalUserid");
3284  }
3285  
3286  function checkModuleActive($module){
3287      global $adb,$log;
3288  
3289      $isactive = false;
3290      $modules = get_modules(true);
3291  
3292      foreach($modules as $key => $value){
3293          if(strcmp($module,$value) == 0){
3294              $isactive = true;
3295              break;
3296          }
3297      }
3298      return $isactive;
3299  }
3300  
3301  /**
3302   *  Function that gives the Currency Symbol
3303   * @params $result $adb object - resultset
3304   * $column String column name
3305   * Return $value - Currency Symbol
3306   */
3307  function getCurrencySymbol($result,$i,$column){
3308      global $adb;
3309      $currencyid = $adb->query_result($result,$i,$column);
3310      $curr = getCurrencySymbolandCRate($currencyid);
3311      $value = "(".$curr['symbol'].")";
3312      return $value;
3313  
3314  }
3315  
3316  function getDefaultAssigneeId() {
3317      global $adb;
3318      $adb->println("Entering customer portal function getPortalUserid");
3319  
3320      // Look the value from cache first
3321      $defaultassignee = Vtiger_Soap_CustomerPortal::lookupPrefValue('defaultassignee');
3322      if($defaultassignee === false) {
3323          $res = $adb->pquery("SELECT prefvalue FROM vtiger_customerportal_prefs WHERE prefkey = 'defaultassignee' AND tabid = 0", array());
3324          $norows = $adb->num_rows($res);
3325          if($norows > 0) {
3326              $defaultassignee = $adb->query_result($res,0,'prefvalue');
3327              // Update the cache information now.
3328              Vtiger_Soap_CustomerPortal::updatePrefValue('defaultassignee', $defaultassignee);
3329          }
3330      }
3331      return $defaultassignee;
3332  }
3333  
3334  /* Begin the HTTP listener service and exit. */
3335  if (!isset($HTTP_RAW_POST_DATA)){
3336      $HTTP_RAW_POST_DATA = file_get_contents('php://input');
3337  }
3338  $server->service($HTTP_RAW_POST_DATA);
3339  
3340  exit();
3341  
3342  ?>


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