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