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