PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/data/CRMEntity.php

https://bitbucket.org/thomashii/vtigercrm-5.4-for-postgresql
PHP | 2459 lines | 1723 code | 352 blank | 384 comment | 508 complexity | d2a6623909a927ebb334c50684877297 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  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/vtigercrm/data/CRMEntity.php,v 1.16 2005/04/29 04:21:31 mickie Exp $
  17. * Description: Defines the base class for all data entities used throughout the
  18. * application. The base class including its methods and variables is designed to
  19. * be overloaded with module-specific methods and variables particular to the
  20. * module's base entity class.
  21. ********************************************************************************/
  22. include_once('config.php');
  23. require_once('include/logging.php');
  24. require_once('data/Tracker.php');
  25. require_once('include/utils/utils.php');
  26. require_once('include/utils/UserInfoUtil.php');
  27. require_once("include/Zend/Json.php");
  28. class CRMEntity {
  29. var $ownedby;
  30. /**
  31. * Detect if we are in bulk save mode, where some features can be turned-off
  32. * to improve performance.
  33. */
  34. static function isBulkSaveMode() {
  35. global $VTIGER_BULK_SAVE_MODE;
  36. if (isset($VTIGER_BULK_SAVE_MODE) && $VTIGER_BULK_SAVE_MODE) {
  37. return true;
  38. }
  39. return false;
  40. }
  41. static function getInstance($module) {
  42. $modName = $module;
  43. if ($module == 'Calendar' || $module == 'Events') {
  44. $module = 'Calendar';
  45. $modName = 'Activity';
  46. }
  47. // File access security check
  48. if (!class_exists($modName)) {
  49. checkFileAccessForInclusion("modules/$module/$modName.php");
  50. require_once("modules/$module/$modName.php");
  51. }
  52. $focus = new $modName();
  53. return $focus;
  54. }
  55. function saveentity($module, $fileid = '') {
  56. global $current_user, $adb; //$adb added by raju for mass mailing
  57. $insertion_mode = $this->mode;
  58. $columnFields = $this->column_fields;
  59. $anyValue = false;
  60. foreach ($columnFields as $value) {
  61. if(!empty($value)) {
  62. $anyValue = true;
  63. break;
  64. }
  65. }
  66. if(!$anyValue) {
  67. die("<center>" .getTranslatedString('LBL_MANDATORY_FIELD_MISSING')."</center>");
  68. }
  69. $this->db->println("TRANS saveentity starts $module");
  70. $this->db->startTransaction();
  71. foreach ($this->tab_name as $table_name) {
  72. if ($table_name == "vtiger_crmentity") {
  73. $this->insertIntoCrmEntity($module, $fileid);
  74. } else {
  75. $this->insertIntoEntityTable($table_name, $module, $fileid);
  76. }
  77. }
  78. //Calling the Module specific save code
  79. $this->save_module($module);
  80. $this->db->completeTransaction();
  81. $this->db->println("TRANS saveentity ends");
  82. // vtlib customization: Hook provide to enable generic module relation.
  83. if ($_REQUEST['createmode'] == 'link') {
  84. $for_module = vtlib_purify($_REQUEST['return_module']);
  85. $for_crmid = vtlib_purify($_REQUEST['return_id']);
  86. $with_module = $module;
  87. $with_crmid = $this->id;
  88. $on_focus = CRMEntity::getInstance($for_module);
  89. if ($for_module && $for_crmid && $with_module && $with_crmid) {
  90. relateEntities($on_focus, $for_module, $for_crmid, $with_module, $with_crmid);
  91. }
  92. }
  93. // END
  94. }
  95. function insertIntoAttachment1($id, $module, $filedata, $filename, $filesize, $filetype, $user_id) {
  96. $date_var = date("Y-m-d H:i:s");
  97. global $current_user;
  98. global $adb;
  99. //global $root_directory;
  100. global $log;
  101. $ownerid = $user_id;
  102. if ($filesize != 0) {
  103. $data = base64_encode(fread(fopen($filedata, "r"), $filesize));
  104. }
  105. $current_id = $adb->getUniqueID("vtiger_crmentity");
  106. if ($module == 'Emails') {
  107. $log->info("module is " . $module);
  108. $idname = 'emailid';
  109. $tablename = 'emails';
  110. $descname = 'description';
  111. } else {
  112. $idname = 'notesid';
  113. $tablename = 'notes';
  114. $descname = 'notecontent';
  115. }
  116. $sql = "update $tablename set filename=? where $idname=?";
  117. $params = array($filename, $id);
  118. $adb->pquery($sql, $params);
  119. $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
  120. $params1 = array($current_id, $current_user->id, $ownerid, $module . " Attachment", '', $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
  121. $adb->pquery($sql1, $params1);
  122. $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type) values(?, ?, ?, ?)";
  123. $params2 = array($current_id, $filename, '', $filetype);
  124. $result = $adb->pquery($sql2, $params2);
  125. //TODO -- instead of put contents in db now we should store the file in harddisk
  126. $sql3 = 'insert into vtiger_seattachmentsrel values(?, ?)';
  127. $params3 = array($id, $current_id);
  128. $adb->pquery($sql3, $params3);
  129. }
  130. /**
  131. * This function is used to upload the attachment in the server and save that attachment information in db.
  132. * @param int $id - entity id to which the file to be uploaded
  133. * @param string $module - the current module name
  134. * @param array $file_details - array which contains the file information(name, type, size, tmp_name and error)
  135. * return void
  136. */
  137. function uploadAndSaveFile($id, $module, $file_details) {
  138. global $log;
  139. $log->debug("Entering into uploadAndSaveFile($id,$module,$file_details) method.");
  140. global $adb, $current_user;
  141. global $upload_badext;
  142. $date_var = date("Y-m-d H:i:s");
  143. //to get the owner id
  144. $ownerid = $this->column_fields['assigned_user_id'];
  145. if (!isset($ownerid) || $ownerid == '')
  146. $ownerid = $current_user->id;
  147. if (isset($file_details['original_name']) && $file_details['original_name'] != null) {
  148. $file_name = $file_details['original_name'];
  149. } else {
  150. $file_name = $file_details['name'];
  151. }
  152. $binFile = sanitizeUploadFileName($file_name, $upload_badext);
  153. $current_id = $adb->getUniqueID("vtiger_crmentity");
  154. $filename = ltrim(basename(" " . $binFile)); //allowed filename like UTF-8 characters
  155. $filetype = $file_details['type'];
  156. $filesize = $file_details['size'];
  157. $filetmp_name = $file_details['tmp_name'];
  158. //get the file path inwhich folder we want to upload the file
  159. $upload_file_path = decideFilePath();
  160. //upload the file in server
  161. $upload_status = move_uploaded_file($filetmp_name, $upload_file_path . $current_id . "_" . $binFile);
  162. $save_file = 'true';
  163. //only images are allowed for these modules
  164. if ($module == 'Contacts' || $module == 'Products') {
  165. $save_file = validateImageFile($file_details);
  166. }
  167. if ($save_file == 'true' && $upload_status == 'true') {
  168. //This is only to update the attached filename in the vtiger_notes vtiger_table for the Notes module
  169. if ($module == 'Contacts' || $module == 'Products') {
  170. $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
  171. $params1 = array($current_id, $current_user->id, $ownerid, $module . " Image", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
  172. } else {
  173. $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
  174. $params1 = array($current_id, $current_user->id, $ownerid, $module . " Attachment", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
  175. }
  176. $adb->pquery($sql1, $params1);
  177. $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?, ?, ?, ?, ?)";
  178. $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path);
  179. $result = $adb->pquery($sql2, $params2);
  180. if ($_REQUEST['mode'] == 'edit') {
  181. if ($id != '' && $_REQUEST['fileid'] != '') {
  182. $delquery = 'delete from vtiger_seattachmentsrel where crmid = ? and attachmentsid = ?';
  183. $delparams = array($id, $_REQUEST['fileid']);
  184. $adb->pquery($delquery, $delparams);
  185. }
  186. }
  187. if ($module == 'Documents') {
  188. $query = "delete from vtiger_seattachmentsrel where crmid = ?";
  189. $qparams = array($id);
  190. $adb->pquery($query, $qparams);
  191. }
  192. if ($module == 'Contacts') {
  193. $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=?";
  194. $res = $adb->pquery($att_sql, array($id));
  195. $attachmentsid = $adb->query_result($res, 0, 'attachmentsid');
  196. if ($attachmentsid != '') {
  197. $delquery = 'delete from vtiger_seattachmentsrel where crmid=? and attachmentsid=?';
  198. $adb->pquery($delquery, array($id, $attachmentsid));
  199. $crm_delquery = "delete from vtiger_crmentity where crmid=?";
  200. $adb->pquery($crm_delquery, array($attachmentsid));
  201. $sql5 = 'insert into vtiger_seattachmentsrel values(?,?)';
  202. $adb->pquery($sql5, array($id, $current_id));
  203. } else {
  204. $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)';
  205. $adb->pquery($sql3, array($id, $current_id));
  206. }
  207. } else {
  208. $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)';
  209. $adb->pquery($sql3, array($id, $current_id));
  210. }
  211. return true;
  212. } else {
  213. $log->debug("Skip the save attachment process.");
  214. return false;
  215. }
  216. }
  217. /** Function to insert values in the vtiger_crmentity for the specified module
  218. * @param $module -- module:: Type varchar
  219. */
  220. function insertIntoCrmEntity($module, $fileid = '') {
  221. global $adb;
  222. global $current_user;
  223. global $log;
  224. if ($fileid != '') {
  225. $this->id = $fileid;
  226. $this->mode = 'edit';
  227. }
  228. $date_var = date("Y-m-d H:i:s");
  229. $ownerid = $this->column_fields['assigned_user_id'];
  230. $sql = "select ownedby from vtiger_tab where name=?";
  231. $res = $adb->pquery($sql, array($module));
  232. $this->ownedby = $adb->query_result($res, 0, 'ownedby');
  233. if ($this->ownedby == 1) {
  234. $log->info("module is =" . $module);
  235. $ownerid = $current_user->id;
  236. }
  237. // Asha - Change ownerid from '' to null since its an integer field.
  238. // It is empty for modules like Invoice/Quotes/SO/PO which do not have Assigned to field
  239. if ($ownerid === '')
  240. $ownerid = 0;
  241. if ($module == 'Events') {
  242. $module = 'Calendar';
  243. }
  244. if ($this->mode == 'edit') {
  245. $description_val = from_html($this->column_fields['description'], ($insertion_mode == 'edit') ? true : false);
  246. require('user_privileges/user_privileges_' . $current_user->id . '.php');
  247. $tabid = getTabid($module);
  248. if ($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) {
  249. $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?,description=?, modifiedtime=? where crmid=?";
  250. $params = array($ownerid, $current_user->id, $description_val, $adb->formatDate($date_var, true), $this->id);
  251. } else {
  252. $profileList = getCurrentUserProfileList();
  253. $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);";
  254. $perm_result = $adb->pquery($perm_qry, array($tabid, $profileList));
  255. $perm_rows = $adb->num_rows($perm_result);
  256. for ($i = 0; $i < $perm_rows; $i++) {
  257. $columname[] = $adb->query_result($perm_result, $i, "columnname");
  258. }
  259. if (is_array($columname) && in_array("description", $columname)) {
  260. $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?,description=?, modifiedtime=? where crmid=?";
  261. $params = array($ownerid, $current_user->id, $description_val, $adb->formatDate($date_var, true), $this->id);
  262. } else {
  263. $sql = "update vtiger_crmentity set smownerid=?,modifiedby=?, modifiedtime=? where crmid=?";
  264. $params = array($ownerid, $current_user->id, $adb->formatDate($date_var, true), $this->id);
  265. }
  266. }
  267. $adb->pquery($sql, $params);
  268. $sql1 = "delete from vtiger_ownernotify where crmid=?";
  269. $params1 = array($this->id);
  270. $adb->pquery($sql1, $params1);
  271. if ($ownerid != $current_user->id) {
  272. $sql1 = "insert into vtiger_ownernotify values(?,?,?)";
  273. $params1 = array($this->id, $ownerid, null);
  274. $adb->pquery($sql1, $params1);
  275. }
  276. } else {
  277. //if this is the create mode and the group allocation is chosen, then do the following
  278. $current_id = $adb->getUniqueID("vtiger_crmentity");
  279. $_REQUEST['currentid'] = $current_id;
  280. if ($current_user->id == '')
  281. $current_user->id = 0;
  282. // Customization
  283. $created_date_var = $adb->formatDate($date_var, true);
  284. $modified_date_var = $adb->formatDate($date_var, true);
  285. // Preserve the timestamp
  286. if (self::isBulkSaveMode()) {
  287. if (!empty($this->column_fields['createdtime']))
  288. $created_date_var = $adb->formatDate($this->column_fields['createdtime'], true);
  289. //NOTE : modifiedtime ignored to support vtws_sync API track changes.
  290. }
  291. // END
  292. $description_val = from_html($this->column_fields['description'], ($insertion_mode == 'edit') ? true : false);
  293. $sql = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,modifiedby,createdtime,modifiedtime) values(?,?,?,?,?,?,?,?)";
  294. $params = array($current_id, $current_user->id, $ownerid, $module, $description_val, $current_user->id, $created_date_var, $modified_date_var);
  295. $adb->pquery($sql, $params);
  296. $this->id = $current_id;
  297. }
  298. }
  299. // Function which returns the value based on result type (array / ADODB ResultSet)
  300. private function resolve_query_result_value($result, $index, $columnname) {
  301. global $adb;
  302. if (is_array($result))
  303. return $result[$index][$columnname];
  304. else
  305. return $adb->query_result($result, $index, $columnname);
  306. }
  307. /** Function to insert values in the specifed table for the specified module
  308. * @param $table_name -- table name:: Type varchar
  309. * @param $module -- module:: Type varchar
  310. */
  311. function insertIntoEntityTable($table_name, $module, $fileid = '') {
  312. global $log;
  313. global $current_user, $app_strings;
  314. $log->info("function insertIntoEntityTable " . $module . ' vtiger_table name ' . $table_name);
  315. global $adb;
  316. $insertion_mode = $this->mode;
  317. //Checkin whether an entry is already is present in the vtiger_table to update
  318. if ($insertion_mode == 'edit') {
  319. $tablekey = $this->tab_name_index[$table_name];
  320. // Make selection on the primary key of the module table to check.
  321. $check_query = "select $tablekey from $table_name where $tablekey=?";
  322. $check_result = $adb->pquery($check_query, array($this->id));
  323. $num_rows = $adb->num_rows($check_result);
  324. if ($num_rows <= 0) {
  325. $insertion_mode = '';
  326. }
  327. }
  328. $tabid = getTabid($module);
  329. if ($module == 'Calendar' && $this->column_fields["activitytype"] != null && $this->column_fields["activitytype"] != 'Task') {
  330. $tabid = getTabid('Events');
  331. }
  332. if ($insertion_mode == 'edit') {
  333. $update = array();
  334. $update_params = array();
  335. require('user_privileges/user_privileges_' . $current_user->id . '.php');
  336. if ($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) {
  337. $sql = "select distinct on (columnname) * from vtiger_field where tabid in (" . generateQuestionMarks($tabid) . ") and tablename=? and displaytype in (1,3) and presence in (0,2) order by columnname";
  338. $params = array($tabid, $table_name);
  339. } else {
  340. $profileList = getCurrentUserProfileList();
  341. if (count($profileList) > 0) {
  342. $sql = "SELECT distinct on (columnname) *
  343. FROM vtiger_field
  344. INNER JOIN vtiger_profile2field
  345. ON vtiger_profile2field.fieldid = vtiger_field.fieldid
  346. INNER JOIN vtiger_def_org_field
  347. ON vtiger_def_org_field.fieldid = vtiger_field.fieldid
  348. WHERE vtiger_field.tabid = ?
  349. AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0
  350. AND vtiger_profile2field.profileid IN (" . generateQuestionMarks($profileList) . ")
  351. 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) order by columnname";
  352. $params = array($tabid, $profileList, $table_name);
  353. } else {
  354. $sql = "SELECT distinct on (columnname) *
  355. FROM vtiger_field
  356. INNER JOIN vtiger_profile2field
  357. ON vtiger_profile2field.fieldid = vtiger_field.fieldid
  358. INNER JOIN vtiger_def_org_field
  359. ON vtiger_def_org_field.fieldid = vtiger_field.fieldid
  360. WHERE vtiger_field.tabid = ?
  361. AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0
  362. 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) order by columnname";
  363. $params = array($tabid, $table_name);
  364. }
  365. }
  366. } else {
  367. $table_index_column = $this->tab_name_index[$table_name];
  368. if ($table_index_column == 'id' && $table_name == 'vtiger_users') {
  369. $currentuser_id = $adb->getUniqueID("vtiger_users");
  370. $this->id = $currentuser_id;
  371. }
  372. $column = array($table_index_column);
  373. $value = array($this->id);
  374. $sql = "select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4) and vtiger_field.presence in (0,2)";
  375. $params = array($tabid, $table_name);
  376. }
  377. // Attempt to re-use the quer-result to avoid reading for every save operation
  378. // TODO Need careful analysis on impact ... MEMORY requirement might be more
  379. static $_privatecache = array();
  380. $cachekey = "{$insertion_mode}-" . implode(',', $params);
  381. if (!isset($_privatecache[$cachekey])) {
  382. $result = $adb->pquery($sql, $params);
  383. $noofrows = $adb->num_rows($result);
  384. if (CRMEntity::isBulkSaveMode()) {
  385. $cacheresult = array();
  386. for ($i = 0; $i < $noofrows; ++$i) {
  387. $cacheresult[] = $adb->fetch_array($result);
  388. }
  389. $_privatecache[$cachekey] = $cacheresult;
  390. }
  391. } else { // Useful when doing bulk save
  392. $result = $_privatecache[$cachekey];
  393. $noofrows = count($result);
  394. }
  395. for ($i = 0; $i < $noofrows; $i++) {
  396. $fieldname = $this->resolve_query_result_value($result, $i, "fieldname");
  397. $columname = $this->resolve_query_result_value($result, $i, "columnname");
  398. $uitype = $this->resolve_query_result_value($result, $i, "uitype");
  399. $generatedtype = $this->resolve_query_result_value($result, $i, "generatedtype");
  400. $typeofdata = $this->resolve_query_result_value($result, $i, "typeofdata");
  401. $typeofdata_array = explode("~", $typeofdata);
  402. $datatype = $typeofdata_array[0];
  403. $ajaxSave = false;
  404. if (($_REQUEST['file'] == 'DetailViewAjax' && $_REQUEST['ajxaction'] == 'DETAILVIEW'
  405. && isset($_REQUEST["fldName"]) && $_REQUEST["fldName"] != $fieldname)
  406. || ($_REQUEST['action'] == 'MassEditSave' && !isset($_REQUEST[$fieldname."_mass_edit_check"]))) {
  407. $ajaxSave = true;
  408. }
  409. if ($uitype == 4 && $insertion_mode != 'edit') {
  410. $fldvalue = '';
  411. // Bulk Save Mode: Avoid generation of module sequence number, take care later.
  412. if (!CRMEntity::isBulkSaveMode())
  413. $fldvalue = $this->setModuleSeqNumber("increment", $module);
  414. $this->column_fields[$fieldname] = $fldvalue;
  415. }
  416. if (isset($this->column_fields[$fieldname])) {
  417. if ($uitype == 56) {
  418. if ($this->column_fields[$fieldname] == 'on' || $this->column_fields[$fieldname] == 1) {
  419. $fldvalue = '1';
  420. } else {
  421. $fldvalue = '0';
  422. }
  423. } elseif ($uitype == 15 || $uitype == 16) {
  424. if ($this->column_fields[$fieldname] == $app_strings['LBL_NOT_ACCESSIBLE']) {
  425. //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
  426. $sql = "select $columname from $table_name where " . $this->tab_name_index[$table_name] . "=?";
  427. $res = $adb->pquery($sql, array($this->id));
  428. $pick_val = $adb->query_result($res, 0, $columname);
  429. $fldvalue = $pick_val;
  430. } else {
  431. $fldvalue = $this->column_fields[$fieldname];
  432. }
  433. } elseif ($uitype == 33) {
  434. if (is_array($this->column_fields[$fieldname])) {
  435. $field_list = implode(' |##| ', $this->column_fields[$fieldname]);
  436. } else {
  437. $field_list = $this->column_fields[$fieldname];
  438. }
  439. $fldvalue = $field_list;
  440. } elseif ($uitype == 5 || $uitype == 6 || $uitype == 23) {
  441. //Added to avoid function call getDBInsertDateValue in ajax save
  442. if (isset($current_user->date_format) && !$ajaxSave) {
  443. $fldvalue = getValidDBInsertDateValue($this->column_fields[$fieldname]);
  444. } else {
  445. $fldvalue = $this->column_fields[$fieldname];
  446. }
  447. } elseif ($uitype == 7) {
  448. //strip out the spaces and commas in numbers if given ie., in amounts there may be ,
  449. $fldvalue = str_replace(",", "", $this->column_fields[$fieldname]); //trim($this->column_fields[$fieldname],",");
  450. } elseif ($uitype == 26) {
  451. if (empty($this->column_fields[$fieldname])) {
  452. $fldvalue = 1; //the documents will stored in default folder
  453. } else {
  454. $fldvalue = $this->column_fields[$fieldname];
  455. }
  456. } elseif ($uitype == 28) {
  457. if ($this->column_fields[$fieldname] == null) {
  458. $fileQuery = $adb->pquery("SELECT filename from vtiger_notes WHERE notesid = ?", array($this->id));
  459. $fldvalue = null;
  460. if (isset($fileQuery)) {
  461. $rowCount = $adb->num_rows($fileQuery);
  462. if ($rowCount > 0) {
  463. $fldvalue = $adb->query_result($fileQuery, 0, 'filename');
  464. }
  465. }
  466. } else {
  467. $fldvalue = $this->column_fields[$fieldname];
  468. }
  469. } elseif ($uitype == 8) {
  470. $this->column_fields[$fieldname] = rtrim($this->column_fields[$fieldname], ',');
  471. $ids = explode(',', $this->column_fields[$fieldname]);
  472. $json = new Zend_Json();
  473. $fldvalue = $json->encode($ids);
  474. } elseif ($uitype == 12) {
  475. // Bulk Sae Mode: Consider the FROM email address as specified, if not lookup
  476. $fldvalue = $this->column_fields[$fieldname];
  477. if (empty($fldvalue)) {
  478. $query = "SELECT email1 FROM vtiger_users WHERE id = ?";
  479. $res = $adb->pquery($query, array($current_user->id));
  480. $rows = $adb->num_rows($res);
  481. if ($rows > 0) {
  482. $fldvalue = $adb->query_result($res, 0, 'email1');
  483. }
  484. }
  485. // END
  486. } elseif ($uitype == 72 && !$ajaxSave) {
  487. // Some of the currency fields like Unit Price, Totoal , Sub-total - doesn't need currency conversion during save
  488. $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname], null, true);
  489. } elseif ($uitype == 71 && !$ajaxSave) {
  490. $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname]);
  491. } else {
  492. $fldvalue = $this->column_fields[$fieldname];
  493. }
  494. if ($uitype != 33 && $uitype != 8)
  495. $fldvalue = from_html($fldvalue, ($insertion_mode == 'edit') ? true : false);
  496. }
  497. else {
  498. $fldvalue = '';
  499. }
  500. if ($fldvalue == '') {
  501. $fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
  502. }
  503. if ($insertion_mode == 'edit') {
  504. if ($table_name != 'vtiger_ticketcomments' && $uitype != 4) {
  505. array_push($update, $columname . "=?");
  506. array_push($update_params, $fldvalue);
  507. }
  508. } else {
  509. array_push($column, $columname);
  510. array_push($value, $fldvalue);
  511. }
  512. }
  513. if ($insertion_mode == 'edit') {
  514. if ($module == 'Potentials') {
  515. $dbquery = 'select sales_stage from vtiger_potential where potentialid = ?';
  516. $sales_stage = $adb->query_result($adb->pquery($dbquery, array($this->id)), 0, 'sales_stage');
  517. if ($sales_stage != $_REQUEST['sales_stage'] && $_REQUEST['sales_stage'] != '') {
  518. $date_var = date("Y-m-d H:i:s");
  519. $closingDateField = new DateTimeField($this->column_fields['closingdate']);
  520. $closingdate = ($_REQUEST['ajxaction'] == 'DETAILVIEW') ? $this->column_fields['closingdate'] : $closingDateField->getDBInsertDateValue();
  521. $sql = "insert into vtiger_potstagehistory values(?,?,?,?,?,?,?,?)";
  522. $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));
  523. $adb->pquery($sql, $params);
  524. }
  525. } elseif ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
  526. //added to update the history for PO, SO, Quotes and Invoice
  527. $history_field_array = Array(
  528. "PurchaseOrder" => "postatus",
  529. "SalesOrder" => "sostatus",
  530. "Quotes" => "quotestage",
  531. "Invoice" => "invoicestatus"
  532. );
  533. $inventory_module = $module;
  534. if ($_REQUEST['ajxaction'] == 'DETAILVIEW') {//if we use ajax edit
  535. if ($inventory_module == "PurchaseOrder")
  536. $relatedname = getVendorName($this->column_fields['vendor_id']);
  537. else
  538. $relatedname = getAccountName($this->column_fields['account_id']);
  539. $total = $this->column_fields['hdnGrandTotal'];
  540. }
  541. else {//using edit button and save
  542. if ($inventory_module == "PurchaseOrder")
  543. $relatedname = $_REQUEST["vendor_name"];
  544. else
  545. $relatedname = $_REQUEST["account_name"];
  546. $total = $_REQUEST['total'];
  547. }
  548. if ($this->column_fields["$history_field_array[$inventory_module]"] == $app_strings['LBL_NOT_ACCESSIBLE']) {
  549. //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
  550. $his_col = $history_field_array[$inventory_module];
  551. $his_sql = "select $his_col from $this->table_name where " . $this->table_index . "=?";
  552. $his_res = $adb->pquery($his_sql, array($this->id));
  553. $status_value = $adb->query_result($his_res, 0, $his_col);
  554. $stat_value = $status_value;
  555. } else {
  556. $stat_value = $this->column_fields["$history_field_array[$inventory_module]"];
  557. }
  558. $oldvalue = getSingleFieldValue($this->table_name, $history_field_array[$inventory_module], $this->table_index, $this->id);
  559. if ($this->column_fields["$history_field_array[$inventory_module]"] != '' && $oldvalue != $stat_value) {
  560. addInventoryHistory($inventory_module, $this->id, $relatedname, $total, $stat_value);
  561. }
  562. }
  563. //Check done by Don. If update is empty the the query fails
  564. if (count($update) > 0) {
  565. $sql1 = "update $table_name set " . implode(",", $update) . " where " . $this->tab_name_index[$table_name] . "=?";
  566. array_push($update_params, $this->id);
  567. $adb->pquery($sql1, $update_params);
  568. }
  569. } else {
  570. $sql1 = "insert into $table_name(" . implode(",", $column) . ") values(" . generateQuestionMarks($value) . ")";
  571. $adb->pquery($sql1, $value);
  572. }
  573. }
  574. /** Function to delete a record in the specifed table
  575. * @param $table_name -- table name:: Type varchar
  576. * 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]
  577. */
  578. function deleteRelation($table_name) {
  579. global $adb;
  580. $check_query = "select * from $table_name where " . $this->tab_name_index[$table_name] . "=?";
  581. $check_result = $adb->pquery($check_query, array($this->id));
  582. $num_rows = $adb->num_rows($check_result);
  583. if ($num_rows == 1) {
  584. $del_query = "DELETE from $table_name where " . $this->tab_name_index[$table_name] . "=?";
  585. $adb->pquery($del_query, array($this->id));
  586. }
  587. }
  588. /** Function to attachment filename of the given entity
  589. * @param $notesid -- crmid:: Type Integer
  590. * The function will get the attachmentsid for the given entityid from vtiger_seattachmentsrel table and get the attachmentsname from vtiger_attachments table
  591. * returns the 'filename'
  592. */
  593. function getOldFileName($notesid) {
  594. global $log;
  595. $log->info("in getOldFileName " . $notesid);
  596. global $adb;
  597. $query1 = "select * from vtiger_seattachmentsrel where crmid=?";
  598. $result = $adb->pquery($query1, array($notesid));
  599. $noofrows = $adb->num_rows($result);
  600. if ($noofrows != 0)
  601. $attachmentid = $adb->query_result($result, 0, 'attachmentsid');
  602. if ($attachmentid != '') {
  603. $query2 = "select * from vtiger_attachments where attachmentsid=?";
  604. $filename = $adb->query_result($adb->pquery($query2, array($attachmentid)), 0, 'name');
  605. }
  606. return $filename;
  607. }
  608. // Code included by Jaguar - Ends
  609. /** Function to retrive the information of the given recordid ,module
  610. * @param $record -- Id:: Type Integer
  611. * @param $module -- module:: Type varchar
  612. * This function retrives the information from the database and sets the value in the class columnfields array
  613. */
  614. function retrieve_entity_info($record, $module) {
  615. global $adb, $log, $app_strings;
  616. $result = Array();
  617. foreach ($this->tab_name_index as $table_name => $index) {
  618. $result[$table_name] = $adb->pquery("select * from $table_name where $index=?", array($record));
  619. $isRecordDeleted = $adb->query_result($result["vtiger_crmentity"], 0, "deleted");
  620. if ($isRecordDeleted !== 0 && $isRecordDeleted !== '0') {
  621. die("<br><br><center>" . $app_strings['LBL_RECORD_DELETE'] . " <a href='javascript:window.history.back()'>" . $app_strings['LBL_GO_BACK'] . ".</a></center>");
  622. }
  623. }
  624. /* Prasad: Fix for ticket #4595 */
  625. if (isset($this->table_name)) {
  626. $mod_index_col = $this->tab_name_index[$this->table_name];
  627. if ($adb->query_result($result[$this->table_name], 0, $mod_index_col) == '')
  628. die("<br><br><center>" . $app_strings['LBL_RECORD_NOT_FOUND'] .
  629. ". <a href='javascript:window.history.back()'>" . $app_strings['LBL_GO_BACK'] . ".</a></center>");
  630. }
  631. // Lookup in cache for information
  632. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  633. if ($cachedModuleFields === false) {
  634. $tabid = getTabid($module);
  635. // Let us pick up all the fields first so that we can cache information
  636. $sql1 = "SELECT fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence
  637. FROM vtiger_field WHERE tabid=?";
  638. // NOTE: Need to skip in-active fields which we will be done later.
  639. $result1 = $adb->pquery($sql1, array($tabid));
  640. $noofrows = $adb->num_rows($result1);
  641. if ($noofrows) {
  642. while ($resultrow = $adb->fetch_array($result1)) {
  643. // Update information to cache for re-use
  644. VTCacheUtils::updateFieldInfo(
  645. $tabid, $resultrow['fieldname'], $resultrow['fieldid'], $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']
  646. );
  647. }
  648. }
  649. // Get only active field information
  650. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  651. }
  652. if ($cachedModuleFields) {
  653. foreach ($cachedModuleFields as $fieldname => $fieldinfo) {
  654. $fieldcolname = $fieldinfo['columnname'];
  655. $tablename = $fieldinfo['tablename'];
  656. $fieldname = $fieldinfo['fieldname'];
  657. // To avoid ADODB execption pick the entries that are in $tablename
  658. // (ex. when we don't have attachment for troubletickets, $result[vtiger_attachments]
  659. // will not be set so here we should not retrieve)
  660. if (isset($result[$tablename])) {
  661. $fld_value = $adb->query_result($result[$tablename], 0, $fieldcolname);
  662. } else {
  663. $adb->println("There is no entry for this entity $record ($module) in the table $tablename");
  664. $fld_value = "";
  665. }
  666. $this->column_fields[$fieldname] = $fld_value;
  667. }
  668. }
  669. if ($module == 'Users') {
  670. for ($i = 0; $i < $noofrows; $i++) {
  671. $fieldcolname = $adb->query_result($result1, $i, "columnname");
  672. $tablename = $adb->query_result($result1, $i, "tablename");
  673. $fieldname = $adb->query_result($result1, $i, "fieldname");
  674. $fld_value = $adb->query_result($result[$tablename], 0, $fieldcolname);
  675. $this->$fieldname = $fld_value;
  676. }
  677. }
  678. $this->column_fields["record_id"] = $record;
  679. $this->column_fields["record_module"] = $module;
  680. }
  681. /** Function to saves the values in all the tables mentioned in the class variable $tab_name for the specified module
  682. * @param $module -- module:: Type varchar
  683. */
  684. function save($module_name, $fileid = '') {
  685. global $log;
  686. $log->debug("module name is " . $module_name);
  687. //Event triggering code
  688. require_once("include/events/include.inc");
  689. global $adb;
  690. $em = new VTEventsManager($adb);
  691. // Initialize Event trigger cache
  692. $em->initTriggerCache();
  693. $entityData = VTEntityData::fromCRMEntity($this);
  694. $em->triggerEvent("vtiger.entity.beforesave.modifiable", $entityData);
  695. $em->triggerEvent("vtiger.entity.beforesave", $entityData);
  696. $em->triggerEvent("vtiger.entity.beforesave.final", $entityData);
  697. //Event triggering code ends
  698. //GS Save entity being called with the modulename as parameter
  699. $this->saveentity($module_name, $fileid);
  700. //Event triggering code
  701. $em->triggerEvent("vtiger.entity.aftersave", $entityData);
  702. $em->triggerEvent("vtiger.entity.aftersave.final", $entityData);
  703. //Event triggering code ends
  704. }
  705. function process_list_query($query, $row_offset, $limit = -1, $max_per_page = -1) {
  706. global $list_max_entries_per_page;
  707. $this->log->debug("process_list_query: " . $query);
  708. if (!empty($limit) && $limit != -1) {
  709. $result = & $this->db->limitQuery($query, $row_offset + 0, $limit, true, "Error retrieving $this->object_name list: ");
  710. } else {
  711. $result = & $this->db->query($query, true, "Error retrieving $this->object_name list: ");
  712. }
  713. $list = Array();
  714. if ($max_per_page == -1) {
  715. $max_per_page = $list_max_entries_per_page;
  716. }
  717. $rows_found = $this->db->getRowCount($result);
  718. $this->log->debug("Found $rows_found " . $this->object_name . "s");
  719. $previous_offset = $row_offset - $max_per_page;
  720. $next_offset = $row_offset + $max_per_page;
  721. if ($rows_found != 0) {
  722. // We have some data.
  723. 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)) {
  724. foreach ($this->list_fields as $entry) {
  725. foreach ($entry as $key => $field) { // this will be cycled only once
  726. if (isset($row[$field])) {
  727. $this->column_fields[$this->list_fields_names[$key]] = $row[$field];
  728. $this->log->debug("$this->object_name({$row['id']}): " . $field . " = " . $this->$field);
  729. } else {
  730. $this->column_fields[$this->list_fields_names[$key]] = "";
  731. }
  732. }
  733. }
  734. //$this->db->println("here is the bug");
  735. $list[] = clone($this); //added by Richie to support PHP5
  736. }
  737. }
  738. $response = Array();
  739. $response['list'] = $list;
  740. $response['row_count'] = $rows_found;
  741. $response['next_offset'] = $next_offset;
  742. $response['previous_offset'] = $previous_offset;
  743. return $response;
  744. }
  745. function process_full_list_query($query) {
  746. $this->log->debug("CRMEntity:process_full_list_query");
  747. $result = & $this->db->query($query, false);
  748. //$this->log->debug("CRMEntity:process_full_list_query: result is ".$result);
  749. if ($this->db->getRowCount($result) > 0) {
  750. // $this->db->println("process_full mid=".$this->table_index." mname=".$this->module_name);
  751. // We have some data.
  752. while ($row = $this->db->fetchByAssoc($result)) {
  753. $rowid = $row[$this->table_index];
  754. if (isset($rowid))
  755. $this->retrieve_entity_info($rowid, $this->module_name);
  756. else
  757. $this->db->println("rowid not set unable to retrieve");
  758. //clone function added to resolvoe PHP5 compatibility issue in Dashboards
  759. //If we do not use clone, while using PHP5, the memory address remains fixed but the
  760. //data gets overridden hence all the rows that come in bear the same value. This in turn
  761. //provides a wrong display of the Dashboard graphs. The data is erroneously shown for a specific month alone
  762. //Added by Richie
  763. $list[] = clone($this); //added by Richie to support PHP5
  764. }
  765. }
  766. if (isset($list))
  767. return $list;
  768. else
  769. return null;
  770. }
  771. /** This function should be overridden in each module. It marks an item as deleted.
  772. * If it is not overridden, then marking this type of item is not allowed
  773. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  774. * All Rights Reserved..
  775. * Contributor(s): ______________________________________..
  776. */
  777. function mark_deleted($id) {
  778. global $current_user;
  779. $date_var = date("Y-m-d H:i:s");
  780. $query = "UPDATE vtiger_crmentity set deleted=1,modifiedtime=?,modifiedby=? where crmid=?";
  781. $this->db->pquery($query, array($this->db->formatDate($date_var, true), $current_user->id, $id), true, "Error marking record deleted: ");
  782. }
  783. function retrieve_by_string_fields($fields_array, $encode = true) {
  784. $where_clause = $this->get_where($fields_array);
  785. $query = "SELECT * FROM $this->table_name $where_clause";
  786. $this->log->debug("Retrieve $this->object_name: " . $query);
  787. $result = & $this->db->requireSingleResult($query, true, "Retrieving record $where_clause:");
  788. if (empty($result)) {
  789. return null;
  790. }
  791. $row = $this->db->fetchByAssoc($result, -1, $encode);
  792. foreach ($this->column_fields as $field) {
  793. if (isset($row[$field])) {
  794. $this->$field = $row[$field];
  795. }
  796. }
  797. return $this;
  798. }
  799. // this method is called during an import before inserting a bean
  800. // define an associative array called $special_fields
  801. // the keys are user defined, and don't directly map to the bean's vtiger_fields
  802. // the value is the method name within that bean that will do extra
  803. // processing for that vtiger_field. example: 'full_name'=>'get_names_from_full_name'
  804. function process_special_fields() {
  805. foreach ($this->special_functions as $func_name) {
  806. if (method_exists($this, $func_name)) {
  807. $this->$func_name();
  808. }
  809. }
  810. }
  811. /**
  812. * Function to check if the custom vtiger_field vtiger_table exists
  813. * return true or false
  814. */
  815. function checkIfCustomTableExists($tablename) {
  816. global $adb;
  817. $query = "select * from " . $adb->sql_escape_string($tablename);
  818. $result = $this->db->pquery($query, array());
  819. $testrow = $this->db->num_fields($result);
  820. if ($testrow > 1) {
  821. $exists = true;
  822. } else {
  823. $exists = false;
  824. }
  825. return $exists;
  826. }
  827. /**
  828. * function to construct the query to fetch the custom vtiger_fields
  829. * return the query to fetch the custom vtiger_fields
  830. */
  831. function constructCustomQueryAddendum($tablename, $module) {
  832. global $adb;
  833. $tabid = getTabid($module);
  834. $sql1 = "select columnname,fieldlabel from vtiger_field where generatedtype=2 and tabid=? and vtiger_field.presence in (0,2)";
  835. $result = $adb->pquery($sql1, array($tabid));
  836. $numRows = $adb->num_rows($result);
  837. $sql3 = "select ";
  838. for ($i = 0; $i < $numRows; $i++) {
  839. $columnName = $adb->query_result($result, $i, "columnname");
  840. $fieldlabel = $adb->query_result($result, $i, "fieldlabel");
  841. //construct query as below
  842. if ($i == 0) {
  843. $sql3 .= $tablename . "." . $columnName . " '" . $fieldlabel . "'";
  844. } else {
  845. $sql3 .= ", " . $tablename . "." . $columnName . " '" . $fieldlabel . "'";
  846. }
  847. }
  848. if ($numRows > 0) {
  849. $sql3 = $sql3 . ',';
  850. }
  851. return $sql3;
  852. }
  853. /**
  854. * This function returns a full (ie non-paged) list of the current object type.
  855. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  856. * All Rights Reserved..
  857. * Contributor(s): ______________________________________..
  858. */
  859. function get_full_list($order_by = "", $where = "") {
  860. $this->log->debug("get_full_list: order_by = '$order_by' and where = '$where'");
  861. $query = $this->create_list_query($order_by, $where);
  862. return $this->process_full_list_query($query);
  863. }
  864. /**
  865. * Track the viewing of a detail record. This leverages get_summary_text() which is object specific
  866. * params $user_id - The user that is viewing the record.
  867. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  868. * All Rights Reserved..
  869. * Contributor(s): ______________________________________..
  870. */
  871. function track_view($user_id, $current_module, $id = '') {
  872. $this->log->debug("About to call vtiger_tracker (user_id, module_name, item_id)($user_id, $current_module, $this->id)");
  873. $tracker = new Tracker();
  874. $tracker->track_view($user_id, $current_module, $id, '');
  875. }
  876. /**
  877. * Function to get the column value of a field when the field value is empty ''
  878. * @param $columnname -- Column name for the field
  879. * @param $fldvalue -- Input value for the field taken from the User
  880. * @param $fieldname -- Name of the Field
  881. * @param $uitype -- UI type of the field
  882. * @return Column value of the field.
  883. */
  884. function get_column_value($columnname, $fldvalue, $fieldname, $uitype, $datatype = '') {
  885. global $log;
  886. $log->debug("Entering function get_column_value ($columnname, $fldvalue, $fieldname, $uitype, $datatype='')");
  887. // Added for the fields of uitype '57' which has datatype mismatch in crmentity table and particular entity table
  888. if ($uitype == 57 && $fldvalue == '') {
  889. return 0;
  890. }
  891. if (is_uitype($uitype, "_date_") && $fldvalue == '') {
  892. return null;
  893. }
  894. if ($datatype == 'I' || $datatype == 'N' || $datatype == 'NN') {
  895. return 0;
  896. }
  897. $log->debug("Exiting function get_column_value");
  898. return $fldvalue;
  899. }
  900. /**
  901. * Function to make change to column fields, depending on the current user's accessibility for the fields
  902. */
  903. function apply_field_security() {
  904. global $current_user, $currentModule;
  905. require_once('include/utils/UserInfoUtil.php');
  906. foreach ($this->column_fields as $fieldname => $fieldvalue) {
  907. $reset_value = false;
  908. if (getFieldVisibilityPermission($currentModule, $current_user->id, $fieldname) != '0')
  909. $reset_value = true;
  910. if ($fieldname == "record_id" || $fieldname == "record_module")
  911. $reset_value = false;
  912. /*
  913. if (isset($this->additional_column_fields) && in_array($fieldname, $this->additional_column_fields) == true)
  914. $reset_value = false;
  915. */
  916. if ($reset_value == true)
  917. $this->column_fields[$fieldname] = "";
  918. }
  919. }
  920. /**
  921. * Function invoked during export of module record value.
  922. */
  923. function transform_export_value($key, $value) {
  924. // NOTE: The sub-class can override this function as required.
  925. return $value;
  926. }
  927. /**
  928. * Function to initialize the importable fields array, based on the User's accessibility to the fields
  929. */
  930. function initImportableFields($module) {
  931. global $current_user, $adb;
  932. require_once('include/utils/UserInfoUtil.php');
  933. $skip_uitypes = array('4'); // uitype 4 is for Mod numbers
  934. // Look at cache if the fields information is available.
  935. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  936. if ($cachedModuleFields === false) {
  937. getColumnFields($module); // This API will initialize the cache as well
  938. // We will succeed now due to above function call
  939. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  940. }
  941. $colf = Array();
  942. if ($cachedModuleFields) {
  943. foreach ($cachedModuleFields as $fieldinfo) {
  944. // Skip non-supported fields
  945. if (in_array($fieldinfo['uitype'], $skip_uitypes)) {
  946. continue;
  947. } else {
  948. $colf[$fieldinfo['fieldname']] = $fieldinfo['uitype'];
  949. }
  950. }
  951. }
  952. foreach ($colf as $key => $value) {
  953. if (getFieldVisibilityPermission($module, $current_user->id, $key, 'readwrite') == '0')
  954. $this->importable_fields[$key] = $value;
  955. }
  956. }
  957. /** Function to initialize the required fields array for that particular module */
  958. function initRequiredFields($module) {
  959. global $adb;
  960. $tabid = getTabId($module);
  961. $sql = "select * from vtiger_field where tabid= ? and typeofdata like '%M%' and uitype not in ('53','70') and vtiger_field.presence in (0,2)";
  962. $result = $adb->pquery($sql, array($tabid));
  963. $numRows = $adb->num_rows($result);
  964. for ($i = 0; $i < $numRows; $i++) {
  965. $fieldName = $adb->query_result($result, $i, "fieldname");
  966. $this->required_fields[$fieldName] = 1;
  967. }
  968. }
  969. /** Function to delete an entity with given Id */
  970. function trash($module, $id) {
  971. global $log, $current_user, $adb;
  972. require_once("include/events/include.inc");
  973. $em = new VTEventsManager($adb);
  974. // Initialize Event trigger cache
  975. $em->initTriggerCache();
  976. $entityData = VTEntityData::fromEntityId($adb, $id);
  977. $em->triggerEvent("vtiger.entity.beforedelete", $entityData);
  978. $this->mark_deleted($id);
  979. $this->unlinkDependencies($module, $id);
  980. require_once('include/freetag/freetag.class.php');
  981. $freetag = new freetag();
  982. $freetag->delete_all_object_tags_for_user($current_user->id, $id);
  983. $sql_recentviewed = 'DELETE FROM vtiger_tracker WHERE user_id = ? AND item_id = ?';
  984. $this->db->pquery($sql_recentviewed, array($current_user->id, $id));
  985. $em->triggerEvent("vtiger.entity.afterdelete", $entityData);
  986. }
  987. /** Function to unlink all the dependent entities of the given Entity by Id */
  988. function unlinkDependencies($module, $id) {
  989. global $log;
  990. $fieldRes = $this->db->pquery('SELECT tabid, tablename, columnname FROM vtiger_field WHERE fieldid IN (
  991. SELECT fieldid FROM vtiger_fieldmodulerel WHERE relmodule=?)', array($module));
  992. $numOfFields = $this->db->num_rows($fieldRes);
  993. for ($i = 0; $i < $numOfFields; $i++) {
  994. $tabId = $this->db->query_result($fieldRes, $i, 'tabid');
  995. $tableName = $this->db->query_result($fieldRes, $i, 'tablename');
  996. $columnName = $this->db->query_result($fieldRes, $i, 'columnname');
  997. $relatedModule = vtlib_getModuleNameById($tabId);
  998. $focusObj = CRMEntity::getInstance($relatedModule);
  999. //Backup Field Relations for the deleted entity
  1000. $relQuery = "SELECT $focusObj->table_index FROM $tableName WHERE $columnName=?";
  1001. $relResult = $this->db->pquery($relQuery, array($id));
  1002. $numOfRelRecords = $this->db->num_rows($relResult);
  1003. if ($numOfRelRecords > 0) {
  1004. $recordIdsList = array();
  1005. for ($k = 0; $k < $numOfRelRecords; $k++) {
  1006. $recordIdsList[] = $this->db->query_result($relResult, $k, $focusObj->table_index);
  1007. }
  1008. $params = array($id, RB_RECORD_UPDATED, $tableName, $columnName, $focusObj->table_index, implode(",", $recordIdsList));
  1009. $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES (?,?,?,?,?,?)', $params);
  1010. }
  1011. }
  1012. }
  1013. /** Function to unlink an entity with given Id from another entity */
  1014. function unlinkRelationship($id, $return_module, $return_id) {
  1015. global $log, $currentModule;
  1016. $query = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
  1017. $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
  1018. $this->db->pquery($query, $params);
  1019. $fieldRes = $this->db->pquery('SELECT tabid, tablename, columnname FROM vtiger_field WHERE fieldid IN (
  1020. SELECT fieldid FROM vtiger_fieldmodulerel WHERE module=? AND relmodule=?)', array($currentModule, $return_module));
  1021. $numOfFields = $this->db->num_rows($fieldRes);
  1022. for ($i = 0; $i < $numOfFields; $i++) {
  1023. $tabId = $this->db->query_result($fieldRes, $i, 'tabid');
  1024. $tableName = $this->db->query_result($fieldRes, $i, 'tablename');
  1025. $columnName = $this->db->query_result($fieldRes, $i, 'columnname');
  1026. $relatedModule = vtlib_getModuleNameById($tabId);
  1027. $focusObj = CRMEntity::getInstance($relatedModule);
  1028. $updateQuery = "UPDATE $tableName SET $columnName=? WHERE $columnName=? AND $focusObj->table_index=?";
  1029. $updateParams = array(null, $return_id, $id);
  1030. $this->db->pquery($updateQuery, $updateParams);
  1031. }
  1032. }
  1033. /** Function to restore a deleted record of specified module with given crmid
  1034. * @param $module -- module name:: Type varchar
  1035. * @param $entity_ids -- list of crmids :: Array
  1036. */
  1037. function restore($module, $id) {
  1038. global $current_user, $adb;
  1039. $this->db->println("TRANS restore starts $module");
  1040. $this->db->startTransaction();
  1041. $date_var = date("Y-m-d H:i:s");
  1042. $query = 'UPDATE vtiger_crmentity SET deleted=0,modifiedtime=?,modifiedby=? WHERE crmid = ?';
  1043. $this->db->pquery($query, array($this->db->formatDate($date_var, true), $current_user->id, $id), true, "Error restoring records :");
  1044. //Restore related entities/records
  1045. $this->restoreRelatedRecords($module, $id);
  1046. //Event triggering code
  1047. require_once("include/events/include.inc");
  1048. global $adb;
  1049. $em = new VTEventsManager($adb);
  1050. // Initialize Event trigger cache
  1051. $em->initTriggerCache();
  1052. $this->id = $id;
  1053. $entityData = VTEntityData::fromCRMEntity($this);
  1054. //Event triggering code
  1055. $em->triggerEvent("vtiger.entity.afterrestore", $entityData);
  1056. //Event triggering code ends
  1057. $this->db->completeTransaction();
  1058. $this->db->println("TRANS restore ends");
  1059. }
  1060. /** Function to restore all the related records of a given record by id */
  1061. function restoreRelatedRecords($module, $record) {
  1062. $result = $this->db->pquery('SELECT * FROM vtiger_relatedlists_rb WHERE entityid = ?', array($record));
  1063. $numRows = $this->db->num_rows($result);
  1064. for ($i = 0; $i < $numRows; $i++) {
  1065. $action = $this->db->query_result($result, $i, "action");
  1066. $rel_table = $this->db->query_result($result, $i, "rel_table");
  1067. $rel_column = $this->db->query_result($result, $i, "rel_column");
  1068. $ref_column = $this->db->query_result($result, $i, "ref_column");
  1069. $related_crm_ids = $this->db->query_result($result, $i, "related_crm_ids");
  1070. if (str

Large files files are truncated, but you can click here to view the full file