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