]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/export_utils.php
Release 6.5.16
[Github/sugarcrm.git] / include / export_utils.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-2013 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  * Description:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  * *******************************************************************************/
44
45 /**
46  * gets the system default delimiter or an user-preference based override
47  * @return string the delimiter
48  */
49 function getDelimiter() {
50     global $sugar_config;
51     global $current_user;
52
53     if (!empty($sugar_config['export_excel_compatible'])) {
54         return "\t";
55     }
56
57     $delimiter = ','; // default to "comma"
58     $userDelimiter = $current_user->getPreference('export_delimiter');
59     $delimiter = empty($sugar_config['export_delimiter']) ? $delimiter : $sugar_config['export_delimiter'];
60     $delimiter = empty($userDelimiter) ? $delimiter : $userDelimiter;
61
62     return $delimiter;
63 }
64
65
66 /**
67  * builds up a delimited string for export
68  * @param string type the bean-type to export
69  * @param array records an array of records if coming directly from a query
70  * @return string delimited string for export
71  */
72 function export($type, $records = null, $members = false, $sample=false) {
73     global $locale;
74     global $beanList;
75     global $beanFiles;
76     global $current_user;
77     global $app_strings;
78     global $app_list_strings;
79     global $timedate;
80     global $mod_strings;
81     global $current_language;
82     $sampleRecordNum = 5;
83     $contact_fields = array(
84         "id"=>"Contact ID"
85         ,"lead_source"=>"Lead Source"
86         ,"date_entered"=>"Date Entered"
87         ,"date_modified"=>"Date Modified"
88         ,"first_name"=>"First Name"
89         ,"last_name"=>"Last Name"
90         ,"salutation"=>"Salutation"
91         ,"birthdate"=>"Lead Source"
92         ,"do_not_call"=>"Do Not Call"
93         ,"email_opt_out"=>"Email Opt Out"
94         ,"title"=>"Title"
95         ,"department"=>"Department"
96         ,"birthdate"=>"Birthdate"
97         ,"do_not_call"=>"Do Not Call"
98         ,"phone_home"=>"Phone (Home)"
99         ,"phone_mobile"=>"Phone (Mobile)"
100         ,"phone_work"=>"Phone (Work)"
101         ,"phone_other"=>"Phone (Other)"
102         ,"phone_fax"=>"Fax"
103         ,"email1"=>"Email"
104         ,"email2"=>"Email (Other)"
105         ,"assistant"=>"Assistant"
106         ,"assistant_phone"=>"Assistant Phone"
107         ,"primary_address_street"=>"Primary Address Street"
108         ,"primary_address_city"=>"Primary Address City"
109         ,"primary_address_state"=>"Primary Address State"
110         ,"primary_address_postalcode"=>"Primary Address Postalcode"
111         ,"primary_address_country"=>"Primary Address Country"
112         ,"alt_address_street"=>"Other Address Street"
113         ,"alt_address_city"=>"Other Address City"
114         ,"alt_address_state"=>"Other Address State"
115         ,"alt_address_postalcode"=>"Other Address Postalcode"
116         ,"alt_address_country"=>"Other Address Country"
117         ,"description"=>"Description"
118     );
119
120     $account_fields = array(
121         "id"=>"Account ID",
122         "name"=>"Account Name",
123         "website"=>"Website",
124         "industry"=>"Industry",
125         "account_type"=>"Type",
126         "ticker_symbol"=>"Ticker Symbol",
127         "employees"=>"Employees",
128         "ownership"=>"Ownership",
129         "phone_office"=>"Phone",
130         "phone_fax"=>"Fax",
131         "phone_alternate"=>"Other Phone",
132         "email1"=>"Email",
133         "email2"=>"Other Email",
134         "rating"=>"Rating",
135         "sic_code"=>"SIC Code",
136         "annual_revenue"=>"Annual Revenue",
137         "billing_address_street"=>"Billing Address Street",
138         "billing_address_city"=>"Billing Address City",
139         "billing_address_state"=>"Billing Address State",
140         "billing_address_postalcode"=>"Billing Address Postalcode",
141         "billing_address_country"=>"Billing Address Country",
142         "shipping_address_street"=>"Shipping Address Street",
143         "shipping_address_city"=>"Shipping Address City",
144         "shipping_address_state"=>"Shipping Address State",
145         "shipping_address_postalcode"=>"Shipping Address Postalcode",
146         "shipping_address_country"=>"Shipping Address Country",
147         "description"=>"Description"
148     );
149     //Array of fields that should not be exported, and are only used for logic
150     $remove_from_members = array("ea_deleted", "ear_deleted", "primary_address");
151     $focus = 0;
152
153     $bean = $beanList[$type];
154     require_once($beanFiles[$bean]);
155     $focus = new $bean;
156     $searchFields = array();
157     $db = DBManagerFactory::getInstance();
158
159     if($records) {
160         $records = explode(',', $records);
161         $records = "'" . implode("','", $records) . "'";
162         $where = "{$focus->table_name}.id in ($records)";
163     } elseif (isset($_REQUEST['all']) ) {
164         $where = '';
165     } else {
166         if(!empty($_REQUEST['current_post'])) {
167             $ret_array = generateSearchWhere($type, $_REQUEST['current_post']);
168
169             $where = $ret_array['where'];
170             $searchFields = $ret_array['searchFields'];
171         } else {
172             $where = '';
173         }
174     }
175     $order_by = "";
176     if($focus->bean_implements('ACL')){
177         if(!ACLController::checkAccess($focus->module_dir, 'export', true)){
178             ACLController::displayNoAccess();
179             sugar_die('');
180         }
181         if(ACLController::requireOwner($focus->module_dir, 'export')){
182             if(!empty($where)){
183                 $where .= ' AND ';
184             }
185             $where .= $focus->getOwnerWhere($current_user->id);
186         }
187
188     }
189     // Export entire list was broken because the where clause already has "where" in it
190     // and when the query is built, it has a "where" as well, so the query was ill-formed.
191     // Eliminating the "where" here so that the query can be constructed correctly.
192     if($members == true){
193            $query = $focus->create_export_members_query($records);
194     }else{
195         $beginWhere = substr(trim($where), 0, 5);
196         if ($beginWhere == "where")
197             $where = substr(trim($where), 5, strlen($where));
198         $ret_array = create_export_query_relate_link_patch($type, $searchFields, $where);
199         if(!empty($ret_array['join'])) {
200             $query = $focus->create_export_query($order_by,$ret_array['where'],$ret_array['join']);
201         } else {
202             $query = $focus->create_export_query($order_by,$ret_array['where']);
203         }
204     }
205
206     $result = '';
207     $populate = false;
208     if($sample) {
209        $result = $db->limitQuery($query, 0, $sampleRecordNum, true, $app_strings['ERR_EXPORT_TYPE'].$type.": <BR>.".$query);
210         if( $focus->_get_num_rows_in_query($query)<1 ){
211             $populate = true;
212         }
213     }
214     else {
215         $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'].$type.": <BR>.".$query);
216     }
217
218
219     $fields_array = $db->getFieldsArray($result,true);
220
221     //set up the order on the header row
222     $fields_array = get_field_order_mapping($focus->module_dir, $fields_array);
223
224
225
226     //set up labels to be used for the header row
227     $field_labels = array();
228     foreach($fields_array as $key=>$dbname){
229         //Remove fields that are only used for logic
230         if($members && (in_array($dbname, $remove_from_members)))
231             continue;
232         
233         //default to the db name of label does not exist
234         $field_labels[$key] = translateForExport($dbname,$focus);
235     }
236
237     $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
238     if ($locale->getExportCharset() == 'UTF-8' &&
239         ! preg_match('/macintosh|mac os x|mac_powerpc/i', $user_agent)) // Bug 60377 - Mac Excel doesn't support UTF-8
240     {
241         //Bug 55520 - add BOM to the exporting CSV so any symbols are displayed correctly in Excel
242         $BOM = "\xEF\xBB\xBF";
243         $content = $BOM;
244     }
245     else
246     {
247         $content = '';
248     }
249
250     // setup the "header" line with proper delimiters
251     $content .= "\"".implode("\"".getDelimiter()."\"", array_values($field_labels))."\"\r\n";
252     $pre_id = '';
253
254     if($populate){
255         //this is a sample request with no data, so create fake datarows
256          $content .= returnFakeDataRow($focus,$fields_array,$sampleRecordNum);
257     }else{
258         $records = array();
259
260         //process retrieved record
261         while($val = $db->fetchByAssoc($result, false)) {
262
263             //order the values in the record array
264             $val = get_field_order_mapping($focus->module_dir,$val);
265
266             $new_arr = array();
267                 if($members){
268                         if($pre_id == $val['id'])
269                                 continue;
270                         if($val['ea_deleted']==1 || $val['ear_deleted']==1){
271                                 $val['primary_email_address'] = '';
272                         }
273                         unset($val['ea_deleted']);
274                         unset($val['ear_deleted']);
275                         unset($val['primary_address']);
276                 }
277                 $pre_id = $val['id'];
278
279                 foreach ($val as $key => $value)
280                 {
281             //getting content values depending on their types
282             $fieldNameMapKey = $fields_array[$key];
283
284             if (isset($focus->field_name_map[$fieldNameMapKey])  && $focus->field_name_map[$fieldNameMapKey]['type'])
285             {
286                 $fieldType = $focus->field_name_map[$fieldNameMapKey]['type'];
287                 switch ($fieldType)
288                 {
289                     //if our value is a currency field, then apply the users locale
290                     case 'currency':
291                         require_once('modules/Currencies/Currency.php');
292                         $value = currency_format_number($value);
293                         break;
294
295                     //if our value is a datetime field, then apply the users locale
296                     case 'datetime':
297                     case 'datetimecombo':
298                         $value = $timedate->to_display_date_time($db->fromConvert($value, 'datetime'));
299                         $value = preg_replace('/([pm|PM|am|AM]+)/', ' \1', $value);
300                         break;
301
302                     //kbrill Bug #16296
303                     case 'date':
304                         $value = $timedate->to_display_date($db->fromConvert($value, 'date'), false);
305                         break;
306
307                     // Bug 32463 - Properly have multienum field translated into something useful for the client
308                     case 'multienum':
309                         $value = str_replace("^","",$value);
310                         if (isset($focus->field_name_map[$fields_array[$key]]['options']) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']]) )
311                         {
312                             $valueArray = explode(",",$value);
313                             foreach ($valueArray as $multikey => $multivalue )
314                             {
315                                 if (isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue]) )
316                                 {
317                                     $valueArray[$multikey] = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue];
318                                 }
319                             }
320                             $value = implode(",",$valueArray);
321                         }
322                         break;
323                 }
324             }
325
326
327             // Keep as $key => $value for post-processing
328             $new_arr[$key] = preg_replace("/\"/","\"\"", $value);
329         }
330
331         // Use Bean ID as key for records
332         $records[$pre_id] = $new_arr;
333     }
334
335         // Check if we're going to export non-primary emails
336         if ($focus->hasEmails() && in_array('email_addresses_non_primary', $fields_array))
337         {
338             // $records keys are bean ids
339             $keys = array_keys($records);
340
341             // Split the ids array into chunks of size 100
342             $chunks = array_chunk($keys, 100);
343
344             foreach ($chunks as $chunk)
345             {
346                 // Pick all the non-primary mails for the chunk
347                 $query =
348                     "
349                       SELECT eabr.bean_id, ea.email_address
350                       FROM email_addr_bean_rel eabr
351                       LEFT JOIN email_addresses ea ON ea.id = eabr.email_address_id
352                       WHERE eabr.bean_module = '{$focus->module_dir}'
353                       AND eabr.primary_address = '0'
354                       AND eabr.bean_id IN ('" . implode("', '", $chunk) . "')
355                       AND eabr.deleted != '1'
356                       ORDER BY eabr.bean_id, eabr.reply_to_address, eabr.primary_address DESC
357                     ";
358
359                 $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
360
361                 while ($val = $db->fetchByAssoc($result, false)) {
362                     if (empty($records[$val['bean_id']]['email_addresses_non_primary'])) {
363                         $records[$val['bean_id']]['email_addresses_non_primary'] = $val['email_address'];
364                     } else {
365                         // No custom non-primary mail delimeter yet, use semi-colon
366                         $records[$val['bean_id']]['email_addresses_non_primary'] .= ';' . $val['email_address'];
367                     }
368                 }
369             }
370         }
371
372         foreach($records as $record)
373         {
374             $line = implode("\"" . getDelimiter() . "\"", $record);
375             $line = "\"" . $line;
376             $line .= "\"\r\n";
377             $content .= $line;
378         }
379
380     }
381
382         return $content;
383
384 }
385
386
387 function generateSearchWhere($module, $query) {//this function is similar with function prepareSearchForm() in view.list.php
388     $seed = loadBean($module);
389     if(file_exists('modules/'.$module.'/SearchForm.html')){
390         if(file_exists('modules/' . $module . '/metadata/SearchFields.php')) {
391             require_once('include/SearchForm/SearchForm.php');
392             $searchForm = new SearchForm($module, $seed);
393         }
394         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.
395         // Currently, massupdate will not generate the where sql. It will use the sql stored in the SESSION. But this will cause bug 24722, and it cannot be avoided now.
396             $where = $_SESSION['export_where'];
397             $whereArr = explode (" ", trim($where));
398             if ($whereArr[0] == trim('where')) {
399                 $whereClean = array_shift($whereArr);
400             }
401             $where = implode(" ", $whereArr);
402             //rrs bug: 31329 - previously this was just returning $where, but the problem is the caller of this function
403             //expects the results in an array, not just a string. So rather than fixing the caller, I felt it would be best for
404             //the function to return the results in a standard format.
405             $ret_array['where'] = $where;
406             $ret_array['searchFields'] =array();
407             return $ret_array;
408         }
409         else {
410             return;
411         }
412     }
413     else{
414         require_once('include/SearchForm/SearchForm2.php');
415
416         if(file_exists('custom/modules/'.$module.'/metadata/metafiles.php')){
417             require('custom/modules/'.$module.'/metadata/metafiles.php');
418         }elseif(file_exists('modules/'.$module.'/metadata/metafiles.php')){
419             require('modules/'.$module.'/metadata/metafiles.php');
420         }
421
422         if (file_exists('custom/modules/'.$module.'/metadata/searchdefs.php'))
423         {
424             require_once('custom/modules/'.$module.'/metadata/searchdefs.php');
425         }
426         elseif (!empty($metafiles[$module]['searchdefs']))
427         {
428             require_once($metafiles[$module]['searchdefs']);
429         }
430         elseif (file_exists('modules/'.$module.'/metadata/searchdefs.php'))
431         {
432             require_once('modules/'.$module.'/metadata/searchdefs.php');
433         }
434
435         //fixing bug #48483: Date Range search on custom date field then export ignores range filter
436         // first of all custom folder should be checked
437         if(file_exists('custom/modules/'.$module.'/metadata/SearchFields.php'))
438         {
439             require_once('custom/modules/'.$module.'/metadata/SearchFields.php');
440         }
441         elseif(!empty($metafiles[$module]['searchfields']))
442         {
443             require_once($metafiles[$module]['searchfields']);
444         }
445         elseif(file_exists('modules/'.$module.'/metadata/SearchFields.php'))
446         {
447             require_once('modules/'.$module.'/metadata/SearchFields.php');
448         }
449         if(empty($searchdefs) || empty($searchFields)) {
450            //for some modules, such as iframe, it has massupdate, but it doesn't have search function, the where sql should be empty.
451             return;
452         }
453         $searchForm = new SearchForm($seed, $module);
454         $searchForm->setup($searchdefs, $searchFields, 'SearchFormGeneric.tpl');
455     }
456     $searchForm->populateFromArray(unserialize(base64_decode($query)));
457     $where_clauses = $searchForm->generateSearchWhere(true, $module);
458     if (count($where_clauses) > 0 )$where = '('. implode(' ) AND ( ', $where_clauses) . ')';
459         $GLOBALS['log']->info("Export Where Clause: {$where}");
460     $ret_array['where'] = $where;
461     $ret_array['searchFields'] = $searchForm->searchFields;
462     return $ret_array;
463 }
464 /**
465   * calls export method to build up a delimited string and some sample instructional text on how to use this file
466   * @param string type the bean-type to export
467   * @return string delimited string for export with some tutorial text
468   */
469      function exportSample($type) {
470          global $app_strings;
471
472          //first grab the
473          $_REQUEST['all']=true;
474
475          //retrieve the export content
476          $content = export($type, null, false, true);
477
478          // Add a new row and add details on removing the sample data
479          // Our Importer will stop after he gets to the new row, ignoring the text below 
480          return $content . "\n" . $app_strings['LBL_IMPORT_SAMPLE_FILE_TEXT'];
481
482      }
483  //this function will take in the bean and field mapping and return a proper value
484  function returnFakeDataRow($focus,$field_array,$rowsToReturn = 5){
485
486     if(empty($focus) || empty($field_array))
487      return ;
488
489      //include the file that defines $sugar_demodata
490      include('install/demoData.en_us.php');
491
492     $person_bean = false;
493     if( isset($focus->first_name)){
494         $person_bean = true;
495     }
496
497      global $timedate;
498      $returnContent = '';
499      $counter = 0;
500      $new_arr = array();
501
502      //iterate through the record creation process as many times as defined.  Each iteration will create a new row
503      while($counter < $rowsToReturn){
504          $counter++;
505          //go through each field and populate with dummy data if possible
506          foreach($field_array as $field_name){
507
508             if(empty($focus->field_name_map[$field_name]) || empty($focus->field_name_map[$field_name]['type'])){
509                 //type is not set, fill in with empty string and continue;
510                 $returnContent .= '"",';
511                 continue;
512             }
513             $field = $focus->field_name_map[$field_name];
514                          //fill in value according to type
515             $type = $field['type'];
516
517              switch ($type) {
518
519                  case "id":
520                  case "assigned_user_name":
521                      //return new guid string
522                     $returnContent .= '"'.create_guid().'",';
523                      break;
524                  case "int":
525                      //return random number`
526                     $returnContent .= '"'.mt_rand(0,4).'",';
527                      break;
528                  case "name":
529                      //return first, last, user name, or random name string
530                      if($field['name'] == 'first_name'){
531                          $count = count($sugar_demodata['first_name_array']) - 1;
532                         $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'",';
533                      }elseif($field['name'] == 'last_name'){
534                          $count = count($sugar_demodata['last_name_array']) - 1;
535                          $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'",';
536                      }elseif($field['name'] == 'user_name'){
537                        $count = count($sugar_demodata['first_name_array']) - 1;
538                         $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'_'.mt_rand(1,111).'",';
539                      }else{
540                          //return based on bean
541                          if($focus->module_dir =='Accounts'){
542                              $count = count($sugar_demodata['company_name_array']) - 1;
543                             $returnContent .= '"'.$sugar_demodata['company_name_array'][mt_rand(0,$count)].'",';
544
545                          }elseif($focus->module_dir =='Bugs'){
546                              $count = count($sugar_demodata['bug_seed_names']) - 1;
547                             $returnContent .= '"'.$sugar_demodata['bug_seed_names'][mt_rand(0,$count)].'",';
548                          }elseif($focus->module_dir =='Notes'){
549                              $count = count($sugar_demodata['note_seed_names_and_Descriptions']) - 1;
550                             $returnContent .= '"'.$sugar_demodata['note_seed_names_and_Descriptions'][mt_rand(0,$count)].'",';
551
552                          }elseif($focus->module_dir =='Calls'){
553                               $count = count($sugar_demodata['call_seed_data_names']) - 1;
554                             $returnContent .= '"'.$sugar_demodata['call_seed_data_names'][mt_rand(0,$count)].'",';
555
556                          }elseif($focus->module_dir =='Tasks'){
557                              $count = count($sugar_demodata['task_seed_data_names']) - 1;
558                            $returnContent .= '"'.$sugar_demodata['task_seed_data_names'][mt_rand(0,$count)].'",';
559
560                          }elseif($focus->module_dir =='Meetings'){
561                              $count = count($sugar_demodata['meeting_seed_data_names']) - 1;
562                            $returnContent .= '"'.$sugar_demodata['meeting_seed_data_names'][mt_rand(0,$count)].'",';
563
564                          }elseif($focus->module_dir =='ProductCategories'){
565                              $count = count($sugar_demodata['productcategory_seed_data_names']) - 1;
566                            $returnContent .= '"'.$sugar_demodata['productcategory_seed_data_names'][mt_rand(0,$count)].'",';
567
568
569                          }elseif($focus->module_dir =='ProductTypes'){
570                              $count = count($sugar_demodata['producttype_seed_data_names']) - 1;
571                            $returnContent .= '"'.$sugar_demodata['producttype_seed_data_names'][mt_rand(0,$count)].'",';
572
573
574                          }elseif($focus->module_dir =='ProductTemplates'){
575                              $count = count($sugar_demodata['producttemplate_seed_data']) - 1;
576                            $returnContent .= '"'.$sugar_demodata['producttemplate_seed_data'][mt_rand(0,$count)].'",';
577
578                          }else{
579                            $returnContent .= '"Default Name for '.$focus->module_dir.'",';
580
581                          }
582
583                      }
584                     break;
585                  case "relate":
586                      if($field['name'] == 'team_name'){
587                          //apply team names and user_name
588                          $teams_count = count($sugar_demodata['teams']) - 1;
589                          $users_count = count($sugar_demodata['users']) - 1;
590
591                      $returnContent .= '"'.$sugar_demodata['teams'][mt_rand(0,$teams_count)]['name'].','.$sugar_demodata['users'][mt_rand(0,$users_count)]['user_name'].'",';
592
593                      }else{
594                          //apply GUID
595                          $returnContent .= '"'.create_guid().'",';
596                      }
597                      break;
598                  case "bool":
599                      //return 0 or 1
600                      $returnContent .= '"'.mt_rand(0,1).'",';
601                      break;
602
603                  case "text":
604                      //return random text
605                      $returnContent .= '"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna",';
606                      break;
607
608                  case "team_list":
609                      $teams_count = count($sugar_demodata['teams']) - 1;
610                      //give fake team names (East,West,North,South)
611                      $returnContent .= '"'.$sugar_demodata['teams'][mt_rand(0,$teams_count)]['name'].'",';
612                      break;
613
614                  case "date":
615                      //return formatted date
616                      $timeStamp = strtotime('now');
617                      $value =    date($timedate->dbDayFormat, $timeStamp);
618                      $returnContent .= '"'.$timedate->to_display_date_time($value).'",';
619                      break;
620
621                  case "datetime":
622                  case "datetimecombo":
623                      //return formatted date time
624                      $timeStamp = strtotime('now');
625                      //Start with db date
626                      $value =    date($timedate->dbDayFormat.' '.$timedate->dbTimeFormat, $timeStamp);
627                      //use timedate to convert to user display format
628                      $value = $timedate->to_display_date_time($value);
629                      //finally forma the am/pm to have a space so it can be recognized as a date field in excel
630                      $value = preg_replace('/([pm|PM|am|AM]+)/', ' \1', $value);
631                      $returnContent .= '"'.$value.'",';
632
633                      break;
634                 case "phone":
635                     $value = '('.mt_rand(300,999).') '.mt_rand(300,999).'-'.mt_rand(1000,9999);
636                       $returnContent .= '"'.$value.'",';
637                      break;
638                  case "varchar":
639                                      //process varchar for possible values
640                                      if($field['name'] == 'first_name'){
641                                          $count = count($sugar_demodata['first_name_array']) - 1;
642                                         $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'",';
643                                      }elseif($field['name'] == 'last_name'){
644                                          $count = count($sugar_demodata['last_name_array']) - 1;
645                                          $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'",';
646                                      }elseif($field['name'] == 'user_name'){
647                                        $count = count($sugar_demodata['first_name_array']) - 1;
648                                         $returnContent .= '"'.$sugar_demodata['last_name_array'][mt_rand(0,$count)].'_'.mt_rand(1,111).'",';
649                                      }elseif($field['name'] == 'title'){
650                                          $count = count($sugar_demodata['titles']) - 1;
651                                          $returnContent .= '"'.$sugar_demodata['titles'][mt_rand(0,$count)].'",';
652                                      }elseif(strpos($field['name'],'address_street')>0){
653                                        $count = count($sugar_demodata['street_address_array']) - 1;
654                                         $returnContent .= '"'.$sugar_demodata['street_address_array'][mt_rand(0,$count)].'",';
655                                      }elseif(strpos($field['name'],'address_city')>0){
656                                        $count = count($sugar_demodata['city_array']) - 1;
657                                         $returnContent .= '"'.$sugar_demodata['city_array'][mt_rand(0,$count)].'",';
658                                      }elseif(strpos($field['name'],'address_state')>0){
659                                          $state_arr = array('CA','NY','CO','TX','NV');
660                                        $count = count($state_arr) - 1;
661                                         $returnContent .= '"'.$state_arr[mt_rand(0,$count)].'",';
662                                      }elseif(strpos($field['name'],'address_postalcode')>0){
663                                         $returnContent .= '"'.mt_rand(12345,99999).'",';
664                                      }else{
665                                          $returnContent .= '"",';
666
667                                      }
668                      break;
669                 case "url":
670                      $returnContent .= '"https://www.sugarcrm.com",';
671                      break;
672
673                 case "enum":
674                     //get the associated enum if available
675                     global $app_list_strings;
676
677                     if(isset($focus->field_name_map[$field_name]['type']) && !empty($focus->field_name_map[$field_name]['options'])){
678                         if ( !empty($app_list_strings[$focus->field_name_map[$field_name]['options']]) ) {
679
680                             //get the values into an array
681                             $dd_values = $app_list_strings[$focus->field_name_map[$field_name]['options']];
682                             $dd_values = array_values($dd_values);
683
684                             //grab the count
685                             $count = count($dd_values) - 1;
686
687                             //choose one at random
688                             $returnContent .= '"'.$dd_values[mt_rand(0,$count)].'",';
689                             } else{
690                                 //name of enum options array was found but is empty, return blank
691                                 $returnContent .= '"",';
692                             }
693                     }else{
694                         //name of enum options array was not found on field, return blank
695                         $returnContent .= '"",';
696                     }
697                      break;
698                 default:
699                     //type is not matched, fill in with empty string and continue;
700                     $returnContent .= '"",';
701
702              }
703          }
704          $returnContent .= "\r\n";
705      }
706      return $returnContent;
707  }
708
709
710
711
712  //expects the field name to translate and a bean of the type being translated (to access field map and mod_strings)
713  function translateForExport($field_db_name,$focus){
714      global $mod_strings,$app_strings;
715
716      if (empty($field_db_name) || empty($focus)){
717         return false;
718      }
719
720     //grab the focus module strings
721     $temp_mod_strings = $mod_strings;
722     global $current_language;
723     $mod_strings = return_module_language($current_language, $focus->module_dir);
724     $fieldLabel = '';
725
726      //!! first check to see if we are overriding the label for export.
727      if (!empty($mod_strings['LBL_EXPORT_'.strtoupper($field_db_name)])){
728          //entry exists which means we are overriding this value for exporting, use this label
729          $fieldLabel = $mod_strings['LBL_EXPORT_'.strtoupper($field_db_name)];
730
731      }
732      //!! next check to see if we are overriding the label for export on app_strings.
733      elseif (!empty($app_strings['LBL_EXPORT_'.strtoupper($field_db_name)])){
734          //entry exists which means we are overriding this value for exporting, use this label
735          $fieldLabel = $app_strings['LBL_EXPORT_'.strtoupper($field_db_name)];
736
737      }//check to see if label exists in mapping and in mod strings
738      elseif (!empty($focus->field_name_map[$field_db_name]['vname']) && !empty($mod_strings[$focus->field_name_map[$field_db_name]['vname']])){
739          $fieldLabel = $mod_strings[$focus->field_name_map[$field_db_name]['vname']];
740
741      }//check to see if label exists in mapping and in app strings
742      elseif (!empty($focus->field_name_map[$field_db_name]['vname']) && !empty($app_strings[$focus->field_name_map[$field_db_name]['vname']])){
743          $fieldLabel = $app_strings[$focus->field_name_map[$field_db_name]['vname']];
744
745      }//field is not in mapping, so check to see if db can be uppercased and found in mod strings
746      elseif (!empty($mod_strings['LBL_'.strtoupper($field_db_name)])){
747          $fieldLabel = $mod_strings['LBL_'.strtoupper($field_db_name)];
748
749      }//check to see if db can be uppercased and found in app strings
750      elseif (!empty($app_strings['LBL_'.strtoupper($field_db_name)])){
751          $fieldLabel = $app_strings['LBL_'.strtoupper($field_db_name)];
752
753      }else{
754          //we could not find the label in mod_strings or app_strings based on either a mapping entry
755          //or on the db_name itself or being overwritten, so default to the db name as a last resort
756          $fieldLabel = $field_db_name;
757
758      }
759      //strip the label of any columns
760      $fieldLabel= preg_replace("/([:]|\xEF\xBC\x9A)[\\s]*$/", '', trim($fieldLabel));
761
762      //reset the bean mod_strings back to original import strings
763      $mod_strings = $temp_mod_strings;
764      return $fieldLabel;
765
766  }
767
768 //call this function to return the desired order to display columns for export in.
769 //if you pass in an array, it will reorder the array and send back to you.  It expects the array
770 //to have the db names as key values, or as labels
771 function get_field_order_mapping($name='',$reorderArr = '', $exclude = true){
772
773     //define the ordering of fields, note that the key value is what is important, and should be the db field name
774     $field_order_array = array();
775     $field_order_array['accounts'] = array( 'name'=>'Name', 'id'=>'ID', 'website'=>'Website', 'email_address' =>'Email Address', 'email_addresses_non_primary' => 'Non Primary E-mails', 'phone_office' =>'Office Phone', 'phone_alternate' => 'Alternate Phone', 'phone_fax' => 'Fax', 'billing_address_street' => 'Billing Street', 'billing_address_city' => 'Billing City', 'billing_address_state' => 'Billing State', 'billing_address_postalcode' => 'Billing Postal Code', 'billing_address_country' => 'Billing Country', 'shipping_address_street' => 'Shipping Street', 'shipping_address_city' => 'Shipping City', 'shipping_address_state' => 'Shipping State', 'shipping_address_postalcode' => 'Shipping Postal Code', 'shipping_address_country' => 'Shipping Country', 'description' => 'Description', 'account_type' => 'Type', 'industry' =>'Industry', 'annual_revenue' => 'Annual Revenue', 'employees' => 'Employees', 'sic_code' => 'SIC Code', 'ticker_symbol' => 'Ticker Symbol', 'parent_id' => 'Parent Account ID', 'ownership' =>'Ownership', 'campaign_id' =>'Campaign ID', 'rating' =>'Rating', 'assigned_user_name' =>'Assigned to',  'assigned_user_id' =>'Assigned User ID', 'team_id' =>'Team Id', 'team_name' =>'Teams', 'team_set_id' =>'Team Set ID', 'date_entered' =>'Date Created', 'date_modified' =>'Date Modified', 'modified_user_id' =>'Modified By', 'created_by' =>'Created By', 'deleted' =>'Deleted');
776     $field_order_array['contacts'] = array( 'first_name' => 'First Name', 'last_name' => 'Last Name', 'id'=>'ID', 'salutation' => 'Salutation', 'title' => 'Title', 'department' => 'Department', 'account_name' => 'Account Name', 'email_address' => 'Email Address', 'email_addresses_non_primary' => 'Non Primary E-mails for Import', 'phone_mobile' => 'Phone Mobile','phone_work' => 'Phone Work', 'phone_home' => 'Phone Home',  'phone_other' => 'Phone Other','phone_fax' => 'Phone Fax', 'primary_address_street' => 'Primary Address Street', 'primary_address_city' => 'Primary Address City', 'primary_address_state' => 'Primary Address State', 'primary_address_postalcode' => 'Primary Address Postal Code', 'primary_address_country' => 'Primary Address Country', 'alt_address_street' => 'Alternate Address Street', 'alt_address_city' => 'Alternate Address City', 'alt_address_state' => 'Alternate Address State', 'alt_address_postalcode' => 'Alternate Address Postal Code', 'alt_address_country' => 'Alternate Address Country', 'description' => 'Description', 'birthdate' => 'Birthdate', 'lead_source' => 'Lead Source', 'campaign_id' => 'campaign_id', 'do_not_call' => 'Do Not Call', 'portal_name' => 'Portal Name', 'portal_active' => 'Portal Active', 'portal_password' => 'Portal Password', 'portal_app' => 'Portal Application', 'reports_to_id' => 'Reports to ID', 'assistant' => 'Assistant', 'assistant_phone' => 'Assistant Phone', 'picture' => 'Picture', 'assigned_user_name' => 'Assigned User Name', 'assigned_user_id' => 'Assigned User ID', 'team_name' => 'Teams', 'team_id' => 'Team id', 'team_set_id' => 'Team Set ID', 'date_entered' =>'Date Created', 'date_modified' =>'Date Modified', 'modified_user_id' =>'Modified By', 'created_by' =>'Created By', 'deleted' =>'Deleted');
777     $field_order_array['leads']    = array( 'first_name' => 'First Name', 'last_name' => 'Last Name', 'id'=>'ID', 'salutation' => 'Salutation', 'title' => 'Title', 'department' => 'Department', 'account_name' => 'Account Name', 'account_description' =>  'Account Description', 'website' =>  'Website', 'email_address' =>  'Email Address', 'email_addresses_non_primary' => 'Non Primary E-mails for Import', 'phone_mobile' =>  'Phone Mobile', 'phone_work' =>  'Phone Work', 'phone_home' =>  'Phone Home', 'phone_other' =>  'Phone Other', 'phone_fax' =>  'Phone Fax', 'primary_address_street' =>  'Primary Address Street', 'primary_address_city' =>  'Primary Address City', 'primary_address_state' =>  'Primary Address State', 'primary_address_postalcode' =>  'Primary Address Postal Code', 'primary_address_country' =>  'Primary Address Country', 'alt_address_street' =>  'Alt Address Street', 'alt_address_city' =>  'Alt Address City', 'alt_address_state' =>  'Alt Address State', 'alt_address_postalcode' =>  'Alt Address Postalcode', 'alt_address_country' =>  'Alt Address Country', 'status' =>  'Status', 'status_description' =>  'Status Description', 'lead_source' =>  'Lead Source', 'lead_source_description' =>  'Lead Source Description', 'description'=>'Description', 'converted' =>  'Converted', 'opportunity_name' =>  'Opportunity Name', 'opportunity_amount' =>  'Opportunity Amount', 'refered_by' =>  'Referred By', 'campaign_id' =>  'campaign_id', 'do_not_call' =>  'Do Not Call', 'portal_name' =>  'Portal Name', 'portal_app' =>  'Portal Application', 'reports_to_id' =>  'Reports To ID', 'assistant' =>  'Assistant', 'assistant_phone' =>  'Assistant Phone', 'birthdate'=>'Birthdate', 'contact_id' =>  'Contact ID', 'account_id' =>  'Account ID', 'opportunity_id' =>  'Opportunity ID',  'assigned_user_name' =>  'Assigned User Name', 'assigned_user_id' =>  'Assigned User ID', 'team_name' =>  'Teams', 'team_id' =>  'Team id', 'team_set_id' =>  'Team Set ID', 'date_entered' =>  'Date Created', 'date_modified' =>  'Date Modified', 'created_by' =>  'Created By ID', 'modified_user_id' =>  'Modified By ID', 'deleted' =>  'Deleted');
778     $field_order_array['opportunities'] = array( 'name' => 'Opportunity Name', 'id'=>'ID', 'amount' => 'Opportunity Amount', 'currency_id' => 'Currency', 'date_closed' => 'Expected Close Date', 'sales_stage' => 'Sales Stage', 'probability' => 'Probability (%)', 'next_step' => 'Next Step', 'opportunity_type' => 'Opportunity Type', 'account_name' => 'Account Name', 'description' => 'Description', 'amount_usdollar' => 'Amount', 'lead_source' => 'Lead Source', 'campaign_id' => 'campaign_id', 'assigned_user_name' => 'Assigned User Name', 'assigned_user_id' => 'Assigned User ID', 'team_name' => 'Teams', 'team_id' => 'Team id', 'team_set_id' => 'Team Set ID', 'date_entered' => 'Date Created', 'date_modified' => 'Date Modified', 'created_by' => 'Created By ID', 'modified_user_id' => 'Modified By ID', 'deleted' => 'Deleted');
779     $field_order_array['notes'] =         array( 'name' => 'Name', 'id'=>'ID', 'description' => 'Description', 'filename' => 'Attachment', 'parent_type' => 'Parent Type', 'parent_id' => 'Parent ID', 'contact_id' => 'Contact ID', 'portal_flag' => 'Display in Portal?', 'assigned_user_name' =>'Assigned to', 'assigned_user_id' => 'assigned_user_id', 'team_id' => 'Team id', 'team_set_id' => 'Team Set ID', 'date_entered' => 'Date Created', 'date_modified' => 'Date Modified',  'created_by' => 'Created By ID', 'modified_user_id' => 'Modified By ID', 'deleted' => 'Deleted' );
780     $field_order_array['bugs'] =   array('bug_number' => 'Bug Number', 'id'=>'ID', 'name' => 'Subject', 'description' => 'Description', 'status' => 'Status', 'type' => 'Type', 'priority' => 'Priority', 'resolution' => 'Resolution', 'work_log' => 'Work Log', 'found_in_release' => 'Found In Release', 'fixed_in_release' => 'Fixed In Release', 'found_in_release_name' => 'Found In Release Name', 'fixed_in_release_name' => 'Fixed In Release', 'product_category' => 'Category', 'source' => 'Source', 'portal_viewable' => 'Portal Viewable', 'system_id' => 'System ID', 'assigned_user_id' => 'Assigned User ID', 'assigned_user_name' => 'Assigned User Name', 'team_name'=>'Teams', 'team_id' => 'Team id', 'team_set_id' => 'Team Set ID', 'date_entered' =>'Date Created', 'date_modified' =>'Date Modified', 'modified_user_id' =>'Modified By', 'created_by' =>'Created By', 'deleted' =>'Deleted');
781     $field_order_array['tasks'] =   array( 'name'=>'Subject', 'id'=>'ID', 'description'=>'Description', 'status'=>'Status', 'date_start'=>'Date Start', 'date_due'=>'Date Due','priority'=>'Priority', 'parent_type'=>'Parent Type', 'parent_id'=>'Parent ID', 'contact_id'=>'Contact ID', 'assigned_user_name' =>'Assigned to', 'assigned_user_id'=>'Assigned User ID', 'team_name'=>'Teams', 'team_id'=>'Team id', 'team_set_id'=>'Team Set ID', 'date_entered'=>'Date Created', 'date_modified'=>'Date Modified', 'created_by'=>'Created By ID', 'modified_user_id'=>'Modified By ID', 'deleted'=>'Deleted');
782     $field_order_array['calls'] =   array( 'name'=>'Subject', 'id'=>'ID', 'description'=>'Description', 'status'=>'Status', 'direction'=>'Direction', 'date_start'=>'Date', 'date_end'=>'Date End', 'duration_hours'=>'Duration Hours', 'duration_minutes'=>'Duration Minutes', 'reminder_time'=>'Reminder Time', 'parent_type'=>'Parent Type', 'parent_id'=>'Parent ID', 'outlook_id'=>'Outlook ID', 'assigned_user_name' =>'Assigned to', 'assigned_user_id'=>'Assigned User ID', 'team_name'=>'Teams', 'team_id'=>'Team id', 'team_set_id'=>'Team Set ID', 'date_entered'=>'Date Created', 'date_modified'=>'Date Modified', 'created_by'=>'Created By ID', 'modified_user_id'=>'Modified By ID', 'deleted'=>'Deleted');
783     $field_order_array['meetings'] =array( 'name'=>'Subject', 'id'=>'ID', 'description'=>'Description', 'status'=>'Status', 'location'=>'Location', 'date_start'=>'Date', 'date_end'=>'Date End', 'duration_hours'=>'Duration Hours', 'duration_minutes'=>'Duration Minutes', 'reminder_time'=>'Reminder Time', 'type'=>'Meeting Type', 'external_id'=>'External ID', 'password'=>'Meeting Password', 'join_url'=>'Join Url', 'host_url'=>'Host Url', 'displayed_url'=>'Displayed Url', 'creator'=>'Meeting Creator', 'parent_type'=>'Related to', 'parent_id'=>'Related to', 'outlook_id'=>'Outlook ID','assigned_user_name' =>'Assigned to','assigned_user_id' => 'Assigned User ID', 'team_name' => 'Teams', 'team_id' => 'Team id', 'team_set_id' => 'Team Set ID', 'date_entered' => 'Date Created', 'date_modified' => 'Date Modified', 'created_by' => 'Created By ID', 'modified_user_id' => 'Modified By ID', 'deleted' => 'Deleted');
784     $field_order_array['cases'] =array( 'case_number'=>'Case Number', 'id'=>'ID', 'name'=>'Subject', 'description'=>'Description', 'status'=>'Status', 'type'=>'Type', 'priority'=>'Priority', 'resolution'=>'Resolution', 'work_log'=>'Work Log', 'portal_viewable'=>'Portal Viewable', 'account_name'=>'Account Name', 'account_id'=>'Account ID', 'assigned_user_id'=>'Assigned User ID', 'team_name'=>'Teams', 'team_id'=>'Team id', 'team_set_id'=>'Team Set ID', 'date_entered'=>'Date Created', 'date_modified'=>'Date Modified', 'created_by'=>'Created By ID', 'modified_user_id'=>'Modified By ID', 'deleted'=>'Deleted');
785     $field_order_array['prospects'] =array( 'first_name'=>'First Name', 'last_name'=>'Last Name', 'id'=>'ID', 'salutation'=>'Salutation', 'title'=>'Title', 'department'=>'Department', 'account_name'=>'Account Name', 'email_address'=>'Email Address', 'email_addresses_non_primary' => 'Non Primary E-mails for Import', 'phone_mobile' => 'Phone Mobile', 'phone_work' => 'Phone Work', 'phone_home' => 'Phone Home', 'phone_other' => 'Phone Other', 'phone_fax' => 'Phone Fax',  'primary_address_street' => 'Primary Address Street', 'primary_address_city' => 'Primary Address City', 'primary_address_state' => 'Primary Address State', 'primary_address_postalcode' => 'Primary Address Postal Code', 'primary_address_country' => 'Primary Address Country', 'alt_address_street' => 'Alternate Address Street', 'alt_address_city' => 'Alternate Address City', 'alt_address_state' => 'Alternate Address State', 'alt_address_postalcode' => 'Alternate Address Postal Code', 'alt_address_country' => 'Alternate Address Country', 'description' => 'Description', 'birthdate' => 'Birthdate', 'assistant'=>'Assistant', 'assistant_phone'=>'Assistant Phone', 'campaign_id'=>'campaign_id', 'tracker_key'=>'Tracker Key', 'do_not_call'=>'Do Not Call', 'lead_id'=>'Lead Id', 'assigned_user_name'=>'Assigned User Name', 'assigned_user_id'=>'Assigned User ID', 'team_id' =>'Team Id', 'team_name' =>'Teams', 'team_set_id' =>'Team Set ID', 'date_entered' =>'Date Created', 'date_modified' =>'Date Modified', 'modified_user_id' =>'Modified By', 'created_by' =>'Created By', 'deleted' =>'Deleted');
786
787     $fields_to_exclude = array();
788     $fields_to_exclude['accounts'] = array('account_name');
789     $fields_to_exclude['bugs'] = array('system_id');
790     $fields_to_exclude['cases'] = array('system_id', 'modified_by_name', 'modified_by_name_owner', 'modified_by_name_mod', 'created_by_name', 'created_by_name_owner', 'created_by_name_mod', 'assigned_user_name', 'assigned_user_name_owner', 'assigned_user_name_mod', 'team_count', 'team_count_owner', 'team_count_mod', 'team_name_owner', 'team_name_mod', 'account_name_owner', 'account_name_mod', 'modified_user_name',  'modified_user_name_owner', 'modified_user_name_mod');
791     $fields_to_exclude['notes'] = array('first_name','last_name', 'file_mime_type','embed_flag');
792     $fields_to_exclude['tasks'] = array('date_start_flag', 'date_due_flag');
793
794     //of array is passed in for reordering, process array
795     if(!empty($name) && !empty($reorderArr) && is_array($reorderArr)){
796
797         //make sure reorderArr has values as keys, if not then iterate through and assign the value as the key
798         $newReorder = array();
799         foreach($reorderArr as $rk=> $rv){
800             if(is_int($rk)){
801                 $newReorder[$rv]=$rv;
802             }else{
803                 $newReorder[$rk]=$rv;
804             }
805         }
806
807         //if module is not defined, lets default the order to another module of the same type
808         //this would apply mostly to custom modules
809         if(!isset($field_order_array[strtolower($name)]) && isset($_REQUEST['module'])){
810
811             $exemptModuleList = array('ProspectLists');
812             if(in_array($name, $exemptModuleList))
813                 return $newReorder;
814
815             //get an instance of the bean
816             global $beanList;
817             global $beanFiles;
818
819             $bean = $beanList[$_REQUEST['module']];
820             require_once($beanFiles[$bean]);
821             $focus = new $bean;
822
823
824             //if module is of type person
825             if($focus instanceof Person){
826                 $name = 'contacts';
827             }
828             //if module is of type company
829             else if ($focus instanceof Company){
830                 $name = 'accounts';
831             }
832             //if module is of type Sale
833             else if ($focus instanceof Sale){
834                 $name = 'opportunities';
835             }//if module is of type File
836             else if ($focus instanceof Issue){
837                 $name = 'bugs';
838             }//all others including type File can use basic
839             else{
840                 $name = 'Notes';
841             }
842
843         }
844
845         //lets iterate through and create a reordered temporary array using
846         //the  newly formatted copy of passed in array
847         $temp_result_arr = array();
848         $lname = strtolower($name);
849         if(!empty($field_order_array[$lname])) {
850                 foreach($field_order_array[$lname] as $fk=> $fv){
851
852                     //if the value exists as a key in the passed in array, add to temp array and remove from reorder array.
853                     //Do not force into the temp array as we don't want to violate acl's
854                     if(array_key_exists($fk,$newReorder)){
855                         $temp_result_arr[$fk] = $newReorder[$fk];
856                         unset($newReorder[$fk]);
857                     }
858                 }
859         }
860         //add in all the left over values that were not in our ordered list
861         //array_splice($temp_result_arr, count($temp_result_arr), 0, $newReorder);
862         foreach($newReorder as $nrk=>$nrv){
863             $temp_result_arr[$nrk] = $nrv;
864         }
865
866
867         if($exclude){
868             //Some arrays have values we wish to exclude
869             if (isset($fields_to_exclude[$lname])){
870                 foreach($fields_to_exclude[$lname] as $exclude_field){
871                     unset($temp_result_arr[$exclude_field]);
872                 }
873             }
874         }
875
876         //return temp ordered list
877         return $temp_result_arr;
878     }
879
880     //if no array was passed in, pass back either the list of ordered columns by module, or the entireorder array
881     if(empty($name)){
882         return $field_order_array;
883     }else{
884         return $field_order_array[strtolower($name)];
885     }
886
887 }
888 ?>