[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

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

   1  <?php
   2  /*********************************************************************************
   3   * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
   4   * ("License"); You may not use this file except in compliance with the
   5   * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
   6   * Software distributed under the License is distributed on an  "AS IS"  basis,
   7   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
   8   * the specific language governing rights and limitations under the License.
   9   * The Original Code is:  SugarCRM Open Source
  10   * The Initial Developer of the Original Code is SugarCRM, Inc.
  11   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
  12   * All Rights Reserved.
  13   * Contributor(s): ______________________________________.
  14   ********************************************************************************/
  15  /*********************************************************************************
  16   * $Header: /advent/projects/wesat/vtiger_crm/sugarcrm/modules/Accounts/Accounts.php,v 1.53 2005/04/28 08:06:45 rank Exp $
  17   * Description:  Defines the Account SugarBean Account entity with the necessary
  18   * methods and variables.
  19   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  20   * All Rights Reserved.
  21   * Contributor(s): ______________________________________..
  22   ********************************************************************************/
  23  class Accounts extends CRMEntity {
  24      var $log;
  25      var $db;
  26      var $table_name = "vtiger_account";
  27      var $table_index= 'accountid';
  28      var $tab_name = Array('vtiger_crmentity','vtiger_account','vtiger_accountbillads','vtiger_accountshipads','vtiger_accountscf');
  29      var $tab_name_index = Array('vtiger_crmentity'=>'crmid','vtiger_account'=>'accountid','vtiger_accountbillads'=>'accountaddressid','vtiger_accountshipads'=>'accountaddressid','vtiger_accountscf'=>'accountid');
  30      /**
  31       * Mandatory table for supporting custom fields.
  32       */
  33      var $customFieldTable = Array('vtiger_accountscf', 'accountid');
  34      var $entity_table = "vtiger_crmentity";
  35  
  36      var $column_fields = Array();
  37  
  38      var $sortby_fields = Array('accountname','bill_city','website','phone','smownerid');
  39  
  40      //var $groupTable = Array('vtiger_accountgrouprelation','accountid');
  41  
  42      // This is the list of vtiger_fields that are in the lists.
  43      var $list_fields = Array(
  44              'Account Name'=>Array('vtiger_account'=>'accountname'),
  45              'Billing City'=>Array('vtiger_accountbillads'=>'bill_city'),
  46              'Website'=>Array('vtiger_account'=>'website'),
  47              'Phone'=>Array('vtiger_account'=> 'phone'),
  48              'Assigned To'=>Array('vtiger_crmentity'=>'smownerid')
  49              );
  50  
  51      var $list_fields_name = Array(
  52              'Account Name'=>'accountname',
  53              'Billing City'=>'bill_city',
  54              'Website'=>'website',
  55              'Phone'=>'phone',
  56              'Assigned To'=>'assigned_user_id'
  57              );
  58      var $list_link_field= 'accountname';
  59  
  60      var $search_fields = Array(
  61              'Account Name'=>Array('vtiger_account'=>'accountname'),
  62              'Billing City'=>Array('vtiger_accountbillads'=>'bill_city'),
  63              'Assigned To'=>Array('vtiger_crmentity'=>'smownerid'),
  64              );
  65  
  66      var $search_fields_name = Array(
  67              'Account Name'=>'accountname',
  68              'Billing City'=>'bill_city',
  69              'Assigned To'=>'assigned_user_id',
  70              );
  71      // This is the list of vtiger_fields that are required
  72      var $required_fields =  array();
  73  
  74      // Used when enabling/disabling the mandatory fields for the module.
  75      // Refers to vtiger_field.fieldname values.
  76      var $mandatory_fields = Array('assigned_user_id', 'createdtime', 'modifiedtime', 'accountname');
  77  
  78      //Default Fields for Email Templates -- Pavani
  79      var $emailTemplate_defaultFields = array('accountname','account_type','industry','annualrevenue','phone','email1','rating','website','fax');
  80  
  81      //Added these variables which are used as default order by and sortorder in ListView
  82      var $default_order_by = 'accountname';
  83      var $default_sort_order = 'ASC';
  84  
  85      // For Alphabetical search
  86      var $def_basicsearch_col = 'accountname';
  87  
  88      var $related_module_table_index = array(
  89          'Contacts' => array('table_name' => 'vtiger_contactdetails', 'table_index' => 'contactid', 'rel_index' => 'accountid'),
  90          'Potentials' => array('table_name' => 'vtiger_potential', 'table_index' => 'potentialid', 'rel_index' => 'related_to'),
  91          'Quotes' => array('table_name' => 'vtiger_quotes', 'table_index' => 'quoteid', 'rel_index' => 'accountid'),
  92          'SalesOrder' => array('table_name' => 'vtiger_salesorder', 'table_index' => 'salesorderid', 'rel_index' => 'accountid'),
  93          'Invoice' => array('table_name' => 'vtiger_invoice', 'table_index' => 'invoiceid', 'rel_index' => 'accountid'),
  94          'HelpDesk' => array('table_name' => 'vtiger_troubletickets', 'table_index' => 'ticketid', 'rel_index' => 'parent_id'),
  95          'Products' => array('table_name' => 'vtiger_seproductsrel', 'table_index' => 'productid', 'rel_index' => 'crmid'),
  96          'Calendar' => array('table_name' => 'vtiger_seactivityrel', 'table_index' => 'activityid', 'rel_index' => 'crmid'),
  97          'Documents' => array('table_name' => 'vtiger_senotesrel', 'table_index' => 'notesid', 'rel_index' => 'crmid'),
  98          'ServiceContracts' => array('table_name' => 'vtiger_servicecontracts', 'table_index' => 'servicecontractsid', 'rel_index' => 'sc_related_to'),
  99          'Services' => array('table_name' => 'vtiger_crmentityrel', 'table_index' => 'crmid', 'rel_index' => 'crmid'),
 100          'Campaigns' => array('table_name' => 'vtiger_campaignaccountrel', 'table_index' => 'campaignid', 'rel_index' => 'accountid'),
 101          'Assets' => array('table_name' => 'vtiger_assets', 'table_index' => 'assetsid', 'rel_index' => 'account'),
 102          'Project' => array('table_name' => 'vtiger_project', 'table_index' => 'projectid', 'rel_index' => 'linktoaccountscontacts'),
 103      );
 104  
 105  	function Accounts() {
 106          $this->log =LoggerManager::getLogger('account');
 107          $this->db = PearDatabase::getInstance();
 108          $this->column_fields = getColumnFields('Accounts');
 109      }
 110  
 111      /** Function to handle module specific operations when saving a entity
 112      */
 113  	function save_module($module) {
 114  
 115      }
 116  
 117  
 118      // Mike Crowe Mod --------------------------------------------------------Default ordering for us
 119      /** Returns a list of the associated Campaigns
 120       * @param $id -- campaign id :: Type Integer
 121       * @returns list of campaigns in array format
 122       */
 123  	function get_campaigns($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 124          global $log, $singlepane_view,$currentModule,$current_user;
 125          $log->debug("Entering get_campaigns(".$id.") method ...");
 126          $this_module = $currentModule;
 127  
 128          $related_module = vtlib_getModuleNameById($rel_tab_id);
 129          require_once("modules/$related_module/$related_module.php");
 130          $other = new $related_module();
 131          vtlib_setup_modulevars($related_module, $other);
 132          $singular_modname = vtlib_toSingular($related_module);
 133  
 134          $parenttab = getParentTab();
 135  
 136          if($singlepane_view == 'true')
 137              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 138          else
 139              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 140  
 141          $button = '';
 142  
 143          $button .= '<input type="hidden" name="email_directing_module"><input type="hidden" name="record">';
 144  
 145          if($actions) {
 146              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 147              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 148                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 149              }
 150          }
 151  
 152          $entityIds = $this->getRelatedContactsIds();
 153          $entityIds = implode(',', $entityIds);
 154  
 155          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 156  
 157          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 158                  vtiger_campaign.campaignid, vtiger_campaign.campaignname, vtiger_campaign.campaigntype, vtiger_campaign.campaignstatus,
 159                  vtiger_campaign.expectedrevenue, vtiger_campaign.closingdate, vtiger_crmentity.crmid, vtiger_crmentity.smownerid,
 160                  vtiger_crmentity.modifiedtime
 161                  from vtiger_campaign
 162                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_campaign.campaignid
 163                  INNER JOIN vtiger_campaignscf ON vtiger_campaignscf.campaignid = vtiger_campaign.campaignid
 164                  LEFT JOIN vtiger_campaignaccountrel ON vtiger_campaignaccountrel.campaignid=vtiger_campaign.campaignid
 165                  LEFT JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.campaignid=vtiger_campaign.campaignid
 166                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid=vtiger_crmentity.smownerid
 167                  LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
 168                  WHERE vtiger_crmentity.deleted=0 AND (vtiger_campaignaccountrel.accountid=$id";
 169  
 170          if(!empty ($entityIds)){
 171              $query .= " OR vtiger_campaigncontrel.contactid IN (".$entityIds."))";
 172          } else {
 173              $query .= ")";
 174          }
 175  
 176          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 177  
 178          if($return_value == null) $return_value = Array();
 179          $return_value['CUSTOM_BUTTON'] = $button;
 180  
 181          $log->debug("Exiting get_campaigns method ...");
 182          return $return_value;
 183      }
 184  
 185      /** Returns a list of the associated contacts
 186       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 187       * All Rights Reserved..
 188       * Contributor(s): ______________________________________..
 189       */
 190  	function get_contacts($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 191          global $log, $singlepane_view,$currentModule,$current_user;
 192          $log->debug("Entering get_contacts(".$id.") method ...");
 193          $this_module = $currentModule;
 194  
 195          $related_module = vtlib_getModuleNameById($rel_tab_id);
 196          require_once("modules/$related_module/$related_module.php");
 197          $other = new $related_module();
 198          vtlib_setup_modulevars($related_module, $other);
 199          $singular_modname = vtlib_toSingular($related_module);
 200  
 201          $parenttab = getParentTab();
 202  
 203          if($singlepane_view == 'true')
 204              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 205          else
 206              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 207  
 208          $button = '';
 209  
 210          if($actions && getFieldVisibilityPermission($related_module, $current_user->id, 'account_id','readwrite') == '0') {
 211              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 212              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 213                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 214              }
 215              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 216                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 217                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 218                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 219              }
 220          }
 221  
 222          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
 223                              'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 224          $query = "SELECT vtiger_contactdetails.*,
 225              vtiger_crmentity.crmid,
 226                          vtiger_crmentity.smownerid,
 227              vtiger_account.accountname,
 228              case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
 229              FROM vtiger_contactdetails
 230              INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
 231              LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_contactdetails.accountid
 232              INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid
 233              INNER JOIN vtiger_contactsubdetails ON vtiger_contactdetails.contactid = vtiger_contactsubdetails.contactsubscriptionid
 234              INNER JOIN vtiger_customerdetails ON vtiger_contactdetails.contactid = vtiger_customerdetails.customerid
 235              INNER JOIN vtiger_contactscf ON vtiger_contactdetails.contactid = vtiger_contactscf.contactid
 236              LEFT JOIN vtiger_groups    ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 237              LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
 238              WHERE vtiger_crmentity.deleted = 0
 239              AND vtiger_contactdetails.accountid = ".$id;
 240  
 241          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 242  
 243          if($return_value == null) $return_value = Array();
 244          $return_value['CUSTOM_BUTTON'] = $button;
 245  
 246          $log->debug("Exiting get_contacts method ...");
 247          return $return_value;
 248      }
 249  
 250      /** Returns a list of the associated opportunities
 251       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 252       * All Rights Reserved..
 253       * Contributor(s): ______________________________________..
 254       */
 255  	function get_opportunities($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 256          global $log, $singlepane_view,$currentModule,$current_user;
 257          $log->debug("Entering get_opportunities(".$id.") method ...");
 258          $this_module = $currentModule;
 259  
 260          $related_module = vtlib_getModuleNameById($rel_tab_id);
 261          require_once("modules/$related_module/$related_module.php");
 262          $other = new $related_module();
 263          vtlib_setup_modulevars($related_module, $other);
 264          $singular_modname = vtlib_toSingular($related_module);
 265  
 266          $parenttab = getParentTab();
 267  
 268          if($singlepane_view == 'true')
 269              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 270          else
 271              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 272  
 273          $button = '';
 274  
 275          if($actions) {
 276              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 277              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 278                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 279              }
 280              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 281                  $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 282                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 283                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 284              }
 285          }
 286  
 287          // TODO: We need to add pull contacts if its linked as secondary in Potentials too.
 288          // These relations are captued in vtiger_contpotentialrel
 289          // Better to provide switch to turn-on / off this feature like in
 290          // Contacts::get_opportunities
 291  
 292          $entityIds = $this->getRelatedContactsIds();
 293          $entityIds = implode(',', $entityIds);
 294  
 295          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 296  
 297          $query = "SELECT vtiger_potential.potentialid, vtiger_potential.related_to, vtiger_potential.potentialname, vtiger_potential.sales_stage,vtiger_potential.contact_id,
 298                  vtiger_potential.potentialtype, vtiger_potential.amount, vtiger_potential.closingdate, vtiger_potential.potentialtype, vtiger_account.accountname,
 299                  case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,vtiger_crmentity.crmid, vtiger_crmentity.smownerid
 300                  FROM vtiger_potential
 301                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid
 302                  LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_potential.related_to
 303                  INNER JOIN vtiger_potentialscf ON vtiger_potential.potentialid = vtiger_potentialscf.potentialid
 304                  LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
 305                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 306                  WHERE vtiger_crmentity.deleted = 0 AND (vtiger_potential.related_to = $id ";
 307          if(!empty($entityIds)) {
 308              $query .= " OR vtiger_potential.contact_id IN (".$entityIds.")";
 309          }
 310  
 311          $query .= ')';
 312  
 313          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 314  
 315          if($return_value == null) $return_value = Array();
 316          $return_value['CUSTOM_BUTTON'] = $button;
 317  
 318          $log->debug("Exiting get_opportunities method ...");
 319          return $return_value;
 320      }
 321  
 322      /** Returns a list of the associated tasks
 323       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 324       * All Rights Reserved..
 325       * Contributor(s): ______________________________________..
 326       */
 327  	function get_activities($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 328          global $log, $singlepane_view,$currentModule,$current_user;
 329          $log->debug("Entering get_activities(".$id.") method ...");
 330          $this_module = $currentModule;
 331  
 332          $related_module = vtlib_getModuleNameById($rel_tab_id);
 333          require_once("modules/$related_module/Activity.php");
 334          $other = new Activity();
 335          vtlib_setup_modulevars($related_module, $other);
 336          $singular_modname = vtlib_toSingular($related_module);
 337  
 338          $parenttab = getParentTab();
 339  
 340          if($singlepane_view == 'true')
 341              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 342          else
 343              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 344  
 345          $button = '';
 346  
 347          $button .= '<input type="hidden" name="activity_mode">';
 348  
 349          if($actions) {
 350              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 351              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 352                  if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id', 'readwrite') == '0') {
 353                      $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
 354                          " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Task\";' type='submit' name='button'" .
 355                          " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_TODO', $related_module) ."'>&nbsp;";
 356                  }
 357                  if(getFieldVisibilityPermission('Events',$current_user->id,'parent_id', 'readwrite') == '0') {
 358                      $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
 359                          " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Events\";' type='submit' name='button'" .
 360                          " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_EVENT', $related_module) ."'>";
 361                  }
 362              }
 363          }
 364  
 365          $entityIds = $this->getRelatedContactsIds();
 366          $entityIds = implode(',', $entityIds);
 367  
 368          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 369  
 370          $query = "SELECT vtiger_activity.*, vtiger_cntactivityrel.*, vtiger_seactivityrel.crmid as parent_id, vtiger_contactdetails.lastname,
 371                  vtiger_contactdetails.firstname, vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime,
 372                  case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 373                  vtiger_recurringevents.recurringtype
 374                  FROM vtiger_activity
 375                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_activity.activityid
 376                  LEFT JOIN vtiger_seactivityrel ON vtiger_seactivityrel.activityid = vtiger_activity.activityid
 377                  LEFT JOIN vtiger_cntactivityrel ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid
 378                  LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid
 379                  LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
 380                  LEFT OUTER JOIN vtiger_recurringevents ON vtiger_recurringevents.activityid = vtiger_activity.activityid
 381                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 382                  WHERE vtiger_crmentity.deleted = 0
 383                  AND ((vtiger_activity.activitytype='Task' and vtiger_activity.status not in ('Completed','Deferred'))
 384                  OR (vtiger_activity.activitytype not in ('Emails','Task') and  vtiger_activity.eventstatus not in ('','Held')))
 385                  AND (vtiger_seactivityrel.crmid = $id";
 386  
 387          if(!empty ($entityIds)){
 388              $query .= " OR vtiger_cntactivityrel.contactid IN (".$entityIds."))";
 389          } else {
 390              $query .= ")";
 391          }
 392          // There could be more than one contact for an activity.
 393          $query .= ' GROUP BY vtiger_activity.activityid';
 394  
 395          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 396          if($return_value == null) $return_value = Array();
 397          $return_value['CUSTOM_BUTTON'] = $button;
 398  
 399          $log->debug("Exiting get_activities method ...");
 400          return $return_value;
 401      }
 402  
 403      /**
 404       * Function to get Account related Task & Event which have activity type Held, Completed or Deferred.
 405        * @param  integer   $id      - accountid
 406        * returns related Task or Event record in array format
 407        */
 408  	function get_history($id)
 409      {
 410          global $log;
 411                  $log->debug("Entering get_history(".$id.") method ...");
 412  
 413          $entityIds = $this->getRelatedContactsIds();
 414          $entityIds = implode(',', $entityIds);
 415  
 416          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 417  
 418          $query = "SELECT DISTINCT(vtiger_activity.activityid), vtiger_activity.subject, vtiger_activity.status, vtiger_activity.eventstatus,
 419                  vtiger_activity.activitytype, vtiger_activity.date_start, vtiger_activity.due_date, vtiger_activity.time_start, vtiger_activity.time_end,
 420                  vtiger_crmentity.modifiedtime, vtiger_crmentity.createdtime, vtiger_crmentity.description,
 421                  case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
 422                  FROM vtiger_activity
 423                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_activity.activityid
 424                  LEFT JOIN vtiger_seactivityrel ON vtiger_seactivityrel.activityid = vtiger_activity.activityid
 425                  LEFT JOIN vtiger_cntactivityrel ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid
 426                  LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid
 427                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 428                  LEFT JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid
 429                  WHERE (vtiger_activity.activitytype != 'Emails')
 430                  AND (vtiger_activity.status = 'Completed'
 431                      OR vtiger_activity.status = 'Deferred'
 432                      OR (vtiger_activity.eventstatus = 'Held' AND vtiger_activity.eventstatus != ''))
 433                  AND vtiger_crmentity.deleted = 0 AND (vtiger_seactivityrel.crmid = $id";
 434  
 435          if(!empty ($entityIds)){
 436              $query .= " OR vtiger_cntactivityrel.contactid IN (".$entityIds."))";
 437          } else {
 438              $query .= ")";
 439          }
 440  
 441          //Don't add order by, because, for security, one more condition will be added with this query in include/RelatedListView.php
 442          $log->debug("Exiting get_history method ...");
 443          return getHistory('Accounts',$query,$id);
 444      }
 445  
 446      /** Returns a list of the associated emails
 447       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 448       * All Rights Reserved..
 449       * Contributor(s): ______________________________________..
 450      */
 451  	function get_emails($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 452          global $log, $singlepane_view,$currentModule,$current_user, $adb;
 453          $log->debug("Entering get_emails(".$id.") method ...");
 454          $this_module = $currentModule;
 455  
 456          $related_module = vtlib_getModuleNameById($rel_tab_id);
 457          require_once("modules/$related_module/$related_module.php");
 458          $other = new $related_module();
 459          vtlib_setup_modulevars($related_module, $other);
 460          $singular_modname = vtlib_toSingular($related_module);
 461  
 462          $parenttab = getParentTab();
 463  
 464          if($singlepane_view == 'true')
 465              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 466          else
 467              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 468  
 469          $button = '';
 470  
 471          $button .= '<input type="hidden" name="email_directing_module"><input type="hidden" name="record">';
 472  
 473          if($actions) {
 474              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 475              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 476                  $button .= "<input title='". getTranslatedString('LBL_ADD_NEW')." ". getTranslatedString($singular_modname)."' accessyKey='F' class='crmbutton small create' onclick='fnvshobj(this,\"sendmail_cont\");sendmail(\"$this_module\",$id);' type='button' name='button' value='". getTranslatedString('LBL_ADD_NEW')." ". getTranslatedString($singular_modname)."'></td>";
 477              }
 478          }
 479  
 480          $entityIds = $this->getRelatedContactsIds();
 481          array_push($entityIds, $id);
 482          $entityIds = implode(',', $entityIds);
 483  
 484          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 485  
 486          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 487              vtiger_activity.activityid, vtiger_activity.subject, vtiger_activity.activitytype, vtiger_crmentity.modifiedtime,
 488              vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_activity.date_start,vtiger_activity.time_start, vtiger_seactivityrel.crmid as parent_id
 489              FROM vtiger_activity, vtiger_seactivityrel, vtiger_account, vtiger_users, vtiger_crmentity
 490              LEFT JOIN vtiger_groups ON vtiger_groups.groupid=vtiger_crmentity.smownerid
 491              WHERE vtiger_seactivityrel.activityid = vtiger_activity.activityid
 492                  AND vtiger_seactivityrel.crmid IN (".$entityIds.")
 493                  AND vtiger_users.id=vtiger_crmentity.smownerid
 494                  AND vtiger_crmentity.crmid = vtiger_activity.activityid
 495                  AND vtiger_activity.activitytype='Emails'
 496                  AND vtiger_account.accountid = ".$id."
 497                  AND vtiger_crmentity.deleted = 0";
 498  
 499          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 500  
 501          if($return_value == null) $return_value = Array();
 502          $return_value['CUSTOM_BUTTON'] = $button;
 503  
 504          $log->debug("Exiting get_emails method ...");
 505          return $return_value;
 506      }
 507  
 508  
 509      /**
 510      * Function to get Account related Quotes
 511      * @param  integer   $id      - accountid
 512      * returns related Quotes record in array format
 513      */
 514  	function get_quotes($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 515          global $log, $singlepane_view,$currentModule,$current_user;
 516          $log->debug("Entering get_quotes(".$id.") method ...");
 517          $this_module = $currentModule;
 518  
 519          $related_module = vtlib_getModuleNameById($rel_tab_id);
 520          require_once("modules/$related_module/$related_module.php");
 521          $other = new $related_module();
 522          vtlib_setup_modulevars($related_module, $other);
 523          $singular_modname = vtlib_toSingular($related_module);
 524  
 525          $parenttab = getParentTab();
 526  
 527          if($singlepane_view == 'true')
 528              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 529          else
 530              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 531  
 532          $button = '';
 533  
 534          if($actions && getFieldVisibilityPermission($related_module, $current_user->id, 'account_id','readwrite') == '0') {
 535              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 536              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 537                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 538              }
 539              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 540                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 541                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 542                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 543              }
 544          }
 545  
 546          $entityIds = $this->getRelatedContactsIds();
 547          $entityIds = implode(',', $entityIds);
 548  
 549          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 550  
 551          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 552                  vtiger_crmentity.*, vtiger_quotes.*, vtiger_potential.potentialname, vtiger_account.accountname
 553                  FROM vtiger_quotes
 554                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_quotes.quoteid
 555                  LEFT OUTER JOIN vtiger_account ON vtiger_account.accountid = vtiger_quotes.accountid
 556                  LEFT OUTER JOIN vtiger_potential ON vtiger_potential.potentialid = vtiger_quotes.potentialid
 557                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 558                  LEFT JOIN vtiger_quotescf ON vtiger_quotescf.quoteid = vtiger_quotes.quoteid
 559                  LEFT JOIN vtiger_quotesbillads ON vtiger_quotesbillads.quotebilladdressid = vtiger_quotes.quoteid
 560                  LEFT JOIN vtiger_quotesshipads ON vtiger_quotesshipads.quoteshipaddressid = vtiger_quotes.quoteid
 561                  LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
 562                  WHERE vtiger_crmentity.deleted = 0 AND (vtiger_account.accountid = $id";
 563  
 564          if(!empty ($entityIds)){
 565              $query .= " OR vtiger_quotes.contactid IN (".$entityIds."))";
 566          } else {
 567              $query .= ")";
 568          }
 569  
 570          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 571  
 572          if($return_value == null) $return_value = Array();
 573          $return_value['CUSTOM_BUTTON'] = $button;
 574  
 575          $log->debug("Exiting get_quotes method ...");
 576          return $return_value;
 577      }
 578      /**
 579      * Function to get Account related Invoices
 580      * @param  integer   $id      - accountid
 581      * returns related Invoices record in array format
 582      */
 583  	function get_invoices($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 584          global $log, $singlepane_view,$currentModule,$current_user;
 585          $log->debug("Entering get_invoices(".$id.") method ...");
 586          $this_module = $currentModule;
 587  
 588          $related_module = vtlib_getModuleNameById($rel_tab_id);
 589          require_once("modules/$related_module/$related_module.php");
 590          $other = new $related_module();
 591          vtlib_setup_modulevars($related_module, $other);
 592          $singular_modname = vtlib_toSingular($related_module);
 593  
 594          $parenttab = getParentTab();
 595  
 596          if($singlepane_view == 'true')
 597              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 598          else
 599              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 600  
 601          $button = '';
 602  
 603          if($actions && getFieldVisibilityPermission($related_module, $current_user->id, 'account_id','readwrite') == '0') {
 604              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 605              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 606                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 607              }
 608              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 609                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 610                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 611                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 612              }
 613          }
 614  
 615          $entityIds = $this->getRelatedContactsIds();
 616          $entityIds = implode(',', $entityIds);
 617  
 618          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 619  
 620          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 621                  vtiger_crmentity.*, vtiger_invoice.*, vtiger_account.accountname, vtiger_salesorder.subject AS salessubject
 622                  FROM vtiger_invoice
 623                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_invoice.invoiceid
 624                  LEFT OUTER JOIN vtiger_account ON vtiger_account.accountid = vtiger_invoice.accountid
 625                  LEFT OUTER JOIN vtiger_salesorder ON vtiger_salesorder.salesorderid = vtiger_invoice.salesorderid
 626                  LEFT JOIN vtiger_invoicecf ON vtiger_invoicecf.invoiceid = vtiger_invoice.invoiceid
 627                  LEFT JOIN vtiger_invoicebillads ON vtiger_invoicebillads.invoicebilladdressid = vtiger_invoice.invoiceid
 628                  LEFT JOIN vtiger_invoiceshipads ON vtiger_invoiceshipads.invoiceshipaddressid = vtiger_invoice.invoiceid
 629                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 630                  LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
 631                  WHERE vtiger_crmentity.deleted = 0 AND (vtiger_invoice.accountid = $id";
 632  
 633          if(!empty ($entityIds)){
 634              $query .= " OR vtiger_invoice.contactid IN (".$entityIds."))";
 635          } else {
 636              $query .= ")";
 637          }
 638  
 639          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 640  
 641          if($return_value == null) $return_value = Array();
 642          $return_value['CUSTOM_BUTTON'] = $button;
 643  
 644          $log->debug("Exiting get_invoices method ...");
 645          return $return_value;
 646      }
 647  
 648      /**
 649      * Function to get Account related SalesOrder
 650      * @param  integer   $id      - accountid
 651      * returns related SalesOrder record in array format
 652      */
 653  	function get_salesorder($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 654          global $log, $singlepane_view,$currentModule,$current_user;
 655          $log->debug("Entering get_salesorder(".$id.") method ...");
 656          $this_module = $currentModule;
 657  
 658          $related_module = vtlib_getModuleNameById($rel_tab_id);
 659          require_once("modules/$related_module/$related_module.php");
 660          $other = new $related_module();
 661          vtlib_setup_modulevars($related_module, $other);
 662          $singular_modname = vtlib_toSingular($related_module);
 663  
 664          $parenttab = getParentTab();
 665  
 666          if($singlepane_view == 'true')
 667              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 668          else
 669              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 670  
 671          $button = '';
 672  
 673          if($actions && getFieldVisibilityPermission($related_module, $current_user->id, 'account_id','readwrite') == '0') {
 674              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 675              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 676                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 677              }
 678              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 679                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 680                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 681                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 682              }
 683          }
 684  
 685          $entityIds = $this->getRelatedContactsIds();
 686          $entityIds = implode(',', $entityIds);
 687  
 688          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 689  
 690          $query = "SELECT vtiger_crmentity.*, vtiger_salesorder.*, vtiger_quotes.subject AS quotename, vtiger_account.accountname,
 691                  case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
 692                  FROM vtiger_salesorder
 693                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid
 694                  LEFT OUTER JOIN vtiger_quotes ON vtiger_quotes.quoteid = vtiger_salesorder.quoteid
 695                  LEFT OUTER JOIN vtiger_account ON vtiger_account.accountid = vtiger_salesorder.accountid
 696                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 697                  LEFT JOIN vtiger_invoice_recurring_info ON vtiger_invoice_recurring_info.start_period = vtiger_salesorder.salesorderid
 698                  LEFT JOIN vtiger_salesordercf ON vtiger_salesordercf.salesorderid = vtiger_salesorder.salesorderid
 699                  LEFT JOIN vtiger_sobillads ON vtiger_sobillads.sobilladdressid = vtiger_salesorder.salesorderid
 700                  LEFT JOIN vtiger_soshipads ON vtiger_soshipads.soshipaddressid = vtiger_salesorder.salesorderid
 701                  LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
 702                  WHERE vtiger_crmentity.deleted = 0 AND (vtiger_salesorder.accountid = $id";
 703  
 704          if(!empty ($entityIds)){
 705              $query .= " OR vtiger_salesorder.contactid IN (".$entityIds."))";
 706          } else {
 707              $query .= ")";
 708          }
 709  
 710          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 711  
 712          if($return_value == null) $return_value = Array();
 713          $return_value['CUSTOM_BUTTON'] = $button;
 714  
 715          $log->debug("Exiting get_salesorder method ...");
 716          return $return_value;
 717      }
 718      /**
 719      * Function to get Account related Tickets
 720      * @param  integer   $id      - accountid
 721      * returns related Ticket record in array format
 722      */
 723  	function get_tickets($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 724          global $log, $singlepane_view,$currentModule,$current_user;
 725          $log->debug("Entering get_tickets(".$id.") method ...");
 726          $this_module = $currentModule;
 727  
 728          $related_module = vtlib_getModuleNameById($rel_tab_id);
 729          require_once("modules/$related_module/$related_module.php");
 730          $other = new $related_module();
 731          vtlib_setup_modulevars($related_module, $other);
 732          $singular_modname = vtlib_toSingular($related_module);
 733  
 734          $parenttab = getParentTab();
 735  
 736          if($singlepane_view == 'true')
 737              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 738          else
 739              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 740  
 741          $button = '';
 742  
 743          if($actions && getFieldVisibilityPermission($related_module, $current_user->id, 'parent_id','readwrite') == '0') {
 744              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 745              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 746                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 747              }
 748              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 749                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 750                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 751                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 752              }
 753          }
 754  
 755          $entityIds = $this->getRelatedContactsIds($id);
 756          $entityIds = implode(',', $entityIds);
 757  
 758          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 759  
 760          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name, vtiger_users.id,
 761                  vtiger_troubletickets.title, vtiger_troubletickets.ticketid AS crmid, vtiger_troubletickets.status, vtiger_troubletickets.priority,
 762                  vtiger_troubletickets.parent_id, vtiger_troubletickets.contact_id, vtiger_troubletickets.ticket_no, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime
 763                  FROM vtiger_troubletickets
 764                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid
 765                  LEFT JOIN vtiger_ticketcf ON vtiger_troubletickets.ticketid = vtiger_ticketcf.ticketid
 766                  LEFT JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid
 767                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 768                  WHERE  vtiger_crmentity.deleted = 0 and (vtiger_troubletickets.parent_id = $id";
 769  
 770          if(!empty ($entityIds)){
 771              $query .= " OR vtiger_troubletickets.contact_id IN (".$entityIds."))";
 772          } else {
 773              $query .= ")";
 774          }
 775          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 776  
 777          if($return_value == null) $return_value = Array();
 778          $return_value['CUSTOM_BUTTON'] = $button;
 779  
 780          $log->debug("Exiting get_tickets method ...");
 781          return $return_value;
 782      }
 783      /**
 784      * Function to get Account related Products
 785      * @param  integer   $id      - accountid
 786      * returns related Products record in array format
 787      */
 788  	function get_products($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 789          global $log, $singlepane_view,$currentModule,$current_user;
 790          $log->debug("Entering get_products(".$id.") method ...");
 791          $this_module = $currentModule;
 792  
 793          $related_module = vtlib_getModuleNameById($rel_tab_id);
 794          require_once("modules/$related_module/$related_module.php");
 795          $other = new $related_module();
 796          vtlib_setup_modulevars($related_module, $other);
 797          $singular_modname = vtlib_toSingular($related_module);
 798  
 799          $parenttab = getParentTab();
 800  
 801          if($singlepane_view == 'true')
 802              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 803          else
 804              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 805  
 806          $button = '';
 807  
 808          if($actions) {
 809              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 810              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 811                  $button .= "<input title='".getTranslatedString('LBL_SELECT')." ". getTranslatedString($related_module). "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 812              }
 813              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 814                  $button .= "<input title='".getTranslatedString('LBL_ADD_NEW'). " ". getTranslatedString($singular_modname) ."' class='crmbutton small create'" .
 815                      " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
 816                      " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString($singular_modname) ."'>&nbsp;";
 817              }
 818          }
 819  
 820          $entityIds = $this->getRelatedContactsIds();
 821          array_push($entityIds, $id);
 822          $entityIds = implode(',', $entityIds);
 823  
 824          $query = "SELECT vtiger_products.productid, vtiger_products.productname, vtiger_products.productcode, vtiger_products.commissionrate,
 825                  vtiger_products.qty_per_unit, vtiger_products.unit_price, vtiger_crmentity.crmid, vtiger_crmentity.smownerid
 826                  FROM vtiger_products
 827                  INNER JOIN vtiger_seproductsrel ON vtiger_products.productid = vtiger_seproductsrel.productid
 828                  and vtiger_seproductsrel.setype IN ('Accounts', 'Contacts')
 829                  INNER JOIN vtiger_productcf ON vtiger_products.productid = vtiger_productcf.productid
 830                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid
 831                  LEFT JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid
 832                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 833                  WHERE vtiger_crmentity.deleted = 0 AND vtiger_seproductsrel.crmid IN (".$entityIds.")";
 834  
 835          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 836  
 837          if($return_value == null) $return_value = Array();
 838          $return_value['CUSTOM_BUTTON'] = $button;
 839  
 840          $log->debug("Exiting get_products method ...");
 841          return $return_value;
 842      }
 843  
 844      /** Function to export the account records in CSV Format
 845      * @param reference variable - where condition is passed when the query is executed
 846      * Returns Export Accounts Query.
 847      */
 848  	function create_export_query($where)
 849      {
 850          global $log;
 851          global $current_user;
 852                  $log->debug("Entering create_export_query(".$where.") method ...");
 853  
 854          include ("include/utils/ExportUtils.php");
 855  
 856          //To get the Permitted fields query and the permitted fields list
 857          $sql = getPermittedFieldsQuery("Accounts", "detail_view");
 858          $fields_list = getFieldsListFromQuery($sql);
 859  
 860          $query = "SELECT $fields_list,case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name
 861                         FROM ".$this->entity_table."
 862                  INNER JOIN vtiger_account
 863                      ON vtiger_account.accountid = vtiger_crmentity.crmid
 864                  LEFT JOIN vtiger_accountbillads
 865                      ON vtiger_accountbillads.accountaddressid = vtiger_account.accountid
 866                  LEFT JOIN vtiger_accountshipads
 867                      ON vtiger_accountshipads.accountaddressid = vtiger_account.accountid
 868                  LEFT JOIN vtiger_accountscf
 869                      ON vtiger_accountscf.accountid = vtiger_account.accountid
 870                              LEFT JOIN vtiger_groups
 871                                      ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 872                  LEFT JOIN vtiger_users
 873                      ON vtiger_users.id = vtiger_crmentity.smownerid and vtiger_users.status = 'Active'
 874                  LEFT JOIN vtiger_account vtiger_account2
 875                      ON vtiger_account2.accountid = vtiger_account.parentid
 876                  ";//vtiger_account2 is added to get the Member of account
 877  
 878          $query .= $this->getNonAdminAccessControlQuery('Accounts',$current_user);
 879          $where_auto = " vtiger_crmentity.deleted = 0 ";
 880  
 881          if($where != "")
 882              $query .= " WHERE ($where) AND ".$where_auto;
 883          else
 884              $query .= " WHERE ".$where_auto;
 885  
 886          $log->debug("Exiting create_export_query method ...");
 887          return $query;
 888      }
 889  
 890      /** Function to get the Columnnames of the Account Record
 891      * Used By vtigerCRM Word Plugin
 892      * Returns the Merge Fields for Word Plugin
 893      */
 894  	function getColumnNames_Acnt()
 895      {
 896          global $log,$current_user;
 897          $log->debug("Entering getColumnNames_Acnt() method ...");
 898          require('user_privileges/user_privileges_'.$current_user->id.'.php');
 899          if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0)
 900          {
 901              $sql1 = "SELECT fieldlabel FROM vtiger_field WHERE tabid = 6 and vtiger_field.presence in (0,2)";
 902              $params1 = array();
 903          }else
 904          {
 905              $profileList = getCurrentUserProfileList();
 906              $sql1 = "select vtiger_field.fieldid,fieldlabel from vtiger_field INNER JOIN vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid=6 and vtiger_field.displaytype in (1,2,4) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)";
 907              $params1 = array();
 908              if (count($profileList) > 0) {
 909                  $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")  group by fieldid";
 910                  array_push($params1,  $profileList);
 911              }
 912          }
 913          $result = $this->db->pquery($sql1, $params1);
 914          $numRows = $this->db->num_rows($result);
 915          for($i=0; $i < $numRows;$i++)
 916          {
 917              $custom_fields[$i] = $this->db->query_result($result,$i,"fieldlabel");
 918              $custom_fields[$i] = preg_replace("/\s+/","",$custom_fields[$i]);
 919              $custom_fields[$i] = strtoupper($custom_fields[$i]);
 920          }
 921          $mergeflds = $custom_fields;
 922          $log->debug("Exiting getColumnNames_Acnt method ...");
 923          return $mergeflds;
 924      }
 925  
 926      /**
 927       * Move the related records of the specified list of id's to the given record.
 928       * @param String This module name
 929       * @param Array List of Entity Id's from which related records need to be transfered
 930       * @param Integer Id of the the Record to which the related records are to be moved
 931       */
 932  	function transferRelatedRecords($module, $transferEntityIds, $entityId) {
 933          global $adb,$log;
 934          $log->debug("Entering function transferRelatedRecords ($module, $transferEntityIds, $entityId)");
 935  
 936          $rel_table_arr = Array("Contacts"=>"vtiger_contactdetails","Potentials"=>"vtiger_potential","Quotes"=>"vtiger_quotes",
 937                      "SalesOrder"=>"vtiger_salesorder","Invoice"=>"vtiger_invoice","Activities"=>"vtiger_seactivityrel",
 938                      "Documents"=>"vtiger_senotesrel","Attachments"=>"vtiger_seattachmentsrel","HelpDesk"=>"vtiger_troubletickets",
 939                      "Products"=>"vtiger_seproductsrel","ServiceContracts"=>"vtiger_servicecontracts","Campaigns"=>"vtiger_campaignaccountrel",
 940                      "Assets"=>"vtiger_assets","Project"=>"vtiger_project");
 941  
 942          $tbl_field_arr = Array("vtiger_contactdetails"=>"contactid","vtiger_potential"=>"potentialid","vtiger_quotes"=>"quoteid",
 943                      "vtiger_salesorder"=>"salesorderid","vtiger_invoice"=>"invoiceid","vtiger_seactivityrel"=>"activityid",
 944                      "vtiger_senotesrel"=>"notesid","vtiger_seattachmentsrel"=>"attachmentsid","vtiger_troubletickets"=>"ticketid",
 945                      "vtiger_seproductsrel"=>"productid","vtiger_servicecontracts"=>"servicecontractsid","vtiger_campaignaccountrel"=>"campaignid",
 946                      "vtiger_assets"=>"assetsid","vtiger_project"=>"projectid","vtiger_payments"=>"paymentsid");
 947  
 948          $entity_tbl_field_arr = Array("vtiger_contactdetails"=>"accountid","vtiger_potential"=>"related_to","vtiger_quotes"=>"accountid",
 949                      "vtiger_salesorder"=>"accountid","vtiger_invoice"=>"accountid","vtiger_seactivityrel"=>"crmid",
 950                      "vtiger_senotesrel"=>"crmid","vtiger_seattachmentsrel"=>"crmid","vtiger_troubletickets"=>"parent_id",
 951                      "vtiger_seproductsrel"=>"crmid","vtiger_servicecontracts"=>"sc_related_to","vtiger_campaignaccountrel"=>"accountid",
 952                      "vtiger_assets"=>"account","vtiger_project"=>"linktoaccountscontacts","vtiger_payments"=>"relatedorganization");
 953  
 954          foreach($transferEntityIds as $transferId) {
 955              foreach($rel_table_arr as $rel_module=>$rel_table) {
 956                  $id_field = $tbl_field_arr[$rel_table];
 957                  $entity_id_field = $entity_tbl_field_arr[$rel_table];
 958                  // IN clause to avoid duplicate entries
 959                  $sel_result =  $adb->pquery("select $id_field from $rel_table where $entity_id_field=? " .
 960                          " and $id_field not in (select $id_field from $rel_table where $entity_id_field=?)",
 961                          array($transferId,$entityId));
 962                  $res_cnt = $adb->num_rows($sel_result);
 963                  if($res_cnt > 0) {
 964                      for($i=0;$i<$res_cnt;$i++) {
 965                          $id_field_value = $adb->query_result($sel_result,$i,$id_field);
 966                          $adb->pquery("update $rel_table set $entity_id_field=? where $entity_id_field=? and $id_field=?",
 967                              array($entityId,$transferId,$id_field_value));
 968                      }
 969                  }
 970              }
 971          }
 972          parent::transferRelatedRecords($module, $transferEntityIds, $entityId);
 973          $log->debug("Exiting transferRelatedRecords...");
 974      }
 975  
 976      /*
 977       * Function to get the relation tables for related modules
 978       * @param - $secmodule secondary module name
 979       * returns the array with table names and fieldnames storing relations between module and this module
 980       */
 981  	function setRelationTables($secmodule){
 982          $rel_tables =  array (
 983              "Contacts" => array("vtiger_contactdetails"=>array("accountid","contactid"),"vtiger_account"=>"accountid"),
 984              "Potentials" => array("vtiger_potential"=>array("related_to","potentialid"),"vtiger_account"=>"accountid"),
 985              "Quotes" => array("vtiger_quotes"=>array("accountid","quoteid"),"vtiger_account"=>"accountid"),
 986              "SalesOrder" => array("vtiger_salesorder"=>array("accountid","salesorderid"),"vtiger_account"=>"accountid"),
 987              "Invoice" => array("vtiger_invoice"=>array("accountid","invoiceid"),"vtiger_account"=>"accountid"),
 988              "Calendar" => array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_account"=>"accountid"),
 989              "HelpDesk" => array("vtiger_troubletickets"=>array("parent_id","ticketid"),"vtiger_account"=>"accountid"),
 990              "Products" => array("vtiger_seproductsrel"=>array("crmid","productid"),"vtiger_account"=>"accountid"),
 991              "Documents" => array("vtiger_senotesrel"=>array("crmid","notesid"),"vtiger_account"=>"accountid"),
 992              "Campaigns" => array("vtiger_campaignaccountrel"=>array("accountid","campaignid"),"vtiger_account"=>"accountid"),
 993              "Emails" => array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_account"=>"accountid"),
 994          );
 995          return $rel_tables[$secmodule];
 996      }
 997  
 998      /*
 999       * Function to get the secondary query part of a report
1000       * @param - $module primary module name
1001       * @param - $secmodule secondary module name
1002       * returns the query string formed on fetching the related data for report for secondary module
1003       */
1004  	function generateReportsSecQuery($module,$secmodule,$queryPlanner){
1005  
1006          $matrix = $queryPlanner->newDependencyMatrix();
1007          $matrix->setDependency('vtiger_crmentityAccounts', array('vtiger_groupsAccounts', 'vtiger_usersAccounts', 'vtiger_lastModifiedByAccounts'));
1008          $matrix->setDependency('vtiger_account', array('vtiger_crmentityAccounts',' vtiger_accountbillads', 'vtiger_accountshipads', 'vtiger_accountscf', 'vtiger_accountAccounts', 'vtiger_email_trackAccounts'));
1009  
1010          if (!$queryPlanner->requireTable('vtiger_account', $matrix)) {
1011              return '';
1012          }
1013  
1014           // Activities related to contact should linked to accounts if contact is related to that account
1015          if($module == "Calendar"){
1016              // query to get all the contacts related to Accounts
1017              $relContactsQuery = "SELECT contactid FROM vtiger_contactdetails as vtiger_tmpContactCalendar
1018                          INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_tmpContactCalendar.contactid
1019                          WHERE vtiger_tmpContactCalendar.accountid IS NOT NULL AND vtiger_tmpContactCalendar.accountid !=''
1020                          AND vtiger_crmentity.deleted=0";
1021  
1022              $query = " left join vtiger_cntactivityrel as vtiger_tmpcntactivityrel ON
1023                  vtiger_activity.activityid = vtiger_tmpcntactivityrel.activityid AND
1024                  vtiger_tmpcntactivityrel.contactid IN ($relContactsQuery)
1025                  left join vtiger_contactdetails as vtiger_tmpcontactdetails on vtiger_tmpcntactivityrel.contactid = vtiger_tmpcontactdetails.contactid ";
1026          }else {
1027              $query = "";
1028          }
1029  
1030          $query .= $this->getRelationQuery($module,$secmodule,"vtiger_account","accountid", $queryPlanner);
1031  
1032          if($module == "Calendar"){
1033              $query .= " OR vtiger_account.accountid = vtiger_tmpcontactdetails.accountid " ;
1034          }
1035          // End
1036  
1037          if ($queryPlanner->requireTable('vtiger_crmentityAccounts', $matrix)) {
1038              $query .= " left join vtiger_crmentity as vtiger_crmentityAccounts on vtiger_crmentityAccounts.crmid=vtiger_account.accountid and vtiger_crmentityAccounts.deleted=0";
1039          }
1040          if ($queryPlanner->requireTable('vtiger_accountbillads')) {
1041              $query .= " left join vtiger_accountbillads on vtiger_account.accountid=vtiger_accountbillads.accountaddressid";
1042          }
1043          if ($queryPlanner->requireTable('vtiger_accountshipads')) {
1044              $query .= " left join vtiger_accountshipads on vtiger_account.accountid=vtiger_accountshipads.accountaddressid";
1045          }
1046          if ($queryPlanner->requireTable('vtiger_accountscf')) {
1047              $query .= " left join vtiger_accountscf on vtiger_account.accountid = vtiger_accountscf.accountid";
1048          }
1049          if ($queryPlanner->requireTable('vtiger_accountAccounts', $matrix)) {
1050              $query .= "    left join vtiger_account as vtiger_accountAccounts on vtiger_accountAccounts.accountid = vtiger_account.parentid";
1051          }
1052          if ($queryPlanner->requireTable('vtiger_email_track')) {
1053              $query .= " LEFT JOIN vtiger_email_track AS vtiger_email_trackAccounts ON vtiger_email_trackAccounts .crmid = vtiger_account.accountid";
1054          }
1055          if ($queryPlanner->requireTable('vtiger_groupsAccounts')) {
1056              $query .= "    left join vtiger_groups as vtiger_groupsAccounts on vtiger_groupsAccounts.groupid = vtiger_crmentityAccounts.smownerid";
1057          }
1058          if ($queryPlanner->requireTable('vtiger_usersAccounts')) {
1059              $query .= " left join vtiger_users as vtiger_usersAccounts on vtiger_usersAccounts.id = vtiger_crmentityAccounts.smownerid";
1060          }
1061          if ($queryPlanner->requireTable('vtiger_lastModifiedByAccounts')) {
1062              $query .= " left join vtiger_users as vtiger_lastModifiedByAccounts on vtiger_lastModifiedByAccounts.id = vtiger_crmentityAccounts.modifiedby ";
1063          }
1064          if ($queryPlanner->requireTable("vtiger_createdbyAccounts")){
1065              $query .= " left join vtiger_users as vtiger_createdbyAccounts on vtiger_createdbyAccounts.id = vtiger_crmentityAccounts.smcreatorid ";
1066          }
1067  
1068          return $query;
1069      }
1070  
1071      /**
1072      * Function to get Account hierarchy of the given Account
1073      * @param  integer   $id      - accountid
1074      * returns Account hierarchy in array format
1075      */
1076  	function getAccountHierarchy($id) {
1077          global $log, $adb, $current_user;
1078          $log->debug("Entering getAccountHierarchy(".$id.") method ...");
1079          require('user_privileges/user_privileges_'.$current_user->id.'.php');
1080  
1081          $tabname = getParentTab();
1082          $listview_header = Array();
1083          $listview_entries = array();
1084  
1085          foreach ($this->list_fields_name as $fieldname=>$colname) {
1086              if(getFieldVisibilityPermission('Accounts', $current_user->id, $colname) == '0') {
1087                  $listview_header[] = getTranslatedString($fieldname);
1088              }
1089          }
1090  
1091          $accounts_list = Array();
1092  
1093          // Get the accounts hierarchy from the top most account in the hierarch of the current account, including the current account
1094          $encountered_accounts = array($id);
1095          $accounts_list = $this->__getParentAccounts($id, $accounts_list, $encountered_accounts);
1096  
1097          // Get the accounts hierarchy (list of child accounts) based on the current account
1098          $accounts_list = $this->__getChildAccounts($id, $accounts_list, $accounts_list[$id]['depth']);
1099  
1100          // Create array of all the accounts in the hierarchy
1101          foreach($accounts_list as $account_id => $account_info) {
1102              $account_info_data = array();
1103  
1104              $hasRecordViewAccess = (is_admin($current_user)) || (isPermitted('Accounts', 'DetailView', $account_id) == 'yes');
1105  
1106              foreach ($this->list_fields_name as $fieldname=>$colname) {
1107                  // Permission to view account is restricted, avoid showing field values (except account name)
1108                  if(!$hasRecordViewAccess && $colname != 'accountname') {
1109                      $account_info_data[] = '';
1110                  } else if(getFieldVisibilityPermission('Accounts', $current_user->id, $colname) == '0') {
1111                      $data = $account_info[$colname];
1112                      if ($colname == 'accountname') {
1113                          if ($account_id != $id) {
1114                              if($hasRecordViewAccess) {
1115                                  $data = '<a href="index.php?module=Accounts&action=DetailView&record='.$account_id.'&parenttab='.$tabname.'">'.$data.'</a>';
1116                              } else {
1117                                  $data = '<i>'.$data.'</i>';
1118                              }
1119                          } else {
1120                              $data = '<b>'.$data.'</b>';
1121                          }
1122                          // - to show the hierarchy of the Accounts
1123                          $account_depth = str_repeat(" .. ", $account_info['depth'] * 2);
1124                          $data = $account_depth . $data;
1125                      } else if ($colname == 'website') {
1126                          $data = '<a href="http://'. $data .'" target="_blank">'.$data.'</a>';
1127                      }
1128                      $account_info_data[] = $data;
1129                  }
1130              }
1131              $listview_entries[$account_id] = $account_info_data;
1132          }
1133  
1134          $account_hierarchy = array('header'=>$listview_header,'entries'=>$listview_entries);
1135          $log->debug("Exiting getAccountHierarchy method ...");
1136          return $account_hierarchy;
1137      }
1138  
1139      /**
1140      * Function to Recursively get all the upper accounts of a given Account
1141      * @param  integer   $id              - accountid
1142      * @param  array   $parent_accounts   - Array of all the parent accounts
1143      * returns All the parent accounts of the given accountid in array format
1144      */
1145  	function __getParentAccounts($id, &$parent_accounts, &$encountered_accounts) {
1146          global $log, $adb;
1147          $log->debug("Entering __getParentAccounts(".$id.",".$parent_accounts.") method ...");
1148  
1149          $query = "SELECT parentid FROM vtiger_account " .
1150                  " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid" .
1151                  " WHERE vtiger_crmentity.deleted = 0 and vtiger_account.accountid = ?";
1152          $params = array($id);
1153  
1154          $res = $adb->pquery($query, $params);
1155  
1156          if ($adb->num_rows($res) > 0 &&
1157              $adb->query_result($res, 0, 'parentid') != '' && $adb->query_result($res, 0, 'parentid') != 0 &&
1158              !in_array($adb->query_result($res, 0, 'parentid'),$encountered_accounts)) {
1159  
1160              $parentid = $adb->query_result($res, 0, 'parentid');
1161              $encountered_accounts[] = $parentid;
1162              $this->__getParentAccounts($parentid,$parent_accounts,$encountered_accounts);
1163          }
1164  
1165          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
1166                              'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
1167          $query = "SELECT vtiger_account.*, vtiger_accountbillads.*," .
1168                  " CASE when (vtiger_users.user_name not like '') THEN $userNameSql ELSE vtiger_groups.groupname END as user_name " .
1169                  " FROM vtiger_account" .
1170                  " INNER JOIN vtiger_crmentity " .
1171                  " ON vtiger_crmentity.crmid = vtiger_account.accountid" .
1172                  " INNER JOIN vtiger_accountbillads" .
1173                  " ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid " .
1174                  " LEFT JOIN vtiger_groups" .
1175                  " ON vtiger_groups.groupid = vtiger_crmentity.smownerid" .
1176                  " LEFT JOIN vtiger_users" .
1177                  " ON vtiger_users.id = vtiger_crmentity.smownerid" .
1178                  " WHERE vtiger_crmentity.deleted = 0 and vtiger_account.accountid = ?";
1179          $params = array($id);
1180          $res = $adb->pquery($query, $params);
1181  
1182          $parent_account_info = array();
1183          $depth = 0;
1184          $immediate_parentid = $adb->query_result($res, 0, 'parentid');
1185          if (isset($parent_accounts[$immediate_parentid])) {
1186              $depth = $parent_accounts[$immediate_parentid]['depth'] + 1;
1187          }
1188          $parent_account_info['depth'] = $depth;
1189          foreach($this->list_fields_name as $fieldname=>$columnname) {
1190              if ($columnname == 'assigned_user_id') {
1191                  $parent_account_info[$columnname] = $adb->query_result($res, 0, 'user_name');
1192              } else {
1193                  $parent_account_info[$columnname] = $adb->query_result($res, 0, $columnname);
1194              }
1195          }
1196          $parent_accounts[$id] = $parent_account_info;
1197          $log->debug("Exiting __getParentAccounts method ...");
1198          return $parent_accounts;
1199      }
1200  
1201      /**
1202      * Function to Recursively get all the child accounts of a given Account
1203      * @param  integer   $id              - accountid
1204      * @param  array   $child_accounts   - Array of all the child accounts
1205      * @param  integer   $depth          - Depth at which the particular account has to be placed in the hierarchy
1206      * returns All the child accounts of the given accountid in array format
1207      */
1208  	function __getChildAccounts($id, &$child_accounts, $depth) {
1209          global $log, $adb;
1210          $log->debug("Entering __getChildAccounts(".$id.",".$child_accounts.",".$depth.") method ...");
1211  
1212          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
1213                              'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
1214          $query = "SELECT vtiger_account.*, vtiger_accountbillads.*," .
1215                  " CASE when (vtiger_users.user_name not like '') THEN $userNameSql ELSE vtiger_groups.groupname END as user_name " .
1216                  " FROM vtiger_account" .
1217                  " INNER JOIN vtiger_crmentity " .
1218                  " ON vtiger_crmentity.crmid = vtiger_account.accountid" .
1219                  " INNER JOIN vtiger_accountbillads" .
1220                  " ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid " .
1221                  " LEFT JOIN vtiger_groups" .
1222                  " ON vtiger_groups.groupid = vtiger_crmentity.smownerid" .
1223                  " LEFT JOIN vtiger_users" .
1224                  " ON vtiger_users.id = vtiger_crmentity.smownerid" .
1225                  " WHERE vtiger_crmentity.deleted = 0 and parentid = ?";
1226          $params = array($id);
1227          $res = $adb->pquery($query, $params);
1228  
1229          $num_rows = $adb->num_rows($res);
1230  
1231          if ($num_rows > 0) {
1232              $depth = $depth + 1;
1233              for($i=0;$i<$num_rows;$i++) {
1234                  $child_acc_id = $adb->query_result($res, $i, 'accountid');
1235                  if(array_key_exists($child_acc_id,$child_accounts)) {
1236                      continue;
1237                  }
1238                  $child_account_info = array();
1239                  $child_account_info['depth'] = $depth;
1240                  foreach($this->list_fields_name as $fieldname=>$columnname) {
1241                      if ($columnname == 'assigned_user_id') {
1242                          $child_account_info[$columnname] = $adb->query_result($res, $i, 'user_name');
1243                      } else {
1244                          $child_account_info[$columnname] = $adb->query_result($res, $i, $columnname);
1245                      }
1246                  }
1247                  $child_accounts[$child_acc_id] = $child_account_info;
1248                  $this->__getChildAccounts($child_acc_id, $child_accounts, $depth);
1249              }
1250          }
1251          $log->debug("Exiting __getChildAccounts method ...");
1252          return $child_accounts;
1253      }
1254  
1255      // Function to unlink the dependent records of the given record by id
1256  	function unlinkDependencies($module, $id) {
1257          global $log;
1258  
1259          //Deleting Account related Potentials.
1260          $pot_q = 'SELECT vtiger_crmentity.crmid FROM vtiger_crmentity
1261              INNER JOIN vtiger_potential ON vtiger_crmentity.crmid=vtiger_potential.potentialid
1262              LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_potential.related_to
1263              WHERE vtiger_crmentity.deleted=0 AND vtiger_potential.related_to=?';
1264          $pot_res = $this->db->pquery($pot_q, array($id));
1265          $pot_ids_list = array();
1266          for($k=0;$k < $this->db->num_rows($pot_res);$k++)
1267          {
1268              $pot_id = $this->db->query_result($pot_res,$k,"crmid");
1269              $pot_ids_list[] = $pot_id;
1270              $sql = 'UPDATE vtiger_crmentity SET deleted = 1 WHERE crmid = ?';
1271              $this->db->pquery($sql, array($pot_id));
1272          }
1273          //Backup deleted Account related Potentials.
1274          $params = array($id, RB_RECORD_UPDATED, 'vtiger_crmentity', 'deleted', 'crmid', implode(",", $pot_ids_list));
1275          $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES(?,?,?,?,?,?)', $params);
1276  
1277          //Deleting Account related Quotes.
1278          $quo_q = 'SELECT vtiger_crmentity.crmid FROM vtiger_crmentity
1279              INNER JOIN vtiger_quotes ON vtiger_crmentity.crmid=vtiger_quotes.quoteid
1280              INNER JOIN vtiger_account ON vtiger_account.accountid=vtiger_quotes.accountid
1281              WHERE vtiger_crmentity.deleted=0 AND vtiger_quotes.accountid=?';
1282          $quo_res = $this->db->pquery($quo_q, array($id));
1283          $quo_ids_list = array();
1284          for($k=0;$k < $this->db->num_rows($quo_res);$k++)
1285          {
1286              $quo_id = $this->db->query_result($quo_res,$k,"crmid");
1287              $quo_ids_list[] = $quo_id;
1288              $sql = 'UPDATE vtiger_crmentity SET deleted = 1 WHERE crmid = ?';
1289              $this->db->pquery($sql, array($quo_id));
1290          }
1291          //Backup deleted Account related Quotes.
1292          $params = array($id, RB_RECORD_UPDATED, 'vtiger_crmentity', 'deleted', 'crmid', implode(",", $quo_ids_list));
1293          $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES(?,?,?,?,?,?)', $params);
1294  
1295          //Backup Contact-Account Relation
1296          $con_q = 'SELECT contactid FROM vtiger_contactdetails WHERE accountid = ?';
1297          $con_res = $this->db->pquery($con_q, array($id));
1298          if ($this->db->num_rows($con_res) > 0) {
1299              $con_ids_list = array();
1300              for($k=0;$k < $this->db->num_rows($con_res);$k++)
1301              {
1302                  $con_ids_list[] = $this->db->query_result($con_res,$k,"contactid");
1303              }
1304              $params = array($id, RB_RECORD_UPDATED, 'vtiger_contactdetails', 'accountid', 'contactid', implode(",", $con_ids_list));
1305              $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES(?,?,?,?,?,?)', $params);
1306          }
1307          //Deleting Contact-Account Relation.
1308          $con_q = 'UPDATE vtiger_contactdetails SET accountid = 0 WHERE accountid = ?';
1309          $this->db->pquery($con_q, array($id));
1310  
1311          //Backup Trouble Tickets-Account Relation
1312          $tkt_q = 'SELECT ticketid FROM vtiger_troubletickets WHERE parent_id = ?';
1313          $tkt_res = $this->db->pquery($tkt_q, array($id));
1314          if ($this->db->num_rows($tkt_res) > 0) {
1315              $tkt_ids_list = array();
1316              for($k=0;$k < $this->db->num_rows($tkt_res);$k++)
1317              {
1318                  $tkt_ids_list[] = $this->db->query_result($tkt_res,$k,"ticketid");
1319              }
1320              $params = array($id, RB_RECORD_UPDATED, 'vtiger_troubletickets', 'parent_id', 'ticketid', implode(",", $tkt_ids_list));
1321              $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES(?,?,?,?,?,?)', $params);
1322          }
1323          //Deleting Trouble Tickets-Account Relation.
1324          $tt_q = 'UPDATE vtiger_troubletickets SET parent_id = 0 WHERE parent_id = ?';
1325          $this->db->pquery($tt_q, array($id));
1326  
1327          parent::unlinkDependencies($module, $id);
1328      }
1329  
1330      // Function to unlink an entity with given Id from another entity
1331  	function unlinkRelationship($id, $return_module, $return_id) {
1332          global $log;
1333          if(empty($return_module) || empty($return_id)) return;
1334  
1335          if($return_module == 'Campaigns') {
1336              $sql = 'DELETE FROM vtiger_campaignaccountrel WHERE accountid=? AND campaignid=?';
1337              $this->db->pquery($sql, array($id, $return_id));
1338          } else if($return_module == 'Products') {
1339              $sql = 'DELETE FROM vtiger_seproductsrel WHERE crmid=? AND productid=?';
1340              $this->db->pquery($sql, array($id, $return_id));
1341          } else {
1342              $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
1343              $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
1344              $this->db->pquery($sql, $params);
1345          }
1346      }
1347  
1348  	function save_related_module($module, $crmid, $with_module, $with_crmids) {
1349          $adb = $this->db;
1350  
1351          if(!is_array($with_crmids)) $with_crmids = Array($with_crmids);
1352          foreach($with_crmids as $with_crmid) {
1353              if($with_module == 'Products')
1354                  $adb->pquery("insert into vtiger_seproductsrel values(?,?,?)", array($crmid, $with_crmid, $module));
1355              elseif($with_module == 'Campaigns') {
1356                  $checkResult = $adb->pquery('SELECT 1 FROM vtiger_campaignaccountrel WHERE campaignid = ? AND accountid = ?',
1357                                                  array($with_crmid, $crmid));
1358                  if($checkResult && $adb->num_rows($checkResult) > 0) {
1359                      continue;
1360                  }
1361                  $adb->pquery("insert into vtiger_campaignaccountrel values(?,?,1)", array($with_crmid, $crmid));
1362              } else {
1363                  parent::save_related_module($module, $crmid, $with_module, $with_crmid);
1364              }
1365          }
1366      }
1367  
1368  	function getListButtons($app_strings,$mod_strings = false) {
1369          $list_buttons = Array();
1370  
1371          if(isPermitted('Accounts','Delete','') == 'yes') {
1372              $list_buttons['del'] = $app_strings[LBL_MASS_DELETE];
1373          }
1374          if(isPermitted('Accounts','EditView','') == 'yes') {
1375              $list_buttons['mass_edit'] = $app_strings[LBL_MASS_EDIT];
1376              $list_buttons['c_owner'] = $app_strings[LBL_CHANGE_OWNER];
1377          }
1378          if(isPermitted('Emails','EditView','') == 'yes') {
1379              $list_buttons['s_mail'] = $app_strings[LBL_SEND_MAIL_BUTTON];
1380          }
1381          // mailer export
1382          if(isPermitted('Accounts','Export','') == 'yes') {
1383              $list_buttons['mailer_exp'] = $mod_strings[LBL_MAILER_EXPORT];
1384          }
1385          // end of mailer export
1386          return $list_buttons;
1387      }
1388  
1389      /* Function to get attachments in the related list of accounts module */
1390  	function get_attachments($id, $cur_tab_id, $rel_tab_id, $actions = false) {
1391  
1392          global $currentModule, $app_strings, $singlepane_view;
1393          $this_module = $currentModule;
1394          $parenttab = getParentTab();
1395  
1396          $related_module = vtlib_getModuleNameById($rel_tab_id);
1397          $other = CRMEntity::getInstance($related_module);
1398  
1399          // Some standard module class doesn't have required variables
1400          // that are used in the query, they are defined in this generic API
1401          vtlib_setup_modulevars($related_module, $other);
1402  
1403          $singular_modname = vtlib_toSingular($related_module);
1404          $button = '';
1405          if ($actions) {
1406              if (is_string($actions))
1407                  $actions = explode(',', strtoupper($actions));
1408              if (in_array('SELECT', $actions) && isPermitted($related_module, 4, '') == 'yes') {
1409                  $button .= "<input title='" . getTranslatedString('LBL_SELECT') . " " . getTranslatedString($related_module) . "' class='crmbutton small edit' type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\" value='" . getTranslatedString('LBL_SELECT') . " " . getTranslatedString($related_module) . "'>&nbsp;";
1410              }
1411              if (in_array('ADD', $actions) && isPermitted($related_module, 1, '') == 'yes') {
1412                  $button .= "<input type='hidden' name='createmode' id='createmode' value='link' />" .
1413                          "<input title='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname) . "' class='crmbutton small create'" .
1414                          " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
1415                          " value='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname) . "'>&nbsp;";
1416              }
1417          }
1418  
1419          // To make the edit or del link actions to return back to same view.
1420          if ($singlepane_view == 'true'){
1421              $returnset = "&return_module=$this_module&return_action=DetailView&return_id=$id";
1422          } else {
1423              $returnset = "&return_module=$this_module&return_action=CallRelatedList&return_id=$id";
1424          }
1425  
1426          $entityIds = $this->getRelatedContactsIds();
1427          array_push($entityIds, $id);
1428          $entityIds = implode(',', $entityIds);
1429  
1430          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=> 'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
1431  
1432          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
1433                  'Documents' ActivityType,vtiger_attachments.type  FileType,crm2.modifiedtime lastmodified,vtiger_crmentity.modifiedtime,
1434                  vtiger_seattachmentsrel.attachmentsid attachmentsid, vtiger_notes.notesid crmid, vtiger_notes.notecontent description,vtiger_notes.*
1435                  from vtiger_notes
1436                  INNER JOIN vtiger_senotesrel ON vtiger_senotesrel.notesid= vtiger_notes.notesid
1437                  LEFT JOIN vtiger_notescf ON vtiger_notescf.notesid= vtiger_notes.notesid
1438                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid= vtiger_notes.notesid and vtiger_crmentity.deleted=0
1439                  INNER JOIN vtiger_crmentity crm2 ON crm2.crmid=vtiger_senotesrel.crmid
1440                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
1441                  LEFT JOIN vtiger_seattachmentsrel ON vtiger_seattachmentsrel.crmid =vtiger_notes.notesid
1442                  LEFT JOIN vtiger_attachments ON vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid
1443                  LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid= vtiger_users.id
1444                  WHERE crm2.crmid IN (".$entityIds.")";
1445  
1446          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
1447  
1448          if ($return_value == null)
1449              $return_value = Array();
1450          $return_value['CUSTOM_BUTTON'] = $button;
1451          return $return_value;
1452      }
1453  
1454      /**
1455       * Function to handle the dependents list for the module.
1456       * NOTE: UI type '10' is used to stored the references to other modules for a given record.
1457       * These dependent records can be retrieved through this function.
1458       * For eg: A trouble ticket can be related to an Account or a Contact.
1459       * From a given Contact/Account if we need to fetch all such dependent trouble tickets, get_dependents_list function can be used.
1460       */
1461  	function get_dependents_list($id, $cur_tab_id, $rel_tab_id, $actions = false) {
1462  
1463          global $currentModule, $app_strings, $singlepane_view, $current_user;
1464  
1465          $parenttab = getParentTab();
1466  
1467          $related_module = vtlib_getModuleNameById($rel_tab_id);
1468          $other = CRMEntity::getInstance($related_module);
1469  
1470          // Some standard module class doesn't have required variables
1471          // that are used in the query, they are defined in this generic API
1472          vtlib_setup_modulevars($currentModule, $this);
1473          vtlib_setup_modulevars($related_module, $other);
1474  
1475          $singular_modname = 'SINGLE_' . $related_module;
1476          $button = '';
1477  
1478          // To make the edit or del link actions to return back to same view.
1479          if ($singlepane_view == 'true')
1480              $returnset = "&return_module=$currentModule&return_action=DetailView&return_id=$id";
1481          else
1482              $returnset = "&return_module=$currentModule&return_action=CallRelatedList&return_id=$id";
1483  
1484          $return_value = null;
1485          $dependentFieldSql = $this->db->pquery("SELECT tabid, fieldname, columnname FROM vtiger_field WHERE uitype='10' AND" .
1486                  " fieldid IN (SELECT fieldid FROM vtiger_fieldmodulerel WHERE relmodule=? AND module=?)", array($currentModule, $related_module));
1487          $numOfFields = $this->db->num_rows($dependentFieldSql);
1488  
1489          if ($numOfFields > 0) {
1490              $dependentColumn = $this->db->query_result($dependentFieldSql, 0, 'columnname');
1491              $dependentField = $this->db->query_result($dependentFieldSql, 0, 'fieldname');
1492  
1493              $button .= '<input type="hidden" name="' . $dependentColumn . '" id="' . $dependentColumn . '" value="' . $id . '">';
1494              $button .= '<input type="hidden" name="' . $dependentColumn . '_type" id="' . $dependentColumn . '_type" value="' . $currentModule . '">';
1495              if ($actions) {
1496                  if (is_string($actions))
1497                      $actions = explode(',', strtoupper($actions));
1498                  if (in_array('ADD', $actions) && isPermitted($related_module, 1, '') == 'yes'
1499                          && getFieldVisibilityPermission($related_module, $current_user->id, $dependentField, 'readwrite') == '0') {
1500                      $button .= "<input title='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname, $related_module) . "' class='crmbutton small create'" .
1501                              " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
1502                              " value='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname, $related_module) . "'>&nbsp;";
1503                  }
1504              }
1505  
1506              $entityIds = $this->getRelatedContactsIds();
1507              array_push($entityIds, $id);
1508              $entityIds = implode(',', $entityIds);
1509  
1510              $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name','last_name' => 'vtiger_users.last_name'), 'Users');
1511  
1512              $query = "SELECT vtiger_crmentity.*, $other->table_name.*";
1513              $query .= ", CASE WHEN (vtiger_users.user_name NOT LIKE '') THEN $userNameSql ELSE vtiger_groups.groupname END AS user_name";
1514  
1515              $more_relation = '';
1516              if (!empty($other->related_tables)) {
1517                  foreach ($other->related_tables as $tname => $relmap) {
1518                      $query .= ", $tname.*";
1519  
1520                      // Setup the default JOIN conditions if not specified
1521                      if (empty($relmap[1]))
1522                          $relmap[1] = $other->table_name;
1523                      if (empty($relmap[2]))
1524                          $relmap[2] = $relmap[0];
1525                      $more_relation .= " LEFT JOIN $tname ON $tname.$relmap[0] = $relmap[1].$relmap[2]";
1526                  }
1527              }
1528  
1529              $query .= " FROM $other->table_name";
1530              $query .= " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $other->table_name.$other->table_index";
1531              $query .= $more_relation;
1532              $query .= " LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid";
1533              $query .= " LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid";
1534              $query .= " WHERE vtiger_crmentity.deleted = 0 AND $other->table_name.$dependentColumn IN (".$entityIds.")";
1535  
1536              $return_value = GetRelatedList($currentModule, $related_module, $other, $query, $button, $returnset);
1537          }
1538          if ($return_value == null)
1539              $return_value = Array();
1540          $return_value['CUSTOM_BUTTON'] = $button;
1541  
1542          return $return_value;
1543      }
1544  
1545      /**
1546       * Function to handle the related list for the module.
1547       * NOTE: Vtiger_Module::setRelatedList sets reference to this function in vtiger_relatedlists table
1548       * if function name is not explicitly specified.
1549       */
1550  	function get_related_list($id, $cur_tab_id, $rel_tab_id, $actions = false) {
1551  
1552          global $currentModule, $app_strings, $singlepane_view;
1553  
1554          $parenttab = getParentTab();
1555  
1556          $related_module = vtlib_getModuleNameById($rel_tab_id);
1557          $other = CRMEntity::getInstance($related_module);
1558  
1559          // Some standard module class doesn't have required variables
1560          // that are used in the query, they are defined in this generic API
1561          vtlib_setup_modulevars($currentModule, $this);
1562          vtlib_setup_modulevars($related_module, $other);
1563  
1564          $singular_modname = 'SINGLE_' . $related_module;
1565  
1566          $button = '';
1567          if ($actions) {
1568              if (is_string($actions))
1569                  $actions = explode(',', strtoupper($actions));
1570              if (in_array('SELECT', $actions) && isPermitted($related_module, 4, '') == 'yes') {
1571                  $button .= "<input title='" . getTranslatedString('LBL_SELECT') . " " . getTranslatedString($related_module) . "' class='crmbutton small edit' " .
1572                          " type='button' onclick=\"return window.open('index.php?module=$related_module&return_module=$currentModule&action=Popup&popuptype=detailview&select=enable&form=EditView&form_submit=false&recordid=$id&parenttab=$parenttab','test','width=640,height=602,resizable=0,scrollbars=0');\"" .
1573                          " value='" . getTranslatedString('LBL_SELECT') . " " . getTranslatedString($related_module, $related_module) . "'>&nbsp;";
1574              }
1575              if (in_array('ADD', $actions) && isPermitted($related_module, 1, '') == 'yes') {
1576                  $button .= "<input type='hidden' name='createmode' id='createmode' value='link' />" .
1577                          "<input title='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname) . "' class='crmbutton small create'" .
1578                          " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\"' type='submit' name='button'" .
1579                          " value='" . getTranslatedString('LBL_ADD_NEW') . " " . getTranslatedString($singular_modname, $related_module) . "'>&nbsp;";
1580              }
1581          }
1582  
1583          // To make the edit or del link actions to return back to same view.
1584          if ($singlepane_view == 'true') {
1585              $returnset = "&return_module=$currentModule&return_action=DetailView&return_id=$id";
1586          } else {
1587              $returnset = "&return_module=$currentModule&return_action=CallRelatedList&return_id=$id";
1588          }
1589  
1590          $more_relation = '';
1591          if (!empty($other->related_tables)) {
1592              foreach ($other->related_tables as $tname => $relmap) {
1593                  $query .= ", $tname.*";
1594  
1595                  // Setup the default JOIN conditions if not specified
1596                  if (empty($relmap[1]))
1597                      $relmap[1] = $other->table_name;
1598                  if (empty($relmap[2]))
1599                      $relmap[2] = $relmap[0];
1600                  $more_relation .= " LEFT JOIN $tname ON $tname.$relmap[0] = $relmap[1].$relmap[2]";
1601              }
1602          }
1603  
1604          $entityIds = $this->getRelatedContactsIds();
1605          array_push($entityIds, $id);
1606          $entityIds = implode(',', $entityIds);
1607  
1608          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
1609  
1610          $query = "SELECT vtiger_crmentity.*, $other->table_name.*,
1611                  CASE WHEN (vtiger_users.user_name NOT LIKE '') THEN $userNameSql ELSE vtiger_groups.groupname END AS user_name FROM $other->table_name
1612                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $other->table_name.$other->table_index
1613                  INNER JOIN vtiger_crmentityrel ON (vtiger_crmentityrel.relcrmid = vtiger_crmentity.crmid OR vtiger_crmentityrel.crmid = vtiger_crmentity.crmid)
1614                  $more_relation
1615                  LEFT  JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
1616                  LEFT  JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
1617                  WHERE vtiger_crmentity.deleted = 0 AND (vtiger_crmentityrel.crmid IN (" .$entityIds. ") OR vtiger_crmentityrel.relcrmid IN (". $entityIds . "))";
1618  
1619          $return_value = GetRelatedList($currentModule, $related_module, $other, $query, $button, $returnset);
1620  
1621          if ($return_value == null)
1622              $return_value = Array();
1623          $return_value['CUSTOM_BUTTON'] = $button;
1624  
1625          return $return_value;
1626      }
1627  
1628      /* Function to get related contact ids for an account record*/
1629  	function getRelatedContactsIds($id = null) {
1630          global $adb;
1631          if($id ==null)
1632          $id = $this->id;
1633          $entityIds = array();
1634          $query = 'SELECT contactid FROM vtiger_contactdetails
1635                  INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
1636                  WHERE vtiger_contactdetails.accountid = ? AND vtiger_crmentity.deleted = 0';
1637          $accountContacts = $adb->pquery($query, array($id));
1638          $numOfContacts = $adb->num_rows($accountContacts);
1639          if($accountContacts && $numOfContacts > 0) {
1640              for($i=0; $i < $numOfContacts; ++$i) {
1641                  array_push($entityIds, $adb->query_result($accountContacts, $i, 'contactid'));
1642              }
1643          }
1644          return $entityIds;
1645      }
1646  }
1647  
1648  ?>


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