]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/Dashlets/DashletGeneric.php
Release 6.2.0
[Github/sugarcrm.git] / include / Dashlets / DashletGeneric.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 require_once('include/Dashlets/Dashlet.php');
39 require_once('include/ListView/ListViewSmarty.php');
40 require_once('include/generic/LayoutManager.php');
41
42 class DashletGeneric extends Dashlet {
43    /**
44      * Fields that are searchable
45      * @var array
46      */
47     var $searchFields;
48     /**
49      * Displayable columns (ones available to display)
50      * @var array
51      */
52     var $columns;
53     /**
54      * Bean file used in this Dashlet
55      * @var bean
56      */
57     var $seedBean;
58     /**
59      * collection of filters to apply
60      * @var array
61      */
62     var $filters = null;
63     /**
64      * Number of Rows to display
65      * @var int
66      */
67     var $displayRows = '5';
68     /**
69      * Actual columns to display, will be a subset of $columns
70      * @var array
71      */
72     var $displayColumns = null;
73     /**
74      * Flag to display only the current users's items.
75      * @var bool
76      */
77     var $myItemsOnly = true;
78     /**
79      * Flag to display "myItemsOnly" checkbox in the DashletGenericConfigure.
80      * @var bool
81      */
82     var $showMyItemsOnly = true;
83     /**
84      * location of Smarty template file for display
85      * @var string
86      */
87     var $displayTpl = 'include/Dashlets/DashletGenericDisplay.tpl';
88     /**
89      * location of smarty template file for configuring
90      * @var string
91      */
92     var $configureTpl = 'include/Dashlets/DashletGenericConfigure.tpl';
93     /**
94      * smarty object for the generic configuration template
95      * @var string
96      */
97     var $configureSS;
98     /** search inputs to be populated in configure template.
99      *  modify this after processDisplayOptions, but before displayOptions to modify search inputs
100      *  @var array
101      */
102     var $currentSearchFields;
103     /**
104      * ListView Smarty Class
105      * @var Smarty
106      */
107     var $lvs;
108     var $layoutManager;
109
110     function DashletGeneric($id, $options = null) {
111         parent::Dashlet($id);
112         $this->isConfigurable = true;
113         if(isset($options)) {
114             if(!empty($options['filters'])) $this->filters = $options['filters'];
115             if(!empty($options['title'])) $this->title = $options['title'];
116             if(!empty($options['displayRows'])) $this->displayRows = $options['displayRows'];
117             if(!empty($options['displayColumns'])) $this->displayColumns = $options['displayColumns'];
118             if(isset($options['myItemsOnly'])) $this->myItemsOnly = $options['myItemsOnly'];
119             if(isset($options['autoRefresh'])) $this->autoRefresh = $options['autoRefresh'];
120         }
121
122         $this->layoutManager = new LayoutManager();
123         $this->layoutManager->setAttribute('context', 'Report');
124         // fake a reporter object here just to pass along the db type used in many widgets.
125         // this should be taken out when sugarwidgets change
126         $temp = (object) array('db' => &$GLOBALS['db'], 'report_def_str' => '');
127         $this->layoutManager->setAttributePtr('reporter', $temp);
128         $this->lvs = new ListViewSmarty();
129     }
130
131     /**
132      * Sets up the display options template
133      *
134      * @return string HTML that shows options
135      */
136     function processDisplayOptions() {
137          require_once('include/templates/TemplateGroupChooser.php');
138
139         $this->configureSS = new Sugar_Smarty();
140         // column chooser
141         $chooser = new TemplateGroupChooser();
142
143         $chooser->args['id'] = 'edit_tabs';
144         $chooser->args['left_size'] = 5;
145         $chooser->args['right_size'] = 5;
146         $chooser->args['values_array'][0] = array();
147         $chooser->args['values_array'][1] = array();
148
149         $this->loadCustomMetadata();
150         // Bug 39517 - Don't add custom fields automatically to the available fields to display in the listview
151         //$this->addCustomFields();
152         if($this->displayColumns) {
153              // columns to display
154              foreach($this->displayColumns as $num => $name) {
155                     // defensive code for array being returned
156                     $translated = translate($this->columns[$name]['label'], $this->seedBean->module_dir);
157                     if(is_array($translated)) $translated = $this->columns[$name]['label'];
158                     $chooser->args['values_array'][0][$name] = trim($translated, ':');
159              }
160              // columns not displayed
161              foreach(array_diff(array_keys($this->columns), array_values($this->displayColumns)) as $num => $name) {
162                     // defensive code for array being returned
163                     $translated = translate($this->columns[$name]['label'], $this->seedBean->module_dir);
164                     if(is_array($translated)) $translated = $this->columns[$name]['label'];
165                     $chooser->args['values_array'][1][$name] = trim($translated, ':');
166              }
167         }
168         else {
169              foreach($this->columns as $name => $val) {
170                 // defensive code for array being returned
171                 $translated = translate($this->columns[$name]['label'], $this->seedBean->module_dir);
172                 if(is_array($translated)) $translated = $this->columns[$name]['label'];
173                 if(!empty($val['default']) && $val['default'])
174                     $chooser->args['values_array'][0][$name] = trim($translated, ':');
175                 else
176                     $chooser->args['values_array'][1][$name] = trim($translated, ':');
177             }
178         }
179
180         $chooser->args['left_name'] = 'display_tabs';
181         $chooser->args['right_name'] = 'hide_tabs';
182         $chooser->args['max_left'] = '6';
183
184         $chooser->args['left_label'] =  $GLOBALS['app_strings']['LBL_DISPLAY_COLUMNS'];
185         $chooser->args['right_label'] =  $GLOBALS['app_strings']['LBL_HIDE_COLUMNS'];
186         $chooser->args['title'] =  '';
187         $this->configureSS->assign('columnChooser', $chooser->display());
188
189         $query = false;
190         $count = 0;
191
192         if(!is_array($this->filters)) {
193             // use default search params
194             $this->filters = array();
195             foreach($this->searchFields as $name => $params) {
196                 if(!empty($params['default']))
197                     $this->filters[$name] = $params['default'];
198             }
199         }
200         foreach($this->searchFields as $name=>$params) {
201             if(!empty($name)) {
202                 $name = strtolower($name);
203                 $currentSearchFields[$name] = array();
204                 $widgetDef = $this->seedBean->field_defs[$name];
205                 if($widgetDef['type'] == 'enum') $widgetDef['remove_blank'] = true; // remove the blank option for the dropdown
206                                 if($widgetDef['name'] == 'assigned_user_name') $widgetDef['name'] = 'assigned_user_id';
207                 $widgetDef['input_name0'] = empty($this->filters[$name]) ? '' : $this->filters[$name];
208                 $currentSearchFields[$name]['label'] = !empty($params['label']) ? translate($params['label'], $this->seedBean->module_dir) : translate($widgetDef['vname'], $this->seedBean->module_dir);
209                 $currentSearchFields[$name]['input'] = $this->layoutManager->widgetDisplayInput($widgetDef, true, (empty($this->filters[$name]) ? '' : $this->filters[$name]));
210             }
211             else { // ability to create spacers in input fields
212                 $currentSearchFields['blank' + $count]['label'] = '';
213                 $currentSearchFields['blank' + $count]['input'] = '';
214                 $count++;
215             }
216         }
217         $this->currentSearchFields = $currentSearchFields;
218
219         $this->configureSS->assign('strings', array('general' => $GLOBALS['mod_strings']['LBL_DASHLET_CONFIGURE_GENERAL'],
220                                      'filters' => $GLOBALS['mod_strings']['LBL_DASHLET_CONFIGURE_FILTERS'],
221                                      'myItems' => $GLOBALS['mod_strings']['LBL_DASHLET_CONFIGURE_MY_ITEMS_ONLY'],
222                                      'displayRows' => $GLOBALS['mod_strings']['LBL_DASHLET_CONFIGURE_DISPLAY_ROWS'],
223                                      'title' => $GLOBALS['mod_strings']['LBL_DASHLET_CONFIGURE_TITLE'],
224                                      'save' => $GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL'],
225                                      'autoRefresh' => $GLOBALS['app_strings']['LBL_DASHLET_CONFIGURE_AUTOREFRESH'],
226                                      ));
227         $this->configureSS->assign('id', $this->id);
228         $this->configureSS->assign('showMyItemsOnly', $this->showMyItemsOnly);
229         $this->configureSS->assign('myItemsOnly', $this->myItemsOnly);
230         $this->configureSS->assign('searchFields', $this->currentSearchFields);
231         // title
232         $this->configureSS->assign('dashletTitle', $this->title);
233
234         // display rows
235         $displayRowOptions = $GLOBALS['sugar_config']['dashlet_display_row_options'];
236         $this->configureSS->assign('displayRowOptions', $displayRowOptions);
237         $this->configureSS->assign('displayRowSelect', $this->displayRows);
238         
239         if($this->isAutoRefreshable()) {
240                 $this->configureSS->assign('isRefreshable', true);
241                         $this->configureSS->assign('autoRefreshOptions', $this->getAutoRefreshOptions());
242                         $this->configureSS->assign('autoRefreshSelect', $this->autoRefresh);
243                 }
244     }
245     /**
246      * Displays the options for this Dashlet
247      *
248      * @return string HTML that shows options
249      */
250     function displayOptions() {
251         $this->processDisplayOptions();
252         return parent::displayOptions() . $this->configureSS->fetch($this->configureTpl);
253     }
254
255     function buildWhere() {
256         global $current_user;
257
258         $returnArray = array();
259
260         if(!is_array($this->filters)) {
261             // use defaults
262             $this->filters = array();
263             foreach($this->searchFields as $name => $params) {
264                 if(!empty($params['default']))
265                     $this->filters[$name] = $params['default'];
266             }
267         }
268         foreach($this->filters as $name=>$params) {
269             if(!empty($params)) {
270                 if($name == 'assigned_user_id' && $this->myItemsOnly) continue; // don't handle assigned user filter if filtering my items only
271                 $widgetDef = $this->seedBean->field_defs[$name];
272
273                 $widgetClass = $this->layoutManager->getClassFromWidgetDef($widgetDef, true);
274                 $widgetDef['table'] = $this->seedBean->table_name;
275                 $widgetDef['table_alias'] = $this->seedBean->table_name;
276                                 if(!empty($widgetDef['source']) && $widgetDef['source'] == 'custom_fields'){
277                     $widgetDef['table'] = $this->seedBean->table_name."_cstm";
278                     $widgetDef['table_alias'] = $widgetDef['table'];
279                 }
280                 switch($widgetDef['type']) {// handle different types
281                     case 'date':
282                     case 'datetime':
283                     case 'datetimecombo':
284                         if(is_array($params) && !empty($params)) {
285                             if(!empty($params['date']))
286                                 $widgetDef['input_name0'] = $params['date'];
287                             $filter = 'queryFilter' . $params['type'];
288                         }
289                         else {
290                             $filter = 'queryFilter' . $params;
291                         }
292                         array_push($returnArray, $widgetClass->$filter($widgetDef, true));
293                         break;
294                     case 'assigned_user_name':
295                         // This type runs through the SugarWidgetFieldname class, and needs a little extra help to make it through
296                         if ( ! isset($widgetDef['column_key']) ) {
297                             $widgetDef['column_key'] = $name;
298                         }
299                         // No break here, we want to run through the default handler
300                     default:
301                         $widgetDef['input_name0'] = $params;
302                         if(is_array($params) && !empty($params)) { // handle array query
303                             array_push($returnArray, $widgetClass->queryFilterone_of($widgetDef, false));
304                         }
305                         else {
306                             array_push($returnArray, $widgetClass->queryFilterStarts_With($widgetDef, true));
307                         }
308                         $widgetDef['input_name0'] = $params;
309                     break;
310                 }
311             }
312         }
313
314         if($this->myItemsOnly) array_push($returnArray, $this->seedBean->table_name . '.' . "assigned_user_id = '" . $current_user->id . "'");
315
316         return $returnArray;
317     }
318
319         protected function loadCustomMetadata()
320         {
321         $customMetadate = 'custom/modules/'.$this->seedBean->module_dir.'/metadata/dashletviewdefs.php';
322         if ( file_exists ( $customMetadate )){
323                 require($customMetadate);
324                         $this->searchFields = $dashletData[$this->seedBean->module_dir.'Dashlet']['searchFields'];
325                         foreach($this->searchFields  as $key =>$def){
326                                 if($key == 'assigned_user_name'){
327                                         $this->searchFields['assigned_user_id'] = $def;
328                                         unset($this->searchFields['assigned_user_name'] );
329                                         break;
330                                 }
331                         }
332                         
333                 $this->columns = $dashletData[$this->seedBean->module_dir.'Dashlet']['columns'];
334         }
335         }
336         
337     /**
338      * Does all dashlet processing, here's your chance to modify the rows being displayed!
339      */
340     function process($lvsParams = array()) {
341         $currentSearchFields = array();
342         $configureView = true; // configure view or regular view
343         $query = false;
344         $whereArray = array();
345         $lvsParams['massupdate'] = false;
346
347                 $this->loadCustomMetadata();
348         $this->addCustomFields();
349         // apply filters
350         if(isset($this->filters) || $this->myItemsOnly) {
351             $whereArray = $this->buildWhere();
352         }
353         
354         $this->lvs->export = false;
355         $this->lvs->multiSelect = false;
356         // columns
357         $displayColumns = array();
358         if(!empty($this->displayColumns)) { // use user specified columns
359                 foreach($this->displayColumns as $name => $val) {
360                 $displayColumns[strtoupper($val)] = $this->columns[$val];
361                 $displayColumns[strtoupper($val)]['label'] = trim($displayColumns[strtoupper($val)]['label'], ':');// strip : at the end of headers
362             } 
363         }
364         else if (isset($this->columns)){ 
365            // use the default
366             foreach($this->columns as $name => $val) {
367                 if(!empty($val['default']) && $val['default']) {
368                     $displayColumns[strtoupper($name)] = $val;
369                     $displayColumns[strtoupper($name)]['label'] = trim($displayColumns[strtoupper($name)]['label'], ':');
370                 }
371             }
372         }
373         $this->lvs->displayColumns = $displayColumns;
374
375
376         $this->lvs->lvd->setVariableName($this->seedBean->object_name, array());
377         $lvdOrderBy = $this->lvs->lvd->getOrderBy(); // has this list been ordered, if not use default
378
379         $nameRelatedFields = array();
380         if(empty($lvdOrderBy['orderBy'])) {
381             foreach($displayColumns as $colName => $colParams) {
382                 if(!empty($colParams['defaultOrderColumn'])) {
383                     $lvsParams['overrideOrder'] = true;
384                     $lvsParams['orderBy'] = $colName;
385                     $lvsParams['sortOrder'] = $colParams['defaultOrderColumn']['sortOrder'];
386                 }
387             }
388         }
389                 // Check for 'last_name' column sorting with related fields (last_name, first_name)
390                 // See ListViewData.php for actual sorting change.
391                 if ($lvdOrderBy['orderBy'] == 'last_name' && !empty($displayColumns['NAME']) && !empty($displayColumns['NAME']['related_fields']) && 
392                         in_array('last_name', $displayColumns['NAME']['related_fields']) &&
393                         in_array('first_name', $displayColumns['NAME']['related_fields'])) {
394                                 $lvsParams['overrideLastNameOrder'] = true;
395                 }
396
397         if(!empty($this->displayTpl))
398         {
399                 //MFH BUG #14296
400             $where = '';
401             if(!empty($whereArray)){
402                 $where = '(' . implode(') AND (', $whereArray) . ')';
403             }
404             $this->lvs->setup($this->seedBean, $this->displayTpl, $where , $lvsParams, 0, $this->displayRows/*, $filterFields*/);
405             if(in_array('CREATED_BY', array_keys($displayColumns))) { // handle the created by field
406                 foreach($this->lvs->data['data'] as $row => $data) {
407                     $this->lvs->data['data'][$row]['CREATED_BY'] = get_assigned_user_name($data['CREATED_BY']);
408                 }
409             }
410             // assign a baseURL w/ the action set as DisplayDashlet
411             foreach($this->lvs->data['pageData']['urls'] as $type => $url) {
412                 // awu Replacing action=DisplayDashlet with action=DynamicAction&DynamicAction=DisplayDashlet
413                 if($type == 'orderBy')
414                     $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url);
415                 else
416                     $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url) . '&sugar_body_only=1&id=' . $this->id;
417             }
418
419             $this->lvs->ss->assign('dashletId', $this->id);
420         }
421     }
422
423    /**
424      * Displays the Dashlet, must call process() prior to calling this
425      *
426      * @return string HTML that displays Dashlet
427      */
428     function display() {
429         return parent::display() . $this->lvs->display(false) . $this->processAutoRefresh();
430     }
431
432     /**
433      * Filter the $_REQUEST and only save only the needed options
434      * @param array $req the array to pull options from
435      *
436      * @return array options array
437      */
438     function saveOptions($req) {
439         $options = array();
440
441                 $this->loadCustomMetadata();
442         foreach($req as $name => $value) {
443             if(!is_array($value)) $req[$name] = trim($value);
444         }
445         $options['filters'] = array();
446         foreach($this->searchFields as $name=>$params) {
447             $widgetDef = $this->seedBean->field_defs[$name];
448             if($widgetDef['type'] == 'datetimecombo' || $widgetDef['type'] == 'datetime' || $widgetDef['type'] == 'date') { // special case datetime types
449                 $options['filters'][$widgetDef['name']] = array();
450                 if(!empty($req['type_' . $widgetDef['name']])) { // save the type of date filter
451                     $options['filters'][$widgetDef['name']]['type'] = $req['type_' . $widgetDef['name']];
452                 }
453                 if(!empty($req['date_' . $widgetDef['name']])) { // save the date
454                     $options['filters'][$widgetDef['name']]['date'] = $req['date_' . $widgetDef['name']];
455                 }
456             }
457             elseif(!empty($req[$widgetDef['name']])) {
458                 $options['filters'][$widgetDef['name']] = $req[$widgetDef['name']];
459             }
460         }
461         if(!empty($req['dashletTitle'])) {
462             $options['title'] = $req['dashletTitle'];
463         }
464
465         if(!empty($req['myItemsOnly'])) {
466             $options['myItemsOnly'] = $req['myItemsOnly'];
467         }
468         else {
469            $options['myItemsOnly'] = false;
470         }
471         $options['displayRows'] = empty($req['displayRows']) ? '5' : $req['displayRows'];
472         // displayColumns
473         if(!empty($req['displayColumnsDef'])) {
474             $options['displayColumns'] = explode('|', $req['displayColumnsDef']);
475         }
476         $options['autoRefresh'] = empty($req['autoRefresh']) ? '0' : $req['autoRefresh'];
477         return $options;
478     }
479
480     /**
481      * Internal function to add custom fields
482      *
483      */
484     function addCustomFields() {
485         foreach($this->seedBean->field_defs as $fieldName => $def) {
486             if(!empty($def['type']) && $def['type'] == 'html')
487                 continue;
488             if(isset($def['vname'])) {
489                 $translated = translate($def['vname'], $this->seedBean->module_dir);
490                 if(is_array($translated)) $translated = $def['vname'];
491                 if(!empty($def['source']) && $def['source'] == 'custom_fields') {
492                         if(isset($this->columns[$fieldName]['default']) && $this->columns[$fieldName]['default']){
493                                 $this->columns[$fieldName] = array('width' => '10',
494                                                        'label' => $translated,
495                                                        'default' => 1);
496                         }else{
497                     $this->columns[$fieldName] = array('width' => '10',
498                                                        'label' => $translated);
499                         }
500                     
501                 }
502             }
503         }
504     }
505 }
506 ?>