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