PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/service/v4/SugarWebServiceImplv4.php

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