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