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