Newer
Older
<?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");
#[\AllowDynamicProperties]
/**
* 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();
$focus->moduleName = $module;
$focus->column_fields = new TrackableObject();
$focus->column_fields = getColumnFields($module);
if (method_exists($focus, 'initialize')) $focus->initialize();
/**
* Function which indicates whether to chagne the modified time or not while saving
*/
static function isTimeStampNoChangeMode(){
global $VTIGER_TIMESTAMP_NO_CHANGE_MODE;
if (isset($VTIGER_TIMESTAMP_NO_CHANGE_MODE) && $VTIGER_TIMESTAMP_NO_CHANGE_MODE) {
return true;
}
return false;
}
/**
* Function which will used to initialize object properties
*/
function initialize() {
$moduleName = $this->moduleName;
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
if($moduleModel && !$moduleModel->isEntityModule()) {
return;
}
$userSpecificTableIgnoredModules = array('SMSNotifier', 'PBXManager', 'ModComments');
if(in_array($moduleName, $userSpecificTableIgnoredModules)) return;
$userSpecificTable = Vtiger_Functions::getUserSpecificTableName($moduleName);
if(!in_array($userSpecificTable, $this->tab_name)) {
$this->tab_name[] = $userSpecificTable;
$this->tab_name_index [$userSpecificTable] = 'recordid';
}
}
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>");
}
// added to support files transformation for file upload fields like uitype 69,
if(!empty($_FILES) && php7_count($_FILES)) {
$_FILES = Vtiger_Util_Helper::transformUploadedFiles($_FILES, true);
}
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();
// vtlib customization: Hook provide to enable generic module relation.
if ( (isset($_REQUEST['createmode']) && $_REQUEST['createmode'] == 'link') &&
!isset($_REQUEST['__linkcreated'])) {
$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, $attachmentType='Attachment') {
$log->debug("Entering into uploadAndSaveFile($id,$module) 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'];
}
$save_file = true;
//only images are allowed for Image Attachmenttype
$mimeType = vtlib_mime_content_type($file_details['tmp_name']);
$mimeTypeContents = explode('/', $mimeType);
// For contacts and products we are sending attachmentType as value
if ($attachmentType == 'Image' || ($file_details['size'] && $mimeTypeContents[0] == 'image')) {
$save_file = validateImageFile($file_details);
}
$log->debug("File Validation status in Check1 save_file => $save_file");
if (!$save_file) {
$save_file = true;
//only images are allowed for these modules
if ($module == 'Contacts' || $module == 'Products') {
$save_file = validateImageFile($file_details);
$log->debug("File Validation status in Check2 save_file => $save_file");
$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'];
$filetmp_name = $file_details['tmp_name'];
//get the file path inwhich folder we want to upload the file
$upload_file_path = decideFilePath();
$encryptFileName = Vtiger_Util_Helper::getEncryptedFileName($binFile);
$upload_status = copy($filetmp_name, $upload_file_path . $current_id . "_" . $encryptFileName);
$log->debug("Upload status of file => $upload_status");
if ($save_file && $upload_status == 'true') {
if($attachmentType != 'Image' && $this->mode == 'edit') {
//Only one Attachment per entity delete previous attachments
$res = $adb->pquery('SELECT vtiger_seattachmentsrel.attachmentsid FROM vtiger_seattachmentsrel
INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_seattachmentsrel.attachmentsid AND vtiger_crmentity.setype = ?
WHERE vtiger_seattachmentsrel.crmid = ?',array($module.' Attachment',$id));
$oldAttachmentIds = array();
for($attachItr = 0;$attachItr < $adb->num_rows($res);$attachItr++) {
$oldAttachmentIds[] = $adb->query_result($res,$attachItr,'attachmentsid');
if(php7_count($oldAttachmentIds)) {
$adb->pquery('DELETE FROM vtiger_seattachmentsrel WHERE attachmentsid IN ('.generateQuestionMarks($oldAttachmentIds).')',$oldAttachmentIds);
//TODO : revisit to delete actual file and attachment entry,as we need to see the deleted file in the history when its changed
//$adb->pquery('DELETE FROM vtiger_attachments WHERE attachmentsid IN ('.generateQuestionMarks($oldAttachmentIds).')',$oldAttachmentIds);
//$adb->pquery('DELETE FROM vtiger_crmentity WHERE crmid IN ('.generateQuestionMarks($oldAttachmentIds).')',$oldAttachmentIds);
//Add entry to crmentity
$sql1 = "INSERT INTO vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) VALUES (?, ?, ?, ?, ?, ?, ?)";
$params1 = array($current_id, $current_user->id, $ownerid, $module." ".$attachmentType, $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
$adb->pquery($sql1, $params1);
//Add entry to attachments
$sql2 = "INSERT INTO vtiger_attachments(attachmentsid, name, description, type, path, storedname) values(?, ?, ?, ?, ?, ?)";
$params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path, $encryptFileName);
$adb->pquery($sql2, $params2);
//Add relation
$sql3 = 'INSERT INTO vtiger_seattachmentsrel VALUES(?,?)';
$params3 = array($id, $current_id);
$adb->pquery($sql3, $params3);
$log->debug("File uploaded successfully with id => $current_id");
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 = $current_user->id;
}
if ($module == 'Events') {
$module = 'Calendar';
}
$entityFields = Vtiger_Functions::getEntityModuleInfo($module);
$entityFieldNames = explode(',', $entityFields['fieldname']);
switch ($module) {
case 'HelpDesk': $entityFieldNames = array('ticket_title');
break;
case 'Documents': $entityFieldNames = array('notes_title');
break;
}
$record_label = '';
foreach($entityFieldNames as $entityFieldName) {
$record_label .= $this->column_fields[$entityFieldName]." ";
}
$label = decode_html($record_label);
$this->column_fields['label'] = $label;
if ($this->mode == 'edit') {
$description_val = from_html($this->column_fields['description'], ($insertion_mode == 'edit') ? true : false);
$tabid = getTabid($module);
$modified_date_var = $adb->formatDate($date_var, true);
if(self::isTimeStampNoChangeMode()) {
if(!empty($this->column_fields['modifiedtime'])) {
$modified_date_var = $adb->formatDate($this->column_fields['modifiedtime'], true);
}
}
$acl = Vtiger_AccessControl::loadUserPrivileges($current_user->id);
if ($acl->is_admin == true || $acl->profileGlobalPermission[1] == 0 || $acl->profileGlobalPermission[2] == 0 || $this->isWorkFlowFieldUpdate) {
$sql = "update vtiger_crmentity set smownerid=?, smgroupid=?,modifiedby=?,description=?, modifiedtime=?";
$params = array($ownerid, $groupid, $current_user->id, $description_val, $adb->formatDate($date_var, true));
} 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=?, smgroupid=?, modifiedby=?,description=?, modifiedtime=?";
$params = array($ownerid, $groupid, $current_user->id, $description_val, $adb->formatDate($date_var, true));
$sql = "update vtiger_crmentity set smownerid=?, smgroupid=?,modifiedby=?, modifiedtime=?";
$params = array($ownerid, $groupid, $current_user->id, $adb->formatDate($date_var, true));
if($label) {
$sql .= ", label = ? ";
array_push($params, trim($label));
}
$sql .= " where crmid=?";
array_push($params,$this->id);
$this->column_fields['modifiedtime'] = $modified_date_var;
$this->column_fields['modifiedby'] = $current_user->id;
} 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
if ($this->column_fields['source'] != null && $this->column_fields['source'] != " ") {
$source = strtoupper($this->column_fields['source']);
} else {
$source = strtoupper($this->recordSource);
}
$description_val = from_html($this->column_fields['description'], ($this->mode == 'edit') ? true : false);
$params = array("crmid" => $current_id, "smcreatorid" => $current_user->id, "smownerid" => $ownerid,
"smgroupid" => $groupid, "setype" => $module, "description" => $description_val,
"modifiedby" => $current_user->id, "createdtime" => $created_date_var,
"modifiedtime" => $modified_date_var, "source" => $source);
if($label) {
$params['label'] = trim($label);
}
$insert_columns = array_keys($params);
$insert_data = array_values($params);
$sql = "insert into vtiger_crmentity (".implode(",",$insert_columns).") values(".generateQuestionMarks($insert_data).")";
$this->column_fields['createdtime'] = $created_date_var;
$this->column_fields['modifiedtime'] = $modified_date_var;
$this->column_fields['modifiedby'] = $current_user->id;
//$this->column_fields['created_user_id'] = $current_user->id;
$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;
$table_name = Vtiger_Util_Helper::validateStringForSql($table_name);
$tablekey = $this->tab_name_index[$table_name];
//Checkin whether an entry is already is present in the vtiger_table to update
if ($insertion_mode == 'edit') {
// Make selection on the primary key of the module table to check.
$check_query = "select $tablekey from $table_name where $tablekey=?";
$check_params = array($this->id);
if (Vtiger_Functions::isUserSpecificFieldTable($table_name, $module)) {
$check_query .= ' AND userid=?';
array_push($check_params, $current_user->id);
}
$check_result = $adb->pquery($check_query, $check_params);
$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();
$updateColumnNames = array();
$updateFieldNameColumnNameMap = array();
$acl = Vtiger_AccessControl::loadUserPrivileges($current_user->id);
if ($acl->is_admin == true || $acl->profileGlobalPermission[1] == 0 || $acl->profileGlobalPermission[2] == 0 || $this->isWorkFlowFieldUpdate) {
$sql = "select fieldname,columnname,uitype,generatedtype,
typeofdata from vtiger_field where tabid in (" . generateQuestionMarks($tabid) . ") and tablename=? and displaytype in (1,3,6) and presence in (0,2) group by columnname";
$params = array($tabid, $table_name);
} else {
$profileList = getCurrentUserProfileList();
if (php7_count($profileList) > 0) {
$sql = "SELECT vtiger_field.fieldname,vtiger_field.columnname,vtiger_field.uitype,vtiger_field.generatedtype,vtiger_field.typeofdata 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,6) and vtiger_field.presence in (0,2) group by columnname";
$params = array($tabid, $profileList, $table_name);
} else {
$sql = "SELECT vtiger_field.fieldname,vtiger_field.columnname,vtiger_field.uitype,vtiger_field.generatedtype,vtiger_field.typeofdata 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,6) 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);
if (Vtiger_Functions::isUserSpecificFieldTable($table_name, $module)) {
array_push($column, 'userid');
array_push($value, $current_user->id);
}
$sql = "select fieldname,columnname,uitype,generatedtype,typeofdata from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4,6) 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 = php7_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 ( (isset($_REQUEST['file']) && $_REQUEST['file'] == 'DetailViewAjax') &&
(isset($_REQUEST['ajaxaction']) && $_REQUEST['ajxaction'] == 'DETAILVIEW') &&
(isset($_REQUEST["fldName"]) && $_REQUEST["fldName"] != $fieldname) ||
((isset($_REQUEST['action']) && $_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];
}
} elseif ($uitype == 5 || $uitype == 6 || $uitype == 23) {
//Added to avoid function call getDBInsertDateValue in ajax save
if (isset($current_user->date_format) && !$ajaxSave) {
$fldvalue = getValidDBInsertDateTimeValue($this->column_fields[$fieldname]);
} else {
$fldvalue = $this->column_fields[$fieldname];
}
} elseif ($uitype == 7 || $uitype == 9) {
//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],",");
if (in_array($datatype, array('N', 'NN'))) {
$fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname], $current_user, true);
}
} elseif ($uitype == 1 && in_array($datatype, array('N', 'NN')) && in_array($fieldname, array('qty_per_unit','qtyinstock','salescommission','exciseduty'))) {
$fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname], $current_user, true);
} 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 = decode_html($adb->query_result($fileQuery, 0, 'filename'));
}
}
} else {
$fldvalue = decode_html($this->column_fields[$fieldname]);
}
} elseif ($uitype == 8) {
$this->column_fields[$fieldname] = isset($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]);
} elseif ($uitype == 69) {
$fldvalue = $this->column_fields[$fieldname];
if(php7_count($_FILES)) {
$IMG_FILES = $_FILES[$fieldname];
if($_REQUEST['action'] == 'MassSave' || $_REQUEST['action'] == 'MassEditSave') {
if($IMG_FILES[0]['error'] == 0) {
$oldImageAttachmentIds = array();
$oldAttachmentsRes = $adb->pquery('SELECT vtiger_seattachmentsrel.attachmentsid FROM vtiger_seattachmentsrel
INNER JOIN vtiger_attachments ON vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid
INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_attachments.attachmentsid AND setype = ?
WHERE vtiger_seattachmentsrel.crmid = ?',array($module.' Image',$this->id));
for($itr = 0;$itr < $adb->num_rows($oldAttachmentsRes);$itr++) {
$oldImageAttachmentIds[] = $adb->query_result($oldAttachmentsRes,$itr,'attachmentsid');
}
if(php7_count($oldImageAttachmentIds)) {
$adb->pquery('DELETE FROM vtiger_seattachmentsrel WHERE attachmentsid IN ('.generateQuestionMarks($oldImageAttachmentIds).')',$oldImageAttachmentIds);
$adb->pquery('DELETE FROM vtiger_attachments WHERE attachmentsid IN ('.generateQuestionMarks($oldImageAttachmentIds).')',$oldImageAttachmentIds);
$adb->pquery('DELETE FROM vtiger_crmentity WHERE crmid IN ('.generateQuestionMarks($oldImageAttachmentIds).')',$oldImageAttachmentIds);
}
}
}
$uploadedFileNames = array();
if(php7_count($IMG_FILES)){
foreach($IMG_FILES as $fileIndex => $file) {
if($file['error'] == 0 && $file['name'] != '' && $file['size'] > 0) {
if(isset($_REQUEST[$fileIndex.'_hidden']) && $_REQUEST[$fileIndex.'_hidden'] != '') {
$file['original_name'] = vtlib_purify($_REQUEST[$fileIndex.'_hidden']);
$file['original_name'] = stripslashes($file['name']);
}
$file['original_name'] = str_replace('"','',$file['original_name']);
$attachmentId = $this->uploadAndSaveFile($this->id,$module,$file,'Image');
if($attachmentId) {
$uploadedFileNames[] = $file['name'];
}
}
}
}
if(php7_count($uploadedFileNames)) {
$fldvalue = implode(',',$uploadedFileNames);
} else {
$skipUpdateForField = true;
}
}
if (($insertion_mode == 'edit' && $skipUpdateForField == false) || (isset($_REQUEST['imgDeleted']) && $_REQUEST['imgDeleted'])) {
$skipUpdateForField = false;
$uploadedFileNames = array();
$getImageNamesSql = 'SELECT name FROM vtiger_seattachmentsrel INNER JOIN vtiger_attachments ON
vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid LEFT JOIN '.$table_name.' ON '.
$table_name.'.'.$tablekey.' = vtiger_seattachmentsrel.crmid WHERE vtiger_seattachmentsrel.crmid = ?';
$imageNamesRes = $adb->pquery($getImageNamesSql,array($this->id));
$numOfRows = $adb->num_rows($imageNamesRes);
for($imgItr = 0;$imgItr < $numOfRows;$imgItr++) {
$imageName = $adb->query_result($imageNamesRes,$imgItr,'name');
array_push($uploadedFileNames, decode_html($imageName));
}
$fldvalue = implode(',',$uploadedFileNames);
}
}elseif ($uitype == 61 && php7_count($_FILES)) {
if($module == "ModComments") {
$UPLOADED_FILES = $_FILES[$fieldname];
foreach($UPLOADED_FILES as $fileIndex => $file) {
if($file['error'] == 0 && $file['name'] != '' && $file['size'] > 0) {
if(isset($_REQUEST[$fileIndex.'_hidden']) && $_REQUEST[$fileIndex.'_hidden'] != '') {
$file['original_name'] = vtlib_purify($_REQUEST[$fileIndex.'_hidden']);
} else {
$file['original_name'] = stripslashes($file['name']);
}
$file['original_name'] = str_replace('"','',$file['original_name']);
$attachmentId = $this->uploadAndSaveFile($this->id,$module,$file);
if($attachmentId) {
$uploadedFileNames[] = $attachmentId;
}
}
}
if(php7_count($uploadedFileNames)) {
$fldvalue = implode(',',$uploadedFileNames);
} else {
$skipUpdateForField = true;
}
} else {
$file = $_FILES[$fieldname];
if($file['error'] == 0 && $file['name'] != '' && $file['size'] > 0) {
$attachmentId = $this->uploadAndSaveFile($this->id,$module,$file);
if($attachmentId) $fldvalue = $attachmentId;
} else {
$skipUpdateForField = true;
}
}
} else {
$fldvalue = $this->column_fields[$fieldname];
}
if ($uitype != 33 && $uitype != 8)
$fldvalue = from_html($fldvalue, ($insertion_mode == 'edit') ? true : false);
$fldvalue = '';
}
if ($fldvalue == '') {
$fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
}
if ($insertion_mode == 'edit') {
array_push($update, $columname . "=?");
array_push($update_params, $fldvalue);
array_push($updateColumnNames, $columname);
$updateFieldNameColumnNameMap[$fieldname]=$columname;
}
} else {
array_push($column, $columname);
array_push($value, $fldvalue);
}
}
if ($insertion_mode == 'edit') {
//Track the update and update only when needed - vikas
$updateFieldValues = @array_combine($updateColumnNames, $update_params);
$changedFields = $this->column_fields->getChanged();
if(php7_count($changedFields) > 0) {
$update = array();
$update_params = array();
foreach($changedFields as $field) {
if (!array_key_exists($field, $updateFieldNameColumnNameMap)) {
continue;
}
$fieldColumn = $updateFieldNameColumnNameMap[$field];
if(array_key_exists($fieldColumn, $updateFieldValues)) {
array_push($update, $fieldColumn.'=?');
array_push($update_params, $updateFieldValues[$fieldColumn]);
}
if (php7_count($update) > 0) {
$sql1 = "UPDATE $table_name SET " . implode(",", $update) . " WHERE " . $this->tab_name_index[$table_name] . "=?";
array_push($update_params, $this->id);
if(Vtiger_Functions::isUserSpecificFieldTable($table_name, $module)){
$sql1 .= ' AND userid = ?';
array_push($update_params, $current_user->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;
$table_name = Vtiger_Util_Helper::validateStringForSql($table_name);
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
$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 to attachment filename of the given entity
* @param $notesid -- crmid:: Type Integer
* The function will get the attachmentsid for the given entityid from vtiger_seattachmentsrel table and get the attachmentsname from vtiger_attachments table
* returns the 'filename'
*/
function getOldFileName($notesid) {
global $log;
$log->info("in getOldFileName " . $notesid);
global $adb;
$query1 = "select * from vtiger_seattachmentsrel where crmid=?";
$result = $adb->pquery($query1, array($notesid));
$noofrows = $adb->num_rows($result);
if ($noofrows != 0)
$attachmentid = $adb->query_result($result, 0, 'attachmentsid');
if ($attachmentid != '') {
$query2 = "select * from vtiger_attachments where attachmentsid=?";
$filename = $adb->query_result($adb->pquery($query2, array($attachmentid)), 0, 'name');
}
return $filename;
}
/**
* 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
*/

Satish
committed
function retrieve_entity_info($record, $module, $allowDeleted = false) {
// 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
if($module == 'Calendar' || $module == 'Events') {
getColumnFields('Calendar');
$cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events');
$cachedCalendarFields = VTCacheUtils::lookupFieldInfo_Module('Calendar');
$cachedModuleFields = array_merge($cachedEventsFields, $cachedCalendarFields);
} else {
$cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
}
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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, vtiger_crmentity.label';
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;
}
$joinCondition = "($tablename.$tableindex = vtiger_crmentity.crmid ";
if($current_user && Vtiger_Functions::isUserSpecificFieldTable($tablename, $module)) {
$joinCondition .= " AND $tablename.userid = ".$current_user->id;
}
$joinCondition .= " )";
$from_clause .= sprintf(' %s %s ON %s', $join_type,
$tablename, $joinCondition);
}
}
$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);
// initialize the object
$this->column_fields = new TrackableObject();
if (!$result || $adb->num_rows($result) < 1) {
throw new Exception($app_strings['LBL_RECORD_NOT_FOUND'], -1);
} else {
$resultrow = $adb->query_result_rowdata($result);

Satish
committed
if (!$allowDeleted) {
if (!empty($resultrow['deleted'])) {
throw new Exception($app_strings['LBL_RECORD_DELETE'], 1);
}
if(!empty($resultrow['label'])){
$this->column_fields['label'] = $resultrow['label'];
} else {
// added to compute label needed in event handlers
$entityFields = Vtiger_Functions::getEntityModuleInfo($module);
if(!empty($entityFields['fieldname'])) {
$entityFieldNames = explode(',', $entityFields['fieldname']);
if(php7_count($entityFieldNames) > 1) {
$this->column_fields['label'] = $resultrow[$entityFields['tablename'].$entityFieldNames[0]].' '.$resultrow[$entityFields['tablename'].$entityFieldNames[1]];
} else {
$this->column_fields['label'] = $resultrow[$entityFields['tablename'].$entityFieldNames[0]];
}
}
}
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];
}
// load picklist value with umlatus with explict decoding
// required for field-value strict check during save.
if ($fieldinfo["uitype"] == 15 || $fieldinfo["uitype"] == 16) {
$fieldvalue = decode_html($fieldvalue);
}
$this->column_fields[$fieldinfo['fieldname']] = $fieldvalue;
}
}
}
//adding tags for vtws_retieve
$tagsList = Vtiger_Tag_Model::getAllAccessible($current_user->id, $module, $record);
$tags = array();
foreach($tagsList as $tag) {
$tags[] = $tag->getName();
}
$this->column_fields['tags'] = (php7_count($tags) > 0) ? implode(',',$tags) : '';
}
/** 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 = '') {
$log->debug("module name is " . $module_name);
//Event triggering code
require_once("include/events/include.inc");
//In Bulk mode stop triggering events
if(!self::isBulkSaveMode()) {