]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - service/v3_1/SugarWebServiceImplv3_1.php
Release 6.2.0beta4
[Github/sugarcrm.git] / service / v3_1 / SugarWebServiceImplv3_1.php
1 <?php
2 if(!defined('sugarEntry'))define('sugarEntry', true);
3 /*********************************************************************************
4  * SugarCRM 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  * This class is an implemenatation class for all the rest services
41  */
42 require_once('service/v3/SugarWebServiceImplv3.php');
43 require_once('SugarWebServiceUtilv3_1.php');
44
45
46 class SugarWebServiceImplv3_1 extends SugarWebServiceImplv3 {
47
48     public function __construct()
49     {
50         self::$helperObject = new SugarWebServiceUtilv3_1();
51     }
52
53    /**
54     * Retrieve a single SugarBean based on ID.
55     *
56     * @param String $session -- Session ID returned by a previous call to login.
57     * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
58     * @param String $id -- The SugarBean's ID value.
59     * @param Array  $select_fields -- A list of the fields to be included in the results. This optional parameter allows for only needed fields to be retrieved.
60     * @param Array $link_name_to_fields_array -- A list of link_names and for each link_name, what fields value to be returned. For ex.'link_name_to_fields_array' => array(array('name' =>  'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address')))
61     * @param bool $trackView -- Should we track the record accessed.
62     * @return Array
63     *        'entry_list' -- Array - The records name value pair for the simple data types excluding link field data.
64     *        'relationship_list' -- Array - The records link field data. The example is if asked about accounts email address then return data would look like Array ( [0] => Array ( [name] => email_addresses [records] => Array ( [0] => Array ( [0] => Array ( [name] => id [value] => 3fb16797-8d90-0a94-ac12-490b63a6be67 ) [1] => Array ( [name] => email_address [value] => hr.kid.qa@example.com ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 1 ) ) [1] => Array ( [0] => Array ( [name] => id [value] => 403f8da1-214b-6a88-9cef-490b63d43566 ) [1] => Array ( [name] => email_address [value] => kid.hr@example.name ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 0 ) ) ) ) )
65     * @exception 'SoapFault' -- The SOAP error, if any
66     */
67     function get_entry($session, $module_name, $id,$select_fields, $link_name_to_fields_array,$track_view = FALSE)
68     {
69         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_entry');
70         return self::get_entries($session, $module_name, array($id), $select_fields, $link_name_to_fields_array, $track_view);
71         $GLOBALS['log']->info('end: SugarWebServiceImpl->get_entry');
72     }
73
74     /**
75      * Retrieve the md5 hash of the vardef entries for a particular module.
76      *
77      * @param String $session -- Session ID returned by a previous call to login.
78      * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
79      * @return String The md5 hash of the vardef definition.
80      * @exception 'SoapFault' -- The SOAP error, if any
81      */
82     function get_module_fields_md5($session, $module_name){
83
84         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_module_fields_md5');
85
86         $results = array();
87         if( is_array($module_name) )
88         {
89             foreach ($module_name as $module)
90                 $results[$module] = md5(serialize(self::get_module_fields($session, $module)));
91         }
92         else
93             $results[$module_name] = md5(serialize(self::get_module_fields($session, $module_name)));
94
95         return $results;
96
97         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_module_fields_md5');
98     }
99
100     /**
101      * Retrieve the md5 hash of a layout metadata for a given module given a specific type and view.
102      *
103      * @param String $session -- Session ID returned by a previous call to login.
104      * @param array $module_name(s) -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
105      * @return array $type(s) The type of view requested.  Current supported types are 'default' (for application) and 'wireless'
106      * @return array $view(s) The view requested.  Current supported types are edit, detail, and list.
107      * @exception 'SoapFault' -- The SOAP error, if any
108      */
109     function get_module_layout_md5($session, $module_name, $type, $view, $acl_check = TRUE){
110         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_module_layout_md5');
111         $results = self::get_module_layout($session, $module_name, $type, $view, $acl_check, TRUE);
112             return array('md5'=> $results);
113         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_module_layout_md5');
114     }
115
116
117     /**
118     * Retrieve a list of SugarBean's based on provided IDs. This API will not wotk with report module
119     *
120     * @param String $session -- Session ID returned by a previous call to login.
121     * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
122     * @param Array $ids -- An array of SugarBean IDs.
123     * @param Array $select_fields -- A list of the fields to be included in the results. This optional parameter allows for only needed fields to be retrieved.
124     * @param Array $link_name_to_fields_array -- A list of link_names and for each link_name, what fields value to be returned. For ex.'link_name_to_fields_array' => array(array('name' =>  'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address')))
125     * @param bool $trackView -- Should we track the record accessed.
126     * @return Array
127     *        'entry_list' -- Array - The records name value pair for the simple data types excluding link field data.
128     *        'relationship_list' -- Array - The records link field data. The example is if asked about accounts email address then return data would look like Array ( [0] => Array ( [name] => email_addresses [records] => Array ( [0] => Array ( [0] => Array ( [name] => id [value] => 3fb16797-8d90-0a94-ac12-490b63a6be67 ) [1] => Array ( [name] => email_address [value] => hr.kid.qa@example.com ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 1 ) ) [1] => Array ( [0] => Array ( [name] => id [value] => 403f8da1-214b-6a88-9cef-490b63d43566 ) [1] => Array ( [name] => email_address [value] => kid.hr@example.name ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 0 ) ) ) ) )
129     * @exception 'SoapFault' -- The SOAP error, if any
130     */
131     function get_entries($session, $module_name, $ids, $select_fields, $link_name_to_fields_array, $track_view = FALSE)
132     {
133         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_entries');
134         global  $beanList, $beanFiles;
135         $error = new SoapError();
136
137         $linkoutput_list = array();
138         $output_list = array();
139         $using_cp = false;
140         if($module_name == 'CampaignProspects')
141         {
142             $module_name = 'Prospects';
143             $using_cp = true;
144         }
145         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error))
146         {
147             $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entries');
148             return;
149         } // if
150
151         $class_name = $beanList[$module_name];
152         require_once($beanFiles[$class_name]);
153
154         $temp = new $class_name();
155         foreach($ids as $id)
156         {
157             $seed = @clone($temp);
158             if($using_cp)
159                 $seed = $seed->retrieveTarget($id);
160             else
161             {
162                 if ($seed->retrieve($id) == null)
163                     $seed->deleted = 1;
164             }
165
166             if ($seed->deleted == 1)
167             {
168                 $list = array();
169                 $list[] = array('name'=>'warning', 'value'=>'Access to this object is denied since it has been deleted or does not exist');
170                 $list[] = array('name'=>'deleted', 'value'=>'1');
171                 $output_list[] = Array('id'=>$id,'module_name'=> $module_name,'name_value_list'=>$list,);
172                 continue;
173             }
174             if (!self::$helperObject->checkACLAccess($seed, 'DetailView', $error, 'no_access'))
175             {
176                 return;
177             }
178             $output_list[] = self::$helperObject->get_return_value_for_fields($seed, $module_name, $select_fields);
179             if (!empty($link_name_to_fields_array))
180             {
181                 $linkoutput_list[] = self::$helperObject->get_return_value_for_link_fields($seed, $module_name, $link_name_to_fields_array);
182             }
183
184             $GLOBALS['log']->info('Should we track view: ' . $trackView);
185             if($track_view)
186             {
187                 self::$helperObject->trackView($seed, 'detailview');
188             }
189         }
190
191         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entries');
192         return array('entry_list'=>$output_list, 'relationship_list' => $linkoutput_list);
193     }
194
195     /**
196      * Update or create a single SugarBean.
197      *
198      * @param String $session -- Session ID returned by a previous call to login.
199      * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
200      * @param Array $name_value_list -- The keys of the array are the SugarBean attributes, the values of the array are the values the attributes should have.
201      * @param Bool $track_view -- Should the tracker be notified that the action was performed on the bean.
202      * @return Array    'id' -- the ID of the bean that was written to (-1 on error)
203      * @exception 'SoapFault' -- The SOAP error, if any
204      */
205     function set_entry($session,$module_name, $name_value_list, $track_view = FALSE){
206         global  $beanList, $beanFiles, $current_user;
207
208         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->set_entry');
209         if (self::$helperObject->isLogLevelDebug()) {
210             $GLOBALS['log']->debug('SoapHelperWebServices->set_entry - input data is ' . var_export($name_value_list, true));
211         } // if
212         $error = new SoapError();
213         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'write', 'no_access', $error)) {
214             $GLOBALS['log']->info('End: SugarWebServiceImpl->set_entry');
215             return;
216         } // if
217         $class_name = $beanList[$module_name];
218         require_once($beanFiles[$class_name]);
219         $seed = new $class_name();
220         foreach($name_value_list as $name=>$value){
221             if(is_array($value) &&  $value['name'] == 'id'){
222                 $seed->retrieve($value['value']);
223                 break;
224             }else if($name === 'id' ){
225
226                 $seed->retrieve($value);
227             }
228         }
229
230         $return_fields = array();
231         foreach($name_value_list as $name=>$value){
232             if($module_name == 'Users' && !empty($seed->id) && ($seed->id != $current_user->id) && $name == 'user_hash'){
233                 continue;
234             }
235             if(!is_array($value)){
236                 $seed->$name = $value;
237                 $return_fields[] = $name;
238             }else{
239                 $seed->$value['name'] = $value['value'];
240                 $return_fields[] = $value['name'];
241             }
242         }
243         if (!self::$helperObject->checkACLAccess($seed, 'Save', $error, 'no_access') || ($seed->deleted == 1  && !self::$helperObject->checkACLAccess($seed, 'Delete', $error, 'no_access'))) {
244             $GLOBALS['log']->info('End: SugarWebServiceImpl->set_entry');
245             return;
246         } // if
247
248         $seed->save(self::$helperObject->checkSaveOnNotify());
249
250         $return_entry_list = self::$helperObject->get_name_value_list_for_fields($seed, $return_fields );
251
252         if($seed->deleted == 1){
253             $seed->mark_deleted($seed->id);
254         }
255
256         if($track_view){
257             self::$helperObject->trackView($seed, 'editview');
258         }
259
260         $GLOBALS['log']->info('End: SugarWebServiceImpl->set_entry');
261         return array('id'=>$seed->id, 'entry_list' => $return_entry_list);
262     } // fn
263
264
265     /**
266      * Log the user into the application
267      *
268      * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
269      *      in the right encoding for the type of authentication the user is setup for.  For Base
270      *      sugar validation, password is the MD5 sum of the plain text password.
271      * @param String $application -- The name of the application you are logging in from.  (Currently unused).
272      * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
273      * @return Array - id - String id is the session_id of the session that was created.
274      *                           - module_name - String - module name of user
275      *                           - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name,
276      *                                         - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat
277      * @exception 'SoapFault' -- The SOAP error, if any
278      */
279     public function login($user_auth, $application, $name_value_list = array()){
280         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login');
281         global $sugar_config, $system_config;
282         $error = new SoapError();
283         $user = new User();
284         $success = false;
285         //rrs
286         $system_config = new Administration();
287         $system_config->retrieveSettings('system');
288         $authController = new AuthenticationController((!empty($sugar_config['authenticationClass'])? $sugar_config['authenticationClass'] : 'SugarAuthenticate'));
289         //rrs
290         if(!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN' && $authController->authController->userAuthenticateClass != "LDAPAuthenticateUser")
291         {
292             $user_auth['password'] = md5($user_auth['password']);
293         }
294         $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true));
295         $usr_id=$user->retrieve_user_id($user_auth['user_name']);
296         if($usr_id)
297             $user->retrieve($usr_id);
298
299         if ($isLoginSuccess)
300         {
301             if ($_SESSION['hasExpiredPassword'] =='1')
302             {
303                 $error->set_error('password_expired');
304                 $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']);
305                 LogicHook::initialize();
306                 $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
307                 self::$helperObject->setFaultObject($error);
308                 return;
309             }
310             if(!empty($user) && !empty($user->id) && !$user->is_group)
311             {
312                 $success = true;
313                 global $current_user;
314                 $current_user = $user;
315             }
316         }
317         else if($usr_id && isset($user->user_name) && ($user->getPreference('lockout') == '1'))
318         {
319             $error->set_error('lockout_reached');
320             $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']);
321             LogicHook::initialize();
322             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
323             self::$helperObject->setFaultObject($error);
324             return;
325         }
326         else if( $authController->authController->userAuthenticateClass == "LDAPAuthenticateUser"
327                  && (empty($user_auth['encryption']) || $user_auth['encryption'] !== 'PLAIN' ) )
328         {
329             $error->set_error('ldap_error');
330             LogicHook::initialize();
331             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
332             self::$helperObject->setFaultObject($error);
333             return;
334         }
335         else if(function_exists('mcrypt_cbc'))
336         {
337             $password = self::$helperObject->decrypt_string($user_auth['password']);
338             if($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id']))
339                 $success = true;
340         }
341
342         if($success)
343         {
344             session_start();
345             global $current_user;
346             //$current_user = $user;
347             self::$helperObject->login_success($name_value_list);
348             $current_user->loadPreferences();
349             $_SESSION['is_valid_session']= true;
350             $_SESSION['ip_address'] = query_client_ip();
351             $_SESSION['user_id'] = $current_user->id;
352             $_SESSION['type'] = 'user';
353             $_SESSION['avail_modules']= self::$helperObject->get_user_module_list($current_user);
354             $_SESSION['authenticated_user_id'] = $current_user->id;
355             $_SESSION['unique_key'] = $sugar_config['unique_key'];
356             $current_user->call_custom_logic('after_login');
357             $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login');
358             $nameValueArray = array();
359             global $current_language;
360             $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id);
361             $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
362             $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language);
363             $cur_id = $current_user->getPreference('currency');
364             $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id);
365             $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user));
366             $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team );
367             $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef') );
368             $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef') );
369
370             $num_grp_sep = $current_user->getPreference('num_grp_sep');
371             $dec_sep = $current_user->getPreference('dec_sep');
372             $nameValueArray['user_number_seperator'] = self::$helperObject->get_name_value('user_number_seperator', empty($num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $num_grp_sep);
373             $nameValueArray['user_decimal_seperator'] = self::$helperObject->get_name_value('user_decimal_seperator', empty($dec_sep) ? $sugar_config['default_decimal_seperator'] : $dec_sep);
374
375             $nameValueArray['mobile_max_list_entries'] = self::$helperObject->get_name_value('mobile_max_list_entries', $sugar_config['wl_list_max_entries_per_page'] );
376             $nameValueArray['mobile_max_subpanel_entries'] = self::$helperObject->get_name_value('mobile_max_subpanel_entries', $sugar_config['wl_list_max_entries_per_subpanel'] );
377
378             if($application == 'mobile')
379             {
380                 $modules = $availModuleNames = array();
381                 $availModules = array_keys($_SESSION['avail_modules']); //ACL check already performed.
382                 $modules = self::$helperObject->get_visible_mobile_modules($availModules);
383                 $nameValueArray['available_modules'] = $modules;
384                 //Get the vardefs md5
385                 foreach($modules as $mod_def)
386                     $availModuleNames[] = $mod_def['module_key'];
387
388                 $nameValueArray['vardefs_md5'] = self::get_module_fields_md5(session_id(), $availModuleNames);
389             }
390
391             $currencyObject = new Currency();
392             $currencyObject->retrieve($cur_id);
393             $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name);
394             $_SESSION['user_language'] = $current_language;
395             return array('id'=>session_id(), 'module_name'=>'Users', 'name_value_list'=>$nameValueArray);
396         }
397         LogicHook::initialize();
398         $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
399         $error->set_error('invalid_login');
400         self::$helperObject->setFaultObject($error);
401         $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login');
402     }
403
404     /**
405      * Retrieve the list of available modules on the system available to the currently logged in user.
406      *
407      * @param String $session -- Session ID returned by a previous call to login.
408      * @param String $filter --  Valid values are: all     - Return all modules,
409      *                                             default - Return all visible modules for the application
410      *                                             mobile  - Return all visible modules for the mobile view
411      * @return Array    'modules' -- Array - An array of module names
412      * @exception 'SoapFault' -- The SOAP error, if any
413      */
414     function get_available_modules($session,$filter='all'){
415         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_available_modules');
416
417         $error = new SoapError();
418         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
419                 $error->set_error('invalid_login');
420                 $GLOBALS['log']->info('End: SugarWebServiceImpl->get_available_modules');
421                 return;
422         } // if
423
424         $modules = array();
425         $availModules = array_keys($_SESSION['avail_modules']); //ACL check already performed.
426         switch ($filter){
427             case 'default':
428                 $modules = self::$helperObject->get_visible_modules($availModules);
429                break;
430             case 'mobile':
431                 $modules = self::$helperObject->get_visible_mobile_modules($availModules);
432                 break;
433             case 'all':
434             default:
435                 $modules = self::$helperObject->getModulesFromList(array_flip($availModules), $availModules);
436         }
437
438         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_available_modules');
439         return array('modules'=> $modules);
440     } // fn
441
442
443     /**
444      * Enter description here...
445      *
446      * @param string $session   - Session ID returned by a previous call to login.
447      * @param array $modules Array of modules to return
448      * @param bool $MD5 Should the results be md5d
449      */
450     function get_language_definition($session, $modules, $MD5 = FALSE)
451     {
452         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_language_file');
453         global  $beanList, $beanFiles;
454         global $sugar_config,$current_language;
455
456         $error = new SoapError();
457         $output_list = array();
458         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error))
459         {
460             $error->set_error('invalid_login');
461             $GLOBALS['log']->info('End: SugarWebServiceImpl->get_report_pdf');
462             return;
463         }
464
465         if( is_string($modules) )
466             $modules = array($modules);
467
468         $results = array();
469         foreach ($modules as $mod)
470         {
471             if( strtolower($mod) == 'app_strings' )
472             {
473                 $values = return_application_language($current_language);
474                 $key = 'app_strings';
475             }
476             else if ( strtolower($mod) == 'app_list_strings' )
477             {
478                 $values = return_app_list_strings_language($current_language);
479                 $key = 'app_list_strings';
480             }
481             else
482             {
483                 $values = return_module_language($current_language, $mod);
484                 $key = $mod;
485             }
486
487             if( $MD5 )
488                 $values = md5(serialize($values));
489
490             $results[$key] = $values;
491         }
492
493         return $results;
494     }
495
496     
497     /**
498      * Retrieve the layout metadata for a given module given a specific type and view.
499      *
500      * @param String $session -- Session ID returned by a previous call to login.
501      * @param array $module_name(s) -- The name of the module(s) to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
502      * @return array $type The type(s) of views requested.  Current supported types are 'default' (for application) and 'wireless'
503      * @return array $view The view(s) requested.  Current supported types are edit, detail, list, and subpanel.
504      * @exception 'SoapFault' -- The SOAP error, if any
505      */
506     function get_module_layout($session, $a_module_names, $a_type, $a_view,$acl_check = TRUE, $md5 = FALSE){
507         $GLOBALS['log']->fatal('Begin: SugarWebServiceImpl->get_module_layout');
508
509         global  $beanList, $beanFiles;
510         $error = new SoapError();
511         $results = array();
512         foreach ($a_module_names as $module_name)
513         {
514             if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error))
515             {
516                 $GLOBALS['log']->info('End: SugarWebServiceImpl->get_module_layout');
517                 continue;
518             }
519
520             $class_name = $beanList[$module_name];
521             require_once($beanFiles[$class_name]);
522             $seed = new $class_name();
523
524             foreach ($a_view as $view)
525             {
526                 $aclViewCheck = (strtolower($view) == 'subpanel') ? 'DetailView' : ucfirst(strtolower($view)) . 'View';
527                 if(!$acl_check || $seed->ACLAccess($aclViewCheck, true) )
528                 {
529                     foreach ($a_type as $type)
530                     {
531                         $a_vardefs = self::$helperObject->get_module_view_defs($module_name, $type, $view);
532                         if($md5)
533                             $results[$module_name][$type][$view] = md5(serialize($a_vardefs));
534                         else
535                             $results[$module_name][$type][$view] = $a_vardefs;
536                     }
537                 }
538             }
539         }
540
541         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_module_layout');
542
543         return $results;
544     }
545
546     /**
547      * Retrieve a list of beans.  This is the primary method for getting list of SugarBeans from Sugar using the SOAP API.
548      *
549      * @param String $session -- Session ID returned by a previous call to login.
550      * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
551      * @param String $query -- SQL where clause without the word 'where'
552      * @param String $order_by -- SQL order by clause without the phrase 'order by'
553      * @param integer $offset -- The record offset to start from.
554      * @param Array  $select_fields -- A list of the fields to be included in the results. This optional parameter allows for only needed fields to be retrieved.
555      * @param Array $link_name_to_fields_array -- A list of link_names and for each link_name, what fields value to be returned. For ex.'link_name_to_fields_array' => array(array('name' =>  'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address')))
556     * @param integer $max_results -- The maximum number of records to return.  The default is the sugar configuration value for 'list_max_entries_per_page'
557      * @param integer $deleted -- false if deleted records should not be include, true if deleted records should be included.
558      * @return Array 'result_count' -- integer - The number of records returned
559      *               'next_offset' -- integer - The start of the next page (This will always be the previous offset plus the number of rows returned.  It does not indicate if there is additional data unless you calculate that the next_offset happens to be closer than it should be.
560      *               'entry_list' -- Array - The records that were retrieved
561      *                   'relationship_list' -- Array - The records link field data. The example is if asked about accounts email address then return data would look like Array ( [0] => Array ( [name] => email_addresses [records] => Array ( [0] => Array ( [0] => Array ( [name] => id [value] => 3fb16797-8d90-0a94-ac12-490b63a6be67 ) [1] => Array ( [name] => email_address [value] => hr.kid.qa@example.com ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 1 ) ) [1] => Array ( [0] => Array ( [name] => id [value] => 403f8da1-214b-6a88-9cef-490b63d43566 ) [1] => Array ( [name] => email_address [value] => kid.hr@example.name ) [2] => Array ( [name] => opt_out [value] => 0 ) [3] => Array ( [name] => primary_address [value] => 0 ) ) ) ) )
562     * @exception 'SoapFault' -- The SOAP error, if any
563     */
564     function get_entry_list($session, $module_name, $query, $order_by,$offset, $select_fields, $link_name_to_fields_array, $max_results, $deleted, $favorites = false ){
565
566         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_entry_list');
567         global  $beanList, $beanFiles;
568         $error = new SoapError();
569         $using_cp = false;
570         if($module_name == 'CampaignProspects'){
571             $module_name = 'Prospects';
572             $using_cp = true;
573         }
574         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error)) {
575             $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list');
576             return;
577         } // if
578
579         // If the maximum number of entries per page was specified, override the configuration value.
580         if($max_results > 0){
581             global $sugar_config;
582             $sugar_config['list_max_entries_per_page'] = $max_results;
583         } // if
584
585         $class_name = $beanList[$module_name];
586         require_once($beanFiles[$class_name]);
587         $seed = new $class_name();
588
589         if (!self::$helperObject->checkACLAccess($seed, 'Export', $error, 'no_access')) {
590             $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list');
591             return;
592         } // if
593
594         if (!self::$helperObject->checkACLAccess($seed, 'list', $error, 'no_access')) {
595             $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list');
596             return;
597         } // if
598
599         if($query == ''){
600             $where = '';
601         } // if
602         if($offset == '' || $offset == -1){
603             $offset = 0;
604         } // if
605         if($using_cp){
606             $response = $seed->retrieveTargetList($query, $select_fields, $offset,-1,-1,$deleted);
607         }else
608         {
609             $response = self::$helperObject->get_data_list($seed,$order_by, $query, $offset,-1,-1,$deleted,$favorites);
610         } // else
611         $list = $response['list'];
612
613         $output_list = array();
614         $linkoutput_list = array();
615
616         foreach($list as $value) {
617             if(isset($value->emailAddress)){
618                 $value->emailAddress->handleLegacyRetrieve($value);
619             } // if
620             $value->fill_in_additional_detail_fields();
621
622             $output_list[] = self::$helperObject->get_return_value_for_fields($value, $module_name, $select_fields);
623             if(!empty($link_name_to_fields_array)){
624                 $linkoutput_list[] = self::$helperObject->get_return_value_for_link_fields($value, $module_name, $link_name_to_fields_array);
625             }
626         } // foreach
627
628         // Calculate the offset for the start of the next page
629         $next_offset = $offset + sizeof($output_list);
630
631                 $returnRelationshipList = array();
632                 foreach($linkoutput_list as $rel){
633                         $link_output = array();
634                         foreach($rel as $row){
635                                 $rowArray = array();
636                                 foreach($row['records'] as $record){
637                                         $rowArray[]['link_value'] = $record;
638                                 }
639                                 $link_output[] = array('name' => $row['name'], 'records' => $rowArray);
640                         }
641                         $returnRelationshipList[]['link_list'] = $link_output;
642                 }
643
644                 $totalRecordCount = $response['row_count'];
645         if( !empty($sugar_config['disable_count_query']) )
646             $totalRecordCount = -1;
647
648         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list');
649         return array('result_count'=>sizeof($output_list), 'total_count' => $totalRecordCount, 'next_offset'=>$next_offset, 'entry_list'=>$output_list, 'relationship_list' => $returnRelationshipList);
650     } // fn
651
652
653
654     /**
655      * Given a list of modules to search and a search string, return the id, module_name, along with the fields
656      * We will support Accounts, Bug Tracker, Cases, Contacts, Leads, Opportunities, Project, ProjectTask, Quotes
657      *
658      * @param string $session                   - Session ID returned by a previous call to login.
659      * @param string $search_string     - string to search
660      * @param string[] $modules                 - array of modules to query
661      * @param int $offset                               - a specified offset in the query
662      * @param int $max_results                  - max number of records to return
663      * @param string $assigned_user_id  - a user id to filter all records by, leave empty to exclude the filter
664      * @param string[] $select_fields   - An array of fields to return.  If empty the default return fields will be from the active list view defs.
665      * @param bool $unified_search_only - A boolean indicating if we should only search against those modules participating in the unified search.
666      * @return Array return_search_result       - Array('Accounts' => array(array('name' => 'first_name', 'value' => 'John', 'name' => 'last_name', 'value' => 'Do')))
667      * @exception 'SoapFault' -- The SOAP error, if any
668      */
669     function search_by_module($session, $search_string, $modules, $offset, $max_results,$assigned_user_id = '', $select_fields = array(), $unified_search_only = TRUE){
670         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->search_by_module');
671         global  $beanList, $beanFiles;
672         global $sugar_config,$current_language;
673
674         $error = new SoapError();
675         $output_list = array();
676         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
677                 $error->set_error('invalid_login');
678                 $GLOBALS['log']->info('End: SugarWebServiceImpl->search_by_module');
679                 return;
680         }
681         global $current_user;
682         if($max_results > 0){
683                 $sugar_config['list_max_entries_per_page'] = $max_results;
684         }
685
686         require_once('modules/Home/UnifiedSearchAdvanced.php');
687         require_once 'include/utils.php';
688         $usa = new UnifiedSearchAdvanced();
689         if(!file_exists($GLOBALS['sugar_config']['cache_dir'].'modules/unified_search_modules.php')) {
690             $usa->buildCache();
691         }
692
693         include($GLOBALS['sugar_config']['cache_dir'].'modules/unified_search_modules.php');
694         $modules_to_search = array();
695         $unified_search_modules['Users'] =   array('fields' => array());
696
697         $unified_search_modules['ProjectTask'] =   array('fields' => array());
698
699         //If we are ignoring the unified search flag within the vardef we need to re-create the search fields.  This allows us to search
700         //against a specific module even though it is not enabled for the unified search within the application.
701         if( !$unified_search_only )
702         {
703             foreach ($modules as $singleModule)
704             {
705                 if( !isset($unified_search_modules[$singleModule]) )
706                 {
707                     $newSearchFields = array('fields' => self::$helperObject->generateUnifiedSearchFields($singleModule) );
708                     $unified_search_modules[$singleModule] = $newSearchFields;
709                 }
710             }
711         }
712
713
714         foreach($unified_search_modules as $module=>$data) {
715                 if (in_array($module, $modules)) {
716                 $modules_to_search[$module] = $beanList[$module];
717                 } // if
718         } // foreach
719
720         $GLOBALS['log']->info('SugarWebServiceImpl->search_by_module - search string = ' . $search_string);
721
722         if(!empty($search_string) && isset($search_string)) {
723                 $search_string = trim($GLOBALS['db']->quote(securexss(from_html(clean_string($search_string, 'UNIFIED_SEARCH')))));
724                 foreach($modules_to_search as $name => $beanName) {
725                         $where_clauses_array = array();
726                         $unifiedSearchFields = array () ;
727                         foreach ($unified_search_modules[$name]['fields'] as $field=>$def ) {
728                                 $unifiedSearchFields[$name] [ $field ] = $def ;
729                                 $unifiedSearchFields[$name] [ $field ]['value'] = $search_string;
730                         }
731
732                         require_once $beanFiles[$beanName] ;
733                         $seed = new $beanName();
734                         require_once 'include/SearchForm/SearchForm2.php' ;
735                         if ($beanName == "User"
736                             || $beanName == "ProjectTask"
737                             ) {
738                                 if(!self::$helperObject->check_modules_access($current_user, $seed->module_dir, 'read')){
739                                         continue;
740                                 } // if
741                                 if(!$seed->ACLAccess('ListView')) {
742                                         continue;
743                                 } // if
744                         }
745
746                         if ($beanName != "User"
747                             && $beanName != "ProjectTask"
748                             ) {
749                                 $searchForm = new SearchForm ($seed, $name ) ;
750
751                                 $searchForm->setup(array ($name => array()) ,$unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
752                                 $where_clauses = $searchForm->generateSearchWhere() ;
753                                 require_once 'include/SearchForm/SearchForm2.php' ;
754                                 $searchForm = new SearchForm ($seed, $name ) ;
755
756                                 $searchForm->setup(array ($name => array()) ,$unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
757                                 $where_clauses = $searchForm->generateSearchWhere() ;
758                                 $emailQuery = false;
759
760                                 $where = '';
761                                 if (count($where_clauses) > 0 ) {
762                                         $where = '('. implode(' ) OR ( ', $where_clauses) . ')';
763                                 }
764
765                                 $mod_strings = return_module_language($current_language, $seed->module_dir);
766
767                                 if(count($select_fields) > 0)
768                                     $filterFields = $select_fields;
769                                 else {
770                                     if(file_exists('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php'))
771                                            require_once('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
772                                         else
773                                                 require_once('modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
774
775                                         $filterFields = array();
776                                         foreach($listViewDefs[$seed->module_dir] as $colName => $param) {
777                                 if(!empty($param['default']) && $param['default'] == true)
778                                     $filterFields[] = strtolower($colName);
779                             }
780                             if (!in_array('id', $filterFields))
781                                 $filterFields[] = 'id';
782                                 }
783
784                                 //Pull in any db fields used for the unified search query so the correct joins will be added
785                                 $selectOnlyQueryFields = array();
786                                 foreach ($unifiedSearchFields[$name] as $field => $def){
787                                     if( isset($def['db_field']) && !in_array($field,$filterFields) ){
788                                         $filterFields[] = $field;
789                                         $selectOnlyQueryFields[] = $field;
790                                     }
791                                 }
792
793                     //Add the assigned user filter if applicable
794                     if (!empty($assigned_user_id) && isset( $seed->field_defs['assigned_user_id']) ) {
795                        $ownerWhere = $seed->getOwnerWhere($assigned_user_id);
796                        $where = "($where) AND $ownerWhere";
797                     }
798
799                     if( $beanName == "Employee" )
800                     {
801                         $where = "($where) AND users.deleted = 0 AND users.is_group = 0 AND users.employee_status = 'Active'";
802                     }
803
804                                 $ret_array = $seed->create_new_list_query('', $where, $filterFields, array(), 0, '', true, $seed, true);
805                         if(empty($params) or !is_array($params)) $params = array();
806                         if(!isset($params['custom_select'])) $params['custom_select'] = '';
807                         if(!isset($params['custom_from'])) $params['custom_from'] = '';
808                         if(!isset($params['custom_where'])) $params['custom_where'] = '';
809                         if(!isset($params['custom_order_by'])) $params['custom_order_by'] = '';
810                                 $main_query = $ret_array['select'] . $params['custom_select'] . $ret_array['from'] . $params['custom_from'] . $ret_array['where'] . $params['custom_where'] . $ret_array['order_by'] . $params['custom_order_by'];
811                         } else {
812                                 if ($beanName == "User") {
813                                         $filterFields = array('id', 'user_name', 'first_name', 'last_name', 'email_address');
814                                         $main_query = "select users.id, ea.email_address, users.user_name, first_name, last_name from users ";
815                                         $main_query = $main_query . " LEFT JOIN email_addr_bean_rel eabl ON eabl.bean_module = '{$seed->module_dir}'
816     LEFT JOIN email_addresses ea ON (ea.id = eabl.email_address_id) ";
817                                         $main_query = $main_query . "where ((users.first_name like '{$search_string}') or (users.last_name like '{$search_string}') or (users.user_name like '{$search_string}') or (ea.email_address like '{$search_string}')) and users.deleted = 0 and users.is_group = 0 and users.employee_status = 'Active'";
818                                 } // if
819                                 if ($beanName == "ProjectTask") {
820                                         $filterFields = array('id', 'name', 'project_id', 'project_name');
821                                         $main_query = "select {$seed->table_name}.project_task_id id,{$seed->table_name}.project_id, {$seed->table_name}.name, project.name project_name from {$seed->table_name} ";
822                                         $seed->add_team_security_where_clause($main_query);
823                                         $main_query .= "LEFT JOIN teams ON $seed->table_name.team_id=teams.id AND (teams.deleted=0) ";
824                             $main_query .= "LEFT JOIN project ON $seed->table_name.project_id = project.id ";
825                             $main_query .= "where {$seed->table_name}.name like '{$search_string}%'";
826                                 } // if
827                         } // else
828
829                         $GLOBALS['log']->info('SugarWebServiceImpl->search_by_module - query = ' . $main_query);
830                         if($max_results < -1) {
831                                 $result = $seed->db->query($main_query);
832                         }
833                         else {
834                                 if($max_results == -1) {
835                                         $limit = $sugar_config['list_max_entries_per_page'];
836                     } else {
837                         $limit = $max_results;
838                     }
839                     $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
840                         }
841
842                         $rowArray = array();
843                         while($row = $seed->db->fetchByAssoc($result)) {
844                                 $nameValueArray = array();
845                                 foreach ($filterFields as $field) {
846                                     if(in_array($field, $selectOnlyQueryFields))
847                                         continue;
848                                         $nameValue = array();
849                                         if (isset($row[$field])) {
850                                                 $nameValueArray[$field] = self::$helperObject->get_name_value($field, $row[$field]);
851                                         } // if
852                                 } // foreach
853                                 $rowArray[] = $nameValueArray;
854                         } // while
855                         $output_list[] = array('name' => $name, 'records' => $rowArray);
856                 } // foreach
857
858         $GLOBALS['log']->info('End: SugarWebServiceImpl->search_by_module');
859         return array('entry_list'=>$output_list);
860         } // if
861         return array('entry_list'=>$output_list);
862     } // fn
863 }
864
865 SugarWebServiceImplv3_1::$helperObject = new SugarWebServiceUtilv3_1();