]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/MassUpdate.php
Release 6.1.6
[Github/sugarcrm.git] / include / MassUpdate.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39
40
41 /**
42  * MassUpdate class for updating multiple records at once
43  */
44  require_once('include/EditView/EditView2.php');
45 class MassUpdate
46 {
47         /*
48          * internal sugarbean reference
49          */
50         var $sugarbean = null;
51
52         /**
53           * set the sugar bean to its internal member
54           * @param sugar bean reference
55           */
56         function setSugarBean($sugar)
57         {
58                 $this->sugarbean = $sugar;
59         }
60
61         /**
62          * get the massupdate form
63          * @param bool boolean need to execute the massupdate form or not
64          * @param multi_select_popup booleanif it is a multi-select value
65          */
66         function getDisplayMassUpdateForm($bool, $multi_select_popup = false)
67         {
68
69                 require_once('include/formbase.php');
70
71                 if(!$multi_select_popup)
72                 $form = '<form action="index.php" method="post" name="displayMassUpdate" id="displayMassUpdate">' . "\n";
73                 else
74                 $form = '<form action="index.php" method="post" name="MassUpdate" id="MassUpdate">' . "\n";
75
76                 if($bool)
77                 {
78                         $form .= '<input type="hidden" name="mu" value="false" />' . "\n";
79                 }
80                 else
81                 {
82                         $form .= '<input type="hidden" name="mu" value="true" />' . "\n";
83                 }
84
85                 $form .= getAnyToForm('mu', true);
86                 if(!$multi_select_popup) $form .= "</form>\n";
87
88                 return $form;
89         }
90         /**
91          * returns the mass update's html form header
92          * @param multi_select_popup boolean if it is a mult-select or not
93          */
94         function getMassUpdateFormHeader($multi_select_popup = false)
95         {
96                 global $sugar_version;
97                 global $sugar_config;
98                 global $current_user;
99
100                 unset($_REQUEST['current_query_by_page']);
101                 unset($_REQUEST[session_name()]);
102                 unset($_REQUEST['PHPSESSID']);
103                 $query = base64_encode(serialize($_REQUEST));
104
105         $bean = loadBean($_REQUEST['module']);
106        $order_by_name = $bean->module_dir.'2_'.strtoupper($bean->object_name).'_ORDER_BY' ;
107        $lvso = isset($_REQUEST['lvso'])?$_REQUEST['lvso']:"";
108        $request_order_by_name = isset($_REQUEST[$order_by_name])?$_REQUEST[$order_by_name]:"";
109        $action = isset($_REQUEST['action'])?$_REQUEST['action']:"";
110        $module = isset($_REQUEST['module'])?$_REQUEST['module']:"";
111                 if($multi_select_popup)
112                 $tempString = '';
113                 else
114                 $tempString = "<form action='index.php' method='post' name='MassUpdate'  id='MassUpdate' onsubmit=\"return check_form('MassUpdate');\">\n"
115                 . "<input type='hidden' name='return_action' value='{$action}' />\n"
116         . "<input type='hidden' name='return_module' value='{$module}' />\n"
117                 . "<input type='hidden' name='massupdate' value='true' />\n"
118                 . "<input type='hidden' name='delete' value='false' />\n"
119                 . "<input type='hidden' name='merge' value='false' />\n"
120         . "<input type='hidden' name='current_query_by_page' value='{$query}' />\n"
121         . "<input type='hidden' name='module' value='{$module}' />\n"
122         . "<input type='hidden' name='action' value='MassUpdate' />\n"
123         . "<input type='hidden' name='lvso' value='{$lvso}' />\n"
124         . "<input type='hidden' name='{$order_by_name}' value='{$request_order_by_name}' />\n";
125
126                 // cn: bug 9103 - MU navigation in emails is broken
127                 if($_REQUEST['module'] == 'Emails') {
128                         $type = "";
129                         // determine "type" - inbound, archive, etc.
130                         if (isset($_REQUEST['type'])) {
131                                 $type = $_REQUEST['type'];
132                         }
133                         // determine owner
134                         $tempString .=<<<eoq
135                                 <input type='hidden' name='type' value="{$type}" />
136                                 <input type='hidden' name='ie_assigned_user_id' value="{$current_user->id}" />
137 eoq;
138                 }
139
140                 return $tempString;
141         }
142
143         /**
144           * Executes the massupdate form
145           * @param displayname Name to display in the popup window
146       * @param varname name of the variable
147           */
148         function handleMassUpdate(){
149
150                 require_once('include/formbase.php');
151                 global $current_user, $db;
152
153                 /*
154                  C.L. - Commented this out... not sure why it's here
155                 if(!is_array($this->sugarbean) && $this->sugarbean->bean_implements('ACL') && !ACLController::checkAccess($this->sugarbean->module_dir, 'edit', true))
156                 {
157
158                 }
159         */
160
161                 foreach($_POST as $post=>$value){
162                         if(is_array($value)){
163                                 if(empty($value)){
164                                         unset($_POST[$post]);
165                                 }
166                         }elseif(strlen($value) == 0){
167                                 if( isset($this->sugarbean->field_defs[$post]) && $this->sugarbean->field_defs[$post]['type'] == 'radioenum' && isset($_POST[$post]) ){
168                                         $_POST[$post] = '';
169                                 }else{
170                                 unset($_POST[$post]);
171                         }
172                         }
173                         if(is_string($value)
174                                  && isset($this->sugarbean->field_defs[$post]) &&
175                                  ($this->sugarbean->field_defs[$post]['type'] == 'bool'
176                                         || (!empty($this->sugarbean->field_defs[$post]['custom_type']) && $this->sugarbean->field_defs[$post]['custom_type'] == 'bool'
177                                         ))){
178
179
180                                                 if(strcmp($value, '2') == 0)$_POST[$post] = 0;
181                                                 if(!empty($this->sugarbean->field_defs[$post]['dbType']) && strcmp($this->sugarbean->field_defs[$post]['dbType'], 'varchar') == 0 ){
182                                                         if(strcmp($value, '1') == 0 )$_POST[$post] = 'on';
183                                                         if(strcmp($value, '2') == 0)$_POST[$post] = 'off';
184                                                 }
185                         }
186                         if(is_string($value)
187                                  && isset($this->sugarbean->field_defs[$post]) && $this->sugarbean->field_defs[$post]['type'] == 'radioenum' && isset($_POST[$post]) && strlen($value) == 0){
188                                 $_POST[$post] = '';
189                         }
190                 }
191
192                 if(!empty($_REQUEST['uid'])) $_POST['mass'] = explode(',', $_REQUEST['uid']); // coming from listview
193                 elseif(isset($_REQUEST['entire']) && empty($_POST['mass'])) {
194                         if(empty($order_by))$order_by = '';
195                         $ret_array = create_export_query_relate_link_patch($_REQUEST['module'], $this->searchFields, $this->where_clauses);
196                         if(!isset($ret_array['join'])) {
197                                 $ret_array['join'] = '';
198                         }
199                         $query = $this->sugarbean->create_export_query($order_by, $ret_array['where'], $ret_array['join']);
200                         $result = $db->query($query,true);
201                         $new_arr = array();
202                         while($val = $db->fetchByAssoc($result,-1,false))
203                         {
204                                 array_push($new_arr, $val['id']);
205                         }
206                         $_POST['mass'] = $new_arr;
207                 }
208
209                 if(isset($_POST['mass']) && is_array($_POST['mass'])  && $_REQUEST['massupdate'] == 'true'){
210                         $count = 0;
211
212
213                         foreach($_POST['mass'] as $id){
214                 if(empty($id)) {
215                     continue;
216                 }
217                                 if(isset($_POST['Delete'])){
218                                         $this->sugarbean->retrieve($id);
219                                         if($this->sugarbean->ACLAccess('Delete')){
220                                         //Martin Hu Bug #20872
221                                                 if($this->sugarbean->object_name == 'EmailMan'){
222                                                         $query = "DELETE FROM emailman WHERE id = '" . $this->sugarbean->id . "'";
223                                                         $db->query($query);
224                                                 } else {
225
226                                                         $this->sugarbean->mark_deleted($id);
227                                                 }
228                                         }
229                                 }
230                                 else {
231                                         if($this->sugarbean->object_name == 'Contact' && isset($_POST['Sync'])){ // special for contacts module
232                                                 if($_POST['Sync'] == 'true') {
233                                                         $this->sugarbean->retrieve($id);
234                                                         if($this->sugarbean->ACLAccess('Save')){
235                                                                 if($this->sugarbean->object_name == 'Contact'){
236
237                                                                         $this->sugarbean->contacts_users_id = $current_user->id;
238                                                                         $this->sugarbean->save(false);
239                                                                 }
240                                                         }
241                                                 }
242                                                 elseif($_POST['Sync'] == 'false') {
243                                                         $this->sugarbean->retrieve($id);
244                                                         if($this->sugarbean->ACLAccess('Save')){
245                                                                 if($this->sugarbean->object_name == 'Contact'){
246                                                                         if (!isset($this->sugarbean->users))
247                                                                         {
248                                                                                 $this->sugarbean->load_relationship('user_sync');
249                                                                         }
250                                                                         $this->sugarbean->contacts_users_id = null;
251                                                                         $this->sugarbean->user_sync->delete($this->sugarbean->id, $current_user->id);
252                                                                 }
253                                                         }
254                                                 }
255                                         } //end if for special Contact handling
256
257                                         if($count++ != 0) {
258                                            //Create a new instance to clear values and handle additional updates to bean's 2,3,4...
259                        $className = get_class($this->sugarbean);
260                        $this->sugarbean = new $className();
261                                         }
262
263                                         $this->sugarbean->retrieve($id);
264
265                                         foreach($_POST as $field=>$value){
266                         if (isset($this->sugarbean->field_defs[$field])) {
267                             if($this->sugarbean->field_defs[$field]['type'] == 'datetime') {
268                                 $_POST[$field] = $this->date_to_dateTime($field, $value);
269                             }
270                             if($this->sugarbean->field_defs[$field]['type'] == 'datetimecombo') {
271                                 if(!empty($_POST[$field]) && strlen($_POST[$field]) > 10 ){
272                                                                 $dateValue = $_POST[$field];
273                                                                 $_POST[$field] = $dateValue;
274                                                         }else{
275                                                                 unset($_POST[$field]);
276                                                         }
277                             }
278                             if ($this->sugarbean->field_defs[$field]['type'] == 'bool') {
279                                 $this->checkClearField($field, $value);
280                             }
281                         }
282                     }
283
284
285                                         if($this->sugarbean->ACLAccess('Save')){
286                                                 $_POST['record'] = $id;
287                                                 $_GET['record'] = $id;
288                                                 $_REQUEST['record'] = $id;
289                                                 $newbean=$this->sugarbean;
290
291                                                 $old_reports_to_id = null;
292                                                 if(!empty($_POST['reports_to_id']) && $newbean->reports_to_id != $_POST['reports_to_id']) {
293                                                    $old_reports_to_id = empty($newbean->reports_to_id) ? 'null' : $newbean->reports_to_id;
294                                                 }
295
296                                                 $check_notify = FALSE;
297
298                                                 if (isset( $this->sugarbean->assigned_user_id)) {
299                                                         $old_assigned_user_id = $this->sugarbean->assigned_user_id;
300                                                         if (!empty($_POST['assigned_user_id'])
301                                                         && ($old_assigned_user_id != $_POST['assigned_user_id'])
302                                                         && ($_POST['assigned_user_id'] != $current_user->id)) {
303                                                                 $check_notify = TRUE;
304                                                         }
305                                                 }
306
307                                                 //Call include/formbase.php, but do not call retrieve again
308                                                 populateFromPost('', $newbean, true);
309                                                 $newbean->save_from_post = false;
310
311                                                 if (!isset($_POST['parent_id'])) {
312                                                         $newbean->parent_type = null;
313                                                 }
314
315                                                 $email_address_id = '';
316                             if (!empty($_POST['optout_primary'])) {
317                                 $optout_flag_value = 0;
318                                 if ($_POST['optout_primary'] == 'true') {
319                                         $optout_flag_value = 1;
320                                 } // if
321                                 if (isset($this->sugarbean->emailAddress)) {
322                                         if (!empty($this->sugarbean->emailAddress->addresses)) {
323                                                 foreach($this->sugarbean->emailAddress->addresses as $key =>$emailAddressRow) {
324                                                         if ($emailAddressRow['primary_address'] == '1') {
325                                                                 $email_address_id = $emailAddressRow['email_address_id'];
326                                                                 break;
327                                                                                 } // if
328                                                                         } // foreach
329                                                                 } // if
330
331                                                         } // if
332                             } // if
333
334
335                                                 $newbean->save($check_notify);
336                                                 if (!empty($email_address_id)) {
337                                                 $query = "UPDATE email_addresses SET opt_out = {$optout_flag_value} where id = '{$emailAddressRow['email_address_id']}'";
338                                                 $GLOBALS['db']->query($query);
339
340                                                 } // if
341
342                                                 if(!empty($old_reports_to_id) && method_exists($newbean, 'update_team_memberships')) {
343                                                    $old_id = $old_reports_to_id == 'null' ? '' : $old_reports_to_id;
344                                                 }
345                                         }
346                                 }
347                         }
348
349                 }
350
351         }
352         /**
353           * Displays the massupdate form
354           */
355         function getMassUpdateForm(
356             $hideDeleteIfNoFieldsAvailable = false
357             )
358         {
359                 global $app_strings;
360                 global $current_user;
361
362                 if($this->sugarbean->bean_implements('ACL') && !ACLController::checkAccess($this->sugarbean->module_dir, 'edit', true)){
363                         return '';
364                 }
365                 $lang_delete = translate('LBL_DELETE');
366                 $lang_update = translate('LBL_UPDATE');
367                 $lang_confirm= translate('NTC_DELETE_CONFIRMATION_MULTIPLE');
368                 $lang_sync = translate('LBL_SYNC_CONTACT');
369                 $lang_oc_status = translate('LBL_OC_STATUS');
370                 $lang_unsync = translate('LBL_UNSYNC');
371                 $lang_archive = translate('LBL_ARCHIVE');
372                 $lang_optout_primaryemail = $app_strings['LBL_OPT_OUT_FLAG_PRIMARY'];
373
374
375
376 //              if(!isset($this->sugarbean->field_defs) || count($this->sugarbean->field_defs) == 0) {
377 //                      $html = "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td>";
378 //
379 //                      if($this->sugarbean->ACLAccess('Delete', true) ){
380 //                              $html .= "<input type='submit' name='Delete' value='{$lang_delete}' onclick=\"return confirm('{$lang_confirm}')\" class='button'>";
381 //                      }
382 //                      $html .= "</td></tr></table>";
383 //                      return $html;
384 //              }
385
386
387                 $should_use = false;
388                 $html = "<div id='massupdate_form' style='display:none;'><table width='100%' cellpadding='0' cellspacing='0' border='0' class='formHeader h3Row'><tr><td nowrap><h3><span>" . $app_strings['LBL_MASS_UPDATE']."</h3></td></tr></table>";
389                 $html .= "<div id='mass_update_div'><table cellpadding='0' cellspacing='1' border='0' width='100%' class='edit view' id='mass_update_table'>";
390
391                 $even = true;
392                 if($this->sugarbean->object_name == 'Contact'){
393                         $html .= "<tr><td width='15%' scope='row'>$lang_sync</td><td width='35%' class='dataField'><select name='Sync'><option value=''>{$GLOBALS['app_strings']['LBL_NONE']}</option><option value='false'>{$GLOBALS['app_list_strings']['checkbox_dom']['2']}</option><option value='true'>{$GLOBALS['app_list_strings']['checkbox_dom']['1']}</option></select></td>";
394                         $even = false;
395                 }
396
397                 if($this->sugarbean->object_name == 'Employee'){
398                         $this->sugarbean->field_defs['employee_status']['type'] = 'enum';
399                         $this->sugarbean->field_defs['employee_status']['massupdate'] = true;
400                         $this->sugarbean->field_defs['employee_status']['options'] = 'employee_status_dom';
401                 }
402                 if($this->sugarbean->object_name == 'InboundEmail'){
403                         $this->sugarbean->field_defs['status']['type'] = 'enum';
404                         $this->sugarbean->field_defs['status']['options'] = 'user_status_dom';
405                 }
406
407                 static $banned = array('date_modified'=>1, 'date_entered'=>1, 'created_by'=>1, 'modified_user_id'=>1, 'deleted'=>1,'modified_by_name'=>1,);
408                 foreach($this->sugarbean->field_defs as $field){
409
410                          if(!isset($banned[$field['name']]) && (!isset($field['massupdate']) || !empty($field['massupdate']))){
411                                 $newhtml = '';
412                                 if($even){
413                                         $newhtml .= "<tr>";
414                                 }
415                                 if(isset($field['vname'])){
416                                         $displayname = translate($field['vname']);
417                                 }else{
418                                         $displayname = '';
419
420                                 }
421                                 if(isset($field['type']) && $field['type'] == 'relate' && isset($field['id_name']) && $field['id_name'] == 'assigned_user_id')
422                                         $field['type'] = 'assigned_user_name';
423                                 if(isset($field['custom_type']))$field['type'] = $field['custom_type'];
424                                 if(isset($field['type']))
425                                 {
426                                         switch($field["type"]){
427                                                 case "relate":
428                                                     // bug 14691: avoid laying out an empty cell in the <table>
429                                                         $handleRelationship = $this->handleRelationship($displayname, $field);
430                                                         if ($handleRelationship != '') {
431                                                                 $even = !$even;
432                                                                 $newhtml .= $handleRelationship;
433                                                         }
434                                                         break;
435                                                 case "parent":$even = !$even; $newhtml .=$this->addParent($displayname, $field); break;
436                                                 case "int":
437                                                         if(!empty($field['massupdate']) && empty($field['auto_increment'])){
438                                                                 $even = !$even; $newhtml .=$this->addInputType($displayname, $field);
439                                                         }
440                                                          break;
441                                                 case "contact_id":$even = !$even; $newhtml .=$this->addContactID($displayname, $field["name"]); break;
442                                                 case "assigned_user_name":$even = !$even; $newhtml .= $this->addAssignedUserID($displayname,  $field["name"]); break;
443                                                 case "account_id":$even = !$even; $newhtml .= $this->addAccountID($displayname,  $field["name"]); break;
444                                                 case "account_name":$even = !$even; $newhtml .= $this->addAccountID($displayname,  $field["id_name"]); break;
445                                                 case "bool": $even = !$even; $newhtml .= $this->addBool($displayname,  $field["name"]); break;
446                                                 case "enum":
447                                                 case "multienum":
448                                                         if(!empty($field['isMultiSelect'])){
449                                                                 $even = !$even; $newhtml .= $this->addStatusMulti($displayname,  $field["name"], translate($field["options"])); break;
450                                                         }else if(!empty($field['options'])) {
451                                                                 $even = !$even; $newhtml .= $this->addStatus($displayname,  $field["name"], translate($field["options"])); break;
452                                                         }else if(!empty($field['function'])){
453                                                                 $functionValue = $this->getFunctionValue($this->sugarbean, $field);
454                                                                 $even = !$even; $newhtml .= $this->addStatus($displayname,  $field["name"], $functionValue); break;
455                                                         }
456                                                         break;
457                                                 case "radioenum":
458                                                 $even = !$even; $newhtml .= $this->addRadioenum($displayname,  $field["name"] , translate($field["options"])); break;
459                                                 case "datetimecombo":
460                                                 $even = !$even; $newhtml .= $this->addDatetime($displayname,  $field["name"]); break;
461                                                 case "datetime":
462                                                 case "date":$even = !$even; $newhtml .= $this->addDate($displayname,  $field["name"]); break;
463                                         }
464                                 }
465                                 if($even){
466                                         $newhtml .="</tr>";
467                                 }else{
468                                         $should_use = true;
469                                 }
470                                 if(!in_array($newhtml, array('<tr>', '</tr>', '<tr></tr>', '<tr><td></td></tr>'))){
471                                         $html.=$newhtml;
472                                 }
473                         }
474                 }
475
476
477                 if ($this->sugarbean->object_name == 'Contact' ||
478                         $this->sugarbean->object_name == 'Account' ||
479                         $this->sugarbean->object_name == 'Lead' ||
480                         $this->sugarbean->object_name == 'Prospect') {
481
482                         $html .= "<tr><td width='15%'  scope='row' class='dataLabel'>$lang_optout_primaryemail</td><td width='35%' class='dataField'><select name='optout_primary'><option value=''>{$GLOBALS['app_strings']['LBL_NONE']}</option><option value='false'>{$GLOBALS['app_list_strings']['checkbox_dom']['2']}</option><option value='true'>{$GLOBALS['app_list_strings']['checkbox_dom']['1']}</option></select></td></tr>";
483
484                         }
485                 $html .="</table>";
486
487                  $html .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td class='buttons'><input onclick='return sListView.send_mass_update(\"selected\", \"{$app_strings['LBL_LISTVIEW_NO_SELECTED']}\")' type='submit' id='update_button' name='Update' value='{$lang_update}' class='button'>&nbsp;<input onclick='javascript:toggleMassUpdateForm();' type='button' id='cancel_button' name='Cancel' value='{$GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL']}' class='button'>";
488                 // TODO: allow ACL access for Delete to be set false always for users
489 //              if($this->sugarbean->ACLAccess('Delete', true) && $this->sugarbean->object_name != 'User') {
490 //                      global $app_list_strings;
491 //                      $html .=" <input id='delete_button' type='submit' name='Delete' value='{$lang_delete}' onclick='return confirm(\"{$lang_confirm}\") && sListView.send_mass_update(\"selected\", \"{$app_strings['LBL_LISTVIEW_NO_SELECTED']}\", 1)' class='button'>";
492 //              }
493
494                 // only for My Inbox views - to allow CSRs to have an "Archive" emails feature to get the email "out" of their inbox.
495                 if($this->sugarbean->object_name == 'Email'
496                 && (isset($_REQUEST['assigned_user_id']) && !empty($_REQUEST['assigned_user_id']))
497                 && (isset($_REQUEST['type']) && !empty($_REQUEST['type']) && $_REQUEST['type'] == 'inbound')) {
498                         $html .=<<<eoq
499                         <input type='button' name='archive' value="{$lang_archive}" class='button' onClick='setArchived();'>
500                         <input type='hidden' name='ie_assigned_user_id' value="{$current_user->id}">
501                         <input type='hidden' name='ie_type' value="inbound">
502 eoq;
503                 }
504
505                 $html .= "</td></tr></table></div></div>";
506
507                 $html .= <<<EOJS
508 <script>
509 function toggleMassUpdateForm(){
510     document.getElementById('massupdate_form').style.display = 'none';
511 }
512 </script>
513 EOJS;
514                 if($should_use){
515                         return $html;
516                 }else{
517                         if($this->sugarbean->ACLAccess('Delete', true) && !$hideDeleteIfNoFieldsAvailable){
518                                 return "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td><input type='submit' name='Delete' value='$lang_delete' onclick=\"return confirm('{$lang_confirm}')\" class='button'></td></tr></table>";
519                         }else{
520                                 return '';
521                         }
522                 }
523         }
524
525         function getFunctionValue($focus, $vardef){
526                 $function = $vardef['function'];
527             if(is_array($function) && isset($function['name'])){
528                 $function = $vardef['function']['name'];
529             }else{
530                 $function = $vardef['function'];
531             }
532                 if(!empty($vardef['function']['returns']) && $vardef['function']['returns'] == 'html'){
533                         if(!empty($vardef['function']['include'])){
534                                 require_once($vardef['function']['include']);
535                         }
536                         return $function($focus, $vardef['name'], '', 'MassUpdate');
537                 }else{
538                         return $function($focus, $vardef['name'], '', 'MassUpdate');
539                 }
540         }
541
542         /**
543           * Returns end of the massupdate form
544           */
545         function endMassUpdateForm(){
546                 return '</form>';
547         }
548
549         /**
550           * Decides which popup HTML code is needed for mass updating
551           * @param displayname Name to display in the popup window
552           * @param field name of the field to update
553           */
554         function handleRelationship($displayname, $field)
555         {
556                 $ret_val = '';
557                 if(isset($field['module']))
558                 {
559                         if ($field['name'] == 'reports_to_name' && ($field['module'] == 'Users' || $field['module'] == 'Employee') )
560                             return $this->addUserName($displayname, $field['name'], $field['id_name'], $field['module']);
561
562                     switch($field['module'])
563                         {
564                                 case 'Accounts':
565                                         $ret_val = $this->addAccountID($displayname, $field['name'], $field['id_name']);
566                                         break;
567                                 case 'Contacts':
568                                         $ret_val = $this->addGenericModuleID($displayname, $field['name'], $field['id_name'], "Contacts");
569                                         break;
570                                 case 'Users':
571                                         $ret_val = $this->addGenericModuleID($displayname, $field['name'], $field['id_name'], "Users");
572                                         break;
573                                 case 'Employee':
574                                         $ret_val = $this->addGenericModuleID($displayname, $field['name'], $field['id_name'], "Employee");
575                                         break;
576                                 case 'Releases':
577                                         $ret_val = $this->addGenericModuleID($displayname, $field['name'], $field['id_name'], "Releases");
578                                         break;
579                                 default:
580                                         if(!empty($field['massupdate'])){
581                                                 $ret_val = $this->addGenericModuleID($displayname, $field['name'], $field['id_name'], $field['module']);
582                                         }
583                                         break;
584                         }
585                 }
586
587                 return $ret_val;
588         }
589         /**
590           * Add a parent selection popup window
591           * @param displayname Name to display in the popup window
592           * @param field_name name of the field
593           */
594         function addParent($displayname, $field){
595                 global $app_strings, $app_list_strings;
596
597                 ///////////////////////////////////////
598                 ///
599                 /// SETUP POPUP
600
601                 $popup_request_data = array(
602                 'call_back_function' => 'set_return',
603                 'form_name' => 'MassUpdate',
604                 'field_to_name_array' => array(
605                         'id' => "parent_id",
606                         'name' => "parent_name",
607                         ),
608                         );
609
610                         $json = getJSONobj();
611                         $encoded_popup_request_data = $json->encode($popup_request_data);
612
613             $qsName = array(
614                                     'form' => 'MassUpdate',
615                                                 'method' => 'query',
616                         'modules' => array("Accounts"),
617                         'group' => 'or',
618                                                 'field_list' => array('name', 'id'),
619                                                 'populate_list' => array("mass_parent_name", "mass_parent_id"),
620                                                 'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
621                                                 'limit' => '30','no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
622                 $qsName = $json->encode($qsName);
623
624                         //
625                         ///////////////////////////////////////
626
627                         $change_parent_button = "<span class='id-ff'><button title='".$app_strings['LBL_SELECT_BUTTON_TITLE']."' accessKey='".$app_strings['LBL_SELECT_BUTTON_KEY']."'  type='button' class='button' value='".$app_strings['LBL_SELECT_BUTTON_LABEL']
628                         ."' name='button_parent_name' onclick='open_popup(document.MassUpdate.{$field['type_name']}.value, 600, 400, \"\", true, false, {$encoded_popup_request_data});'><img src='".SugarThemeRegistry::current()->getImageURL('id-ff-select.png')."'></button></span>";
629                         $parent_type = $field['parent_type'];
630             $parent_types = $app_list_strings[$parent_type];
631             $disabled_parent_types = ACLController::disabledModuleList($parent_types,false, 'list');
632             foreach($disabled_parent_types as $disabled_parent_type) {
633                             unset($parent_types[$disabled_parent_type]);
634             }
635                         $types = get_select_options_with_id($parent_types, '');
636                         //BS Fix Bug 17110
637                         $pattern = "/\n<OPTION.*".$app_strings['LBL_NONE']."<\/OPTION>/";
638                         $types = preg_replace($pattern, "", $types);
639                         // End Fix
640
641             $json = getJSONobj();
642             $disabled_parent_types = $json->encode($disabled_parent_types);
643
644                         return <<<EOHTML
645 <td width="15%" scope="row">{$displayname} </td>
646 <td>
647     <table width='100%' border='0' cellspacing='0' cellpadding='0'>
648     <tr>
649         <td valign='top'>
650             <select name='{$field['type_name']}' id='mass_{$field['type_name']}'>
651                 $types
652             </select>
653         </td>
654         <td valign='top'>
655                         <input name='{$field['id_name']}' id='mass_{$field['id_name']}' type='hidden' value=''>
656                         <input name='parent_name' id='mass_parent_name' class='sqsEnabled' autocomplete='off'
657                 type='text' value=''>
658             $change_parent_button
659         </td>
660     </tr>
661     </table>
662 </td>
663 <script type="text/javascript">
664 <!--
665 var disabledModules='{$disabled_parent_types}';
666 if(typeof sqs_objects == 'undefined'){
667     var sqs_objects = new Array;
668 }
669 sqs_objects['MassUpdate_parent_name'] = $qsName;
670 registerSingleSmartInputListener(document.getElementById('mass_parent_name'));
671 addToValidateBinaryDependency('MassUpdate', 'parent_name', 'alpha', false, '{$app_strings['ERR_SQS_NO_MATCH_FIELD']} {$app_strings['LBL_ASSIGNED_TO']}','parent_id');
672
673 document.getElementById('mass_{$field['type_name']}').onchange = function()
674 {
675     document.MassUpdate.parent_name.value="";
676     document.MassUpdate.parent_id.value="";
677
678         new_module = document.forms["MassUpdate"].elements["parent_type"].value;
679
680         if(typeof(disabledModules[new_module]) != 'undefined') {
681                 sqs_objects["MassUpdate_parent_name"]["disable"] = true;
682                 document.forms["MassUpdate"].elements["parent_name"].readOnly = true;
683         } else {
684                 sqs_objects["MassUpdate_parent_name"]["disable"] = false;
685                 document.forms["MassUpdate"].elements["parent_name"].readOnly = false;
686         }
687         sqs_objects["MassUpdate_parent_name"]["modules"] = new Array(new_module);
688     enableQS(false);
689
690     checkParentType(document.MassUpdate.parent_type.value, document.MassUpdate.button_parent_name);
691 }
692 -->
693 </script>
694 EOHTML;
695         }
696
697         /**
698           * Add a generic input type='text' field
699           * @param displayname Name to display in the popup window
700           * @param field_name name of the field
701           */
702         function addInputType($displayname, $varname){
703                 $html = <<<EOQ
704         <td scope="row" width="20%">$displayname</td>
705         <td class='dataField' width="30%"><input type="text" name='$varname' size="12" id='{$varname}' maxlength='10' value=""></td>
706         <script> addToValidate('MassUpdate','$varname','int',false,'$displayname');</script>
707 EOQ;
708                 return $html;
709
710         }
711
712     /**
713           * Add a generic widget to lookup Users.
714           * @param displayname Name to display in the popup window
715           * @param varname name of the variable
716           * @param id_name name of the id in vardef
717           * @param mod_type name of the module, either "Contact" or "Releases" currently
718           */
719         function addUserName($displayname, $varname, $id_name='', $mod_type){
720                 global $app_strings;
721
722                 if(empty($id_name))
723                 $id_name = strtolower($mod_type)."_id";
724
725                 ///////////////////////////////////////
726                 ///
727                 /// SETUP POPUP
728         $reportsDisplayName = showFullName() ? 'name' : 'user_name';
729                 $popup_request_data = array(
730                         'call_back_function' => 'set_return',
731                         'form_name' => 'MassUpdate',
732                         'field_to_name_array' => array(
733                                 'id' => "{$id_name}",
734                                 "$reportsDisplayName" => "{$varname}",
735                                 ),
736                                 );
737
738                                 $json = getJSONobj();
739                                 $encoded_popup_request_data = $json->encode($popup_request_data);
740
741                 $qsName = array(
742                                     'form' => 'MassUpdate',
743                                                 'method' => 'get_user_array',
744                         'modules' => array("{$mod_type}"),
745                         'group' => 'or',
746                                                 'field_list' => array('user_name', 'id'),
747                                                 'populate_list' => array("mass_{$varname}", "mass_{$id_name}"),
748                                                 'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
749                                                 'limit' => '30','no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
750                 $qsName = $json->encode($qsName);
751                                 //
752                                 ///////////////////////////////////////
753
754             return <<<EOHTML
755 <td width='15%'  scope='row' class='dataLabel'>$displayname</td>
756 <td width='35%' class='dataField'>
757     <input name='{$varname}' id='mass_{$varname}' class='sqsEnabled' autocomplete='off' type='text' value=''>
758     <input name='{$id_name}' id='mass_{$id_name}' type='hidden' value=''>&nbsp;
759     <input title='{$app_strings['LBL_SELECT_BUTTON_TITLE']}'
760         accessKey='{$app_strings['LBL_SELECT_BUTTON_KEY']}'
761         type='button' class='button' value='{$app_strings['LBL_SELECT_BUTTON_LABEL']}' name='button'
762         onclick='open_popup("$mod_type", 600, 400, "", true, false, {$encoded_popup_request_data});'
763         />
764 </td>
765 <script type="text/javascript">
766 <!--
767 if(typeof sqs_objects == 'undefined'){
768     var sqs_objects = new Array;
769 }
770 sqs_objects['MassUpdate_{$varname}'] = $qsName;
771 registerSingleSmartInputListener(document.getElementById('mass_{$varname}'));
772 addToValidateBinaryDependency('MassUpdate', '{$varname}', 'alpha', false, '{$app_strings['ERR_SQS_NO_MATCH_FIELD']} {$app_strings['LBL_ASSIGNED_TO']}','{$id_name}');
773 -->
774 </script>
775 EOHTML;
776         }
777
778
779         /**
780           * Add a generic module popup selection popup window HTML code.
781           * Currently supports Contact and Releases
782           * @param displayname Name to display in the popup window
783           * @param varname name of the variable
784           * @param id_name name of the id in vardef
785           * @param mod_type name of the module, either "Contact" or "Releases" currently
786           */
787         function addGenericModuleID($displayname, $varname, $id_name='', $mod_type){
788                 global $app_strings;
789
790                 if(empty($id_name))
791                 $id_name = strtolower($mod_type)."_id";
792
793                 ///////////////////////////////////////
794                 ///
795                 /// SETUP POPUP
796
797                 $popup_request_data = array(
798                         'call_back_function' => 'set_return',
799                         'form_name' => 'MassUpdate',
800                         'field_to_name_array' => array(
801                                 'id' => "{$id_name}",
802                                 'name' => "{$varname}",
803                                 ),
804                                 );
805
806                                 $json = getJSONobj();
807                                 $encoded_popup_request_data = $json->encode($popup_request_data);
808
809                 $qsName = array(
810                                     'form' => 'MassUpdate',
811                                                 'method' => 'query',
812                         'modules' => array("{$mod_type}"),
813                         'group' => 'or',
814                                                 'field_list' => array('name', 'id'),
815                                                 'populate_list' => array("mass_{$varname}", "mass_{$id_name}"),
816                                                 'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
817                                                 'limit' => '30','no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
818                 $qsName = $json->encode($qsName);
819                                 $img = SugarThemeRegistry::current()->getImageURL("id-ff-select.png");
820                                 //
821                                 ///////////////////////////////////////
822
823             return <<<EOHTML
824 <td width='15%'  scope='row' class='dataLabel'>$displayname</td>
825 <td width='35%' class='dataField'>
826     <input name='{$varname}' id='mass_{$varname}' class='sqsEnabled' autocomplete='off' type='text' value=''>
827     <input name='{$id_name}' id='mass_{$id_name}' type='hidden' value=''>
828         <span class="id-ff multiple">
829     <button title='{$app_strings['LBL_SELECT_BUTTON_TITLE']}'
830         accessKey='{$app_strings['LBL_SELECT_BUTTON_KEY']}'
831         type='button' class='button' value='{$app_strings['LBL_SELECT_BUTTON_LABEL']}' name='button'
832         onclick='open_popup("$mod_type", 600, 400, "", true, false, {$encoded_popup_request_data});'
833         /><img src="$img"></button></span>
834 </td>
835 <script type="text/javascript">
836 <!--
837 if(typeof sqs_objects == 'undefined'){
838     var sqs_objects = new Array;
839 }
840 sqs_objects['MassUpdate_{$varname}'] = $qsName;
841 registerSingleSmartInputListener(document.getElementById('mass_{$varname}'));
842 addToValidateBinaryDependency('MassUpdate', '{$varname}', 'alpha', false, '{$app_strings['ERR_SQS_NO_MATCH_FIELD']} {$app_strings['LBL_ASSIGNED_TO']}','{$id_name}');
843 -->
844 </script>
845 EOHTML;
846         }
847         /**
848           * Add Account selection popup window HTML code
849           * @param displayname Name to display in the popup window
850           * @param varname name of the variable
851           * @param id_name name of the id in vardef
852           */
853         function addAccountID($displayname, $varname, $id_name=''){
854                 global $app_strings;
855
856                 $json = getJSONobj();
857
858                 if(empty($id_name))
859                 $id_name = "account_id";
860
861                 ///////////////////////////////////////
862                 ///
863                 /// SETUP POPUP
864
865                 $popup_request_data = array(
866                         'call_back_function' => 'set_return',
867                         'form_name' => 'MassUpdate',
868                         'field_to_name_array' => array(
869                                 'id' => "{$id_name}",
870                                 'name' => "{$varname}",
871                                 ),
872                                 );
873
874                                 $encoded_popup_request_data = $json->encode($popup_request_data);
875
876                                 //
877                                 ///////////////////////////////////////
878
879                                 $qsParent = array(
880                                                         'form' => 'MassUpdate',
881                                                         'method' => 'query',
882                                                         'modules' => array('Accounts'),
883                                                         'group' => 'or',
884                                                         'field_list' => array('name', 'id'),
885                                                         'populate_list' => array('parent_name', 'parent_id'),
886                                                         'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
887                                                         'order' => 'name',
888                                                         'limit' => '30',
889                                                         'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']
890                                                         );
891                                                         $qsParent['populate_list'] = array('mass_'. $varname, 'mass_' . $id_name);
892                                                         $img = SugarThemeRegistry::current()->getImageURL("id-ff-select.png");
893                                                         $html = '<td scope="row">' . $displayname . " </td>\n"
894                                                         . '<td><input class="sqsEnabled" type="text" autocomplete="off" id="mass_' . $varname .'" name="' . $varname . '" value="" /><input id="mass_' . $id_name . '" type="hidden" name="'
895                                                         . $id_name . '" value="" />&nbsp;<span class="id-ff multiple"><button type="button" name="btn1" class="button" title="'
896                                                         . $app_strings['LBL_SELECT_BUTTON_LABEL'] . '" accesskey="'
897                                                         . $app_strings['LBL_SELECT_BUTTON_KEY'] . '" value="' . $app_strings['LBL_SELECT_BUTTON_LABEL'] . '" onclick='
898                                                         . "'open_popup(\"Accounts\",600,400,\"\",true,false,{$encoded_popup_request_data});' /><img src=\"$img\"></button></span></td>\n";
899                                                         $html .= '<script type="text/javascript" language="javascript">if(typeof sqs_objects == \'undefined\'){var sqs_objects = new Array;}sqs_objects[\'MassUpdate_' . $varname . '\'] = ' .
900                                                         $json->encode($qsParent) . '; registerSingleSmartInputListener(document.getElementById(\'mass_' . $varname . '\'));
901                                         addToValidateBinaryDependency(\'MassUpdate\', \''.$varname.'\', \'alpha\', false, \'' . $app_strings['ERR_SQS_NO_MATCH_FIELD'] . $app_strings['LBL_ACCOUNT'] . '\',\''.$id_name.'\');
902                                         </script>';
903
904                                                         return $html;
905         }
906
907         /**
908           * Add AssignedUser popup window HTML code
909           * @param displayname Name to display in the popup window
910           * @param varname name of the variable
911           */
912         function addAssignedUserID($displayname, $varname){
913                 global $app_strings;
914
915                 $json = getJSONobj();
916
917                 $popup_request_data = array(
918                 'call_back_function' => 'set_return',
919                 'form_name' => 'MassUpdate',
920                 'field_to_name_array' => array(
921                         'id' => 'assigned_user_id',
922                         'user_name' => 'assigned_user_name',
923                         ),
924                         );
925                         $encoded_popup_request_data = $json->encode($popup_request_data);
926                         $qsUser = array(
927                                     'form' => 'MassUpdate',
928                                                 'method' => 'get_user_array', // special method
929                                                 'field_list' => array('user_name', 'id'),
930                                                 'populate_list' => array('assigned_user_name', 'assigned_user_id'),
931                                                 'conditions' => array(array('name'=>'user_name','op'=>'like_custom','end'=>'%','value'=>'')),
932                                                 'limit' => '30','no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
933
934                                                 $qsUser['populate_list'] = array('mass_assigned_user_name', 'mass_assigned_user_id');
935                                                 $img = SugarThemeRegistry::current()->getImageURL("id-ff-select.png");
936                                                 $html = <<<EOQ
937                 <td width="15%" scope="row">$displayname</td>
938                 <td ><input class="sqsEnabled" autocomplete="off" id="mass_assigned_user_name" name='assigned_user_name' type="text" value=""><input id='mass_assigned_user_id' name='assigned_user_id' type="hidden" value="" />
939                 <span class="id-ff multiple"><button title="{$app_strings['LBL_SELECT_BUTTON_TITLE']}" accessKey="{$app_strings['LBL_SELECT_BUTTON_KEY']}" type="button" class="button" value='{$app_strings['LBL_SELECT_BUTTON_LABEL']}' name=btn1
940                                 onclick='open_popup("Users", 600, 400, "", true, false, $encoded_popup_request_data);' /><img src="$img"></button></span>
941                 </td>
942 EOQ;
943                                                 $html .= '<script type="text/javascript" language="javascript">if(typeof sqs_objects == \'undefined\'){var sqs_objects = new Array;}sqs_objects[\'MassUpdate_assigned_user_name\'] = ' .
944                                                 $json->encode($qsUser) . '; registerSingleSmartInputListener(document.getElementById(\'mass_assigned_user_name\'));
945                                 addToValidateBinaryDependency(\'MassUpdate\', \'assigned_user_name\', \'alpha\', false, \'' . $app_strings['ERR_SQS_NO_MATCH_FIELD'] . $app_strings['LBL_ASSIGNED_TO'] . '\',\'assigned_user_id\');
946                                 </script>';
947
948                                                 return $html;
949         }
950         /**
951           * Add Status selection popup window HTML code
952           * @param displayname Name to display in the popup window
953           * @param varname name of the variable
954           * @param options array of options for status
955           */
956         function addStatus($displayname, $varname, $options){
957                 global $app_strings, $app_list_strings;
958
959                 // cn: added "mass_" to the id tag to diffentieate from the status id in StoreQuery
960                 $html = '<td scope="row" width="15%">'.$displayname.'</td><td>';
961                 if(is_array($options)){
962                         if(!isset($options['']) && !isset($options['0'])){
963                            $new_options = array();
964                            $new_options[''] = '';
965                            foreach($options as $key=>$value) {
966                                    $new_options[$key] = $value;
967                            }
968                            $options = $new_options;
969                         }
970                         $options = get_select_options_with_id_separate_key($options, $options, '', true);;
971                         $html .= '<select id="mass_'.$varname.'" name="'.$varname.'">'.$options.'</select>';
972                 }else{
973                         $html .= $options;
974                 }
975                 $html .= '</td>';
976                 return $html;
977         }
978
979 /**
980           * Add Status selection popup window HTML code
981           * @param displayname Name to display in the popup window
982           * @param varname name of the variable
983           * @param options array of options for status
984           */
985         function addBool($displayname, $varname){
986                 global $app_strings, $app_list_strings;
987                 return $this->addStatus($displayname, $varname, $app_list_strings['checkbox_dom']);
988         }
989         function addStatusMulti($displayname, $varname, $options){
990                 global $app_strings, $app_list_strings;
991
992                 if(!isset($options['']) && !isset($options['0'])){
993                    $new_options = array();
994                    $new_options[''] = '';
995                    foreach($options as $key=>$value) {
996                            $new_options[$key] = $value;
997                    }
998                    $options = $new_options;
999                 }
1000                 $options = get_select_options_with_id_separate_key($options, $options, '', true);;
1001
1002                 // cn: added "mass_" to the id tag to diffentieate from the status id in StoreQuery
1003                 $html = '<td scope="row" width="15%">'.$displayname.'</td>
1004                          <td><select id="mass_'.$varname.'" name="'.$varname.'[]" size="5" MULTIPLE>'.$options.'</select></td>';
1005                 return $html;
1006         }
1007         /**
1008           * Add Date selection popup window HTML code
1009           * @param displayname Name to display in the popup window
1010           * @param varname name of the variable
1011           */
1012         function addDate($displayname, $varname){
1013                 global $timedate;
1014                 $userformat = '('. $timedate->get_user_date_format().')';
1015                 $cal_dateformat = $timedate->get_cal_date_format();
1016                 global $app_strings, $app_list_strings, $theme;
1017
1018                 $javascriptend = <<<EOQ
1019                  <script type="text/javascript">
1020                 Calendar.setup ({
1021                         inputField : "${varname}jscal_field", daFormat : "$cal_dateformat", ifFormat : "$cal_dateformat", showsTime : false, button : "${varname}jscal_trigger", singleClick : true, step : 1, weekNumbers:false
1022                 });
1023                 </script>
1024 EOQ;
1025         $jscalendarImage = SugarThemeRegistry::current()->getImageURL('jscalendar.gif');
1026                 $html = <<<EOQ
1027         <td scope="row" width="20%">$displayname</td>
1028         <td class='dataField' width="30%"><input onblur="parseDate(this, '$cal_dateformat')" type="text" name='$varname' size="12" id='{$varname}jscal_field' maxlength='10' value="">
1029     <img src="$jscalendarImage" id="{$varname}jscal_trigger" align="absmiddle" title="{$app_strings['LBL_MASSUPDATE_DATE']}" alt='{$app_strings['LBL_MASSUPDATE_DATE']}'>&nbsp;<span class="dateFormat">$userformat</span>
1030         $javascriptend</td>
1031         <script> addToValidate('MassUpdate','$varname','date',false,'$displayname');</script>
1032 EOQ;
1033                 return $html;
1034
1035         }
1036
1037         function addRadioenumItem($name, $value, $output) {
1038                 $_output = '';
1039                 $_output .= '<label>';
1040                 $_output .= '<input type="radio" name="'
1041                 . $name . '" value="'
1042                 . $value. '"';
1043
1044             $_output .= ' />' . ($output == '' ? $GLOBALS['app_strings']['LBL_LINK_NONE'] : $output);
1045             $_output .= '</label><br />';
1046             return $_output;
1047         }
1048
1049         function addRadioenum($displayname, $varname, $options){
1050                  foreach ($options as $_key=>$_val){
1051             $_html_result[] = $this->addRadioenumItem($varname, $_key, $_val);
1052         }
1053
1054                 $html = '<td scope="row" width="15%">'.$displayname.'</td>
1055                          <td>'.implode("\n",$_html_result).'</td>';
1056                 return $html;
1057         }
1058         /**
1059           * Add Datetime selection popup window HTML code
1060           * @param displayname Name to display in the popup window
1061           * @param varname name of the variable
1062           */
1063         function addDatetime($displayname, $varname){
1064                 global $timedate;
1065                 $userformat = $timedate->get_user_time_format();
1066                 $cal_dateformat = $timedate->get_cal_date_format();
1067                 global $app_strings, $app_list_strings, $theme;
1068                 $jscalendarImage = SugarThemeRegistry::current()->getImageURL('jscalendar.gif');
1069
1070                 $javascriptend = <<<EOQ
1071                  <script type="text/javascript">
1072                 Calendar.setup ({
1073                         inputField : "{$varname}_date",
1074                         daFormat : "$cal_dateformat",
1075                         ifFormat : "$cal_dateformat",
1076                         showsTime : false,
1077                         button : "{$varname}_trigger",
1078                         singleClick : true,
1079                         step : 1,
1080                         weekNumbers:false
1081                 });
1082                 </script>
1083 EOQ;
1084
1085                 $html = <<<EOQ
1086                 <td scope="row" width="20%">$displayname</td>
1087                 <td class='dataField' width="30%"><input onblur="parseDate(this, '$cal_dateformat')" type="text" name='$varname' size="12" id='{$varname}_date' maxlength='10' value="">
1088                 <img border="0" src="$jscalendarImage" alt='{$app_strings['LBL_MASSUPDATE_DATE']}' id="{$varname}_trigger" title="{$app_strings['LBL_MASSUPDATE_DATE']}"  align="absmiddle">&nbsp;$javascriptend
1089
1090                 <span id="{$varname}_time_section"></span>
1091                 </td>
1092                 <input type="hidden" id="{$varname}" name="{$varname}">
1093                 <script type="text/javascript" src="include/SugarFields/Fields/Datetimecombo/Datetimecombo.js"></script>
1094                 <script type="text/javascript">
1095                 var combo_{$varname} = new Datetimecombo(" ", "$varname", "$userformat", '','','',1);
1096                 //Render the remaining widget fields
1097                 text = combo_{$varname}.html('');
1098                 document.getElementById('{$varname}_time_section').innerHTML = text;
1099
1100                 //Call eval on the update function to handle updates to calendar picker object
1101                 eval(combo_{$varname}.jsscript(''));
1102
1103                 function update_{$varname}_available() {
1104                       YAHOO.util.Event.onAvailable("{$varname}_date", this.handleOnAvailable, this);
1105                 }
1106
1107                 update_{$varname}_available.prototype.handleOnAvailable = function(me) {
1108                         Calendar.setup ({
1109                         onClose : update_{$varname},
1110                         inputField : "{$varname}_date",
1111                         daFormat : "$cal_dateformat",
1112                         ifFormat : "$cal_dateformat",
1113                         button : "{$varname}_trigger",
1114                         singleClick : true,
1115                         step : 1,
1116                         weekNumbers:false
1117                         });
1118
1119                         //Call update for first time to round hours and minute values
1120                         combo_{$varname}.update();
1121                 }
1122
1123                 var obj_{$varname} = new update_{$varname}_available();
1124                 </script>
1125
1126                 <script> addToValidate('MassUpdate','{$varname}_date','date',false,'$displayname');
1127                 addToValidateBinaryDependency('MassUpdate', '{$varname}_hours', 'alpha', false, "{$app_strings['ERR_MISSING_REQUIRED_FIELDS']}", '{$varname}_date');
1128                 addToValidateBinaryDependency('MassUpdate', '{$varname}_minutes', 'alpha', false, "{$app_strings['ERR_MISSING_REQUIRED_FIELDS']}", '{$varname}_date');
1129                 addToValidateBinaryDependency('MassUpdate', '{$varname}_meridiem', 'alpha', false, "{$app_strings['ERR_MISSING_REQUIRED_FIELDS']}", '{$varname}_date');
1130                 </script>
1131
1132 EOQ;
1133                 return $html;
1134         }
1135
1136         function date_to_dateTime($field, $value) {
1137                 global $timedate;
1138             //Check if none was set
1139         if (isset($this->sugarbean->field_defs[$field]['group'])) {
1140             $group =  $this->sugarbean->field_defs[$field]['group'];
1141             if (isset($this->sugarbean->field_defs[$group."_flag"]) && isset($_POST[$group."_flag"])
1142                 && $_POST[$group."_flag"] == 1) {
1143                 return "";
1144             }
1145         }
1146
1147         $oldDateTime = $this->sugarbean->$field;
1148         $oldTime = explode(" ", $oldDateTime);
1149         if (isset($oldTime[1])) {
1150                 $oldTime = $oldTime[1];
1151         } else {
1152                 $oldTime = $timedate->to_display_time($timedate->get_gmt_db_datetime());
1153         }
1154         $value = explode(" ", $value);
1155         $value = $value[0];
1156             return $value." ".$oldTime;
1157         }
1158
1159         function checkClearField($field, $value) {
1160             if ($value == 1 && strpos($field, '_flag')) {
1161                 $fName = substr($field, -5);
1162             if (isset($this->sugarbean->field_defs[$field]['group'])) {
1163                 $group =  $this->sugarbean->field_defs[$field]['group'];
1164                 if (isset($this->sugarbean->field_defs[$group])) {
1165                     $_POST[$group] = "";
1166                 }
1167             }
1168             }
1169         }
1170
1171     function generateSearchWhere($module, $query) {//this function is similar with function prepareSearchForm() in view.list.php
1172         $seed = loadBean($module);
1173         $this->use_old_search = true;
1174         if(file_exists('modules/'.$module.'/SearchForm.html')){
1175             if(file_exists('modules/' . $module . '/metadata/SearchFields.php')) {
1176                 require_once('include/SearchForm/SearchForm.php');
1177                 $searchForm = new SearchForm($module, $seed);
1178             }
1179             elseif(!empty($_SESSION['export_where'])) { //bug 26026, sometimes some module doesn't have a metadata/SearchFields.php, the searchfrom is generated in the ListView.php.
1180             //So currently massupdate will not gernerate the where sql. It will use the sql stored in the SESSION. But this will cause bug 24722, and it cannot be avoided now.
1181                 $where = $_SESSION['export_where'];
1182                 $whereArr = explode (" ", trim($where));
1183                 if ($whereArr[0] == trim('where')) {
1184                     $whereClean = array_shift($whereArr);
1185                 }
1186                 $this->where_clauses = implode(" ", $whereArr);
1187                 return;
1188             }
1189             else {
1190                 $this->where_clauses = '';
1191                 return;
1192             }
1193         }
1194         else{
1195             $this->use_old_search = false;
1196             require_once('include/SearchForm/SearchForm2.php');
1197
1198             if(file_exists('custom/modules/'.$module.'/metadata/metafiles.php')){
1199                 require('custom/modules/'.$module.'/metadata/metafiles.php');
1200             }elseif(file_exists('modules/'.$module.'/metadata/metafiles.php')){
1201                 require('modules/'.$module.'/metadata/metafiles.php');
1202             }
1203
1204             if (file_exists('custom/modules/'.$module.'/metadata/searchdefs.php'))
1205             {
1206                 require_once('custom/modules/'.$module.'/metadata/searchdefs.php');
1207             }
1208             elseif (!empty($metafiles[$module]['searchdefs']))
1209             {
1210                 require_once($metafiles[$module]['searchdefs']);
1211             }
1212             elseif (file_exists('modules/'.$module.'/metadata/searchdefs.php'))
1213             {
1214                 require_once('modules/'.$module.'/metadata/searchdefs.php');
1215             }
1216
1217
1218             if(!empty($metafiles[$module]['searchfields']))
1219                 require_once($metafiles[$module]['searchfields']);
1220             elseif(file_exists('modules/'.$module.'/metadata/SearchFields.php'))
1221                 require_once('modules/'.$module.'/metadata/SearchFields.php');
1222             if(empty($searchdefs) || empty($searchFields)) {
1223                $this->where_clauses = ''; //for some modules, such as iframe, it has massupdate, but it doesn't have search function, the where sql should be empty.
1224                return;
1225             }
1226             $searchForm = new SearchForm($seed, $module);
1227             $searchForm->setup($searchdefs, $searchFields, 'include/SearchForm/tpls/SearchFormGeneric.tpl');
1228         }
1229         $searchForm->populateFromArray(unserialize(base64_decode($query)));
1230         $this->searchFields = $searchForm->searchFields;
1231         $where_clauses = $searchForm->generateSearchWhere(true, $module);
1232         if (count($where_clauses) > 0 ) {
1233             $this->where_clauses = '('. implode(' ) AND ( ', $where_clauses) . ')';
1234             $GLOBALS['log']->info("MassUpdate Where Clause: {$this->where_clauses}");
1235         }
1236     }
1237
1238     /**
1239      * This is kinda a hack how it is implimented, but will tell us whether or not a focus has
1240      * fields for Mass Update
1241      *
1242      * @return bool
1243      */
1244     public function doMassUpdateFieldsExistForFocus()
1245     {
1246         static $banned = array('date_modified'=>1, 'date_entered'=>1, 'created_by'=>1, 'modified_user_id'=>1, 'deleted'=>1,'modified_by_name'=>1,);
1247         foreach($this->sugarbean->field_defs as $field) {
1248             if(!isset($banned[$field['name']]) && (!isset($field['massupdate']) || !empty($field['massupdate']))){
1249                 if(isset($field['type']) && $field['type'] == 'relate' && isset($field['id_name']) && $field['id_name'] == 'assigned_user_id')
1250                     $field['type'] = 'assigned_user_name';
1251                 if(isset($field['custom_type']))$field['type'] = $field['custom_type'];
1252                 if(isset($field['type']))
1253                 {
1254                     switch($field["type"]){
1255                     case "relate":
1256                     case "parent":
1257                     case "int":
1258                     case "contact_id":
1259                     case "assigned_user_name":
1260                     case "account_id":
1261                     case "account_name":
1262                     case "bool":
1263                     case "enum":
1264                     case "multienum":
1265                     case "radioenum":
1266                     case "datetimecombo":
1267                     case "datetime":
1268                     case "date":
1269                         return true;
1270                         break;
1271                     }
1272                 }
1273             }
1274         }
1275
1276         return false;
1277     }
1278 }
1279
1280 ?>