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