PageRenderTime 35ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/Vtiger/helpers/Util.php

https://bitbucket.org/thomashii/vtigercrm-6-for-postgresql
PHP | 358 lines | 209 code | 39 blank | 110 comment | 43 complexity | d738e906331bcbd3a1dd80997a6daa2c MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, LGPL-2.1, GPL-2.0, GPL-3.0
  1. <?php
  2. /*+***********************************************************************************
  3. * The contents of this file are subject to the vtiger CRM Public License Version 1.0
  4. * ("License"); You may not use this file except in compliance with the License
  5. * The Original Code is: vtiger CRM Open Source
  6. * The Initial Developer of the Original Code is vtiger.
  7. * Portions created by vtiger are Copyright (C) vtiger.
  8. * All Rights Reserved.
  9. *************************************************************************************/
  10. class Vtiger_Util_Helper {
  11. /**
  12. * Function used to transform mulitiple uploaded file information into useful format.
  13. * @param array $_files - ex: array( 'file' => array('name'=> array(0=>'name1',1=>'name2'),
  14. * array('type'=>array(0=>'type1',2=>'type2'),
  15. * ...);
  16. * @param type $top
  17. * @return array array( 'file' => array(0=> array('name'=> 'name1','type' => 'type1'),
  18. * array(1=> array('name'=> 'name2','type' => 'type2'),
  19. * ...);
  20. */
  21. public static function transformUploadedFiles(array $_files, $top = TRUE) {
  22. $files = array();
  23. foreach($_files as $name=>$file) {
  24. if($top) $subName = $file['name'];
  25. else $subName = $name;
  26. if(is_array($subName)) {
  27. foreach(array_keys($subName) as $key) {
  28. $files[$name][$key] = array(
  29. 'name' => $file['name'][$key],
  30. 'type' => $file['type'][$key],
  31. 'tmp_name' => $file['tmp_name'][$key],
  32. 'error' => $file['error'][$key],
  33. 'size' => $file['size'][$key],
  34. );
  35. $files[$name] = self::transformUploadedFiles($files[$name], FALSE);
  36. }
  37. }else {
  38. $files[$name] = $file;
  39. }
  40. }
  41. return $files;
  42. }
  43. /**
  44. * Function parses date into readable format
  45. * @param <Date Time> $dateTime
  46. * @return <String>
  47. */
  48. public static function formatDateDiffInStrings($dateTime) {
  49. // http://www.php.net/manual/en/datetime.diff.php#101029
  50. $currentDateTime = date('Y-m-d H:i:s');
  51. $seconds = strtotime($currentDateTime) - strtotime($dateTime);
  52. if ($seconds == 0) return vtranslate('LBL_JUSTNOW');
  53. if ($seconds > 0) {
  54. $prefix = '';
  55. $suffix = ' '. vtranslate('LBL_AGO');
  56. } else if ($seconds < 0) {
  57. $prefix = vtranslate('LBL_DUE') . ' ';
  58. $suffix = '';
  59. $seconds = -($seconds);
  60. }
  61. $minutes = floor($seconds/60);
  62. $hours = floor($minutes/60);
  63. $days = floor($hours/24);
  64. $months = floor($days/30);
  65. if ($seconds < 60) return $prefix . self::pluralize($seconds, "LBL_SECOND") . $suffix;
  66. if ($minutes < 60) return $prefix . self::pluralize($minutes, "LBL_MINUTE") . $suffix;
  67. if ($hours < 24) return $prefix . self::pluralize($hours, "LBL_HOUR") . $suffix;
  68. if ($days < 30) return $prefix . self::pluralize($days, "LBL_DAY") . $suffix;
  69. if ($months < 12) return $prefix . self::pluralize($months, "LBL_MONTH") . $suffix;
  70. if ($months > 11) return $prefix . self::pluralize(floor($days/365), "LBL_YEAR") . $suffix;
  71. }
  72. /**
  73. * Function returns singular or plural text
  74. * @param <Number> $count
  75. * @param <String> $text
  76. * @return <String>
  77. */
  78. public static function pluralize($count, $text) {
  79. return $count ." ". (($count == 1) ? vtranslate("$text") : vtranslate("${text}S"));
  80. }
  81. /**
  82. * Function to make the input safe to be used as HTML
  83. */
  84. public static function toSafeHTML($input) {
  85. global $default_charset;
  86. return htmlentities($input, ENT_QUOTES, $default_charset);
  87. }
  88. /**
  89. * Function that will strip all the tags while displaying
  90. * @param <String> $input - html data
  91. * @return <String> vtiger6 displayable data
  92. */
  93. public static function toVtiger6SafeHTML($input) {
  94. $allowableTags = '<a><br>';
  95. return strip_tags($input, $allowableTags);
  96. }
  97. /**
  98. * Function to validate the input with given pattern.
  99. * @param <String> $string
  100. * @param <Boolean> $skipEmpty Skip the check if string is empty.
  101. * @return <String>
  102. * @throws AppException
  103. */
  104. public static function validateStringForSql($string, $skipEmpty=true) {
  105. if (vtlib_purifyForSql($string, $skipEmpty)) {
  106. return $string;
  107. }
  108. return false;
  109. }
  110. /**
  111. * Function Checks the existence of the record
  112. * @param <type> $recordId - module recordId
  113. * returns 1 if record exists else 0
  114. */
  115. public static function checkRecordExistance($recordId){
  116. global $adb;
  117. $query = 'Select deleted from vtiger_crmentity where crmid=?';
  118. $result = $adb->pquery($query, array($recordId));
  119. return $adb->query_result($result, 'deleted');
  120. }
  121. /**
  122. * Function to parses date into string format
  123. * @param <Date> $date
  124. * @param <Time> $time
  125. * @return <String>
  126. */
  127. public static function formatDateIntoStrings($date, $time = false) {
  128. $currentUser = Users_Record_Model::getCurrentUserModel();
  129. $dateTimeInUserFormat = Vtiger_Datetime_UIType::getDisplayDateTimeValue($date . ' ' . $time);
  130. list($dateInUserFormat, $timeInUserFormat) = explode(' ', $dateTimeInUserFormat);
  131. list($hours, $minutes, $seconds) = explode(':', $timeInUserFormat);
  132. $displayTime = $hours .':'. $minutes;
  133. if ($currentUser->get('hour_format') === '12') {
  134. $displayTime = Vtiger_Time_UIType::getTimeValueInAMorPM($displayTime);
  135. }
  136. $today = Vtiger_Date_UIType::getDisplayDateValue(date('Y-m-d H:i:s'));
  137. $tomorrow = Vtiger_Date_UIType::getDisplayDateValue(date('Y-m-d H:i:s', strtotime('tomorrow')));
  138. if ($dateInUserFormat == $today) {
  139. $formatedDate = vtranslate('LBL_TODAY');
  140. if ($time) {
  141. $formatedDate .= ' '. vtranslate('LBL_AT') .' '. $displayTime;
  142. }
  143. } elseif ($dateInUserFormat == $tomorrow) {
  144. $formatedDate = vtranslate('LBL_TOMORROW');
  145. if ($time) {
  146. $formatedDate .= ' '. vtranslate('LBL_AT') .' '. $displayTime;
  147. }
  148. } else {
  149. /**
  150. * To support strtotime() for 'mm-dd-yyyy' format the seperator should be '/'
  151. * For more referrences
  152. * http://php.net/manual/en/datetime.formats.date.php
  153. */
  154. if ($currentUser->get('date_format') === 'mm-dd-yyyy') {
  155. $dateInUserFormat = str_replace('-', '/', $dateInUserFormat);
  156. }
  157. $date = strtotime($dateInUserFormat);
  158. $formatedDate = vtranslate('LBL_'.date('D', $date)) . ' ' . date('d', $date) . ' ' . vtranslate('LBL_'.date('M', $date));
  159. if (date('Y', $date) != date('Y')) {
  160. $formatedDate .= ', '.date('Y', $date);
  161. }
  162. }
  163. return $formatedDate;
  164. }
  165. /**
  166. * Function to replace spaces with under scores
  167. * @param <String> $string
  168. * @return <String>
  169. */
  170. public static function replaceSpaceWithUnderScores($string) {
  171. return str_replace(' ', '_', $string);
  172. }
  173. public static function getRecordName ($recordId, $checkDelete=false) {
  174. $adb = PearDatabase::getInstance();
  175. $query = 'SELECT label from vtiger_crmentity where crmid=?';
  176. if($checkDelete) {
  177. $query.= ' AND deleted=0';
  178. }
  179. $result = $adb->pquery($query,array($recordId));
  180. $num_rows = $adb->num_rows($result);
  181. if($num_rows) {
  182. return $adb->query_result($result,0,'label');
  183. }
  184. return false;
  185. }
  186. /**
  187. * Function to parse dateTime into Days
  188. * @param <DateTime> $dateTime
  189. * @return <String>
  190. */
  191. public static function formatDateTimeIntoDayString($dateTime) {
  192. $currentUser = Users_Record_Model::getCurrentUserModel();
  193. $dateTimeInUserFormat = Vtiger_Datetime_UIType::getDisplayDateTimeValue($dateTime);
  194. list($dateInUserFormat, $timeInUserFormat) = explode(' ', $dateTimeInUserFormat);
  195. list($hours, $minutes, $seconds) = explode(':', $timeInUserFormat);
  196. $displayTime = $hours .':'. $minutes;
  197. if ($currentUser->get('hour_format') === '12') {
  198. $displayTime = Vtiger_Time_UIType::getTimeValueInAMorPM($displayTime);
  199. }
  200. /**
  201. * To support strtotime() for 'mm-dd-yyyy' format the seperator should be '/'
  202. * For more referrences
  203. * http://php.net/manual/en/datetime.formats.date.php
  204. */
  205. if ($currentUser->get('date_format') === 'mm-dd-yyyy') {
  206. $dateInUserFormat = str_replace('-', '/', $dateInUserFormat);
  207. }
  208. $date = strtotime($dateInUserFormat);
  209. //Adding date details
  210. $formatedDate = vtranslate('LBL_'.date('D', $date)). ', ' .vtranslate('LBL_'.date('M', $date)). ' ' .date('d', $date). ', ' .date('Y', $date);
  211. //Adding time details
  212. $formatedDate .= ' ' .vtranslate('LBL_AT'). ' ' .$displayTime;
  213. return $formatedDate;
  214. }
  215. /**
  216. * Function which will give the picklist values for a field
  217. * @param type $fieldName -- string
  218. * @return type -- array of values
  219. */
  220. public static function getPickListValues($fieldName) {
  221. $cache = Vtiger_Cache::getInstance();
  222. if($cache->getPicklistValues($fieldName)) {
  223. return $cache->getPicklistValues($fieldName);
  224. }
  225. $db = PearDatabase::getInstance();
  226. $query = 'SELECT '.$fieldName.' FROM vtiger_'.$fieldName.' order by sortorderid';
  227. $values = array();
  228. $result = $db->pquery($query, array());
  229. $num_rows = $db->num_rows($result);
  230. for($i=0; $i<$num_rows; $i++) {
  231. //Need to decode the picklist values twice which are saved from old ui
  232. $values[] = decode_html(decode_html($db->query_result($result,$i,$fieldName)));
  233. }
  234. $cache->setPicklistValues($fieldName, $values);
  235. return $values;
  236. }
  237. /**
  238. * Function gets the CRM's base Currency information
  239. * @return Array
  240. */
  241. public static function getBaseCurrency() {
  242. $db = PearDatabase::getInstance();
  243. $result = $db->pquery('SELECT * FROM vtiger_currency_info WHERE defaultid < 0', array());
  244. if($db->num_rows($result)) return $db->query_result_rowdata($result, 0);
  245. }
  246. /**
  247. * Function to get role based picklist values
  248. * @param <String> $fieldName
  249. * @param <Integer> $roleId
  250. * @return <Array> list of role based picklist values
  251. */
  252. public static function getRoleBasedPicklistValues($fieldName, $roleId) {
  253. $db = PearDatabase::getInstance();
  254. $query = "SELECT $fieldName
  255. FROM vtiger_$fieldName
  256. INNER JOIN vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldName.picklist_valueid
  257. WHERE roleid=? and picklistid in (select picklistid from vtiger_picklist) order by sortorderid";
  258. $result = $db->pquery($query, array($roleId));
  259. $picklistValues = Array();
  260. while ($row = $db->fetch_array($result)) {
  261. //Need to decode the picklist values twice which are saved from old ui
  262. $picklistValues[] = decode_html(decode_html($row[$fieldName]));
  263. }
  264. return $picklistValues;
  265. }
  266. /**
  267. * Function to sanitize the uploaded file name
  268. * @param <String> $fileName
  269. * @param <Array> $badFileExtensions
  270. * @return <String> sanitized file name
  271. */
  272. public static function sanitizeUploadFileName($fileName, $badFileExtensions) {
  273. $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename
  274. $fileName = rtrim($fileName, '\\/<>?*:"<>|');
  275. $fileNameParts = explode('.', $fileName);
  276. $countOfFileNameParts = count($fileNameParts);
  277. $badExtensionFound = false;
  278. for ($i=0; $i<$countOfFileNameParts; $i++) {
  279. $partOfFileName = $fileNameParts[$i];
  280. if(in_array(strtolower($partOfFileName), $badFileExtensions)) {
  281. $badExtensionFound = true;
  282. $fileNameParts[$i] = $partOfFileName . 'file';
  283. }
  284. }
  285. $newFileName = implode('.', $fileNameParts);
  286. if ($badExtensionFound) {
  287. $newFileName .= ".txt";
  288. }
  289. return $newFileName;
  290. }
  291. /**
  292. * Function to check with database has utf-8 support or not.
  293. * @global type $db_type
  294. * @param type $conn
  295. * @return character_set_database and collation_database
  296. */
  297. function checkDbUTF8Support($conn) {
  298. //global $db_type;
  299. //if($db_type == 'postgres')
  300. $pos = strpos($conn->databaseType, 'postgres');
  301. if( $pos !== false ) {
  302. return true;
  303. }
  304. $dbvarRS = &$conn->Execute("show variables like '%_database' ");
  305. $db_character_set = null;
  306. $db_collation_type = null;
  307. while(!$dbvarRS->EOF) {
  308. $arr = $dbvarRS->FetchRow();
  309. $arr = array_change_key_case($arr);
  310. switch($arr['variable_name']) {
  311. case 'character_set_database' : $db_character_set = $arr['value']; break;
  312. case 'collation_database' : $db_collation_type = $arr['value']; break;
  313. }
  314. // If we have all the required information break the loop.
  315. if($db_character_set != null && $db_collation_type != null) break;
  316. }
  317. return (stristr($db_character_set, 'utf8') && stristr($db_collation_type, 'utf8'));
  318. }
  319. }