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