]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/ListView/ListView.php
Release 6.5.6
[Github/sugarcrm.git] / include / ListView / ListView.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-2012 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/EditView/SugarVCR.php');
39 /**
40  * ListView - list of many objects
41  * @api
42  */
43 class ListView
44 {
45     var $local_theme= null;
46     var $local_app_strings= null;
47     var $local_image_path = null;
48     var $local_current_module = null;
49     var $local_mod_strings = null;
50     var $records_per_page = 20;
51     var $xTemplate = null;
52     var $xTemplatePath = null;
53     var $seed_data = null;
54     var $query_where = null;
55     var $query_limit = -1;
56     var $query_orderby = null;
57     var $header_title = '';
58     var $header_text = '';
59     var $initialized = false;
60     var $show_export_button = true;
61     var $show_delete_button = true;
62     var $show_select_menu = true;
63     var $show_paging = true;
64     var $show_mass_update = true;
65     var $show_mass_update_form = true;
66     var $query_where_has_changed = false;
67     var $display_header_and_footer = true;
68     var $baseURL = '';
69     var $is_dynamic = false;
70     var $inline = false;
71     var $start_link_wrapper = '';
72     var $end_link_wrapper = '';
73     var $list_field_defs = array();
74
75     var $shouldProcess = false;
76     var $data_array;
77     var $related_field_name = '';
78     var $child_focus = '';
79     var $layout_manager = null;
80     var $process_for_popups = false;
81     var $multi_select_popup=false;
82     var $_additionalDetails = false;
83     var $additionalDetailsFunction = null;
84     var $sort_order = '';
85     var $force_mass_update=false;
86     var $keep_mass_update_form_open=false;
87     var $ignorePopulateOnly = false;
88
89 function setDataArray($value) {
90     $this->data_array = $value;
91 }
92
93 function processListViewMulti($seed, $xTemplateSection, $html_varName) {
94
95     $this->shouldProcess = true;
96
97     echo "<form name='MassUpdate' method='post' action='index.php'>";
98     $this->processListViewTwo($seed, $xTemplateSection, $html_varName);
99
100     echo "<a href='javascript:" . ((!$this->multi_select_popup) ? 'sListView.' : ''). "check_all(document.MassUpdate, \"mass[]\", true)'>".translate('LBL_CHECKALL')."</a> - <a href='javascript:sListView.check_all(document.MassUpdate, \"mass[]\", false);'>".translate('LBL_CLEARALL')."</a>";
101     echo '<br><br>';
102 }
103
104
105 function processListView($seed, $xTemplateSection, $html_varName)
106 {
107     global $sugar_config;
108
109     $populateOnly = $this->ignorePopulateOnly ? FALSE : (!empty($sugar_config['save_query']) && $sugar_config['save_query'] == 'populate_only');
110     if(isset($seed->module_dir) && $populateOnly) {
111         if(empty($GLOBALS['displayListView']) && strcmp(strtolower($_REQUEST['action']), 'popup') != 0 && (!empty($_REQUEST['clear_query']) || $_REQUEST['module'] == $seed->module_dir && ((empty($_REQUEST['query']) || $_REQUEST['query'] == 'MSI')&& (empty($_SESSION['last_search_mod']) || $_SESSION['last_search_mod'] != $seed->module_dir)))) {
112             $_SESSION['last_search_mod'] = $_REQUEST['module'] ;
113             return;
114         }
115     }
116     if(strcmp(strtolower($_REQUEST['action']), 'popup') != 0){
117         $_SESSION['last_search_mod'] = $_REQUEST['module'] ;
118     }
119     //following session variable will track the detail view navigation history.
120     //needs to the reset after each search.
121     $this->setLocalSessionVariable($html_varName,"DETAIL_NAV_HISTORY",false);
122
123     require_once('include/MassUpdate.php');
124     $mass = new MassUpdate();
125     $add_acl_javascript = false;
126     if(!isset($_REQUEST['action'])) {
127         $this->shouldProcess=false;
128     } else {
129     $this->shouldProcess = is_subclass_of($seed, "SugarBean")
130         && (($_REQUEST['action'] == 'index') || ('ListView' == substr($_REQUEST['action'],0,8)) /* cn: to include all ListViewXXX.php type views */)
131         && ($_REQUEST['module'] == $seed->module_dir);
132     }
133
134     //when processing a multi-select popup.
135     if($this->process_for_popups && $this->multi_select_popup)  $this->shouldProcess =true;
136     //mass update turned off?
137     if(!$this->show_mass_update) $this->shouldProcess = false;
138     if(is_subclass_of($seed, "SugarBean")) {
139         if($seed->bean_implements('ACL')) {
140             if(!ACLController::checkAccess($seed->module_dir,'list',true)) {
141                 if($_REQUEST['module'] != 'Home') {
142                     ACLController::displayNoAccess();
143                 }
144                 return;
145             }
146             if(!ACLController::checkAccess($seed->module_dir,'export',true)) {
147                 $sugar_config['disable_export']= true;
148             }
149
150         }
151     }
152
153     //force mass update form if requested.
154     if($this->force_mass_update) {
155         $this->shouldProcess = true;
156     }
157
158     if($this->shouldProcess) {
159         echo $mass->getDisplayMassUpdateForm(true, $this->multi_select_popup);
160         echo $mass->getMassUpdateFormHeader($this->multi_select_popup);
161         $mass->setSugarBean($seed);
162
163         //C.L. Fix for 10048, do not process handleMassUpdate for multi select popups
164         if(!$this->multi_select_popup) {
165             $mass->handleMassUpdate();
166         }
167     }
168
169     $this->processListViewTwo($seed,$xTemplateSection, $html_varName);
170
171     if($this->shouldProcess && empty($this->process_for_popups)) {
172         //echo "<a href='javascript:sListView.clear_all(document.MassUpdate, \"mass[]\");'>".translate('LBL_CLEARALL')."</a>";
173         // cn: preserves current functionality, exception is InboundEmail
174         if($this->show_mass_update_form) {
175             echo $mass->getMassUpdateForm();
176         }
177         if(!$this->keep_mass_update_form_open) {
178             echo $mass->endMassUpdateForm();
179         }
180     }
181 }
182
183
184 function process_dynamic_listview($source_module, $sugarbean,$subpanel_def)
185 {
186         $this->source_module = $source_module;
187         $this->subpanel_module = $subpanel_def->name;
188         if(!isset($this->xTemplate))
189             $this->createXTemplate();
190
191         $html_var = $this->subpanel_module . "_CELL";
192
193         $list_data = $this->processUnionBeans($sugarbean,$subpanel_def, $html_var);
194
195         $list = $list_data['list'];
196         $parent_data = $list_data['parent_data'];
197
198         if($subpanel_def->isCollection()) {
199             $thepanel=$subpanel_def->get_header_panel_def();
200         } else {
201             $thepanel=$subpanel_def;
202         }
203
204
205
206         $this->process_dynamic_listview_header($thepanel->get_module_name(), $thepanel, $html_var);
207         $this->process_dynamic_listview_rows($list,$parent_data, 'dyn_list_view', $html_var,$subpanel_def);
208
209         if($this->display_header_and_footer)
210         {
211             $this->getAdditionalHeader();
212             if(!empty($this->header_title))
213             {
214                 echo get_form_header($this->header_title, $this->header_text, false);
215             }
216         }
217
218         $this->xTemplate->out('dyn_list_view');
219
220         if(isset($_SESSION['validation']))
221         {
222             print base64_decode('PGEgaHJlZj0naHR0cDovL3d3dy5zdWdhcmNybS5jb20nPlBPV0VSRUQmbmJzcDtCWSZuYnNwO1NVR0FSQ1JNPC9hPg==');
223         }
224         if(isset($list_data['query'])) {
225             return ($list_data['query']);
226         }
227     }
228
229 /**
230  * @return void
231  * @param unknown $data
232  * @param unknown $xTemplateSection
233  * @param unknown $html_varName
234  * @desc INTERNAL FUNCTION handles the rows
235  */
236  function process_dynamic_listview_rows($data,$parent_data, $xtemplateSection, $html_varName, $subpanel_def)
237  {
238     global $subpanel_item_count;
239     global $odd_bg;
240     global $even_bg;
241     global $hilite_bg;
242     global $click_bg;
243
244     $this->xTemplate->assign("BG_HILITE", $hilite_bg);
245     $this->xTemplate->assign('CHECKALL', SugarThemeRegistry::current()->getImage('blank', '', 1, 1, ".gif", ''));
246     //$this->xTemplate->assign("BG_CLICK", $click_bg);
247     $subpanel_item_count = 0;
248     $oddRow = true;
249     $count = 0;
250     reset($data);
251
252     //GETTING OFFSET
253     $offset = $this->getOffset($html_varName);
254     //$totaltime = 0;
255     $processed_ids = array();
256
257     $fill_additional_fields = array();
258     //Either retrieve the is_fill_in_additional_fields property from the lone
259     //subpanel or visit each subpanel's subpanels to retrieve the is_fill_in_addition_fields
260     //property
261     $subpanel_list=array();
262     if($subpanel_def->isCollection()) {
263         $subpanel_list=$subpanel_def->sub_subpanels;
264     } else {
265         $subpanel_list[]= $subpanel_def;
266     }
267
268     foreach($subpanel_list as $this_subpanel)
269     {
270         if($this_subpanel->is_fill_in_additional_fields())
271         {
272             $fill_additional_fields[] = $this_subpanel->bean_name;
273             $fill_additional_fields[$this_subpanel->bean_name] = true;
274         }
275     }
276
277     if ( empty($data) ) {
278         $this->xTemplate->assign("ROW_COLOR", 'oddListRow');
279         $thepanel=$subpanel_def;
280         if($subpanel_def->isCollection())
281             $thepanel=$subpanel_def->get_header_panel_def();
282         $this->xTemplate->assign("COL_COUNT", count($thepanel->get_list_fields()));
283         $this->xTemplate->parse($xtemplateSection.".nodata");
284     }
285     while(list($aVal, $aItem) = each($data))
286     {
287         $subpanel_item_count++;
288         $aItem->check_date_relationships_load();
289         // TODO: expensive and needs to be removed and done better elsewhere
290
291         if(!empty($fill_additional_fields[$aItem->object_name])
292         || ($aItem->object_name == 'Case' && !empty($fill_additional_fields['aCase']))
293         )
294         {
295             $aItem->fill_in_additional_list_fields();
296             //$aItem->fill_in_additional_detail_fields();
297         }
298         //rrs bug: 25343
299         $aItem->call_custom_logic("process_record");
300
301         if(isset($parent_data[$aItem->id])) {
302
303             $aItem->parent_name = $parent_data[$aItem->id]['parent_name'];
304             if(!empty($parent_data[$aItem->id]['parent_name_owner'])) {
305             $aItem->parent_name_owner =  $parent_data[$aItem->id]['parent_name_owner'];
306             $aItem->parent_name_mod =  $parent_data[$aItem->id]['parent_name_mod'];
307         }}
308         $fields = $aItem->get_list_view_data();
309         if(isset($processed_ids[$aItem->id])) {
310             continue;
311
312         } else {
313             $processed_ids[$aItem->id] = 1;
314         }
315
316
317         //ADD OFFSET TO ARRAY
318         $fields['OFFSET'] = ($offset + $count + 1);
319
320         if($this->shouldProcess) {
321             if($aItem->ACLAccess('EditView')) {
322             $this->xTemplate->assign('PREROW', "<input type='checkbox' class='checkbox' name='mass[]' value='". $fields['ID']. "' />");
323             } else {
324                 $this->xTemplate->assign('PREROW', '');
325
326             }
327             if($aItem->ACLAccess('DetailView')) {
328                 $this->xTemplate->assign('TAG_NAME','a');
329             } else {
330                 $this->xTemplate->assign('TAG_NAME','span');
331             }
332             $this->xTemplate->assign('CHECKALL', "<input type='checkbox'  title='".$GLOBALS['app_strings']['LBL_SELECT_ALL_TITLE']."' class='checkbox' name='massall' id='massall' value='' onclick='sListView.check_all(document.MassUpdate, \"mass[]\", this.checked);' />");
333         }
334
335         if($oddRow)
336         {
337             $ROW_COLOR = 'oddListRow';
338             $BG_COLOR =  $odd_bg;
339         }
340         else
341         {
342             $ROW_COLOR = 'evenListRow';
343             $BG_COLOR =  $even_bg;
344         }
345         $oddRow = !$oddRow;
346                 $button_contents = array();
347         $this->xTemplate->assign("ROW_COLOR", $ROW_COLOR);
348         $this->xTemplate->assign("BG_COLOR", $BG_COLOR);
349         $layout_manager = $this->getLayoutManager();
350         $layout_manager->setAttribute('context','List');
351         $layout_manager->setAttribute('image_path',$this->local_image_path);
352         $layout_manager->setAttribute('module_name', $subpanel_def->_instance_properties['module']);
353         if(!empty($this->child_focus))
354             $layout_manager->setAttribute('related_module_name',$this->child_focus->module_dir);
355
356         //AG$subpanel_data = $this->list_field_defs;
357         //$bla = array_pop($subpanel_data);
358         //select which sub-panel to display here, the decision will be made based on the type of
359         //the sub-panel and panel in the bean being processed.
360         if($subpanel_def->isCollection()) {
361             $thepanel=$subpanel_def->sub_subpanels[$aItem->panel_name];
362         } else {
363             $thepanel=$subpanel_def;
364         }
365         //get data source name
366         $linked_field=$thepanel->get_data_source_name();
367         $linked_field_set=$thepanel->get_data_source_name(true);
368         static $count;
369         if(!isset($count))$count = 0;
370
371         $field_acl['DetailView'] = $aItem->ACLAccess('DetailView');
372         $field_acl['ListView'] = $aItem->ACLAccess('ListView');
373         $field_acl['EditView'] = $aItem->ACLAccess('EditView');
374         $field_acl['Delete'] = $aItem->ACLAccess('Delete');
375         foreach($thepanel->get_list_fields() as $field_name=>$list_field)
376         {
377             //add linked field attribute to the array.
378             $list_field['linked_field']=$linked_field;
379             $list_field['linked_field_set']=$linked_field_set;
380
381             $usage = empty($list_field['usage']) ? '' : $list_field['usage'];
382             if($usage != 'query_only')
383             {
384                 $list_field['name']=$field_name;
385
386                 $module_field = $field_name.'_mod';
387                 $owner_field = $field_name.'_owner';
388                 if(!empty($aItem->$module_field)) {
389
390                     $list_field['owner_id'] = $aItem->$owner_field;
391                     $list_field['owner_module'] = $aItem->$module_field;
392
393                 } else {
394                     $list_field['owner_id'] = false;
395                     $list_field['owner_module'] = false;
396                 }
397                 if(isset($list_field['alias'])) $list_field['name'] = $list_field['alias'];
398                 else $list_field['name']=$field_name;
399                 $list_field['fields'] = $fields;
400                 $list_field['module'] = $aItem->module_dir;
401                 $list_field['start_link_wrapper'] = $this->start_link_wrapper;
402                 $list_field['end_link_wrapper'] = $this->end_link_wrapper;
403                 $list_field['subpanel_id'] = $this->subpanel_id;
404                 $list_field += $field_acl;
405                 if ( isset($aItem->field_defs[strtolower($list_field['name'])])) {
406                     require_once('include/SugarFields/SugarFieldHandler.php');
407                     // We need to see if a sugar field exists for this field type first,
408                     // if it doesn't, toss it at the old sugarWidgets. This is for
409                     // backwards compatibility and will be removed in a future release
410                     $vardef = $aItem->field_defs[strtolower($list_field['name'])];
411                     if ( isset($vardef['type']) ) {
412                         $fieldType = isset($vardef['custom_type'])?$vardef['custom_type']:$vardef['type'];
413                         $tmpField = SugarFieldHandler::getSugarField($fieldType,true);
414                     } else {
415                         $tmpField = NULL;
416                     }
417
418                     if ( $tmpField != NULL ) {
419                         $widget_contents = SugarFieldHandler::displaySmarty($list_field['fields'],$vardef,'ListView',$list_field);
420                     } else {
421                         // No SugarField for this particular type
422                         // Use the old, icky, SugarWidget for now
423                         $widget_contents = $layout_manager->widgetDisplay($list_field);
424                     }
425
426                     if ( isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelDetailViewLink' ) {
427                         // We need to call into the old SugarWidgets for the time being, so it can generate a proper link with all the various corner-cases handled
428                         // So we'll populate the field data with the pre-rendered display for the field
429                         $list_field['fields'][$field_name] = $widget_contents;
430                         if('full_name' == $field_name){//bug #32465
431                            $list_field['fields'][strtoupper($field_name)] = $widget_contents;
432                         }
433
434                         //vardef source is non db, assign the field name to varname for processing of column.
435                         if(!empty($vardef['source']) && $vardef['source']=='non-db'){
436                             $list_field['varname'] = $field_name;
437
438                         }
439                         $widget_contents = $layout_manager->widgetDisplay($list_field);
440                     } else if(isset($list_field['widget_class']) && $list_field['widget_class'] == 'SubPanelEmailLink' ) {
441                         $widget_contents = $layout_manager->widgetDisplay($list_field);
442                     }
443
444                  $count++;
445                 $this->xTemplate->assign('CELL_COUNT', $count);
446                 $this->xTemplate->assign('CLASS', "");
447                 if ( empty($widget_contents) ) $widget_contents = '&nbsp;';
448                 $this->xTemplate->assign('CELL', $widget_contents);
449                 $this->xTemplate->parse($xtemplateSection.".row.cell");
450                 } else {
451                     // This handles the edit and remove buttons and icon widget
452                         if( isset($list_field['widget_class']) && $list_field['widget_class'] == "SubPanelIcon") {
453                                 $count++;
454                                 $widget_contents = $layout_manager->widgetDisplay($list_field);
455                                 $this->xTemplate->assign('CELL_COUNT', $count);
456                                 $this->xTemplate->assign('CLASS', "");
457                                 if ( empty($widget_contents) ) $widget_contents = '&nbsp;';
458                                 $this->xTemplate->assign('CELL', $widget_contents);
459                                 $this->xTemplate->parse($xtemplateSection.".row.cell");
460                         } elseif (preg_match("/button/i", $list_field['name'])) {
461                         if ( '' != $_content = $layout_manager->widgetDisplay($list_field) )
462                         {
463                             $button_contents[] = $_content;
464                             unset($_content);
465                         }
466                         } else {
467                                 $count++;
468                                 $this->xTemplate->assign('CLASS', "");
469                                 $widget_contents = $layout_manager->widgetDisplay($list_field);
470                                 $this->xTemplate->assign('CELL_COUNT', $count);
471                                 if ( empty($widget_contents) ) $widget_contents = '&nbsp;';
472                                 $this->xTemplate->assign('CELL', $widget_contents);
473                                 $this->xTemplate->parse($xtemplateSection.".row.cell");
474                         }
475                 }
476
477             }
478         }
479
480
481         // Make sure we have at least one button before rendering a column for
482         // the action buttons in a list view. Relevant bugs: #51647 and #51640.
483         if(isset($button_contents[0])) {
484             // this is for inline buttons on listviews
485             // bug#51275: smarty widget to help provide the action menu functionality as it is currently sprinkled throughout the app with html
486             require_once('include/Smarty/plugins/function.sugar_action_menu.php');
487             $tempid = create_guid();
488             $button_contents[0] = "<div style='display: inline' id='$tempid'>".$button_contents[0]."</div>";
489             $action_button = smarty_function_sugar_action_menu(array(
490                 'id' => $tempid,
491                 'buttons' => $button_contents,
492                 'class' => 'clickMenu subpanel records fancymenu button',
493                 'flat' => false //assign flat value as false to display dropdown menu at any other preferences.
494             ), $this->xTemplate);
495             $this->xTemplate->assign('CLASS', "inlineButtons");
496             $this->xTemplate->assign('CELL_COUNT', ++$count);
497             //Bug#51275 for beta3 pre_script is not required any more
498             $this->xTemplate->assign('CELL', $action_button);
499             $this->xTemplate->parse($xtemplateSection.".row.cell");
500         }
501
502
503         $aItem->setupCustomFields($aItem->module_dir);
504         $aItem->custom_fields->populateAllXTPL($this->xTemplate, 'detail', $html_varName, $fields);
505
506         $count++;
507
508         $this->xTemplate->parse($xtemplateSection.".row");
509     }
510
511     $this->xTemplate->parse($xtemplateSection);
512 }
513
514 /**sets whether or not to display the xtemplate header and footer
515  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
516  * All Rights Reserved.
517  * Contributor(s): ______________________________________.
518 */
519 function setDisplayHeaderAndFooter($bool) {
520         $this->display_header_and_footer = $bool;
521 }
522
523 /**initializes ListView
524  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
525  * All Rights Reserved.
526  * Contributor(s): ______________________________________.
527 */
528  function ListView() {
529
530
531     if(!$this->initialized) {
532         global $sugar_config;
533         $this->records_per_page = $sugar_config['list_max_entries_per_page'] + 0;
534         $this->initialized = true;
535         global $app_strings, $currentModule;
536         $this->local_theme = SugarThemeRegistry::current()->__toString();
537         $this->local_app_strings =$app_strings;
538         $this->local_image_path = SugarThemeRegistry::current()->getImagePath();
539         $this->local_current_module = $currentModule;
540     }
541 }
542 /**sets how many records should be displayed per page in the list view
543  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
544  * All Rights Reserved.
545  * Contributor(s): ______________________________________.
546 */
547  function setRecordsPerPage($count) {
548     $this->records_per_page = $count;
549 }
550 /**sets the header title */
551  function setHeaderTitle($value) {
552     $this->header_title = $value;
553 }
554 /**sets the header text this is text that's appended to the header table and is usually used for the creation of buttons
555  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
556  * All Rights Reserved.
557  * Contributor(s): ______________________________________.
558 */
559  function setHeaderText($value) {
560     $this->header_text = $value;
561 }
562 /**sets the path for the XTemplate HTML file to be used this is only needed to be set if you are allowing ListView to create the XTemplate
563  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
564  * All Rights Reserved.
565  * Contributor(s): ______________________________________.
566 */
567  function setXTemplatePath($value) {
568     $this->xTemplatePath= $value;
569 }
570
571 /**this is a helper function for allowing ListView to create a new XTemplate it groups parameters that should be set into a single function
572  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
573  * All Rights Reserved.
574  * Contributor(s): ______________________________________.
575 */
576  function initNewXTemplate($XTemplatePath, $modString, $imagePath = null) {
577     $this->setXTemplatePath($XTemplatePath);
578     if(isset($modString))
579         $this->setModStrings($modString);
580     if(isset($imagePath))
581         $this->setImagePath($imagePath);
582 }
583
584
585 function getOrderBy($varName, $defaultOrderBy='', $force_sortorder='') {
586     $sortBy = $this->getSessionVariable($varName, "ORDER_BY") ;
587
588     $orderByDirection = $this->getSessionVariableName($varName, "order_by_direction");
589     $orderByColumn = $this->getSessionVariableName($varName, "ORDER_BY");
590     $lastEqualsSortBy = false;
591     $defaultOrder = false; //ascending
592
593     if(empty($sortBy)) {
594         $this->setUserVariable($varName, "ORDER_BY", $defaultOrderBy);
595         $sortBy = $defaultOrderBy;
596     } else {
597         $this->setUserVariable($varName, "ORDER_BY", $sortBy);
598     }
599
600     $desc = $this->getSessionVariable($varName, $sortBy."S");
601
602     if (empty($desc))
603         {
604             $desc = $defaultOrder;
605         }
606         $defaultOrder = $desc ? 'desc' : 'asc';
607         $orderByValue = $defaultOrder;
608         if (isset($_REQUEST[$orderByDirection]))
609         {
610             $possibleRequestOrderBy = $_REQUEST[$orderByDirection];
611             if ($possibleRequestOrderBy == 'asc' || $possibleRequestOrderBy == 'desc')
612             {
613                 $orderByValue = $possibleRequestOrderBy;
614             }
615         }
616
617         if (isset($_REQUEST[$orderByColumn]))
618         {
619             $last = $this->getSessionVariable($varName, "OBL");
620         }
621         if (!empty($last) && $last == $sortBy)
622         {
623             $lastEqualsSortBy = true;
624         } else
625         {
626             $orderByValue = $defaultOrder;
627             $this->setSessionVariable($varName, "OBL", $sortBy);
628         }
629         $desc = $orderByValue == 'desc';
630         $orderByDirectionValue = false;
631         $this->setSessionVariable($varName, $sortBy . "S", $desc);
632         if (!empty($sortBy))
633         {
634             if (empty($force_sortorder))
635             {
636                 if (substr_count(strtolower($sortBy), ' desc') == 0 && substr_count(strtolower($sortBy), ' asc') == 0)
637                 {
638                     if ($sortBy)
639                     {
640                         $orderByDirectionValue = $desc ? 'asc' : 'desc';
641                     }
642                     $this->query_orderby = $sortBy . ' ' . $orderByValue;
643                 }
644             } else
645             {
646                 $this->query_orderby = $sortBy . ' ' . $force_sortorder;
647             }
648             if (!isset($this->appendToBaseUrl))
649             {
650                 $this->appendToBaseUrl = array();
651             }
652             if ($orderByDirectionValue)
653             {
654                 $this->appendToBaseUrl[$orderByDirection] = $orderByDirectionValue;
655             }
656             $offsetVar = $this->getSessionVariableName($varName, "offset");
657             if (isset($_REQUEST[$offsetVar]))
658             {
659                 $this->appendToBaseUrl[$offsetVar] = $_REQUEST[$offsetVar];
660             }
661             //Just clear from url...
662             $this->appendToBaseUrl[$orderByColumn] = false;
663     }else {
664         $this->query_orderby = "";
665     }
666     $this->sortby = $sortBy;
667     return $this->query_orderby;
668
669 }
670
671
672 /**sets the parameters dealing with the db
673  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
674  * All Rights Reserved.
675  * Contributor(s): ______________________________________.
676 */
677  function setQuery($where, $limit, $orderBy, $varName, $allowOrderByOveride=true) {
678     $this->query_where = $where;
679     if($this->getSessionVariable("query", "where") != $where) {
680         $this->query_where_has_changed = true;
681         $this->setSessionVariable("query", "where", $where);
682     }
683
684     $this->query_limit = $limit;
685     if(!$allowOrderByOveride) {
686         $this->query_orderby = $orderBy;
687         return;
688     }
689     $this->getOrderBy($varName, $orderBy);
690
691     $this->setLocalSessionVariable($varName, "QUERY_WHERE", $where);
692
693     //SETTING ORDER_BY FOR USE IN DETAILVIEW
694     $this->setLocalSessionVariable($varName, "ORDER_BY_DETAIL", $this->query_orderby);
695 }
696
697 function displayArrow() {
698
699 }
700
701 /**sets the theme used only use if it is different from the global
702  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
703  * All Rights Reserved.
704  * Contributor(s): ______________________________________.
705 */
706  function setTheme($theme) {
707     $this->local_theme = $theme;
708     if(isset($this->xTemplate))$this->xTemplate->assign("THEME", $this->local_theme);
709 }
710
711 /**sets the AppStrings used only use if it is different from the global
712  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
713  * All Rights Reserved.
714  * Contributor(s): ______________________________________.
715 */
716  function setAppStrings($app_strings) {
717     unset($this->local_app_strings);
718     $this->local_app_strings = $app_strings;
719     if(isset($this->xTemplate))$this->xTemplate->assign("APP", $this->local_app_strings);
720 }
721
722 /**sets the ModStrings used
723  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
724  * All Rights Reserved.
725  * Contributor(s): ______________________________________.
726 */
727  function setModStrings($mod_strings) {
728     unset($this->local_module_strings);
729     $this->local_mod_strings = $mod_strings;
730     if(isset($this->xTemplate))$this->xTemplate->assign("MOD", $this->local_mod_strings);
731 }
732
733 /**sets the ImagePath used
734  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
735  * All Rights Reserved.
736  * Contributor(s): ______________________________________.
737 */
738  function setImagePath($image_path) {
739     $this->local_image_path = $image_path;
740     if(empty($this->local_image_path)) {
741         $this->local_image_path = SugarThemeRegistry::get($this->local_theme)->getImagePath();
742     }
743     if(isset($this->xTemplate))$this->xTemplate->assign("IMAGE_PATH", $this->local_image_path);
744 }
745
746 /**sets the currentModule only use if this is different from the global
747  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
748  * All Rights Reserved.
749  * Contributor(s): ______________________________________.
750 */
751  function setCurrentModule($currentModule) {
752     unset($this->local_current_module);
753     $this->local_current_module = $currentModule;
754     if(isset($this->xTemplate))$this->xTemplate->assign("MODULE_NAME", $this->local_current_module);
755 }
756
757 /**INTERNAL FUNCTION creates an XTemplate DO NOT CALL THIS THIS IS AN INTERNAL FUNCTION
758  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
759  * All Rights Reserved.
760  * Contributor(s): ______________________________________.
761 */
762  function createXTemplate() {
763     if(!isset($this->xTemplate)) {
764         if(isset($this->xTemplatePath)) {
765
766             $this->xTemplate = new XTemplate($this->xTemplatePath);
767             $this->xTemplate->assign("APP", $this->local_app_strings);
768             if(isset($this->local_mod_strings))$this->xTemplate->assign("MOD", $this->local_mod_strings);
769             $this->xTemplate->assign("THEME", $this->local_theme);
770             $this->xTemplate->assign("IMAGE_PATH", $this->local_image_path);
771             $this->xTemplate->assign("MODULE_NAME", $this->local_current_module);
772         } else {
773             $GLOBALS['log']->error("NO XTEMPLATEPATH DEFINED CANNOT CREATE XTEMPLATE");
774         }
775     }
776 }
777
778 /**sets the XTemplate telling ListView to use newXTemplate as its current XTemplate
779  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
780  * All Rights Reserved.
781  * Contributor(s): ______________________________________.
782 */
783  function setXTemplate($newXTemplate) {
784     $this->xTemplate = $newXTemplate;
785 }
786
787 /**returns the XTemplate
788  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
789  * All Rights Reserved.
790  * Contributor(s): ______________________________________.
791 */
792  function getXTemplate() {
793     return $this->xTemplate;
794 }
795
796 /**assigns a name value pair to the XTemplate
797  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
798  * All Rights Reserved.
799  * Contributor(s): ______________________________________.
800 */
801  function xTemplateAssign($name, $value) {
802
803         if(!isset($this->xTemplate)) {
804             $this->createXTemplate();
805         }
806         $this->xTemplate->assign($name, $value);
807
808 }
809
810 /**INTERNAL FUNCTION returns the offset first checking the query then checking the session if the where clause has changed from the last time it returns 0
811  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
812  * All Rights Reserved.
813  * Contributor(s): ______________________________________.
814 */
815  function getOffset($localVarName) {
816         if($this->query_where_has_changed || isset($GLOBALS['record_has_changed'])) {
817                 $this->setSessionVariable($localVarName,"offset", 0);
818         }
819         $offset = $this->getSessionVariable($localVarName,"offset");
820         if(isset($offset)) {
821                 return $offset;
822         }
823         return 0;
824 }
825
826 /**INTERNAL FUNCTION sets the offset in the session
827  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
828  * All Rights Reserved.
829  * Contributor(s): ______________________________________.
830 */
831  function setOffset($localVarName, $value) {
832         $this->setSessionVariable($localVarName, "offset", $value);
833 }
834
835 /**INTERNAL FUNCTION sets a session variable
836  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
837  * All Rights Reserved.
838  * Contributor(s): ______________________________________.
839 */
840  function setSessionVariable($localVarName,$varName, $value) {
841     $_SESSION[$this->local_current_module."_".$localVarName."_".$varName] = $value;
842 }
843
844 function setUserVariable($localVarName,$varName, $value) {
845         if($this->is_dynamic ||  $localVarName == 'CELL')return;
846         global $current_user;
847         $current_user->setPreference($this->local_current_module."_".$localVarName."_".$varName, $value);
848 }
849
850 /**INTERNAL FUNCTION returns a session variable first checking the query for it then checking the session
851  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
852  * All Rights Reserved.
853  * Contributor(s): ______________________________________.
854 */
855  function getSessionVariable($localVarName,$varName) {
856     //Set any variables pass in through request first
857     if(isset($_REQUEST[$this->getSessionVariableName($localVarName, $varName)])) {
858         $this->setSessionVariable($localVarName,$varName,$_REQUEST[$this->getSessionVariableName($localVarName, $varName)]);
859     }
860
861     if(isset($_SESSION[$this->getSessionVariableName($localVarName, $varName)])) {
862         return $_SESSION[$this->getSessionVariableName($localVarName, $varName)];
863     }
864     return "";
865 }
866
867 function getUserVariable($localVarName, $varName) {
868     global $current_user;
869     if($this->is_dynamic ||  $localVarName == 'CELL')return;
870     if(isset($_REQUEST[$this->getSessionVariableName($localVarName, $varName)])) {
871
872             $this->setUserVariable($localVarName,$varName,$_REQUEST[$this->getSessionVariableName($localVarName, $varName)]);
873     }
874     return $current_user->getPreference($this->getSessionVariableName($localVarName, $varName));
875 }
876
877
878     /**
879      * helper method to determine sort order by priority of source
880      * 1. explicit in request object
881      * 2. in session variable
882      * 3. subpaneldefs metadata
883      * 4. default 'asc'
884      * @param array $sortOrderList - contains options
885      * @return string 'asc' | 'desc'
886      */
887     function calculateSortOrder($sortOrderList)
888     {
889         $priority_map = array(
890           'request',
891           'session',
892           'subpaneldefs',
893           'default',
894         );
895
896         foreach($priority_map as $p) {
897             if (key_exists($p, $sortOrderList)) {
898                 $order = strtolower($sortOrderList[$p]);
899                 if (in_array($order, array('asc', 'desc'))) {
900                     return $order;
901                 }
902             }
903         }
904         return 'asc';
905     }
906
907
908     /**
909
910     * @return void
911     * @param unknown $localVarName
912     * @param unknown $varName
913     * @desc INTERNAL FUNCTION returns the session/query variable name
914     * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
915     * All Rights Reserved.
916     * Contributor(s): ______________________________________..
917     */
918     function getSessionVariableName($localVarName,$varName) {
919         return $this->local_current_module."_".$localVarName."_".$varName;
920     }
921
922     /**
923
924     * @return void
925     * @param unknown $seed
926     * @param unknown $xTemplateSection
927     * @param unknown $html_varName
928     * @desc INTERNAL FUNCTION Handles List Views using seeds that extend SugarBean
929         $XTemplateSection is the section in the XTemplate file that should be parsed usually main
930         $html_VarName is the variable name used in the XTemplateFile e.g. TASK
931         $seed is a seed that extends SugarBean
932         * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
933         * All Rights Reserved..
934         * Contributor(s): ______________________________________..
935     */
936     function processSugarBean($xtemplateSection, $html_varName, $seed) {
937         global $list_view_row_count;
938
939         $current_offset = $this->getOffset($html_varName);
940         $response = array();
941
942         //ADDING VCR CONTROL
943         SugarVCR::erase($seed->module_dir);
944         $params = array();
945         //$filter = array('id', 'full_name');
946         $filter=array();
947         $ret_array = $seed->create_new_list_query($this->query_orderby, $this->query_where, $filter, $params, 0, '', true, $seed, true);
948         if(!is_array($params)) $params = array();
949         if(!isset($params['custom_select'])) $params['custom_select'] = '';
950         if(!isset($params['custom_from'])) $params['custom_from'] = '';
951         if(!isset($params['custom_where'])) $params['custom_where'] = '';
952         if(!isset($params['custom_order_by'])) $params['custom_order_by'] = '';
953         $main_query = $ret_array['select'] . $params['custom_select'] . $ret_array['from'] . $params['custom_from'] . $ret_array['where'] . $params['custom_where'] . $ret_array['order_by'] . $params['custom_order_by'];
954         SugarVCR::store($seed->module_dir,  $main_query);
955         //ADDING VCR CONTROL
956
957         if(empty($this->related_field_name)) {
958             $response = $seed->get_list($this->query_orderby, $this->query_where, $current_offset, $this->query_limit);
959         } else {
960             $related_field_name = $this->related_field_name;
961             $response = $seed->get_related_list($this->child_focus,$related_field_name, $this->query_orderby,
962             $this->query_where, $current_offset, $this->query_limit);
963         }
964
965         $list = $response['list'];
966         $row_count = $response['row_count'];
967         $next_offset = $response['next_offset'];
968         $previous_offset = $response['previous_offset'];
969
970         if(!empty($response['current_offset'])) {
971             $current_offset = $response['current_offset'];
972         }
973
974         $list_view_row_count = $row_count;
975         $this->processListNavigation($xtemplateSection,$html_varName, $current_offset, $next_offset, $previous_offset, $row_count, null, null, empty($seed->column_fields) ? null : count($seed->column_fields));
976
977         return $list;
978     }
979
980
981
982     function processUnionBeans($sugarbean, $subpanel_def, $html_var = 'CELL') {
983
984                 $last_detailview_record = $this->getSessionVariable("detailview", "record");
985                 if(!empty($last_detailview_record) && $last_detailview_record != $sugarbean->id){
986                         $GLOBALS['record_has_changed'] = true;
987                 }
988                 $this->setSessionVariable("detailview", "record", $sugarbean->id);
989
990                 $current_offset = $this->getOffset($html_var);
991                 $module = isset($_REQUEST['module']) ? $_REQUEST['module'] : '';
992                 $response = array();
993
994         // choose sort order
995         $sort_order = array();
996         $sort_order['default'] = 'asc';
997
998         // explicit request parameter gets priority over all
999         $sort_order['request'] = isset($_REQUEST['sort_order']) ? $_REQUEST['sort_order'] : null;
1000
1001         // see if the session data has a sort order
1002         if (isset($_SESSION['last_sub' . $this->subpanel_module . '_order']))
1003         {
1004             $sort_order['session'] = $_SESSION['last_sub' . $this->subpanel_module . '_order'];
1005
1006             // We swap the order when the request contains an offset (indicating a column sort issued);
1007             // otherwise we do not sort.  If we don't make this check, then the subpanel listview will
1008             // swap ordering each time a new record is entered via quick create forms
1009             if (isset($_REQUEST[$module . '_' . $html_var . '_offset']))
1010             {
1011                 $sort_order['session'] = $sort_order['session'] == 'asc' ? 'desc' : 'asc';
1012             }
1013         }
1014         else
1015         {
1016             $sort_order['session'] = null;
1017         }
1018
1019         // does the metadata have a default sort order?
1020         $sort_order['subpaneldefs'] = isset($subpanel_def->_instance_properties['sort_order']) ?
1021             $subpanel_def->_instance_properties['sort_order'] : null;
1022
1023         $this->sort_order = $this->calculateSortOrder($sort_order);
1024
1025
1026         if (isset($subpanel_def->_instance_properties['sort_by'])) {
1027             $this->query_orderby = $subpanel_def->_instance_properties['sort_by'];
1028         } else {
1029             $this->query_orderby = 'id';
1030         }
1031
1032         $this->getOrderBy($html_var,$this->query_orderby, $this->sort_order);
1033
1034         $_SESSION['last_sub' .$this->subpanel_module. '_order'] = $this->sort_order;
1035         $_SESSION['last_sub' .$this->subpanel_module. '_url'] = $this->getBaseURL($html_var);
1036
1037                 // Bug 8139 - Correct Subpanel sorting on 'name', when subpanel sorting default is 'last_name, first_name'
1038                 if (($this->sortby == 'name' || $this->sortby == 'last_name') &&
1039                         str_replace(' ', '', trim($subpanel_def->_instance_properties['sort_by'])) == 'last_name,first_name') {
1040                         $this->sortby = 'last_name '.$this->sort_order.', first_name ';
1041                 }
1042
1043         if(!empty($this->response)){
1044             $response =& $this->response;
1045             echo 'cached';
1046         }else{
1047             $response = SugarBean::get_union_related_list($sugarbean,$this->sortby, $this->sort_order, $this->query_where, $current_offset, -1,-1,$this->query_limit,$subpanel_def);
1048             $this->response =& $response;
1049         }
1050         $list = $response['list'];
1051         $row_count = $response['row_count'];
1052         $next_offset = $response['next_offset'];
1053         $previous_offset = $response['previous_offset'];
1054         if(!empty($response['current_offset']))$current_offset = $response['current_offset'];
1055         global $list_view_row_count;
1056         $list_view_row_count = $row_count;
1057         $this->processListNavigation('dyn_list_view', $html_var, $current_offset, $next_offset, $previous_offset, $row_count, $sugarbean,$subpanel_def);
1058
1059         return array('list'=>$list, 'parent_data'=>$response['parent_data'], 'query'=>$response['query']);
1060     }
1061
1062     function getBaseURL($html_varName) {
1063         static $cache = array();
1064
1065         if(!empty($cache[$html_varName]))return $cache[$html_varName];
1066         $blockVariables = array('mass', 'uid', 'massupdate', 'delete', 'merge', 'selectCount','current_query_by_page');
1067         if(!empty($this->base_URL)) {
1068             return $this->base_URL;
1069         }
1070
1071             $baseurl = $_SERVER['PHP_SELF'];
1072             if(empty($baseurl)) {
1073                 $baseurl = 'index.php';
1074             }
1075
1076             /*fixes an issue with deletes when doing a search*/
1077             foreach(array_merge($_GET, $_POST) as $name=>$value) {
1078                 //echo ("$name = $value <br/>");
1079                 if(!empty($value) && $name != 'sort_order' //&& $name != ListView::getSessionVariableName($html_varName,"ORDER_BY")
1080                         && $name != ListView::getSessionVariableName($html_varName,"offset")
1081                         /*&& substr_count($name, "ORDER_BY")==0*/ && !in_array($name, $blockVariables))
1082                 {
1083                     if(is_array($value)) {
1084                         foreach($value as $valuename=>$valuevalue) {
1085                             if(substr_count($baseurl, '?') > 0)
1086                                 $baseurl        .= "&{$name}[]=".$valuevalue;
1087                             else
1088                                 $baseurl        .= "?{$name}[]=".$valuevalue;
1089                         }
1090                     } else {
1091                         $value = urlencode($value);
1092                         if(substr_count($baseurl, '?') > 0) {
1093                             $baseurl    .= "&$name=$value";
1094                         } else {
1095                             $baseurl    .= "?$name=$value";
1096                         }
1097                     }
1098                 }
1099             }
1100
1101
1102             if($_SERVER['REQUEST_METHOD'] == 'POST') {
1103                 // at this point it is possible that the above foreach already executed resulting in double ?'s in the url
1104                 if(substr_count($baseurl, '?') == 0) {
1105                     $baseurl .= '?';
1106                 }
1107                 if(isset($_REQUEST['action'])) $baseurl.= '&action='.$_REQUEST['action'];
1108                 if(isset($_REQUEST['record'])) $baseurl .= '&record='.$_REQUEST['record'];
1109                 if(isset($_REQUEST['module'])) $baseurl .= '&module='.$_REQUEST['module'];
1110             }
1111
1112             $baseurl .= "&".ListView::getSessionVariableName($html_varName,"offset")."=";
1113             $cache[$html_varName] = $baseurl;
1114             return $baseurl;
1115     }
1116     /**
1117     * @return void
1118     * @param unknown $data
1119     * @param unknown $xTemplateSection
1120     * @param unknown $html_varName
1121     * @desc INTERNAL FUNCTION process the List Navigation
1122     * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1123     * All Rights Reserved.
1124     * Contributor(s): ______________________________________..
1125     */
1126     function processListNavigation($xtemplateSection, $html_varName, $current_offset, $next_offset, $previous_offset, $row_count, $sugarbean=null, $subpanel_def=null, $col_count = 20) {
1127
1128         global $export_module;
1129         global $sugar_config;
1130         global $current_user;
1131         global $currentModule;
1132         global $app_strings;
1133
1134         $start_record = $current_offset + 1;
1135
1136         if(!is_numeric($col_count))
1137             $col_count = 20;
1138
1139         if($row_count == 0)
1140             $start_record = 0;
1141
1142         $end_record = $start_record + $this->records_per_page;
1143         // back up the the last page.
1144         if($end_record > $row_count+1) {
1145             $end_record = $row_count+1;
1146         }
1147         // Determine the start location of the last page
1148         if($row_count == 0)
1149             $number_pages = 0;
1150         else
1151             $number_pages = floor(($row_count - 1) / $this->records_per_page);
1152
1153         $last_offset = $number_pages * $this->records_per_page;
1154
1155         if(empty($this->query_limit)  || $this->query_limit > $this->records_per_page) {
1156             $this->base_URL = $this->getBaseURL($html_varName);
1157             $dynamic_url = '';
1158
1159             if($this->is_dynamic) {
1160                 $dynamic_url .='&'. $this->getSessionVariableName($html_varName,'ORDER_BY') . '='. $this->getSessionVariable($html_varName,'ORDER_BY').'&sort_order='.$this->sort_order.'&to_pdf=true&action=SubPanelViewer&subpanel=' . $this->subpanel_module;
1161             }
1162
1163             $current_URL = htmlentities($this->base_URL.$current_offset.$dynamic_url);
1164             $start_URL = htmlentities($this->base_URL."0".$dynamic_url);
1165             $previous_URL  = htmlentities($this->base_URL.$previous_offset.$dynamic_url);
1166             $next_URL  = htmlentities($this->base_URL.$next_offset.$dynamic_url);
1167             $end_URL  = htmlentities($this->base_URL.'end'.$dynamic_url);
1168
1169             if(!empty($this->start_link_wrapper)) {
1170                 $current_URL = $this->start_link_wrapper.$current_URL.$this->end_link_wrapper;
1171                 $start_URL = $this->start_link_wrapper.$start_URL.$this->end_link_wrapper;
1172                 $previous_URL = $this->start_link_wrapper.$previous_URL.$this->end_link_wrapper;
1173                 $next_URL = $this->start_link_wrapper.$next_URL.$this->end_link_wrapper;
1174                 $end_URL = $this->start_link_wrapper.$end_URL.$this->end_link_wrapper;
1175             }
1176
1177             $moduleString = "{$currentModule}_{$html_varName}_offset";
1178             $moduleStringOrder = "{$currentModule}_{$html_varName}_ORDER_BY";
1179             if($this->shouldProcess && !$this->multi_select_popup) {
1180                 // check the checkboxes onload
1181                 echo "<script>YAHOO.util.Event.addListener(window, \"load\", sListView.check_boxes);</script>\n";
1182
1183                 $massUpdateRun = isset($_REQUEST['massupdate']) && $_REQUEST['massupdate'] == 'true';
1184                 $uids = empty($_REQUEST['uid']) || $massUpdateRun ? '' : $_REQUEST['uid'];
1185                 $select_entire_list = ($massUpdateRun) ? 0 : (isset($_POST['select_entire_list']) ? $_POST['select_entire_list'] : (isset($_REQUEST['select_entire_list']) ? $_REQUEST['select_entire_list'] : 0));
1186
1187                 echo "<textarea style='display: none' name='uid'>{$uids}</textarea>\n" .
1188                     "<input type='hidden' name='select_entire_list' value='{$select_entire_list}'>\n".
1189                     "<input type='hidden' name='{$moduleString}' value='0'>\n".
1190                     "<input type='hidden' name='{$moduleStringOrder}' value='0'>\n";
1191
1192             }
1193
1194
1195             $GLOBALS['log']->debug("Offsets: (start, previous, next, last)(0, $previous_offset, $next_offset, $last_offset)");
1196
1197             if(0 == $current_offset) {
1198                 $start_link = "<button type='button' name='listViewStartButton' title='{$this->local_app_strings['LNK_LIST_START']}' class='button' disabled>".SugarThemeRegistry::current()->getImage("start_off","aborder='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_START'])."</button>";
1199                 $previous_link = "<button type='button' name='listViewPrevButton' title='{$this->local_app_strings['LNK_LIST_PREVIOUS']}' class='button' disabled>".SugarThemeRegistry::current()->getImage("previous_off","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_PREVIOUS'])."</button>";
1200             } else {
1201                 if($this->multi_select_popup) {// nav links for multiselect popup, submit form to save checks.
1202                     $start_link = "<button type='button' class='button' name='listViewStartButton' title='{$this->local_app_strings['LNK_LIST_START']}' onClick='javascript:save_checks(0, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("start","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_START'])."</button>";
1203                     $previous_link = "<button type='button' class='button' name='listViewPrevButton' title='{$this->local_app_strings['LNK_LIST_PREVIOUS']}' onClick='javascript:save_checks($previous_offset, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("previous","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_PREVIOUS'])."</button>";
1204                 } elseif($this->shouldProcess) {
1205                     $start_link = "<button type='button' class='button' name='listViewStartButton' title='{$this->local_app_strings['LNK_LIST_START']}' onClick='location.href=\"$start_URL\"; sListView.save_checks(0, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("start","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_START'])."</button>";
1206                     $previous_link = "<button type='button' class='button' name='listViewPrevButton' title='{$this->local_app_strings['LNK_LIST_PREVIOUS']}' onClick='location.href=\"$previous_URL\"; sListView.save_checks($previous_offset, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("previous","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_PREVIOUS'])."</button>";
1207                 } else {
1208                     $onClick = '';
1209                     if(0 != preg_match('/javascript.*/', $start_URL)){
1210                         $onClick = "\"$start_URL;\"";
1211                     }else{
1212                         $onClick ="'location.href=\"$start_URL\";'";
1213                     }
1214                     $start_link = "<button type='button' class='button' name='listViewStartButton' title='{$this->local_app_strings['LNK_LIST_START']}' onClick=".$onClick.">".SugarThemeRegistry::current()->getImage("start","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_START'])."</button>";
1215
1216                     $onClick = '';
1217                     if(0 != preg_match('/javascript.*/', $previous_URL)){
1218                         $onClick = "\"$previous_URL;\"";
1219                     }else{
1220                         $onClick = "'location.href=\"$previous_URL\";'";
1221                     }
1222                     $previous_link = "<button type='button' class='button' name='listViewPrevButton' title='{$this->local_app_strings['LNK_LIST_PREVIOUS']}' onClick=".$onClick.">".SugarThemeRegistry::current()->getImage("previous","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_PREVIOUS'])."</button>";
1223                 }
1224             }
1225
1226             if($last_offset <= $current_offset) {
1227                 $end_link = "<button type='button' name='listViewEndButton' title='{$this->local_app_strings['LNK_LIST_END']}' class='button' disabled>".SugarThemeRegistry::current()->getImage("end_off","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_END'])."</button>";
1228                 $next_link = "<button type='button' name='listViewNextButton' title='{$this->local_app_strings['LNK_LIST_NEXT']}' class='button' disabled>".SugarThemeRegistry::current()->getImage("next_off","aborder='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_NEXT'])."</button>";
1229             } else {
1230                 if($this->multi_select_popup) { // nav links for multiselect popup, submit form to save checks.
1231                     $end_link = "<button type='button' name='listViewEndButton' class='button' title='{$this->local_app_strings['LNK_LIST_END']}' onClick='javascript:save_checks($last_offset, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("end","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_END'])."</button>";
1232                     if(!empty($sugar_config['disable_count_query'])) {
1233                         $end_link = '';
1234                     }
1235                     $next_link = "<button type='button' name='listViewNextButton' title='{$this->local_app_strings['LNK_LIST_NEXT']}' class='button' onClick='javascript:save_checks($next_offset, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("next","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_NEXT'])."</button>";
1236                 } elseif($this->shouldProcess) {
1237                     $end_link = "<button type='button' name='listViewEndButton' class='button' title='{$this->local_app_strings['LNK_LIST_END']}' onClick='location.href=\"$end_URL\"; sListView.save_checks(\"end\", \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("end","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_END'])."</button>";
1238                     $next_link = "<button type='button' name='listViewNextButton' class='button' title='{$this->local_app_strings['LNK_LIST_NEXT']}' onClick='location.href=\"$next_URL\"; sListView.save_checks($next_offset, \"{$moduleString}\");'>".SugarThemeRegistry::current()->getImage("next","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_NEXT'])."</button>";
1239                 } else {
1240                     $onClick = '';
1241                     if(0 != preg_match('/javascript.*/', $next_URL)){
1242                         $onClick = "\"$next_URL;\"";
1243                     }else{
1244                         $onClick ="'location.href=\"$next_URL\";'";
1245                     }
1246                     $next_link = "<button type='button' name='listViewNextButton' class='button' title='{$this->local_app_strings['LNK_LIST_NEXT']}' onClick=".$onClick.">".SugarThemeRegistry::current()->getImage("next","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_NEXT'])."</button>";
1247
1248                     $onClick = '';
1249                     if(0 != preg_match('/javascript.*/', $end_URL)){
1250                         $onClick = "\"$end_URL;\"";
1251                     }else{
1252                         $onClick = "'location.href=\"$end_URL\";'";
1253                     }
1254                     $end_link = "<button type='button' name='listViewEndButton' class='button' title='{$this->local_app_strings['LNK_LIST_END']}' onClick=".$onClick.">".SugarThemeRegistry::current()->getImage("end","border='0' align='absmiddle'",null,null,'.gif',$this->local_app_strings['LNK_LIST_END'])."</button>";
1255
1256                 }
1257             }
1258
1259             $GLOBALS['log']->info("Offset (next, current, prev)($next_offset, $current_offset, $previous_offset)");
1260             $GLOBALS['log']->info("Start/end records ($start_record, $end_record)");
1261
1262             $end_record = $end_record-1;
1263
1264 $script_href = "<a style=\'width: 150px\' name=\"thispage\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'if (document.MassUpdate.select_entire_list.value==1){document.MassUpdate.select_entire_list.value=0;sListView.check_all(document.MassUpdate, \"mass[]\", true, $this->records_per_page)}else {sListView.check_all(document.MassUpdate, \"mass[]\", true)};\' href=\'#\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_CURRENT']}&nbsp;&#x28;{$this->records_per_page}&#x29;&#x200E;</a>"
1265  . "<a style=\'width: 150px\' name=\"selectall\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'sListView.check_entire_list(document.MassUpdate, \"mass[]\",true,{$row_count});\' href=\'#\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_ENTIRE']}&nbsp;&#x28;{$row_count}&#x29;&#x200E;</a>"
1266  . "<a style=\'width: 150px\' name=\"deselect\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'sListView.clear_all(document.MassUpdate, \"mass[]\", false);\' href=\'#\'>{$this->local_app_strings['LBL_LISTVIEW_NONE']}</a>";
1267
1268 $close_inline_img = SugarThemeRegistry::current()->getImage('close_inline', 'border=0', null, null, ".gif", $app_strings['LBL_CLOSEINLINE']);
1269
1270             echo "<script>
1271                 function select_dialog() {
1272                         var \$dialog = \$('<div></div>')
1273                                         .html('<a style=\'width: 150px\' name=\"thispage\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'if (document.MassUpdate.select_entire_list.value==1){document.MassUpdate.select_entire_list.value=0;sListView.check_all(document.MassUpdate, \"mass[]\", true, $this->records_per_page)}else {sListView.check_all(document.MassUpdate, \"mass[]\", true)};\' href=\'javascript:void(0)\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_CURRENT']}&nbsp;&#x28;{$this->records_per_page}&#x29;&#x200E;</a>"
1274                 . "<a style=\'width: 150px\' name=\"selectall\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'sListView.check_entire_list(document.MassUpdate, \"mass[]\",true,{$row_count});\' href=\'javascript:void(0)\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_ENTIRE']}&nbsp;&#x28;{$row_count}&#x29;&#x200E;</a>"
1275                 . "<a style=\'width: 150px\' name=\"deselect\" class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'sListView.clear_all(document.MassUpdate, \"mass[]\", false);\' href=\'javascript:void(0)\'>{$this->local_app_strings['LBL_LISTVIEW_NONE']}</a>')
1276                                         .dialog({
1277                                                 autoOpen: false,
1278                                                 width: 150
1279                                         });
1280                                         \$dialog.dialog('open');
1281
1282                 }
1283                 </script>";
1284
1285             if($this->show_select_menu)
1286             {
1287                 $total_label = "";
1288                 $total = $row_count;
1289                 $pageTotal = ($row_count > 0) ? $end_record - $start_record + 1 : 0;
1290                 if (!empty($GLOBALS['sugar_config']['disable_count_query']) && $GLOBALS['sugar_config']['disable_count_query'] === true && $total > $pageTotal) {
1291                     $this->show_plus = true;
1292                     $total =  $pageTotal;
1293                     $total_label = $total.'+';
1294                 } else {
1295                     $this->show_plus = false;
1296                     $total_label = $total;
1297                 }
1298                 echo "<input type='hidden' name='show_plus' value='{$this->show_plus}'>\n";
1299
1300                 //Bug#52931: Replace with actionMenu
1301                 //$select_link = "<a id='select_link' onclick='return select_dialog();' href=\"javascript:void(0)\">".$this->local_app_strings['LBL_LINK_SELECT']."&nbsp;".SugarThemeRegistry::current()->getImage('MoreDetail', 'border=0', 11, 7, '.png', $app_strings['LBL_MOREDETAIL'])."</a>";
1302                 $menuItems = array(
1303                     "<input title=\"".$app_strings['LBL_SELECT_ALL_TITLE']."\" type='checkbox' class='checkbox massall' name='massall' id='massall' value='' onclick='sListView.check_all(document.MassUpdate, \"mass[]\", this.checked);' /><a href='javascript: void(0);'></a>",
1304                     "<a  name='thispage' id='button_select_this_page' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' onclick='if (document.MassUpdate.select_entire_list.value==1){document.MassUpdate.select_entire_list.value=0;sListView.check_all(document.MassUpdate, \"mass[]\", true, $pageTotal)}else {sListView.check_all(document.MassUpdate, \"mass[]\", true)};' href='#'>{$app_strings['LBL_LISTVIEW_OPTION_CURRENT']}&nbsp;&#x28;{$pageTotal}&#x29;&#x200E;</a>",
1305                     "<a  name='selectall' id='button_select_all' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' onclick='sListView.check_entire_list(document.MassUpdate, \"mass[]\",true,{$total});' href='#'>{$app_strings['LBL_LISTVIEW_OPTION_ENTIRE']}&nbsp;&#x28;{$total_label}&#x29;&#x200E;</a>",
1306                     "<a name='deselect' id='button_deselect' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' onclick='sListView.clear_all(document.MassUpdate, \"mass[]\", false);' href='#'>{$app_strings['LBL_LISTVIEW_NONE']}</a>",
1307                 );
1308                 require_once('include/Smarty/plugins/function.sugar_action_menu.php');
1309                 $select_link = smarty_function_sugar_action_menu(array(
1310                     'class' => 'clickMenu selectmenu',
1311                     'id' => 'selectLink',
1312                     'buttons' => $menuItems,
1313                     'flat' => false,
1314                 ),$this->xTemplate);
1315
1316             } else {
1317                 $select_link = "&nbsp;";
1318             }
1319
1320             $export_link = '<input class="button" type="button" value="'.$this->local_app_strings['LBL_EXPORT'].'" ' .
1321                     'onclick="return sListView.send_form(true, \''.$_REQUEST['module'].'\', \'index.php?entryPoint=export\',\''.$this->local_app_strings['LBL_LISTVIEW_NO_SELECTED'].'\')">';
1322
1323             if($this->show_delete_button) {
1324                 $delete_link = '<input class="button" type="button" id="delete_button" name="Delete" value="'.$this->local_app_strings['LBL_DELETE_BUTTON_LABEL'].'" onclick="return sListView.send_mass_update(\'selected\',\''.$this->local_app_strings['LBL_LISTVIEW_NO_SELECTED'].'\', 1)">';
1325             } else {
1326                 $delete_link = '&nbsp;';
1327             }
1328
1329             $admin = new Administration();
1330             $admin->retrieveSettings('system');
1331
1332             $user_merge = $current_user->getPreference('mailmerge_on');
1333             if($user_merge == 'on' && isset($admin->settings['system_mailmerge_on']) && $admin->settings['system_mailmerge_on']) {
1334                 echo "<script>
1335                 function mailmerge_dialog(el) {
1336                         var \$dialog = \$('<div></div>')
1337                                         .html('<a style=\'width: 150px\' class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' onclick=\'return sListView.send_form(true, \"MailMerge\", \"index.php\", \"{$this->local_app_strings['LBL_LISTVIEW_NO_SELECTED']}\")\' href=\'javascript:void(0)\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_SELECTED']}</a>"
1338                         . "<a style=\'width: 150px\' class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' href=\'index.php?action=index&module=MailMerge\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_CURRENT']}</a>"
1339                         . "<a style=\'width: 150px\' class=\'menuItem\' onmouseover=\'hiliteItem(this,\"yes\");\' onmouseout=\'unhiliteItem(this);\' href=\'index.php?action=index&module=MailMerge&entire=true\'>{$this->local_app_strings['LBL_LISTVIEW_OPTION_ENTIRE']}</a>')
1340                                         .dialog({
1341                                                 autoOpen: false,
1342                                                 title: '". $this->local_app_strings['LBL_MAILMERGE']."',
1343                                                 width: 150,
1344                                                 position: {
1345                                                     my: myPos,
1346                                                     at: atPos,
1347                                                     of: \$(el)
1348                                                 }
1349                                         });
1350
1351                 }
1352             </script>";
1353                 $merge_link = "&nbsp;|&nbsp;<a id='mailmerge_link' onclick='return mailmerge_dialog(this)'; href=\"javascript:void(0)\">".$this->local_app_strings['LBL_MAILMERGE']."</a>";
1354             } else {
1355                 $merge_link = "&nbsp;";
1356             }
1357
1358             $selected_objects_span = "&nbsp;|&nbsp;{$this->local_app_strings['LBL_LISTVIEW_SELECTED_OBJECTS']}<input  style='border: 0px; background: transparent; font-size: inherit; color: inherit' type='text' readonly name='selectCount[]' value='" . ((isset($_POST['mass'])) ? count($_POST['mass']): 0) . "' />";
1359
1360             if($_REQUEST['module'] == 'Home' || $this->local_current_module == 'Import'
1361                 || $this->show_export_button == false
1362                 || (!empty($sugar_config['disable_export']))
1363                 || (!empty($sugar_config['admin_export_only'])
1364                 && !(
1365                         is_admin($current_user)
1366                         || (ACLController::moduleSupportsACL($_REQUEST['module'])
1367                             && ACLAction::getUserAccessLevel($current_user->id,$_REQUEST['module'], 'access') == ACL_ALLOW_ENABLED
1368                             && (ACLAction::getUserAccessLevel($current_user->id, $_REQUEST['module'], 'admin') == ACL_ALLOW_ADMIN ||
1369                                 ACLAction::getUserAccessLevel($current_user->id, $_REQUEST['module'], 'admin') == ACL_ALLOW_ADMIN_DEV)))))
1370             {
1371                 if ($_REQUEST['module'] != 'InboundEmail' && $_REQUEST['module'] != 'EmailMan' && $_REQUEST['module'] != 'iFrames') {
1372                     $selected_objects_span = '';
1373                 }
1374                 $export_link = "&nbsp;";
1375                 $merge_link = "&nbsp;";
1376             } elseif($_REQUEST['module'] != "Accounts" && $_REQUEST['module'] != "Cases" && $_REQUEST['module'] != "Contacts" && $_REQUEST['module'] != "Leads" && $_REQUEST['module'] != "Opportunities") {
1377                 $merge_link = "&nbsp;";
1378             }
1379
1380             if($this->show_paging == true) {
1381                 if(!empty($sugar_config['disable_count_query'])) {
1382                     if($row_count > $end_record) {
1383                         $row_count .= '+';
1384                     }
1385                 }
1386
1387                 $html_text = '';
1388                 $html_text .= "<tr class='pagination' role='presentation'>\n";
1389                 $html_text .= "<td COLSPAN=\"$col_count\" align=\"right\">\n";
1390                 //$html_text .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td align=\"left\"  >$export_link$merge_link$selected_objects_span</td>\n";
1391                 //$html_text .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td align=\"left\"  >";
1392                 if ($subpanel_def != null) {
1393                     include_once('include/SubPanel/SubPanelTiles.php');
1394                     $subpanelTiles = new SubPanelTiles($sugarbean);
1395                     $html_text .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td align=\"left\"  >";
1396
1397                     //attempt to get the query to recreate this subpanel
1398                     if(!empty($this->response)){
1399                         $response =& $this->response;
1400                     }else{
1401                         $response = SugarBean::get_union_related_list($sugarbean,$this->sortby, $this->sort_order, $this->query_where, $current_offset, -1,-1,$this->query_limit,$subpanel_def);
1402                         $this->response = $response;
1403                     }
1404                     //if query is present, then pass it in as parameter
1405                     if (isset($response['query']) && !empty($response['query'])){
1406                         $html_text .= $subpanelTiles->get_buttons($subpanel_def, $response['query']);
1407                     }else{
1408                         $html_text .= $subpanelTiles->get_buttons($subpanel_def);
1409                     }
1410                 }
1411                 else {
1412                     $html_text .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td align=\"left\"  nowrap>$select_link&nbsp;$export_link&nbsp;$delete_link&nbsp;$selected_objects_span";
1413                 }
1414                 $html_text .= "</td>\n<td nowrap align=\"right\">".$start_link."&nbsp;&nbsp;".$previous_link."&nbsp;&nbsp;<span class='pageNumbers'>(".$start_record." - ".$end_record." ".$this->local_app_strings['LBL_LIST_OF']." ".$row_count.")</span>&nbsp;&nbsp;".$next_link."&nbsp;&nbsp;".$end_link."</td></tr></table>\n";
1415                 $html_text .= "</td>\n";
1416                 $html_text .= "</tr>\n";
1417                 $this->xTemplate->assign("PAGINATION",$html_text);
1418             }
1419
1420             //C.L. - Fix for 23461
1421             if(empty($_REQUEST['action']) || $_REQUEST['action'] != 'Popup') {
1422                 $_SESSION['export_where'] = $this->query_where;
1423             }
1424             $this->xTemplate->parse($xtemplateSection.".list_nav_row");
1425         }
1426     } // end processListNavigation
1427
1428     function processOrderBy($html_varName) {
1429
1430         if(!isset($this->base_URL)) {
1431             $this->base_URL = $_SERVER['PHP_SELF'];
1432
1433             if(isset($_SERVER['QUERY_STRING'])) {
1434                 $this->base_URL = preg_replace("/\&".$this->getSessionVariableName($html_varName,"ORDER_BY")."=[0-9a-zA-Z\_\.]*/","",$this->base_URL .'?'.$_SERVER['QUERY_STRING']);
1435                 $this->base_URL = preg_replace("/\&".$this->getSessionVariableName($html_varName,"offset")."=[0-9]*/","",$this->base_URL);
1436             }
1437             if($_SERVER['REQUEST_METHOD'] == 'POST') {
1438                 $this->base_URL .= '?';
1439                 if(isset($_REQUEST['action'])) $this->base_URL .= '&action='.$_REQUEST['action'];
1440                 if(isset($_REQUEST['record'])) $this->base_URL .= '&record='.$_REQUEST['record'];
1441                 if(isset($_REQUEST['module'])) $this->base_URL .= '&module='.$_REQUEST['module'];
1442             }
1443             $this->base_URL .= "&".$this->getSessionVariableName($html_varName,"offset")."=";
1444         }
1445
1446         if($this->is_dynamic) {
1447             $this->base_URL.='&to_pdf=true&action=SubPanelViewer&subpanel=' . $this->source_module;
1448         }
1449
1450         //bug43465 start
1451         if (isset($this->appendToBaseUrl) && is_array($this->appendToBaseUrl))
1452         {
1453             foreach ($this->appendToBaseUrl as $key => $value)
1454             {
1455                 $fullRequestString = $key . '=' . $value;
1456
1457                 if ($this->base_URL == "/index.php")
1458                 {
1459                     $this->base_URL .= "?";
1460                 } else
1461                 {
1462                     if ($fullRequestString == substr($this->baseURL, '-' . strlen($fullRequestString)))
1463                     {
1464                         $this->base_URL = preg_replace("/&" . $key . "\=.*/", "", $this->base_URL);
1465                     } else
1466                     {
1467                         $this->base_URL = preg_replace("/&" . $key . "\=.*?&/", "&", $this->base_URL);
1468                     }
1469                     $this->base_URL .= "&";
1470                 }
1471                 if (!empty($value))
1472                 {
1473                     $this->base_URL .= "{$key}={$value}";
1474                 }
1475             }
1476         }
1477         //bug43465 end
1478
1479         $sort_URL_base = $this->base_URL. "&".$this->getSessionVariableName($html_varName,"ORDER_BY")."=";
1480
1481         if($sort_URL_base !== "")
1482         {
1483             $this->xTemplate->assign("ORDER_BY", $sort_URL_base);
1484             return $sort_URL_base;
1485         } else {
1486             return '';
1487         }
1488     }
1489
1490
1491     function getAdditionalHeader() {
1492
1493     }
1494
1495
1496     /**
1497     * @return void
1498     * @param unknown $data
1499     * @param unknown $xTemplateSection
1500     * @param unknown $html_varName
1501     * @desc INTERNAL FUNCTION handles the rows
1502     * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1503     * All Rights Reserved.
1504     * Contributor(s): ______________________________________..
1505     */
1506     function processListRows($data, $xtemplateSection, $html_varName)
1507     {
1508         global $odd_bg;
1509         global $even_bg;
1510         global $hilite_bg;
1511         global $app_strings, $sugar_version, $sugar_config;
1512         global $currentModule;
1513
1514         $this->xTemplate->assign('BG_HILITE', $hilite_bg);
1515         $this->xTemplate->assign('CHECKALL', SugarThemeRegistry::current()->getImage('blank', '', 1, 1, ".gif", ''));
1516     //$this->xTemplate->assign("BG_CLICK", $click_bg);
1517         $oddRow = true;
1518         $count = 0;
1519         reset($data);
1520
1521         //GETTING OFFSET
1522         $offset = $this->getOffset($html_varName);
1523         $timeStamp = $this->unique_id();
1524         $_SESSION[$html_varName."_FROM_LIST_VIEW"] = $timeStamp;
1525
1526         $associated_row_data = array();
1527
1528         //mail merge list
1529         $mergeList = array();
1530         $module = '';
1531         //todo what is this?  It is using an array as a boolean
1532         while(list($aVal, $aItem) = each($data))
1533         {
1534             if(isset($this->data_array)) {
1535                 $fields = $this->data_array;
1536             } else {
1537                 $aItem->check_date_relationships_load();
1538                 $fields = $aItem->get_list_view_data();
1539             }
1540
1541             if(is_object($aItem)) { // cn: bug 5349
1542                 //add item id to merge list, if the button is clicked
1543                 $mergeList[] = $aItem->id;
1544                 if(empty($module)) {
1545                     $module = $aItem->module_dir;
1546                 }
1547             }
1548             //ADD OFFSET TO ARRAY
1549
1550                 $fields['OFFSET'] = ($offset + $count + 1);
1551
1552             $fields['STAMP'] = $timeStamp;
1553             if($this->shouldProcess) {
1554
1555             $prerow = '';
1556             if(!isset($this->data_array)) {
1557                 $prerow .= "<input onclick='sListView.check_item(this, document.MassUpdate)' type='checkbox' class='checkbox' name='mass[]' value='". $fields['ID']. "'>";
1558             }
1559             $this->xTemplate->assign('PREROW', $prerow);
1560
1561             $this->xTemplate->assign('CHECKALL', "<input type='checkbox' class='checkbox'  title='".$GLOBALS['app_strings']['LBL_SELECT_ALL_TITLE']."'  name='massall' id='massall' value='' onclick='sListView.check_all(document.MassUpdate, \"mass[]\", this.checked)'>");
1562             }
1563             if(!isset($this->data_array)) {
1564                 $tag = $aItem->listviewACLHelper();
1565                 $this->xTemplate->assign('TAG',$tag) ;
1566             }
1567
1568             if($oddRow)
1569             {
1570                 $ROW_COLOR = 'oddListRow';
1571                 $BG_COLOR =  $odd_bg;
1572             }
1573             else
1574             {
1575                 $ROW_COLOR = 'evenListRow';
1576                 $BG_COLOR =  $even_bg;
1577             }
1578             $oddRow = !$oddRow;
1579
1580             $this->xTemplate->assign('ROW_COLOR', $ROW_COLOR);
1581             $this->xTemplate->assign('BG_COLOR', $BG_COLOR);
1582
1583             if(isset($this->data_array))
1584             {
1585                 $this->xTemplate->assign('KEY', $aVal);
1586                 $this->xTemplate->assign('VALUE', $aItem);
1587                 $this->xTemplate->assign('INDEX', $count);
1588
1589             }
1590             else
1591             {
1592     //AED -- some modules do not have their additionalDetails.php established. Add a check to ensure require_once does not fail
1593     // Bug #2786
1594                 if($this->_additionalDetails && $aItem->ACLAccess('DetailView') && (file_exists('modules/' . $aItem->module_dir . '/metadata/additionalDetails.php') || file_exists('custom/modules/' . $aItem->module_dir . '/metadata/additionalDetails.php'))) {
1595
1596                     $additionalDetailsFile = 'modules/' . $aItem->module_dir . '/metadata/additionalDetails.php';
1597                     if(file_exists('custom/modules/' . $aItem->module_dir . '/metadata/additionalDetails.php')){
1598                         $additionalDetailsFile = 'custom/modules/' . $aItem->module_dir . '/metadata/additionalDetails.php';
1599                     }
1600
1601                     require_once($additionalDetailsFile);
1602                     $ad_function = (empty($this->additionalDetailsFunction) ? 'additionalDetails' : $this->additionalDetailsFunction) . $aItem->object_name;
1603                     $results = $ad_function($fields);
1604                     $results['string'] = str_replace(array("&#039", "'"), '\&#039', $results['string']); // no xss!
1605
1606                     if(trim($results['string']) == '') $results['string'] = $app_strings['LBL_NONE'];
1607                     $fields[$results['fieldToAddTo']] = $fields[$results['fieldToAddTo']].'</a>';
1608                 }
1609
1610                 if($aItem->ACLAccess('Delete')) {
1611                     $delete = '<a class="listViewTdToolsS1" onclick="return confirm(\''.$this->local_app_strings['NTC_DELETE_CONFIRMATION'].'\')" href="'.'index.php?action=Delete&module='.$aItem->module_dir.'&record='.$fields['ID'].'&return_module='.$aItem->module_dir.'&return_action=index&return_id=">'.$this->local_app_strings['LBL_DELETE_INLINE'].'</a>';
1612                     require_once('include/Smarty/plugins/function.sugar_action_menu.php');
1613                     $fields['DELETE_BUTTON'] = smarty_function_sugar_action_menu(array(
1614                         'id' => $aItem->module_dir.'_'.$fields['ID'].'_create_button',
1615                         'buttons' => array($delete),
1616                     ), $this);
1617
1618                 }
1619
1620                 $this->xTemplate->assign($html_varName, $fields);
1621                 $aItem->setupCustomFields($aItem->module_dir);
1622                 $aItem->custom_fields->populateAllXTPL($this->xTemplate, 'detail', $html_varName, $fields);
1623             }
1624             if(!isset($this->data_array) && $aItem->ACLAccess('DetailView')) {
1625                 $count++;
1626             }
1627             if(isset($this->data_array)) {
1628                 $count++;
1629             }
1630             if(!isset($this->data_array)) {
1631                 $aItem->list_view_parse_additional_sections($this->xTemplate, $xtemplateSection);
1632
1633                 if($this->xTemplate->exists($xtemplateSection.'.row.pro')) {
1634                     $this->xTemplate->parse($xtemplateSection.'.row.pro');
1635                 }
1636             }
1637             $this->xTemplate->parse($xtemplateSection . '.row');
1638
1639             if(isset($fields['ID'])) {
1640                 $associated_row_data[$fields['ID']] = $fields;
1641                 // Bug 38908: cleanup data for JS to avoid having &nbsp; shuffled around
1642                 foreach($fields as $key => $value) {
1643                     if($value == '&nbsp;') {
1644                         $associated_row_data[$fields['ID']][$key] = '';
1645                     }
1646                 }
1647             }
1648         }
1649
1650         $_SESSION['MAILMERGE_RECORDS'] = $mergeList;
1651         $_SESSION['MAILMERGE_MODULE_FROM_LISTVIEW'] = $module;
1652         if(empty($_REQUEST['action']) || $_REQUEST['action'] != 'Popup') {
1653             $_SESSION['MAILMERGE_MODULE'] = $module;
1654         }
1655
1656         if($this->process_for_popups)
1657         {
1658             $json = getJSONobj();
1659             $is_show_fullname = showFullName() ? 1 : 0;
1660             $associated_javascript_data = '<script type="text/javascript">' . "\n"
1661                 //. '<!-- // associated javascript data generated by ListView' . "\n"
1662                 . 'var associated_javascript_data = '
1663                 . $json->encode($associated_row_data) . ";\n"
1664                 //. '-->' . "\n"
1665                 . 'var is_show_fullname = '
1666                 . $is_show_fullname . ";\n"
1667                 . '</script>';
1668             $this->xTemplate->assign('ASSOCIATED_JAVASCRIPT_DATA', $associated_javascript_data);
1669         }
1670
1671         $this->xTemplate->parse($xtemplateSection);
1672     }
1673
1674
1675     function getLayoutManager()
1676     {
1677         require_once('include/generic/LayoutManager.php');
1678         if($this->layout_manager == null)
1679         {
1680             $this->layout_manager = new LayoutManager();
1681         }
1682         return $this->layout_manager;
1683     }
1684
1685
1686     function process_dynamic_listview_header($source_module, $subpanel_def, $html_var = 'CELL')
1687     {
1688
1689
1690         $layout_manager = $this->getLayoutManager();
1691         $layout_manager->setAttribute('order_by_link',$this->processOrderBy($html_var));
1692         $layout_manager->setAttribute('context','HeaderCell');
1693         $layout_manager->setAttribute('image_path',$this->local_image_path);
1694         $layout_manager->setAttribute('html_varName',$html_var);
1695         $layout_manager->setAttribute('module_name', $source_module);
1696         list($orderBy,$desc) = $this->getOrderByInfo($html_var);
1697
1698         if($orderBy == 'amount*1')
1699         {
1700             $orderBy=  'amount';
1701         }
1702                 $buttons = false;
1703         foreach($subpanel_def->get_list_fields() as $column_name=>$widget_args)
1704         {
1705             $usage = empty($widget_args['usage']) ? '' : $widget_args['usage'];
1706             if($usage != 'query_only')
1707             {
1708                 $imgArrow = '';
1709
1710                 if($orderBy == $column_name || (isset($widget_args['sort_by']) && str_replace('.','_',$widget_args['sort_by']) == $orderBy))
1711                 {
1712                     $imgArrow = "_down";
1713                     if($this->sort_order == 'asc') {
1714                         $imgArrow = "_up";
1715                     }
1716                 }
1717
1718                 if (!preg_match("/_button/i", $column_name)) {
1719                         $widget_args['name']=$column_name;
1720                         $widget_args['sort'] = $imgArrow;
1721                         $widget_args['start_link_wrapper'] = $this->start_link_wrapper;
1722                         $widget_args['end_link_wrapper'] = $this->end_link_wrapper;
1723                         $widget_args['subpanel_module'] = $this->subpanel_module;
1724
1725                         $widget_contents = $layout_manager->widgetDisplay($widget_args);
1726                         $cell_width = empty($widget_args['width']) ? '' : $widget_args['width'];
1727                         $this->xTemplate->assign('HEADER_CELL', $widget_contents);
1728                         static $count;
1729                     if(!isset($count))$count = 0; else $count++;
1730                         $this->xTemplate->assign('CELL_COUNT', $count);
1731                         $this->xTemplate->assign('CELL_WIDTH', $cell_width);
1732                         $this->xTemplate->parse('dyn_list_view.header_cell');
1733                 } else {
1734                         $buttons = true;
1735                 }
1736             }
1737         }
1738
1739         if($buttons) {
1740                                 $this->xTemplate->assign('HEADER_CELL', "&nbsp;");
1741                                 $this->xTemplate->assign('CELL_COUNT', $count);
1742                         $this->xTemplate->assign('CELL_WIDTH', $cell_width);
1743                         $this->xTemplate->parse('dyn_list_view.header_cell');
1744         }
1745
1746     }
1747
1748
1749     /**
1750     * @return void
1751     * @param unknown $seed
1752     * @param unknown $xTemplateSection
1753     * @param unknown $html_varName
1754     * @desc PUBLIC FUNCTION Handles List Views using seeds that extend SugarBean
1755         $XTemplateSection is the section in the XTemplate file that should be parsed usually main
1756         $html_VarName is the variable name used in the XTemplateFile e.g. TASK
1757         $seed is a seed there are two types of seeds one is a subclass of SugarBean, the other is a list usually created from a sugar bean using get_list
1758         if no XTemplate is set it will create  a new XTemplate
1759         * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
1760         * All Rights Reserved..
1761         * Contributor(s): ______________________________________..
1762     */
1763
1764     function processListViewTwo($seed, $xTemplateSection, $html_varName) {
1765         global $current_user;
1766         if(!isset($this->xTemplate)) {
1767             $this->createXTemplate();
1768         }
1769
1770         $isSugarBean = is_subclass_of($seed, "SugarBean");
1771         $list = null;
1772
1773         if($isSugarBean) {
1774             $list = $this->processSugarBean($xTemplateSection, $html_varName, $seed);
1775         } else {
1776             $list = $seed;
1777         }
1778
1779         if (is_object($seed) && isset($seed->object_name) && $seed->object_name == 'WorkFlow') {
1780             $tab=array();
1781             $access = get_workflow_admin_modules_for_user($current_user);
1782             for ($i = 0; $i < count($list); $i++) {
1783                 if(!empty($access[$list[$i]->base_module])){
1784                     $tab[]=$list[$i];
1785                 }
1786             }
1787             $list = $tab;
1788         }
1789
1790         if($this->is_dynamic) {
1791             $this->processHeaderDynamic($xTemplateSection,$html_varName);
1792             $this->processListRows($list,$xTemplateSection, $html_varName);
1793         } else {
1794             $this->processSortArrows($html_varName);
1795
1796             if($isSugarBean) {
1797                 $seed->parse_additional_headers($this->xTemplate, $xTemplateSection);
1798             }
1799             $this->xTemplateAssign('CHECKALL', SugarThemeRegistry::current()->getImage('blank', '', 1, 1, ".gif", ''));
1800
1801             // Process the  order by before processing the pro_nav.  The pro_nav requires the order by values to be set
1802             $this->processOrderBy($html_varName);
1803
1804
1805             $this->processListRows($list,$xTemplateSection, $html_varName);
1806         }
1807
1808         if($this->display_header_and_footer) {
1809             $this->getAdditionalHeader();
1810             if(!empty($this->header_title)) {
1811                 echo get_form_header($this->header_title, $this->header_text, false);
1812             }
1813         }
1814
1815         $this->xTemplate->out($xTemplateSection);
1816
1817         if(isset($_SESSION['validation'])) {
1818             print base64_decode('PGEgaHJlZj0naHR0cDovL3d3dy5zdWdhcmNybS5jb20nPlBPV0VSRUQmbmJzcDtCWSZuYnNwO1NVR0FSQ1JNPC9hPg==');
1819         }
1820     }
1821
1822     function getArrowStart() {
1823         $imgFileParts = pathinfo(SugarThemeRegistry::current()->getImageURL("arrow.gif"));
1824
1825         return "&nbsp;<!--not_in_theme!--><img border='0' src='".$imgFileParts['dirname']."/".$imgFileParts['filename']."";
1826     }
1827
1828     function getArrowUpDownStart($upDown) {
1829         $ext = ( SugarThemeRegistry::current()->pngSupport ? "png" : "gif" );
1830
1831         if (!isset($upDown) || empty($upDown)) {
1832             $upDown = "";
1833         }
1834         return "&nbsp;<img border='0' src='".SugarThemeRegistry::current()->getImageURL("arrow{$upDown}.{$ext}")."' ";
1835     }
1836
1837         function getArrowEnd() {
1838                 $imgFileParts = pathinfo(SugarThemeRegistry::current()->getImageURL("arrow.gif"));
1839
1840         list($width,$height) = ListView::getArrowImageSize();
1841
1842                 return '.'.$imgFileParts['extension']."' width='$width' height='$height' align='absmiddle' alt=".translate('LBL_SORT').">";
1843     }
1844
1845     function getArrowUpDownEnd($upDown) {
1846         if (!isset($upDown) || empty($upDown)) {
1847             $upDown = "";
1848         }
1849         $imgFileParts = pathinfo(SugarThemeRegistry::current()->getImageURL("arrow{$upDown}.gif"));
1850
1851         list($width,$height) = ListView::getArrowUpDownImageSize($upDown);
1852
1853         //get the right alt tag for the sort
1854         $sortStr = translate('LBL_ALT_SORT');
1855         if($upDown == '_down'){
1856             $sortStr = translate('LBL_ALT_SORT_DESC');
1857         }elseif($upDown == '_up'){
1858             $sortStr = translate('LBL_ALT_SORT_ASC');
1859         }
1860         return " width='$width' height='$height' align='absmiddle' alt='$sortStr'>";
1861     }
1862
1863         function getArrowImageSize() {
1864             // jbasicChartDashletsExpColust get the non-sort image's size.. the up and down have be the same.
1865                 $image = SugarThemeRegistry::current()->getImageURL("arrow.gif",false);
1866
1867         $cache_key = 'arrow_size.'.$image;
1868
1869         // Check the cache
1870         $result = sugar_cache_retrieve($cache_key);
1871         if(!empty($result))
1872         return $result;
1873
1874         // No cache hit.  Calculate the value and return.
1875         $result = getimagesize($image);
1876         sugar_cache_put($cache_key, $result);
1877         return $result;
1878     }
1879
1880     function getArrowUpDownImageSize($upDown) {
1881         // just get the non-sort image's size.. the up and down have be the same.
1882         $image = SugarThemeRegistry::current()->getImageURL("arrow{$upDown}.gif",false);
1883
1884         $cache_key = 'arrowupdown_size.'.$image;
1885
1886         // Check the cache
1887         $result = sugar_cache_retrieve($cache_key);
1888         if(!empty($result))
1889         return $result;
1890
1891         // No cache hit.  Calculate the value and return.
1892         $result = getimagesize($image);
1893         sugar_cache_put($cache_key, $result);
1894         return $result;
1895     }
1896
1897         function getOrderByInfo($html_varName)
1898         {
1899                 $orderBy = $this->getSessionVariable($html_varName, "OBL");
1900                 $desc = $this->getSessionVariable($html_varName, $orderBy.'S');
1901                 $orderBy = str_replace('.', '_', $orderBy);
1902                 return array($orderBy,$desc);
1903         }
1904
1905     function processSortArrows($html_varName)
1906     {
1907
1908         $this->xTemplateAssign("arrow_start", $this->getArrowStart());
1909
1910         list($orderBy,$desc) = $this->getOrderByInfo($html_varName);
1911
1912                 $imgArrow = "_up";
1913                 if($desc) {
1914                         $imgArrow = "_down";
1915                 }
1916                 /**
1917                  * @deprecated only used by legacy opportunites listview, nothing current. Leaving for BC
1918                  */
1919                 if($orderBy == 'amount')
1920                 {
1921                         $this->xTemplateAssign('amount_arrow', $imgArrow);
1922                 }
1923                 else if($orderBy == 'amount_usdollar')
1924                 {
1925                         $this->xTemplateAssign('amount_usdollar_arrow', $imgArrow);
1926                 }
1927                 else
1928                 {
1929                         $this->xTemplateAssign($orderBy.'_arrow', $imgArrow);
1930                 }
1931
1932         $this->xTemplateAssign('arrow_end', $this->getArrowEnd());
1933     }
1934
1935     // this is where translation happens for dynamic list views
1936     function loadListFieldDefs(&$subpanel_fields,&$child_focus)
1937     {
1938         $this->list_field_defs = $subpanel_fields;
1939
1940         for($i=0;$i < count($this->list_field_defs);$i++)
1941         {
1942             $list_field = $this->list_field_defs[$i];
1943             $field_def = null;
1944             $key = '';
1945             if(!empty($list_field['vname']))
1946             {
1947                 $key = $list_field['vname'];
1948             } else if(isset($list_field['name']) &&  isset($child_focus->field_defs[$list_field['name']]))
1949             {
1950                     $field_def = $child_focus->field_defs[$list_field['name']];
1951                     $key = $field_def['vname'];
1952             }
1953             if(!empty($key))
1954             {
1955                 $list_field['label'] = translate($key,$child_focus->module_dir);
1956                 $this->list_field_defs[$i]['label'] = preg_replace('/:$/','',$list_field['label']);
1957             }
1958             else
1959             {
1960                 $this->list_field_defs[$i]['label'] ='&nbsp;';
1961             }
1962         }
1963     }
1964
1965     function unique_id() {
1966         return sugar_microtime();
1967     }
1968
1969      /**INTERNAL FUNCTION sets a session variable keeping it local to the listview
1970      not the current_module
1971      * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1972      * All Rights Reserved.
1973      * Contributor(s): ______________________________________.
1974      */
1975      function setLocalSessionVariable($localVarName,$varName, $value) {
1976         $_SESSION[$localVarName."_".$varName] = $value;
1977      }
1978
1979      /**INTERNAL FUNCTION returns a session variable that is local to the listview,
1980      not the current_module
1981      * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1982      * All Rights Reserved.
1983      * Contributor(s): ______________________________________.
1984      */
1985  function getLocalSessionVariable($localVarName,$varName) {
1986     if(isset($_SESSION[$localVarName."_".$varName])) {
1987         return $_SESSION[$localVarName."_".$varName];
1988     }
1989     else{
1990         return "";
1991     }
1992  }
1993
1994  /* Set to true if you want Additional Details to appear in the listview
1995   */
1996  function setAdditionalDetails($value = true, $function = '') {
1997     if(!empty($function)) $this->additionalDetailsFunction = $function;
1998     $this->_additionalDetails = $value;
1999  }
2000
2001 }
2002 ?>