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