/data/CRMEntity.php
PHP | 2631 lines | 1832 code | 386 blank | 413 comment | 554 complexity | 5663782404bc175a23fa27fc38cd02d8 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, LGPL-2.1, GPL-2.0, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /*********************************************************************************
- * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
- * ("License"); You may not use this file except in compliance with the
- * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
- * the specific language governing rights and limitations under the License.
- * The Original Code is: SugarCRM Open Source
- * The Initial Developer of the Original Code is SugarCRM, Inc.
- * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
- * All Rights Reserved.
- * Contributor(s): ______________________________________.
- ********************************************************************************/
- /*********************************************************************************
- * $Header: /advent/projects/wesat/vtiger_crm/vtigercrm/data/CRMEntity.php,v 1.16 2005/04/29 04:21:31 mickie Exp $
- * Description: Defines the base class for all data entities used throughout the
- * application. The base class including its methods and variables is designed to
- * be overloaded with module-specific methods and variables particular to the
- * module's base entity class.
- ********************************************************************************/
- include_once('config.php');
- require_once('include/logging.php');
- require_once('data/Tracker.php');
- require_once('include/utils/utils.php');
- require_once('include/utils/UserInfoUtil.php');
- require_once("include/Zend/Json.php");
- class CRMEntity {
- var $ownedby;
- /**
- * Detect if we are in bulk save mode, where some features can be turned-off
- * to improve performance.
- */
- static function isBulkSaveMode() {
- global $VTIGER_BULK_SAVE_MODE;
- if (isset($VTIGER_BULK_SAVE_MODE) && $VTIGER_BULK_SAVE_MODE) {
- return true;
- }
- return false;
- }
- static function getInstance($module) {
- $modName = $module;
- if ($module == 'Calendar' || $module == 'Events') {
- $module = 'Calendar';
- $modName = 'Activity';
- }
- // File access security check
- if (!class_exists($modName)) {
- checkFileAccessForInclusion("modules/$module/$modName.php");
- require_once("modules/$module/$modName.php");
- }
- $focus = new $modName();
- return $focus;
- }
- function saveentity($module, $fileid = '') {
- global $current_user, $adb; //$adb added by raju for mass mailing
- $insertion_mode = $this->mode;
- $columnFields = $this->column_fields;
- $anyValue = false;
- foreach ($columnFields as $value) {
- if(!empty($value)) {
- $anyValue = true;
- break;
- }
- }
- if(!$anyValue) {
- die("<center>" .getTranslatedString('LBL_MANDATORY_FIELD_MISSING')."</center>");
- }
- $this->db->println("TRANS saveentity starts $module");
- $this->db->startTransaction();
- foreach ($this->tab_name as $table_name) {
- if ($table_name == "vtiger_crmentity") {
- $this->insertIntoCrmEntity($module, $fileid);
- } else {
- $this->insertIntoEntityTable($table_name, $module, $fileid);
- }
- }
- //Calling the Module specific save code
- $this->save_module($module);
- $this->db->completeTransaction();
- $this->db->println("TRANS saveentity ends");
- // vtlib customization: Hook provide to enable generic module relation.
- if ($_REQUEST['createmode'] == 'link') {
- $for_module = vtlib_purify($_REQUEST['return_module']);
- $for_crmid = vtlib_purify($_REQUEST['return_id']);
- $with_module = $module;
- $with_crmid = $this->id;
- $on_focus = CRMEntity::getInstance($for_module);
- if ($for_module && $for_crmid && $with_module && $with_crmid) {
- relateEntities($on_focus, $for_module, $for_crmid, $with_module, $with_crmid);
- }
- }
- // END
- }
- /**
- * This function is used to upload the attachment in the server and save that attachment information in db.
- * @param int $id - entity id to which the file to be uploaded
- * @param string $module - the current module name
- * @param array $file_details - array which contains the file information(name, type, size, tmp_name and error)
- * return void
- */
- function uploadAndSaveFile($id, $module, $file_details) {
- global $log;
- $log->debug("Entering into uploadAndSaveFile($id,$module,$file_details) method.");
- global $adb, $current_user;
- global $upload_badext;
- $date_var = date("Y-m-d H:i:s");
- //to get the owner id
- $ownerid = $this->column_fields['assigned_user_id'];
- if (!isset($ownerid) || $ownerid == '')
- $ownerid = $current_user->id;
- if (isset($file_details['original_name']) && $file_details['original_name'] != null) {
- $file_name = $file_details['original_name'];
- } else {
- $file_name = $file_details['name'];
- }
- $binFile = sanitizeUploadFileName($file_name, $upload_badext);
- $current_id = $adb->getUniqueID("vtiger_crmentity");
- $filename = ltrim(basename(" " . $binFile)); //allowed filename like UTF-8 characters
- $filetype = $file_details['type'];
- $filesize = $file_details['size'];
- $filetmp_name = $file_details['tmp_name'];
- //get the file path inwhich folder we want to upload the file
- $upload_file_path = decideFilePath();
- //upload the file in server
- $upload_status = move_uploaded_file($filetmp_name, $upload_file_path . $current_id . "_" . $binFile);
- $save_file = 'true';
- //only images are allowed for these modules
- if ($module == 'Contacts' || $module == 'Products') {
- $save_file = validateImageFile($file_details);
- }
- if ($save_file == 'true' && $upload_status == 'true') {
- //This is only to update the attached filename in the vtiger_notes vtiger_table for the Notes module
- if ($module == 'Contacts' || $module == 'Products') {
- $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
- $params1 = array($current_id, $current_user->id, $ownerid, $module . " Image", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
- } else {
- $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
- $params1 = array($current_id, $current_user->id, $ownerid, $module . " Attachment", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
- }
- $adb->pquery($sql1, $params1);
- $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?, ?, ?, ?, ?)";
- $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path);
- $result = $adb->pquery($sql2, $params2);
- if ($_REQUEST['mode'] == 'edit') {
- if ($id != '' && vtlib_purify($_REQUEST['fileid']) != '') {
- $delquery = 'delete from vtiger_seattachmentsrel where crmid = ? and attachmentsid = ?';
- $delparams = array($id, vtlib_purify($_REQUEST['fileid']));
- $adb->pquery($delquery, $delparams);
- }
- }
- if ($module == 'Documents') {
- $query = "delete from vtiger_seattachmentsrel where crmid = ?";
- $qparams = array($id);
- $adb->pquery($query, $qparams);
- }
- if ($module == 'Contacts') {
- $att_sql = "select vtiger_seattachmentsrel.attachmentsid from vtiger_seattachmentsrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seattachmentsrel.attachmentsid where vtiger_crmentity.setype='Contacts Image' and vtiger_seattachmentsrel.crmid=?";
- $res = $adb->pquery($att_sql, array($id));
- $attachmentsid = $adb->query_result($res, 0, 'attachmentsid');
- if ($attachmentsid != '') {
- $delquery = 'delete from vtiger_seattachmentsrel where crmid=? and attachmentsid=?';
- $adb->pquery($delquery, array($id, $attachmentsid));
- $crm_delquery = "delete from vtiger_crmentity where crmid=?";
- $adb->pquery($crm_delquery, array($attachmentsid));
- $sql5 = 'insert into vtiger_seattachmentsrel values(?,?)';
- $adb->pquery($sql5, array($id, $current_id));
- } else {
- $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)';
- $adb->pquery($sql3, array($id, $current_id));
- }
- } else {
- $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)';
- $adb->pquery($sql3, array($id, $current_id));
- }
- return true;
- } else {
- $log->debug("Skip the save attachment process.");
- return false;
- }
- }
- /** Function to insert values in the vtiger_crmentity for the specified module
- * @param $module -- module:: Type varchar
- */
- function insertIntoCrmEntity($module, $fileid = '') {
- global $adb;
- global $current_user;
- global $log;
- if ($fileid != '') {
- $this->id = $fileid;
- $this->mode = 'edit';
- }
- $date_var = date("Y-m-d H:i:s");
- $ownerid = $this->column_fields['assigned_user_id'];
- if(empty($ownerid)) {
- $ownerid = $current_user->id;
- }
- if ($module == 'Events') {
- $module = 'Calendar';
- }
- if ($this->mode == 'edit') {
- $description_val = from_html($this->column_fields['description'], ($insertion_mode == 'edit') ? true : false);
- checkFileAccessForInclusion('user_privileges/user_privileges_' . $current_user->id . '.php');
- require('user_privileges/user_privileges_' . $current_user->id . '.php');
- $tabid = getTabid($module);
- if ($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) {
- $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?,description=?, modifiedtime=? where crmid=?";
- $params = array($ownerid, $current_user->id, $description_val, $adb->formatDate($date_var, true), $this->id);
- } else {
- $profileList = getCurrentUserProfileList();
- $perm_qry = "SELECT 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 = ? AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0 AND vtiger_profile2field.profileid IN (" . generateQuestionMarks($profileList) . ") AND vtiger_def_org_field.visible = 0 and vtiger_field.tablename='vtiger_crmentity' and vtiger_field.displaytype in (1,3) and vtiger_field.presence in (0,2);";
- $perm_result = $adb->pquery($perm_qry, array($tabid, $profileList));
- $perm_rows = $adb->num_rows($perm_result);
- for ($i = 0; $i < $perm_rows; $i++) {
- $columname[] = $adb->query_result($perm_result, $i, "columnname");
- }
- if (is_array($columname) && in_array("description", $columname)) {
- $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?,description=?, modifiedtime=? where crmid=?";
- $params = array($ownerid, $current_user->id, $description_val, $adb->formatDate($date_var, true), $this->id);
- } else {
- $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?, modifiedtime=? where crmid=?";
- $params = array($ownerid, $current_user->id, $adb->formatDate($date_var, true), $this->id);
- }
- }
- $adb->pquery($sql, $params);
- } else {
- //if this is the create mode and the group allocation is chosen, then do the following
- $current_id = $adb->getUniqueID("vtiger_crmentity");
- $_REQUEST['currentid'] = $current_id;
- if ($current_user->id == '')
- $current_user->id = 0;
- // Customization
- $created_date_var = $adb->formatDate($date_var, true);
- $modified_date_var = $adb->formatDate($date_var, true);
- // Preserve the timestamp
- if (self::isBulkSaveMode()) {
- if (!empty($this->column_fields['createdtime']))
- $created_date_var = $adb->formatDate($this->column_fields['createdtime'], true);
- //NOTE : modifiedtime ignored to support vtws_sync API track changes.
- }
- // END
- $description_val = from_html($this->column_fields['description'], ($insertion_mode == 'edit') ? true : false);
- $sql = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,modifiedby,createdtime,modifiedtime) values(?,?,?,?,?,?,?,?)";
- $params = array($current_id, $current_user->id, $ownerid, $module, $description_val, $current_user->id, $created_date_var, $modified_date_var);
- $adb->pquery($sql, $params);
- $this->id = $current_id;
- }
- }
- // Function which returns the value based on result type (array / ADODB ResultSet)
- private function resolve_query_result_value($result, $index, $columnname) {
- global $adb;
- if (is_array($result))
- return $result[$index][$columnname];
- else
- return $adb->query_result($result, $index, $columnname);
- }
- /** Function to insert values in the specifed table for the specified module
- * @param $table_name -- table name:: Type varchar
- * @param $module -- module:: Type varchar
- */
- function insertIntoEntityTable($table_name, $module, $fileid = '') {
- global $log;
- global $current_user, $app_strings;
- $log->info("function insertIntoEntityTable " . $module . ' vtiger_table name ' . $table_name);
- global $adb;
- $insertion_mode = $this->mode;
- //Checkin whether an entry is already is present in the vtiger_table to update
- if ($insertion_mode == 'edit') {
- $tablekey = $this->tab_name_index[$table_name];
- // Make selection on the primary key of the module table to check.
- $check_query = "select $tablekey from $table_name where $tablekey=?";
- $check_result = $adb->pquery($check_query, array($this->id));
- $num_rows = $adb->num_rows($check_result);
- if ($num_rows <= 0) {
- $insertion_mode = '';
- }
- }
- $tabid = getTabid($module);
- if ($module == 'Calendar' && $this->column_fields["activitytype"] != null && $this->column_fields["activitytype"] != 'Task') {
- $tabid = getTabid('Events');
- }
- if ($insertion_mode == 'edit') {
- $update = array();
- $update_params = array();
- checkFileAccessForInclusion('user_privileges/user_privileges_' . $current_user->id . '.php');
- require('user_privileges/user_privileges_' . $current_user->id . '.php');
- if ($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) {
- $sql = "select * from vtiger_field where tabid in (" . generateQuestionMarks($tabid) . ") and tablename=? and displaytype in (1,3) and presence in (0,2) group by columnname";
- $params = array($tabid, $table_name);
- } else {
- $profileList = getCurrentUserProfileList();
- if (count($profileList) > 0) {
- $sql = "SELECT *
- 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 = ?
- AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0
- AND vtiger_profile2field.profileid IN (" . generateQuestionMarks($profileList) . ")
- AND vtiger_def_org_field.visible = 0 and vtiger_field.tablename=? and vtiger_field.displaytype in (1,3) and vtiger_field.presence in (0,2) group by columnname";
- $params = array($tabid, $profileList, $table_name);
- } else {
- $sql = "SELECT *
- 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 = ?
- AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0
- AND vtiger_def_org_field.visible = 0 and vtiger_field.tablename=? and vtiger_field.displaytype in (1,3) and vtiger_field.presence in (0,2) group by columnname";
- $params = array($tabid, $table_name);
- }
- }
- } else {
- $table_index_column = $this->tab_name_index[$table_name];
- if ($table_index_column == 'id' && $table_name == 'vtiger_users') {
- $currentuser_id = $adb->getUniqueID("vtiger_users");
- $this->id = $currentuser_id;
- }
- $column = array($table_index_column);
- $value = array($this->id);
- $sql = "select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4) and vtiger_field.presence in (0,2)";
- $params = array($tabid, $table_name);
- }
- // Attempt to re-use the quer-result to avoid reading for every save operation
- // TODO Need careful analysis on impact ... MEMORY requirement might be more
- static $_privatecache = array();
- $cachekey = "{$insertion_mode}-" . implode(',', $params);
- if (!isset($_privatecache[$cachekey])) {
- $result = $adb->pquery($sql, $params);
- $noofrows = $adb->num_rows($result);
- if (CRMEntity::isBulkSaveMode()) {
- $cacheresult = array();
- for ($i = 0; $i < $noofrows; ++$i) {
- $cacheresult[] = $adb->fetch_array($result);
- }
- $_privatecache[$cachekey] = $cacheresult;
- }
- } else { // Useful when doing bulk save
- $result = $_privatecache[$cachekey];
- $noofrows = count($result);
- }
- for ($i = 0; $i < $noofrows; $i++) {
- $fieldname = $this->resolve_query_result_value($result, $i, "fieldname");
- $columname = $this->resolve_query_result_value($result, $i, "columnname");
- $uitype = $this->resolve_query_result_value($result, $i, "uitype");
- $generatedtype = $this->resolve_query_result_value($result, $i, "generatedtype");
- $typeofdata = $this->resolve_query_result_value($result, $i, "typeofdata");
- $typeofdata_array = explode("~", $typeofdata);
- $datatype = $typeofdata_array[0];
- $ajaxSave = false;
- if (($_REQUEST['file'] == 'DetailViewAjax' && $_REQUEST['ajxaction'] == 'DETAILVIEW'
- && isset($_REQUEST["fldName"]) && $_REQUEST["fldName"] != $fieldname)
- || ($_REQUEST['action'] == 'MassEditSave' && !isset($_REQUEST[$fieldname."_mass_edit_check"]))) {
- $ajaxSave = true;
- }
- if ($uitype == 4 && $insertion_mode != 'edit') {
- $fldvalue = '';
- // Bulk Save Mode: Avoid generation of module sequence number, take care later.
- if (!CRMEntity::isBulkSaveMode())
- $fldvalue = $this->setModuleSeqNumber("increment", $module);
- $this->column_fields[$fieldname] = $fldvalue;
- }
- if (isset($this->column_fields[$fieldname])) {
- if ($uitype == 56) {
- if ($this->column_fields[$fieldname] == 'on' || $this->column_fields[$fieldname] == 1) {
- $fldvalue = '1';
- } else {
- $fldvalue = '0';
- }
- } elseif ($uitype == 15 || $uitype == 16) {
- if ($this->column_fields[$fieldname] == $app_strings['LBL_NOT_ACCESSIBLE']) {
- //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
- $sql = "select $columname from $table_name where " . $this->tab_name_index[$table_name] . "=?";
- $res = $adb->pquery($sql, array($this->id));
- $pick_val = $adb->query_result($res, 0, $columname);
- $fldvalue = $pick_val;
- } else {
- $fldvalue = $this->column_fields[$fieldname];
- }
- } elseif ($uitype == 33) {
- if (is_array($this->column_fields[$fieldname])) {
- $field_list = implode(' |##| ', $this->column_fields[$fieldname]);
- } else {
- $field_list = $this->column_fields[$fieldname];
- }
- $fldvalue = $field_list;
- } elseif ($uitype == 5 || $uitype == 6 || $uitype == 23) {
- //Added to avoid function call getDBInsertDateValue in ajax save
- if (isset($current_user->date_format) && !$ajaxSave) {
- $fldvalue = getValidDBInsertDateValue($this->column_fields[$fieldname]);
- } else {
- $fldvalue = $this->column_fields[$fieldname];
- }
- } elseif ($uitype == 7) {
- //strip out the spaces and commas in numbers if given ie., in amounts there may be ,
- $fldvalue = str_replace(",", "", $this->column_fields[$fieldname]); //trim($this->column_fields[$fieldname],",");
- } elseif ($uitype == 26) {
- if (empty($this->column_fields[$fieldname])) {
- $fldvalue = 1; //the documents will stored in default folder
- } else {
- $fldvalue = $this->column_fields[$fieldname];
- }
- } elseif ($uitype == 28) {
- if ($this->column_fields[$fieldname] == null) {
- $fileQuery = $adb->pquery("SELECT filename from vtiger_notes WHERE notesid = ?", array($this->id));
- $fldvalue = null;
- if (isset($fileQuery)) {
- $rowCount = $adb->num_rows($fileQuery);
- if ($rowCount > 0) {
- $fldvalue = $adb->query_result($fileQuery, 0, 'filename');
- }
- }
- } else {
- $fldvalue = $this->column_fields[$fieldname];
- }
- } elseif ($uitype == 8) {
- $this->column_fields[$fieldname] = rtrim($this->column_fields[$fieldname], ',');
- $ids = explode(',', $this->column_fields[$fieldname]);
- $json = new Zend_Json();
- $fldvalue = $json->encode($ids);
- } elseif ($uitype == 12) {
- // Bulk Sae Mode: Consider the FROM email address as specified, if not lookup
- $fldvalue = $this->column_fields[$fieldname];
- if (empty($fldvalue)) {
- $query = "SELECT email1 FROM vtiger_users WHERE id = ?";
- $res = $adb->pquery($query, array($current_user->id));
- $rows = $adb->num_rows($res);
- if ($rows > 0) {
- $fldvalue = $adb->query_result($res, 0, 'email1');
- }
- }
- // END
- } elseif ($uitype == 72 && !$ajaxSave) {
- // Some of the currency fields like Unit Price, Totoal , Sub-total - doesn't need currency conversion during save
- $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname], null, true);
- } elseif ($uitype == 71 && !$ajaxSave) {
- $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname]);
- } else {
- $fldvalue = $this->column_fields[$fieldname];
- }
- if ($uitype != 33 && $uitype != 8)
- $fldvalue = from_html($fldvalue, ($insertion_mode == 'edit') ? true : false);
- }
- else {
- $fldvalue = '';
- }
- if ($fldvalue == '') {
- $fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
- }
- if ($insertion_mode == 'edit') {
- if ($table_name != 'vtiger_ticketcomments' && $uitype != 4) {
- array_push($update, $columname . "=?");
- array_push($update_params, $fldvalue);
- }
- } else {
- array_push($column, $columname);
- array_push($value, $fldvalue);
- }
- }
- if ($insertion_mode == 'edit') {
- if ($module == 'Potentials') {
- $dbquery = 'select sales_stage from vtiger_potential where potentialid = ?';
- $sales_stage = $adb->query_result($adb->pquery($dbquery, array($this->id)), 0, 'sales_stage');
- if ($sales_stage != $_REQUEST['sales_stage'] && $_REQUEST['sales_stage'] != '') {
- $date_var = date("Y-m-d H:i:s");
- $closingDateField = new DateTimeField($this->column_fields['closingdate']);
- $closingdate = ($_REQUEST['ajxaction'] == 'DETAILVIEW') ? $this->column_fields['closingdate'] : $closingDateField->getDBInsertDateValue();
- $sql = "insert into vtiger_potstagehistory values(?,?,?,?,?,?,?,?)";
- $params = array('', $this->id, $this->column_fields['amount'], decode_html($sales_stage), $this->column_fields['probability'], 0, $adb->formatDate($closingdate, true), $adb->formatDate($date_var, true));
- $adb->pquery($sql, $params);
- }
- } elseif ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
- //added to update the history for PO, SO, Quotes and Invoice
- $history_field_array = Array(
- "PurchaseOrder" => "postatus",
- "SalesOrder" => "sostatus",
- "Quotes" => "quotestage",
- "Invoice" => "invoicestatus"
- );
- $inventory_module = $module;
- if ($_REQUEST['ajxaction'] == 'DETAILVIEW') {//if we use ajax edit
- if ($inventory_module == "PurchaseOrder")
- $relatedname = getVendorName($this->column_fields['vendor_id']);
- else
- $relatedname = getAccountName($this->column_fields['account_id']);
- $total = $this->column_fields['hdnGrandTotal'];
- }
- else {//using edit button and save
- if ($inventory_module == "PurchaseOrder")
- $relatedname = $_REQUEST["vendor_name"];
- else
- $relatedname = $_REQUEST["account_name"];
- $total = $_REQUEST['total'];
- }
- if ($this->column_fields["$history_field_array[$inventory_module]"] == $app_strings['LBL_NOT_ACCESSIBLE']) {
- //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
- $his_col = $history_field_array[$inventory_module];
- $his_sql = "select $his_col from $this->table_name where " . $this->table_index . "=?";
- $his_res = $adb->pquery($his_sql, array($this->id));
- $status_value = $adb->query_result($his_res, 0, $his_col);
- $stat_value = $status_value;
- } else {
- $stat_value = $this->column_fields["$history_field_array[$inventory_module]"];
- }
- $oldvalue = getSingleFieldValue($this->table_name, $history_field_array[$inventory_module], $this->table_index, $this->id);
- if ($this->column_fields["$history_field_array[$inventory_module]"] != '' && $oldvalue != $stat_value) {
- addInventoryHistory($inventory_module, $this->id, $relatedname, $total, $stat_value);
- }
- }
- //Check done by Don. If update is empty the the query fails
- if (count($update) > 0) {
- $sql1 = "update $table_name set " . implode(",", $update) . " where " . $this->tab_name_index[$table_name] . "=?";
- array_push($update_params, $this->id);
- $adb->pquery($sql1, $update_params);
- }
- } else {
- $sql1 = "insert into $table_name(" . implode(",", $column) . ") values(" . generateQuestionMarks($value) . ")";
- $adb->pquery($sql1, $value);
- }
- }
- /** Function to delete a record in the specifed table
- * @param $table_name -- table name:: Type varchar
- * The function will delete a record .The id is obtained from the class variable $this->id and the columnname got from $this->tab_name_index[$table_name]
- */
- function deleteRelation($table_name) {
- global $adb;
- $check_query = "select * from $table_name where " . $this->tab_name_index[$table_name] . "=?";
- $check_result = $adb->pquery($check_query, array($this->id));
- $num_rows = $adb->num_rows($check_result);
- if ($num_rows == 1) {
- $del_query = "DELETE from $table_name where " . $this->tab_name_index[$table_name] . "=?";
- $adb->pquery($del_query, array($this->id));
- }
- }
- /**
- * Function returns the column alias for a field
- * @param <Array> $fieldinfo - field information
- * @return <String> field value
- */
- protected function createColumnAliasForField($fieldinfo) {
- return strtolower($fieldinfo['tablename'] . $fieldinfo['fieldname']);
- }
- /**
- * Retrieve record information of the module
- * @param <Integer> $record - crmid of record
- * @param <String> $module - module name
- */
- function retrieve_entity_info($record, $module) {
- global $adb, $log, $app_strings;
- // INNER JOIN is desirable if all dependent table has entries for the record.
- // LEFT JOIN is desired if the dependent tables does not have entry.
- $join_type = 'LEFT JOIN';
- // Tables which has multiple rows for the same record
- // will be skipped in record retrieve - need to be taken care separately.
- $multirow_tables = NULL;
- if (isset($this->multirow_tables)) {
- $multirow_tables = $this->multirow_tables;
- } else {
- $multirow_tables = array(
- 'vtiger_campaignrelstatus',
- 'vtiger_attachments',
- //'vtiger_inventoryproductrel',
- //'vtiger_cntactivityrel',
- 'vtiger_email_track'
- );
- }
- // Lookup module field cache
- $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
- if ($cachedModuleFields === false) {
- // Pull fields and cache for further use
- $tabid = getTabid($module);
- $sql0 = "SELECT fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata,presence FROM vtiger_field WHERE tabid=?";
- // NOTE: Need to skip in-active fields which we will be done later.
- $result0 = $adb->pquery($sql0, array($tabid));
- if ($adb->num_rows($result0)) {
- while ($resultrow = $adb->fetch_array($result0)) {
- // Update cache
- VTCacheUtils::updateFieldInfo(
- $tabid, $resultrow['fieldname'], $resultrow['fieldid'], $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']
- );
- }
- // Get only active field information
- $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
- }
- }
- if ($cachedModuleFields) {
- $column_clause = '';
- $from_clause = '';
- $where_clause = '';
- $limit_clause = ' LIMIT 1'; // to eliminate multi-records due to table joins.
- $params = array();
- $required_tables = $this->tab_name_index; // copies-on-write
- foreach ($cachedModuleFields as $fieldinfo) {
- if (in_array($fieldinfo['tablename'], $multirow_tables)) {
- continue;
- }
- // Added to avoid picking shipping tax fields for Inventory modules, the shipping tax detail are stored in vtiger_inventoryshippingrel
- // table, but in vtiger_field table we have set tablename as vtiger_inventoryproductrel.
- if(($module == 'Invoice' || $module == 'Quotes' || $module == 'SalesOrder' || $module == 'PurchaseOrder')
- && stripos($fieldinfo['columnname'], 'shtax') !== false) {
- continue;
- }
- // Alias prefixed with tablename+fieldname to avoid duplicate column name across tables
- // fieldname are always assumed to be unique for a module
- $column_clause .= $fieldinfo['tablename'].'.'.$fieldinfo['columnname'].' AS '.$this->createColumnAliasForField($fieldinfo).',';
- }
- $column_clause .= 'vtiger_crmentity.deleted';
- if (isset($required_tables['vtiger_crmentity'])) {
- $from_clause = ' vtiger_crmentity';
- unset($required_tables['vtiger_crmentity']);
- foreach ($required_tables as $tablename => $tableindex) {
- if (in_array($tablename, $multirow_tables)) {
- // Avoid multirow table joins.
- continue;
- }
- $from_clause .= sprintf(' %s %s ON %s.%s=%s.%s', $join_type,
- $tablename, $tablename, $tableindex, 'vtiger_crmentity', 'crmid');
- }
- }
- $where_clause .= ' vtiger_crmentity.crmid=?';
- $params[] = $record;
- $sql = sprintf('SELECT %s FROM %s WHERE %s %s', $column_clause, $from_clause, $where_clause, $limit_clause);
- $result = $adb->pquery($sql, $params);
- if (!$result || $adb->num_rows($result) < 1) {
- throw new Exception($app_strings['LBL_RECORD_NOT_FOUND'], -1);
- } else {
- $resultrow = $adb->query_result_rowdata($result);
- if (!empty($resultrow['deleted'])) {
- throw new Exception($app_strings['LBL_RECORD_DELETE'], 1);
- }
- foreach ($cachedModuleFields as $fieldinfo) {
- $fieldvalue = '';
- $fieldkey = $this->createColumnAliasForField($fieldinfo);
- //Note : value is retrieved with a tablename+fieldname as we are using alias while building query
- if (isset($resultrow[$fieldkey])) {
- $fieldvalue = $resultrow[$fieldkey];
- }
- $this->column_fields[$fieldinfo['fieldname']] = $fieldvalue;
- }
- }
- }
- $this->column_fields['record_id'] = $record;
- $this->column_fields['record_module'] = $module;
- }
- /** Function to saves the values in all the tables mentioned in the class variable $tab_name for the specified module
- * @param $module -- module:: Type varchar
- */
- function save($module_name, $fileid = '') {
- global $log;
- $log->debug("module name is " . $module_name);
- //Event triggering code
- require_once("include/events/include.inc");
- global $adb;
- //In Bulk mode stop triggering events
- if(!self::isBulkSaveMode()) {
- $em = new VTEventsManager($adb);
- // Initialize Event trigger cache
- $em->initTriggerCache();
- $entityData = VTEntityData::fromCRMEntity($this);
- $em->triggerEvent("vtiger.entity.beforesave.modifiable", $entityData);
- $em->triggerEvent("vtiger.entity.beforesave", $entityData);
- $em->triggerEvent("vtiger.entity.beforesave.final", $entityData);
- }
- //Event triggering code ends
- //GS Save entity being called with the modulename as parameter
- $this->saveentity($module_name, $fileid);
- if($em) {
- //Event triggering code
- $em->triggerEvent("vtiger.entity.aftersave", $entityData);
- $em->triggerEvent("vtiger.entity.aftersave.final", $entityData);
- //Event triggering code ends
- }
- }
- function process_list_query($query, $row_offset, $limit = -1, $max_per_page = -1) {
- global $list_max_entries_per_page;
- $this->log->debug("process_list_query: " . $query);
- if (!empty($limit) && $limit != -1) {
- $result = & $this->db->limitQuery($query, $row_offset + 0, $limit, true, "Error retrieving $this->object_name list: ");
- } else {
- $result = & $this->db->query($query, true, "Error retrieving $this->object_name list: ");
- }
- $list = Array();
- if ($max_per_page == -1) {
- $max_per_page = $list_max_entries_per_page;
- }
- $rows_found = $this->db->getRowCount($result);
- $this->log->debug("Found $rows_found " . $this->object_name . "s");
- $previous_offset = $row_offset - $max_per_page;
- $next_offset = $row_offset + $max_per_page;
- if ($rows_found != 0) {
- // We have some data.
- for ($index = $row_offset, $row = $this->db->fetchByAssoc($result, $index); $row && ($index < $row_offset + $max_per_page || $max_per_page == -99); $index++, $row = $this->db->fetchByAssoc($result, $index)) {
- foreach ($this->list_fields as $entry) {
- foreach ($entry as $key => $field) { // this will be cycled only once
- if (isset($row[$field])) {
- $this->column_fields[$this->list_fields_names[$key]] = $row[$field];
- $this->log->debug("$this->object_name({$row['id']}): " . $field . " = " . $this->$field);
- } else {
- $this->column_fields[$this->list_fields_names[$key]] = "";
- }
- }
- }
- //$this->db->println("here is the bug");
- $list[] = clone($this); //added by Richie to support PHP5
- }
- }
- $response = Array();
- $response['list'] = $list;
- $response['row_count'] = $rows_found;
- $response['next_offset'] = $next_offset;
- $response['previous_offset'] = $previous_offset;
- return $response;
- }
- function process_full_list_query($query) {
- $this->log->debug("CRMEntity:process_full_list_query");
- $result = & $this->db->query($query, false);
- //$this->log->debug("CRMEntity:process_full_list_query: result is ".$result);
- if ($this->db->getRowCount($result) > 0) {
- // $this->db->println("process_full mid=".$this->table_index." mname=".$this->module_name);
- // We have some data.
- while ($row = $this->db->fetchByAssoc($result)) {
- $rowid = $row[$this->table_index];
- if (isset($rowid))
- $this->retrieve_entity_info($rowid, $this->module_name);
- else
- $this->db->println("rowid not set unable to retrieve");
- //clone function added to resolvoe PHP5 compatibility issue in Dashboards
- //If we do not use clone, while using PHP5, the memory address remains fixed but the
- //data gets overridden hence all the rows that come in bear the same value. This in turn
- //provides a wrong display of the Dashboard graphs. The data is erroneously shown for a specific month alone
- //Added by Richie
- $list[] = clone($this); //added by Richie to support PHP5
- }
- }
- if (isset($list))
- return $list;
- else
- return null;
- }
- /** This function should be overridden in each module. It marks an item as deleted.
- * If it is not overridden, then marking this type of item is not allowed
- * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
- * All Rights Reserved..
- * Contributor(s): ______________________________________..
- */
- function mark_deleted($id) {
- global $current_user;
- $date_var = date("Y-m-d H:i:s");
- $query = "UPDATE vtiger_crmentity set deleted=1,modifiedtime=?,modifiedby=? where crmid=?";
- $this->db->pquery($query, array($this->db->formatDate($date_var, true), $current_user->id, $id), true, "Error marking record deleted: ");
- }
- function retrieve_by_string_fields($fields_array, $encode = true) {
- $where_clause = $this->get_where($fields_array);
- $query = "SELECT * FROM $this->table_name $where_clause";
- $this->log->debug("Retrieve $this->object_name: " . $query);
- $result = & $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
- if (empty($result)) {
- return null;
- }
- $row = $this->db->fetchByAssoc($result, -1, $encode);
- foreach ($this->column_fields as $field) {
- if (isset($row[$field])) {
- $this->$field = $row[$field];
- }
- }
- return $this;
- }
- // this method is called during an import before inserting a bean
- // define an associative array called $special_fields
- // the keys are user defined, and don't directly map to the bean's vtiger_fields
- // the value is the method name within that bean that will do extra
- // processing for that vtiger_field. example: 'full_name'=>'get_names_from_full_name'
- function process_special_fields() {
- foreach ($this->special_functions as $func_name) {
- if (method_exists($this, $func_name)) {
- $this->$func_name();
- }
- }
- }
- /**
- * Function to check if the custom vtiger_field vtiger_table exists
- * return true or false
- */
- function checkIfCustomTableExists($tablename) {
- global $adb;
- $query = "select * from " . $adb->sql_escape_string($tablename);
- $result = $this->db->pquery($query, array());
- $testrow = $this->db->num_fields($result);
- if ($testrow > 1) {
- $exists = true;
- } else {
- $exists = false;
- }
- return $exists;
- }
- /**
- * function to construct the query to fetch the custom vtiger_fields
- * return the query to fetch the custom vtiger_fields
- */
- function constructCustomQueryAddendum($tablename, $module) {
- global $adb;
- $tabid = getTabid($module);
- $sql1 = "select columnname,fieldlabel from vtiger_field where generatedtype=2 and tabid=? and vtiger_field.presence in (0,2)";
- $result = $adb->pquery($sql1, array($tabid));
- $numRows = $adb->num_rows($result);
- $sql3 = "select ";
- for ($i = 0; $i < $numRows; $i++) {
- $columnName = $adb->query_result($result, $i, "columnname");
- $fieldlabel = $adb->query_result($result, $i, "fieldlabel");
- //construct query as below
- if ($i == 0) {
- $sql3 .= $tablename . "." . $columnName . " '" . $fieldlabel . "'";
- } else {
- $sql3 .= ", " . $tablename . "." . $columnName . " '" . $fieldlabel . "'";
- }
- }
- if ($numRows > 0) {
- $sql3 = $sql3 . ',';
- }
- return $sql3;
- }
- /**
- * This function returns a full (ie non-paged) list of the current object type.
- * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
- * All Rights Reserved..
- * Contributor(s): ______________________________________..
- */
- function get_full_list($order_by = "", $where = "") {
- $this->log->debug("get_full_list: order_by = '$order_by' and where = '$where'");
- $query = $this->create_list_query($order_by, $where);
- return $this->process_full_list_query($query);
- }
- /**
- * Track the viewing of a detail record. This leverages get_summary_text() which is object specific
- * params $user_id - The user that is viewing the record.
- * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
- * All Rights Reserved..
- * Contributor(s): ______________________________________..
- */
- function track_view($user_id, $current_module, $id = '') {
- $this->log->debug("About to call vtiger_tracker (user_id, module_name, item_id)($user_id, $current_module, $this->id)");
- $tracker = new Tracker();
- $tracker->track_view($user_id, $current_module, $id, '');
- }
- /**
- * Function to get the column value of a field when the field value is empty ''
- * @param $columnname -- Column name for the field
- * @param $fldvalue -- Input value for the field taken from the User
- * @param $fieldname -- Name of the Field
- * @param $uitype -- UI type of the field
- * @return Column value of the field.
- */
- function get_column_value($columnname, $fldvalue, $fieldname, $uitype, $datatype = '') {
- global $log;
- $log->debug("Entering function get_column_value ($columnname, $fldvalue, $fieldname, $uitype, $datatype='')");
- // Added for the fields of uitype '57' which has datatype mismatch in crmentity table and particular entity table
- if ($uitype == 57 && $fldvalue == '') {
- return 0;
- }
- if (is_uitype($uitype, "_date_") && $fldvalue == '' || $uitype == '14') {
- return null;
- }
- if ($datatype == 'I' || $datatype == 'N' || $datatype == 'NN') {
- return 0;
- }
- $log->debug("Exiting function get_column_value");
- return $fldvalue;
- }
- /**
- * Function to make change to column fields, depending on the current user's accessibility for the fields
- */
- function apply_field_security($moduleName = '') {
- global $current_user, $currentModule;
- if($moduleName == '') {
- $moduleName = $currentModule;
- }
- require_once('include/utils/UserInfoUtil.php');
- foreach ($this->column_fields as $fieldname => $fieldvalue) {
- $reset_value = false;
- if (getFieldVisibilityPermission($moduleName, $current_user->id, $fieldname) != '0')
- $reset_value = true;
- if ($fieldname == "record_id" || $fieldname == "record_module")
- $reset_value = false;
- /*
- if (isset($this->additional_column_fields) && in_array($fieldname, $this->additional_column_fields) == true)
- $reset_value = false;
- */
- if ($reset_value == true)
- $this->column_fields[$fieldname] = "";
- }
- }
- /**
- * Function invoked during export of module record value.
- */
- function transform_export_value($key, $value) {
- // NOTE: The sub-class can override this function as required.
- return $value;
- }
- /**
- * Function to initialize the importable fields array, based on the User's accessibility to the fields
- */
- function initImportableFields($module) {
- global $current_user, $adb;
- require_once('include/utils/UserInfoUtil.php');
- $skip_uitypes = array('4'); // uitype 4 is for Mod numbers
- // Look at cache if the fields information is available.
- $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
- if ($cachedModuleFields === false) {
- getColumnFields($module); // This API will initialize the cache as well
- // We will succeed now due to above function call
- $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
- }
- $colf = Array();
- if ($cachedModuleFields) {
- foreach ($cachedModuleFields as $fieldinfo) {
- // Skip non-supported fields
- if (in_array($fieldinfo['uitype'], $skip_uitypes)) {
- continue;
- } else {
- $colf[$fieldinfo['fieldname']] = $fieldinfo['uitype'];
- }
- }
- }
- foreach ($colf as $key => $value) {
- if (getFieldVisibilityPermission($module, $current_user->id, $key, 'readwrite') == '0')
- $this->importable_fields[$key] = $value;
- }
- }
- /** Function to initialize the required fields array for that particular module */
- function initRequiredFields($module) {
- global $adb;
- $tabid = getTabId($module);
- $sql = "select * from vtiger_field where tabid= ? and typeofdata like '%M%' and uitype not in ('53','70') and vtiger_field.presence in (0,2)";
- $result = $adb->pquery($sql, array($tabid));
- $numRows = $adb->num_rows($result);
- for ($i = 0; $i < $numRows; $i++) {
- $fieldName = $adb->query_result($result, $i, "fieldname");
- $this->required_fields[$fieldName] = 1;
- }
- }
- /** Function to delete an entity with given Id */
- function trash($module, $id) {
- global $log, $current_user, $adb;
- if(!self::isBulkSaveMode()) {
- require_once("include/events/include.inc");
- $em = new VTEventsManager($adb);
- // Initialize Event trigger cache
- $em->initTriggerCache();
- $entityData = VTEntityData::fromEntityId($adb, $id);
- $em->triggerEvent("vtiger.entity.beforedelete", $entityData);
- }
- $this->mark_deleted($id);
- $this->unlinkDependencies($module, $id);
- require_once('libraries/freetag/freetag.class.php');
- $freetag = new freetag();
- $freetag->delete_all_object_tags_for_user($current_user->id, $id);
- $sql_recentviewed = 'DELETE FROM vtiger_tracker WHERE user_id = ? AND item_id = ?';
- $this->db->pquery($sql_recentviewed, array($current_user->id, $id));
- if($em){
- $em->triggerEvent("vtiger.entity.afterdelete", $entityData);
- }
- }
- /** Function to unlink all the dependent entities of the given Entity by Id */
- function unlinkDependencies($module, $id) {
- global $log;
- $fieldRes = $this->db->pquery('SELECT tabid, tablename, columnname FROM vtiger_field WHERE fieldid IN (
- SELECT fieldid FROM vtiger_fieldmodulerel WHERE relmodule=?)', array($module));
- $numOfFields = $this->db->num_rows($fieldRes);
- for ($i = 0; $i < $numOfFields; $i++) {
- $tabId = $this->db->query_result($fieldRes, $i, 'tabid');
- $tableName = $this->db->query_result($fieldRes, $i, 'tablename');
- $columnName = $this->db->query_result($fieldRes, $i, 'columnname');
- $relatedModule = vtlib_getModuleNameById($tabId);
- $focusObj = CRMEntity::getInstance($relatedModule);
- //Backup Field Relations for the deleted entity
- $targetTableColumn = $focusObj->table_index;
- //While deleting product record the $targetTableColumn should 'id'.
- if ($tableName == 'vtiger_inventoryproductrel') {
- $targetTableColumn = 'id';
- }
- $relQuery = "SELECT $targetTableColumn FROM $tableName WHERE $columnName=?";
- $relResult = $this->db->pquery($relQuery, array($id));
- $numOfRelRecords = $this->db->num_rows($relResult);
- if ($numOfRelRecords > 0) {
- $recordIdsList = array();
- for ($k = 0; $k < $numOfRelRecords; $k++) {
- $recordIdsList[] = $this->db->query_result($relResult, $k, $focusObj->table_index);
- }
- $params = array($id, RB_RECORD_UPDATED, $tableName, $columnName, $focusObj->table_index, implode(",", $recordIdsList));
- $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES (?,?,?,?,?,?)', $params);
- }
- }
- }
- /** Function to unlink an entity with given Id from another entity */
- function unlinkRelationship($id, $return_module, $return_id) {
- global $log, $currentModule;
- $query = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
- $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
- $this->db->pquery($query, $params);
- $fieldRes = $this->db->pquery('SELECT tabid, tablename, columnname FROM vtiger_field WHERE fieldid IN (
- SELECT fieldid FROM vtiger_fieldmodulerel WHERE module=? AND relmodule=?)', array($currentModule, $return_module));
- $numOfFields = $this->db->num_rows($fieldRes);
- for ($i = 0; $i < $numOfFields; $i++) {
- $tabId = $this->db->query_result($fieldRes, $i, 'tabid');
- $tableName = $this->db->query_result($fieldRes, $i, 'tablename');
- $columnName = $this->db->query_result($fieldRes, $i, 'columnname');
- $relatedModule = vtlib_getModuleNameById($tabId);
- $focusObj = CRMEntity::getInstance($relatedModule);
- $updateQuery = "UPDATE $tableName SET $columnName=? WHERE $columnName=? AND $focusObj->table_index=?";
- $updateParams = array(null, $return_id, $id);
- $this->db->pquery($updateQuery, $updateParams);
- }
- }
- /** Function to restore a deleted record of specified module with given crmid
- * @param $module -- module name:: Type varchar
- * @param $entity_ids -- list of crmids :: Array
- */
- function restore($module, $id) {
- global $current_user, $adb;
- $this->db->println("TRANS restore starts $module");
- $this->db->startTransaction();
- $date_var = date("Y-m-d H:i:s");
- $query = 'UPDATE vtiger_crmentity SET deleted=0,modifiedtime=?,modifiedby=? WHERE crmid = ?';
- $this->db->pquery($query, array($this->db->formatDate($date_var, true), $current_user->id, $id), true, "Error restoring records :");
- //Restore related entities/records
- $this->restoreRelatedRecords($module, $id);
- //Event triggering code
- require_once("include/events/include.inc");
- global $adb;
- $em = new VTEventsManager($adb);
- // Initialize Event trigger cache
- $em->initTriggerCache();
- $this->id = $id;
- $entityData = VTEntityData::fromCRMEntity($this);
- //Event triggering code
- $em->triggerEvent("vtiger.entity.afterrestore", $entityData);
- //Event triggering code ends
- $this->db->completeTransaction();
- $this->db->println("TRANS restore ends");
- }
- /** Function to restore all the related records of a given record by id */
- function restoreRelatedRecords($module, $record) {
- $result = $this->db->pquery('SELECT * FROM vtiger_relatedlists_rb WHERE entityid = ?', array($record));
- $numRows = $this->db->num_rows($result);
- for ($i = 0; $i < $numRows; $i++) {
- $action = $this->db->query_result($result, $i, "action");
- $rel_table = $this->db->query_result($result, $i, "rel_table");
- $rel_column = $this->db->query_result($result, $i, "rel_column");
- $ref_column = $this->db->query_result($result, $i, "ref_column");
- $related_crm_ids = $this->db->query_result($result, $i, "related_crm_ids");
- if (strtoupper($action) == RB_RECORD_UPDATED) {
- $related_ids = explode(",", $related_crm_ids);
- if ($rel_table == 'vtiger_crmentity' && $rel_column == 'deleted') {
- $sql = "UPDATE $rel_table set $rel_column = 0 WHERE $ref_column IN (" . generateQuestionMarks($related_ids) . ")";
- $this->db->pquery($sql, array($related_ids));
- } else {
- $sql = "UPDATE $rel_table set $rel_column = ? WHERE $rel_column = 0 AND $ref_column IN (" . generateQuestionMarks($related_ids) . ")";
- $this->db->pquery($sql, array($record, $related_ids));
- }
- } elseif (strtoupper($action) == RB_RECORD_DELETED) {
- if ($rel_table == 'vtiger_seproductrel') {
- $sql = "INSERT INTO $rel_table($rel_column, $ref_column, 'setype') VALUES (?,?,?)";
- $this->db->pquery($sql, array($record, $related_crm_ids, $module));
- } else {
- $sql = "INSERT INTO $rel_table($rel_column, $ref_column) VALUES (?,?)";
- $this->db->pquery($sql, array($record, $related_crm_ids));
- }
- }
- }
- //Clean up the the backup data also after restoring
- $this->db->pquery('DELETE FROM vtiger_relatedlists_rb WHERE entityid = ?', array($record));
- }
- /**
- * Function to initialize the sortby fields array
- */
- function initSortByField($module) {
- global $adb, $log;
- $log->d…
Large files files are truncated, but you can click here to view the full file