]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/export_utils.php
Release 6.2.0
[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) {
69         global $beanList;
70         global $beanFiles;
71         global $current_user;
72         global $app_strings;
73         global $app_list_strings;
74         global $timedate;
75         $contact_fields = array(
76                 "id"=>"Contact ID"
77                 ,"lead_source"=>"Lead Source"
78                 ,"date_entered"=>"Date Entered"
79                 ,"date_modified"=>"Date Modified"
80                 ,"first_name"=>"First Name"
81                 ,"last_name"=>"Last Name"
82                 ,"salutation"=>"Salutation"
83                 ,"birthdate"=>"Lead Source"
84                 ,"do_not_call"=>"Do Not Call"
85                 ,"email_opt_out"=>"Email Opt Out"
86                 ,"title"=>"Title"
87                 ,"department"=>"Department"
88                 ,"birthdate"=>"Birthdate"
89                 ,"do_not_call"=>"Do Not Call"
90                 ,"phone_home"=>"Phone (Home)"
91                 ,"phone_mobile"=>"Phone (Mobile)"
92                 ,"phone_work"=>"Phone (Work)"
93                 ,"phone_other"=>"Phone (Other)"
94                 ,"phone_fax"=>"Fax"
95                 ,"email1"=>"Email"
96                 ,"email2"=>"Email (Other)"
97                 ,"assistant"=>"Assistant"
98                 ,"assistant_phone"=>"Assistant Phone"
99                 ,"primary_address_street"=>"Primary Address Street"
100                 ,"primary_address_city"=>"Primary Address City"
101                 ,"primary_address_state"=>"Primary Address State"
102                 ,"primary_address_postalcode"=>"Primary Address Postalcode"
103                 ,"primary_address_country"=>"Primary Address Country"
104                 ,"alt_address_street"=>"Other Address Street"
105                 ,"alt_address_city"=>"Other Address City"
106                 ,"alt_address_state"=>"Other Address State"
107                 ,"alt_address_postalcode"=>"Other Address Postalcode"
108                 ,"alt_address_country"=>"Other Address Country"
109                 ,"description"=>"Description"
110         );
111
112         $account_fields = array(
113                 "id"=>"Account ID",
114                 "name"=>"Account Name",
115                 "website"=>"Website",
116                 "industry"=>"Industry",
117                 "account_type"=>"Type",
118                 "ticker_symbol"=>"Ticker Symbol",
119                 "employees"=>"Employees",
120                 "ownership"=>"Ownership",
121                 "phone_office"=>"Phone",
122                 "phone_fax"=>"Fax",
123                 "phone_alternate"=>"Other Phone",
124                 "email1"=>"Email",
125                 "email2"=>"Other Email",
126                 "rating"=>"Rating",
127                 "sic_code"=>"SIC Code",
128                 "annual_revenue"=>"Annual Revenue",
129                 "billing_address_street"=>"Billing Address Street",
130                 "billing_address_city"=>"Billing Address City",
131                 "billing_address_state"=>"Billing Address State",
132                 "billing_address_postalcode"=>"Billing Address Postalcode",
133                 "billing_address_country"=>"Billing Address Country",
134                 "shipping_address_street"=>"Shipping Address Street",
135                 "shipping_address_city"=>"Shipping Address City",
136                 "shipping_address_state"=>"Shipping Address State",
137                 "shipping_address_postalcode"=>"Shipping Address Postalcode",
138                 "shipping_address_country"=>"Shipping Address Country",
139                 "description"=>"Description"
140         );
141         $focus = 0;
142         $content = '';
143
144         $bean = $beanList[$type];
145         require_once($beanFiles[$bean]);
146         $focus = new $bean;
147     $searchFields = array();
148         $db = DBManagerFactory::getInstance();
149         
150         if($records) {
151                 $records = explode(',', $records);
152                 $records = "'" . implode("','", $records) . "'";
153                 $where = "{$focus->table_name}.id in ($records)";
154         } elseif (isset($_REQUEST['all']) ) {
155                 $where = '';
156         } else {
157                 if(!empty($_REQUEST['current_post'])) {
158                         $ret_array = generateSearchWhere($type, $_REQUEST['current_post']);
159                         
160                         $where = $ret_array['where'];
161                         $searchFields = $ret_array['searchFields'];
162                 } else {
163                         $where = '';
164                 }
165         }
166         $order_by = "";
167         if($focus->bean_implements('ACL')){
168                 if(!ACLController::checkAccess($focus->module_dir, 'export', true)){
169                         ACLController::displayNoAccess();
170                         sugar_die('');
171                 }
172                 if(ACLController::requireOwner($focus->module_dir, 'export')){
173                         if(!empty($where)){
174                                 $where .= ' AND ';
175                         }
176                         $where .= $focus->getOwnerWhere($current_user->id);
177                 }
178
179         }
180     // Export entire list was broken because the where clause already has "where" in it
181     // and when the query is built, it has a "where" as well, so the query was ill-formed.
182     // Eliminating the "where" here so that the query can be constructed correctly.
183     if($members == true){
184                 $query = $focus->create_export_members_query($records);
185     }else{
186                 $beginWhere = substr(trim($where), 0, 5);
187             if ($beginWhere == "where")
188                 $where = substr(trim($where), 5, strlen($where));
189         $ret_array = create_export_query_relate_link_patch($type, $searchFields, $where); 
190         if(!empty($ret_array['join'])) {
191                 $query = $focus->create_export_query($order_by,$ret_array['where'],$ret_array['join']);
192         } else {
193                 $query = $focus->create_export_query($order_by,$ret_array['where']);
194         }
195     }
196
197    
198         $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'].$type.": <BR>.".$query);
199         
200         $fields_array = $db->getFieldsArray($result,true);
201
202         // setup the "header" line with proper delimiters
203         $header = implode("\"".getDelimiter()."\"", array_values($fields_array));
204         if($members){
205                 $header = str_replace('"ea_deleted"'.getDelimiter().'"ear_deleted"'.getDelimiter().'"primary_address"'.getDelimiter().'','',$header);
206         }
207         $header = "\"" .$header;
208         $header .= "\"\r\n";
209         $content .= $header;
210         $pre_id = '';
211         
212         while($val = $db->fetchByAssoc($result, -1, false)) {
213                 $new_arr = array();
214                 if($members){
215                         if($pre_id == $val['id'])
216                                 continue;
217                         if($val['ea_deleted']==1 || $val['ear_deleted']==1){    
218                                 $val['primary_email_address'] = '';
219                         }
220                         unset($val['ea_deleted']);
221                         unset($val['ear_deleted']);     
222                         unset($val['primary_address']);                 
223                 }
224                 $pre_id = $val['id'];
225                 $vals = array_values($val);
226                 foreach ($vals as $key => $value) {
227                         //if our value is a datetime field, then apply the users locale
228                         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')){
229                                 $value = $timedate->to_display_date_time($value);
230                                 $value = preg_replace('/([pm|PM|am|AM]+)/', ' \1', $value);
231                         }
232                         //kbrill Bug #16296
233                         if(isset($focus->field_name_map[$fields_array[$key]]['type']) && $focus->field_name_map[$fields_array[$key]]['type'] == 'date'){
234                                 $value = $timedate->to_display_date($value, false);
235                         }
236                         // Bug 32463 - Properly have multienum field translated into something useful for the client
237                         if(isset($focus->field_name_map[$fields_array[$key]]['type']) && $focus->field_name_map[$fields_array[$key]]['type'] == 'multienum'){
238                             $value = str_replace("^","",$value);
239                             if ( isset($focus->field_name_map[$fields_array[$key]]['options'])
240                                     && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']]) ) {
241                     $valueArray = explode(",",$value);
242                     foreach ( $valueArray as $multikey => $multivalue ) {
243                         if ( isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue]) ) {
244                             $valueArray[$multikey] = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue];
245                         }
246                     }
247                     $value = implode(",",$valueArray);
248                             }
249                         }
250                         array_push($new_arr, preg_replace("/\"/","\"\"", $value));
251                 }
252                 $line = implode("\"".getDelimiter()."\"", $new_arr);
253                 $line = "\"" .$line;
254                 $line .= "\"\r\n";
255
256                 $content .= $line;
257         }
258         return $content;
259 }
260
261 function generateSearchWhere($module, $query) {//this function is similar with function prepareSearchForm() in view.list.php
262     $seed = loadBean($module);
263     if(file_exists('modules/'.$module.'/SearchForm.html')){
264         if(file_exists('modules/' . $module . '/metadata/SearchFields.php')) {
265             require_once('include/SearchForm/SearchForm.php');
266             $searchForm = new SearchForm($module, $seed);
267         }
268         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. 
269         //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.
270             $where = $_SESSION['export_where'];
271             $whereArr = explode (" ", trim($where));
272             if ($whereArr[0] == trim('where')) {
273                 $whereClean = array_shift($whereArr);
274             }
275             $where = implode(" ", $whereArr);
276             //rrs bug: 31329 - previously this was just returning $where, but the problem is the caller of this function 
277             //expects the results in an array, not just a string. So rather than fixing the caller, I felt it would be best for
278             //the function to return the results in a standard format.
279             $ret_array['where'] = $where;
280                 $ret_array['searchFields'] =array();
281             return $ret_array;
282         }
283         else {
284             return;
285         }
286     }
287     else{
288         require_once('include/SearchForm/SearchForm2.php');
289         
290         if(file_exists('custom/modules/'.$module.'/metadata/metafiles.php')){
291             require('custom/modules/'.$module.'/metadata/metafiles.php');       
292         }elseif(file_exists('modules/'.$module.'/metadata/metafiles.php')){
293             require('modules/'.$module.'/metadata/metafiles.php');
294         }
295             
296         if (file_exists('custom/modules/'.$module.'/metadata/searchdefs.php'))
297         {
298             require_once('custom/modules/'.$module.'/metadata/searchdefs.php');
299         }
300         elseif (!empty($metafiles[$module]['searchdefs']))
301         {
302             require_once($metafiles[$module]['searchdefs']);
303         }
304         elseif (file_exists('modules/'.$module.'/metadata/searchdefs.php'))
305         {
306             require_once('modules/'.$module.'/metadata/searchdefs.php');
307         }
308             
309         if(!empty($metafiles[$module]['searchfields']))
310             require_once($metafiles[$module]['searchfields']);
311         elseif(file_exists('modules/'.$module.'/metadata/SearchFields.php'))
312             require_once('modules/'.$module.'/metadata/SearchFields.php');
313         if(empty($searchdefs) || empty($searchFields)) {
314            //for some modules, such as iframe, it has massupdate, but it doesn't have search function, the where sql should be empty.
315             return;
316         }
317         $searchForm = new SearchForm($seed, $module);
318         $searchForm->setup($searchdefs, $searchFields, 'include/SearchForm/tpls/SearchFormGeneric.tpl');
319     }
320     $searchForm->populateFromArray(unserialize(base64_decode($query)));
321     $where_clauses = $searchForm->generateSearchWhere(true, $module);
322     if (count($where_clauses) > 0 )$where = '('. implode(' ) AND ( ', $where_clauses) . ')';
323         $GLOBALS['log']->info("Export Where Clause: {$where}");
324     $ret_array['where'] = $where;
325     $ret_array['searchFields'] = $searchForm->searchFields;
326     return $ret_array;
327 }
328
329
330 ?>