PageRenderTime 78ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/include/utils/utils.php

https://bitbucket.org/thomashii/vtigercrm-5.4-for-postgresql
PHP | 5134 lines | 3858 code | 546 blank | 730 comment | 627 complexity | fbcd1419ab8f4fb67eff80d6c2581f21 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  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$
  17. * Description: Includes generic helper functions used throughout the application.
  18. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  19. * All Rights Reserved.
  20. * Contributor(s): ______________________________________..
  21. ********************************************************************************/
  22. /** This function returns the name of the person.
  23. * It currently returns "first last". It should not put the space if either name is not available.
  24. * It should not return errors if either name is not available.
  25. * If no names are present, it will return ""
  26. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  27. * All Rights Reserved.
  28. * Contributor(s): ______________________________________..
  29. */
  30. require_once('include/database/PearDatabase.php');
  31. require_once('include/ComboUtil.php'); //new
  32. require_once('include/utils/ListViewUtils.php');
  33. require_once('include/utils/EditViewUtils.php');
  34. require_once('include/utils/DetailViewUtils.php');
  35. require_once('include/utils/CommonUtils.php');
  36. require_once('include/utils/InventoryUtils.php');
  37. require_once('include/utils/SearchUtils.php');
  38. require_once('include/FormValidationUtil.php');
  39. require_once('include/DatabaseUtil.php');
  40. require_once('include/events/SqlResultIterator.inc');
  41. require_once('include/fields/DateTimeField.php');
  42. require_once('include/fields/CurrencyField.php');
  43. require_once('data/CRMEntity.php');
  44. require_once 'vtlib/Vtiger/Language.php';
  45. // Constants to be defined here
  46. // For Migration status.
  47. define("MIG_CHARSET_PHP_UTF8_DB_UTF8", 1);
  48. define("MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8", 2);
  49. define("MIG_CHARSET_PHP_NONUTF8_DB_UTF8", 3);
  50. define("MIG_CHARSET_PHP_UTF8_DB_NONUTF8", 4);
  51. // For Customview status.
  52. define("CV_STATUS_DEFAULT", 0);
  53. define("CV_STATUS_PRIVATE", 1);
  54. define("CV_STATUS_PENDING", 2);
  55. define("CV_STATUS_PUBLIC", 3);
  56. // For Restoration.
  57. define("RB_RECORD_DELETED", 'delete');
  58. define("RB_RECORD_INSERTED", 'insert');
  59. define("RB_RECORD_UPDATED", 'update');
  60. /** Function to return a full name
  61. * @param $row -- row:: Type integer
  62. * @param $first_column -- first column:: Type string
  63. * @param $last_column -- last column:: Type string
  64. * @returns $fullname -- fullname:: Type string
  65. *
  66. */
  67. function return_name(&$row, $first_column, $last_column)
  68. {
  69. global $log;
  70. $log->debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ...");
  71. $first_name = "";
  72. $last_name = "";
  73. $full_name = "";
  74. if(isset($row[$first_column]))
  75. {
  76. $first_name = stripslashes($row[$first_column]);
  77. }
  78. if(isset($row[$last_column]))
  79. {
  80. $last_name = stripslashes($row[$last_column]);
  81. }
  82. $full_name = $first_name;
  83. // If we have a first name and we have a last name
  84. if($full_name != "" && $last_name != "")
  85. {
  86. // append a space, then the last name
  87. $full_name .= " ".$last_name;
  88. }
  89. // If we have no first name, but we have a last name
  90. else if($last_name != "")
  91. {
  92. // append the last name without the space.
  93. $full_name .= $last_name;
  94. }
  95. $log->debug("Exiting return_name method ...");
  96. return $full_name;
  97. }
  98. /** Function to return language
  99. * @returns $languages -- languages:: Type string
  100. *
  101. */
  102. function get_languages()
  103. {
  104. global $log;
  105. $log->debug("Entering get_languages() method ...");
  106. global $languages;
  107. $log->debug("Exiting get_languages method ...");
  108. return $languages;
  109. }
  110. /** Function to return language
  111. * @param $key -- key:: Type string
  112. * @returns $languages -- languages:: Type string
  113. *
  114. */
  115. //seems not used
  116. function get_language_display($key)
  117. {
  118. global $log;
  119. $log->debug("Entering get_language_display(".$key.") method ...");
  120. global $languages;
  121. $log->debug("Exiting get_language_display method ...");
  122. return $languages[$key];
  123. }
  124. /** Function returns the user array
  125. * @param $assigned_user_id -- assigned_user_id:: Type string
  126. * @returns $user_list -- user list:: Type array
  127. *
  128. */
  129. function get_assigned_user_name(&$assigned_user_id)
  130. {
  131. global $log;
  132. $log->debug("Entering get_assigned_user_name(".$assigned_user_id.") method ...");
  133. $user_list = &get_user_array(false,"");
  134. if(isset($user_list[$assigned_user_id]))
  135. {
  136. $log->debug("Exiting get_assigned_user_name method ...");
  137. return $user_list[$assigned_user_id];
  138. }
  139. $log->debug("Exiting get_assigned_user_name method ...");
  140. return "";
  141. }
  142. /** Function returns the user key in user array
  143. * @param $add_blank -- boolean:: Type boolean
  144. * @param $status -- user status:: Type string
  145. * @param $assigned_user -- user id:: Type string
  146. * @param $private -- sharing type:: Type string
  147. * @returns $user_array -- user array:: Type array
  148. *
  149. */
  150. //used in module file
  151. function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="")
  152. {
  153. global $log;
  154. $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ...");
  155. global $current_user;
  156. if(isset($current_user) && $current_user->id != '')
  157. {
  158. require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
  159. require('user_privileges/user_privileges_'.$current_user->id.'.php');
  160. }
  161. static $user_array = null;
  162. $module=$_REQUEST['module'];
  163. if($user_array == null)
  164. {
  165. require_once('include/database/PearDatabase.php');
  166. $db = PearDatabase::getInstance();
  167. $temp_result = Array();
  168. // Including deleted vtiger_users for now.
  169. if (empty($status)) {
  170. $query = "SELECT id, user_name from vtiger_users";
  171. $params = array();
  172. }
  173. else {
  174. if($private == 'private')
  175. {
  176. $log->debug("Sharing is Private. Only the current user should be listed");
  177. $query = "select id as id,user_name as user_name,first_name,last_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name ,
  178. vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name
  179. from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union
  180. select shareduserid as id,vtiger_users.user_name as user_name ,
  181. vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?";
  182. $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module));
  183. }
  184. else
  185. {
  186. $log->debug("Sharing is Public. All vtiger_users should be listed");
  187. $query = "SELECT id, user_name,first_name,last_name from vtiger_users WHERE status=?";
  188. $params = array($status);
  189. }
  190. }
  191. if (!empty($assigned_user)) {
  192. $query .= " OR id=?";
  193. array_push($params, $assigned_user);
  194. }
  195. $query .= " order by user_name ASC";
  196. $result = $db->pquery($query, $params, true, "Error filling in user array: ");
  197. if ($add_blank==true){
  198. // Add in a blank row
  199. $temp_result[''] = '';
  200. }
  201. // Get the id and the name.
  202. while($row = $db->fetchByAssoc($result))
  203. {
  204. $temp_result[$row['id']] = getFullNameFromArray('Users', $row);
  205. }
  206. $user_array = &$temp_result;
  207. }
  208. $log->debug("Exiting get_user_array method ...");
  209. return $user_array;
  210. }
  211. function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="")
  212. {
  213. global $log;
  214. $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ...");
  215. global $current_user;
  216. if(isset($current_user) && $current_user->id != '')
  217. {
  218. require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
  219. require('user_privileges/user_privileges_'.$current_user->id.'.php');
  220. }
  221. static $group_array = null;
  222. $module=$_REQUEST['module'];
  223. if($group_array == null)
  224. {
  225. require_once('include/database/PearDatabase.php');
  226. $db = PearDatabase::getInstance();
  227. $temp_result = Array();
  228. // Including deleted vtiger_users for now.
  229. $log->debug("Sharing is Public. All vtiger_users should be listed");
  230. $query = "SELECT groupid, groupname from vtiger_groups";
  231. $params = array();
  232. if($private == 'private'){
  233. $query .= " WHERE groupid=?";
  234. $params = array( $current_user->id);
  235. if(count($current_user_groups) != 0) {
  236. $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")";
  237. array_push($params, $current_user_groups);
  238. }
  239. $log->debug("Sharing is Private. Only the current user should be listed");
  240. $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?";
  241. array_push($params, $current_user_parent_role_seq."::%");
  242. if(count($current_user_groups) != 0) {
  243. $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")";
  244. array_push($params, $parent_roles);
  245. }
  246. $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?";
  247. array_push($params, $current_user->id);
  248. $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?";
  249. array_push($params, getTabid($module));
  250. }
  251. $query .= " order by groupname ASC";
  252. $result = $db->pquery($query, $params, true, "Error filling in user array: ");
  253. if ($add_blank==true){
  254. // Add in a blank row
  255. $temp_result[''] = '';
  256. }
  257. // Get the id and the name.
  258. while($row = $db->fetchByAssoc($result))
  259. {
  260. $temp_result[$row['groupid']] = $row['groupname'];
  261. }
  262. $group_array = &$temp_result;
  263. }
  264. $log->debug("Exiting get_user_array method ...");
  265. return $group_array;
  266. }
  267. /** Function skips executing arbitary commands given in a string
  268. * @param $string -- string:: Type string
  269. * @param $maxlength -- maximun length:: Type integer
  270. * @returns $string -- escaped string:: Type string
  271. *
  272. */
  273. function clean($string, $maxLength)
  274. {
  275. global $log;
  276. $log->debug("Entering clean(".$string.",". $maxLength.") method ...");
  277. $string = substr($string, 0, $maxLength);
  278. $log->debug("Exiting clean method ...");
  279. return escapeshellcmd($string);
  280. }
  281. /**
  282. * Copy the specified request variable to the member variable of the specified object.
  283. * Do no copy if the member variable is already set.
  284. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  285. * All Rights Reserved.
  286. * Contributor(s): ______________________________________..
  287. */
  288. function safe_map($request_var, & $focus, $always_copy = false)
  289. {
  290. global $log;
  291. $log->debug("Entering safe_map(".$request_var.",".get_class($focus).",".$always_copy.") method ...");
  292. safe_map_named($request_var, $focus, $request_var, $always_copy);
  293. $log->debug("Exiting safe_map method ...");
  294. }
  295. /**
  296. * Copy the specified request variable to the member variable of the specified object.
  297. * Do no copy if the member variable is already set.
  298. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  299. * All Rights Reserved.
  300. * Contributor(s): ______________________________________..
  301. */
  302. function safe_map_named($request_var, & $focus, $member_var, $always_copy)
  303. {
  304. global $log;
  305. $log->debug("Entering safe_map_named(".$request_var.",".get_class($focus).",".$member_var.",".$always_copy.") method ...");
  306. if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) {
  307. $log->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var");
  308. $focus->$member_var = $_REQUEST[$request_var];
  309. }
  310. $log->debug("Exiting safe_map_named method ...");
  311. }
  312. /** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var.
  313. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  314. * All Rights Reserved.
  315. * Contributor(s): ______________________________________..
  316. * If you are using the current language, do not call this function unless you are loading it for the first time */
  317. function return_app_list_strings_language($language)
  318. {
  319. global $log;
  320. $log->debug("Entering return_app_list_strings_language(".$language.") method ...");
  321. global $app_list_strings, $default_language, $log, $translation_string_prefix;
  322. $temp_app_list_strings = $app_list_strings;
  323. $language_used = $language;
  324. @include("include/language/$language.lang.php");
  325. if(!isset($app_list_strings))
  326. {
  327. $log->warn("Unable to find the application language file for language: ".$language);
  328. require("include/language/$default_language.lang.php");
  329. $language_used = $default_language;
  330. }
  331. if(!isset($app_list_strings))
  332. {
  333. $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)");
  334. $log->debug("Exiting return_app_list_strings_language method ...");
  335. return null;
  336. }
  337. $return_value = $app_list_strings;
  338. $app_list_strings = $temp_app_list_strings;
  339. $log->debug("Exiting return_app_list_strings_language method ...");
  340. return $return_value;
  341. }
  342. /**
  343. * Retrieve the app_currency_strings for the required language.
  344. */
  345. function return_app_currency_strings_language($language) {
  346. global $log;
  347. $log->debug("Entering return_app_currency_strings_language(".$language.") method ...");
  348. global $app_currency_strings, $default_language, $log, $translation_string_prefix;
  349. // Backup the value first
  350. $temp_app_currency_strings = $app_currency_strings;
  351. @include("include/language/$language.lang.php");
  352. if(!isset($app_currency_strings))
  353. {
  354. $log->warn("Unable to find the application language file for language: ".$language);
  355. require("include/language/$default_language.lang.php");
  356. $language_used = $default_language;
  357. }
  358. if(!isset($app_currency_strings))
  359. {
  360. $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)");
  361. $log->debug("Exiting return_app_currency_strings_language method ...");
  362. return null;
  363. }
  364. $return_value = $app_currency_strings;
  365. // Restore the value back
  366. $app_currency_strings = $temp_app_currency_strings;
  367. $log->debug("Exiting return_app_currency_strings_language method ...");
  368. return $return_value;
  369. }
  370. /** This function retrieves an application language file and returns the array of strings included.
  371. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  372. * All Rights Reserved.
  373. * Contributor(s): ______________________________________..
  374. * If you are using the current language, do not call this function unless you are loading it for the first time */
  375. function return_application_language($language)
  376. {
  377. global $log;
  378. $log->debug("Entering return_application_language(".$language.") method ...");
  379. global $app_strings, $default_language, $log, $translation_string_prefix;
  380. $temp_app_strings = $app_strings;
  381. $language_used = $language;
  382. checkFileAccessForInclusion("include/language/$language.lang.php");
  383. @include("include/language/$language.lang.php");
  384. if(!isset($app_strings))
  385. {
  386. $log->warn("Unable to find the application language file for language: ".$language);
  387. require("include/language/$default_language.lang.php");
  388. $language_used = $default_language;
  389. }
  390. if(!isset($app_strings))
  391. {
  392. $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)");
  393. $log->debug("Exiting return_application_language method ...");
  394. return null;
  395. }
  396. // If we are in debug mode for translating, turn on the prefix now!
  397. if($translation_string_prefix)
  398. {
  399. foreach($app_strings as $entry_key=>$entry_value)
  400. {
  401. $app_strings[$entry_key] = $language_used.' '.$entry_value;
  402. }
  403. }
  404. $return_value = $app_strings;
  405. $app_strings = $temp_app_strings;
  406. $log->debug("Exiting return_application_language method ...");
  407. return $return_value;
  408. }
  409. /** This function retrieves a module's language file and returns the array of strings included.
  410. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  411. * All Rights Reserved.
  412. * Contributor(s): ______________________________________..
  413. * If you are in the current module, do not call this function unless you are loading it for the first time */
  414. function return_module_language($language, $module)
  415. {
  416. global $log;
  417. $log->debug("Entering return_module_language(".$language.",". $module.") method ...");
  418. global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix;
  419. static $cachedModuleStrings = array();
  420. if(!empty($cachedModuleStrings[$module])) {
  421. $log->debug("Exiting return_module_language method ...");
  422. return $cachedModuleStrings[$module];
  423. }
  424. $temp_mod_strings = $mod_strings;
  425. $language_used = $language;
  426. @include("modules/$module/language/$language.lang.php");
  427. if(!isset($mod_strings))
  428. {
  429. $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module);
  430. if($default_language == 'en_us') {
  431. require("modules/$module/language/$default_language.lang.php");
  432. $language_used = $default_language;
  433. } else {
  434. @include("modules/$module/language/$default_language.lang.php");
  435. if(!isset($mod_strings)) {
  436. require("modules/$module/language/en_us.lang.php");
  437. $language_used = 'en_us';
  438. } else {
  439. $language_used = $default_language;
  440. }
  441. }
  442. }
  443. if(!isset($mod_strings))
  444. {
  445. $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)");
  446. $log->debug("Exiting return_module_language method ...");
  447. return null;
  448. }
  449. // If we are in debug mode for translating, turn on the prefix now!
  450. if($translation_string_prefix)
  451. {
  452. foreach($mod_strings as $entry_key=>$entry_value)
  453. {
  454. $mod_strings[$entry_key] = $language_used.' '.$entry_value;
  455. }
  456. }
  457. $return_value = $mod_strings;
  458. $mod_strings = $temp_mod_strings;
  459. $log->debug("Exiting return_module_language method ...");
  460. $cachedModuleStrings[$module] = $return_value;
  461. return $return_value;
  462. }
  463. /*This function returns the mod_strings for the current language and the specified module
  464. */
  465. function return_specified_module_language($language, $module)
  466. {
  467. global $log;
  468. global $default_language, $translation_string_prefix;
  469. @include("modules/$module/language/$language.lang.php");
  470. if(!isset($mod_strings))
  471. {
  472. $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module);
  473. require("modules/$module/language/$default_language.lang.php");
  474. $language_used = $default_language;
  475. }
  476. if(!isset($mod_strings))
  477. {
  478. $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)");
  479. $log->debug("Exiting return_module_language method ...");
  480. return null;
  481. }
  482. $return_value = $mod_strings;
  483. $log->debug("Exiting return_module_language method ...");
  484. return $return_value;
  485. }
  486. /** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var.
  487. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  488. * All Rights Reserved.
  489. * Contributor(s): ______________________________________..
  490. * If you are using the current language, do not call this function unless you are loading it for the first time */
  491. function return_mod_list_strings_language($language,$module)
  492. {
  493. global $log;
  494. $log->debug("Entering return_mod_list_strings_language(".$language.",".$module.") method ...");
  495. global $mod_list_strings, $default_language, $log, $currentModule,$translation_string_prefix;
  496. $language_used = $language;
  497. $temp_mod_list_strings = $mod_list_strings;
  498. if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null)
  499. {
  500. $log->debug("Exiting return_mod_list_strings_language method ...");
  501. return $mod_list_strings;
  502. }
  503. @include("modules/$module/language/$language.lang.php");
  504. if(!isset($mod_list_strings))
  505. {
  506. $log->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language)");
  507. $log->debug("Exiting return_mod_list_strings_language method ...");
  508. return null;
  509. }
  510. $return_value = $mod_list_strings;
  511. $mod_list_strings = $temp_mod_list_strings;
  512. $log->debug("Exiting return_mod_list_strings_language method ...");
  513. return $return_value;
  514. }
  515. /** This function retrieves a theme's language file and returns the array of strings included.
  516. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  517. * All Rights Reserved.
  518. * Contributor(s): ______________________________________..
  519. */
  520. function return_theme_language($language, $theme)
  521. {
  522. global $log;
  523. $log->debug("Entering return_theme_language(".$language.",". $theme.") method ...");
  524. global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix;
  525. $language_used = $language;
  526. @include("themes/$theme/language/$current_language.lang.php");
  527. if(!isset($theme_strings))
  528. {
  529. $log->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme);
  530. require("themes/$theme/language/$default_language.lang.php");
  531. $language_used = $default_language;
  532. }
  533. if(!isset($theme_strings))
  534. {
  535. $log->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)");
  536. $log->debug("Exiting return_theme_language method ...");
  537. return null;
  538. }
  539. // If we are in debug mode for translating, turn on the prefix now!
  540. if($translation_string_prefix)
  541. {
  542. foreach($theme_strings as $entry_key=>$entry_value)
  543. {
  544. $theme_strings[$entry_key] = $language_used.' '.$entry_value;
  545. }
  546. }
  547. $log->debug("Exiting return_theme_language method ...");
  548. return $theme_strings;
  549. }
  550. /** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value.
  551. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  552. * All Rights Reserved.
  553. * Contributor(s): ______________________________________..
  554. */
  555. function return_session_value_or_default($varname, $default)
  556. {
  557. global $log;
  558. $log->debug("Entering return_session_value_or_default(".$varname.",". $default.") method ...");
  559. if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "")
  560. {
  561. $log->debug("Exiting return_session_value_or_default method ...");
  562. return $_SESSION[$varname];
  563. }
  564. $log->debug("Exiting return_session_value_or_default method ...");
  565. return $default;
  566. }
  567. /**
  568. * Creates an array of where restrictions. These are used to construct a where SQL statement on the query
  569. * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it.
  570. * @param &$where_clauses - The array to append the clause to
  571. * @param $variable_name - The name of the variable to look for an add to the where clause if found
  572. * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name.
  573. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  574. * All Rights Reserved.
  575. * Contributor(s): ______________________________________..
  576. */
  577. function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null)
  578. {
  579. global $log;
  580. $log->debug("Entering append_where_clause(".$where_clauses.",".$variable_name.",".$SQL_name.") method ...");
  581. if($SQL_name == null)
  582. {
  583. $SQL_name = $variable_name;
  584. }
  585. if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "")
  586. {
  587. array_push($where_clauses, "$SQL_name like '$_REQUEST[$variable_name]%'");
  588. }
  589. $log->debug("Exiting append_where_clause method ...");
  590. }
  591. /**
  592. * Generate the appropriate SQL based on the where clauses.
  593. * @param $where_clauses - An Array of individual where clauses stored as strings
  594. * @returns string where_clause - The final SQL where clause to be executed.
  595. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  596. * All Rights Reserved.
  597. * Contributor(s): ______________________________________..
  598. */
  599. function generate_where_statement($where_clauses)
  600. {
  601. global $log;
  602. $log->debug("Entering generate_where_statement(".$where_clauses.") method ...");
  603. $where = "";
  604. foreach($where_clauses as $clause)
  605. {
  606. if($where != "")
  607. $where .= " and ";
  608. $where .= $clause;
  609. }
  610. $log->info("Here is the where clause for the list view: $where");
  611. $log->debug("Exiting generate_where_statement method ...");
  612. return $where;
  613. }
  614. /**
  615. * A temporary method of generating GUIDs of the correct format for our DB.
  616. * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
  617. *
  618. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  619. * All Rights Reserved.
  620. * Contributor(s): ______________________________________..
  621. */
  622. function create_guid()
  623. {
  624. global $log;
  625. $log->debug("Entering create_guid() method ...");
  626. $microTime = microtime();
  627. list($a_dec, $a_sec) = explode(" ", $microTime);
  628. $dec_hex = sprintf("%x", $a_dec* 1000000);
  629. $sec_hex = sprintf("%x", $a_sec);
  630. ensure_length($dec_hex, 5);
  631. ensure_length($sec_hex, 6);
  632. $guid = "";
  633. $guid .= $dec_hex;
  634. $guid .= create_guid_section(3);
  635. $guid .= '-';
  636. $guid .= create_guid_section(4);
  637. $guid .= '-';
  638. $guid .= create_guid_section(4);
  639. $guid .= '-';
  640. $guid .= create_guid_section(4);
  641. $guid .= '-';
  642. $guid .= $sec_hex;
  643. $guid .= create_guid_section(6);
  644. $log->debug("Exiting create_guid method ...");
  645. return $guid;
  646. }
  647. /** Function to create guid section for a given character
  648. * @param $characters -- characters:: Type string
  649. * @returns $return -- integer:: Type integer``
  650. */
  651. function create_guid_section($characters)
  652. {
  653. global $log;
  654. $log->debug("Entering create_guid_section(".$characters.") method ...");
  655. $return = "";
  656. for($i=0; $i<$characters; $i++)
  657. {
  658. $return .= sprintf("%x", rand(0,15));
  659. }
  660. $log->debug("Exiting create_guid_section method ...");
  661. return $return;
  662. }
  663. /** Function to ensure length
  664. * @param $string -- string:: Type string
  665. * @param $length -- length:: Type string
  666. */
  667. function ensure_length(&$string, $length)
  668. {
  669. global $log;
  670. $log->debug("Entering ensure_length(".$string.",". $length.") method ...");
  671. $strlen = strlen($string);
  672. if($strlen < $length)
  673. {
  674. $string = str_pad($string,$length,"0");
  675. }
  676. else if($strlen > $length)
  677. {
  678. $string = substr($string, 0, $length);
  679. }
  680. $log->debug("Exiting ensure_length method ...");
  681. }
  682. /*
  683. function microtime_diff($a, $b) {
  684. global $log;
  685. $log->debug("Entering microtime_diff(".$a.",". $b.") method ...");
  686. list($a_dec, $a_sec) = explode(" ", $a);
  687. list($b_dec, $b_sec) = explode(" ", $b);
  688. $log->debug("Exiting microtime_diff method ...");
  689. return $b_sec - $a_sec + $b_dec - $a_dec;
  690. }
  691. */
  692. /**
  693. * Return the display name for a theme if it exists.
  694. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  695. * All Rights Reserved.
  696. * Contributor(s): ______________________________________..
  697. */
  698. function get_theme_display($theme) {
  699. global $log;
  700. $log->debug("Entering get_theme_display(".$theme.") method ...");
  701. global $theme_name, $theme_description;
  702. $temp_theme_name = $theme_name;
  703. $temp_theme_description = $theme_description;
  704. if (is_file("./themes/$theme/config.php")) {
  705. @include("./themes/$theme/config.php");
  706. $return_theme_value = $theme_name;
  707. }
  708. else {
  709. $return_theme_value = $theme;
  710. }
  711. $theme_name = $temp_theme_name;
  712. $theme_description = $temp_theme_description;
  713. $log->debug("Exiting get_theme_display method ...");
  714. return $return_theme_value;
  715. }
  716. /**
  717. * Return an array of directory names.
  718. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  719. * All Rights Reserved.
  720. * Contributor(s): ______________________________________..
  721. */
  722. function get_themes() {
  723. global $log;
  724. $log->debug("Entering get_themes() method ...");
  725. if ($dir = @opendir("./themes")) {
  726. while (($file = readdir($dir)) !== false) {
  727. if ($file != ".." && $file != "." && $file != "CVS" && $file != "Attic" && $file != "akodarkgem" && $file != "bushtree" && $file != "coolblue" && $file != "Amazon" && $file != "busthree" && $file != "Aqua" && $file != "nature" && $file != "orange" && $file != "blue") {
  728. if(is_dir("./themes/".$file)) {
  729. if(!($file[0] == '.')) {
  730. // set the initial theme name to the filename
  731. $name = $file;
  732. // if there is a configuration class, load that.
  733. if(is_file("./themes/$file/config.php"))
  734. {
  735. require_once("./themes/$file/config.php");
  736. }
  737. if(is_file("./themes/$file/style.css"))
  738. {
  739. $filelist[$file] = $name;
  740. }
  741. }
  742. }
  743. }
  744. }
  745. closedir($dir);
  746. }
  747. ksort($filelist);
  748. $log->debug("Exiting get_themes method ...");
  749. return $filelist;
  750. }
  751. /**
  752. * Create javascript to clear values of all elements in a form.
  753. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  754. * All Rights Reserved.
  755. * Contributor(s): ______________________________________..
  756. */
  757. function get_clear_form_js () {
  758. global $log;
  759. $log->debug("Entering get_clear_form_js () method ...");
  760. $the_script = <<<EOQ
  761. <script type="text/javascript" language="JavaScript">
  762. <!-- Begin
  763. function clear_form(form) {
  764. for (j = 0; j < form.elements.length; j++) {
  765. if (form.elements[j].type == 'text' || form.elements[j].type == 'select-one') {
  766. form.elements[j].value = '';
  767. }
  768. }
  769. }
  770. // End -->
  771. </script>
  772. EOQ;
  773. $log->debug("Exiting get_clear_form_js method ...");
  774. return $the_script;
  775. }
  776. /**
  777. * Create javascript to set the cursor focus to specific vtiger_field in a form
  778. * when the screen is rendered. The vtiger_field name is currently hardcoded into the
  779. * the function.
  780. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  781. * All Rights Reserved.
  782. * Contributor(s): ______________________________________..
  783. */
  784. function get_set_focus_js () {
  785. global $log;
  786. $log->debug("Entering set_focus() method ...");
  787. //TODO Clint 5/20 - Make this function more generic so that it can take in the target form and vtiger_field names as variables
  788. $the_script = <<<EOQ
  789. <script type="text/javascript" language="JavaScript">
  790. <!-- Begin
  791. function set_focus() {
  792. if (document.forms.length > 0) {
  793. for (i = 0; i < document.forms.length; i++) {
  794. for (j = 0; j < document.forms[i].elements.length; j++) {
  795. var vtiger_field = document.forms[i].elements[j];
  796. if ((vtiger_field.type == "text" || vtiger_field.type == "textarea" || vtiger_field.type == "password") &&
  797. !field.disabled && (vtiger_field.name == "first_name" || vtiger_field.name == "name")) {
  798. vtiger_field.focus();
  799. if (vtiger_field.type == "text") {
  800. vtiger_field.select();
  801. }
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. }
  808. // End -->
  809. </script>
  810. EOQ;
  811. $log->debug("Exiting get_set_focus_js method ...");
  812. return $the_script;
  813. }
  814. /**
  815. * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php
  816. * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...);
  817. * Explanation: $array is the array you want to sort, 'col1' is the name of the column
  818. * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING
  819. * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to
  820. * the first - so the array is sorted by the last given column first, then the one before ...
  821. * Example: $array = array_csort($array,'town','age',SORT_DESC,'name');
  822. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  823. * All Rights Reserved.
  824. * Contributor(s): ______________________________________..
  825. */
  826. function array_csort() {
  827. global $log;
  828. $log->debug("Entering array_csort() method ...");
  829. $args = func_get_args();
  830. $marray = array_shift($args);
  831. $i = 0;
  832. $msortline = "return(array_multisort(";
  833. foreach ($args as $arg) {
  834. $i++;
  835. if (is_string($arg)) {
  836. foreach ($marray as $row) {
  837. $sortarr[$i][] = $row[$arg];
  838. }
  839. } else {
  840. $sortarr[$i] = $arg;
  841. }
  842. $msortline .= "\$sortarr[".$i."],";
  843. }
  844. $msortline .= "\$marray));";
  845. eval($msortline);
  846. $log->debug("Exiting array_csort method ...");
  847. return $marray;
  848. }
  849. /** Function to set default varibles on to the global variable
  850. * @param $defaults -- default values:: Type array
  851. */
  852. function set_default_config(&$defaults)
  853. {
  854. global $log;
  855. $log->debug("Entering set_default_config(".$defaults.") method ...");
  856. foreach ($defaults as $name=>$value)
  857. {
  858. if ( ! isset($GLOBALS[$name]) )
  859. {
  860. $GLOBALS[$name] = $value;
  861. }
  862. }
  863. $log->debug("Exiting set_default_config method ...");
  864. }
  865. $toHtml = array(
  866. '"' => '&quot;',
  867. '<' => '&lt;',
  868. '>' => '&gt;',
  869. '& ' => '&amp; ',
  870. "'" => '&#039;',
  871. '' => '\r',
  872. '\r\n'=>'\n',
  873. );
  874. /** Function to convert the given string to html
  875. * @param $string -- string:: Type string
  876. * @param $ecnode -- boolean:: Type boolean
  877. * @returns $string -- string:: Type string
  878. *
  879. */
  880. function to_html($string, $encode=true)
  881. {
  882. global $log,$default_charset;
  883. //$log->debug("Entering to_html(".$string.",".$encode.") method ...");
  884. global $toHtml;
  885. $action = $_REQUEST['action'];
  886. $search = $_REQUEST['search'];
  887. $doconvert = false;
  888. if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails')
  889. $ajax_action = $_REQUEST['module'].'Ajax';
  890. if(is_string($string))
  891. {
  892. if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) )
  893. {
  894. $doconvert = true;
  895. }
  896. else if($search == true)
  897. {
  898. // Fix for tickets #4647, #4648. Conversion required in case of search results also.
  899. $doconvert = true;
  900. }
  901. if ($doconvert == true)
  902. {
  903. if(strtolower($default_charset) == 'utf-8')
  904. $string = htmlentities($string, ENT_QUOTES, $default_charset);
  905. else
  906. $string = preg_replace(array('/</', '/>/', '/"/'), array('&lt;', '&gt;', '&quot;'), $string);
  907. }
  908. }
  909. //$log->debug("Exiting to_html method ...");
  910. return $string;
  911. }
  912. /** Function to get the tablabel for a given id
  913. * @param $tabid -- tab id:: Type integer
  914. * @returns $string -- string:: Type string
  915. */
  916. function getTabname($tabid)
  917. {
  918. global $log;
  919. $log->debug("Entering getTabname(".$tabid.") method ...");
  920. $log->info("tab id is ".$tabid);
  921. global $adb;
  922. $sql = "select tablabel from vtiger_tab where tabid=?";
  923. $result = $adb->pquery($sql, array($tabid));
  924. $tabname= $adb->query_result($result,0,"tablabel");
  925. $log->debug("Exiting getTabname method ...");
  926. return $tabname;
  927. }
  928. /** Function to get the tab module name for a given id
  929. * @param $tabid -- tab id:: Type integer
  930. * @returns $string -- string:: Type string
  931. *
  932. */
  933. function getTabModuleName($tabid)
  934. {
  935. global $log;
  936. $log->debug("Entering getTabModuleName(".$tabid.") method ...");
  937. // Lookup information in cache first
  938. $tabname = VTCacheUtils::lookupModulename($tabid);
  939. if($tabname === false) {
  940. if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) {
  941. include('tabdata.php');
  942. $tabname = array_search($tabid,$tab_info_array);
  943. if($tabname == false) {
  944. global $adb;
  945. $sql = "select name from vtiger_tab where tabid=?";
  946. $result = $adb->pquery($sql, array($tabid));
  947. $tabname= $adb->query_result($result,0,"name");
  948. }
  949. // Update information to cache for re-use
  950. VTCacheUtils::updateTabidInfo($tabid, $tabname);
  951. } else {
  952. $log->info("tab id is ".$tabid);
  953. global $adb;
  954. $sql = "select name from vtiger_tab where tabid=?";
  955. $result = $adb->pquery($sql, array($tabid));
  956. $tabname= $adb->query_result($result,0,"name");
  957. // Update information to cache for re-use
  958. VTCacheUtils::updateTabidInfo($tabid, $tabname);
  959. }
  960. }
  961. $log->debug("Exiting getTabModuleName method ...");
  962. return $tabname;
  963. }
  964. /** Function to get column fields for a given module
  965. * @param $module -- module:: Type string
  966. * @returns $column_fld -- column field :: Type array
  967. *
  968. */
  969. function getColumnFields($module)
  970. {
  971. global $log;
  972. $log->debug("Entering getColumnFields(".$module.") method ...");
  973. $log->debug("in getColumnFields ".$module);
  974. // Lookup in cache for information
  975. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  976. if($cachedModuleFields === false) {
  977. global $adb;
  978. $tabid = getTabid($module);
  979. if ($module == 'Calendar') {
  980. $tabid = array('9','16');
  981. }
  982. // Let us pick up all the fields first so that we can cache information
  983. $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence
  984. FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")";
  985. $result = $adb->pquery($sql, array($tabid));
  986. $noofrows = $adb->num_rows($result);
  987. if($noofrows) {
  988. while($resultrow = $adb->fetch_array($result)) {
  989. // Update information to cache for re-use
  990. VTCacheUtils::updateFieldInfo(
  991. $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'],
  992. $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'],
  993. $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']
  994. );
  995. }
  996. }
  997. // For consistency get information from cache
  998. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  999. }
  1000. if($module == 'Calendar') {
  1001. $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events');
  1002. if($cachedModuleFields == false) $cachedModuleFields = $cachedEventsFields;
  1003. else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields);
  1004. }
  1005. $column_fld = array();
  1006. if($cachedModuleFields) {
  1007. foreach($cachedModuleFields as $fieldinfo) {
  1008. $column_fld[$fieldinfo['fieldname']] = '';
  1009. }
  1010. }
  1011. $log->debug("Exiting getColumnFields method ...");
  1012. return $column_fld;
  1013. }
  1014. /** Function to get a users's mail id
  1015. * @param $userid -- userid :: Type integer
  1016. * @returns $email -- email :: Type string
  1017. *
  1018. */
  1019. function getUserEmail($userid)
  1020. {
  1021. global $log;
  1022. $log->debug("Entering getUserEmail(".$userid.") method ...");
  1023. $log->info("in getUserEmail ".$userid);
  1024. global $adb;
  1025. if($userid != '')
  1026. {
  1027. $sql = "select email1 from vtiger_users where id=?";
  1028. $result = $adb->pquery($sql, array($userid));
  1029. $email = $adb->query_result($result,0,"email1");
  1030. }
  1031. $log->debug("Exiting getUserEmail method ...");
  1032. return $email;
  1033. }
  1034. /** Function to get a userid for outlook
  1035. * @param $username -- username :: Type string
  1036. * @returns $user_id -- user id :: Type integer
  1037. */
  1038. //outlook security
  1039. function getUserId_Ol($username)
  1040. {
  1041. global $log;
  1042. $log->debug("Entering getUserId_Ol(".$username.") method ...");
  1043. $log->info("in getUserId_Ol ".$username);
  1044. global $adb;
  1045. $sql = "select id from vtiger_users where user_name=?";
  1046. $result = $adb->pquery($sql, array($username));
  1047. $num_rows = $adb->num_rows($result);
  1048. if($num_rows > 0)
  1049. {
  1050. $user_id = $adb->query_result($result,0,"id");
  1051. }
  1052. else
  1053. {
  1054. $user_id = 0;
  1055. }
  1056. $log->debug("Exiting getUserId_Ol method ...");
  1057. return $user_id;
  1058. }
  1059. /** Function to get a action id for a given action name
  1060. * @param $action -- action name :: Type string
  1061. * @returns $actionid -- action id :: Type integer
  1062. */
  1063. //outlook security
  1064. function getActionid($action)
  1065. {
  1066. global $log;
  1067. $log->debug("Entering getActionid(".$action.") method ...");
  1068. global $adb;
  1069. $log->info("get Actionid ".$action);
  1070. $actionid = '';
  1071. if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0))
  1072. {
  1073. include('tabdata.php');
  1074. $actionid= $action_id_array[$action];
  1075. }
  1076. else
  1077. {
  1078. $query="select * from vtiger_actionmapping where actionname=?";
  1079. $result =$adb->pquery($query, array($action));
  1080. $actionid=$adb->query_result($result,0,'actionid');
  1081. }
  1082. $log->info("action id selected is ".$actionid );
  1083. $log->debug("Exiting getActionid method ...");
  1084. return $actionid;
  1085. }
  1086. /** Function to get a action for a given action id
  1087. * @param $action id -- action id :: Type integer
  1088. * @returns $actionname-- action name :: Type string
  1089. */
  1090. function getActionname($actionid)
  1091. {
  1092. global $log;
  1093. $log->debug("Entering getActionname(".$actionid.") method ...");
  1094. global $adb;
  1095. $actionname='';
  1096. if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0))
  1097. {
  1098. include('tabdata.php');
  1099. $actionname= $action_name_array[$actionid];
  1100. }
  1101. else
  1102. {
  1103. $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0";
  1104. $result =$adb->pquery($query, array($actionid));
  1105. $actionname=$adb->query_result($result,0,"actionname");
  1106. }
  1107. $log->debug("Exiting getActionname method ...");
  1108. return $actionname;
  1109. }
  1110. /** Function to get a assigned user id for a given entity
  1111. * @param $record -- entity id :: Type integer
  1112. * @returns $user_id -- user id :: Type integer
  1113. */
  1114. function getUserId($record)
  1115. {
  1116. global $log;
  1117. $log->debug("Entering getUserId(".$record.") method ...");
  1118. $log->info("in getUserId ".$record);
  1119. global $adb;
  1120. $user_id=$adb->query_result($adb->pquery("select * from vtiger_crmentity where crmid = ?", array($record)),0,'smownerid');
  1121. $log->debug("Exiting getUserId method ...");
  1122. return $user_id;
  1123. }
  1124. /** Function to get a user id or group id for a given entity
  1125. * @param $record -- entity id :: Type integer
  1126. * @returns $ownerArr -- owner id :: Type array
  1127. */
  1128. function getRecordOwnerId($record)
  1129. {
  1130. global $log;
  1131. $log->debug("Entering getRecordOwnerId(".$record.") method ...");
  1132. global $adb;
  1133. $ownerArr=Array();
  1134. $query="select smownerid from vtiger_crmentity where crmid = ?";
  1135. $result=$adb->pquery($query, array($record));
  1136. if($adb->num_rows($result) > 0)
  1137. {
  1138. $ownerId=$adb->query_result($result,0,'smownerid');
  1139. $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId));
  1140. if($adb->query_result($sql_result,0,'count') > 0)
  1141. $ownerArr['Users'] = $ownerId;
  1142. else
  1143. $ownerArr['Groups'] = $ownerId;
  1144. }
  1145. $log->debug("Exiting getRecordOwnerId method ...");
  1146. return $ownerArr;
  1147. }
  1148. /** Function to insert value to profile2field table
  1149. * @param $profileid -- profileid :: Type integer
  1150. */
  1151. function insertProfile2field($profileid)
  1152. {
  1153. global $log;
  1154. $log->debug("Entering insertProfile2field(".$profileid.") method ...");
  1155. $log->info("in insertProfile2field ".$profileid);
  1156. global $adb;
  1157. $adb->database->SetFetchMode(ADODB_FETCH_ASSOC);
  1158. $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array());
  1159. $num_rows = $adb->num_rows($fld_result);
  1160. for($i=0; $i<$num_rows; $i++) {
  1161. $tab_id = $adb->query_result($fld_result,$i,'tabid');
  1162. $field_id = $adb->query_result($fld_result,$i,'fieldid');
  1163. $params = array($profileid, $tab_id, $field_id, 0, 0);
  1164. $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params);
  1165. }
  1166. $log->debug("Exiting insertProfile2field method ...");
  1167. }
  1168. /** Function to insert into default org field
  1169. */
  1170. function insert_def_org_field()
  1171. {
  1172. global $log;
  1173. $log->debug("Entering insert_def_org_field() method ...");
  1174. global $adb;
  1175. $adb->database->SetFetchMode(ADODB_FETCH_ASSOC);
  1176. $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array());
  1177. $num_rows = $adb->num_rows($fld_result);
  1178. for($i=0; $i<$num_rows; $i++)
  1179. {
  1180. $tab_id = $adb->query_result($fld_result,$i,'tabid');
  1181. $field_id = $adb->query_result($fld_result,$i,'fieldid');
  1182. $params = array($tab_id, $field_id, 0, 0);
  1183. $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params);
  1184. }
  1185. $log->debug("Exiting insert_def_org_field() method ...");
  1186. }
  1187. /** Function to insert value to profile2field table
  1188. * @param $fld_module -- field module :: Type string
  1189. * @param $profileid -- profileid :: Type integer
  1190. * @returns $result -- result :: Type string
  1191. */
  1192. function getProfile2FieldList($fld_module, $profileid)
  1193. {
  1194. global $log;
  1195. $log->debug("Entering getProfile2FieldList(".$fld_module.",". $profileid.") method ...");
  1196. $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid);
  1197. global $adb;
  1198. $tabid = getTabid($fld_module);
  1199. $query = "select vtiger_profile2field.visible,vtiger_field.* from vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid=vtiger_profile2field.fieldid where vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,1,2)";
  1200. $result = $adb->pquery($query, array($profileid, $tabid));
  1201. $log->debug("Exiting getProfile2FieldList method ...");
  1202. return $result;
  1203. }
  1204. /** Function to insert value to profile2fieldPermissions table
  1205. * @param $fld_module -- field module :: Type string
  1206. * @param $profileid -- profileid :: Type integer
  1207. * @returns $return_data -- return_data :: Type string
  1208. */
  1209. //added by jeri
  1210. function getProfile2FieldPermissionList($fld_module, $profileid)
  1211. {
  1212. global $log;
  1213. $log->debug("Entering getProfile2FieldPermissionList(".$fld_module.",". $profileid.") method ...");
  1214. $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid);
  1215. // Cache information to re-use
  1216. static $_module_fieldpermission_cache = array();
  1217. if(!isset($_module_fieldpermission_cache[$fld_module])) {
  1218. $_module_fieldpermission_cache[$fld_module] = array();
  1219. }
  1220. // Lookup cache first
  1221. $return_data = VTCacheUtils::lookupProfile2FieldPermissionList($fld_module, $profileid);
  1222. if($return_data === false) {
  1223. $return_data = array();
  1224. global $adb;
  1225. $tabid = getTabid($fld_module);
  1226. $query = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly, vtiger_field.fieldlabel, vtiger_field.uitype,
  1227. vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata
  1228. FROM vtiger_profile2field INNER JOIN vtiger_field ON vtiger_field.fieldid=vtiger_profile2field.fieldid
  1229. WHERE vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)";
  1230. $qparams = array($profileid, $tabid);
  1231. $result = $adb->pquery($query, $qparams);
  1232. for($i=0; $i<$adb->num_rows($result); $i++) {
  1233. $return_data[]=array(
  1234. $adb->query_result($result,$i,"fieldlabel"),
  1235. $adb->query_result($result,$i,"visible"), // From vtiger_profile2field.visible
  1236. $adb->query_result($result,$i,"uitype"),
  1237. $adb->query_result($result,$i,"readonly"),
  1238. $adb->query_result($result,$i,"fieldid"),
  1239. $adb->query_result($result,$i,"displaytype"),
  1240. $adb->query_result($result,$i,"typeofdata")
  1241. );
  1242. }
  1243. // Update information to cache for re-use
  1244. VTCacheUtils::updateProfile2FieldPermissionList($fld_module, $profileid, $return_data);
  1245. }
  1246. $log->debug("Exiting getProfile2FieldPermissionList method ...");
  1247. return $return_data;
  1248. }
  1249. /** Function to insert value to profile2fieldPermissions table
  1250. * @param $fld_module -- field module :: Type string
  1251. * @param $profileid -- profileid :: Type integer
  1252. * @returns $return_data -- return_data :: Type string
  1253. */
  1254. function getProfile2ModuleFieldPermissionList($fld_module, $profileid) {
  1255. global $log;
  1256. $log->debug("Entering getProfile2ModuleFieldPermissionList(".$fld_module.",". $profileid.") method ...");
  1257. $log->info("in getProfile2ModuleFieldList ".$fld_module. ' vtiger_profile id is '.$profileid);
  1258. // Cache information to re-use
  1259. static $_module_fieldpermission_cache = array();
  1260. if(!isset($_module_fieldpermission_cache[$fld_module])) {
  1261. $_module_fieldpermission_cache[$fld_module] = array();
  1262. }
  1263. $return_data = array();
  1264. global $adb;
  1265. $tabid = getTabid($fld_module);
  1266. $query = "SELECT vtiger_profile2tab.tabid, vtiger_profile2tab.permissions, vtiger_field.fieldlabel, vtiger_field.uitype,
  1267. vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata
  1268. FROM vtiger_profile2tab INNER JOIN vtiger_field ON vtiger_field.tabid=vtiger_profile2tab.tabid
  1269. WHERE vtiger_profile2tab.profileid=? AND vtiger_profile2tab.tabid=? AND vtiger_field.presence in (0,2)";
  1270. $qparams = array($profileid, $tabid);
  1271. $result = $adb->pquery($query, $qparams);
  1272. for($i=0; $i<$adb->num_rows($result); $i++) {
  1273. $fieldid = $adb->query_result($result,$i,"fieldid");
  1274. $checkentry = $adb->pquery("SELECT 1 FROM vtiger_profile2field WHERE profileid=? AND tabid=? AND fieldid =?",array($profileid,$tabid,$fieldid));
  1275. $visible_value = 0;
  1276. $readOnlyValue = 0;
  1277. if($adb->num_rows($checkentry) == 0) {
  1278. $sql11="INSERT INTO vtiger_profile2field VALUES(?,?,?,?,?)";
  1279. $adb->pquery($sql11, array($profileid, $tabid, $fieldid,$visible_value, $readOnlyValue));
  1280. }
  1281. $sql = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly FROM vtiger_profile2field WHERE fieldid=? AND tabid=? AND profileid=?";
  1282. $params = array($fieldid,$tabid,$profileid);
  1283. $res = $adb->pquery($sql, $params);
  1284. $return_data[]=array(
  1285. $adb->query_result($result,$i,"fieldlabel"),
  1286. $adb->query_result($res,0,"visible"), // From vtiger_profile2field.visible
  1287. $adb->query_result($result,$i,"uitype"),
  1288. $adb->query_result($res,0,"readonly"), // From vtiger_profile2field.readonly
  1289. $adb->query_result($result,$i,"fieldid"),
  1290. $adb->query_result($result,$i,"displaytype"),
  1291. $adb->query_result($result,$i,"typeofdata")
  1292. );
  1293. }
  1294. $log->debug("Exiting getProfile2ModuleFieldPermissionList method ...");
  1295. return $return_data;
  1296. }
  1297. /** Function to getProfile2allfieldsListinsert value to profile2fieldPermissions table
  1298. * @param $mod_array -- mod_array :: Type string
  1299. * @param $profileid -- profileid :: Type integer
  1300. * @returns $profilelist -- profilelist :: Type string
  1301. */
  1302. function getProfile2AllFieldList($mod_array,$profileid)
  1303. {
  1304. global $log;
  1305. $log->debug("Entering getProfile2AllFieldList(".$mod_array.",".$profileid.") method ...");
  1306. $log->info("in getProfile2AllFieldList vtiger_profile id is " .$profileid);
  1307. global $adb;
  1308. $profilelist=array();
  1309. for($i=0;$i<count($mod_array);$i++)
  1310. {
  1311. $profilelist[key($mod_array)]=getProfile2ModuleFieldPermissionList(key($mod_array), $profileid);
  1312. next($mod_array);
  1313. }
  1314. $log->debug("Exiting getProfile2AllFieldList method ...");
  1315. return $profilelist;
  1316. }
  1317. /** Function to getdefaultfield organisation list for a given module
  1318. * @param $fld_module -- module name :: Type string
  1319. * @returns $result -- string :: Type object
  1320. */
  1321. //end of fn added by jeri
  1322. function getDefOrgFieldList($fld_module)
  1323. {
  1324. global $log;
  1325. $log->debug("Entering getDefOrgFieldList(".$fld_module.") method ...");
  1326. $log->info("in getDefOrgFieldList ".$fld_module);
  1327. global $adb;
  1328. $tabid = getTabid($fld_module);
  1329. $query = "select vtiger_def_org_field.visible,vtiger_field.* from vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid=vtiger_def_org_field.fieldid where vtiger_def_org_field.tabid=? and vtiger_field.presence in (0,2)";
  1330. $qparams = array($tabid);
  1331. $result = $adb->pquery($query, $qparams);
  1332. $log->debug("Exiting getDefOrgFieldList method ...");
  1333. return $result;
  1334. }
  1335. /** Function to getQuickCreate for a given tabid
  1336. * @param $tabid -- tab id :: Type string
  1337. * @param $actionid -- action id :: Type integer
  1338. * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean
  1339. */
  1340. function getQuickCreate($tabid,$actionid)
  1341. {
  1342. global $log;
  1343. $log->debug("Entering getQuickCreate(".$tabid.",".$actionid.") method ...");
  1344. $module=getTabModuleName($tabid);
  1345. $actionname=getActionname($actionid);
  1346. $QuickCreateForm= 'true';
  1347. $perr=isPermitted($module,$actionname);
  1348. if($perr == 'no')
  1349. {
  1350. $QuickCreateForm= 'false';
  1351. }
  1352. $log->debug("Exiting getQuickCreate method ...");
  1353. return $QuickCreateForm;
  1354. }
  1355. /** Function to getQuickCreate for a given tabid
  1356. * @param $tabid -- tab id :: Type string
  1357. * @param $actionid -- action id :: Type integer
  1358. * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean
  1359. */
  1360. function ChangeStatus($status,$activityid,$activity_mode='')
  1361. {
  1362. global $log;
  1363. $log->debug("Entering ChangeStatus(".$status.",".$activityid.",".$activity_mode."='') method ...");
  1364. $log->info("in ChangeStatus ".$status. ' vtiger_activityid is '.$activityid);
  1365. global $adb;
  1366. if ($activity_mode == 'Task')
  1367. {
  1368. $query = "Update vtiger_activity set status=? where activityid = ?";
  1369. }
  1370. elseif ($activity_mode == 'Events')
  1371. {
  1372. $query = "Update vtiger_activity set eventstatus=? where activityid = ?";
  1373. }
  1374. if($query) {
  1375. $adb->pquery($query, array($status, $activityid));
  1376. }
  1377. $log->debug("Exiting ChangeStatus method ...");
  1378. }
  1379. /** Function to get unitprice for a given product id
  1380. * @param $productid -- product id :: Type integer
  1381. * @returns $up -- up :: Type string
  1382. */
  1383. function getUnitPrice($productid, $module='Products')
  1384. {
  1385. global $log, $adb;
  1386. $log->debug("Entering getUnitPrice($productid,$module) method ...");
  1387. if($module == 'Services') {
  1388. $query = "select unit_price from vtiger_service where serviceid=?";
  1389. } else {
  1390. $query = "select unit_price from vtiger_products where productid=?";
  1391. }
  1392. $result = $adb->pquery($query, array($productid));
  1393. $unitpice = $adb->query_result($result,0,'unit_price');
  1394. $log->debug("Exiting getUnitPrice method ...");
  1395. return $unitpice;
  1396. }
  1397. /** Function to upload product image file
  1398. * @param $mode -- mode :: Type string
  1399. * @param $id -- id :: Type integer
  1400. * @returns $ret_array -- return array:: Type array
  1401. */
  1402. function upload_product_image_file($mode,$id)
  1403. {
  1404. global $log;
  1405. $log->debug("Entering upload_product_image_file(".$mode.",".$id.") method ...");
  1406. global $root_directory;
  1407. $log->debug("Inside upload_product_image_file. The id is ".$id);
  1408. $uploaddir = $root_directory ."/test/product/";
  1409. $file_path_name = $_FILES['imagename']['name'];
  1410. if (isset($_REQUEST['imagename_hidden'])) {
  1411. $file_name = $_REQUEST['imagename_hidden'];
  1412. } else {
  1413. //allowed file pathname like UTF-8 Character
  1414. $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name);
  1415. }
  1416. $file_name = $id.'_'.$file_name;
  1417. $filetype= $_FILES['imagename']['type'];
  1418. $filesize = $_FILES['imagename']['size'];
  1419. $ret_array = Array();
  1420. if($filesize > 0)
  1421. {
  1422. if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name))
  1423. {
  1424. $upload_status = "yes";
  1425. $ret_array["status"] = $upload_status;
  1426. $ret_array["file_name"] = $file_name;
  1427. }
  1428. else
  1429. {
  1430. $errorCode = $_FILES['imagename']['error'];
  1431. $upload_status = "no";
  1432. $ret_array["status"] = $upload_status;
  1433. $ret_array["errorcode"] = $errorCode;
  1434. }
  1435. }
  1436. else
  1437. {
  1438. $upload_status = "no";
  1439. $ret_array["status"] = $upload_status;
  1440. }
  1441. $log->debug("Exiting upload_product_image_file method ...");
  1442. return $ret_array;
  1443. }
  1444. /** Function to upload product image file
  1445. * @param $id -- id :: Type integer
  1446. * @param $deleted_array -- images to be deleted :: Type array
  1447. * @returns $imagename -- imagelist:: Type array
  1448. */
  1449. function getProductImageName($id,$deleted_array='')
  1450. {
  1451. global $log;
  1452. $log->debug("Entering getProductImageName(".$id.",".$deleted_array."='') method ...");
  1453. global $adb;
  1454. $image_array=array();
  1455. $query = "select imagename from vtiger_products where productid=?";
  1456. $result = $adb->pquery($query, array($id));
  1457. $image_name = $adb->query_result($result,0,"imagename");
  1458. $image_array=explode("###",$image_name);
  1459. $log->debug("Inside getProductImageName. The image_name is ".$image_name);
  1460. if($deleted_array!='')
  1461. {
  1462. $resultant_image = array();
  1463. $resultant_image=array_merge(array_diff($image_array,$deleted_array));
  1464. $imagelists=implode('###',$resultant_image);
  1465. $log->debug("Exiting getProductImageName method ...");
  1466. return $imagelists;
  1467. }
  1468. else
  1469. {
  1470. $log->debug("Exiting getProductImageName method ...");
  1471. return $image_name;
  1472. }
  1473. }
  1474. /** Function to get Contact images
  1475. * @param $id -- id :: Type integer
  1476. * @returns $imagename -- imagename:: Type string
  1477. */
  1478. function getContactImageName($id)
  1479. {
  1480. global $log;
  1481. $log->debug("Entering getContactImageName(".$id.") method ...");
  1482. global $adb;
  1483. $query = "select imagename from vtiger_contactdetails where contactid=?";
  1484. $result = $adb->pquery($query, array($id));
  1485. $image_name = $adb->query_result($result,0,"imagename");
  1486. $log->debug("Inside getContactImageName. The image_name is ".$image_name);
  1487. $log->debug("Exiting getContactImageName method ...");
  1488. return $image_name;
  1489. }
  1490. /** Function to update sub total in inventory
  1491. * @param $module -- module name :: Type string
  1492. * @param $tablename -- tablename :: Type string
  1493. * @param $colname -- colname :: Type string
  1494. * @param $colname1 -- coluname1 :: Type string
  1495. * @param $entid_fld -- entity field :: Type string
  1496. * @param $entid -- entid :: Type integer
  1497. * @param $prod_total -- totalproduct :: Type integer
  1498. */
  1499. function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total)
  1500. {
  1501. global $log;
  1502. $log->debug("Entering updateSubTotal(".$module.",".$tablename.",".$colname.",".$colname1.",".$entid_fld.",".$entid.",".$prod_total.") method ...");
  1503. global $adb;
  1504. //getting the subtotal
  1505. $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=?";
  1506. $result1 = $adb->pquery($query, array($entid));
  1507. $subtot = $adb->query_result($result1,0,$colname);
  1508. $subtot_upd = $subtot - $prod_total;
  1509. $gdtot = $adb->query_result($result1,0,$colname1);
  1510. $gdtot_upd = $gdtot - $prod_total;
  1511. //updating the subtotal
  1512. $sub_query = "update $tablename set $colname=?, $colname1=? where $entid_fld=?";
  1513. $adb->pquery($sub_query, array($subtot_upd, $gdtot_upd, $entid));
  1514. $log->debug("Exiting updateSubTotal method ...");
  1515. }
  1516. /** Function to get Inventory Total
  1517. * @param $return_module -- return module :: Type string
  1518. * @param $id -- entity id :: Type integer
  1519. * @returns $total -- total:: Type integer
  1520. */
  1521. function getInventoryTotal($return_module,$id)
  1522. {
  1523. global $log;
  1524. $log->debug("Entering getInventoryTotal(".$return_module.",".$id.") method ...");
  1525. global $adb;
  1526. if($return_module == "Potentials")
  1527. {
  1528. $query ="select vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?";
  1529. }
  1530. elseif($return_module == "Products")
  1531. {
  1532. $query="select vtiger_products.productid,vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?";
  1533. }
  1534. $result = $adb->pquery($query, array($id));
  1535. $num_rows=$adb->num_rows($result);
  1536. $total=0;
  1537. for($i=1;$i<=$num_rows;$i++)
  1538. {
  1539. $unitprice=$adb->query_result($result,$i-1,'unit_price');
  1540. $qty=$adb->query_result($result,$i-1,'quantity');
  1541. $listprice=$adb->query_result($result,$i-1,'listprice');
  1542. if($listprice == '')
  1543. $listprice = $unitprice;
  1544. if($qty =='')
  1545. $qty = 1;
  1546. $total = $total+($qty*$listprice);
  1547. }
  1548. $log->debug("Exiting getInventoryTotal method ...");
  1549. return $total;
  1550. }
  1551. /** Function to update product quantity
  1552. * @param $product_id -- product id :: Type integer
  1553. * @param $upd_qty -- quantity :: Type integer
  1554. */
  1555. function updateProductQty($product_id, $upd_qty)
  1556. {
  1557. global $log;
  1558. $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ...");
  1559. global $adb;
  1560. $query= "update vtiger_products set qtyinstock=? where productid=?";
  1561. $adb->pquery($query, array($upd_qty, $product_id));
  1562. $log->debug("Exiting updateProductQty method ...");
  1563. }
  1564. /** Function to get account information
  1565. * @param $parent_id -- parent id :: Type integer
  1566. * @returns $accountid -- accountid:: Type integer
  1567. */
  1568. function get_account_info($parent_id)
  1569. {
  1570. global $log;
  1571. $log->debug("Entering get_account_info(".$parent_id.") method ...");
  1572. global $adb;
  1573. $query = "select related_to from vtiger_potential where potentialid=?";
  1574. $result = $adb->pquery($query, array($parent_id));
  1575. $accountid=$adb->query_result($result,0,'related_to');
  1576. $log->debug("Exiting get_account_info method ...");
  1577. return $accountid;
  1578. }
  1579. /** Function to get quick create form fields
  1580. * @param $fieldlabel -- field label :: Type string
  1581. * @param $uitype -- uitype :: Type integer
  1582. * @param $fieldname -- field name :: Type string
  1583. * @param $tabid -- tabid :: Type integer
  1584. * @returns $return_field -- return field:: Type string
  1585. */
  1586. //for Quickcreate-Form
  1587. function get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid)
  1588. {
  1589. global $log;
  1590. $log->debug("Entering get_quickcreate_form(".$fieldlabel.",".$uitype.",".$fieldname.",".$tabid.") method ...");
  1591. $return_field ='';
  1592. switch($uitype)
  1593. {
  1594. case 1: $return_field .=get_textField($fieldlabel,$fieldname);
  1595. $log->debug("Exiting get_quickcreate_form method ...");
  1596. return $return_field;
  1597. break;
  1598. case 2: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid);
  1599. $log->debug("Exiting get_quickcreate_form method ...");
  1600. return $return_field;
  1601. break;
  1602. case 6: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid);
  1603. $log->debug("Exiting get_quickcreate_form method ...");
  1604. return $return_field;
  1605. break;
  1606. case 11: $return_field .=get_textField($fieldlabel,$fieldname);
  1607. $log->debug("Exiting get_quickcreate_form method ...");
  1608. return $return_field;
  1609. break;
  1610. case 13: $return_field .=get_textField($fieldlabel,$fieldname);
  1611. $log->debug("Exiting get_quickcreate_form method ...");
  1612. return $return_field;
  1613. break;
  1614. case 15: $return_field .=get_textcomboField($fieldlabel,$fieldname);
  1615. $log->debug("Exiting get_quickcreate_form method ...");
  1616. return $return_field;
  1617. break;
  1618. case 16: $return_field .=get_textcomboField($fieldlabel,$fieldname);
  1619. $log->debug("Exiting get_quickcreate_form method ...");
  1620. return $return_field;
  1621. break;
  1622. case 17: $return_field .=get_textwebField($fieldlabel,$fieldname);
  1623. $log->debug("Exiting get_quickcreate_form method ...");
  1624. return $return_field;
  1625. break;
  1626. case 19: $return_field .=get_textField($fieldlabel,$fieldname);
  1627. $log->debug("Exiting get_quickcreate_form method ...");
  1628. return $return_field;
  1629. break;
  1630. case 22: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid);
  1631. $log->debug("Exiting get_quickcreate_form method ...");
  1632. return $return_field;
  1633. break;
  1634. case 23: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid);
  1635. $log->debug("Exiting get_quickcreate_form method ...");
  1636. return $return_field;
  1637. break;
  1638. case 50: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid);
  1639. $log->debug("Exiting get_quickcreate_form method ...");
  1640. return $return_field;
  1641. break;
  1642. case 51: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid);
  1643. $log->debug("Exiting get_quickcreate_form method ...");
  1644. return $return_field;
  1645. break;
  1646. case 55: $return_field .=get_textField($fieldlabel,$fieldname);
  1647. $log->debug("Exiting get_quickcreate_form method ...");
  1648. return $return_field;
  1649. break;
  1650. case 63: $return_field .=get_textdurationField($fieldlabel,$fieldname,$tabid);
  1651. $log->debug("Exiting get_quickcreate_form method ...");
  1652. return $return_field;
  1653. break;
  1654. case 71: $return_field .=get_textField($fieldlabel,$fieldname);
  1655. $log->debug("Exiting get_quickcreate_form method ...");
  1656. return $return_field;
  1657. break;
  1658. }
  1659. }
  1660. /** Function to get quick create form fields
  1661. * @param $label -- field label :: Type string
  1662. * @param $name -- field name :: Type string
  1663. * @param $tid -- tabid :: Type integer
  1664. * @returns $form_field -- return field:: Type string
  1665. */
  1666. function get_textmanField($label,$name,$tid)
  1667. {
  1668. global $log;
  1669. $log->debug("Entering get_textmanField(".$label.",".$name.",".$tid.") method ...");
  1670. $form_field='';
  1671. if($tid == 9)
  1672. {
  1673. $form_field .='<td>';
  1674. $form_field .= '<font color="red">*</font>';
  1675. $form_field .= $label.':<br>';
  1676. $form_field .='<input name="'.$name.'" id="QCK_T_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1677. $log->debug("Exiting get_textmanField method ...");
  1678. return $form_field;
  1679. }
  1680. if($tid == 16)
  1681. {
  1682. $form_field .='<td>';
  1683. $form_field .= '<font color="red">*</font>';
  1684. $form_field .= $label.':<br>';
  1685. $form_field .='<input name="'.$name.'" id="QCK_E_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1686. $log->debug("Exiting get_textmanField method ...");
  1687. return $form_field;
  1688. }
  1689. else
  1690. {
  1691. $form_field .='<td>';
  1692. $form_field .= '<font color="red">*</font>';
  1693. $form_field .= $label.':<br>';
  1694. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1695. $log->debug("Exiting get_textmanField method ...");
  1696. return $form_field;
  1697. }
  1698. }
  1699. /** Function to get textfield for website field
  1700. * @param $label -- field label :: Type string
  1701. * @param $name -- field name :: Type string
  1702. * @returns $form_field -- return field:: Type string
  1703. */
  1704. function get_textwebField($label,$name)
  1705. {
  1706. global $log;
  1707. $log->debug("Entering get_textwebField(".$label.",".$name.") method ...");
  1708. $form_field='';
  1709. $form_field .='<td>';
  1710. $form_field .= $label.':<br>http://<br>';
  1711. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1712. $log->debug("Exiting get_textwebField method ...");
  1713. return $form_field;
  1714. }
  1715. /** Function to get textfield
  1716. * @param $label -- field label :: Type string
  1717. * @param $name -- field name :: Type string
  1718. * @returns $form_field -- return field:: Type string
  1719. */
  1720. function get_textField($label,$name)
  1721. {
  1722. global $log;
  1723. $log->debug("Entering get_textField(".$label.",".$name.") method ...");
  1724. $form_field='';
  1725. if($name == "amount")
  1726. {
  1727. $form_field .='<td>';
  1728. $form_field .= $label.':(U.S Dollar:$)<br>';
  1729. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1730. $log->debug("Exiting get_textField method ...");
  1731. return $form_field;
  1732. }
  1733. else
  1734. {
  1735. $form_field .='<td>';
  1736. $form_field .= $label.':<br>';
  1737. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="20" maxlength="" value=""></td>';
  1738. $log->debug("Exiting get_textField method ...");
  1739. return $form_field;
  1740. }
  1741. }
  1742. /** Function to get account textfield
  1743. * @param $label -- field label :: Type string
  1744. * @param $name -- field name :: Type string
  1745. * @param $tid -- tabid :: Type integer
  1746. * @returns $form_field -- return field:: Type string
  1747. */
  1748. function get_textaccField($label,$name,$tid)
  1749. {
  1750. global $log;
  1751. $log->debug("Entering get_textaccField(".$label.",".$name.",".$tid.") method ...");
  1752. global $app_strings;
  1753. $form_field='';
  1754. if($tid == 2)
  1755. {
  1756. $form_field .='<td>';
  1757. $form_field .= '<font color="red">*</font>';
  1758. $form_field .= $label.':<br>';
  1759. $form_field .='<input name="account_name" type="text" size="20" maxlength="" id="account_name" value="" readonly><br>';
  1760. $form_field .='<input name="account_id" id="QCK_'.$name.'" type="hidden" value="">&nbsp;<input title="'.$app_strings[LBL_CHANGE_BUTTON_TITLE].'" accessKey="'.$app_strings[LBL_CHANGE_BUTTON_KEY].'" type="button" tabindex="3" class="button" value="'.$app_strings[LBL_CHANGE_BUTTON_LABEL].'" name="btn1" LANGUAGE=javascript onclick=\'return window.open("index.php?module=Accounts&action=Popup&popuptype=specific&form=EditView&form_submit=false","test","width=600,height=400,resizable=1,scrollbars=1");\'></td>';
  1761. $log->debug("Exiting get_textaccField method ...");
  1762. return $form_field;
  1763. }
  1764. else
  1765. {
  1766. $form_field .='<td>';
  1767. $form_field .= $label.':<br>';
  1768. $form_field .='<input name="account_name" type="text" size="20" maxlength="" value="" readonly><br>';
  1769. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="hidden" value="">&nbsp;<input title="'.$app_strings[LBL_CHANGE_BUTTON_TITLE].'" accessKey="'.$app_strings[LBL_CHANGE_BUTTON_KEY].'" type="button" tabindex="3" class="button" value="'.$app_strings[LBL_CHANGE_BUTTON_LABEL].'" name="btn1" LANGUAGE=javascript onclick=\'return window.open("index.php?module=Accounts&action=Popup&popuptype=specific&form=EditView&form_submit=false","test","width=600,height=400,resizable=1,scrollbars=1");\'></td>';
  1770. $log->debug("Exiting get_textaccField method ...");
  1771. return $form_field;
  1772. }
  1773. }
  1774. /** Function to get combo field values
  1775. * @param $label -- field label :: Type string
  1776. * @param $name -- field name :: Type string
  1777. * @returns $form_field -- return field:: Type string
  1778. */
  1779. function get_textcomboField($label,$name)
  1780. {
  1781. global $log;
  1782. $log->debug("Entering get_textcomboField(".$label.",".$name.") method ...");
  1783. $form_field='';
  1784. if($name == "sales_stage")
  1785. {
  1786. $comboFieldNames = Array('leadsource'=>'leadsource_dom'
  1787. ,'opportunity_type'=>'opportunity_type_dom'
  1788. ,'sales_stage'=>'sales_stage_dom');
  1789. $comboFieldArray = getComboArray($comboFieldNames);
  1790. $form_field .='<td>';
  1791. $form_field .= '<font color="red">*</font>';
  1792. $form_field .= $label.':<br>';
  1793. $form_field .='<select name="'.$name.'">';
  1794. $form_field .=get_select_options_with_id($comboFieldArray['sales_stage_dom'], "");
  1795. $form_field .='</select></td>';
  1796. $log->debug("Exiting get_textcomboField method ...");
  1797. return $form_field;
  1798. }
  1799. if($name == "productcategory")
  1800. {
  1801. $comboFieldNames = Array('productcategory'=>'productcategory_dom');
  1802. $comboFieldArray = getComboArray($comboFieldNames);
  1803. $form_field .='<td>';
  1804. $form_field .= $label.':<br>';
  1805. $form_field .='<select name="'.$name.'">';
  1806. $form_field .=get_select_options_with_id($comboFieldArray['productcategory_dom'], "");
  1807. $form_field .='</select></td>';
  1808. $log->debug("Exiting get_textcomboField method ...");
  1809. return $form_field;
  1810. }
  1811. if($name == "ticketpriorities")
  1812. {
  1813. $comboFieldNames = Array('ticketpriorities'=>'ticketpriorities_dom');
  1814. $comboFieldArray = getComboArray($comboFieldNames);
  1815. $form_field .='<td>';
  1816. $form_field .= $label.':<br>';
  1817. $form_field .='<select name="'.$name.'">';
  1818. $form_field .=get_select_options_with_id($comboFieldArray['ticketpriorities_dom'], "");
  1819. $form_field .='</select></td>';
  1820. $log->debug("Exiting get_textcomboField method ...");
  1821. return $form_field;
  1822. }
  1823. if($name == "activitytype")
  1824. {
  1825. $comboFieldNames = Array('activitytype'=>'activitytype_dom',
  1826. 'duration_minutes'=>'duration_minutes_dom');
  1827. $comboFieldArray = getComboArray($comboFieldNames);
  1828. $form_field .='<td>';
  1829. $form_field .= $label.'<br>';
  1830. $form_field .='<select name="'.$name.'">';
  1831. $form_field .=get_select_options_with_id($comboFieldArray['activitytype_dom'], "");
  1832. $form_field .='</select></td>';
  1833. $log->debug("Exiting get_textcomboField method ...");
  1834. return $form_field;
  1835. }
  1836. if($name == "eventstatus")
  1837. {
  1838. $comboFieldNames = Array('eventstatus'=>'eventstatus_dom');
  1839. $comboFieldArray = getComboArray($comboFieldNames);
  1840. $form_field .='<td>';
  1841. $form_field .= $label.'<br>';
  1842. $form_field .='<select name="'.$name.'">';
  1843. $form_field .=get_select_options_with_id($comboFieldArray['eventstatus_dom'], "");
  1844. $form_field .='</select></td>';
  1845. $log->debug("Exiting get_textcomboField method ...");
  1846. return $form_field;
  1847. }
  1848. if($name == "taskstatus")
  1849. {
  1850. $comboFieldNames = Array('taskstatus'=>'taskstatus_dom');
  1851. $comboFieldArray = getComboArray($comboFieldNames);
  1852. $form_field .='<td>';
  1853. $form_field .= $label.'<br>';
  1854. $form_field .='<select name="'.$name.'">';
  1855. $form_field .=get_select_options_with_id($comboFieldArray['taskstatus_dom'], "");
  1856. $form_field .='</select></td>';
  1857. $log->debug("Exiting get_textcomboField method ...");
  1858. return $form_field;
  1859. }
  1860. }
  1861. /** Function to get date field
  1862. * @param $label -- field label :: Type string
  1863. * @param $name -- field name :: Type string
  1864. * @param $tid -- tabid :: Type integer
  1865. * @returns $form_field -- return field:: Type string
  1866. */
  1867. function get_textdateField($label,$name,$tid)
  1868. {
  1869. global $log;
  1870. $log->debug("Entering get_textdateField(".$label.",".$name.",".$tid.") method ...");
  1871. global $theme;
  1872. global $app_strings;
  1873. global $current_user;
  1874. $ntc_date_format = $app_strings['NTC_DATE_FORMAT'];
  1875. $ntc_time_format = $app_strings['NTC_TIME_FORMAT'];
  1876. $form_field='';
  1877. $default_date_start = date('Y-m-d');
  1878. $default_time_start = date('H:i');
  1879. $dis_value=getNewDisplayDate();
  1880. if($tid == 2)
  1881. {
  1882. $form_field .='<td>';
  1883. $form_field .= '<font color="red">*</font>';
  1884. $form_field .= $label.':<br>';
  1885. $form_field .='<font size="1"><em old="ntc_date_format">('.$current_user->date_format.')</em></font><br>';
  1886. $form_field .='<input name="'.$name.'" size="12" maxlength="10" id="QCK_'.$name.'" type="text" value="">&nbsp';
  1887. $form_field .='<img src="themes/'.$theme.'/images/btnL3Calendar.gif" id="jscal_trigger"></td>';
  1888. $log->debug("Exiting get_textdateField method ...");
  1889. return $form_field;
  1890. }
  1891. if($tid == 9)
  1892. {
  1893. $form_field .='<td>';
  1894. $form_field .= '<font color="red">*</font>';
  1895. $form_field .= $label.':<br>';
  1896. $form_field .='<input name="'.$name.'" id="QCK_T_'.$name.'" tabindex="2" type="text" size="10" maxlength="10" value="'.$default_date_start.'">&nbsp';
  1897. $form_field.= '<img src="themes/'.$theme.'/images/btnL3Calendar.gif" id="jscal_trigger_date_start">&nbsp';
  1898. $form_field.='<input name="time_start" id="task_time_start" tabindex="1" type="text" size="5" maxlength="5" type="text" value="'.$default_time_start.'"><br><font size="1"><em old="ntc_date_format">('.$current_user->date_format.')</em></font>&nbsp<font size="1"><em>'.$ntc_time_format.'</em></font></td>';
  1899. $log->debug("Exiting get_textdateField method ...");
  1900. return $form_field;
  1901. }
  1902. if($tid == 16)
  1903. {
  1904. $form_field .='<td>';
  1905. $form_field .= '<font color="red">*</font>';
  1906. $form_field .= $label.':<br>';
  1907. $form_field .='<input name="'.$name.'" id="QCK_E_'.$name.'" tabindex="2" type="text" size="10" maxlength="10" value="'.$default_date_start.'">&nbsp';
  1908. $form_field.= '<img src="themes/'.$theme.'/images/btnL3Calendar.gif" id="jscal_trigger_event_date_start">&nbsp';
  1909. $form_field.='<input name="time_start" id="event_time_start" tabindex="1" type="text" size="5" maxlength="5" type="text" value="'.$default_time_start.'"><br><font size="1"><em old="ntc_date_format">('.$current_user->date_format.')</em></font>&nbsp<font size="1"><em>'.$ntc_time_format.'</em></font></td>';
  1910. $log->debug("Exiting get_textdateField method ...");
  1911. return $form_field;
  1912. }
  1913. else
  1914. {
  1915. $form_field .='<td>';
  1916. $form_field .= '<font color="red">*</font>';
  1917. $form_field .= $label.':<br>';
  1918. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="10" maxlength="10" value="'.$default_date_start.'">&nbsp';
  1919. $form_field.= '<img src="themes/'.$theme.'/images/btnL3Calendar.gif" id="jscal_trigger">&nbsp';
  1920. $form_field.='<input name="time_start" type="text" size="5" maxlength="5" type="text" value="'.$default_time_start.'"><br><font size="1"><em old="ntc_date_format">('.$current_user->date_format.')</em></font>&nbsp<font size="1"><em>'.$ntc_time_format.'</em></font></td>';
  1921. $log->debug("Exiting get_textdateField method ...");
  1922. return $form_field;
  1923. }
  1924. }
  1925. /** Function to get duration text field in activity
  1926. * @param $label -- field label :: Type string
  1927. * @param $name -- field name :: Type string
  1928. * @param $tid -- tabid :: Type integer
  1929. * @returns $form_field -- return field:: Type string
  1930. */
  1931. function get_textdurationField($label,$name,$tid)
  1932. {
  1933. global $log;
  1934. $log->debug("Entering get_textdurationField(".$label.",".$name.",".$tid.") method ...");
  1935. $form_field='';
  1936. if($tid == 16)
  1937. {
  1938. $comboFieldNames = Array('activitytype'=>'activitytype_dom',
  1939. 'duration_minutes'=>'duration_minutes_dom');
  1940. $comboFieldArray = getComboArray($comboFieldNames);
  1941. $form_field .='<td>';
  1942. $form_field .= $label.'<br>';
  1943. $form_field .='<input name="'.$name.'" id="QCK_'.$name.'" type="text" size="2" value="1">&nbsp;';
  1944. $form_field .='<select name="duration_minutes">';
  1945. $form_field .=get_select_options_with_id($comboFieldArray['duration_minutes_dom'], "");
  1946. $form_field .='</select><br>(hours/minutes)<br></td>';
  1947. $log->debug("Exiting get_textdurationField method ...");
  1948. return $form_field;
  1949. }
  1950. }
  1951. /** Function to get email text field
  1952. * @param $module -- module name :: Type name
  1953. * @param $id -- entity id :: Type integer
  1954. * @returns $hidden -- hidden:: Type string
  1955. */
  1956. //Added to get the parents list as hidden for Emails -- 09-11-2005
  1957. function getEmailParentsList($module,$id,$focus = false)
  1958. {
  1959. global $log;
  1960. $log->debug("Entering getEmailParentsList(".$module.",".$id.") method ...");
  1961. global $adb;
  1962. // If the information is not sent then read it
  1963. if($focus === false) {
  1964. if($module == 'Contacts')
  1965. $focus = new Contacts();
  1966. if($module == 'Leads')
  1967. $focus = new Leads();
  1968. $focus->retrieve_entity_info($id,$module);
  1969. }
  1970. $fieldid = 0;
  1971. $fieldname = 'email';
  1972. if($focus->column_fields['email'] == '' && $focus->column_fields['yahooid'] != '' )
  1973. $fieldname = 'yahooid';
  1974. elseif($focus->column_fields['email'] == '' && $focus->column_fields['secondaryemail'] != '' )
  1975. $fieldname='secondaryemail';
  1976. $res = $adb->pquery("select * from vtiger_field where tabid = ? and fieldname= ? and vtiger_field.presence in (0,2)", array(getTabid($module), $fieldname));
  1977. $fieldid = $adb->query_result($res,0,'fieldid');
  1978. $hidden .= '<input type="hidden" name="emailids" value="'.$id.'@'.$fieldid.'|">';
  1979. $hidden .= '<input type="hidden" name="pmodule" value="'.$module.'">';
  1980. $log->debug("Exiting getEmailParentsList method ...");
  1981. return $hidden;
  1982. }
  1983. /** This Function returns the current status of the specified Purchase Order.
  1984. * The following is the input parameter for the function
  1985. * $po_id --> Purchase Order Id, Type:Integer
  1986. */
  1987. function getPoStatus($po_id)
  1988. {
  1989. global $log;
  1990. $log->debug("Entering getPoStatus(".$po_id.") method ...");
  1991. global $log;
  1992. $log->info("in getPoName ".$po_id);
  1993. global $adb;
  1994. $sql = "select postatus from vtiger_purchaseorder where purchaseorderid=?";
  1995. $result = $adb->pquery($sql, array($po_id));
  1996. $po_status = $adb->query_result($result,0,"postatus");
  1997. $log->debug("Exiting getPoStatus method ...");
  1998. return $po_status;
  1999. }
  2000. /** This Function adds the specified product quantity to the Product Quantity in Stock in the Warehouse
  2001. * The following is the input parameter for the function:
  2002. * $productId --> ProductId, Type:Integer
  2003. * $qty --> Quantity to be added, Type:Integer
  2004. */
  2005. function addToProductStock($productId,$qty)
  2006. {
  2007. global $log;
  2008. $log->debug("Entering addToProductStock(".$productId.",".$qty.") method ...");
  2009. global $adb;
  2010. $qtyInStck=getProductQtyInStock($productId);
  2011. $updQty=$qtyInStck + $qty;
  2012. $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?";
  2013. $adb->pquery($sql, array($updQty, $productId));
  2014. $log->debug("Exiting addToProductStock method ...");
  2015. }
  2016. /** This Function adds the specified product quantity to the Product Quantity in Demand in the Warehouse
  2017. * @param int $productId - ProductId
  2018. * @param int $qty - Quantity to be added
  2019. */
  2020. function addToProductDemand($productId,$qty)
  2021. {
  2022. global $log;
  2023. $log->debug("Entering addToProductDemand(".$productId.",".$qty.") method ...");
  2024. global $adb;
  2025. $qtyInStck=getProductQtyInDemand($productId);
  2026. $updQty=$qtyInStck + $qty;
  2027. $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?";
  2028. $adb->pquery($sql, array($updQty, $productId));
  2029. $log->debug("Exiting addToProductDemand method ...");
  2030. }
  2031. /** This Function subtract the specified product quantity to the Product Quantity in Stock in the Warehouse
  2032. * @param int $productId - ProductId
  2033. * @param int $qty - Quantity to be subtracted
  2034. */
  2035. function deductFromProductStock($productId,$qty)
  2036. {
  2037. global $log;
  2038. $log->debug("Entering deductFromProductStock(".$productId.",".$qty.") method ...");
  2039. global $adb;
  2040. $qtyInStck=getProductQtyInStock($productId);
  2041. $updQty=$qtyInStck - $qty;
  2042. $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?";
  2043. $adb->pquery($sql, array($updQty, $productId));
  2044. $log->debug("Exiting deductFromProductStock method ...");
  2045. }
  2046. /** This Function subtract the specified product quantity to the Product Quantity in Demand in the Warehouse
  2047. * @param int $productId - ProductId
  2048. * @param int $qty - Quantity to be subtract
  2049. */
  2050. function deductFromProductDemand($productId,$qty)
  2051. {
  2052. global $log;
  2053. $log->debug("Entering deductFromProductDemand(".$productId.",".$qty.") method ...");
  2054. global $adb;
  2055. $qtyInStck=getProductQtyInDemand($productId);
  2056. $updQty=$qtyInStck - $qty;
  2057. $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?";
  2058. $adb->pquery($sql, array($updQty, $productId));
  2059. $log->debug("Exiting deductFromProductDemand method ...");
  2060. }
  2061. /** This Function returns the current product quantity in stock.
  2062. * The following is the input parameter for the function:
  2063. * $product_id --> ProductId, Type:Integer
  2064. */
  2065. function getProductQtyInStock($product_id)
  2066. {
  2067. global $log;
  2068. $log->debug("Entering getProductQtyInStock(".$product_id.") method ...");
  2069. global $adb;
  2070. $query1 = "select qtyinstock from vtiger_products where productid=?";
  2071. $result=$adb->pquery($query1, array($product_id));
  2072. $qtyinstck= $adb->query_result($result,0,"qtyinstock");
  2073. $log->debug("Exiting getProductQtyInStock method ...");
  2074. return $qtyinstck;
  2075. }
  2076. /** This Function returns the current product quantity in demand.
  2077. * @param int $product_id - ProductId
  2078. * @return int $qtyInDemand - Quantity in Demand of a product
  2079. */
  2080. function getProductQtyInDemand($product_id)
  2081. {
  2082. global $log;
  2083. $log->debug("Entering getProductQtyInDemand(".$product_id.") method ...");
  2084. global $adb;
  2085. $query1 = "select qtyindemand from vtiger_products where productid=?";
  2086. $result = $adb->pquery($query1, array($product_id));
  2087. $qtyInDemand = $adb->query_result($result,0,"qtyindemand");
  2088. $log->debug("Exiting getProductQtyInDemand method ...");
  2089. return $qtyInDemand;
  2090. }
  2091. /** Function to seperate the Date and Time
  2092. * This function accepts a sting with date and time and
  2093. * returns an array of two elements.The first element
  2094. * contains the date and the second one contains the time
  2095. */
  2096. function getDateFromDateAndtime($date_time)
  2097. {
  2098. global $log;
  2099. $log->debug("Entering getDateFromDateAndtime(".$date_time.") method ...");
  2100. $result = explode(" ",$date_time);
  2101. $log->debug("Exiting getDateFromDateAndtime method ...");
  2102. return $result;
  2103. }
  2104. /** Function to get header for block in edit/create and detailview
  2105. * @param $header_label -- header label :: Type string
  2106. * @returns $output -- output:: Type string
  2107. */
  2108. function getBlockTableHeader($header_label)
  2109. {
  2110. global $log;
  2111. $log->debug("Entering getBlockTableHeader(".$header_label.") method ...");
  2112. global $mod_strings;
  2113. $label = $mod_strings[$header_label];
  2114. $output = $label;
  2115. $log->debug("Exiting getBlockTableHeader method ...");
  2116. return $output;
  2117. }
  2118. /** Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module
  2119. * @param : string $module - current module value
  2120. * @param : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename
  2121. * @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis
  2122. */
  2123. function getTableNameForField($module,$fieldname)
  2124. {
  2125. global $log;
  2126. $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ...");
  2127. global $adb;
  2128. $tabid = getTabid($module);
  2129. //Asha
  2130. if($module == 'Calendar') {
  2131. $tabid = array('9','16');
  2132. }
  2133. $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.presence in (0,2) and columnname like ?";
  2134. $res = $adb->pquery($sql, array($tabid, '%'.$fieldname.'%'));
  2135. $tablename = '';
  2136. if($adb->num_rows($res) > 0)
  2137. {
  2138. $tablename = $adb->query_result($res,0,'tablename');
  2139. }
  2140. $log->debug("Exiting getTableNameForField method ...");
  2141. return $tablename;
  2142. }
  2143. /** Function to get parent record owner
  2144. * @param $tabid -- tabid :: Type integer
  2145. * @param $parModId -- parent module id :: Type integer
  2146. * @param $record_id -- record id :: Type integer
  2147. * @returns $parentRecOwner -- parentRecOwner:: Type integer
  2148. */
  2149. function getParentRecordOwner($tabid,$parModId,$record_id)
  2150. {
  2151. global $log;
  2152. $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ...");
  2153. $parentRecOwner=Array();
  2154. $parentTabName=getTabname($parModId);
  2155. $relTabName=getTabname($tabid);
  2156. $fn_name="get".$relTabName."Related".$parentTabName;
  2157. $ent_id=$fn_name($record_id);
  2158. if($ent_id != '')
  2159. {
  2160. $parentRecOwner=getRecordOwnerId($ent_id);
  2161. }
  2162. $log->debug("Exiting getParentRecordOwner method ...");
  2163. return $parentRecOwner;
  2164. }
  2165. /** Function to get potential related accounts
  2166. * @param $record_id -- record id :: Type integer
  2167. * @returns $accountid -- accountid:: Type integer
  2168. */
  2169. function getPotentialsRelatedAccounts($record_id)
  2170. {
  2171. global $log;
  2172. $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ...");
  2173. global $adb;
  2174. $query="select related_to from vtiger_potential where potentialid=?";
  2175. $result=$adb->pquery($query, array($record_id));
  2176. $accountid=$adb->query_result($result,0,'related_to');
  2177. $log->debug("Exiting getPotentialsRelatedAccounts method ...");
  2178. return $accountid;
  2179. }
  2180. /** Function to get email related accounts
  2181. * @param $record_id -- record id :: Type integer
  2182. * @returns $accountid -- accountid:: Type integer
  2183. */
  2184. function getEmailsRelatedAccounts($record_id)
  2185. {
  2186. global $log;
  2187. $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ...");
  2188. global $adb;
  2189. $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?";
  2190. $result = $adb->pquery($query, array($record_id));
  2191. $accountid=$adb->query_result($result,0,'crmid');
  2192. $log->debug("Exiting getEmailsRelatedAccounts method ...");
  2193. return $accountid;
  2194. }
  2195. /** Function to get email related Leads
  2196. * @param $record_id -- record id :: Type integer
  2197. * @returns $leadid -- leadid:: Type integer
  2198. */
  2199. function getEmailsRelatedLeads($record_id)
  2200. {
  2201. global $log;
  2202. $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ...");
  2203. global $adb;
  2204. $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?";
  2205. $result = $adb->pquery($query, array($record_id));
  2206. $leadid=$adb->query_result($result,0,'crmid');
  2207. $log->debug("Exiting getEmailsRelatedLeads method ...");
  2208. return $leadid;
  2209. }
  2210. /** Function to get HelpDesk related Accounts
  2211. * @param $record_id -- record id :: Type integer
  2212. * @returns $accountid -- accountid:: Type integer
  2213. */
  2214. function getHelpDeskRelatedAccounts($record_id)
  2215. {
  2216. global $log;
  2217. $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ...");
  2218. global $adb;
  2219. $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'";
  2220. $result=$adb->pquery($query, array($record_id));
  2221. $accountid=$adb->query_result($result,0,'parent_id');
  2222. $log->debug("Exiting getHelpDeskRelatedAccounts method ...");
  2223. return $accountid;
  2224. }
  2225. /** Function to get Quotes related Accounts
  2226. * @param $record_id -- record id :: Type integer
  2227. * @returns $accountid -- accountid:: Type integer
  2228. */
  2229. function getQuotesRelatedAccounts($record_id)
  2230. {
  2231. global $log;
  2232. $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ...");
  2233. global $adb;
  2234. $query="select accountid from vtiger_quotes where quoteid=?";
  2235. $result=$adb->pquery($query, array($record_id));
  2236. $accountid=$adb->query_result($result,0,'accountid');
  2237. $log->debug("Exiting getQuotesRelatedAccounts method ...");
  2238. return $accountid;
  2239. }
  2240. /** Function to get Quotes related Potentials
  2241. * @param $record_id -- record id :: Type integer
  2242. * @returns $potid -- potid:: Type integer
  2243. */
  2244. function getQuotesRelatedPotentials($record_id)
  2245. {
  2246. global $log;
  2247. $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ...");
  2248. global $adb;
  2249. $query="select potentialid from vtiger_quotes where quoteid=?";
  2250. $result=$adb->pquery($query, array($record_id));
  2251. $potid=$adb->query_result($result,0,'potentialid');
  2252. $log->debug("Exiting getQuotesRelatedPotentials method ...");
  2253. return $potid;
  2254. }
  2255. /** Function to get Quotes related Potentials
  2256. * @param $record_id -- record id :: Type integer
  2257. * @returns $accountid -- accountid:: Type integer
  2258. */
  2259. function getSalesOrderRelatedAccounts($record_id)
  2260. {
  2261. global $log;
  2262. $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ...");
  2263. global $adb;
  2264. $query="select accountid from vtiger_salesorder where salesorderid=?";
  2265. $result=$adb->pquery($query, array($record_id));
  2266. $accountid=$adb->query_result($result,0,'accountid');
  2267. $log->debug("Exiting getSalesOrderRelatedAccounts method ...");
  2268. return $accountid;
  2269. }
  2270. /** Function to get SalesOrder related Potentials
  2271. * @param $record_id -- record id :: Type integer
  2272. * @returns $potid -- potid:: Type integer
  2273. */
  2274. function getSalesOrderRelatedPotentials($record_id)
  2275. {
  2276. global $log;
  2277. $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ...");
  2278. global $adb;
  2279. $query="select potentialid from vtiger_salesorder where salesorderid=?";
  2280. $result=$adb->pquery($query, array($record_id));
  2281. $potid=$adb->query_result($result,0,'potentialid');
  2282. $log->debug("Exiting getSalesOrderRelatedPotentials method ...");
  2283. return $potid;
  2284. }
  2285. /** Function to get SalesOrder related Quotes
  2286. * @param $record_id -- record id :: Type integer
  2287. * @returns $qtid -- qtid:: Type integer
  2288. */
  2289. function getSalesOrderRelatedQuotes($record_id)
  2290. {
  2291. global $log;
  2292. $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ...");
  2293. global $adb;
  2294. $query="select quoteid from vtiger_salesorder where salesorderid=?";
  2295. $result=$adb->pquery($query, array($record_id));
  2296. $qtid=$adb->query_result($result,0,'quoteid');
  2297. $log->debug("Exiting getSalesOrderRelatedQuotes method ...");
  2298. return $qtid;
  2299. }
  2300. /** Function to get Invoice related Accounts
  2301. * @param $record_id -- record id :: Type integer
  2302. * @returns $accountid -- accountid:: Type integer
  2303. */
  2304. function getInvoiceRelatedAccounts($record_id)
  2305. {
  2306. global $log;
  2307. $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ...");
  2308. global $adb;
  2309. $query="select accountid from vtiger_invoice where invoiceid=?";
  2310. $result=$adb->pquery($query, array($record_id));
  2311. $accountid=$adb->query_result($result,0,'accountid');
  2312. $log->debug("Exiting getInvoiceRelatedAccounts method ...");
  2313. return $accountid;
  2314. }
  2315. /** Function to get Invoice related SalesOrder
  2316. * @param $record_id -- record id :: Type integer
  2317. * @returns $soid -- soid:: Type integer
  2318. */
  2319. function getInvoiceRelatedSalesOrder($record_id)
  2320. {
  2321. global $log;
  2322. $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ...");
  2323. global $adb;
  2324. $query="select salesorderid from vtiger_invoice where invoiceid=?";
  2325. $result=$adb->pquery($query, array($record_id));
  2326. $soid=$adb->query_result($result,0,'salesorderid');
  2327. $log->debug("Exiting getInvoiceRelatedSalesOrder method ...");
  2328. return $soid;
  2329. }
  2330. /** Function to get Days and Dates in between the dates specified
  2331. * Portions created by vtiger are Copyright (C) vtiger.
  2332. * All Rights Reserved.
  2333. * Contributor(s): ______________________________________..
  2334. */
  2335. function get_days_n_dates($st,$en)
  2336. {
  2337. global $log;
  2338. $log->debug("Entering get_days_n_dates(".$st.",".$en.") method ...");
  2339. $stdate_arr=explode("-",$st);
  2340. $endate_arr=explode("-",$en);
  2341. $dateDiff = mktime(0,0,0,$endate_arr[1],$endate_arr[2],$endate_arr[0]) - mktime(0,0,0,$stdate_arr[1],$stdate_arr[2],$stdate_arr[0]);//to get dates difference
  2342. $days = floor($dateDiff/60/60/24)+1; //to calculate no of. days
  2343. for($i=0;$i<$days;$i++)
  2344. {
  2345. $day_date[] = date("Y-m-d",mktime(0,0,0,date("$stdate_arr[1]"),(date("$stdate_arr[2]")+($i)),date("$stdate_arr[0]")));
  2346. }
  2347. if(!isset($day_date))
  2348. $day_date=0;
  2349. $nodays_dates=array($days,$day_date);
  2350. $log->debug("Exiting get_days_n_dates method ...");
  2351. return $nodays_dates; //passing no of days , days in between the days
  2352. }//function end
  2353. /** Function to get the start and End Dates based upon the period which we give
  2354. * Portions created by vtiger are Copyright (C) vtiger.
  2355. * All Rights Reserved.
  2356. * Contributor(s): ______________________________________..
  2357. */
  2358. function start_end_dates($period)
  2359. {
  2360. global $log;
  2361. $log->debug("Entering start_end_dates(".$period.") method ...");
  2362. $st_thisweek= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y")));
  2363. if($period=="tweek")
  2364. {
  2365. $st_date= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y")));
  2366. $end_date = date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-1),date("Y")));
  2367. $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y")));
  2368. if($st_week==0)
  2369. {
  2370. $start_week=explode("-",$st_thisweek);
  2371. $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]")));
  2372. $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]")));
  2373. }
  2374. $period_type="week";
  2375. $width="360";
  2376. }
  2377. else if($period=="lweek")
  2378. {
  2379. $start_week=explode("-",$st_thisweek);
  2380. $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]")));
  2381. $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]")));
  2382. $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y")));
  2383. if($st_week==0)
  2384. {
  2385. $start_week=explode("-",$st_thisweek);
  2386. $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-14),date("$start_week[0]")));
  2387. $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-8),date("$start_week[0]")));
  2388. }
  2389. $period_type="week";
  2390. $width="360";
  2391. }
  2392. else if($period=="tmon")
  2393. {
  2394. $period_type="month";
  2395. $width="840";
  2396. $st_date = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y")));
  2397. $end_date = date("Y-m-t");
  2398. }
  2399. else if($period=="lmon")
  2400. {
  2401. $st_date=date("Y-m-d",mktime(0,0,0,date("n")-1,date("1"),date("Y")));
  2402. $end_date = date("Y-m-d",mktime(0, 0, 1, date("n"), 0,date("Y")));
  2403. $period_type="month";
  2404. $start_month=date("d",mktime(0,0,0,date("n"),date("j"),date("Y")));
  2405. if($start_month==1)
  2406. {
  2407. $st_date=date("Y-m-d",mktime(0,0,0,date("n")-2,date("1"),date("Y")));
  2408. $end_date = date("Y-m-d",mktime(0, 0, 1, date("n")-1, 0,date("Y")));
  2409. }
  2410. $width="840";
  2411. }
  2412. else
  2413. {
  2414. $curr_date=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
  2415. $today_date=explode("-",$curr_date);
  2416. $lastday_date=date("Y-m-d",mktime(0,0,0,date("$today_date[1]"),date("$today_date[2]")-1,date("$today_date[0]")));
  2417. $st_date=$lastday_date;
  2418. $end_date=$lastday_date;
  2419. $period_type="yday";
  2420. $width="250";
  2421. }
  2422. if($period_type=="yday")
  2423. $height="160";
  2424. else
  2425. $height="250";
  2426. $datevalues=array($st_date,$end_date,$period_type,$width,$height);
  2427. $log->debug("Exiting start_end_dates method ...");
  2428. return $datevalues;
  2429. }//function ends
  2430. /** Function to get the Graph and vtiger_table format for a particular date
  2431. based upon the period
  2432. * Portions created by vtiger are Copyright (C) vtiger.
  2433. * All Rights Reserved.
  2434. * Contributor(s): ______________________________________..
  2435. */
  2436. function Graph_n_table_format($period_type,$date_value)
  2437. {
  2438. global $log;
  2439. $log->debug("Entering Graph_n_table_format(".$period_type.",".$date_value.") method ...");
  2440. $date_val=explode("-",$date_value);
  2441. if($period_type=="month") //to get the vtiger_table format dates
  2442. {
  2443. $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
  2444. $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
  2445. }
  2446. else if($period_type=="week")
  2447. {
  2448. $table_format=date("d/m",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
  2449. $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
  2450. }
  2451. else if($period_type=="yday")
  2452. {
  2453. $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
  2454. $graph_format=$table_format;
  2455. }
  2456. $values=array($graph_format,$table_format);
  2457. $log->debug("Exiting Graph_n_table_format method ...");
  2458. return $values;
  2459. }
  2460. /** Function to get image count for a given product
  2461. * @param $id -- product id :: Type integer
  2462. * @returns count -- count:: Type integer
  2463. */
  2464. function getImageCount($id)
  2465. {
  2466. global $log;
  2467. $log->debug("Entering getImageCount(".$id.") method ...");
  2468. global $adb;
  2469. $image_lists=array();
  2470. $query="select imagename from vtiger_products where productid=?";
  2471. $result=$adb->pquery($query, array($id));
  2472. $imagename=$adb->query_result($result,0,'imagename');
  2473. $image_lists=explode("###",$imagename);
  2474. $log->debug("Exiting getImageCount method ...");
  2475. return count($image_lists);
  2476. }
  2477. /** Function to get user image for a given user
  2478. * @param $id -- user id :: Type integer
  2479. * @returns $image_name -- image name:: Type string
  2480. */
  2481. function getUserImageName($id)
  2482. {
  2483. global $log;
  2484. $log->debug("Entering getUserImageName(".$id.") method ...");
  2485. global $adb;
  2486. $query = "select imagename from vtiger_users where id=?";
  2487. $result = $adb->pquery($query, array($id));
  2488. $image_name = $adb->query_result($result,0,"imagename");
  2489. $log->debug("Inside getUserImageName. The image_name is ".$image_name);
  2490. $log->debug("Exiting getUserImageName method ...");
  2491. return $image_name;
  2492. }
  2493. /** Function to get all user images for displaying it in listview
  2494. * @returns $image_name -- image name:: Type array
  2495. */
  2496. function getUserImageNames()
  2497. {
  2498. global $log;
  2499. $log->debug("Entering getUserImageNames() method ...");
  2500. global $adb;
  2501. $query = "select imagename from vtiger_users where deleted=0";
  2502. $result = $adb->pquery($query, array());
  2503. $image_name=array();
  2504. for($i=0;$i<$adb->num_rows($result);$i++)
  2505. {
  2506. if($adb->query_result($result,$i,"imagename")!='')
  2507. $image_name[] = $adb->query_result($result,$i,"imagename");
  2508. }
  2509. $log->debug("Inside getUserImageNames.");
  2510. if(count($image_name) > 0)
  2511. {
  2512. $log->debug("Exiting getUserImageNames method ...");
  2513. return $image_name;
  2514. }
  2515. }
  2516. /** Function to remove the script tag in the contents
  2517. * Portions created by vtiger are Copyright (C) vtiger.
  2518. * All Rights Reserved.
  2519. * Contributor(s): ______________________________________..
  2520. */
  2521. function strip_selected_tags($text, $tags = array())
  2522. {
  2523. $args = func_get_args();
  2524. $text = array_shift($args);
  2525. $tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
  2526. foreach ($tags as $tag){
  2527. if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
  2528. $text = str_replace($found[0],$found[1],$text);
  2529. }
  2530. }
  2531. return $text;
  2532. }
  2533. /** Function to check whether user has opted for internal mailer
  2534. * @returns $int_mailer -- int mailer:: Type boolean
  2535. */
  2536. function useInternalMailer() {
  2537. global $current_user,$adb;
  2538. return $adb->query_result($adb->pquery("select int_mailer from vtiger_mail_accounts where user_id=?", array($current_user->id)),0,"int_mailer");
  2539. }
  2540. /**
  2541. * the function is like unescape in javascript
  2542. * added by dingjianting on 2006-10-1 for picklist editor
  2543. */
  2544. function utf8RawUrlDecode ($source) {
  2545. global $default_charset;
  2546. $decodedStr = "";
  2547. $pos = 0;
  2548. $len = strlen ($source);
  2549. while ($pos < $len) {
  2550. $charAt = substr ($source, $pos, 1);
  2551. if ($charAt == '%') {
  2552. $pos++;
  2553. $charAt = substr ($source, $pos, 1);
  2554. if ($charAt == 'u') {
  2555. // we got a unicode character
  2556. $pos++;
  2557. $unicodeHexVal = substr ($source, $pos, 4);
  2558. $unicode = hexdec ($unicodeHexVal);
  2559. $entity = "&#". $unicode . ';';
  2560. $decodedStr .= utf8_encode ($entity);
  2561. $pos += 4;
  2562. }
  2563. else {
  2564. // we have an escaped ascii character
  2565. $hexVal = substr ($source, $pos, 2);
  2566. $decodedStr .= chr (hexdec ($hexVal));
  2567. $pos += 2;
  2568. }
  2569. } else {
  2570. $decodedStr .= $charAt;
  2571. $pos++;
  2572. }
  2573. }
  2574. if(strtolower($default_charset) == 'utf-8')
  2575. return html_to_utf8($decodedStr);
  2576. else
  2577. return $decodedStr;
  2578. //return html_to_utf8($decodedStr);
  2579. }
  2580. /**
  2581. *simple HTML to UTF-8 conversion:
  2582. */
  2583. function html_to_utf8 ($data)
  2584. {
  2585. return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data);
  2586. }
  2587. function _html_to_utf8 ($data)
  2588. {
  2589. if ($data > 127)
  2590. {
  2591. $i = 5;
  2592. while (($i--) > 0)
  2593. {
  2594. if ($data != ($a = $data % ($p = pow(64, $i))))
  2595. {
  2596. $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
  2597. for ($i; $i > 0; $i--)
  2598. $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
  2599. break;
  2600. }
  2601. }
  2602. }
  2603. else
  2604. $ret = "&#$data;";
  2605. return $ret;
  2606. }
  2607. // Return Question mark
  2608. function _questionify($v){
  2609. return "?";
  2610. }
  2611. /**
  2612. * Function to generate question marks for a given list of items
  2613. */
  2614. function generateQuestionMarks($items_list) {
  2615. // array_map will call the function specified in the first parameter for every element of the list in second parameter
  2616. if (is_array($items_list)) {
  2617. return implode(",", array_map("_questionify", $items_list));
  2618. } else {
  2619. return implode(",", array_map("_questionify", explode(",", $items_list)));
  2620. }
  2621. }
  2622. /**
  2623. * Function to find the UI type of a field based on the uitype id
  2624. */
  2625. function is_uitype($uitype, $reqtype) {
  2626. $ui_type_arr = array(
  2627. '_date_' => array(5, 6, 23, 70),
  2628. '_picklist_' => array(15, 16, 52, 53, 54, 55, 59, 62, 63, 66, 68, 76, 77, 78, 80, 98, 101, 115, 357),
  2629. '_users_list_' => array(52),
  2630. );
  2631. if ($ui_type_arr[$reqtype] != null) {
  2632. if (in_array($uitype, $ui_type_arr[$reqtype])) {
  2633. return true;
  2634. }
  2635. }
  2636. return false;
  2637. }
  2638. /**
  2639. * Function to escape quotes
  2640. * @param $value - String in which single quotes have to be replaced.
  2641. * @return Input string with single quotes escaped.
  2642. */
  2643. function escape_single_quotes($value) {
  2644. if (isset($value)) $value = str_replace("'", "\'", $value);
  2645. return $value;
  2646. }
  2647. /**
  2648. * Function to format the input value for SQL like clause.
  2649. * @param $str - Input string value to be formatted.
  2650. * @param $flag - By default set to 0 (Will look for cases %string%).
  2651. * If set to 1 - Will look for cases %string.
  2652. * If set to 2 - Will look for cases string%.
  2653. * @return String formatted as per the SQL like clause requirement
  2654. */
  2655. function formatForSqlLike($str, $flag=0,$is_field=false) {
  2656. global $adb;
  2657. if (isset($str)) {
  2658. if($is_field==false){
  2659. $str = str_replace('%', '\%', $str);
  2660. $str = str_replace('_', '\_', $str);
  2661. if ($flag == 0) {
  2662. $str = '%'. $str .'%';
  2663. } elseif ($flag == 1) {
  2664. $str = '%'. $str;
  2665. } elseif ($flag == 2) {
  2666. $str = $str .'%';
  2667. }
  2668. } else {
  2669. if ($flag == 0) {
  2670. $str = 'concat("%",'. $str .',"%")';
  2671. } elseif ($flag == 1) {
  2672. $str = 'concat("%",'. $str .')';
  2673. } elseif ($flag == 2) {
  2674. $str = 'concat('. $str .',"%")';
  2675. }
  2676. }
  2677. }
  2678. return $adb->sql_escape_string($str);
  2679. }
  2680. /**
  2681. * Get Current Module (global variable or from request)
  2682. */
  2683. function getCurrentModule($perform_set=false) {
  2684. global $currentModule,$root_directory;
  2685. if(isset($currentModule)) return $currentModule;
  2686. // Do some security check and return the module information
  2687. if(isset($_REQUEST['module']))
  2688. {
  2689. $is_module = false;
  2690. $module = $_REQUEST['module'];
  2691. $dir = @scandir($root_directory."modules");
  2692. $temp_arr = Array("CVS","Attic");
  2693. $res_arr = @array_intersect($dir,$temp_arr);
  2694. if(count($res_arr) == 0 && !preg_match("/[\/.]/",$module)) {
  2695. if(@in_array($module,$dir))
  2696. $is_module = true;
  2697. }
  2698. if($is_module) {
  2699. if($perform_set) $currentModule = $module;
  2700. return $module;
  2701. }
  2702. }
  2703. return null;
  2704. }
  2705. /**
  2706. * Set the language strings.
  2707. */
  2708. function setCurrentLanguage($active_module=null) {
  2709. global $current_language, $default_language, $app_strings, $app_list_strings, $mod_strings, $currentModule;
  2710. if($active_module==null) {
  2711. if (!isset($currentModule))
  2712. $active_module = getCurrentModule();
  2713. else
  2714. $active_module = $currentModule;
  2715. }
  2716. if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '')
  2717. {
  2718. $current_language = $_SESSION['authenticated_user_language'];
  2719. }
  2720. else
  2721. {
  2722. $current_language = $default_language;
  2723. }
  2724. //set module and application string arrays based upon selected language
  2725. if (!isset($app_strings))
  2726. $app_strings = return_application_language($current_language);
  2727. if (!isset($app_list_strings))
  2728. $app_list_strings = return_app_list_strings_language($current_language);
  2729. if (!isset($mod_strings) && isset($active_module))
  2730. $mod_strings = return_module_language($current_language, $active_module);
  2731. }
  2732. /** Function used to get all the picklists and their values for a module
  2733. @param string $module - Module name to which the list of picklists and their values needed
  2734. @return array $fieldlists - Array of picklists and their values
  2735. **/
  2736. function getAccessPickListValues($module)
  2737. {
  2738. global $adb, $log;
  2739. global $current_user;
  2740. $log->debug("Entering into function getAccessPickListValues($module)");
  2741. $id = getTabid($module);
  2742. $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_field.presence in (0,2)";
  2743. $result = $adb->pquery($query, array($id));
  2744. $roleid = $current_user->roleid;
  2745. $subrole = getRoleSubordinates($roleid);
  2746. if(count($subrole)> 0)
  2747. {
  2748. $roleids = $subrole;
  2749. array_push($roleids, $roleid);
  2750. }
  2751. else
  2752. {
  2753. $roleids = $roleid;
  2754. }
  2755. $temp_status = Array();
  2756. for($i=0;$i < $adb->num_rows($result);$i++)
  2757. {
  2758. $fieldname = $adb->query_result($result,$i,"fieldname");
  2759. $fieldlabel = $adb->query_result($result,$i,"fieldlabel");
  2760. $columnname = $adb->query_result($result,$i,"columnname");
  2761. $tabid = $adb->query_result($result,$i,"tabid");
  2762. $uitype = $adb->query_result($result,$i,"uitype");
  2763. $keyvalue = $columnname;
  2764. $fieldvalues = Array();
  2765. if (count($roleids) > 1)
  2766. {
  2767. $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc";
  2768. }
  2769. else
  2770. {
  2771. $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc";
  2772. }
  2773. if($fieldname != 'firstname')
  2774. $mulselresult = $adb->query($mulsel);
  2775. for($j=0;$j < $adb->num_rows($mulselresult);$j++)
  2776. {
  2777. $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname);
  2778. }
  2779. $field_count = count($fieldvalues);
  2780. if($uitype == 15 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus'))
  2781. {
  2782. $temp_count =count($temp_status[$keyvalue]);
  2783. if($temp_count > 0)
  2784. {
  2785. for($t=0;$t < $field_count;$t++)
  2786. {
  2787. $temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t];
  2788. }
  2789. $fieldvalues = $temp_status[$keyvalue];
  2790. }
  2791. else
  2792. $temp_status[$keyvalue] = $fieldvalues;
  2793. }
  2794. if($uitype == 33)
  2795. $fieldlists[1][$keyvalue] = $fieldvalues;
  2796. else if($uitype == 55 && $fieldname == 'salutationtype')
  2797. $fieldlists[$keyvalue] = $fieldvalues;
  2798. else if($uitype == 15)
  2799. $fieldlists[$keyvalue] = $fieldvalues;
  2800. }
  2801. $log->debug("Exit from function getAccessPickListValues($module)");
  2802. return $fieldlists;
  2803. }
  2804. function get_config_status() {
  2805. global $default_charset;
  2806. if(strtolower($default_charset) == 'utf-8')
  2807. $config_status=1;
  2808. else
  2809. $config_status=0;
  2810. return $config_status;
  2811. }
  2812. function getMigrationCharsetFlag() {
  2813. global $adb;
  2814. if(!$adb->isPostgres())
  2815. $db_status=check_db_utf8_support($adb);
  2816. $config_status=get_config_status();
  2817. if ($db_status == $config_status) {
  2818. if ($db_status == 1) { // Both are UTF-8
  2819. $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8;
  2820. } else { // Both are Non UTF-8
  2821. $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8;
  2822. }
  2823. } else {
  2824. if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8
  2825. $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8;
  2826. } else { // Database charset is Non UTF-8 and CRM charset is UTF-8
  2827. $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8;
  2828. }
  2829. }
  2830. return $db_migration_status;
  2831. }
  2832. /** Function to convert a given time string to Minutes */
  2833. function ConvertToMinutes($time_string)
  2834. {
  2835. $interval = split(' ', $time_string);
  2836. $interval_minutes = intval($interval[0]);
  2837. $interval_string = strtolower($interval[1]);
  2838. if($interval_string == 'hour' || $interval_string == 'hours')
  2839. {
  2840. $interval_minutes = $interval_minutes * 60;
  2841. }
  2842. elseif($interval_string == 'day' || $interval_string == 'days')
  2843. {
  2844. $interval_minutes = $interval_minutes * 1440;
  2845. }
  2846. return $interval_minutes;
  2847. }
  2848. //added to find duplicates
  2849. /** To get the converted record values which have to be display in duplicates merging tpl*/
  2850. function getRecordValues($id_array,$module) {
  2851. global $adb,$current_user;
  2852. global $app_strings;
  2853. $tabid=getTabid($module);
  2854. $query="select fieldname,fieldlabel,uitype from vtiger_field where tabid=? and fieldname not in ('createdtime','modifiedtime') and vtiger_field.presence in (0,2) and uitype not in('4')";
  2855. $result=$adb->pquery($query, array($tabid));
  2856. $no_rows=$adb->num_rows($result);
  2857. $focus = new $module();
  2858. if(isset($id_array) && $id_array !='') {
  2859. foreach($id_array as $value_pair['disp_value']) {
  2860. $focus->id=$value_pair['disp_value'];
  2861. $focus->retrieve_entity_info($value_pair['disp_value'],$module);
  2862. $field_values[]=$focus->column_fields;
  2863. }
  2864. }
  2865. $labl_array=array();
  2866. $value_pair = array();
  2867. $c = 0;
  2868. for($i=0;$i<$no_rows;$i++) {
  2869. $fld_name=$adb->query_result($result,$i,"fieldname");
  2870. $fld_label=$adb->query_result($result,$i,"fieldlabel");
  2871. $ui_type=$adb->query_result($result,$i,"uitype");
  2872. if(getFieldVisibilityPermission($module,$current_user->id,$fld_name, 'readwrite') == '0') {
  2873. $fld_array []= $fld_name;
  2874. $record_values[$c][$fld_label] = Array();
  2875. $ui_value[]=$ui_type;
  2876. for($j=0;$j < count($field_values);$j++) {
  2877. if($ui_type ==56) {
  2878. if($field_values[$j][$fld_name] == 0)
  2879. $value_pair['disp_value']=$app_strings['no'];
  2880. else
  2881. $value_pair['disp_value']=$app_strings['yes'];
  2882. } elseif($ui_type == 51 || $ui_type == 50) {
  2883. $entity_id=$field_values[$j][$fld_name];
  2884. if($module !='Products')
  2885. $entity_name=getAccountName($entity_id);
  2886. else
  2887. $entity_name=getProductName($entity_id);
  2888. $value_pair['disp_value']=$entity_name;
  2889. } elseif($ui_type == 53) {
  2890. $owner_id=$field_values[$j][$fld_name];
  2891. $ownername=getOwnerName($owner_id);
  2892. $value_pair['disp_value']=$ownername;
  2893. } elseif($ui_type ==57) {
  2894. $contact_id= $field_values[$j][$fld_name];
  2895. if($contact_id != '') {
  2896. $displayValueArray = getEntityName('Contacts', $contact_id);
  2897. if (!empty($displayValueArray)) {
  2898. foreach ($displayValueArray as $key => $field_value) {
  2899. $contactname = $field_value;
  2900. }
  2901. }
  2902. }
  2903. $value_pair['disp_value']=$contactname;
  2904. } elseif($ui_type == 75 || $ui_type ==81) {
  2905. $vendor_id=$field_values[$j][$fld_name];
  2906. if($vendor_id != '') {
  2907. $vendor_name=getVendorName($vendor_id);
  2908. }
  2909. $value_pair['disp_value']=$vendor_name;
  2910. } elseif($ui_type == 52) {
  2911. $user_id = $field_values[$j][$fld_name];
  2912. $user_name=getUserFullName($user_id);
  2913. $value_pair['disp_value']=$user_name;
  2914. } elseif($ui_type ==68) {
  2915. $parent_id = $field_values[$j][$fld_name];
  2916. $value_pair['disp_value'] = getAccountName($parent_id);
  2917. if($value_pair['disp_value'] == '' || $value_pair['disp_value'] == NULL) {
  2918. $displayValueArray = getEntityName('Contacts', $parent_id);
  2919. if (!empty($displayValueArray)) {
  2920. foreach ($displayValueArray as $key => $field_value) {
  2921. $contact_name = $field_value;
  2922. }
  2923. } else {
  2924. $contact_name='';
  2925. }
  2926. $value_pair['disp_value'] = $contact_name;
  2927. }
  2928. } elseif($ui_type ==59) {
  2929. $product_name=getProductName($field_values[$j][$fld_name]);
  2930. if($product_name != '')
  2931. $value_pair['disp_value']=$product_name;
  2932. else $value_pair['disp_value']='';
  2933. } elseif($ui_type==58) {
  2934. $campaign_name=getCampaignName($field_values[$j][$fld_name]);
  2935. if($campaign_name != '')
  2936. $value_pair['disp_value']=$campaign_name;
  2937. else $value_pair['disp_value']='';
  2938. } elseif($ui_type == 10) {
  2939. $value_pair['disp_value'] = getRecordInfoFromID($field_values[$j][$fld_name]);
  2940. }elseif($ui_type == 5 || $ui_type == 6 || $ui_type == 23){
  2941. if ($field_values[$j][$fld_name] != '' && $field_values[$j][$fld_name]
  2942. != '0000-00-00') {
  2943. $date = new DateTimeField($field_values[$j][$fld_name]);
  2944. $value_pair['disp_value'] = $date->getDisplayDate();
  2945. if(strpos($field_values[$j][$fld_name], ' ') > -1) {
  2946. $value_pair['disp_value'] .= (' ' . $date->getDisplayTime());
  2947. }
  2948. } elseif ($field_values[$j][$fld_name] == '0000-00-00') {
  2949. $value_pair['disp_value'] = '';
  2950. } else {
  2951. $value_pair['disp_value'] = $field_values[$j][$fld_name];
  2952. }
  2953. }elseif($ui_type == '71' || $ui_type == '72') {
  2954. $currencyField = new CurrencyField($field_values[$j][$fld_name]);
  2955. if($ui_type == '72') {
  2956. $value_pair['disp_value'] = $currencyField->getDisplayValue(null, true);
  2957. } else {
  2958. $value_pair['disp_value'] = $currencyField->getDisplayValue();
  2959. }
  2960. } else {
  2961. $value_pair['disp_value']=$field_values[$j][$fld_name];
  2962. }
  2963. $value_pair['org_value'] = $field_values[$j][$fld_name];
  2964. array_push($record_values[$c][$fld_label],$value_pair);
  2965. }
  2966. $c++;
  2967. }
  2968. }
  2969. $parent_array[0]=$record_values;
  2970. $parent_array[1]=$fld_array;
  2971. $parent_array[2]=$fld_array;
  2972. return $parent_array;
  2973. }
  2974. /** Function to check whether the relationship entries are exist or not on elationship tables */
  2975. function is_related($relation_table,$crm_field,$related_module_id,$crmid)
  2976. {
  2977. global $adb;
  2978. $check_res = $adb->query("select * from $relation_table where $crm_field=$related_module_id and crmid=$crmid");
  2979. $count = $adb->num_rows($check_res);
  2980. if($count > 0)
  2981. return true;
  2982. else
  2983. return false;
  2984. }
  2985. /** Function to get a to find duplicates in a particular module*/
  2986. function getDuplicateQuery($module,$field_values,$ui_type_arr)
  2987. {
  2988. global $current_user;
  2989. $tbl_col_fld = explode(",", $field_values);
  2990. $i=0;
  2991. foreach($tbl_col_fld as $val) {
  2992. list($tbl[$i], $cols[$i], $fields[$i]) = explode(".", $val);
  2993. $tbl_cols[$i] = $tbl[$i]. "." . $cols[$i];
  2994. $i++;
  2995. }
  2996. $table_cols = implode(",",$tbl_cols);
  2997. $sec_parameter = getSecParameterforMerge($module);
  2998. if($module == 'Contacts')
  2999. {
  3000. $nquery = "SELECT vtiger_contactdetails.contactid AS recordid,
  3001. vtiger_users_last_import.deleted,".$table_cols."
  3002. FROM vtiger_contactdetails
  3003. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid
  3004. INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid
  3005. INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid
  3006. LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid
  3007. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid
  3008. LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid
  3009. LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid
  3010. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3011. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3012. INNER JOIN (SELECT $table_cols
  3013. FROM vtiger_contactdetails
  3014. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
  3015. INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid
  3016. INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid
  3017. LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid
  3018. LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid
  3019. LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid
  3020. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3021. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3022. WHERE vtiger_crmentity.deleted=0 $sec_parameter
  3023. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3024. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3025. WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC";
  3026. }
  3027. else if($module == 'Accounts')
  3028. {
  3029. $nquery="SELECT vtiger_account.accountid AS recordid,
  3030. vtiger_users_last_import.deleted,".$table_cols."
  3031. FROM vtiger_account
  3032. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid
  3033. INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid
  3034. INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid
  3035. LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid
  3036. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid
  3037. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3038. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3039. INNER JOIN (SELECT $table_cols
  3040. FROM vtiger_account
  3041. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid
  3042. INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid
  3043. INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid
  3044. LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid
  3045. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3046. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3047. WHERE vtiger_crmentity.deleted=0 $sec_parameter
  3048. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3049. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3050. WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC";
  3051. }
  3052. else if($module == 'Leads')
  3053. {
  3054. $nquery = "SELECT vtiger_leaddetails.leadid AS recordid, vtiger_users_last_import.deleted,$table_cols
  3055. FROM vtiger_leaddetails
  3056. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid
  3057. INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid
  3058. INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid
  3059. LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid
  3060. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3061. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3062. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid
  3063. INNER JOIN (SELECT $table_cols
  3064. FROM vtiger_leaddetails
  3065. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid
  3066. INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid
  3067. INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid
  3068. LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid
  3069. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3070. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3071. WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter
  3072. GROUP BY $table_cols HAVING COUNT(*)>1) as temp
  3073. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3074. WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC";
  3075. }
  3076. else if($module == 'Products')
  3077. {
  3078. $nquery = "SELECT vtiger_products.productid AS recordid,
  3079. vtiger_users_last_import.deleted,".$table_cols."
  3080. FROM vtiger_products
  3081. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid
  3082. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid
  3083. LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid
  3084. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3085. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3086. INNER JOIN (SELECT $table_cols
  3087. FROM vtiger_products
  3088. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid
  3089. LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid
  3090. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3091. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3092. WHERE vtiger_crmentity.deleted=0 $sec_parameter
  3093. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3094. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3095. WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_products.productid ASC";
  3096. }
  3097. else if($module == "HelpDesk")
  3098. {
  3099. $nquery = "SELECT vtiger_troubletickets.ticketid AS recordid,
  3100. vtiger_users_last_import.deleted,".$table_cols."
  3101. FROM vtiger_troubletickets
  3102. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid
  3103. LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid
  3104. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid
  3105. LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid
  3106. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3107. LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id
  3108. LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid
  3109. INNER JOIN (SELECT $table_cols FROM vtiger_troubletickets
  3110. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid
  3111. LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid
  3112. LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid
  3113. LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id
  3114. LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid
  3115. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3116. LEFT JOIN vtiger_contactdetails contd ON contd.contactid = vtiger_troubletickets.parent_id
  3117. WHERE vtiger_crmentity.deleted=0 $sec_parameter
  3118. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3119. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3120. WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC";
  3121. }
  3122. else if($module == "Potentials")
  3123. {
  3124. $nquery = "SELECT vtiger_potential.potentialid AS recordid,
  3125. vtiger_users_last_import.deleted,".$table_cols."
  3126. FROM vtiger_potential
  3127. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid
  3128. LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid
  3129. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid
  3130. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3131. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3132. INNER JOIN (SELECT $table_cols
  3133. FROM vtiger_potential
  3134. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid
  3135. LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid
  3136. LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
  3137. LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
  3138. WHERE vtiger_crmentity.deleted=0 $sec_parameter
  3139. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3140. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3141. WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC";
  3142. }
  3143. else if($module == "Vendors")
  3144. {
  3145. $nquery = "SELECT vtiger_vendor.vendorid AS recordid,
  3146. vtiger_users_last_import.deleted,".$table_cols."
  3147. FROM vtiger_vendor
  3148. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid
  3149. LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid
  3150. LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid
  3151. INNER JOIN (SELECT $table_cols
  3152. FROM vtiger_vendor
  3153. INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid
  3154. LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid
  3155. WHERE vtiger_crmentity.deleted=0
  3156. GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp
  3157. ON ".get_on_clause($field_values,$ui_type_arr,$module) ."
  3158. WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC";
  3159. } else {
  3160. $modObj = CRMEntity::getInstance($module);
  3161. if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) {
  3162. $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr);
  3163. }
  3164. }
  3165. return $nquery;
  3166. }
  3167. /** Function to return the duplicate records data as a formatted array */
  3168. function getDuplicateRecordsArr($module)
  3169. {
  3170. global $adb,$app_strings,$list_max_entries_per_page,$theme;
  3171. $field_values_array=getFieldValues($module);
  3172. $field_values=$field_values_array['fieldnames_list'];
  3173. $fld_arr=$field_values_array['fieldnames_array'];
  3174. $col_arr=$field_values_array['columnnames_array'];
  3175. $fld_labl_arr=$field_values_array['fieldlabels_array'];
  3176. $ui_type=$field_values_array['fieldname_uitype'];
  3177. $dup_query = getDuplicateQuery($module,$field_values,$ui_type);
  3178. // added for page navigation
  3179. $dup_count_query = substr($dup_query, stripos($dup_query,'FROM'),strlen($dup_query));
  3180. $dup_count_query = "SELECT count(*) as count ".$dup_count_query;
  3181. $count_res = $adb->query($dup_count_query);
  3182. $no_of_rows = $adb->query_result($count_res,0,"count");
  3183. if($no_of_rows <= $list_max_entries_per_page)
  3184. $_SESSION['dup_nav_start'.$module] = 1;
  3185. else if(isset($_REQUEST["start"]) && $_REQUEST["start"] != "" && $_SESSION['dup_nav_start'.$module] != $_REQUEST["start"])
  3186. $_SESSION['dup_nav_start'.$module] = ListViewSession::getRequestStartPage();
  3187. $start = ($_SESSION['dup_nav_start'.$module] != "")?$_SESSION['dup_nav_start'.$module]:1;
  3188. $navigation_array = getNavigationValues($start, $no_of_rows, $list_max_entries_per_page);
  3189. $start_rec = $navigation_array['start'];
  3190. $end_rec = $navigation_array['end_val'];
  3191. $navigationOutput = getTableHeaderNavigation($navigation_array, "",$module,"FindDuplicate","");
  3192. if ($start_rec == 0)
  3193. $limit_start_rec = 0;
  3194. else
  3195. $limit_start_rec = $start_rec -1;
  3196. $dup_query .= " LIMIT $limit_start_rec, $list_max_entries_per_page";
  3197. //ends
  3198. $nresult=$adb->query($dup_query);
  3199. $no_rows=$adb->num_rows($nresult);
  3200. require_once('modules/Vtiger/layout_utils.php');
  3201. if($no_rows == 0)
  3202. {
  3203. if ($_REQUEST['action'] == 'FindDuplicateRecords')
  3204. {
  3205. //echo "<br><br><center>".$app_strings['LBL_NO_DUPLICATE']." <a href='javascript:window.history.back()'>".$app_strings['LBL_GO_BACK'].".</a></center>";
  3206. //die;
  3207. echo "<link rel='stylesheet' type='text/css' href='themes/$theme/style.css'>";
  3208. echo "<table border='0' cellpadding='5' cellspacing='0' width='100%' height='450px'><tr><td align='center'>";
  3209. echo "<div style='border: 3px solid rgb(153, 153, 153); background-color: rgb(255, 255, 255); width: 55%; position: relative; z-index: 10000000;'>
  3210. <table border='0' cellpadding='5' cellspacing='0' width='98%'>
  3211. <tbody><tr>
  3212. <td rowspan='2' width='11%'><img src='" . vtiger_imageurl('empty.jpg', $theme) . "' ></td>
  3213. <td style='border-bottom: 1px solid rgb(204, 204, 204);' nowrap='nowrap' width='70%'><span class='genHeaderSmall'>$app_strings[LBL_NO_DUPLICATE]</span></td>
  3214. </tr>
  3215. <tr>
  3216. <td class='small' align='right' nowrap='nowrap'>
  3217. <a href='javascript:window.history.back();'>$app_strings[LBL_GO_BACK]</a><br> </td>
  3218. </tr>
  3219. </tbody></table>
  3220. </div>";
  3221. echo "</td></tr></table>";
  3222. exit();
  3223. }
  3224. else
  3225. {
  3226. echo "<br><br><table align='center' class='reportCreateBottom big' width='95%'><tr><td align='center'>".$app_strings['LBL_NO_DUPLICATE']."</td></tr></table>";
  3227. die;
  3228. }
  3229. }
  3230. $rec_cnt = 0;
  3231. $temp = Array();
  3232. $sl_arr = Array();
  3233. $grp = "group0";
  3234. $gcnt = 0;
  3235. $ii = 0; //ii'th record in group
  3236. while ( $rec_cnt < $no_rows )
  3237. {
  3238. $result = $adb->fetchByAssoc($nresult);
  3239. //echo '<pre>';print_r($result);echo '</pre>';
  3240. if($rec_cnt != 0)
  3241. {
  3242. $sl_arr = array_slice($result,2);
  3243. array_walk($temp,'lower_array');
  3244. array_walk($sl_arr,'lower_array');
  3245. $arr_diff = array_diff($temp,$sl_arr);
  3246. if(count($arr_diff) > 0)
  3247. {
  3248. $gcnt++;
  3249. $temp = $sl_arr;
  3250. $ii = 0;
  3251. }
  3252. $grp = "group".$gcnt;
  3253. }
  3254. $fld_values[$grp][$ii]['recordid'] = $result['recordid'];
  3255. for($k=0;$k<count($col_arr);$k++)
  3256. {
  3257. if($rec_cnt == 0)
  3258. {
  3259. $temp[$fld_labl_arr[$k]] = $result[$col_arr[$k]];
  3260. }
  3261. if($ui_type[$fld_arr[$k]] == 56)
  3262. {
  3263. if($result[$col_arr[$k]] == 0)
  3264. {
  3265. $result[$col_arr[$k]]=$app_strings['no'];
  3266. }
  3267. else
  3268. $result[$col_arr[$k]]=$app_strings['yes'];
  3269. }
  3270. if($ui_type[$fld_arr[$k]] ==75 || $ui_type[$fld_arr[$k]] ==81)
  3271. {
  3272. $vendor_id=$result[$col_arr[$k]];
  3273. if($vendor_id != '')
  3274. {
  3275. $vendor_name=getVendorName($vendor_id);
  3276. }
  3277. $result[$col_arr[$k]]=$vendor_name;
  3278. }
  3279. if($ui_type[$fld_arr[$k]] ==57)
  3280. {
  3281. $contact_id= $result[$col_arr[$k]];
  3282. if($contact_id != '')
  3283. {
  3284. $parent_module = 'Contacts';
  3285. $displayValueArray = getEntityName($parent_module, $contact_id);
  3286. if (!empty($displayValueArray)) {
  3287. foreach ($displayValueArray as $key => $field_value) {
  3288. $contactname = $field_value;
  3289. }
  3290. }
  3291. }
  3292. $result[$col_arr[$k]]=$contactname;
  3293. }
  3294. if($ui_type[$fld_arr[$k]] == 15 || $ui_type[$fld_arr[$k]] == 16)
  3295. {
  3296. $result[$col_arr[$k]]=getTranslatedString($result[$col_arr[$k]],$module);
  3297. }
  3298. if($ui_type[$fld_arr[$k]] == 33){
  3299. $fieldvalue = explode(' |##| ',$result[$col_arr[$k]]);
  3300. $result[$col_arr[$k]] = array();
  3301. foreach ($fieldvalue as $picklistValue) {
  3302. $result[$col_arr[$k]][] = getTranslatedString($picklistValue,$module);
  3303. }
  3304. $result[$col_arr[$k]] = implode(', ',$result[$col_arr[$k]]);
  3305. }
  3306. if($ui_type[$fld_arr[$k]] ==68)
  3307. {
  3308. $parent_id= $result[$col_arr[$k]];
  3309. if($parent_id != '')
  3310. {
  3311. $parentname=getParentName($parent_id);
  3312. }
  3313. $result[$col_arr[$k]]=$parentname;
  3314. }
  3315. if($ui_type[$fld_arr[$k]] ==53 || $ui_type[$fld_arr[$k]] ==52)
  3316. {
  3317. if($result[$col_arr[$k]] != '')
  3318. {
  3319. $owner=getOwnerName($result[$col_arr[$k]]);
  3320. }
  3321. $result[$col_arr[$k]]=$owner;
  3322. }
  3323. if($ui_type[$fld_arr[$k]] ==50 or $ui_type[$fld_arr[$k]] ==51)
  3324. {
  3325. if($module!='Products') {
  3326. $entity_name=getAccountName($result[$col_arr[$k]]);
  3327. } else {
  3328. $entity_name=getProductName($result[$col_arr[$k]]);
  3329. }
  3330. if($entity_name != '') {
  3331. $result[$col_arr[$k]]=$entity_name;
  3332. } else {
  3333. $result[$col_arr[$k]]='';
  3334. }
  3335. }
  3336. if($ui_type[$fld_arr[$k]] ==58)
  3337. {
  3338. $campaign_name=getCampaignName($result[$col_arr[$k]]);
  3339. if($campaign_name != '')
  3340. $result[$col_arr[$k]]=$campaign_name;
  3341. else $result[$col_arr[$k]]='';
  3342. }
  3343. if($ui_type[$fld_arr[$k]] == 59)
  3344. {
  3345. $product_name=getProductName($result[$col_arr[$k]]);
  3346. if($product_name != '')
  3347. $result[$col_arr[$k]]=$product_name;
  3348. else $result[$col_arr[$k]]='';
  3349. }
  3350. /*uitype 10 handling*/
  3351. if($ui_type[$fld_arr[$k]] == 10){
  3352. $result[$col_arr[$k]] = getRecordInfoFromID($result[$col_arr[$k]]);
  3353. }
  3354. if($ui_type[$fld_arr[$k]] == 5 || $ui_type[$fld_arr[$k]] == 6 || $ui_type[$fld_arr[$k]] == 23){
  3355. if ($$result[$col_arr[$k]] != '' && $$result[$col_arr[$k]] != '0000-00-00') {
  3356. $date = new DateTimeField($$result[$col_arr[$k]]);
  3357. $value = $date->getDisplayDate();
  3358. if(strpos($$result[$col_arr[$k]], ' ') > -1) {
  3359. $value .= (' ' . $date->getDisplayTime());
  3360. }
  3361. } elseif ($$result[$col_arr[$k]] == '0000-00-00') {
  3362. $value = '';
  3363. } else {
  3364. $value = $$result[$col_arr[$k]];
  3365. }
  3366. $result[$col_arr[$k]] = $value;
  3367. }
  3368. if($ui_type[$fld_arr[$k]] == 71) {
  3369. $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]]);
  3370. }
  3371. if($ui_type[$fld_arr[$k]] == 72) {
  3372. $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]], null, true);
  3373. }
  3374. $fld_values[$grp][$ii][$fld_labl_arr[$k]] = $result[$col_arr[$k]];
  3375. }
  3376. $fld_values[$grp][$ii]['Entity Type'] = $result['deleted'];
  3377. $ii++;
  3378. $rec_cnt++;
  3379. }
  3380. $gro="group";
  3381. for($i=0;$i<$no_rows;$i++)
  3382. {
  3383. $ii=0;
  3384. $dis_group[]=$fld_values[$gro.$i][$ii];
  3385. $count_group[$i]=count($fld_values[$gro.$i]);
  3386. $ii++;
  3387. $new_group[]=$dis_group[$i];
  3388. }
  3389. $fld_nam=$new_group[0];
  3390. $ret_arr[0]=$fld_values;
  3391. $ret_arr[1]=$fld_nam;
  3392. $ret_arr[2]=$ui_type;
  3393. $ret_arr["navigation"]=$navigationOutput;
  3394. return $ret_arr;
  3395. }
  3396. /** Function to get on clause criteria for sub tables like address tables to construct duplicate check query */
  3397. function get_special_on_clause($field_list)
  3398. {
  3399. $field_array = explode(",",$field_list);
  3400. $ret_str = '';
  3401. $sel_clause = '';
  3402. $i=1;
  3403. $cnt = count($field_array);
  3404. $spl_chk = ($_REQUEST['modulename'] != '')?$_REQUEST['modulename']:$_REQUEST['module'];
  3405. foreach($field_array as $fld)
  3406. {
  3407. $sub_arr = explode(".",$fld);
  3408. $tbl_name = $sub_arr[0];
  3409. $col_name = $sub_arr[1];
  3410. $fld_name = $sub_arr[2];
  3411. //need to handle aditional conditions with sub tables for further modules of duplicate check
  3412. if($tbl_name == 'vtiger_leadsubdetails' || $tbl_name == 'vtiger_contactsubdetails')
  3413. $tbl_alias = "subd";
  3414. else if($tbl_name == 'vtiger_leadaddress' || $tbl_name == 'vtiger_contactaddress')
  3415. $tbl_alias = "addr";
  3416. else if($tbl_name == 'vtiger_account' && $spl_chk == 'Contacts')
  3417. $tbl_alias = "acc";
  3418. else if($tbl_name == 'vtiger_accountbillads')
  3419. $tbl_alias = "badd";
  3420. else if($tbl_name == 'vtiger_accountshipads')
  3421. $tbl_alias = "sadd";
  3422. else if($tbl_name == 'vtiger_crmentity')
  3423. $tbl_alias = "crm";
  3424. else if($tbl_name == 'vtiger_customerdetails')
  3425. $tbl_alias = "custd";
  3426. else if($tbl_name == 'vtiger_contactdetails' && spl_chk == 'HelpDesk')
  3427. $tbl_alias = "contd";
  3428. else if(stripos($tbl_name, 'cf') === (strlen($tbl_name) - strlen('cf')))
  3429. $tbl_alias = "tcf"; // Custom Field Table Prefix to use in subqueries
  3430. else
  3431. $tbl_alias = "t";
  3432. $sel_clause .= $tbl_alias.".".$col_name.",";
  3433. $ret_str .= " $tbl_name.$col_name = $tbl_alias.$col_name";
  3434. if ($cnt != $i) $ret_str .= " and ";
  3435. $i++;
  3436. }
  3437. $ret_arr['on_clause'] = $ret_str;
  3438. $ret_arr['sel_clause'] = trim($sel_clause,",");
  3439. return $ret_arr;
  3440. }
  3441. /** Function to get on clause criteria for duplicate check queries */
  3442. function get_on_clause($field_list,$uitype_arr,$module)
  3443. {
  3444. $field_array = explode(",",$field_list);
  3445. $ret_str = '';
  3446. $i=1;
  3447. foreach($field_array as $fld)
  3448. {
  3449. $sub_arr = explode(".",$fld);
  3450. $tbl_name = $sub_arr[0];
  3451. $col_name = $sub_arr[1];
  3452. $fld_name = $sub_arr[2];
  3453. $ret_str .= " ifnull($tbl_name.$col_name,'null') = ifnull(temp.$col_name,'null')";
  3454. if (count($field_array) != $i) $ret_str .= " and ";
  3455. $i++;
  3456. }
  3457. return $ret_str;
  3458. }
  3459. /** call back function to change the array values in to lower case */
  3460. function lower_array(&$string){
  3461. $string = strtolower(trim($string));
  3462. }
  3463. /** Function to get recordids for subquery where condition */
  3464. // TODO - Need to check if this method is used anywhere?
  3465. function get_subquery_recordids($sub_query)
  3466. {
  3467. global $adb;
  3468. //need to update this module whenever duplicate check tool added for new modules
  3469. $module_id_array = Array("Accounts"=>"accountid","Contacts"=>"contactid","Leads"=>"leadid","Products"=>"productid","HelpDesk"=>"ticketid","Potentials"=>"potentialid","Vendors"=>"vendorid");
  3470. $id = ($module_id_array[$_REQUEST['modulename']] != '')?$module_id_array[$_REQUEST['modulename']]:$module_id_array[$_REQUEST['module']];
  3471. $sub_res = '';
  3472. $sub_result = $adb->query($sub_query);
  3473. $row_count = $adb->num_rows($sub_result);
  3474. $sub_res = '';
  3475. if($row_count > 0)
  3476. {
  3477. while($rows = $adb->fetchByAssoc($sub_result))
  3478. {
  3479. $sub_res .= $rows[$id].",";
  3480. }
  3481. $sub_res = trim($sub_res,",");
  3482. }
  3483. else
  3484. $sub_res .= "''";
  3485. return $sub_res;
  3486. }
  3487. /** Function to get tablename, columnname, fieldname, fieldlabel and uitypes of fields of merge criteria for a particular module*/
  3488. function getFieldValues($module)
  3489. {
  3490. global $adb,$current_user;
  3491. //In future if we want to change a id mapping to name or other string then we can add that elements in this array.
  3492. //$fld_table_arr = Array("vtiger_contactdetails.account_id"=>"vtiger_account.accountname");
  3493. //$special_fld_arr = Array("account_id"=>"accountname");
  3494. $fld_table_arr = Array();
  3495. $special_fld_arr = Array();
  3496. $tabid = getTabid($module);
  3497. $fieldname_query="select fieldname,fieldlabel,uitype,tablename,columnname from vtiger_field where fieldid in
  3498. (select fieldid from vtiger_user2mergefields WHERE tabid=? AND userid=? AND visible = ?) and vtiger_field.presence in (0,2)";
  3499. $fieldname_result = $adb->pquery($fieldname_query, array($tabid, $current_user->id, 1));
  3500. $field_num_rows = $adb->num_rows($fieldname_result);
  3501. $fld_arr = array();
  3502. $col_arr = array();
  3503. for($j=0;$j< $field_num_rows;$j ++)
  3504. {
  3505. $tablename = $adb->query_result($fieldname_result,$j,'tablename');
  3506. $column_name = $adb->query_result($fieldname_result,$j,'columnname');
  3507. $field_name = $adb->query_result($fieldname_result,$j,'fieldname');
  3508. $field_lbl = $adb->query_result($fieldname_result,$j,'fieldlabel');
  3509. $ui_type = $adb->query_result($fieldname_result,$j,'uitype');
  3510. $table_col = $tablename.".".$column_name;
  3511. if(getFieldVisibilityPermission($module,$current_user->id,$field_name) == 0)
  3512. {
  3513. $fld_name = ($special_fld_arr[$field_name] != '')?$special_fld_arr[$field_name]:$field_name;
  3514. $fld_arr[] = $fld_name;
  3515. $col_arr[] = $column_name;
  3516. if($fld_table_arr[$table_col] != '')
  3517. $table_col = $fld_table_arr[$table_col];
  3518. $field_values_array['fieldnames_list'][] = $table_col . "." . $fld_name;
  3519. $fld_labl_arr[]=$field_lbl;
  3520. $uitype[$field_name]=$ui_type;
  3521. }
  3522. }
  3523. $field_values_array['fieldnames_list']=implode(",",$field_values_array['fieldnames_list']);
  3524. $field_values=implode(",",$fld_arr);
  3525. $field_values_array['fieldnames']=$field_values;
  3526. $field_values_array["fieldnames_array"]=$fld_arr;
  3527. $field_values_array["columnnames_array"]=$col_arr;
  3528. $field_values_array['fieldlabels_array']=$fld_labl_arr;
  3529. $field_values_array['fieldname_uitype']=$uitype;
  3530. return $field_values_array;
  3531. }
  3532. /** To get security parameter for a particular module -- By Pavani*/
  3533. function getSecParameterforMerge($module)
  3534. {
  3535. global $current_user;
  3536. $tab_id = getTabid($module);
  3537. $sec_parameter="";
  3538. require('user_privileges/user_privileges_'.$current_user->id.'.php');
  3539. require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
  3540. if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3)
  3541. {
  3542. if($module == "Vendors") {
  3543. $sec_parameter = "";
  3544. } else {
  3545. $sec_parameter=getListViewSecurityParameter($module);
  3546. if($module == "Accounts") {
  3547. $sec_parameter .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.")
  3548. OR vtiger_crmentity.smownerid IN (
  3549. SELECT vtiger_user2role.userid
  3550. FROM vtiger_user2role
  3551. INNER JOIN vtiger_users
  3552. ON vtiger_users.id = vtiger_user2role.userid
  3553. INNER JOIN vtiger_role
  3554. ON vtiger_role.roleid = vtiger_user2role.roleid
  3555. WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%')
  3556. OR vtiger_crmentity.smownerid IN (
  3557. SELECT shareduserid
  3558. FROM vtiger_tmp_read_user_sharing_per
  3559. WHERE userid=".$current_user->id."
  3560. AND tabid=".$tab_id.")
  3561. OR (vtiger_crmentity.smownerid in (0)
  3562. AND (";
  3563. if(sizeof($current_user_groups) > 0) {
  3564. $sec_parameter .= " vtiger_groups.groupname IN (
  3565. SELECT groupname
  3566. FROM vtiger_groups
  3567. WHERE groupid IN (". implode(",", getCurrentUserGroupList()) ."))
  3568. OR ";
  3569. }
  3570. $sec_parameter .= " vtiger_groups.groupname IN (
  3571. SELECT vtiger_groups.groupname
  3572. FROM vtiger_tmp_read_group_sharing_per
  3573. INNER JOIN vtiger_groups
  3574. ON vtiger_groups.groupid = vtiger_tmp_read_group_sharing_per.sharedgroupid
  3575. WHERE userid=".$current_user->id."
  3576. AND tabid=".$tab_id.")))) ";
  3577. }
  3578. }
  3579. }
  3580. return $sec_parameter;
  3581. }
  3582. // Update all the data refering to currency $old_cur to $new_cur
  3583. function transferCurrency($old_cur, $new_cur) {
  3584. // Transfer User currency to new currency
  3585. transferUserCurrency($old_cur, $new_cur);
  3586. // Transfer Product Currency to new currency
  3587. transferProductCurrency($old_cur, $new_cur);
  3588. // Transfer PriceBook Currency to new currency
  3589. transferPriceBookCurrency($old_cur, $new_cur);
  3590. }
  3591. // Function to transfer the users with currency $old_cur to $new_cur as currency
  3592. function transferUserCurrency($old_cur, $new_cur) {
  3593. global $log, $adb, $current_user;
  3594. $log->debug("Entering function transferUserCurrency...");
  3595. $sql = "update vtiger_users set currency_id=? where currency_id=?";
  3596. $adb->pquery($sql, array($new_cur, $old_cur));
  3597. $current_user->retrieve_entity_info($current_user->id,"Users");
  3598. $log->debug("Exiting function transferUserCurrency...");
  3599. }
  3600. // Function to transfer the products with currency $old_cur to $new_cur as currency
  3601. function transferProductCurrency($old_cur, $new_cur) {
  3602. global $log, $adb;
  3603. $log->debug("Entering function updateProductCurrency...");
  3604. $prod_res = $adb->pquery("select productid from vtiger_products where currency_id = ?", array($old_cur));
  3605. $numRows = $adb->num_rows($prod_res);
  3606. $prod_ids = array();
  3607. for($i=0;$i<$numRows;$i++) {
  3608. $prod_ids[] = $adb->query_result($prod_res,$i,'productid');
  3609. }
  3610. if(count($prod_ids) > 0) {
  3611. $prod_price_list = getPricesForProducts($new_cur,$prod_ids);
  3612. for($i=0;$i<count($prod_ids);$i++) {
  3613. $product_id = $prod_ids[$i];
  3614. $unit_price = $prod_price_list[$product_id];
  3615. $query = "update vtiger_products set currency_id=?, unit_price=? where productid=?";
  3616. $params = array($new_cur, $unit_price, $product_id);
  3617. $adb->pquery($query, $params);
  3618. }
  3619. }
  3620. $log->debug("Exiting function updateProductCurrency...");
  3621. }
  3622. // Function to transfer the pricebooks with currency $old_cur to $new_cur as currency
  3623. // and to update the associated products with list price in $new_cur currency
  3624. function transferPriceBookCurrency($old_cur, $new_cur) {
  3625. global $log, $adb;
  3626. $log->debug("Entering function updatePriceBookCurrency...");
  3627. $pb_res = $adb->pquery("select pricebookid from vtiger_pricebook where currency_id = ?", array($old_cur));
  3628. $numRows = $adb->num_rows($pb_res);
  3629. $pb_ids = array();
  3630. for($i=0;$i<$numRows;$i++) {
  3631. $pb_ids[] = $adb->query_result($pb_res,$i,'pricebookid');
  3632. }
  3633. if(count($pb_ids) > 0) {
  3634. require_once('modules/PriceBooks/PriceBooks.php');
  3635. for($i=0;$i<count($pb_ids);$i++) {
  3636. $pb_id = $pb_ids[$i];
  3637. $focus = new PriceBooks();
  3638. $focus->id = $pb_id;
  3639. $focus->mode = 'edit';
  3640. $focus->retrieve_entity_info($pb_id, "PriceBooks");
  3641. $focus->column_fields['currency_id'] = $new_cur;
  3642. $focus->save("PriceBooks");
  3643. }
  3644. }
  3645. $log->debug("Exiting function updatePriceBookCurrency...");
  3646. }
  3647. //functions for asterisk integration start
  3648. /**
  3649. * this function returns the caller name based on the phone number that is passed to it
  3650. * @param $from - the number which is calling
  3651. * returns caller information in name(type) format :: for e.g. Mary Smith (Contact)
  3652. * if no information is present in database, it returns :: Unknown Caller (Unknown)
  3653. */
  3654. function getCallerName($from) {
  3655. global $adb;
  3656. //information found
  3657. $callerInfo = getCallerInfo($from);
  3658. if($callerInfo != false){
  3659. $callerName = decode_html($callerInfo['name']);
  3660. $module = $callerInfo['module'];
  3661. $callerModule = " (<a href='index.php?module=$module&action=index'>$module</a>)";
  3662. $callerID = $callerInfo['id'];
  3663. $caller =$caller."<a href='index.php?module=$module&action=DetailView&record=$callerID'>$callerName</a>$callerModule";
  3664. }else{
  3665. $caller = $caller."<br>
  3666. <a target='_blank' href='index.php?module=Leads&action=EditView&phone=$from'>".getTranslatedString('LBL_CREATE_LEAD')."</a><br>
  3667. <a target='_blank' href='index.php?module=Contacts&phone=$from'>".getTranslatedString('LBL_CREATE_CONTACT')."</a><br>
  3668. <a target='_blank' href='index.php?module=Accounts&action=EditView&phone=$from'>".getTranslatedString('LBL_CREATE_ACCOUNT')."</a>";
  3669. }
  3670. return $caller;
  3671. }
  3672. /**
  3673. * this function searches for a given number in vtiger and returns the callerInfo in an array format
  3674. * currently the search is made across only leads, accounts and contacts modules
  3675. *
  3676. * @param $number - the number whose information you want
  3677. * @return array in format array(name=>callername, module=>module, id=>id);
  3678. */
  3679. function getCallerInfo($number){
  3680. global $adb, $log;
  3681. if(empty($number)){
  3682. return false;
  3683. }
  3684. $caller = "Unknown Number (Unknown)"; //declare caller as unknown in beginning
  3685. $params = array();
  3686. $name = array('Contacts', 'Accounts', 'Leads');
  3687. foreach ($name as $module) {
  3688. $focus = CRMEntity::getInstance($module);
  3689. $query = $focus->buildSearchQueryForFieldTypes(11, $number);
  3690. if(empty($query)) return;
  3691. $result = $adb->pquery($query, array());
  3692. if($adb->num_rows($result) > 0 ){
  3693. $callerName = $adb->query_result($result, 0, "name");
  3694. $callerID = $adb->query_result($result,0,'id');
  3695. $data = array("name"=>$callerName, "module"=>$module, "id"=>$callerID);
  3696. return $data;
  3697. }
  3698. }
  3699. return false;
  3700. }
  3701. /**
  3702. * this function returns the tablename and primarykeys for a given module in array format
  3703. * @param object $adb - peardatabase type object
  3704. * @param string $module - module name for which you want the array
  3705. * @return array(tablename1=>primarykey1,.....)
  3706. */
  3707. function get_tab_name_index($adb, $module){
  3708. $tabid = getTabid($module);
  3709. $sql = "select * from vtiger_tab_name_index where tabid = ?";
  3710. $result = $adb->pquery($sql, array($tabid));
  3711. $count = $adb->num_rows($result);
  3712. $data = array();
  3713. for($i=0; $i<$count; $i++){
  3714. $tablename = $adb->query_result($result, $i, "tablename");
  3715. $primaryKey = $adb->query_result($result, $i, "primarykey");
  3716. $data[$tablename] = $primaryKey;
  3717. }
  3718. return $data;
  3719. }
  3720. /**
  3721. * this function returns the value of use_asterisk from the database for the current user
  3722. * @param string $id - the id of the current user
  3723. */
  3724. function get_use_asterisk($id){
  3725. global $adb;
  3726. if(!vtlib_isModuleActive('PBXManager') || isPermitted('PBXManager', 'index') == 'no'){
  3727. return false;
  3728. }
  3729. $sql = "select * from vtiger_asteriskextensions where userid = ?";
  3730. $result = $adb->pquery($sql, array($id));
  3731. if($adb->num_rows($result)>0){
  3732. $use_asterisk = $adb->query_result($result, 0, "use_asterisk");
  3733. $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension");
  3734. if($use_asterisk == 0 || empty($asterisk_extension)){
  3735. return 'false';
  3736. }else{
  3737. return 'true';
  3738. }
  3739. }else{
  3740. return 'false';
  3741. }
  3742. }
  3743. /**
  3744. * this function adds a record to the callhistory module
  3745. *
  3746. * @param string $userExtension - the extension of the current user
  3747. * @param string $callfrom - the caller number
  3748. * @param string $callto - the called number
  3749. * @param string $status - the status of the call (outgoing/incoming/missed)
  3750. * @param object $adb - the peardatabase object
  3751. */
  3752. function addToCallHistory($userExtension, $callfrom, $callto, $status, $adb, $useCallerInfo){
  3753. $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
  3754. $result = $adb->pquery($sql,array($userExtension));
  3755. $userID = $adb->query_result($result, 0, "userid");
  3756. if(empty($userID)) {
  3757. // we have observed call to extension not configured in Vtiger will returns NULL
  3758. return;
  3759. }
  3760. $crmID = $adb->getUniqueID('vtiger_crmentity');
  3761. $timeOfCall = date('Y-m-d H:i:s');
  3762. $sql = "insert into vtiger_crmentity values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
  3763. $params = array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0);
  3764. $adb->pquery($sql, $params);
  3765. if(empty($callfrom)){
  3766. $callfrom = "Unknown";
  3767. }
  3768. if(empty($callto)){
  3769. $callto = "Unknown";
  3770. }
  3771. if($status == 'outgoing'){
  3772. //call is from user to record
  3773. $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
  3774. $result = $adb->pquery($sql, array($callfrom));
  3775. if($adb->num_rows($result)>0){
  3776. $userid = $adb->query_result($result, 0, "userid");
  3777. $callerName = getUserFullName($userid);
  3778. }
  3779. $receiver = $useCallerInfo;
  3780. if(empty($receiver)){
  3781. $receiver = "Unknown";
  3782. }else{
  3783. $receiver = "<a href='index.php?module=".$receiver['module']."&action=DetailView&record=".$receiver['id']."'>".$receiver['name']."</a>";
  3784. }
  3785. }else{
  3786. //call is from record to user
  3787. $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
  3788. $result = $adb->pquery($sql,array($callto));
  3789. if($adb->num_rows($result)>0){
  3790. $userid = $adb->query_result($result, 0, "userid");
  3791. $receiver = getUserFullName($userid);
  3792. }
  3793. $callerName = $useCallerInfo;
  3794. if(empty($callerName)){
  3795. $callerName = "Unknown $callfrom";
  3796. }else{
  3797. $callerName = "<a href='index.php?module=".$callerName['module']."&action=DetailView&record=".$callerName['id']."'>".decode_html($callerName['name'])."</a>";
  3798. }
  3799. }
  3800. $sql = "insert into vtiger_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)";
  3801. $params = array($crmID, $callerName, $receiver, $timeOfCall, $status);
  3802. $adb->pquery($sql, $params);
  3803. return $crmID;
  3804. }
  3805. //functions for asterisk integration end
  3806. //functions for settings page
  3807. /**
  3808. * this function returns the blocks for the settings page
  3809. */
  3810. function getSettingsBlocks(){
  3811. global $adb;
  3812. $sql = "select * from vtiger_settings_blocks order by sequence";
  3813. $result = $adb->query($sql);
  3814. $count = $adb->num_rows($result);
  3815. $blocks = array();
  3816. if($count>0){
  3817. for($i=0;$i<$count;$i++){
  3818. $blockid = $adb->query_result($result, $i, "blockid");
  3819. $label = $adb->query_result($result, $i, "label");
  3820. $blocks[$blockid] = $label;
  3821. }
  3822. }
  3823. return $blocks;
  3824. }
  3825. /**
  3826. * this function returns the fields for the settings page
  3827. */
  3828. function getSettingsFields(){
  3829. global $adb;
  3830. $sql = "select * from vtiger_settings_field where blockid!=? and active=0 order by blockid,sequence";
  3831. $result = $adb->pquery($sql, array(getSettingsBlockId('LBL_MODULE_MANAGER')));
  3832. $count = $adb->num_rows($result);
  3833. $fields = array();
  3834. if($count>0){
  3835. for($i=0;$i<$count;$i++){
  3836. $blockid = $adb->query_result($result, $i, "blockid");
  3837. $iconpath = $adb->query_result($result, $i, "iconpath");
  3838. $description = $adb->query_result($result, $i, "description");
  3839. $linkto = $adb->query_result($result, $i, "linkto");
  3840. $action = getPropertiesFromURL($linkto, "action");
  3841. $module = getPropertiesFromURL($linkto, "module");
  3842. $name = $adb->query_result($result, $i, "name");
  3843. $fields[$blockid][] = array("icon"=>$iconpath, "description"=>$description, "link"=>$linkto, "name"=>$name, "action"=>$action, "module"=>$module);
  3844. }
  3845. //add blanks for 4-column layout
  3846. foreach($fields as $blockid=>&$field){
  3847. if(count($field)>0 && count($field)<4){
  3848. for($i=count($field);$i<4;$i++){
  3849. $field[$i] = array();
  3850. }
  3851. }
  3852. }
  3853. }
  3854. return $fields;
  3855. }
  3856. /**
  3857. * this function takes an url and returns the module name from it
  3858. */
  3859. function getPropertiesFromURL($url, $action){
  3860. $result = array();
  3861. preg_match("/$action=([^&]+)/",$url,$result);
  3862. return $result[1];
  3863. }
  3864. //functions for settings page end
  3865. /* Function to get the name of the Field which is used for Module Specific Sequence Numbering, if any
  3866. * @param module String - Module label
  3867. * return Array - Field name and label are returned */
  3868. function getModuleSequenceField($module) {
  3869. global $adb, $log;
  3870. $log->debug("Entering function getModuleSequenceFieldName ($module)...");
  3871. $field = null;
  3872. if (!empty($module)) {
  3873. // First look at the cached information
  3874. $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
  3875. if($cachedModuleFields === false) {
  3876. //uitype 4 points to Module Numbering Field
  3877. $seqColRes = $adb->pquery("SELECT fieldname, fieldlabel, columnname FROM vtiger_field WHERE uitype=? AND tabid=? and vtiger_field.presence in (0,2)", array('4', getTabid($module)));
  3878. if($adb->num_rows($seqColRes) > 0) {
  3879. $fieldname = $adb->query_result($seqColRes,0,'fieldname');
  3880. $columnname = $adb->query_result($seqColRes,0,'columnname');
  3881. $fieldlabel = $adb->query_result($seqColRes,0,'fieldlabel');
  3882. $field = array();
  3883. $field['name'] = $fieldname;
  3884. $field['column'] = $columnname;
  3885. $field['label'] = $fieldlabel;
  3886. }
  3887. } else {
  3888. foreach($cachedModuleFields as $fieldinfo) {
  3889. if($fieldinfo['uitype'] == '4') {
  3890. $field = array();
  3891. $field['name'] = $fieldinfo['fieldname'];
  3892. $field['column'] = $fieldinfo['columnname'];
  3893. $field['label'] = $fieldinfo['fieldlabel'];
  3894. break;
  3895. }
  3896. }
  3897. }
  3898. }
  3899. $log->debug("Exiting getModuleSequenceFieldName...");
  3900. return $field;
  3901. }
  3902. /* Function to get the Result of all the field ids allowed for Duplicates merging for specified tab/module (tabid) */
  3903. function getFieldsResultForMerge($tabid) {
  3904. global $log, $adb;
  3905. $log->debug("Entering getFieldsResultForMerge(".$tabid.") method ...");
  3906. $nonmergable_tabids = array(29);
  3907. if (in_array($tabid, $nonmergable_tabids)) {
  3908. return null;
  3909. }
  3910. // List of Fields not allowed for Duplicates Merging based on the module (tabid) [tabid to fields mapping]
  3911. $nonmergable_field_tab = Array(
  3912. 4 => array('portal','imagename'),
  3913. 13 => array('update_log','filename','comments'),
  3914. );
  3915. $nonmergable_displaytypes = Array(4);
  3916. $nonmergable_uitypes = Array('70','69','4');
  3917. $sql = "SELECT fieldid,typeofdata FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2) AND block IS NOT NULL";
  3918. $params = array($tabid);
  3919. $where = '';
  3920. if (isset($nonmergable_field_tab[$tabid]) && count($nonmergable_field_tab[$tabid]) > 0) {
  3921. $where .= " AND fieldname NOT IN (". generateQuestionMarks($nonmergable_field_tab[$tabid]) .")";
  3922. array_push($params, $nonmergable_field_tab[$tabid]);
  3923. }
  3924. if (count($nonmergable_displaytypes) > 0) {
  3925. $where .= " AND displaytype NOT IN (". generateQuestionMarks($nonmergable_displaytypes) .")";
  3926. array_push($params, $nonmergable_displaytypes);
  3927. }
  3928. if (count($nonmergable_uitypes) > 0) {
  3929. $where .= " AND uitype NOT IN ( ". generateQuestionMarks($nonmergable_uitypes) .")" ;
  3930. array_push($params, $nonmergable_uitypes);
  3931. }
  3932. if (trim($where) != '') {
  3933. $sql .= $where;
  3934. }
  3935. $res = $adb->pquery($sql, $params);
  3936. $log->debug("Exiting getFieldsResultForMerge method ...");
  3937. return $res;
  3938. }
  3939. /* Function to get the related tables data
  3940. * @param - $module - Primary module name
  3941. * @param - $secmodule - Secondary module name
  3942. * return Array $rel_array tables and fields to be compared are sent
  3943. * */
  3944. function getRelationTables($module,$secmodule){
  3945. global $adb;
  3946. $primary_obj = CRMEntity::getInstance($module);
  3947. $secondary_obj = CRMEntity::getInstance($secmodule);
  3948. $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?)",array($module,$secmodule,$secmodule,$module));
  3949. if($adb->num_rows($ui10_query)>0){
  3950. $ui10_tablename = $adb->query_result($ui10_query,0,'tablename');
  3951. $ui10_columnname = $adb->query_result($ui10_query,0,'columnname');
  3952. $ui10_tabid = $adb->query_result($ui10_query,0,'tabid');
  3953. if($primary_obj->table_name == $ui10_tablename){
  3954. $reltables = array($ui10_tablename=>array("".$primary_obj->table_index."","$ui10_columnname"));
  3955. } else if($secondary_obj->table_name == $ui10_tablename){
  3956. $reltables = array($ui10_tablename=>array("$ui10_columnname","".$secondary_obj->table_index.""),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
  3957. } else {
  3958. if(isset($secondary_obj->tab_name_index[$ui10_tablename])){
  3959. $rel_field = $secondary_obj->tab_name_index[$ui10_tablename];
  3960. $reltables = array($ui10_tablename=>array("$ui10_columnname","$rel_field"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
  3961. } else {
  3962. $rel_field = $primary_obj->tab_name_index[$ui10_tablename];
  3963. $reltables = array($ui10_tablename=>array("$rel_field","$ui10_columnname"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
  3964. }
  3965. }
  3966. }else {
  3967. if(method_exists($primary_obj,setRelationTables)){
  3968. $reltables = $primary_obj->setRelationTables($secmodule);
  3969. } else {
  3970. $reltables = '';
  3971. }
  3972. }
  3973. if(is_array($reltables) && !empty($reltables)){
  3974. $rel_array = $reltables;
  3975. } else {
  3976. $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
  3977. }
  3978. return $rel_array;
  3979. }
  3980. /**
  3981. * This function returns no value but handles the delete functionality of each entity.
  3982. * Input Parameter are $module - module name, $return_module - return module name, $focus - module object, $record - entity id, $return_id - return entity id.
  3983. */
  3984. function DeleteEntity($module,$return_module,$focus,$record,$return_id) {
  3985. global $log;
  3986. $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)");
  3987. if ($module != $return_module && !empty($return_module) && !empty($return_id)) {
  3988. $focus->unlinkRelationship($record, $return_module, $return_id);
  3989. $focus->trackUnLinkedInfo($return_module, $return_id, $module, $record);
  3990. } else {
  3991. $focus->trash($module, $record);
  3992. }
  3993. $log->debug("Exiting DeleteEntity method ...");
  3994. }
  3995. /**
  3996. * Function to related two records of different entity types
  3997. */
  3998. function relateEntities($focus, $sourceModule, $sourceRecordId, $destinationModule, $destinationRecordIds) {
  3999. if(!is_array($destinationRecordIds)) $destinationRecordIds = Array($destinationRecordIds);
  4000. foreach($destinationRecordIds as $destinationRecordId) {
  4001. $focus->save_related_module($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId);
  4002. $focus->trackLinkedInfo($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId);
  4003. }
  4004. }
  4005. /* Function to install Vtlib Compliant modules
  4006. * @param - $packagename - Name of the module
  4007. * @param - $packagepath - Complete path to the zip file of the Module
  4008. */
  4009. function installVtlibModule($packagename, $packagepath, $customized=false) {
  4010. global $log;
  4011. require_once('vtlib/Vtiger/Package.php');
  4012. require_once('vtlib/Vtiger/Module.php');
  4013. $Vtiger_Utils_Log = true;
  4014. $package = new Vtiger_Package();
  4015. if($package->isLanguageType($packagepath)) {
  4016. $package = new Vtiger_Language();
  4017. $package->import($packagepath, true);
  4018. return;
  4019. }
  4020. $module = $package->getModuleNameFromZip($packagepath);
  4021. // Customization
  4022. if($package->isLanguageType()) {
  4023. require_once('vtlib/Vtiger/Language.php');
  4024. $languagePack = new Vtiger_Language();
  4025. @$languagePack->import($packagepath, true);
  4026. return;
  4027. }
  4028. // END
  4029. $module_exists = false;
  4030. $module_dir_exists = false;
  4031. if($module == null) {
  4032. $log->fatal("$packagename Module zipfile is not valid!");
  4033. } else if(Vtiger_Module::getInstance($module)) {
  4034. $log->fatal("$module already exists!");
  4035. $module_exists = true;
  4036. }
  4037. if($module_exists == false) {
  4038. $log->debug("$module - Installation starts here");
  4039. $package->import($packagepath, true);
  4040. $moduleInstance = Vtiger_Module::getInstance($module);
  4041. if (empty($moduleInstance)) {
  4042. $log->fatal("$module module installation failed!");
  4043. }
  4044. }
  4045. }
  4046. /* Function to update Vtlib Compliant modules
  4047. * @param - $module - Name of the module
  4048. * @param - $packagepath - Complete path to the zip file of the Module
  4049. */
  4050. function updateVtlibModule($module, $packagepath) {
  4051. global $log;
  4052. require_once('vtlib/Vtiger/Package.php');
  4053. require_once('vtlib/Vtiger/Module.php');
  4054. $Vtiger_Utils_Log = true;
  4055. $package = new Vtiger_Package();
  4056. if($package->isLanguageType($packagepath)) {
  4057. require_once('vtlib/Vtiger/Language.php');
  4058. $languagePack = new Vtiger_Language();
  4059. $languagePack->update(null, $packagepath, true);
  4060. return;
  4061. }
  4062. if($module == null) {
  4063. $log->fatal("Module name is invalid");
  4064. } else {
  4065. $moduleInstance = Vtiger_Module::getInstance($module);
  4066. if($moduleInstance || $package->isModuleBundle($packagepath)) {
  4067. $log->debug("$module - Module instance found - Update starts here");
  4068. $package->update($moduleInstance, $packagepath);
  4069. } else {
  4070. $log->fatal("$module doesn't exists!");
  4071. }
  4072. }
  4073. }
  4074. /* Function to only initialize the update of Vtlib Compliant modules
  4075. * @param - $module - Name of the module
  4076. * @param - $packagepath - Complete path to the zip file of the Module
  4077. */
  4078. function initUpdateVtlibModule($module, $packagepath) {
  4079. global $log;
  4080. require_once('vtlib/Vtiger/Package.php');
  4081. require_once('vtlib/Vtiger/Module.php');
  4082. $Vtiger_Utils_Log = true;
  4083. $package = new Vtiger_Package();
  4084. if($module == null) {
  4085. $log->fatal("Module name is invalid");
  4086. } else {
  4087. $moduleInstance = Vtiger_Module::getInstance($module);
  4088. if($moduleInstance) {
  4089. $log->debug("$module - Module instance found - Init Update starts here");
  4090. $package->initUpdate($moduleInstance, $packagepath, true);
  4091. } else {
  4092. $log->fatal("$module doesn't exists!");
  4093. }
  4094. }
  4095. }
  4096. /**
  4097. * this function checks if a given column exists in a given table or not
  4098. * @param string $columnName - the columnname
  4099. * @param string $tableName - the tablename
  4100. * @return boolean $status - true if column exists; false otherwise
  4101. */
  4102. function columnExists($columnName, $tableName){
  4103. global $adb;
  4104. $columnNames = array();
  4105. $columnNames = $adb->getColumnNames($tableName);
  4106. if(in_array($columnName, $columnNames)){
  4107. return true;
  4108. }else{
  4109. return false;
  4110. }
  4111. }
  4112. /* To get modules list for which work flow and field formulas is permitted*/
  4113. function com_vtGetModules($adb) {
  4114. $sql="select distinct vtiger_field.tabid, name
  4115. from vtiger_field
  4116. inner join vtiger_tab
  4117. on vtiger_field.tabid=vtiger_tab.tabid
  4118. where vtiger_field.tabid not in(9,10,16,15,8,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1";
  4119. $it = new SqlResultIterator($adb, $adb->query($sql));
  4120. $modules = array();
  4121. foreach($it as $row) {
  4122. if(isPermitted($row->name,'index') == "yes") {
  4123. $modules[$row->name] = getTranslatedString($row->name);
  4124. }
  4125. }
  4126. return $modules;
  4127. }
  4128. /**
  4129. * this function accepts a potential id returns the module name and entity value for the related field
  4130. * @param integer $id - the potential id
  4131. * @return array $data - the related module name and field value
  4132. */
  4133. function getRelatedInfo($id){
  4134. global $adb;
  4135. $data = array();
  4136. $sql = "select related_to from vtiger_potential where potentialid=?";
  4137. $result = $adb->pquery($sql, array($id));
  4138. if($adb->num_rows($result)>0){
  4139. $relID = $adb->query_result($result, 0, "related_to");
  4140. $sql = "select setype from vtiger_crmentity where crmid=?";
  4141. $result = $adb->pquery($sql, array($relID));
  4142. if($adb->num_rows($result)>0){
  4143. $setype = $adb->query_result($result, 0, "setype");
  4144. }
  4145. $data = array("setype"=>$setype, "relID"=>$relID);
  4146. }
  4147. return $data;
  4148. }
  4149. /**
  4150. * this function accepts an ID and returns the entity value for that id
  4151. * @param integer $id - the crmid of the record
  4152. * @return string $data - the entity name for the id
  4153. */
  4154. function getRecordInfoFromID($id){
  4155. global $adb;
  4156. $data = array();
  4157. $sql = "select setype from vtiger_crmentity where crmid=?";
  4158. $result = $adb->pquery($sql, array($id));
  4159. if($adb->num_rows($result)>0){
  4160. $setype = $adb->query_result($result, 0, "setype");
  4161. $data = getEntityName($setype, $id);
  4162. }
  4163. $data = array_values($data);
  4164. $data = $data[0];
  4165. return $data;
  4166. }
  4167. /**
  4168. * this function accepts an tabiD and returns the tablename, fieldname and fieldlabel for email field
  4169. * @param integer $tabid - the tabid of current module
  4170. * @return string $fields - the array of mail field's tablename, fieldname and fieldlabel
  4171. */
  4172. function getMailFields($tabid){
  4173. global $adb;
  4174. $fields = array();
  4175. $result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM vtiger_field WHERE tabid=? AND uitype IN (13,104)", array($tabid));
  4176. if($adb->num_rows($result)>0){
  4177. $tablename = $adb->query_result($result, 0, "tablename");
  4178. $fieldname = $adb->query_result($result, 0, "fieldname");
  4179. $fieldlabel = $adb->query_result($result, 0, "fieldlabel");
  4180. $fields = array("tablename"=>$tablename,"fieldname"=>$fieldname,"fieldlabel"=>$fieldlabel);
  4181. }
  4182. return $fields;
  4183. }
  4184. /**
  4185. * Function to check if a given record exists (not deleted)
  4186. * @param integer $recordId - record id
  4187. */
  4188. function isRecordExists($recordId) {
  4189. global $adb;
  4190. $query = "SELECT crmid FROM vtiger_crmentity where crmid=? AND deleted=0";
  4191. $result = $adb->pquery($query, array($recordId));
  4192. if ($adb->num_rows($result)) {
  4193. return true;
  4194. }
  4195. return false;
  4196. }
  4197. /** Function to set date values compatible to database (YY_MM_DD)
  4198. * @param $value -- value :: Type string
  4199. * @returns $insert_date -- insert_date :: Type string
  4200. */
  4201. function getValidDBInsertDateValue($value) {
  4202. global $log;
  4203. $log->debug("Entering getValidDBInsertDateValue(".$value.") method ...");
  4204. $value = trim($value);
  4205. $delim = array('/','.');
  4206. foreach ($delim as $delimiter){
  4207. $x = strpos($value, $delimiter);
  4208. if($x === false) continue;
  4209. else{
  4210. $value=str_replace($delimiter, '-', $value);
  4211. break;
  4212. }
  4213. }
  4214. list($y,$m,$d) = explode('-',$value);
  4215. if(strlen($y) == 1) $y = '0'.$y;
  4216. if(strlen($m) == 1) $m = '0'.$m;
  4217. if(strlen($d) == 1) $d = '0'.$d;
  4218. $value = implode('-', array($y,$m,$d));
  4219. if(strlen($y)<4){
  4220. $insert_date = DateTimeField::convertToDBFormat($value);
  4221. } else {
  4222. $insert_date = $value;
  4223. }
  4224. if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2}$/", $insert_date) == 0) {
  4225. return '';
  4226. }
  4227. $log->debug("Exiting getValidDBInsertDateValue method ...");
  4228. return $insert_date;
  4229. }
  4230. function getValidDBInsertDateTimeValue($value) {
  4231. $value = trim($value);
  4232. $valueList = explode(' ',$value);
  4233. if(count($valueList) == 2) {
  4234. $dbDateValue = getValidDBInsertDateValue($valueList[0]);
  4235. $dbTimeValue = $valueList[1];
  4236. if(!empty($dbTimeValue) && strpos($dbTimeValue, ':') === false) {
  4237. $dbTimeValue = $dbTimeValue.':';
  4238. }
  4239. $timeValueLength = strlen($dbTimeValue);
  4240. if(!empty($dbTimeValue) && strrpos($dbTimeValue, ':') == ($timeValueLength-1)) {
  4241. $dbTimeValue = $dbTimeValue.'00';
  4242. }
  4243. try {
  4244. $dateTime = new DateTimeField($dbDateValue.' '.$dbTimeValue);
  4245. return $dateTime->getDBInsertDateTimeValue();
  4246. } catch (Exception $ex) {
  4247. return '';
  4248. }
  4249. } elseif(count($valueList == 1)) {
  4250. return getValidDBInsertDateValue($value);
  4251. }
  4252. }
  4253. /** Function to set the PHP memory limit to the specified value, if the memory limit set in the php.ini is less than the specified value
  4254. * @param $newvalue -- Required Memory Limit
  4255. */
  4256. function _phpset_memorylimit_MB($newvalue) {
  4257. $current = @ini_get('memory_limit');
  4258. if(preg_match("/(.*)M/", $current, $matches)) {
  4259. // Check if current value is less then new value
  4260. if($matches[1] < $newvalue) {
  4261. @ini_set('memory_limit', "{$newvalue}M");
  4262. }
  4263. }
  4264. }
  4265. /** Function to sanitize the upload file name when the file name is detected to have bad extensions
  4266. * @param String -- $fileName - File name to be sanitized
  4267. * @return String - Sanitized file name
  4268. */
  4269. function sanitizeUploadFileName($fileName, $badFileExtensions) {
  4270. $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename
  4271. $fileName = rtrim($fileName, '\\/<>?*:"<>|');
  4272. $fileNameParts = explode(".", $fileName);
  4273. $countOfFileNameParts = count($fileNameParts);
  4274. $badExtensionFound = false;
  4275. for ($i=0;$i<$countOfFileNameParts;++$i) {
  4276. $partOfFileName = $fileNameParts[$i];
  4277. if(in_array(strtolower($partOfFileName), $badFileExtensions)) {
  4278. $badExtensionFound = true;
  4279. $fileNameParts[$i] = $partOfFileName . 'file';
  4280. }
  4281. }
  4282. $newFileName = implode(".", $fileNameParts);
  4283. if ($badExtensionFound) {
  4284. $newFileName .= ".txt";
  4285. }
  4286. return $newFileName;
  4287. }
  4288. /** Function to get the tab meta information for a given id
  4289. * @param $tabId -- tab id :: Type integer
  4290. * @returns $tabInfo -- array of preference name to preference value :: Type array
  4291. */
  4292. function getTabInfo($tabId) {
  4293. global $adb;
  4294. $tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM vtiger_tab_info WHERE tabid=?', array($tabId));
  4295. $tabInfo = array();
  4296. for($i=0; $i<$adb->num_rows($tabInfoResult); ++$i) {
  4297. $prefName = $adb->query_result($tabInfoResult, $i, 'prefname');
  4298. $prefValue = $adb->query_result($tabInfoResult, $i, 'prefvalue');
  4299. $tabInfo[$prefName] = $prefValue;
  4300. }
  4301. }
  4302. /** Function to return block name
  4303. * @param Integer -- $blockid
  4304. * @return String - Block Name
  4305. */
  4306. function getBlockName($blockid) {
  4307. global $adb;
  4308. if(!empty($blockid)){
  4309. $block_res = $adb->pquery('SELECT blocklabel FROM vtiger_blocks WHERE blockid = ?',array($blockid));
  4310. if($adb->num_rows($block_res)){
  4311. $blockname = $adb->query_result($block_res,0,'blocklabel');
  4312. return $blockname;
  4313. }
  4314. }
  4315. return '';
  4316. }
  4317. function validateAlphaNumericInput($string){
  4318. preg_match('/^[\w _\-]+$/', $string, $matches);
  4319. if(count($matches) == 0) {
  4320. return false;
  4321. }
  4322. return true;
  4323. }
  4324. function validateServerName($string){
  4325. preg_match('/^[\w\-\.\\/:]+$/', $string, $matches);
  4326. if(count($matches) == 0) {
  4327. return false;
  4328. }
  4329. return true;
  4330. }
  4331. function validateEmailId($string){
  4332. preg_match('/^[a-zA-Z0-9]+([\_\-\.]*[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-]?[a-zA-Z0-9]+)*\.+([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)*$/', $string, $matches);
  4333. if(count($matches) == 0) {
  4334. return false;
  4335. }
  4336. return true;
  4337. }
  4338. function str_rsplit($string, $splitLength) {
  4339. $reverseString = strrev($string);
  4340. $chunks = str_split($reverseString, $splitLength);
  4341. return array_reverse($chunks);
  4342. }
  4343. /**
  4344. * Function to get the list of Contacts related to an activity
  4345. * @param Integer $activityId
  4346. * @return Array $contactsList - List of Contact ids, mapped to Contact Names
  4347. */
  4348. function getActivityRelatedContacts($activityId) {
  4349. $adb = PearDatabase::getInstance();
  4350. $query = 'SELECT * FROM vtiger_cntactivityrel WHERE activityid=?';
  4351. $result = $adb->pquery($query, array($activityId));
  4352. $noOfContacts = $adb->num_rows($result);
  4353. $contactsList = array();
  4354. for ($i = 0; $i < $noOfContacts; ++$i) {
  4355. $contactId = $adb->query_result($result, $i, 'contactid');
  4356. $displayValueArray = getEntityName('Contacts', $contactId);
  4357. if (!empty($displayValueArray)) {
  4358. foreach ($displayValueArray as $key => $field_value) {
  4359. $contact_name = $field_value;
  4360. }
  4361. } else {
  4362. $contact_name='';
  4363. }
  4364. $contactsList[$contactId] = $contact_name;
  4365. }
  4366. return $contactsList;
  4367. }
  4368. function isLeadConverted($leadId) {
  4369. $adb = PearDatabase::getInstance();
  4370. $query = 'SELECT converted FROM vtiger_leaddetails WHERE converted = 1 AND leadid=?';
  4371. $params = array($leadId);
  4372. $result = $adb->pquery($query, $params);
  4373. if($result && $adb->num_rows($result) > 0) {
  4374. return true;
  4375. }
  4376. return false;
  4377. }
  4378. function getSelectedRecords($input,$module,$idstring,$excludedRecords) {
  4379. global $current_user, $adb;
  4380. if($idstring == 'relatedListSelectAll') {
  4381. $recordid = vtlib_purify($input['recordid']);
  4382. if($module == 'Accounts') {
  4383. $result = getCampaignAccountIds($recordid);
  4384. }
  4385. if($module == 'Contacts') {
  4386. $result = getCampaignContactIds($recordid);
  4387. }
  4388. if($module == 'Leads') {
  4389. $result = getCampaignLeadIds($recordid);
  4390. }
  4391. $storearray = array();
  4392. for ($i = 0; $i < $adb->num_rows($result); $i++) {
  4393. $storearray[] = $adb->query_result($result, $i, 'id');
  4394. }
  4395. $excludedRecords=explode(';',$excludedRecords);
  4396. $storearray=array_diff($storearray,$excludedRecords);
  4397. } else if($module == 'Documents') {
  4398. if($input['selectallmode']=='true') {
  4399. $result = getSelectAllQuery($input,$module);
  4400. $storearray = array();
  4401. $focus = CRMEntity::getInstance($module);
  4402. for ($i = 0; $i < $adb->num_rows($result); $i++) {
  4403. $storearray[] = $adb->query_result($result, $i, $focus->table_index);
  4404. }
  4405. $excludedRecords = explode(';',$excludedRecords);
  4406. $storearray = array_diff($storearray,$excludedRecords);
  4407. if($idstring != 'all') {
  4408. $storearray = array_merge($storearray,explode(';',$idstring));
  4409. }
  4410. $storearray = array_unique($storearray);
  4411. } else {
  4412. $storearray = explode(";",$idstring);
  4413. }
  4414. } elseif($idstring == 'all') {
  4415. $result = getSelectAllQuery($input,$module);
  4416. $storearray = array();
  4417. $focus = CRMEntity::getInstance($module);
  4418. for ($i = 0; $i < $adb->num_rows($result); $i++) {
  4419. $storearray[] = $adb->query_result($result, $i, $focus->table_index);
  4420. }
  4421. $excludedRecords = explode(';',$excludedRecords);
  4422. $storearray = array_diff($storearray,$excludedRecords);
  4423. } else {
  4424. $storearray = explode(";",$idstring);
  4425. }
  4426. return $storearray;
  4427. }
  4428. function getSelectAllQuery($input,$module) {
  4429. global $adb,$current_user;
  4430. $viewid = vtlib_purify($input['viewname']);
  4431. if($module == "Calendar") {
  4432. $listquery = getListQuery($module);
  4433. $oCustomView = new CustomView($module);
  4434. $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,$module);
  4435. $where = '';
  4436. if($input['query'] == 'true') {
  4437. list($where, $ustring) = split("#@@#",getWhereCondition($module, $input));
  4438. if(isset($where) && $where != '') {
  4439. $query .= " AND " .$where;
  4440. }
  4441. }
  4442. } else {
  4443. $queryGenerator = new QueryGenerator($module, $current_user);
  4444. $queryGenerator->initForCustomViewById($viewid);
  4445. if($input['query'] == 'true') {
  4446. $queryGenerator->addUserSearchConditions($input);
  4447. }
  4448. $queryGenerator->setFields(array('id'));
  4449. $query = $queryGenerator->getQuery();
  4450. if($module == 'Documents') {
  4451. $folderid = vtlib_purify($input['folderidstring']);
  4452. $folderid = str_replace(';', ',', $folderid);
  4453. $query .= " AND vtiger_notes.folderid in (".$folderid.")";
  4454. }
  4455. }
  4456. $result = $adb->pquery($query, array());
  4457. return $result;
  4458. }
  4459. function getCampaignAccountIds($id) {
  4460. global $adb;
  4461. $sql="SELECT vtiger_account.accountid as id FROM vtiger_account
  4462. INNER JOIN vtiger_campaignaccountrel ON vtiger_campaignaccountrel.accountid = vtiger_account.accountid
  4463. LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid
  4464. WHERE vtiger_campaignaccountrel.campaignid = ? AND vtiger_crmentity.deleted=0";
  4465. $result = $adb->pquery($sql, array($id));
  4466. return $result;
  4467. }
  4468. function getCampaignContactIds($id) {
  4469. global $adb;
  4470. $sql="SELECT vtiger_contactdetails.contactid as id FROM vtiger_contactdetails
  4471. INNER JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid
  4472. LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
  4473. WHERE vtiger_campaigncontrel.campaignid = ? AND vtiger_crmentity.deleted=0";
  4474. $result = $adb->pquery($sql, array($id));
  4475. return $result;
  4476. }
  4477. function getCampaignLeadIds($id) {
  4478. global $adb;
  4479. $sql="SELECT vtiger_leaddetails.leadid as id FROM vtiger_leaddetails
  4480. INNER JOIN vtiger_campaignleadrel ON vtiger_campaignleadrel.leadid = vtiger_leaddetails.leadid
  4481. LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid
  4482. WHERE vtiger_campaignleadrel.campaignid = ? AND vtiger_crmentity.deleted=0";
  4483. $result = $adb->pquery($sql, array($id));
  4484. return $result;
  4485. }
  4486. /** Function to get the difference between 2 datetime strings or millisecond values */
  4487. function dateDiff($d1, $d2){
  4488. $d1 = (is_string($d1) ? strtotime($d1) : $d1);
  4489. $d2 = (is_string($d2) ? strtotime($d2) : $d2);
  4490. $diffSecs = abs($d1 - $d2);
  4491. $baseYear = min(date("Y", $d1), date("Y", $d2));
  4492. $diff = mktime(0, 0, $diffSecs, 1, 1, $baseYear);
  4493. return array(
  4494. "years" => date("Y", $diff) - $baseYear,
  4495. "months_total" => (date("Y", $diff) - $baseYear) * 12 + date("n", $diff) - 1,
  4496. "months" => date("n", $diff) - 1,
  4497. "days_total" => floor($diffSecs / (3600 * 24)),
  4498. "days" => date("j", $diff) - 1,
  4499. "hours_total" => floor($diffSecs / 3600),
  4500. "hours" => date("G", $diff),
  4501. "minutes_total" => floor($diffSecs / 60),
  4502. "minutes" => (int) date("i", $diff),
  4503. "seconds_total" => $diffSecs,
  4504. "seconds" => (int) date("s", $diff)
  4505. );
  4506. }
  4507. /**
  4508. * Function to get the approximate difference between two date time values as string
  4509. */
  4510. function dateDiffAsString($d1, $d2) {
  4511. global $currentModule;
  4512. $dateDiff = dateDiff($d1, $d2);
  4513. $years = $dateDiff['years'];
  4514. $months = $dateDiff['months'];
  4515. $days = $dateDiff['days'];
  4516. $hours = $dateDiff['hours'];
  4517. $minutes = $dateDiff['minutes'];
  4518. $seconds = $dateDiff['seconds'];
  4519. if($years > 0) {
  4520. $diffString = "$years ".getTranslatedString('LBL_YEARS',$currentModule);
  4521. } elseif($months > 0) {
  4522. $diffString = "$months ".getTranslatedString('LBL_MONTHS',$currentModule);
  4523. } elseif($days > 0) {
  4524. $diffString = "$days ".getTranslatedString('LBL_DAYS',$currentModule);
  4525. } elseif($hours > 0) {
  4526. $diffString = "$hours ".getTranslatedString('LBL_HOURS',$currentModule);
  4527. } elseif($minutes > 0) {
  4528. $diffString = "$minutes ".getTranslatedString('LBL_MINUTES',$currentModule);
  4529. } else {
  4530. $diffString = "$seconds ".getTranslatedString('LBL_SECONDS',$currentModule);
  4531. }
  4532. return $diffString;
  4533. }
  4534. function getMinimumCronFrequency() {
  4535. if(file_exists('modules/Ondemand/Ondemand.config.php')) {
  4536. require_once('modules/Ondemand/Ondemand.config.php');
  4537. global $VtigerOndemandConfig;
  4538. if($VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY'] != '')
  4539. return $VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY'];
  4540. }
  4541. global $MINIMUM_CRON_FREQUENCY;
  4542. if(!empty($MINIMUM_CRON_FREQUENCY)) {
  4543. return $MINIMUM_CRON_FREQUENCY;
  4544. }
  4545. return 15;
  4546. }
  4547. ?>