[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/Calendar/ -> Activity.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/Activities/Activity.php,v 1.26 2005/03/26 10:42:13 rank Exp $
  17   * Description:  TODO: To be written.
  18   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  19   * All Rights Reserved.
  20   * Contributor(s): ______________________________________..
  21   ********************************************************************************/
  22  
  23  require_once ('modules/Calendar/RenderRelatedListUI.php');
  24  require_once ('modules/Calendar/CalendarCommon.php');
  25  
  26  // Task is used to store customer information.
  27  class Activity extends CRMEntity {
  28      var $log;
  29      var $db;
  30      var $table_name = "vtiger_activity";
  31      var $table_index= 'activityid';
  32      var $reminder_table = 'vtiger_activity_reminder';
  33      var $tab_name = Array('vtiger_crmentity','vtiger_activity','vtiger_activitycf');
  34  
  35      var $tab_name_index = Array('vtiger_crmentity'=>'crmid','vtiger_activity'=>'activityid','vtiger_seactivityrel'=>'activityid','vtiger_cntactivityrel'=>'activityid','vtiger_salesmanactivityrel'=>'activityid','vtiger_activity_reminder'=>'activity_id','vtiger_recurringevents'=>'activityid','vtiger_activitycf'=>'activityid');
  36  
  37      var $column_fields = Array();
  38      var $sortby_fields = Array('subject','due_date','date_start','smownerid','activitytype','lastname');    //Sorting is added for due date and start date
  39  
  40      // This is used to retrieve related vtiger_fields from form posts.
  41      var $additional_column_fields = Array('assigned_user_name', 'assigned_user_id', 'contactname', 'contact_phone', 'contact_email', 'parent_name');
  42  
  43      /**
  44       * Mandatory table for supporting custom fields.
  45       */
  46      var $customFieldTable = Array('vtiger_activitycf', 'activityid');
  47  
  48      // This is the list of vtiger_fields that are in the lists.
  49      var $list_fields = Array(
  50         'Close'=>Array('activity'=>'status'),
  51         'Type'=>Array('activity'=>'activitytype'),
  52         'Subject'=>Array('activity'=>'subject'),
  53         'Related to'=>Array('seactivityrel'=>'parent_id'),
  54         'Start Date'=>Array('activity'=>'date_start'),
  55         'Start Time'=>Array('activity','time_start'),
  56         'End Date'=>Array('activity'=>'due_date'),
  57         'End Time'=>Array('activity','time_end'),
  58         'Recurring Type'=>Array('recurringevents'=>'recurringtype'),
  59         'Assigned To'=>Array('crmentity'=>'smownerid'),
  60         'Contact Name'=>Array('contactdetails'=>'lastname')
  61         );
  62  
  63         var $range_fields = Array(
  64          'name',
  65          'date_modified',
  66          'start_date',
  67          'id',
  68          'status',
  69          'date_due',
  70          'time_start',
  71          'description',
  72          'contact_name',
  73          'priority',
  74          'duehours',
  75          'dueminutes',
  76          'location'
  77         );
  78  
  79  
  80         var $list_fields_name = Array(
  81         'Close'=>'status',
  82         'Type'=>'activitytype',
  83         'Subject'=>'subject',
  84         'Contact Name'=>'lastname',
  85         'Related to'=>'parent_id',
  86         'Start Date & Time'=>'date_start',
  87         'End Date & Time'=>'due_date',
  88         'Recurring Type'=>'recurringtype',
  89         'Assigned To'=>'assigned_user_id',
  90         'Start Date'=>'date_start',
  91         'Start Time'=>'time_start',
  92         'End Date'=>'due_date',
  93         'End Time'=>'time_end');
  94  
  95         var $list_link_field= 'subject';
  96  
  97      //Added these variables which are used as default order by and sortorder in ListView
  98      var $default_order_by = 'due_date';
  99      var $default_sort_order = 'ASC';
 100  
 101      //var $groupTable = Array('vtiger_activitygrouprelation','activityid');
 102  
 103  	function Activity() {
 104          $this->log = LoggerManager::getLogger('Calendar');
 105          $this->db = PearDatabase::getInstance();
 106          $this->column_fields = getColumnFields('Calendar');
 107      }
 108  
 109  	function save_module($module)
 110      {
 111          global $adb;
 112          //Handling module specific save
 113          //Insert into seactivity rel
 114          $insertion_mode = $this->mode;
 115          if(isset($this->column_fields['parent_id']) && $this->column_fields['parent_id'] != '')
 116          {
 117              $this->insertIntoEntityTable("vtiger_seactivityrel", $module);
 118          }
 119          elseif($this->column_fields['parent_id']=='' && $insertion_mode=="edit")
 120          {
 121              $this->deleteRelation("vtiger_seactivityrel");
 122          }
 123          //Insert into cntactivity rel
 124          if(isset($this->column_fields['contact_id']) && $this->column_fields['contact_id'] != '')
 125          {
 126                  $this->insertIntoEntityTable('vtiger_cntactivityrel', $module);
 127          }
 128          elseif($this->column_fields['contact_id'] =='' && $insertion_mode=="edit")
 129          {
 130                  $this->deleteRelation('vtiger_cntactivityrel');
 131          }
 132          $recordId = $this->id;
 133          if(isset($_REQUEST['contactidlist']) && $_REQUEST['contactidlist'] != '') {
 134              $adb->pquery( 'DELETE from vtiger_cntactivityrel WHERE activityid = ?', array($recordId));
 135  
 136  
 137              $contactIdsList = explode (';', $_REQUEST['contactidlist']);
 138              $count = count($contactIdsList);
 139  
 140              $sql = 'INSERT INTO vtiger_cntactivityrel VALUES ';
 141              for($i=0; $i<$count; $i++) {
 142                  $sql .= " ($contactIdsList[$i], $recordId)";
 143                  if ($i != $count - 1) {
 144                      $sql .= ',';
 145                  }
 146              }
 147              $adb->pquery($sql, array());
 148          } else if ($_REQUEST['contactidlist'] == '' && $this->column_fields['contact_id'] == '' && $insertion_mode == "edit") {
 149              $adb->pquery('DELETE FROM vtiger_cntactivityrel WHERE activityid = ?', array($recordId));
 150          }
 151  
 152          $recur_type='';
 153          if(($recur_type == "--None--" || $recur_type == '') && $this->mode == "edit")
 154          {
 155              $sql = 'delete  from vtiger_recurringevents where activityid=?';
 156              $adb->pquery($sql, array($this->id));
 157          }
 158          //Handling for recurring type
 159          //Insert into vtiger_recurring event table
 160          if(isset($this->column_fields['recurringtype']) && $this->column_fields['recurringtype']!='' && $this->column_fields['recurringtype']!='--None--')
 161          {
 162              $recur_type = trim($this->column_fields['recurringtype']);
 163              $recur_data = getrecurringObjValue();
 164              if(is_object($recur_data))
 165                        $this->insertIntoRecurringTable($recur_data);
 166          }
 167  
 168          //Insert into vtiger_activity_remainder table
 169  
 170              $this->insertIntoReminderTable('vtiger_activity_reminder',$module,"");
 171  
 172          //Handling for invitees
 173              $selected_users_string =  $_REQUEST['inviteesid'];
 174              $invitees_array = explode(';',$selected_users_string);
 175              $this->insertIntoInviteeTable($module,$invitees_array);
 176  
 177          //Inserting into sales man activity rel
 178          $this->insertIntoSmActivityRel($module);
 179  
 180          $this->insertIntoActivityReminderPopup($module);
 181      }
 182  
 183  
 184      /** Function to insert values in vtiger_activity_reminder_popup table for the specified module
 185          * @param $cbmodule -- module:: Type varchar
 186        */
 187  	function insertIntoActivityReminderPopup($cbmodule) {
 188  
 189          global $adb;
 190  
 191          $cbrecord = $this->id;
 192          unset($_SESSION['next_reminder_time']);
 193          if(isset($cbmodule) && isset($cbrecord)) {
 194              $cbdate = getValidDBInsertDateValue($this->column_fields['date_start']);
 195              $cbtime = $this->column_fields['time_start'];
 196  
 197              $reminder_query = "SELECT reminderid FROM vtiger_activity_reminder_popup WHERE semodule = ? and recordid = ?";
 198              $reminder_params = array($cbmodule, $cbrecord);
 199              $reminderidres = $adb->pquery($reminder_query, $reminder_params);
 200  
 201              $reminderid = null;
 202              if($adb->num_rows($reminderidres) > 0) {
 203                  $reminderid = $adb->query_result($reminderidres, 0, "reminderid");
 204              }
 205  
 206              if(isset($reminderid)) {
 207                  $current_date = new DateTime();
 208                  $record_date = new DateTime($cbdate.' '.$cbtime);
 209  
 210                  $current = $current_date->format('Y-m-d H:i:s');
 211                  $record = $record_date->format('Y-m-d H:i:s');
 212                  if(strtotime($record) > strtotime($current)){
 213                      $callback_query = "UPDATE vtiger_activity_reminder_popup set status = 0, date_start = ?, time_start = ? WHERE reminderid = ?";
 214                      $callback_params = array($cbdate, $cbtime, $reminderid);
 215                  }
 216              } else {
 217                  $callback_query = "INSERT INTO vtiger_activity_reminder_popup (recordid, semodule, date_start, time_start) VALUES (?,?,?,?)";
 218                  $callback_params = array($cbrecord, $cbmodule, $cbdate, $cbtime);
 219              }
 220  
 221              if($callback_query)
 222                  $adb->pquery($callback_query, $callback_params);
 223          }
 224      }
 225  
 226  
 227      /** Function to insert values in vtiger_activity_remainder table for the specified module,
 228          * @param $table_name -- table name:: Type varchar
 229          * @param $module -- module:: Type varchar
 230        */
 231  	function insertIntoReminderTable($table_name,$module,$recurid)
 232      {
 233           global $log;
 234          $log->info("in insertIntoReminderTable  ".$table_name."    module is  ".$module);
 235          if($_REQUEST['set_reminder'] == 'Yes')
 236          {
 237              unset($_SESSION['next_reminder_time']);
 238              $log->debug("set reminder is set");
 239              $rem_days = $_REQUEST['remdays'];
 240              $log->debug("rem_days is ".$rem_days);
 241              $rem_hrs = $_REQUEST['remhrs'];
 242              $log->debug("rem_hrs is ".$rem_hrs);
 243              $rem_min = $_REQUEST['remmin'];
 244              $log->debug("rem_minutes is ".$rem_min);
 245              $reminder_time = $rem_days * 24 * 60 + $rem_hrs * 60 + $rem_min;
 246              $log->debug("reminder_time is ".$reminder_time);
 247              if ($recurid == "")
 248              {
 249                  if($_REQUEST['mode'] == 'edit')
 250                  {
 251                      $this->activity_reminder($this->id,$reminder_time,0,$recurid,'edit');
 252                  }
 253                  else
 254                  {
 255                      $this->activity_reminder($this->id,$reminder_time,0,$recurid,'');
 256                  }
 257              }
 258              else
 259              {
 260                  $this->activity_reminder($this->id,$reminder_time,0,$recurid,'');
 261              }
 262          }
 263          elseif($_REQUEST['set_reminder'] == 'No')
 264          {
 265              $this->activity_reminder($this->id,'0',0,$recurid,'delete');
 266          }
 267      }
 268  
 269  
 270      // Code included by Jaguar - starts
 271      /** Function to insert values in vtiger_recurringevents table for the specified tablename,module
 272          * @param $recurObj -- Recurring Object:: Type varchar
 273        */
 274  function insertIntoRecurringTable(& $recurObj)
 275  {
 276      global $log,$adb;
 277      $st_date = $recurObj->startdate->get_DB_formatted_date();
 278      $end_date = $recurObj->enddate->get_DB_formatted_date();
 279      if(!empty($recurObj->recurringenddate)){
 280          $recurringenddate = $recurObj->recurringenddate->get_DB_formatted_date();
 281      }
 282      $type = $recurObj->getRecurringType();
 283      $flag="true";
 284  
 285      if($_REQUEST['mode'] == 'edit')
 286      {
 287          $activity_id=$this->id;
 288  
 289          $sql='select min(recurringdate) AS min_date,max(recurringdate) AS max_date, recurringtype, activityid from vtiger_recurringevents where activityid=? group by activityid, recurringtype';
 290          $result = $adb->pquery($sql, array($activity_id));
 291          $noofrows = $adb->num_rows($result);
 292          for($i=0; $i<$noofrows; $i++)
 293          {
 294              $recur_type_b4_edit = $adb->query_result($result,$i,"recurringtype");
 295              $date_start_b4edit = $adb->query_result($result,$i,"min_date");
 296              $end_date_b4edit = $adb->query_result($result,$i,"max_date");
 297          }
 298          if(($st_date == $date_start_b4edit) && ($end_date==$end_date_b4edit) && ($type == $recur_type_b4_edit))
 299          {
 300              if($_REQUEST['set_reminder'] == 'Yes')
 301              {
 302                  $sql = 'delete from vtiger_activity_reminder where activity_id=?';
 303                  $adb->pquery($sql, array($activity_id));
 304                  $sql = 'delete  from vtiger_recurringevents where activityid=?';
 305                  $adb->pquery($sql, array($activity_id));
 306                  $flag="true";
 307              }
 308              elseif($_REQUEST['set_reminder'] == 'No')
 309              {
 310                  $sql = 'delete  from vtiger_activity_reminder where activity_id=?';
 311                  $adb->pquery($sql, array($activity_id));
 312                  $flag="false";
 313              }
 314              else
 315                  $flag="false";
 316          }
 317          else
 318          {
 319              $sql = 'delete from vtiger_activity_reminder where activity_id=?';
 320              $adb->pquery($sql, array($activity_id));
 321              $sql = 'delete  from vtiger_recurringevents where activityid=?';
 322              $adb->pquery($sql, array($activity_id));
 323          }
 324      }
 325  
 326      $recur_freq = $recurObj->getRecurringFrequency();
 327      $recurringinfo = $recurObj->getDBRecurringInfoString();
 328  
 329      if($flag=="true") {
 330          $max_recurid_qry = 'select max(recurringid) AS recurid from vtiger_recurringevents;';
 331          $result = $adb->pquery($max_recurid_qry, array());
 332          $noofrows = $adb->num_rows($result);
 333          $recur_id = 0;
 334          if($noofrows > 0) {
 335              $recur_id = $adb->query_result($result,0,"recurid");
 336          }
 337          $current_id =$recur_id+1;
 338          $recurring_insert = "insert into vtiger_recurringevents values (?,?,?,?,?,?,?)";
 339          $rec_params = array($current_id, $this->id, $st_date, $type, $recur_freq, $recurringinfo,$recurringenddate);
 340          $adb->pquery($recurring_insert, $rec_params);
 341          unset($_SESSION['next_reminder_time']);
 342          if($_REQUEST['set_reminder'] == 'Yes') {
 343              $this->insertIntoReminderTable("vtiger_activity_reminder",$module,$current_id,'');
 344          }
 345      }
 346  }
 347  
 348  
 349      /** Function to insert values in vtiger_invitees table for the specified module,tablename ,invitees_array
 350          * @param $table_name -- table name:: Type varchar
 351          * @param $module -- module:: Type varchar
 352        * @param $invitees_array Array
 353        */
 354  	function insertIntoInviteeTable($module,$invitees_array)
 355      {
 356          global $log,$adb;
 357          $log->debug("Entering insertIntoInviteeTable(".$module.",".$invitees_array.") method ...");
 358          if($this->mode == 'edit'){
 359              $sql = "delete from vtiger_invitees where activityid=?";
 360              $adb->pquery($sql, array($this->id));
 361          }
 362          foreach($invitees_array as $inviteeid)
 363          {
 364              if($inviteeid != '')
 365              {
 366                  $query="insert into vtiger_invitees values(?,?)";
 367                  $adb->pquery($query, array($this->id, $inviteeid));
 368              }
 369          }
 370          $log->debug("Exiting insertIntoInviteeTable method ...");
 371  
 372      }
 373  
 374  
 375      /** Function to insert values in vtiger_salesmanactivityrel table for the specified module
 376          * @param $module -- module:: Type varchar
 377        */
 378  
 379    	function insertIntoSmActivityRel($module)
 380        {
 381              global $adb;
 382              global $current_user;
 383              if($this->mode == 'edit'){
 384                    $sql = "delete from vtiger_salesmanactivityrel where activityid=?";
 385                    $adb->pquery($sql, array($this->id));
 386              }
 387  
 388          $user_sql = $adb->pquery("select count(*) as count from vtiger_users where id=?", array($this->column_fields['assigned_user_id']));
 389          if($adb->query_result($user_sql, 0, 'count') != 0) {
 390          $sql_qry = "insert into vtiger_salesmanactivityrel (smid,activityid) values(?,?)";
 391              $adb->pquery($sql_qry, array($this->column_fields['assigned_user_id'], $this->id));
 392  
 393          if(isset($_REQUEST['inviteesid']) && $_REQUEST['inviteesid']!='')
 394          {
 395              $selected_users_string =  $_REQUEST['inviteesid'];
 396              $invitees_array = explode(';',$selected_users_string);
 397              foreach($invitees_array as $inviteeid)
 398              {
 399                  if($inviteeid != '')
 400                  {
 401                      $resultcheck = $adb->pquery("select * from vtiger_salesmanactivityrel where activityid=? and smid=?",array($this->id,$inviteeid));
 402                      if($adb->num_rows($resultcheck) != 1){
 403                          $query="insert into vtiger_salesmanactivityrel values(?,?)";
 404                          $adb->pquery($query, array($inviteeid, $this->id));
 405                      }
 406                  }
 407              }
 408          }
 409      }
 410  }
 411  
 412      /**
 413       *
 414       * @param String $tableName
 415       * @return String
 416       */
 417  	public function getJoinClause($tableName) {
 418          if($tableName == "vtiger_activity_reminder")
 419              return 'LEFT JOIN';
 420          return parent::getJoinClause($tableName);
 421      }
 422  
 423  
 424      // Mike Crowe Mod --------------------------------------------------------Default ordering for us
 425      /**
 426       * Function to get sort order
 427       * return string  $sorder    - sortorder string either 'ASC' or 'DESC'
 428       */
 429  	function getSortOrder()
 430      {
 431          global $log;
 432          $log->debug("Entering getSortOrder() method ...");
 433          if(isset($_REQUEST['sorder']))
 434              $sorder = $this->db->sql_escape_string($_REQUEST['sorder']);
 435          else
 436              $sorder = (($_SESSION['ACTIVITIES_SORT_ORDER'] != '')?($_SESSION['ACTIVITIES_SORT_ORDER']):($this->default_sort_order));
 437          $log->debug("Exiting getSortOrder method ...");
 438          return $sorder;
 439      }
 440  
 441      /**
 442       * Function to get order by
 443       * return string  $order_by    - fieldname(eg: 'subject')
 444       */
 445  	function getOrderBy()
 446      {
 447          global $log;
 448          $log->debug("Entering getOrderBy() method ...");
 449  
 450          $use_default_order_by = '';
 451          if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) {
 452              $use_default_order_by = $this->default_order_by;
 453          }
 454  
 455          if (isset($_REQUEST['order_by']))
 456              $order_by = $this->db->sql_escape_string($_REQUEST['order_by']);
 457          else
 458              $order_by = (($_SESSION['ACTIVITIES_ORDER_BY'] != '')?($_SESSION['ACTIVITIES_ORDER_BY']):($use_default_order_by));
 459          $log->debug("Exiting getOrderBy method ...");
 460          return $order_by;
 461      }
 462      // Mike Crowe Mod --------------------------------------------------------
 463  
 464  
 465  
 466  //Function Call for Related List -- Start
 467      /**
 468       * Function to get Activity related Contacts
 469       * @param  integer   $id      - activityid
 470       * returns related Contacts record in array format
 471       */
 472  	function get_contacts($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 473          global $log, $singlepane_view,$currentModule,$current_user;
 474          $log->debug("Entering get_contacts(".$id.") method ...");
 475          $this_module = $currentModule;
 476  
 477          $related_module = vtlib_getModuleNameById($rel_tab_id);
 478          require_once("modules/$related_module/$related_module.php");
 479          $other = new $related_module();
 480          vtlib_setup_modulevars($related_module, $other);
 481          $singular_modname = vtlib_toSingular($related_module);
 482  
 483          $parenttab = getParentTab();
 484  
 485          $returnset = '&return_module='.$this_module.'&return_action=DetailView&activity_mode=Events&return_id='.$id;
 486  
 487          $search_string = '';
 488          $button = '';
 489  
 490          if($actions) {
 491              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 492              if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') {
 493                  $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$search_string','test','width=640,height=602,resizable=0,scrollbars=0');\" value='". getTranslatedString('LBL_SELECT'). " " . getTranslatedString($related_module) ."'>&nbsp;";
 494              }
 495          }
 496  
 497          $query = 'select vtiger_users.user_name,vtiger_contactdetails.accountid,vtiger_contactdetails.contactid, vtiger_contactdetails.firstname,vtiger_contactdetails.lastname, vtiger_contactdetails.department, vtiger_contactdetails.title, vtiger_contactdetails.email, vtiger_contactdetails.phone, vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime from vtiger_contactdetails inner join vtiger_cntactivityrel on vtiger_cntactivityrel.contactid=vtiger_contactdetails.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid where vtiger_cntactivityrel.activityid='.$id.' 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_contacts method ...");
 505          return $return_value;
 506      }
 507  
 508      /**
 509       * Function to get Activity related Users
 510       * @param  integer   $id      - activityid
 511       * returns related Users record in array format
 512       */
 513  
 514  	function get_users($id) {
 515          global $log;
 516                  $log->debug("Entering get_contacts(".$id.") method ...");
 517          global $app_strings;
 518  
 519          $focus = new Users();
 520  
 521          $button = '<input title="Change" accessKey="" tabindex="2" type="button" class="crmbutton small edit"
 522                      value="'.getTranslatedString('LBL_SELECT_USER_BUTTON_LABEL').'" name="button" LANGUAGE=javascript
 523                      onclick=\'return window.open("index.php?module=Users&return_module=Calendar&return_action={$return_modname}&activity_mode=Events&action=Popup&popuptype=detailview&form=EditView&form_submit=true&select=enable&return_id='.$id.'&recordid='.$id.'","test","width=640,height=525,resizable=0,scrollbars=0")\';>';
 524  
 525          $returnset = '&return_module=Calendar&return_action=CallRelatedList&return_id='.$id;
 526  
 527          $query = 'SELECT vtiger_users.id, vtiger_users.first_name,vtiger_users.last_name, vtiger_users.user_name, vtiger_users.email1, vtiger_users.email2, vtiger_users.status, vtiger_users.is_admin, vtiger_user2role.roleid, vtiger_users.secondaryemail, vtiger_users.phone_home, vtiger_users.phone_work, vtiger_users.phone_mobile, vtiger_users.phone_other, vtiger_users.phone_fax,vtiger_activity.date_start,vtiger_activity.due_date,vtiger_activity.time_start,vtiger_activity.duration_hours,vtiger_activity.duration_minutes from vtiger_users inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.smid=vtiger_users.id  inner join vtiger_activity on vtiger_activity.activityid=vtiger_salesmanactivityrel.activityid inner join vtiger_user2role on vtiger_user2role.userid=vtiger_users.id where vtiger_activity.activityid='.$id;
 528  
 529          $return_data = GetRelatedList('Calendar','Users',$focus,$query,$button,$returnset);
 530  
 531          if($return_data == null) $return_data = Array();
 532          $return_data['CUSTOM_BUTTON'] = $button;
 533  
 534          $log->debug("Exiting get_users method ...");
 535          return $return_data;
 536      }
 537  
 538      /**
 539           * Function to get activities for given criteria
 540       * @param   string   $criteria     - query string
 541       * returns  activity records in array format($list) or null value
 542           */
 543    	function get_full_list($criteria) {
 544           global $log;
 545          $log->debug("Entering get_full_list(".$criteria.") method ...");
 546          $query = "select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_activity.*,
 547                  vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, vtiger_contactdetails.contactid
 548                  from vtiger_activity
 549                  inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
 550                  left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid
 551                  left join vtiger_contactdetails on vtiger_contactdetails.contactid= vtiger_cntactivityrel.contactid
 552                  left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid
 553                  WHERE vtiger_crmentity.deleted=0 ".$criteria;
 554          $result =& $this->db->query($query);
 555  
 556      if($this->db->getRowCount($result) > 0){
 557  
 558        // We have some data.
 559        while ($row = $this->db->fetchByAssoc($result)) {
 560          foreach($this->list_fields_name as $field)
 561          {
 562            if (isset($row[$field])) {
 563              $this->$field = $row[$field];
 564            }
 565            else {
 566              $this->$field = '';
 567            }
 568          }
 569          $list[] = $this;
 570        }
 571      }
 572      if (isset($list))
 573          {
 574          $log->debug("Exiting get_full_list method ...");
 575          return $list;
 576      }
 577      else
 578      {
 579          $log->debug("Exiting get_full_list method ...");
 580          return null;
 581      }
 582  
 583    }
 584  
 585  
 586  //calendarsync
 587      /**
 588       * Function to get meeting count
 589       * @param  string   $user_name        - User Name
 590       * return  integer  $row["count(*)"]  - count
 591       */
 592      function getCount_Meeting($user_name)
 593      {
 594          global $log;
 595              $log->debug("Entering getCount_Meeting(".$user_name.") method ...");
 596        $query = "select count(*) from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid where user_name=? and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting'";
 597        $result = $this->db->pquery($query, array($user_name),true,"Error retrieving contacts count");
 598        $rows_found =  $this->db->getRowCount($result);
 599        $row = $this->db->fetchByAssoc($result, 0);
 600      $log->debug("Exiting getCount_Meeting method ...");
 601        return $row["count(*)"];
 602      }
 603  
 604      function get_calendars($user_name,$from_index,$offset)
 605      {
 606          global $log;
 607              $log->debug("Entering get_calendars(".$user_name.",".$from_index.",".$offset.") method ...");
 608          $query = "select vtiger_activity.location as location,vtiger_activity.duration_hours as duehours, vtiger_activity.duration_minutes as dueminutes,vtiger_activity.time_start as time_start, vtiger_activity.subject as name,vtiger_crmentity.modifiedtime as date_modified, vtiger_activity.date_start start_date,vtiger_activity.activityid as id,vtiger_activity.status as status, vtiger_crmentity.description as description, vtiger_activity.priority as vtiger_priority, vtiger_activity.due_date as date_due ,vtiger_contactdetails.firstname cfn, vtiger_contactdetails.lastname cln from vtiger_activity inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where user_name='" .$user_name ."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting' limit " .$from_index ."," .$offset;
 609      $log->debug("Exiting get_calendars method ...");
 610          return $this->process_list_query1($query);
 611      }
 612  //calendarsync
 613      /**
 614       * Function to get task count
 615       * @param  string   $user_name        - User Name
 616       * return  integer  $row["count(*)"]  - count
 617       */
 618      function getCount($user_name)
 619      {
 620          global $log;
 621              $log->debug("Entering getCount(".$user_name.") method ...");
 622          $query = "select count(*) from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid where user_name=? and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task'";
 623          $result = $this->db->pquery($query,array($user_name), true,"Error retrieving contacts count");
 624          $rows_found =  $this->db->getRowCount($result);
 625          $row = $this->db->fetchByAssoc($result, 0);
 626  
 627      $log->debug("Exiting getCount method ...");
 628          return $row["count(*)"];
 629      }
 630  
 631      /**
 632       * Function to get list of task for user with given limit
 633       * @param  string   $user_name        - User Name
 634       * @param  string   $from_index       - query string
 635       * @param  string   $offset           - query string
 636       * returns tasks in array format
 637       */
 638      function get_tasks($user_name,$from_index,$offset)
 639      {
 640      global $log;
 641          $log->debug("Entering get_tasks(".$user_name.",".$from_index.",".$offset.") method ...");
 642       $query = "select vtiger_activity.subject as name,vtiger_crmentity.modifiedtime as date_modified, vtiger_activity.date_start start_date,vtiger_activity.activityid as id,vtiger_activity.status as status, vtiger_crmentity.description as description, vtiger_activity.priority as priority, vtiger_activity.due_date as date_due ,vtiger_contactdetails.firstname cfn, vtiger_contactdetails.lastname cln from vtiger_activity inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where user_name='" .$user_name ."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task' limit " .$from_index ."," .$offset;
 643       $log->debug("Exiting get_tasks method ...");
 644      return $this->process_list_query1($query);
 645  
 646      }
 647  
 648      /**
 649       * Function to process the activity list query
 650       * @param  string   $query     - query string
 651       * return  array    $response  - activity lists
 652       */
 653      function process_list_query1($query)
 654      {
 655          global $log;
 656              $log->debug("Entering process_list_query1(".$query.") method ...");
 657          $result =& $this->db->query($query,true,"Error retrieving $this->object_name list: ");
 658          $list = Array();
 659          $rows_found =  $this->db->getRowCount($result);
 660          if($rows_found != 0)
 661          {
 662              $task = Array();
 663                for($index = 0 , $row = $this->db->fetchByAssoc($result, $index); $row && $index <$rows_found;$index++, $row = $this->db->fetchByAssoc($result, $index))
 664  
 665               {
 666                  foreach($this->range_fields as $columnName)
 667                  {
 668                      if (isset($row[$columnName])) {
 669                          if($columnName == 'time_start'){
 670                              $startDate = new DateTimeField($row['date_start'].' '.
 671                                      $row[$columnName]);
 672                              $task[$columnName] = $startDate->getDBInsertTimeValue();
 673                          }else{
 674                              $task[$columnName] = $row[$columnName];
 675                          }
 676                      }
 677                      else
 678                      {
 679                              $task[$columnName] = "";
 680                      }
 681                  }
 682  
 683                  $task[contact_name] = return_name($row, 'cfn', 'cln');
 684  
 685                      $list[] = $task;
 686                  }
 687           }
 688  
 689          $response = Array();
 690          $response['list'] = $list;
 691          $response['row_count'] = $rows_found;
 692          $response['next_offset'] = $next_offset;
 693          $response['previous_offset'] = $previous_offset;
 694  
 695  
 696      $log->debug("Exiting process_list_query1 method ...");
 697          return $response;
 698      }
 699  
 700          /**
 701       * Function to get reminder for activity
 702       * @param  integer   $activity_id     - activity id
 703       * @param  string    $reminder_time   - reminder time
 704       * @param  integer   $reminder_sent   - 0 or 1
 705       * @param  integer   $recurid         - recuring eventid
 706       * @param  string    $remindermode    - string like 'edit'
 707       */
 708  	function activity_reminder($activity_id,$reminder_time,$reminder_sent=0,$recurid,$remindermode='')
 709      {
 710          global $log;
 711          $log->debug("Entering vtiger_activity_reminder(".$activity_id.",".$reminder_time.",".$reminder_sent.",".$recurid.",".$remindermode.") method ...");
 712          //Check for vtiger_activityid already present in the reminder_table
 713          $query_exist = "SELECT activity_id FROM ".$this->reminder_table." WHERE activity_id = ?";
 714          $result_exist = $this->db->pquery($query_exist, array($activity_id));
 715  
 716          if($remindermode == 'edit')
 717          {
 718              if($this->db->num_rows($result_exist) > 0)
 719              {
 720                  $query = "UPDATE ".$this->reminder_table." SET";
 721                  $query .=" reminder_sent = ?, reminder_time = ? WHERE activity_id =?";
 722                  $params = array($reminder_sent, $reminder_time, $activity_id);
 723              }
 724              else
 725              {
 726                  $query = "INSERT INTO ".$this->reminder_table." VALUES (?,?,?,?)";
 727                  $params = array($activity_id, $reminder_time, 0, $recurid);
 728              }
 729          }
 730          elseif(($remindermode == 'delete') && ($this->db->num_rows($result_exist) > 0))
 731          {
 732              $query = "DELETE FROM ".$this->reminder_table." WHERE activity_id = ?";
 733              $params = array($activity_id);
 734          }
 735          else
 736          {
 737              if($_REQUEST['set_reminder'] == 'Yes'){
 738                  $query = "INSERT INTO ".$this->reminder_table." VALUES (?,?,?,?)";
 739                  $params = array($activity_id, $reminder_time, 0, $recurid);
 740              }
 741          }
 742          if(!empty($query)){
 743              $this->db->pquery($query,$params,true,"Error in processing vtiger_table $this->reminder_table");
 744          }
 745          $log->debug("Exiting vtiger_activity_reminder method ...");
 746      }
 747  
 748      //Used for vtigerCRM Outlook Add-In
 749      /**
 750       * Function to get tasks to display in outlookplugin
 751       * @param   string    $username     -  User name
 752       * return   string    $query        -  sql query
 753       */
 754  	function get_tasksforol($username)
 755      {
 756          global $log,$adb;
 757          $log->debug("Entering get_tasksforol(".$username.") method ...");
 758          global $current_user;
 759          require_once ("modules/Users/Users.php");
 760          $seed_user=new Users();
 761          $user_id=$seed_user->retrieve_user_id($username);
 762          $current_user=$seed_user;
 763          $current_user->retrieve_entity_info($user_id, 'Users');
 764          require('user_privileges/user_privileges_'.$current_user->id.'.php');
 765          require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
 766  
 767          if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0)
 768            {
 769              $sql1 = "select tablename,columnname from vtiger_field where tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.presence in (0,2)";
 770              $params1 = array();
 771            }else
 772        {
 773          $profileList = getCurrentUserProfileList();
 774          $sql1 = "select tablename,columnname 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=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.displaytype in (1,2,4,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)";
 775          $params1 = array();
 776          if (count($profileList) > 0) {
 777                $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")";
 778              array_push($params1, $profileList);
 779          }
 780        }
 781        $result1 = $adb->pquery($sql1,$params1);
 782        for($i=0;$i < $adb->num_rows($result1);$i++)
 783        {
 784          $permitted_lists[] = $adb->query_result($result1,$i,'tablename');
 785            $permitted_lists[] = $adb->query_result($result1,$i,'columnname');
 786            /*if($adb->query_result($result1,$i,'columnname') == "parentid")
 787            {
 788              $permitted_lists[] = 'vtiger_account';
 789              $permitted_lists[] = 'accountname';
 790            }*/
 791            }
 792          $permitted_lists = array_chunk($permitted_lists,2);
 793          $column_table_lists = array();
 794          for($i=0;$i < count($permitted_lists);$i++)
 795          {
 796                 $column_table_lists[] = implode(".",$permitted_lists[$i]);
 797            }
 798  
 799          $query = "select vtiger_activity.activityid as taskid, ".implode(',',$column_table_lists)." from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
 800               inner join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid
 801               left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid
 802               left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid
 803               left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid
 804               where vtiger_users.user_name='".$username."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task'";
 805          $log->debug("Exiting get_tasksforol method ...");
 806          return $query;
 807      }
 808  
 809      /**
 810       * Function to get calendar query for outlookplugin
 811       * @param   string    $username     -  User name                                                                            * return   string    $query        -  sql query                                                                            */
 812  	function get_calendarsforol($user_name)
 813      {
 814          global $log,$adb;
 815          $log->debug("Entering get_calendarsforol(".$user_name.") method ...");
 816          global $current_user;
 817          require_once ("modules/Users/Users.php");
 818          $seed_user=new Users();
 819          $user_id=$seed_user->retrieve_user_id($user_name);
 820          $current_user=$seed_user;
 821          $current_user->retrieve_entity_info($user_id, 'Users');
 822          require('user_privileges/user_privileges_'.$current_user->id.'.php');
 823          require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
 824  
 825          if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0)
 826            {
 827              $sql1 = "select tablename,columnname from vtiger_field where tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.presence in (0,2)";
 828                $params1 = array();
 829            }else
 830            {
 831              $profileList = getCurrentUserProfileList();
 832              $sql1 = "select tablename,columnname 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=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.displaytype in (1,2,4,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)";
 833              $params1 = array();
 834              if (count($profileList) > 0) {
 835                  $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")";
 836                  array_push($params1,$profileList);
 837              }
 838            }
 839            $result1 = $adb->pquery($sql1, $params1);
 840            for($i=0;$i < $adb->num_rows($result1);$i++)
 841            {
 842              $permitted_lists[] = $adb->query_result($result1,$i,'tablename');
 843                $permitted_lists[] = $adb->query_result($result1,$i,'columnname');
 844                if($adb->query_result($result1,$i,'columnname') == "date_start")
 845                {
 846                  $permitted_lists[] = 'vtiger_activity';
 847                  $permitted_lists[] = 'time_start';
 848                }
 849                if($adb->query_result($result1,$i,'columnname') == "due_date")
 850                {
 851                  $permitted_lists[] = 'vtiger_activity';
 852                  $permitted_lists[] = 'time_end';
 853                }
 854            }
 855          $permitted_lists = array_chunk($permitted_lists,2);
 856          $column_table_lists = array();
 857          for($i=0;$i < count($permitted_lists);$i++)
 858          {
 859                 $column_table_lists[] = implode(".",$permitted_lists[$i]);
 860            }
 861  
 862            $query = "select vtiger_activity.activityid as clndrid, ".implode(',',$column_table_lists)." from vtiger_activity
 863                  inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid
 864                  inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid
 865                  left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid
 866                  left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid
 867                  left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid
 868                  inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
 869                  where vtiger_users.user_name='".$user_name."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting'";
 870          $log->debug("Exiting get_calendarsforol method ...");
 871          return $query;
 872      }
 873  
 874      // Function to unlink all the dependent entities of the given Entity by Id
 875  	function unlinkDependencies($module, $id) {
 876          global $log;
 877  
 878          $sql = 'DELETE FROM vtiger_activity_reminder WHERE activity_id=?';
 879          $this->db->pquery($sql, array($id));
 880  
 881          $sql = 'DELETE FROM vtiger_recurringevents WHERE activityid=?';
 882          $this->db->pquery($sql, array($id));
 883  
 884          $sql = 'DELETE FROM vtiger_cntactivityrel WHERE activityid = ?';
 885          $this->db->pquery($sql, array($id));
 886  
 887          parent::unlinkDependencies($module, $id);
 888      }
 889  
 890      // Function to unlink an entity with given Id from another entity
 891  	function unlinkRelationship($id, $return_module, $return_id) {
 892          global $log;
 893          if(empty($return_module) || empty($return_id)) return;
 894  
 895          if($return_module == 'Contacts') {
 896              $sql = 'DELETE FROM vtiger_cntactivityrel WHERE contactid = ? AND activityid = ?';
 897              $this->db->pquery($sql, array($return_id, $id));
 898          } elseif($return_module == 'HelpDesk') {
 899              $sql = 'DELETE FROM vtiger_seactivityrel WHERE crmid = ? AND activityid = ?';
 900              $this->db->pquery($sql, array($return_id, $id));
 901          } elseif($return_module == 'Accounts') {
 902              $sql = 'DELETE FROM vtiger_seactivityrel WHERE crmid = ? AND activityid = ?';
 903              $this->db->pquery($sql, array($return_id, $id));
 904              $sql = 'DELETE FROM vtiger_cntactivityrel WHERE activityid = ? AND contactid IN    (SELECT contactid from vtiger_contactdetails where accountid=?)';
 905              $this->db->pquery($sql, array($id, $return_id));
 906          } else {
 907              $sql='DELETE FROM vtiger_seactivityrel WHERE activityid=?';
 908              $this->db->pquery($sql, array($id));
 909  
 910              $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
 911              $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
 912              $this->db->pquery($sql, $params);
 913          }
 914      }
 915  
 916      /**
 917       * this function sets the status flag of activity to true or false depending on the status passed to it
 918       * @param string $status - the status of the activity flag to set
 919       * @return:: true if successful; false otherwise
 920       */
 921  	function setActivityReminder($status){
 922          global $adb;
 923          if($status == "on"){
 924              $flag = 0;
 925          }elseif($status == "off"){
 926              $flag = 1;
 927          }else{
 928              return false;
 929          }
 930          $sql = "update vtiger_activity_reminder_popup set status=1 where recordid=?";
 931          $adb->pquery($sql, array($this->id));
 932          return true;
 933      }
 934  
 935      /*
 936       * Function to get the relation tables for related modules
 937       * @param - $secmodule secondary module name
 938       * returns the array with table names and fieldnames storing relations between module and this module
 939       */
 940  	function setRelationTables($secmodule){
 941          $rel_tables = array (
 942              "Contacts" => array("vtiger_cntactivityrel"=>array("activityid","contactid"),"vtiger_activity"=>"activityid"),
 943              "Leads" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"),
 944              "Accounts" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"),
 945              "Potentials" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"),
 946          );
 947          return $rel_tables[$secmodule];
 948      }
 949  
 950      /*
 951       * Function to get the secondary query part of a report
 952       * @param - $module primary module name
 953       * @param - $secmodule secondary module name
 954       * returns the query string formed on fetching the related data for report for secondary module
 955       */
 956  	function generateReportsSecQuery($module,$secmodule,$queryPlanner){
 957          $matrix = $queryPlanner->newDependencyMatrix();
 958          $matrix->setDependency('vtiger_crmentityCalendar',array('vtiger_groupsCalendar','vtiger_usersCalendar','vtiger_lastModifiedByCalendar'));
 959          $matrix->setDependency('vtiger_cntactivityrel',array('vtiger_contactdetailsCalendar'));
 960          $matrix->setDependency('vtiger_seactivityrel',array('vtiger_crmentityRelCalendar'));
 961          $matrix->setDependency('vtiger_crmentityRelCalendar',array('vtiger_accountRelCalendar','vtiger_leaddetailsRelCalendar','vtiger_potentialRelCalendar',
 962                                  'vtiger_quotesRelCalendar','vtiger_purchaseorderRelCalendar','vtiger_invoiceRelCalendar',
 963                                  'vtiger_salesorderRelCalendar','vtiger_troubleticketsRelCalendar','vtiger_campaignRelCalendar'));
 964          $matrix->setDependency('vtiger_activity',array('vtiger_crmentityCalendar','vtiger_cntactivityrel','vtiger_activitycf',
 965                                  'vtiger_seactivityrel','vtiger_activity_reminder','vtiger_recurringevents'));
 966  
 967          if (!$queryPlanner->requireTable('vtiger_activity', $matrix)) {
 968              return '';
 969          }
 970  
 971          $query = $this->getRelationQuery($module,$secmodule,"vtiger_activity","activityid", $queryPlanner);
 972  
 973          if ($queryPlanner->requireTable("vtiger_crmentityCalendar",$matrix)){
 974              $query .=" left join vtiger_crmentity as vtiger_crmentityCalendar on vtiger_crmentityCalendar.crmid=vtiger_activity.activityid and vtiger_crmentityCalendar.deleted=0";
 975          }
 976          if ($queryPlanner->requireTable("vtiger_cntactivityrel",$matrix)){
 977              $query .="     left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid";
 978          }
 979          if ($queryPlanner->requireTable("vtiger_contactdetailsCalendar")){
 980              $query .="     left join vtiger_contactdetails as vtiger_contactdetailsCalendar on vtiger_contactdetailsCalendar.contactid= vtiger_cntactivityrel.contactid";
 981          }
 982          if ($queryPlanner->requireTable("vtiger_activitycf")){
 983              $query .="     left join vtiger_activitycf on vtiger_activitycf.activityid = vtiger_activity.activityid";
 984          }
 985          if ($queryPlanner->requireTable("vtiger_seactivityrel",$matrix)){
 986              $query .="     left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid";
 987          }
 988          if ($queryPlanner->requireTable("vtiger_activity_reminder")){
 989              $query .="     left join vtiger_activity_reminder on vtiger_activity_reminder.activity_id = vtiger_activity.activityid";
 990          }
 991          if ($queryPlanner->requireTable("vtiger_recurringevents")){
 992              $query .="     left join vtiger_recurringevents on vtiger_recurringevents.activityid = vtiger_activity.activityid";
 993          }
 994          if ($queryPlanner->requireTable("vtiger_crmentityRelCalendar",$matrix)){
 995              $query .="     left join vtiger_crmentity as vtiger_crmentityRelCalendar on vtiger_crmentityRelCalendar.crmid = vtiger_seactivityrel.crmid and vtiger_crmentityRelCalendar.deleted=0";
 996          }
 997          if ($queryPlanner->requireTable("vtiger_accountRelCalendar")){
 998              $query .="     left join vtiger_account as vtiger_accountRelCalendar on vtiger_accountRelCalendar.accountid=vtiger_crmentityRelCalendar.crmid";
 999          }
1000          if ($queryPlanner->requireTable("vtiger_leaddetailsRelCalendar")){
1001              $query .="     left join vtiger_leaddetails as vtiger_leaddetailsRelCalendar on vtiger_leaddetailsRelCalendar.leadid = vtiger_crmentityRelCalendar.crmid";
1002          }
1003          if ($queryPlanner->requireTable("vtiger_potentialRelCalendar")){
1004              $query .="     left join vtiger_potential as vtiger_potentialRelCalendar on vtiger_potentialRelCalendar.potentialid = vtiger_crmentityRelCalendar.crmid";
1005          }
1006          if ($queryPlanner->requireTable("vtiger_quotesRelCalendar")){
1007              $query .="     left join vtiger_quotes as vtiger_quotesRelCalendar on vtiger_quotesRelCalendar.quoteid = vtiger_crmentityRelCalendar.crmid";
1008          }
1009          if ($queryPlanner->requireTable("vtiger_purchaseorderRelCalendar")){
1010              $query .="     left join vtiger_purchaseorder as vtiger_purchaseorderRelCalendar on vtiger_purchaseorderRelCalendar.purchaseorderid = vtiger_crmentityRelCalendar.crmid";
1011          }
1012          if ($queryPlanner->requireTable("vtiger_invoiceRelCalendar")){
1013              $query .="     left join vtiger_invoice as vtiger_invoiceRelCalendar on vtiger_invoiceRelCalendar.invoiceid = vtiger_crmentityRelCalendar.crmid";
1014          }
1015          if ($queryPlanner->requireTable("vtiger_salesorderRelCalendar")){
1016              $query .="     left join vtiger_salesorder as vtiger_salesorderRelCalendar on vtiger_salesorderRelCalendar.salesorderid = vtiger_crmentityRelCalendar.crmid";
1017          }
1018          if ($queryPlanner->requireTable("vtiger_troubleticketsRelCalendar")){
1019              $query .=" left join vtiger_troubletickets as vtiger_troubleticketsRelCalendar on vtiger_troubleticketsRelCalendar.ticketid = vtiger_crmentityRelCalendar.crmid";
1020          }
1021          if ($queryPlanner->requireTable("vtiger_campaignRelCalendar")){
1022              $query .="     left join vtiger_campaign as vtiger_campaignRelCalendar on vtiger_campaignRelCalendar.campaignid = vtiger_crmentityRelCalendar.crmid";
1023          }
1024          if ($queryPlanner->requireTable("vtiger_groupsCalendar")){
1025              $query .=" left join vtiger_groups as vtiger_groupsCalendar on vtiger_groupsCalendar.groupid = vtiger_crmentityCalendar.smownerid";
1026          }
1027          if ($queryPlanner->requireTable("vtiger_usersCalendar")){
1028              $query .="     left join vtiger_users as vtiger_usersCalendar on vtiger_usersCalendar.id = vtiger_crmentityCalendar.smownerid";
1029          }
1030          if ($queryPlanner->requireTable("vtiger_lastModifiedByCalendar")){
1031              $query .="  left join vtiger_users as vtiger_lastModifiedByCalendar on vtiger_lastModifiedByCalendar.id = vtiger_crmentityCalendar.modifiedby ";
1032          }
1033          if ($queryPlanner->requireTable("vtiger_createdbyCalendar")){
1034              $query .= " left join vtiger_users as vtiger_createdbyCalendar on vtiger_createdbyCalendar.id = vtiger_crmentityCalendar.smcreatorid ";
1035          }
1036          return $query;
1037      }
1038  
1039  	public function getNonAdminAccessControlQuery($module, $user,$scope='') {
1040          require('user_privileges/user_privileges_'.$user->id.'.php');
1041          require('user_privileges/sharing_privileges_'.$user->id.'.php');
1042          $query = ' ';
1043          $tabId = getTabid($module);
1044          if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2]
1045                  == 1 && $defaultOrgSharingPermission[$tabId] == 3) {
1046              $tableName = 'vt_tmp_u'.$user->id.'_t'.$tabId;
1047              $sharingRuleInfoVariable = $module.'_share_read_permission';
1048              $sharingRuleInfo = $$sharingRuleInfoVariable;
1049              $sharedTabId = null;
1050              $this->setupTemporaryTable($tableName, $sharedTabId, $user,
1051                      $current_user_parent_role_seq, $current_user_groups);
1052  
1053              $sharedUsers = $this->getListViewAccessibleUsers($user->id);
1054              // we need to include group id's in $sharedUsers list to get the current user's group records
1055              if($current_user_groups){
1056                  $sharedUsers = $sharedUsers.','. implode(',',$current_user_groups);
1057              }
1058              $query = " INNER JOIN $tableName $tableName$scope ON ($tableName$scope.id = ".
1059                      "vtiger_crmentity$scope.smownerid and $tableName$scope.shared=0 and $tableName$scope.id IN ($sharedUsers)) ";
1060          }
1061          return $query;
1062      }
1063  
1064      /**
1065       * To get non admin access query for Reports generation
1066       * @param type $tableName
1067       * @param type $tabId
1068       * @param type $user
1069       * @param type $parent_roles
1070       * @param type $groups
1071       * @return $query
1072       */
1073      public function getReportsNonAdminAccessControlQuery($tableName, $tabId, $user, $parent_roles,$groups){
1074          $sharedUsers = $this->getListViewAccessibleUsers($user->id);
1075          $this->setupTemporaryTable($tableName, $tabId, $user, $parent_roles,$groups);
1076          $query = "SELECT id FROM $tableName WHERE $tableName.shared=0 AND $tableName.id IN ($sharedUsers)";
1077          return $query;
1078      }
1079  
1080  	protected function setupTemporaryTable($tableName, $tabId, $user, $parentRole, $userGroups) {
1081          $module = null;
1082          if (!empty($tabId)) {
1083              $module = getTabname($tabId);
1084          }
1085          $query = $this->getNonAdminAccessQuery($module, $user, $parentRole, $userGroups);
1086          $query = "create temporary table IF NOT EXISTS $tableName(id int(11) primary key, shared ".
1087              "int(1) default 0) ignore ".$query;
1088          $db = PearDatabase::getInstance();
1089          $result = $db->pquery($query, array());
1090          if(is_object($result)) {
1091              $query = "REPLACE INTO $tableName (id) SELECT userid as id FROM vtiger_sharedcalendar WHERE sharedid = ?";
1092              $result = $db->pquery($query, array($user->id));
1093  
1094              //For newly created users, entry will not be there in vtiger_sharedcalendar table
1095              //so, consider the users whose having the calendarsharedtype is public
1096              $query = "REPLACE INTO $tableName (id) SELECT id FROM vtiger_users WHERE calendarsharedtype = ?";
1097              $result = $db->pquery($query, array('public'));
1098  
1099              if(is_object($result)) {
1100                  return true;
1101              }
1102          }
1103          return false;
1104      }
1105  
1106  	protected function getListViewAccessibleUsers($sharedid) {
1107          $db = PearDatabase::getInstance();;
1108          $query = "SELECT vtiger_users.id as userid FROM vtiger_sharedcalendar
1109                      RIGHT JOIN vtiger_users ON vtiger_sharedcalendar.userid=vtiger_users.id and status= 'Active'
1110                      WHERE sharedid=? OR (vtiger_users.status='Active' AND vtiger_users.calendarsharedtype='public' AND vtiger_users.id <> ?);";
1111              $result = $db->pquery($query, array($sharedid, $sharedid));
1112              $rows = $db->num_rows($result);
1113          if($db->num_rows($result)!=0)
1114          {
1115              for($j=0;$j<$db->num_rows($result);$j++) {
1116                  $userid[] = $db->query_result($result,$j,'userid');
1117              }
1118              $shared_ids = implode (",",$userid);
1119          }
1120          $userid[] = $sharedid;
1121          $shared_ids = implode (",",$userid);
1122          return $shared_ids;
1123      }
1124  }
1125  ?>


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