]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - service/v4/SugarWebServiceImplv4.php
Release 6.5.1
[Github/sugarcrm.git] / service / v4 / SugarWebServiceImplv4.php
1 <?php
2 if(!defined('sugarEntry'))define('sugarEntry', true);
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 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_1/SugarWebServiceImplv3_1.php');
43 require_once('SugarWebServiceUtilv4.php');
44
45
46 class SugarWebServiceImplv4 extends SugarWebServiceImplv3_1 {
47
48     public function __construct()
49     {
50         self::$helperObject = new SugarWebServiceUtilv4();
51     }
52
53         /**
54      * Log the user into the application
55      *
56      * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
57      *      in the right encoding for the type of authentication the user is setup for.  For Base
58      *      sugar validation, password is the MD5 sum of the plain text password.
59      * @param String $application -- The name of the application you are logging in from.  (Currently unused).
60      * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
61      * @return Array - id - String id is the session_id of the session that was created.
62      *                           - module_name - String - module name of user
63      *                           - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name,
64      *                                         - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat
65      * @exception 'SoapFault' -- The SOAP error, if any
66      */
67     public function login($user_auth, $application, $name_value_list = array()){
68         $GLOBALS['log']->info("Begin: SugarWebServiceImpl->login({$user_auth['user_name']}, $application, ". print_r($name_value_list, true) .")");
69         global $sugar_config, $system_config;
70         $error = new SoapError();
71         $user = new User();
72         $success = false;
73         //rrs
74         $system_config = new Administration();
75         $system_config->retrieveSettings('system');
76         $authController = new AuthenticationController((!empty($sugar_config['authenticationClass'])? $sugar_config['authenticationClass'] : 'SugarAuthenticate'));
77         //rrs
78         if(!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN' && $authController->authController->userAuthenticateClass != "LDAPAuthenticateUser")
79         {
80             $user_auth['password'] = md5($user_auth['password']);
81         }
82         $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true));
83         $usr_id=$user->retrieve_user_id($user_auth['user_name']);
84         if($usr_id)
85             $user->retrieve($usr_id);
86
87         if ($isLoginSuccess)
88         {
89             if ($_SESSION['hasExpiredPassword'] =='1')
90             {
91                 $error->set_error('password_expired');
92                 $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']);
93                 LogicHook::initialize();
94                 $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
95                 self::$helperObject->setFaultObject($error);
96                 return;
97             }
98             if(!empty($user) && !empty($user->id) && !$user->is_group)
99             {
100                 $success = true;
101                 global $current_user;
102                 $current_user = $user;
103             }
104         }
105         else if($usr_id && isset($user->user_name) && ($user->getPreference('lockout') == '1'))
106         {
107             $error->set_error('lockout_reached');
108             $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']);
109             LogicHook::initialize();
110             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
111             self::$helperObject->setFaultObject($error);
112             return;
113         }
114                 else if(function_exists('mcrypt_cbc') && $authController->authController->userAuthenticateClass == "LDAPAuthenticateUser"
115                         && (empty($user_auth['encryption']) || $user_auth['encryption'] !== 'PLAIN' ) )
116         {
117             $password = self::$helperObject->decrypt_string($user_auth['password']);
118             $authController->loggedIn = false; // reset login attempt to try again with decrypted password
119             if($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id']))
120                 $success = true;
121         }
122         else if( $authController->authController->userAuthenticateClass == "LDAPAuthenticateUser"
123                  && (empty($user_auth['encryption']) || $user_auth['encryption'] == 'PLAIN' ) )
124         {
125
126                 $authController->loggedIn = false; // reset login attempt to try again with md5 password
127                 if($authController->login($user_auth['user_name'], md5($user_auth['password']), array('passwordEncrypted' => true))
128                         && isset($_SESSION['authenticated_user_id']))
129                 {
130                         $success = true;
131                 }
132                 else
133                 {
134
135                     $error->set_error('ldap_error');
136                     LogicHook::initialize();
137                     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
138                     self::$helperObject->setFaultObject($error);
139                     return;
140                 }
141         }
142
143
144         if($success)
145         {
146             session_start();
147             global $current_user;
148             //$current_user = $user;
149             self::$helperObject->login_success($name_value_list);
150             $current_user->loadPreferences();
151             $_SESSION['is_valid_session']= true;
152             $_SESSION['ip_address'] = query_client_ip();
153             $_SESSION['user_id'] = $current_user->id;
154             $_SESSION['type'] = 'user';
155             $_SESSION['avail_modules']= self::$helperObject->get_user_module_list($current_user);
156             $_SESSION['authenticated_user_id'] = $current_user->id;
157             $_SESSION['unique_key'] = $sugar_config['unique_key'];
158             $GLOBALS['log']->info('End: SugarWebServiceImpl->login - successful login');
159             $current_user->call_custom_logic('after_login');
160             $nameValueArray = array();
161             global $current_language;
162             $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id);
163             $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
164             $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language);
165             $cur_id = $current_user->getPreference('currency');
166             $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id);
167             $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user));
168             $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team );
169             $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef') );
170             $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef') );
171
172             $num_grp_sep = $current_user->getPreference('num_grp_sep');
173             $dec_sep = $current_user->getPreference('dec_sep');
174             $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);
175             $nameValueArray['user_decimal_seperator'] = self::$helperObject->get_name_value('user_decimal_seperator', empty($dec_sep) ? $sugar_config['default_decimal_seperator'] : $dec_sep);
176
177             $nameValueArray['mobile_max_list_entries'] = self::$helperObject->get_name_value('mobile_max_list_entries', $sugar_config['wl_list_max_entries_per_page'] );
178             $nameValueArray['mobile_max_subpanel_entries'] = self::$helperObject->get_name_value('mobile_max_subpanel_entries', $sugar_config['wl_list_max_entries_per_subpanel'] );
179
180
181             $currencyObject = new Currency();
182             $currencyObject->retrieve($cur_id);
183             $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name);
184             $_SESSION['user_language'] = $current_language;
185             return array('id'=>session_id(), 'module_name'=>'Users', 'name_value_list'=>$nameValueArray);
186         }
187         LogicHook::initialize();
188         $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
189         $error->set_error('invalid_login');
190         self::$helperObject->setFaultObject($error);
191         $GLOBALS['log']->error('End: SugarWebServiceImpl->login - failed login');
192     }
193
194
195         /**
196          * Retrieve a list of SugarBean's based on provided IDs. This API will not wotk with report module
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 $ids -- An array of SugarBean IDs.
201          * @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.
202          * @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')))
203          * @return Array
204          *        'entry_list' -- Array - The records name value pair for the simple data types excluding link field data.
205          *           '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 ) ) ) ) )
206          * @exception 'SoapFault' -- The SOAP error, if any
207          */
208         public function get_entries($session, $module_name, $ids, $select_fields, $link_name_to_fields_array)
209         {
210             $result = parent::get_entries($session, $module_name, $ids, $select_fields, $link_name_to_fields_array);
211                 $relationshipList = $result['relationship_list'];
212                 $returnRelationshipList = array();
213                 foreach($relationshipList as $rel){
214                         $link_output = array();
215                         foreach($rel as $row){
216                                 $rowArray = array();
217                                 foreach($row['records'] as $record){
218                                         $rowArray[]['link_value'] = $record;
219                                 }
220                                 $link_output[] = array('name' => $row['name'], 'records' => $rowArray);
221                         }
222                         $returnRelationshipList[]['link_list'] = $link_output;
223                 }
224
225                 $result['relationship_list'] = $returnRelationshipList;
226                 return $result;
227         }
228
229             /**
230      * Retrieve a list of beans.  This is the primary method for getting list of SugarBeans from Sugar using the SOAP API.
231      *
232      * @param String $session -- Session ID returned by a previous call to login.
233      * @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)..
234      * @param String $query -- SQL where clause without the word 'where'
235      * @param String $order_by -- SQL order by clause without the phrase 'order by'
236      * @param integer $offset -- The record offset to start from.
237      * @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.
238      * @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')))
239     * @param integer $max_results -- The maximum number of records to return.  The default is the sugar configuration value for 'list_max_entries_per_page'
240      * @param integer $deleted -- false if deleted records should not be include, true if deleted records should be included.
241      * @return Array 'result_count' -- integer - The number of records returned
242      *               '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.
243      *               'entry_list' -- Array - The records that were retrieved
244      *                   '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 ) ) ) ) )
245     * @exception 'SoapFault' -- The SOAP error, if any
246     */
247     function get_entry_list($session, $module_name, $query, $order_by,$offset, $select_fields, $link_name_to_fields_array, $max_results, $deleted, $favorites = false ){
248
249         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_entry_list');
250         global  $beanList, $beanFiles;
251         $error = new SoapError();
252         $using_cp = false;
253         if($module_name == 'CampaignProspects'){
254             $module_name = 'Prospects';
255             $using_cp = true;
256         }
257         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error)) {
258             $GLOBALS['log']->error('End: SugarWebServiceImpl->get_entry_list - FAILED on checkSessionAndModuleAccess');
259             return;
260         } // if
261
262         if (!self::$helperObject->checkQuery($error, $query, $order_by)) {
263                 $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list');
264                 return;
265         } // if
266
267         // If the maximum number of entries per page was specified, override the configuration value.
268         if($max_results > 0){
269             global $sugar_config;
270             $sugar_config['list_max_entries_per_page'] = $max_results;
271         } // if
272
273         $class_name = $beanList[$module_name];
274         require_once($beanFiles[$class_name]);
275         $seed = new $class_name();
276
277         if (!self::$helperObject->checkACLAccess($seed, 'list', $error, 'no_access')) {
278             $GLOBALS['log']->error('End: SugarWebServiceImpl->get_entry_list - FAILED on checkACLAccess');
279             return;
280         } // if
281
282         if($query == ''){
283             $where = '';
284         } // if
285         if($offset == '' || $offset == -1){
286             $offset = 0;
287         } // if
288         if($deleted){
289             $deleted = -1;
290         }
291         if($using_cp){
292             $response = $seed->retrieveTargetList($query, $select_fields, $offset,-1,-1,$deleted);
293         }else
294         {
295             $response = self::$helperObject->get_data_list($seed,$order_by, $query, $offset,-1,-1,$deleted,$favorites);
296         } // else
297         $list = $response['list'];
298
299         $output_list = array();
300         $linkoutput_list = array();
301
302         foreach($list as $value) {
303             if(isset($value->emailAddress)){
304                 $value->emailAddress->handleLegacyRetrieve($value);
305             } // if
306             $value->fill_in_additional_detail_fields();
307
308             $output_list[] = self::$helperObject->get_return_value_for_fields($value, $module_name, $select_fields);
309             if(!empty($link_name_to_fields_array)){
310                 $linkoutput_list[] = self::$helperObject->get_return_value_for_link_fields($value, $module_name, $link_name_to_fields_array);
311             }
312         } // foreach
313
314         // Calculate the offset for the start of the next page
315         $next_offset = $offset + sizeof($output_list);
316
317                 $returnRelationshipList = array();
318                 foreach($linkoutput_list as $rel){
319                         $link_output = array();
320                         foreach($rel as $row){
321                                 $rowArray = array();
322                                 foreach($row['records'] as $record){
323                                         $rowArray[]['link_value'] = $record;
324                                 }
325                                 $link_output[] = array('name' => $row['name'], 'records' => $rowArray);
326                         }
327                         $returnRelationshipList[]['link_list'] = $link_output;
328                 }
329
330                 $totalRecordCount = $response['row_count'];
331         if( !empty($sugar_config['disable_count_query']) )
332             $totalRecordCount = -1;
333
334         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_entry_list - SUCCESS');
335         return array('result_count'=>sizeof($output_list), 'total_count' => $totalRecordCount, 'next_offset'=>$next_offset, 'entry_list'=>$output_list, 'relationship_list' => $returnRelationshipList);
336     } // fn
337
338         /**
339      * Retrieve the layout metadata for a given module given a specific type and view.
340      *
341      * @param String $session -- Session ID returned by a previous call to login.
342      * @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)..
343      * @return array $type The type(s) of views requested.  Current supported types are 'default' (for application) and 'wireless'
344      * @return array $view The view(s) requested.  Current supported types are edit, detail, list, and subpanel.
345      * @exception 'SoapFault' -- The SOAP error, if any
346      */
347     function get_module_layout($session, $a_module_names, $a_type, $a_view,$acl_check = TRUE, $md5 = FALSE){
348         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_module_layout');
349
350         global  $beanList, $beanFiles;
351         $error = new SoapError();
352         $results = array();
353         foreach ($a_module_names as $module_name)
354         {
355             if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', $module_name, 'read', 'no_access', $error))
356             {
357                 $GLOBALS['log']->error("End: SugarWebServiceImpl->get_module_layout for $module_name - FAILED on checkSessionAndModuleAccess");
358                 continue;
359             }
360
361             if( empty($module_name) )
362                 continue;
363
364             $class_name = $beanList[$module_name];
365             require_once($beanFiles[$class_name]);
366             $seed = new $class_name();
367
368             foreach ($a_view as $view)
369             {
370                 $aclViewCheck = (strtolower($view) == 'subpanel') ? 'DetailView' : ucfirst(strtolower($view)) . 'View';
371                 if(!$acl_check || $seed->ACLAccess($aclViewCheck, true) )
372                 {
373                     foreach ($a_type as $type)
374                     {
375                         $a_vardefs = self::$helperObject->get_module_view_defs($module_name, $type, $view);
376                         if($md5)
377                             $results[$module_name][$type][$view] = md5(serialize($a_vardefs));
378                         else
379                             $results[$module_name][$type][$view] = $a_vardefs;
380                     }
381                 }
382             }
383         }
384
385         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_module_layout ->> '.print_r($results,true) );
386
387         return $results;
388     }
389
390
391         /**
392      * Given a list of modules to search and a search string, return the id, module_name, along with the fields
393      * We will support Accounts, Bug Tracker, Cases, Contacts, Leads, Opportunities, Project, ProjectTask, Quotes
394      *
395      * @param string $session                   - Session ID returned by a previous call to login.
396      * @param string $search_string     - string to search
397      * @param string[] $modules                 - array of modules to query
398      * @param int $offset                               - a specified offset in the query
399      * @param int $max_results                  - max number of records to return
400      * @param string $assigned_user_id  - a user id to filter all records by, leave empty to exclude the filter
401      * @param string[] $select_fields   - An array of fields to return.  If empty the default return fields will be from the active list view defs.
402      * @param bool $unified_search_only - A boolean indicating if we should only search against those modules participating in the unified search.
403      * @param bool $favorites           - A boolean indicating if we should only search against records marked as favorites.
404      * @return Array return_search_result       - Array('Accounts' => array(array('name' => 'first_name', 'value' => 'John', 'name' => 'last_name', 'value' => 'Do')))
405      * @exception 'SoapFault' -- The SOAP error, if any
406      */
407     function search_by_module($session, $search_string, $modules, $offset, $max_results,$assigned_user_id = '', $select_fields = array(), $unified_search_only = TRUE, $favorites = FALSE){
408         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->search_by_module');
409         global  $beanList, $beanFiles;
410         global $sugar_config,$current_language;
411
412         $error = new SoapError();
413         $output_list = array();
414         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
415                 $error->set_error('invalid_login');
416                 $GLOBALS['log']->error('End: SugarWebServiceImpl->search_by_module - FAILED on checkSessionAndModuleAccess');
417                 return;
418         }
419         global $current_user;
420         if($max_results > 0){
421                 $sugar_config['list_max_entries_per_page'] = $max_results;
422         }
423
424         require_once('modules/Home/UnifiedSearchAdvanced.php');
425         require_once 'include/utils.php';
426         $usa = new UnifiedSearchAdvanced();
427         if(!file_exists($cachefile = sugar_cached('modules/unified_search_modules.php'))) {
428             $usa->buildCache();
429         }
430
431         include $cachefile;
432         $modules_to_search = array();
433         $unified_search_modules['Users'] =   array('fields' => array());
434
435         $unified_search_modules['ProjectTask'] =   array('fields' => array());
436
437         //If we are ignoring the unified search flag within the vardef we need to re-create the search fields.  This allows us to search
438         //against a specific module even though it is not enabled for the unified search within the application.
439         if( !$unified_search_only )
440         {
441             foreach ($modules as $singleModule)
442             {
443                 if( !isset($unified_search_modules[$singleModule]) )
444                 {
445                     $newSearchFields = array('fields' => self::$helperObject->generateUnifiedSearchFields($singleModule) );
446                     $unified_search_modules[$singleModule] = $newSearchFields;
447                 }
448             }
449         }
450
451
452         foreach($unified_search_modules as $module=>$data) {
453                 if (in_array($module, $modules)) {
454                 $modules_to_search[$module] = $beanList[$module];
455                 } // if
456         } // foreach
457
458         $GLOBALS['log']->info('SugarWebServiceImpl->search_by_module - search string = ' . $search_string);
459
460         if(!empty($search_string) && isset($search_string)) {
461                 $search_string = trim($GLOBALS['db']->quote(securexss(from_html(clean_string($search_string, 'UNIFIED_SEARCH')))));
462                 foreach($modules_to_search as $name => $beanName) {
463                         $where_clauses_array = array();
464                         $unifiedSearchFields = array () ;
465                         foreach ($unified_search_modules[$name]['fields'] as $field=>$def ) {
466                                 $unifiedSearchFields[$name] [ $field ] = $def ;
467                                 $unifiedSearchFields[$name] [ $field ]['value'] = $search_string;
468                         }
469
470                         require_once $beanFiles[$beanName] ;
471                         $seed = new $beanName();
472                         require_once 'include/SearchForm/SearchForm2.php' ;
473                         if ($beanName == "User"
474                             || $beanName == "ProjectTask"
475                             ) {
476                                 if(!self::$helperObject->check_modules_access($current_user, $seed->module_dir, 'read')){
477                                         continue;
478                                 } // if
479                                 if(!$seed->ACLAccess('ListView')) {
480                                         continue;
481                                 } // if
482                         }
483
484                         if ($beanName != "User"
485                             && $beanName != "ProjectTask"
486                             ) {
487                                 $searchForm = new SearchForm ($seed, $name ) ;
488
489                                 $searchForm->setup(array ($name => array()) ,$unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
490                                 $where_clauses = $searchForm->generateSearchWhere() ;
491                                 require_once 'include/SearchForm/SearchForm2.php' ;
492                                 $searchForm = new SearchForm ($seed, $name ) ;
493
494                                 $searchForm->setup(array ($name => array()) ,$unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
495                                 $where_clauses = $searchForm->generateSearchWhere() ;
496                                 $emailQuery = false;
497
498                                 $where = '';
499                                 if (count($where_clauses) > 0 ) {
500                                         $where = '('. implode(' ) OR ( ', $where_clauses) . ')';
501                                 }
502
503                                 $mod_strings = return_module_language($current_language, $seed->module_dir);
504
505                                 if(count($select_fields) > 0)
506                                     $filterFields = $select_fields;
507                                 else {
508                                     if(file_exists('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php'))
509                                            require_once('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
510                                         else
511                                                 require_once('modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
512
513                                         $filterFields = array();
514                                         foreach($listViewDefs[$seed->module_dir] as $colName => $param) {
515                                 if(!empty($param['default']) && $param['default'] == true)
516                                     $filterFields[] = strtolower($colName);
517                             }
518                             if (!in_array('id', $filterFields))
519                                 $filterFields[] = 'id';
520                                 }
521
522                                 //Pull in any db fields used for the unified search query so the correct joins will be added
523                                 $selectOnlyQueryFields = array();
524                                 foreach ($unifiedSearchFields[$name] as $field => $def){
525                                     if( isset($def['db_field']) && !in_array($field,$filterFields) ){
526                                         $filterFields[] = $field;
527                                         $selectOnlyQueryFields[] = $field;
528                                     }
529                                 }
530
531                     //Add the assigned user filter if applicable
532                     if (!empty($assigned_user_id) && isset( $seed->field_defs['assigned_user_id']) ) {
533                        $ownerWhere = $seed->getOwnerWhere($assigned_user_id);
534                        $where = "($where) AND $ownerWhere";
535                     }
536
537                     if( $beanName == "Employee" )
538                     {
539                         $where = "($where) AND users.deleted = 0 AND users.is_group = 0 AND users.employee_status = 'Active'";
540                     }
541
542                     $list_params = array();
543
544                                 $ret_array = $seed->create_new_list_query('', $where, $filterFields, $list_params, 0, '', true, $seed, true);
545                         if(empty($params) or !is_array($params)) $params = array();
546                         if(!isset($params['custom_select'])) $params['custom_select'] = '';
547                         if(!isset($params['custom_from'])) $params['custom_from'] = '';
548                         if(!isset($params['custom_where'])) $params['custom_where'] = '';
549                         if(!isset($params['custom_order_by'])) $params['custom_order_by'] = '';
550                                 $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'];
551                         } else {
552                                 if ($beanName == "User") {
553                                         $filterFields = array('id', 'user_name', 'first_name', 'last_name', 'email_address');
554                                         $main_query = "select users.id, ea.email_address, users.user_name, first_name, last_name from users ";
555                                         $main_query = $main_query . " LEFT JOIN email_addr_bean_rel eabl ON eabl.bean_module = '{$seed->module_dir}'
556     LEFT JOIN email_addresses ea ON (ea.id = eabl.email_address_id) ";
557                                         $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'";
558                                 } // if
559                                 if ($beanName == "ProjectTask") {
560                                         $filterFields = array('id', 'name', 'project_id', 'project_name');
561                                         $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} ";
562                                         $seed->add_team_security_where_clause($main_query);
563                                         $main_query .= "LEFT JOIN teams ON $seed->table_name.team_id=teams.id AND (teams.deleted=0) ";
564                             $main_query .= "LEFT JOIN project ON $seed->table_name.project_id = project.id ";
565                             $main_query .= "where {$seed->table_name}.name like '{$search_string}%'";
566                                 } // if
567                         } // else
568
569                         $GLOBALS['log']->info('SugarWebServiceImpl->search_by_module - query = ' . $main_query);
570                         if($max_results < -1) {
571                                 $result = $seed->db->query($main_query);
572                         }
573                         else {
574                                 if($max_results == -1) {
575                                         $limit = $sugar_config['list_max_entries_per_page'];
576                     } else {
577                         $limit = $max_results;
578                     }
579                     $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
580                         }
581
582                         $rowArray = array();
583                         while($row = $seed->db->fetchByAssoc($result)) {
584                                 $nameValueArray = array();
585                                 foreach ($filterFields as $field) {
586                                     if(in_array($field, $selectOnlyQueryFields))
587                                         continue;
588                                         $nameValue = array();
589                                         if (isset($row[$field])) {
590                                                 $nameValueArray[$field] = self::$helperObject->get_name_value($field, $row[$field]);
591                                         } // if
592                                 } // foreach
593                                 $rowArray[] = $nameValueArray;
594                         } // while
595                         $output_list[] = array('name' => $name, 'records' => $rowArray);
596                 } // foreach
597
598         $GLOBALS['log']->info('End: SugarWebServiceImpl->search_by_module');
599         return array('entry_list'=>$output_list);
600         } // if
601         return array('entry_list'=>$output_list);
602     } // fn
603
604
605
606     /**
607      * Get OAuth reqtest token
608      */
609     public function oauth_request_token()
610     {
611         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->oauth_request_token');
612         require_once "include/SugarOAuthServer.php";
613         try {
614                 $oauth = new SugarOAuthServer(rtrim($GLOBALS['sugar_config']['site_url'],'/').'/service/v4/rest.php');
615                 $result = $oauth->requestToken()."&oauth_callback_confirmed=true&authorize_url=".$oauth->authURL();
616         } catch(OAuthException $e) {
617             $GLOBALS['log']->debug("OAUTH Exception: $e");
618             $errorObject = new SoapError();
619             $errorObject->set_error('invalid_login');
620                         self::$helperObject->setFaultObject($errorObject);
621             $result = null;
622         }
623         $GLOBALS['log']->info('End: SugarWebServiceImpl->oauth_request_token');
624         return $result;
625     }
626
627     /**
628      * Get OAuth access token
629      */
630     public function oauth_access_token()
631     {
632         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->oauth_access_token');
633         require_once "include/SugarOAuthServer.php";
634         try {
635                 $oauth = new SugarOAuthServer();
636                 $result = $oauth->accessToken();
637         } catch(OAuthException $e) {
638             $GLOBALS['log']->debug("OAUTH Exception: $e");
639             $errorObject = new SoapError();
640             $errorObject->set_error('invalid_login');
641                         self::$helperObject->setFaultObject($errorObject);
642             $result = null;
643         }
644         $GLOBALS['log']->info('End: SugarWebServiceImpl->oauth_access_token');
645         return $result;
646     }
647
648     public function oauth_access($session='')
649     {
650         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->oauth_access');
651         $error = new SoapError();
652         $output_list = array();
653         if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
654                 $error->set_error('invalid_login');
655                 $GLOBALS['log']->info('End: SugarWebServiceImpl->oauth_access');
656                 $result = $error;
657         } else {
658             $result = array('id'=>session_id());
659         }
660         $GLOBALS['log']->info('End: SugarWebServiceImpl->oauth_access');
661         return $result;
662     }
663
664
665     /**
666      * Get next job from the queue
667      * @param string $session
668      * @param string $clientid
669      */
670     public function job_queue_next($session, $clientid)
671     {
672         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->job_queue_next');
673         $error = new SoapError();
674         if (! self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', 'read', 'no_access',  $error)) {
675             $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_next denied.');
676             return;
677         }
678         require_once 'include/SugarQueue/SugarJobQueue.php';
679         $queue = new SugarJobQueue();
680         $job = $queue->nextJob($clientid);
681         if(!empty($job)) {
682             $jobid = $job->id;
683         } else {
684             $jobid = null;
685         }
686         $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_next');
687         return array("results" => $jobid);
688     }
689
690     /**
691      * Run cleanup and schedule
692      * @param string $session
693      * @param string $clientid
694      */
695     public function job_queue_cycle($session, $clientid)
696     {
697         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->job_queue_cycle');
698         $error = new SoapError();
699         if (! self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', 'read', 'no_access',  $error)) {
700             $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_cycle denied.');
701             return;
702         }
703         require_once 'include/SugarQueue/SugarJobQueue.php';
704         $queue = new SugarJobQueue();
705         $queue->cleanup();
706         $queue->runSchedulers();
707         $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_cycle');
708         return array("results" => "ok");
709     }
710
711     /**
712      * Run job from queue
713      * @param string $session
714      * @param string $jobid
715      * @param string $clientid
716      */
717     public function job_queue_run($session, $jobid, $clientid)
718     {
719         $GLOBALS['log']->info('Begin: SugarWebServiceImpl->job_queue_run');
720         $error = new SoapError();
721         if (! self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', 'read', 'no_access',  $error)) {
722             $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_run denied.');
723             return;
724         }
725         $GLOBALS['log']->debug('Starting job $jobid execution as $clientid');
726         require_once 'modules/SchedulersJobs/SchedulersJob.php';
727         $result = SchedulersJob::runJobId($jobid, $clientid);
728         $GLOBALS['log']->info('End: SugarWebServiceImpl->job_queue_run');
729         if($result === true) {
730             return array("results" => true);
731         } else {
732             return array("results" => false, "message" => $result);
733         }
734     }
735 }
736
737 SugarWebServiceImplv4::$helperObject = new SugarWebServiceUtilv4();