PageRenderTime 48ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vtiger6/modules/CustomView/models/Record.php

https://bitbucket.org/thomashii/vtigercrm-6-for-postgresql
PHP | 999 lines | 722 code | 99 blank | 178 comment | 174 complexity | efebb7a058e459666748238d958a3cea 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. /**
  11. * CustomView Record Model Class
  12. */
  13. class CustomView_Record_Model extends Vtiger_Base_Model {
  14. // Constants to identify different status of the custom view
  15. const CV_STATUS_DEFAULT = 0;
  16. const CV_STATUS_PRIVATE = 1;
  17. const CV_STATUS_PENDING = 2;
  18. const CV_STATUS_PUBLIC = 3;
  19. /**
  20. * Function to get the Id
  21. * @return <Number> Custom View Id
  22. */
  23. public function getId() {
  24. return $this->get('cvid');
  25. }
  26. /**
  27. * Function to get the Owner Id
  28. * @return <Number> Id of the User who created the Custom View
  29. */
  30. public function getOwnerId() {
  31. return $this->get('userid');
  32. }
  33. /**
  34. * Function to get the Owner Name
  35. * @return <String> Custom View creator User Name
  36. */
  37. public function getOwnerName() {
  38. $ownerId = $this->getOwnerId();
  39. $entityNames = getEntityName('Users', array($ownerId));
  40. return $entityNames[$ownerId];
  41. }
  42. /**
  43. * Function to get the Module to which the record belongs
  44. * @return Vtiger_Module_Model
  45. */
  46. public function getModule() {
  47. return $this->module;
  48. }
  49. /**
  50. * Function to set the Module to which the record belongs
  51. * @param <String> $moduleName
  52. * @return Vtiger_Record_Model or Module Specific Record Model instance
  53. */
  54. public function setModule($moduleName) {
  55. $this->module = Vtiger_Module_Model::getInstance($moduleName);
  56. return $this;
  57. }
  58. /**
  59. * Function to set the Module to which the record belongs from the Module model instance
  60. * @param <Vtiger_Module_Model> $module
  61. * @return Vtiger_Record_Model or Module Specific Record Model instance
  62. */
  63. public function setModuleFromInstance($module) {
  64. $this->module = $module;
  65. return $this;
  66. }
  67. /**
  68. * Function to check if the view is marked as default
  69. * @return <Boolean> true/false
  70. */
  71. public function isDefault() {
  72. $db = PearDatabase::getInstance();
  73. $userPrivilegeModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
  74. $result = $db->pquery('SELECT default_cvid FROM vtiger_user_module_preferences WHERE userid = ? AND tabid = ?',
  75. array($userPrivilegeModel->getId(), $this->getModule()->getId()));
  76. if($db->num_rows($result)) {
  77. $cvId = $db->query_result($result, 0, 'default_cvid');
  78. if($cvId === $this->getId()) {
  79. return true;
  80. } else {
  81. return false;
  82. }
  83. }
  84. return ($this->get('setdefault') == 1);
  85. }
  86. /**
  87. * Function to check if the view is created by the current user or is default view
  88. * @return <Boolean> true/false
  89. */
  90. public function isMine() {
  91. $userPrivilegeModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
  92. return ($this->get('status') == self::CV_STATUS_DEFAULT || $this->get('userid') == $userPrivilegeModel->getId());
  93. }
  94. /**
  95. * Function to check if the view is approved to be Public
  96. * @return <Boolean> true/false
  97. */
  98. public function isPublic() {
  99. return (!$this->isMine() && $this->get('status') == self::CV_STATUS_PUBLIC);
  100. }
  101. /**
  102. * Function to check if the view is marked as Private
  103. * @return <Boolean> true/false
  104. */
  105. public function isPrivate() {
  106. return ($this->get('status') == self::CV_STATUS_PRIVATE);
  107. }
  108. /**
  109. * Function to check if the view is requested to be Public and is awaiting for Approval
  110. * @return <Boolean> true/false
  111. */
  112. public function isPending() {
  113. return (!$this->isMine() && $this->get('status') == self::CV_STATUS_PENDING);
  114. }
  115. /**
  116. * Function to check if the view is created by one of the users, who is below the current user in the role hierarchy
  117. * @return <Boolean> true/false
  118. */
  119. public function isOthers() {
  120. return (!$this->isMine() && $this->get('status') != self::CV_STATUS_PUBLIC);
  121. }
  122. /**
  123. * Function which checks if a view is set to Public by the user which may/may not be approved.
  124. * @return <Boolean> true/false
  125. */
  126. public function isSetPublic() {
  127. return ($this->get('status') == self::CV_STATUS_PUBLIC || $this->get('status') == self::CV_STATUS_PENDING);
  128. }
  129. public function isEditable() {
  130. if($this->get('viewname') == 'All') {
  131. return false;
  132. }
  133. if($this->isMine() || $this->isOthers()) {
  134. return true;
  135. }
  136. return false;
  137. }
  138. public function isDeletable() {
  139. return $this->isEditable();
  140. }
  141. /**
  142. * Function which provides the records for the current view
  143. * @param <Boolean> $skipRecords - List of the RecordIds to be skipped
  144. * @return <Array> List of RecordsIds
  145. */
  146. public function getRecordIds($skipRecords=false) {
  147. $db = PearDatabase::getInstance();
  148. $cvId = $this->getId();
  149. $moduleModel = $this->getModule();
  150. $moduleName = $moduleModel->get('name');
  151. $baseTableName = $moduleModel->get('basetable');
  152. $baseTableId = $moduleModel->get('basetableid');
  153. $listViewModel = Vtiger_ListView_Model::getInstance($moduleName, $cvId);
  154. $queryGenerator = $listViewModel->get('query_generator');
  155. $listQuery = $queryGenerator->getQuery();
  156. if($skipRecords && !empty($skipRecords) && is_array($skipRecords) && count($skipRecords) > 0) {
  157. $listQuery .= ' AND '.$baseTableName.'.'.$baseTableId.' NOT IN ('. implode(',', $skipRecords) .')';
  158. }
  159. $result = $db->query($listQuery);
  160. $noOfRecords = $db->num_rows($result);
  161. $recordIds = array();
  162. for($i=0; $i<$noOfRecords; ++$i) {
  163. $recordIds[] = $db->query_result($result, $i, $baseTableId);
  164. }
  165. return $recordIds;
  166. }
  167. /**
  168. * Function to save the custom view record
  169. */
  170. public function save() {
  171. $db = PearDatabase::getInstance();
  172. $currentUserModel = Users_Record_Model::getCurrentUserModel();
  173. $cvId = $this->getId();
  174. $moduleModel = $this->getModule();
  175. $moduleName = $moduleModel->get('name');
  176. $viewName = $this->get('viewname');
  177. $setDefault = $this->get('setdefault');
  178. $setMetrics = $this->get('setmetrics');
  179. $status = $this->get('status');
  180. if($status == self::CV_STATUS_PENDING) {
  181. if($currentUserModel->isAdminUser()) {
  182. $status = self::CV_STATUS_PUBLIC;
  183. }
  184. }
  185. if(!$cvId) {
  186. $cvId = $db->getUniqueID("vtiger_customview");
  187. $this->set('cvid', $cvId);
  188. $sql = 'INSERT INTO vtiger_customview(cvid, viewname, setdefault, setmetrics, entitytype, status, userid) VALUES (?,?,?,?,?,?,?)';
  189. $params = array($cvId, $viewName, $setDefault, $setMetrics, $moduleName, $status, $currentUserModel->getId());
  190. $db->pquery($sql, $params);
  191. } else {
  192. $sql = 'UPDATE vtiger_customview SET viewname=?, setdefault=?, setmetrics=?, status=? WHERE cvid=?';
  193. $params = array($viewName, $setDefault, $setMetrics, $status, $cvId);
  194. $db->pquery($sql, $params);
  195. $db->pquery('DELETE FROM vtiger_cvcolumnlist WHERE cvid = ?', array($cvId));
  196. $db->pquery('DELETE FROM vtiger_cvstdfilter WHERE cvid = ?', array($cvId));
  197. $db->pquery('DELETE FROM vtiger_cvadvfilter WHERE cvid = ?', array($cvId));
  198. $db->pquery('DELETE FROM vtiger_cvadvfilter_grouping WHERE cvid = ?', array($cvId));
  199. }
  200. if($setDefault == 1) {
  201. $query = 'SELECT 1 FROM vtiger_user_module_preferences WHERE userid = ? AND tabid = ?';
  202. $queryParams = array($currentUserModel->getId(), $moduleModel->getId());
  203. $queryResult = $db->pquery($query, $queryParams);
  204. if($db->num_rows($queryResult) > 0) {
  205. $updateSql = 'UPDATE vtiger_user_module_preferences SET default_cvid = ? WHERE userid = ? AND tabid = ?';
  206. $updateParams = array($cvId, $currentUserModel->getId(), $moduleModel->getId());
  207. $db->pquery($updateSql, $updateParams);
  208. } else {
  209. $insertSql = 'INSERT INTO vtiger_user_module_preferences(userid, tabid, default_cvid) VALUES (?,?,?)';
  210. $insertParams = array($currentUserModel->getId(), $moduleModel->getId(), $cvId);
  211. $db->pquery($insertSql, $insertParams);
  212. }
  213. } else {
  214. $deleteSql = 'DELETE FROM vtiger_user_module_preferences WHERE userid = ? AND tabid = ? AND default_cvid = ?';
  215. $deleteParams = array($currentUserModel->getId(), $moduleModel->getId(), $cvId);
  216. $db->pquery($deleteSql, $deleteParams);
  217. }
  218. $selectedColumnsList = $this->get('columnslist');
  219. if(!empty($selectedColumnsList)) {
  220. $noOfColumns = count($selectedColumnsList);
  221. for($i=0; $i<$noOfColumns; $i++) {
  222. $columnSql = 'INSERT INTO vtiger_cvcolumnlist (cvid, columnindex, columnname) VALUES (?,?,?)';
  223. $columnParams = array($cvId, $i, $selectedColumnsList[$i]);
  224. $db->pquery($columnSql, $columnParams);
  225. }
  226. } else {
  227. //no fields were sent so add default All filter columns
  228. $defaultModuleFilter = $db->pquery('SELECT cvid FROM vtiger_customview WHERE setdefault = 1 AND entitytype = ?',
  229. array($moduleName));
  230. $defaultViewId = $db->query_result($defaultModuleFilter, 0, 'cvid');
  231. if(empty($defaultViewId)) {
  232. $userDefaultModuleFilter = $db->pquery('SELECT default_cvid FROM vtiger_user_module_preferences WHERE
  233. userid = ? AND tabid = ?', array($currentUserModel->id, $moduleModel->getId()));
  234. $defaultViewId = $db->query_result($userDefaultModuleFilter, 0, 'default_cvid');
  235. }
  236. // Get the defaults filters columnlist
  237. $columnSql = "INSERT INTO vtiger_cvcolumnlist (cvid, columnindex, columnname)
  238. SELECT ?, columnindex, columnname FROM vtiger_cvcolumnlist WHERE cvid = ?";
  239. $db->pquery($columnSql, array($cvId, $defaultViewId));
  240. }
  241. $stdFilterList = $this->get('stdfilterlist');
  242. if(!empty($stdFilterList) && !empty($stdFilterList['columnname'])) {
  243. $stdFilterSql = 'INSERT INTO vtiger_cvstdfilter(cvid,columnname,stdfilter,startdate,enddate) VALUES (?,?,?,?,?)';
  244. $stdFilterParams = array($cvId, $stdFilterList['columnname'], $stdFilterList['stdfilter'],
  245. $db->formatDate($stdFilterList['startdate'], true),
  246. $db->formatDate($stdFilterList['enddate'], true));
  247. $db->pquery($stdFilterSql, $stdFilterParams);
  248. }
  249. $advFilterList = $this->get('advfilterlist');
  250. if(!empty($advFilterList)) {
  251. foreach($advFilterList as $groupIndex => $groupInfo) {
  252. if(empty($groupInfo)) continue;
  253. $groupColumns = $groupInfo['columns'];
  254. $groupCondition = $groupInfo['condition'];
  255. foreach($groupColumns as $columnIndex => $columnCondition) {
  256. if(empty($columnCondition)) continue;
  257. $advFilterColumn = $columnCondition['columnname'];
  258. $advFilterComparator = $columnCondition['comparator'];
  259. $advFitlerValue = $columnCondition['value'];
  260. $advFilterColumnCondition = $columnCondition['column_condition'];
  261. $columnInfo = explode(":",$advFilterColumn);
  262. $fieldName = $columnInfo[2];
  263. $fieldModel = $moduleModel->getField($fieldName);
  264. $fieldType = $fieldModel->getFieldDataType();
  265. if($fieldType == 'currency') {
  266. if($fieldModel->get('uitype') == '71') {
  267. $advFitlerValue = CurrencyField::convertToDBFormat($advFitlerValue, null, true);
  268. } else {
  269. $advFitlerValue = CurrencyField::convertToDBFormat($advFitlerValue);
  270. }
  271. }
  272. $temp_val = explode(",",$advFitlerValue);
  273. if(($fieldType == 'date' || ($fieldType == 'time' && $fieldName != 'time_start' && $fieldName != 'time_end') || ($fieldType == 'datetime')) && ($fieldType != '' && $advFitlerValue != '' )) {
  274. $val = Array();
  275. for($x=0;$x<count($temp_val);$x++) {
  276. //if date and time given then we have to convert the date and
  277. //leave the time as it is, if date only given then temp_time
  278. //value will be empty
  279. if(trim($temp_val[$x]) != '') {
  280. $date = new DateTimeField(trim($temp_val[$x]));
  281. if($fieldType == 'date') {
  282. $val[$x] = DateTimeField::convertToDBFormat(
  283. trim($temp_val[$x]));
  284. } elseif($fieldType == 'datetime') {
  285. $val[$x] = $date->getDBInsertDateTimeValue();
  286. } else {
  287. $val[$x] = $date->getDBInsertTimeValue();
  288. }
  289. }
  290. }
  291. $advFitlerValue = implode(",",$val);
  292. }
  293. $advCriteriaSql = 'INSERT INTO vtiger_cvadvfilter(cvid,columnindex,columnname,comparator,value,groupid,column_condition)
  294. values (?,?,?,?,?,?,?)';
  295. $advCriteriaParams = array($cvId, $columnIndex, $advFilterColumn, $advFilterComparator, $advFitlerValue, $groupIndex, $advFilterColumnCondition);
  296. $db->pquery($advCriteriaSql, $advCriteriaParams);
  297. // Update the condition expression for the group to which the condition column belongs
  298. $groupConditionExpression = '';
  299. if(!empty($advFilterList[$groupIndex]["conditionexpression"])) {
  300. $groupConditionExpression = $advFilterList[$groupIndex]["conditionexpression"];
  301. }
  302. $groupConditionExpression = $groupConditionExpression .' '. $columnIndex .' '. $advFilterColumnCondition;
  303. $advFilterList[$groupIndex]["conditionexpression"] = $groupConditionExpression;
  304. }
  305. $groupConditionExpression = $advFilterList[$groupIndex]["conditionexpression"];
  306. if(empty($groupConditionExpression)) continue; // Case when the group doesn't have any column criteria
  307. $advGroupSql = 'INSERT INTO vtiger_cvadvfilter_grouping(groupid,cvid,group_condition,condition_expression) VALUES (?,?,?,?)';
  308. $advGroupParams = array($groupIndex, $cvId, $groupCondition, $groupConditionExpression);
  309. $db->pquery($advGroupSql, $advGroupParams);
  310. }
  311. }
  312. }
  313. /**
  314. * Function to delete the custom view record
  315. */
  316. public function delete() {
  317. $db = PearDatabase::getInstance();
  318. $cvId = $this->getId();
  319. $db->pquery('DELETE FROM vtiger_customview WHERE cvid = ?', array($cvId));
  320. $db->pquery('DELETE FROM vtiger_cvcolumnlist WHERE cvid = ?', array($cvId));
  321. $db->pquery('DELETE FROM vtiger_cvstdfilter WHERE cvid = ?', array($cvId));
  322. $db->pquery('DELETE FROM vtiger_cvadvfilter WHERE cvid = ?', array($cvId));
  323. $db->pquery('DELETE FROM vtiger_cvadvfilter_grouping WHERE cvid = ?', array($cvId));
  324. }
  325. /**
  326. * Function to get the list of selected fields for the current custom view
  327. * @return <Array> List of Field Column Names
  328. */
  329. public function getSelectedFields() {
  330. $db = PearDatabase::getInstance();
  331. $query = 'SELECT vtiger_cvcolumnlist.* FROM vtiger_cvcolumnlist
  332. INNER JOIN vtiger_customview ON vtiger_customview.cvid = vtiger_cvcolumnlist.cvid
  333. WHERE vtiger_customview.cvid = ? ORDER BY vtiger_cvcolumnlist.columnindex';
  334. $params = array($this->getId());
  335. $result = $db->pquery($query, $params);
  336. $noOfFields = $db->num_rows($result);
  337. $selectedFields = array();
  338. for($i=0; $i<$noOfFields; ++$i) {
  339. $columnIndex = $db->query_result($result, $i, 'columnindex');
  340. $columnName = $db->query_result($result, $i, 'columnname');
  341. $selectedFields[$columnIndex] = $columnName;
  342. }
  343. return $selectedFields;
  344. }
  345. /**
  346. * Function to get the Standard filter condition for the current custom view
  347. * @return <Array> Standard filter condition
  348. */
  349. public function getStandardCriteria() {
  350. $db = PearDatabase::getInstance();
  351. $cvId = $this->getId();
  352. if(empty($cvId)) {
  353. return array();
  354. }
  355. $query = 'SELECT vtiger_cvstdfilter.* FROM vtiger_cvstdfilter
  356. INNER JOIN vtiger_customview ON vtiger_customview.cvid = vtiger_cvstdfilter.cvid
  357. WHERE vtiger_cvstdfilter.cvid = ?';
  358. $params = array($this->getId());
  359. $result = $db->pquery($query, $params);
  360. $stdfilterrow = $db->fetch_array($result);
  361. if(!empty($stdfilterrow)){
  362. $stdfilterlist = array();
  363. $stdfilterlist["columnname"] = $stdfilterrow["columnname"];
  364. $stdfilterlist["stdfilter"] = $stdfilterrow["stdfilter"];
  365. if ($stdfilterrow["stdfilter"] == "custom" || $stdfilterrow["stdfilter"] == "") {
  366. if ($stdfilterrow["startdate"] != "0000-00-00" && $stdfilterrow["startdate"] != "") {
  367. $startDateTime = new DateTimeField($stdfilterrow["startdate"] . ' ' . date('H:i:s'));
  368. $stdfilterlist["startdate"] = $startDateTime->getDisplayDate();
  369. }
  370. if ($stdfilterrow["enddate"] != "0000-00-00" && $stdfilterrow["enddate"] != "") {
  371. $endDateTime = new DateTimeField($stdfilterrow["enddate"] . ' ' . date('H:i:s'));
  372. $stdfilterlist["enddate"] = $endDateTime->getDisplayDate();
  373. }
  374. } else { //if it is not custom get the date according to the selected duration
  375. $datefilter = self::getDateForStdFilterBytype($stdfilterrow["stdfilter"]);
  376. $startDateTime = new DateTimeField($datefilter[0] . ' ' . date('H:i:s'));
  377. $stdfilterlist["startdate"] = $startDateTime->getDisplayDate();
  378. $endDateTime = new DateTimeField($datefilter[1] . ' ' . date('H:i:s'));
  379. $stdfilterlist["enddate"] = $endDateTime->getDisplayDate();
  380. }
  381. }
  382. return $stdfilterlist;
  383. }
  384. /**
  385. * Function to get the list of advanced filter conditions for the current custom view
  386. * @return <Array> - All the advanced filter conditions for the custom view, grouped by the condition grouping
  387. */
  388. public function getAdvancedCriteria() {
  389. $db = PearDatabase::getInstance();
  390. $default_charset = vglobal('default_charset');
  391. $cvId = $this->getId();
  392. $advft_criteria = array();
  393. if(empty($cvId)) {
  394. return $advft_criteria;
  395. }
  396. $sql = 'SELECT * FROM vtiger_cvadvfilter_grouping WHERE cvid = ? ORDER BY groupid';
  397. $groupsresult = $db->pquery($sql, array($this->getId()));
  398. $i = 1;
  399. $j = 0;
  400. while ($relcriteriagroup = $db->fetch_array($groupsresult)) {
  401. $groupId = $relcriteriagroup["groupid"];
  402. $groupCondition = $relcriteriagroup["group_condition"];
  403. $ssql = 'select vtiger_cvadvfilter.* from vtiger_customview
  404. inner join vtiger_cvadvfilter on vtiger_cvadvfilter.cvid = vtiger_customview.cvid
  405. left join vtiger_cvadvfilter_grouping on vtiger_cvadvfilter.cvid = vtiger_cvadvfilter_grouping.cvid
  406. and vtiger_cvadvfilter.groupid = vtiger_cvadvfilter_grouping.groupid';
  407. $ssql.= " where vtiger_customview.cvid = ? AND vtiger_cvadvfilter.groupid = ? order by vtiger_cvadvfilter.columnindex";
  408. $result = $db->pquery($ssql, array($this->getId(), $groupId));
  409. $noOfColumns = $db->num_rows($result);
  410. if ($noOfColumns <= 0)
  411. continue;
  412. while ($relcriteriarow = $db->fetch_array($result)) {
  413. $criteria = array();
  414. $criteria['columnname'] = html_entity_decode($relcriteriarow["columnname"], ENT_QUOTES, $default_charset);
  415. $criteria['comparator'] = $relcriteriarow["comparator"];
  416. $advfilterval = html_entity_decode($relcriteriarow["value"], ENT_QUOTES, $default_charset);
  417. $col = explode(":", $relcriteriarow["columnname"]);
  418. $temp_val = explode(",", $relcriteriarow["value"]);
  419. if ($col[4] == 'D' || ($col[4] == 'T' && $col[1] != 'time_start' && $col[1] != 'time_end') || ($col[4] == 'DT')) {
  420. $val = Array();
  421. for ($x = 0; $x < count($temp_val); $x++) {
  422. if ($col[4] == 'D') {
  423. $date = new DateTimeField(trim($temp_val[$x]));
  424. $val[$x] = $date->getDisplayDate();
  425. } elseif ($col[4] == 'DT') {
  426. $date = new DateTimeField(trim($temp_val[$x]));
  427. $val[$x] = $date->getDisplayDateTimeValue();
  428. } else {
  429. $date = new DateTimeField(trim($temp_val[$x]));
  430. $val[$x] = $date->getDisplayTime();
  431. }
  432. }
  433. $advfilterval = implode(",", $val);
  434. }
  435. $criteria['value'] = Vtiger_Util_Helper::toSafeHTML(decode_html($advfilterval));
  436. $criteria['column_condition'] = $relcriteriarow["column_condition"];
  437. $advft_criteria[$i]['columns'][$j] = $criteria;
  438. $advft_criteria[$i]['condition'] = $groupCondition;
  439. $j++;
  440. }
  441. if (!empty($advft_criteria[$i]['columns'][$j - 1]['column_condition'])) {
  442. $advft_criteria[$i]['columns'][$j - 1]['column_condition'] = '';
  443. }
  444. $i++;
  445. }
  446. // Clear the condition (and/or) for last group, if any.
  447. if (!empty($advft_criteria[$i - 1]['condition']))
  448. $advft_criteria[$i - 1]['condition'] = '';
  449. return $advft_criteria;
  450. }
  451. /**
  452. * Function returns standard filter sql
  453. * @return <String>
  454. */
  455. public function getCVStdFilterSQL() {
  456. $customView = new CustomView();
  457. return $customView->getCVStdFilterSQL($this->getId());
  458. }
  459. /**
  460. * Function returns Advanced filter sql
  461. * @return <String>
  462. */
  463. public function getCVAdvFilterSQL() {
  464. $customView = new CustomView();
  465. return $customView->getCVAdvFilterSQL($this->getId());
  466. }
  467. /**
  468. * Function returns approve url
  469. * @return String - approve url
  470. */
  471. public function getCreateUrl() {
  472. return 'index.php?module=CustomView&view=EditAjax&source_module='.$this->getModule()->get('name');
  473. }
  474. /**
  475. * Function returns approve url
  476. * @return String - approve url
  477. */
  478. public function getEditUrl() {
  479. return 'module=CustomView&view=EditAjax&source_module='.$this->getModule()->get('name').'&record='.$this->getId();
  480. }
  481. /**
  482. * Function returns approve url
  483. * @return String - approve url
  484. */
  485. public function getApproveUrl() {
  486. return 'index.php?module=CustomView&action=Approve&sourceModule='.$this->getModule()->get('name').'&record='.$this->getId();
  487. }
  488. /**
  489. * Function returns deny url
  490. * @return String - deny url
  491. */
  492. public function getDenyUrl() {
  493. return 'index.php?module=CustomView&action=Deny&sourceModule='.$this->getModule()->get('name').'&record='.$this->getId();
  494. }
  495. /**
  496. * Functions returns delete url
  497. * @return String - delete url
  498. */
  499. public function getDeleteUrl() {
  500. return 'index.php?module=CustomView&action=Delete&sourceModule='.$this->getModule()->get('name').'&record='.$this->getId();
  501. }
  502. public function approve() {
  503. $db = PearDatabase::getInstance();
  504. $db->pquery('UPDATE vtiger_customview SET status = ? WHERE cvid = ?',
  505. array(self::CV_STATUS_PUBLIC, $this->getId()));
  506. }
  507. public function deny() {
  508. $db = PearDatabase::getInstance();
  509. $db->pquery('UPDATE vtiger_customview SET status = ? WHERE cvid = ?',
  510. array(self::CV_STATUS_PRIVATE, $this->getId()));
  511. }
  512. /**
  513. * Function to get the date values for the given type of Standard filter
  514. * @param <String> $type
  515. * @return <Array> - 2 date values representing the range for the given type of Standard filter
  516. */
  517. protected static function getDateForStdFilterBytype($type) {
  518. $today = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
  519. $tomorrow = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 1, date("Y")));
  520. $yesterday = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
  521. $currentmonth0 = date("Y-m-d", mktime(0, 0, 0, date("m"), "01", date("Y")));
  522. $currentmonth1 = date("Y-m-t");
  523. $lastmonth0 = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, "01", date("Y")));
  524. $lastmonth1 = date("Y-m-t", strtotime("-1 Month"));
  525. $nextmonth0 = date("Y-m-d", mktime(0, 0, 0, date("m") + 1, "01", date("Y")));
  526. $nextmonth1 = date("Y-m-t", strtotime("+1 Month"));
  527. $lastweek0 = date("Y-m-d", strtotime("-2 week Sunday"));
  528. $lastweek1 = date("Y-m-d", strtotime("-1 week Saturday"));
  529. $thisweek0 = date("Y-m-d", strtotime("-1 week Sunday"));
  530. $thisweek1 = date("Y-m-d", strtotime("this Saturday"));
  531. $nextweek0 = date("Y-m-d", strtotime("this Sunday"));
  532. $nextweek1 = date("Y-m-d", strtotime("+1 week Saturday"));
  533. $next7days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 6, date("Y")));
  534. $next30days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 29, date("Y")));
  535. $next60days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 59, date("Y")));
  536. $next90days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 89, date("Y")));
  537. $next120days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 119, date("Y")));
  538. $last7days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 6, date("Y")));
  539. $last30days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 29, date("Y")));
  540. $last60days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 59, date("Y")));
  541. $last90days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 89, date("Y")));
  542. $last120days = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 119, date("Y")));
  543. $currentFY0 = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y")));
  544. $currentFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")));
  545. $lastFY0 = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y") - 1));
  546. $lastFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y") - 1));
  547. $nextFY0 = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y") + 1));
  548. $nextFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y") + 1));
  549. if (date("m") <= 4) {
  550. $cFq = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y")));
  551. $cFq1 = date("Y-m-d", mktime(0, 0, 0, "04", "30", date("Y")));
  552. $nFq = date("Y-m-d", mktime(0, 0, 0, "05", "01", date("Y")));
  553. $nFq1 = date("Y-m-d", mktime(0, 0, 0, "08", "31", date("Y")));
  554. $pFq = date("Y-m-d", mktime(0, 0, 0, "09", "01", date("Y") - 1));
  555. $pFq1 = date("Y-m-d", mktime(0, 0, 0, "12", "31", date("Y") - 1));
  556. } else if (date("m") > 4 and date("m") <= 8) {
  557. $pFq = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y")));
  558. $pFq1 = date("Y-m-d", mktime(0, 0, 0, "04", "30", date("Y")));
  559. $cFq = date("Y-m-d", mktime(0, 0, 0, "05", "01", date("Y")));
  560. $cFq1 = date("Y-m-d", mktime(0, 0, 0, "08", "31", date("Y")));
  561. $nFq = date("Y-m-d", mktime(0, 0, 0, "09", "01", date("Y")));
  562. $nFq1 = date("Y-m-d", mktime(0, 0, 0, "12", "31", date("Y")));
  563. } else {
  564. $nFq = date("Y-m-d", mktime(0, 0, 0, "01", "01", date("Y") + 1));
  565. $nFq1 = date("Y-m-d", mktime(0, 0, 0, "04", "30", date("Y") + 1));
  566. $pFq = date("Y-m-d", mktime(0, 0, 0, "05", "01", date("Y")));
  567. $pFq1 = date("Y-m-d", mktime(0, 0, 0, "08", "31", date("Y")));
  568. $cFq = date("Y-m-d", mktime(0, 0, 0, "09", "01", date("Y")));
  569. $cFq1 = date("Y-m-d", mktime(0, 0, 0, "12", "31", date("Y")));
  570. }
  571. $dateValues = array();
  572. if ($type == "today") {
  573. $dateValues[0] = $today;
  574. $dateValues[1] = $today;
  575. } elseif ($type == "yesterday") {
  576. $dateValues[0] = $yesterday;
  577. $dateValues[1] = $yesterday;
  578. } elseif ($type == "tomorrow") {
  579. $dateValues[0] = $tomorrow;
  580. $dateValues[1] = $tomorrow;
  581. } elseif ($type == "thisweek") {
  582. $dateValues[0] = $thisweek0;
  583. $dateValues[1] = $thisweek1;
  584. } elseif ($type == "lastweek") {
  585. $dateValues[0] = $lastweek0;
  586. $dateValues[1] = $lastweek1;
  587. } elseif ($type == "nextweek") {
  588. $dateValues[0] = $nextweek0;
  589. $dateValues[1] = $nextweek1;
  590. } elseif ($type == "thismonth") {
  591. $dateValues[0] = $currentmonth0;
  592. $dateValues[1] = $currentmonth1;
  593. } elseif ($type == "lastmonth") {
  594. $dateValues[0] = $lastmonth0;
  595. $dateValues[1] = $lastmonth1;
  596. } elseif ($type == "nextmonth") {
  597. $dateValues[0] = $nextmonth0;
  598. $dateValues[1] = $nextmonth1;
  599. } elseif ($type == "next7days") {
  600. $dateValues[0] = $today;
  601. $dateValues[1] = $next7days;
  602. } elseif ($type == "next30days") {
  603. $dateValues[0] = $today;
  604. $dateValues[1] = $next30days;
  605. } elseif ($type == "next60days") {
  606. $dateValues[0] = $today;
  607. $dateValues[1] = $next60days;
  608. } elseif ($type == "next90days") {
  609. $dateValues[0] = $today;
  610. $dateValues[1] = $next90days;
  611. } elseif ($type == "next120days") {
  612. $dateValues[0] = $today;
  613. $dateValues[1] = $next120days;
  614. } elseif ($type == "last7days") {
  615. $dateValues[0] = $last7days;
  616. $dateValues[1] = $today;
  617. } elseif ($type == "last30days") {
  618. $dateValues[0] = $last30days;
  619. $dateValues[1] = $today;
  620. } elseif ($type == "last60days") {
  621. $dateValues[0] = $last60days;
  622. $dateValues[1] = $today;
  623. } else if ($type == "last90days") {
  624. $dateValues[0] = $last90days;
  625. $dateValues[1] = $today;
  626. } elseif ($type == "last120days") {
  627. $dateValues[0] = $last120days;
  628. $dateValues[1] = $today;
  629. } elseif ($type == "thisfy") {
  630. $dateValues[0] = $currentFY0;
  631. $dateValues[1] = $currentFY1;
  632. } elseif ($type == "prevfy") {
  633. $dateValues[0] = $lastFY0;
  634. $dateValues[1] = $lastFY1;
  635. } elseif ($type == "nextfy") {
  636. $dateValues[0] = $nextFY0;
  637. $dateValues[1] = $nextFY1;
  638. } elseif ($type == "nextfq") {
  639. $dateValues[0] = $nFq;
  640. $dateValues[1] = $nFq1;
  641. } elseif ($type == "prevfq") {
  642. $dateValues[0] = $pFq;
  643. $dateValues[1] = $pFq1;
  644. } elseif ($type == "thisfq") {
  645. $dateValues[0] = $cFq;
  646. $dateValues[1] = $cFq1;
  647. } else {
  648. $dateValues[0] = "";
  649. $dateValues[1] = "";
  650. }
  651. return $dateValues;
  652. }
  653. /**
  654. * Function to get all the date filter type informations
  655. * @return <Array>
  656. */
  657. public static function getDateFilterTypes() {
  658. $dateFilters = Array('custom' => array('label' => 'LBL_CUSTOM'),
  659. 'prevfy' => array('label' => 'LBL_PREVIOUS_FY'),
  660. 'thisfy' => array('label' => 'LBL_CURRENT_FY'),
  661. 'nextfy' => array('label' => 'LBL_NEXT_FY'),
  662. 'prevfq' => array('label' => 'LBL_PREVIOUS_FQ'),
  663. 'thisfq' => array('label' => 'LBL_CURRENT_FQ'),
  664. 'nextfq' => array('label' => 'LBL_NEXT_FQ'),
  665. 'yesterday' => array('label' => 'LBL_YESTERDAY'),
  666. 'today' => array('label' => 'LBL_TODAY'),
  667. 'tomorrow' => array('label' => 'LBL_TOMORROW'),
  668. 'lastweek' => array('label' => 'LBL_LAST_WEEK'),
  669. 'thisweek' => array('label' => 'LBL_CURRENT_WEEK'),
  670. 'nextweek' => array('label' => 'LBL_NEXT_WEEK'),
  671. 'lastmonth' => array('label' => 'LBL_LAST_MONTH'),
  672. 'thismonth' => array('label' => 'LBL_CURRENT_MONTH'),
  673. 'nextmonth' => array('label' => 'LBL_NEXT_MONTH'),
  674. 'last7days' => array('label' => 'LBL_LAST_7_DAYS'),
  675. 'last30days' => array('label' => 'LBL_LAST_30_DAYS'),
  676. 'last60days' => array('label' => 'LBL_LAST_60_DAYS'),
  677. 'last90days' => array('label' => 'LBL_LAST_90_DAYS'),
  678. 'last120days' => array('label' => 'LBL_LAST_120_DAYS'),
  679. 'next30days' => array('label' => 'LBL_NEXT_30_DAYS'),
  680. 'next60days' => array('label' => 'LBL_NEXT_60_DAYS'),
  681. 'next90days' => array('label' => 'LBL_NEXT_90_DAYS'),
  682. 'next120days' => array('label' => 'LBL_NEXT_120_DAYS')
  683. );
  684. foreach($dateFilters as $filterType => $filterDetails) {
  685. $dateValues = self::getDateForStdFilterBytype($filterType);
  686. $dateFilters[$filterType]['startdate'] = $dateValues[0];
  687. $dateFilters[$filterType]['enddate'] = $dateValues[1];
  688. }
  689. return $dateFilters;
  690. }
  691. /**
  692. * Function to get all the supported advanced filter operations
  693. * @return <Array>
  694. */
  695. public static function getAdvancedFilterOptions() {
  696. return array(
  697. 'e' => 'LBL_EQUALS',
  698. 'n' => 'LBL_NOT_EQUAL_TO',
  699. 's' => 'LBL_STARTS_WITH',
  700. 'ew' => 'LBL_ENDS_WITH',
  701. 'c' => 'LBL_CONTAINS',
  702. 'k' => 'LBL_DOES_NOT_CONTAIN',
  703. 'l' => 'LBL_LESS_THAN',
  704. 'g' => 'LBL_GREATER_THAN',
  705. 'm' => 'LBL_LESS_THAN_OR_EQUAL',
  706. 'h' => 'LBL_GREATER_OR_EQUAL',
  707. 'b' => 'LBL_BEFORE',
  708. 'a' => 'LBL_AFTER',
  709. 'bw' => 'LBL_BETWEEN',
  710. );
  711. }
  712. /**
  713. * Function to get the advanced filter option names by Field type
  714. * @return <Array>
  715. */
  716. public static function getAdvancedFilterOpsByFieldType() {
  717. return array(
  718. 'V' => array('e','n','s','ew','c','k'),
  719. 'N' => array('e','n','l','g','m','h'),
  720. 'T' => array('e','n','l','g','m','h','bw','b','a'),
  721. 'I' => array('e','n','l','g','m','h'),
  722. 'C' => array('e','n'),
  723. 'D' => array('e','n','bw','b','a'),
  724. 'DT' => array('e','n','bw','b','a'),
  725. 'NN' => array('e','n','l','g','m','h'),
  726. 'E' => array('e','n','s','ew','c','k')
  727. );
  728. }
  729. /**
  730. * Function to get all the accessible Custom Views, for a given module if specified
  731. * @param <String> $moduleName
  732. * @return <Array> - Array of Vtiger_CustomView_Record models
  733. */
  734. public static function getAll($moduleName='') {
  735. $db = PearDatabase::getInstance();
  736. $userPrivilegeModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
  737. $currentUser = Users_Record_Model::getCurrentUserModel();
  738. $sql = 'SELECT * FROM vtiger_customview';
  739. $params = array();
  740. if(!empty($moduleName)) {
  741. $sql .= ' WHERE entitytype=?';
  742. $params[] = $moduleName;
  743. }
  744. if(!$userPrivilegeModel->isAdminUser()) {
  745. $userParentRoleSeq = $userPrivilegeModel->get('parent_role_seq');
  746. $sql .= " AND ( vtiger_customview.userid = ? OR vtiger_customview.status = 0 OR vtiger_customview.status = 3
  747. OR vtiger_customview.userid IN (
  748. SELECT vtiger_user2role.userid FROM vtiger_user2role
  749. INNER JOIN vtiger_users ON vtiger_users.id = vtiger_user2role.userid
  750. INNER JOIN vtiger_role ON vtiger_role.roleid = vtiger_user2role.roleid
  751. WHERE vtiger_role.parentrole LIKE '".$userParentRoleSeq."::%')
  752. )";
  753. $params[] = $currentUser->getId();
  754. }
  755. $result = $db->pquery($sql, $params);
  756. $noOfCVs = $db->num_rows($result);
  757. $customViews = array();
  758. for ($i=0; $i<$noOfCVs; ++$i) {
  759. $row = $db->query_result_rowdata($result, $i);
  760. $customView = new self();
  761. $customViews[$row['viewname']] = $customView->setData($row)->setModule($row['entitytype']);
  762. }
  763. return $customViews;
  764. }
  765. /**
  766. * Function to get the instance of Custom View module, given custom view id
  767. * @param <Integer> $cvId
  768. * @return CustomView_Record_Model instance, if exists. Null otherwise
  769. */
  770. public static function getInstanceById($cvId) {
  771. $db = PearDatabase::getInstance();
  772. $sql = 'SELECT * FROM vtiger_customview WHERE cvid = ?';
  773. $params = array($cvId);
  774. $result = $db->pquery($sql, $params);
  775. if($db->num_rows($result) > 0) {
  776. $row = $db->query_result_rowdata($result, 0);
  777. $customView = new self();
  778. return $customView->setData($row)->setModule($row['entitytype']);
  779. }
  780. return null;
  781. }
  782. /**
  783. * Function to get all the custom views, of a given module if specified, grouped by their status
  784. * @param <String> $moduleName
  785. * @return <Array> - Associative array of Status label to an array of Vtiger_CustomView_Record models
  786. */
  787. public static function getAllByGroup($moduleName='') {
  788. $customViews = self::getAll($moduleName);
  789. $groupedCustomViews = array();
  790. foreach ($customViews as $viewName => $customView) {
  791. if($customView->isMine()) {
  792. $groupedCustomViews['Mine'][$viewName] = $customView;
  793. } elseif($customView->isPublic()) {
  794. $groupedCustomViews['Public'][$viewName] = $customView;
  795. } elseif($customView->isPending()) {
  796. $groupedCustomViews['Pending'][$viewName] = $customView;
  797. } else {
  798. $groupedCustomViews['Others'][$viewName] = $customView;
  799. }
  800. }
  801. return $groupedCustomViews;
  802. }
  803. /**
  804. * Function to get Clean instance of this record
  805. * @return self
  806. */
  807. public static function getCleanInstance() {
  808. return new self();
  809. }
  810. /**
  811. * function to check duplicates from database
  812. * @param <type> $viewName
  813. * @param <type> module name entity type in database
  814. * @return <boolean> true/false
  815. */
  816. public function checkDuplicate() {
  817. $db = PearDatabase::getInstance();
  818. $query = "SELECT 1 FROM vtiger_customview WHERE viewname = ? AND entitytype = ?";
  819. $params = array($this->get('viewname'), $this->getModule()->getName());
  820. $cvid = $this->getId();
  821. if ($cvid) {
  822. $query .= " AND cvid != ?";
  823. array_push($params, $cvid);
  824. }
  825. $result = $db->pquery($query, $params);
  826. if ($db->num_rows($result)) {
  827. return true;
  828. }
  829. return false;
  830. }
  831. /**
  832. * Function used to transform the older filter condition to suit newer filters.
  833. * The newer filters have only two groups one with ALL(AND) condition between each
  834. * filter and other with ANY(OR) condition, this functions tranforms the older
  835. * filter with 'AND' condition between filters of a group and will be placed under
  836. * match ALL conditions group and the rest of it will be placed under match Any group.
  837. * @return <Array>
  838. */
  839. function transformToNewAdvancedFilter() {
  840. $standardFilter = $this->transformStandardFilter();
  841. $advancedFilter = $this->getAdvancedCriteria();
  842. $allGroupColumns = $anyGroupColumns = array();
  843. foreach($advancedFilter as $index=>$group) {
  844. $columns = $group['columns'];
  845. $and = $or = 0;
  846. if(!empty($group['condition'])){
  847. $block = $group['condition'];
  848. }
  849. if(count($columns) != 1) {
  850. foreach($columns as $column) {
  851. if($column['column_condition'] == 'and') {
  852. ++$and;
  853. } else {
  854. ++$or;
  855. }
  856. }
  857. if($and == count($columns)-1 && count($columns) != 1) {
  858. $allGroupColumns = array_merge($allGroupColumns, $group['columns']);
  859. } else {
  860. $anyGroupColumns = array_merge($anyGroupColumns, $group['columns']);
  861. }
  862. }else if($block == 'and'){
  863. $allGroupColumns = array_merge($allGroupColumns, $group['columns']);
  864. }else {
  865. $anyGroupColumns = array_merge($anyGroupColumns, $group['columns']);
  866. }
  867. }
  868. if($standardFilter){
  869. $allGroupColumns = array_merge($allGroupColumns,$standardFilter);
  870. }
  871. $transformedAdvancedCondition = array();
  872. $transformedAdvancedCondition[1] = array('columns' => $allGroupColumns, 'condition' => 'and');
  873. $transformedAdvancedCondition[2] = array('columns' => $anyGroupColumns, 'condition' => '');
  874. return $transformedAdvancedCondition;
  875. }
  876. /*
  877. * Function used to tranform the standard filter as like as advanced filter format
  878. * @returns array of tranformed standard filter
  879. */
  880. public function transformStandardFilter(){
  881. $standardFilter = $this->getStandardCriteria();
  882. if(!empty($standardFilter)){
  883. $tranformedStandardFilter = array();
  884. $tranformedStandardFilter['comparator'] = 'bw';
  885. $fields = explode(':',$standardFilter['columnname']);
  886. if($fields[1] == 'createdtime' || $fields[1] == 'modifiedtime' ||($fields[0] == 'vtiger_activity' && $fields[1] == 'date_start')){
  887. $tranformedStandardFilter['columnname'] = $standardFilter['columnname'].':DT';
  888. $date[] = $standardFilter['startdate'].' 00:00:00';
  889. $date[] = $standardFilter['enddate'].' 00:00:00';
  890. $tranformedStandardFilter['value'] = implode(',',$date);
  891. } else{
  892. $tranformedStandardFilter['columnname'] = $standardFilter['columnname'].':D';
  893. $tranformedStandardFilter['value'] = $standardFilter['startdate'].','.$standardFilter['enddate'];
  894. }
  895. return array($tranformedStandardFilter);
  896. } else{
  897. return false;
  898. }
  899. }
  900. }