search_api_saved_searches.module 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. <?php
  2. /**
  3. * @file
  4. * Offers the ability to save searches and be notified of new results.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function search_api_saved_searches_menu() {
  10. $items['admin/config/search/search_api/index/%search_api_index/saved_searches'] = array(
  11. 'title' => 'Saved searches',
  12. 'description' => 'Let users save searches on this index.',
  13. 'page callback' => 'drupal_get_form',
  14. 'page arguments' => array('search_api_saved_searches_index_edit', 5),
  15. 'access arguments' => array('administer search_api_saved_searches'),
  16. 'weight' => -1,
  17. 'type' => MENU_LOCAL_TASK,
  18. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  19. 'file' => 'search_api_saved_searches.admin.inc',
  20. );
  21. $items['user/%user/saved-searches'] = array(
  22. 'title' => 'Saved searches',
  23. 'description' => 'View and edit your saved searches.',
  24. 'page callback' => 'search_api_saved_searches_user_listing',
  25. 'page arguments' => array(1),
  26. 'access callback' => 'search_api_saved_search_edit_access',
  27. 'access arguments' => array(1),
  28. 'weight' => 5,
  29. 'type' => MENU_LOCAL_TASK,
  30. 'file' => 'search_api_saved_searches.pages.inc',
  31. );
  32. $items['user/%user/saved-searches/add'] = array(
  33. 'title' => 'Create saved search',
  34. 'description' => 'Create a new saved search.',
  35. 'page callback' => 'search_api_saved_searches_create_manual',
  36. 'access callback' => 'search_api_saved_search_create_access',
  37. 'access arguments' => array(NULL, TRUE),
  38. 'type' => MENU_LOCAL_ACTION,
  39. 'file' => 'search_api_saved_searches.pages.inc',
  40. );
  41. $items['search-api/saved-searches/add'] = array(
  42. 'title' => 'Create saved search',
  43. 'description' => 'Create a new saved search.',
  44. 'page callback' => 'search_api_saved_searches_create_manual',
  45. 'access callback' => 'search_api_saved_search_create_access',
  46. 'access arguments' => array(NULL, TRUE),
  47. 'file' => 'search_api_saved_searches.pages.inc',
  48. );
  49. $items['search-api/saved-searches/add/%search_api_saved_searches_settings'] = array(
  50. 'title' => 'Create saved search',
  51. 'description' => 'Create a new saved search.',
  52. 'page callback' => 'search_api_saved_searches_create_manual',
  53. 'page arguments' => array(3),
  54. 'access callback' => 'search_api_saved_search_create_access',
  55. 'access arguments' => array(3, TRUE),
  56. 'file' => 'search_api_saved_searches.pages.inc',
  57. );
  58. $items['search-api/saved-search/%search_api_saved_search/activate/%'] = array(
  59. 'title' => 'Activate saved search',
  60. 'description' => 'Activate a new saved search.',
  61. 'page callback' => 'search_api_saved_searches_activate_page',
  62. 'page arguments' => array(2, 4),
  63. 'access callback' => 'search_api_saved_search_edit_access',
  64. 'access arguments' => array(NULL, 2, 4),
  65. 'file' => 'search_api_saved_searches.pages.inc',
  66. );
  67. $items['search-api/saved-search/%search_api_saved_search/enable'] = array(
  68. 'title' => 'Enable/Disable saved search',
  69. 'description' => 'Enable or disable a saved search.',
  70. 'page callback' => 'search_api_saved_searches_search_enable',
  71. 'page arguments' => array(2),
  72. 'access callback' => 'search_api_saved_search_edit_access',
  73. 'access arguments' => array(NULL, 2, 4),
  74. 'file' => 'search_api_saved_searches.pages.inc',
  75. );
  76. $items['search-api/saved-search/%search_api_saved_search/disable'] = array(
  77. 'title' => 'Enable/Disable saved search',
  78. 'description' => 'Enable or disable a saved search.',
  79. 'page callback' => 'drupal_get_form',
  80. 'page arguments' => array('search_api_saved_searches_search_disable_form', 2),
  81. 'access callback' => 'search_api_saved_search_edit_access',
  82. 'access arguments' => array(NULL, 2, 4),
  83. 'file' => 'search_api_saved_searches.pages.inc',
  84. );
  85. $items['search-api/saved-search/%search_api_saved_search/edit'] = array(
  86. 'title' => 'Edit saved search',
  87. 'description' => 'Edit a saved search.',
  88. 'page callback' => 'drupal_get_form',
  89. 'page arguments' => array('search_api_saved_searches_search_edit_form', 2),
  90. 'access callback' => 'search_api_saved_search_edit_access',
  91. 'access arguments' => array(NULL, 2, 4),
  92. 'file' => 'search_api_saved_searches.pages.inc',
  93. );
  94. $items['search-api/saved-search/%search_api_saved_search/delete'] = array(
  95. 'title' => 'Delete saved search',
  96. 'description' => 'Delete a saved search.',
  97. 'page callback' => 'drupal_get_form',
  98. 'page arguments' => array('search_api_saved_searches_search_delete_form', 2),
  99. 'access callback' => 'search_api_saved_search_edit_access',
  100. 'access arguments' => array(NULL, 2, 4),
  101. 'file' => 'search_api_saved_searches.pages.inc',
  102. );
  103. return $items;
  104. }
  105. /**
  106. * Implements hook_permission();
  107. */
  108. function search_api_saved_searches_permission() {
  109. $perms['administer search_api_saved_searches'] = array(
  110. 'title' => t('Administer saved searches'),
  111. 'description' => t('Enable and configure saved searches for search indexes.'),
  112. );
  113. $perms['use search_api_saved_searches'] = array(
  114. 'title' => t('Use saved searches'),
  115. 'description' => t('Save searches and receive e-mail notifications.'),
  116. );
  117. return $perms;
  118. }
  119. /**
  120. * Implements hook_entity_info().
  121. */
  122. function search_api_saved_searches_entity_info() {
  123. $info['search_api_saved_searches_settings'] = array(
  124. 'label' => t('Saved search settings'),
  125. 'controller class' => 'EntityAPIControllerExportable',
  126. 'entity class' => 'SearchApiSavedSearchesSettings',
  127. 'base table' => 'search_api_saved_searches_settings',
  128. 'uri callback' => 'search_api_saved_searches_settings_url',
  129. 'access callback' => 'search_api_saved_searches_settings_access',
  130. 'module' => 'search_api_saved_searches',
  131. 'exportable' => TRUE,
  132. 'entity keys' => array(
  133. 'id' => 'id',
  134. 'name' => 'delta',
  135. 'label' => 'delta',
  136. ),
  137. );
  138. $info['search_api_saved_search'] = array(
  139. 'label' => t('Saved search'),
  140. 'controller class' => 'EntityAPIController',
  141. 'entity class' => 'SearchApiSavedSearch',
  142. 'base table' => 'search_api_saved_search',
  143. 'access callback' => 'search_api_saved_search_access',
  144. 'module' => 'search_api_saved_searches',
  145. 'exportable' => FALSE,
  146. 'entity keys' => array(
  147. 'id' => 'id',
  148. 'label' => 'name',
  149. ),
  150. );
  151. return $info;
  152. }
  153. /**
  154. * Implements hook_entity_property_info_alter().
  155. *
  156. * Corrects the types which the Entity API automatically infers from the schema.
  157. * Otherwise, the "token" types would be "text", and "boolean" and "date" would
  158. * be "integer". Also, changes saved search results to be a list, not just a CSV
  159. * string.
  160. *
  161. * Fixing this here automatically also fixes the Views integration provided by
  162. * the Entity API, regarding these types.
  163. */
  164. function search_api_saved_searches_entity_property_info_alter(array &$info) {
  165. $settings = &$info['search_api_saved_searches_settings']['properties'];
  166. $settings['index_id']['type'] = 'token';
  167. $settings['enabled']['type'] = 'boolean';
  168. $settings['module']['type'] = 'token';
  169. $searches = &$info['search_api_saved_search']['properties'];
  170. $searches['settings_id']['type'] = 'token';
  171. $searches['enabled']['type'] = 'boolean';
  172. $searches['created']['type'] = 'date';
  173. $searches['last_queued']['type'] = 'date';
  174. $searches['last_execute']['type'] = 'date';
  175. // We can't assign "duration" until Entity API Views integration supports
  176. // this.
  177. //$searches['notify_interval']['type'] = 'duration';
  178. $searches['results']['type'] = 'list<token>';
  179. $searches['results']['getter callback'] = 'search_api_saved_searches_get_results_property';
  180. }
  181. /**
  182. * Getter callback for the saved search results property.
  183. *
  184. * @param SearchApiSavedSearch $search
  185. * The search whose results should be returned.
  186. * @param array $options
  187. * Options for the property. Are ignored.
  188. * @param string $property
  189. * The property to retrieve. Will always be "results".
  190. * @param string $entity_type
  191. * The entity type. Will always be "search_api_saved_search".
  192. *
  193. * @return array
  194. * An array with the IDs of all stored results.
  195. */
  196. function search_api_saved_searches_get_results_property(SearchApiSavedSearch $search, array $options, $property, $entity_type) {
  197. return $search->results ? explode(',', $search->results) : array();
  198. }
  199. /**
  200. * Implements hook_views_api().
  201. */
  202. function search_api_saved_searches_views_api() {
  203. return array(
  204. 'api' => 3,
  205. 'path' => drupal_get_path('module', 'search_api_saved_searches') . '/views',
  206. );
  207. }
  208. /**
  209. * URL callback for settings entities.
  210. */
  211. function search_api_saved_searches_settings_url(SearchApiSavedSearchesSettings $settings) {
  212. return array('path' => 'admin/config/search/search_api/index/' . $settings->index_id . '/saved_searches');
  213. }
  214. /**
  215. * Access callback for settings entities.
  216. *
  217. * @param string $op
  218. * The operation being performed. One of "view", "update", "create" or
  219. * "delete".
  220. * @param SearchApiSavedSearchesSettings|null $settings
  221. * (optional) The entity to check access for. If NULL is given, it will be
  222. * determined whether access is allowed for all settings.
  223. * @param object|null $account
  224. * The user to check for. NULL to check for the global user.
  225. *
  226. * @return bool
  227. * Whether access is allowed or not.
  228. *
  229. * @see entity_access
  230. */
  231. function search_api_saved_searches_settings_access($op, SearchApiSavedSearchesSettings $settings = NULL, $account = NULL) {
  232. return user_access('administer search_api_saved_searches', $account);
  233. }
  234. /**
  235. * Access callback for saved search entities.
  236. *
  237. * @param string $op
  238. * The operation being performed. One of "view", "update", "create" or
  239. * "delete".
  240. * @param SearchApiSavedSearch|null $search
  241. * (optional) The entity to check access for. If NULL is given, it will be
  242. * determined whether access is allowed for all searches.
  243. * @param object|null $account
  244. * The user to check for. NULL to check for the global user.
  245. *
  246. * @return bool
  247. * Whether access is allowed or not.
  248. *
  249. * @see entity_access
  250. */
  251. function search_api_saved_search_access($op, SearchApiSavedSearch $search = NULL, $account = NULL) {
  252. if (user_access('administer search_api_saved_searches', $account)) {
  253. return TRUE;
  254. }
  255. if (!$account) {
  256. global $user;
  257. $account = $user;
  258. }
  259. switch ($op) {
  260. case 'create':
  261. return user_access('use search_api_saved_searches', $account);
  262. default:
  263. // If the search was created by an anonymous user, there's no way we can
  264. // correctly determine access here.
  265. if (!$search || !$search->uid) {
  266. return FALSE;
  267. }
  268. return $search->uid == $account->uid;
  269. }
  270. }
  271. /**
  272. * Implements hook_user_insert().
  273. *
  274. * If a new user already has saved searches with the same mail address,
  275. * associate them with the new user. However, only do this if the user is
  276. * already active.
  277. */
  278. function search_api_saved_searches_user_insert(&$edit, $account, $category) {
  279. if (!empty($account->status)) {
  280. foreach (search_api_saved_search_load_multiple(FALSE, array('mail' => $account->mail, 'uid' => 0)) as $search) {
  281. $search->uid = $account->uid;
  282. if (empty($search->settings()->options['registered_user_delete_key'])) {
  283. unset($search->options['key']);
  284. }
  285. $search->save();
  286. }
  287. }
  288. }
  289. /**
  290. * Implements hook_user_update().
  291. *
  292. * If a user gets activated, associate saved searches with the same mail address
  293. * with them.
  294. *
  295. * If a user gets deactivated, disable all related saved searches.
  296. *
  297. * Also, change mail address of saved searches when the user mail address
  298. * changes.
  299. */
  300. function search_api_saved_searches_user_update(&$edit, $account, $category) {
  301. // For newly activated users, transfer all saved searches with their mail
  302. // address to them.
  303. if (!empty($account->status) && empty($account->original->status)) {
  304. foreach (search_api_saved_search_load_multiple(FALSE, array('mail' => $account->mail, 'uid' => 0)) as $search) {
  305. $search->uid = $account->uid;
  306. if (empty($search->settings()->options['registered_user_delete_key'])) {
  307. unset($search->options['key']);
  308. }
  309. $search->save();
  310. }
  311. }
  312. // If an account gets deactivated/banned, disable all associated searches.
  313. if (empty($account->status) && !empty($account->original->status)) {
  314. foreach (search_api_saved_search_load_multiple(FALSE, array('uid' => $account->uid)) as $search) {
  315. $search->enabled = FALSE;
  316. $search->save();
  317. }
  318. }
  319. // If the user's mail address changed, also change the mail address of the
  320. // user's saved searches.
  321. if ($account->mail != $account->original->mail) {
  322. foreach (search_api_saved_search_load_multiple(FALSE, array('mail' => $account->mail, 'uid' => $account->uid)) as $search) {
  323. $search->mail = $account->mail;
  324. $search->save();
  325. }
  326. }
  327. }
  328. /**
  329. * Implements hook_user_delete().
  330. *
  331. * If a user is deleted, delete their saved searches, too.
  332. */
  333. function search_api_saved_searches_user_delete($account) {
  334. entity_delete_multiple('search_api_saved_search', array_keys(search_api_saved_search_load_multiple(FALSE, array('uid' => $account->uid))));
  335. }
  336. // @todo Rules integration
  337. /**
  338. * Implements hook_search_api_index_update().
  339. *
  340. * If the index got disabled, do the same with its search settings.
  341. */
  342. function search_api_saved_searches_search_api_index_update(SearchApiIndex $index) {
  343. if (!$index->enabled && $index->original->enabled) {
  344. foreach (search_api_saved_searches_settings_load_multiple(FALSE, array('index_id' => $index->machine_name)) as $settings) {
  345. if ($settings->enabled) {
  346. $settings->enabled = FALSE;
  347. $settings->save();
  348. }
  349. }
  350. }
  351. }
  352. /**
  353. * Implements hook_search_api_index_delete().
  354. *
  355. * Deletes the settings associated with a search index.
  356. */
  357. function search_api_saved_searches_search_api_index_delete(SearchApiIndex $index) {
  358. // Only react on real delete, not revert.
  359. if ($index->status & ENTITY_IN_CODE) {
  360. return;
  361. }
  362. foreach (search_api_saved_searches_settings_load_multiple(FALSE, array('index_id' => $index->machine_name)) as $settings) {
  363. $settings->delete();
  364. }
  365. }
  366. /**
  367. * Implements hook_search_api_saved_searches_settings_insert().
  368. *
  369. * Clear block caches when new enabled saved search settings are saved.
  370. */
  371. function search_api_saved_searches_search_api_saved_searches_settings_insert(SearchApiSavedSearchesSettings $settings) {
  372. if ($settings->enabled) {
  373. block_flush_caches();
  374. cache_clear_all('*', 'cache_block', TRUE);
  375. }
  376. }
  377. /**
  378. * Implements hook_search_api_saved_searches_settings_update().
  379. *
  380. * Clear block caches when saved search settings are enabled or disabled.
  381. */
  382. function search_api_saved_searches_search_api_saved_searches_settings_update(SearchApiSavedSearchesSettings $settings) {
  383. if ($settings->enabled != $settings->original->enabled) {
  384. block_flush_caches();
  385. cache_clear_all('*', 'cache_block', TRUE);
  386. }
  387. // React if the new results determination method was switched to/from the
  388. // ID-based method.
  389. $options = $settings->options + array('date_field' => NULL);
  390. $orig_options = $settings->original->options + array('date_field' => NULL);
  391. if ($options['date_field'] != $orig_options['date_field']) {
  392. if (!$options['date_field']) {
  393. // When we switch to the ID-based method from another one, we need to save
  394. // the current results.
  395. foreach (search_api_saved_search_load_multiple(FALSE, array('settings_id' => $settings->delta)) as $search) {
  396. // This will automatically populate the results.
  397. $search->save();
  398. }
  399. }
  400. elseif (!$orig_options['date_field']) {
  401. // If we previously used the ID-based method and are now using a
  402. // field-based one, set the saved results for all searches to NULL.
  403. db_update('search_api_saved_search')
  404. ->fields(array(
  405. 'results' => NULL,
  406. ))
  407. ->condition('settings_id', $settings->delta)
  408. ->execute();
  409. }
  410. }
  411. }
  412. /**
  413. * Implements hook_search_api_saved_searches_settings_delete().
  414. *
  415. * Clear block caches when enabled saved search settings are deleted.
  416. */
  417. function search_api_saved_searches_search_api_saved_searches_settings_delete(SearchApiSavedSearchesSettings $settings) {
  418. // Only react on real delete, not revert.
  419. if ($settings->status & ENTITY_IN_CODE) {
  420. return;
  421. }
  422. foreach (search_api_saved_search_load_multiple(FALSE, array('settings_id' => $settings->delta)) as $search) {
  423. $search->delete();
  424. }
  425. if ($settings->enabled) {
  426. block_flush_caches();
  427. cache_clear_all('*', 'cache_block', TRUE);
  428. }
  429. }
  430. /**
  431. * Loads a single settings object.
  432. *
  433. * @param int|string $id
  434. * The settings' identifier or delta.
  435. * @param bool $reset
  436. * If TRUE, will reset the internal entity cache.
  437. *
  438. * @return SearchApiSavedSearchesSettings
  439. * The requested entity, or FALSE if no settings for that ID exist.
  440. */
  441. function search_api_saved_searches_settings_load($id, $reset = FALSE) {
  442. $ret = search_api_saved_searches_settings_load_multiple(array($id), array(), $reset);
  443. return $ret ? reset($ret) : FALSE;
  444. }
  445. /**
  446. * Loads multiple settings objects.
  447. *
  448. * @param array|false $ids
  449. * The settings' identifiers or deltas; or FALSE to load all settings objects.
  450. * @param array $conditions
  451. * Associative array of field => value conditions that returned objects must
  452. * satisfy.
  453. * @param bool $reset
  454. * If TRUE, will reset the internal entity cache.
  455. *
  456. * @return SearchApiSavedSearchesSettings[]
  457. * All saved search settings matching the conditions, keyed by delta.
  458. */
  459. function search_api_saved_searches_settings_load_multiple($ids = FALSE, array $conditions = array(), $reset = FALSE) {
  460. $settings = entity_load('search_api_saved_searches_settings', $ids, $conditions, $reset);
  461. return entity_key_array_by_property($settings, 'delta');
  462. }
  463. /**
  464. * Loads a single saved search object.
  465. *
  466. * @param $id
  467. * The saved search's ID.
  468. * @param $reset
  469. * If TRUE, will reset the internal entity cache.
  470. *
  471. * @return SearchApiSavedSearch
  472. * The requested entity, or FALSE if no settings for that ID exist.
  473. */
  474. function search_api_saved_search_load($id, $reset = FALSE) {
  475. $ret = entity_load('search_api_saved_search', array($id), array(), $reset);
  476. return $ret ? reset($ret) : FALSE;
  477. }
  478. /**
  479. * Loads multiple saved search objects.
  480. *
  481. * @param int[]|false $ids
  482. * The saved search's IDs; or FALSE to load all saved searches.
  483. * @param array $conditions
  484. * Associative array of field => value conditions that returned objects must
  485. * satisfy.
  486. * @param bool $reset
  487. * If TRUE, will reset the internal entity cache.
  488. *
  489. * @return SearchApiSavedSearch[]
  490. * All saved searches matching the conditions, keyed by their IDs.
  491. */
  492. function search_api_saved_search_load_multiple($ids = FALSE, array $conditions = array(), $reset = FALSE) {
  493. return entity_load('search_api_saved_search', $ids, $conditions, $reset);
  494. }
  495. /**
  496. * Determine whether the current user can create a saved search for specific settings.
  497. *
  498. * @param SearchApiSavedSearchesSettings $settings
  499. * The settings to check for. May be NULL, if $manual is TRUE, to check if any
  500. * saved searches can be created manually.
  501. * @param boolean $manual
  502. * (optional) If TRUE, check access for creating a saved search manually.
  503. *
  504. * @return boolean
  505. * TRUE iff the current user is allowed to create a new saved search.
  506. */
  507. function search_api_saved_search_create_access(SearchApiSavedSearchesSettings $settings = NULL, $manual = FALSE) {
  508. if ($manual) {
  509. if (isset($settings)) {
  510. if (!$settings->enabled || empty($settings->options['manual']['allow'])) {
  511. return FALSE;
  512. }
  513. }
  514. else {
  515. foreach (search_api_saved_searches_settings_load_multiple(FALSE, array('enabled' => TRUE)) as $settings) {
  516. if (!empty($settings->options['manual']['allow'])) {
  517. $found = TRUE;
  518. break;
  519. }
  520. }
  521. if (empty($found)) {
  522. return FALSE;
  523. }
  524. }
  525. }
  526. elseif (!$settings->enabled) {
  527. return FALSE;
  528. }
  529. if (user_access('administer search_api_saved_searches')) {
  530. return TRUE;
  531. }
  532. if (!user_access('use search_api_saved_searches')) {
  533. return FALSE;
  534. }
  535. if (!isset($settings)) {
  536. return TRUE;
  537. }
  538. // @todo Check settings-specific access rules, when there are any.
  539. return TRUE;
  540. }
  541. /**
  542. * Determine access to the edit interface for saved searches of a given user.
  543. *
  544. * This is both used to determine whether the current user can edit a specific
  545. * saved search, or whether she can display the overview of the user's saved
  546. * searches.
  547. * For anonymous users' searches an access key is generated that allows
  548. * accessing and editing the searches.
  549. *
  550. * @param $account
  551. * (optional) The user whose saved search(es) would be edited. NULL for guest.
  552. * @param SearchApiSavedSearch $search
  553. * (optional) The saved search involved, if there is just a single one.
  554. * @param string $key
  555. * (optional) The secret key to access the search.
  556. *
  557. * @return boolean
  558. * TRUE iff the current user is allowed to edit the saved search(es).
  559. */
  560. function search_api_saved_search_edit_access($account = NULL, SearchApiSavedSearch $search = NULL, $key = NULL) {
  561. global $user;
  562. if (empty($account)) {
  563. if (empty($search)) {
  564. return FALSE;
  565. }
  566. $account = (object) array('uid' => $search->uid);
  567. }
  568. if (user_access('administer search_api_saved_searches')) {
  569. return TRUE;
  570. }
  571. // Barring admins, the only way to edit anonymous users' saved searches is by
  572. // providing the access key. There is no overview of all saved searches.
  573. if (!empty($key) && !empty($search->options['key']) && $search->options['key'] == $key) {
  574. return TRUE;
  575. }
  576. if ($account->uid == 0) {
  577. return FALSE;
  578. }
  579. if ($account->uid != $user->uid || !user_access('use search_api_saved_searches')) {
  580. return FALSE;
  581. }
  582. if (isset($search)) {
  583. return $search->uid == $account->uid;
  584. }
  585. foreach (search_api_saved_searches_settings_load_multiple() as $settings) {
  586. // Allow access if users can manually create searches.
  587. if (!empty($settings->options['manual']['allow'])) {
  588. return TRUE;
  589. }
  590. // Allow access if the list should always be displayed.
  591. if (!empty($settings->options['show_empty_list'])) {
  592. return TRUE;
  593. }
  594. }
  595. // Let the user view the listing if there are any saved searches.
  596. $select = db_select('search_api_saved_search', 's')
  597. ->condition('uid', $account->uid);
  598. $select->addExpression('COUNT(1)');
  599. return (bool) $select->execute()->fetchField();
  600. }
  601. /**
  602. * Implements hook_block_info().
  603. */
  604. function search_api_saved_searches_block_info() {
  605. $blocks = array();
  606. foreach (search_api_saved_searches_settings_load_multiple(FALSE, array('enabled' => TRUE)) as $settings) {
  607. try {
  608. $blocks[$settings->delta] = array(
  609. 'info' => t('!index: Save search', array('!index' => $settings->index()->name)),
  610. // @todo Is this cache setting correct?
  611. 'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
  612. );
  613. }
  614. catch (SearchApiException $e) {}
  615. }
  616. return $blocks;
  617. }
  618. /**
  619. * Implements hook_ctools_block_info().
  620. */
  621. function search_api_saved_searches_ctools_block_info($module, $delta, &$info) {
  622. $info['category'] = t('Search API Saved Searches');
  623. // Allow blocks to be used before the search results in Panels.
  624. $info['render last'] = TRUE;
  625. }
  626. /**
  627. * Implements hook_block_configure().
  628. */
  629. function search_api_saved_searches_block_configure($delta = '') {
  630. $settings = search_api_saved_searches_settings_load($delta);
  631. $form['settings_link'] = array(
  632. '#markup' => l(t('To saved search settings'), 'admin/config/search/search_api/index/' . $settings->index_id . '/saved_searches'),
  633. );
  634. return $form;
  635. }
  636. /**
  637. * Implements hook_block_view().
  638. */
  639. function search_api_saved_searches_block_view($delta = '') {
  640. $searches = search_api_current_search();
  641. if (!$searches) {
  642. return;
  643. }
  644. if (!user_access('use search_api_saved_searches')) {
  645. return;
  646. }
  647. $settings = search_api_saved_searches_settings_load($delta);
  648. if (!$settings || !search_api_saved_search_create_access($settings)) {
  649. return;
  650. }
  651. $index_id = $settings->index_id;
  652. $options = $settings->options;
  653. $ids_list = drupal_map_assoc($options['ids_list']);
  654. $search_ids = variable_get('search_api_saved_searches_search_ids', array());
  655. foreach ($searches as $id => $data) {
  656. if ($data[0]->getIndex()->machine_name == $index_id){
  657. if (!isset($search_ids[$index_id][$id])) {
  658. $search_ids[$index_id][$id] = $id;
  659. $search_ids_updated = TRUE;
  660. }
  661. if (isset($ids_list[$id]) != $options['default_true']) {
  662. if (isset($query)) {
  663. watchdog('search_api_saved_searches', 'Two matching searches on index %index for saved search block.',
  664. array('%index' => $settings->index()->name), WATCHDOG_WARNING,
  665. l(t('view page'), $_GET['q'], array('query' => drupal_get_query_parameters())));
  666. }
  667. else {
  668. list($query, $results) = $data;
  669. }
  670. }
  671. }
  672. }
  673. if (isset($search_ids_updated)) {
  674. variable_set('search_api_saved_searches_search_ids', $search_ids);
  675. }
  676. if (empty($query)) {
  677. return;
  678. }
  679. return array(
  680. 'subject' => t('Save search'),
  681. 'content' => array('form' => drupal_get_form('search_api_saved_searches_save_form', $settings, $query)),
  682. );
  683. }
  684. /**
  685. * Form builder for creating a new saved search.
  686. *
  687. * @param SearchApiSavedSearchesSettings $settings
  688. * The saved search settings with which to create a new saved search.
  689. * @param SearchApiQueryInterface $query
  690. * (optional) If creating a saved search for an already executed query, the
  691. * query.
  692. *
  693. * @see search_api_saved_searches_save_form_validate()
  694. * @see search_api_saved_searches_save_form_submit()
  695. * @ingroup forms
  696. */
  697. function search_api_saved_searches_save_form(array $form, array &$form_state, SearchApiSavedSearchesSettings $settings, SearchApiQueryInterface $query = NULL) {
  698. global $user;
  699. if (!isset($form_state['query']) && isset($query)) {
  700. $options = $query->getOptions();
  701. // When checking for new results, we need all results.
  702. // @todo Make this configurable?
  703. unset($options['offset'], $options['limit']);
  704. $options['search id'] = $settings->delta . ':' . 'saved-search';
  705. $form_state['query'] = array(
  706. 'index_id' => $query->getIndex()->machine_name,
  707. 'keys' => $query->getKeys(),
  708. 'original_keys' => $query->getOriginalKeys(),
  709. 'fields' => $query->getFields(),
  710. 'filters' => $query->getFilter()->getFilters(),
  711. 'options' => $options,
  712. );
  713. }
  714. $form_state['settings'] = $settings;
  715. $description = $settings->getTranslatedOption('description');
  716. if (!empty($description)) {
  717. $form['description'] = array(
  718. '#type' => 'item',
  719. '#description' => _filter_autop(check_plain($description)),
  720. );
  721. }
  722. if (empty($form_state['query'])) {
  723. $form['query'] = _search_api_saved_searches_create_search_form($settings);
  724. $form['name'] = array(
  725. '#type' => 'textfield',
  726. '#title' => t('Name'),
  727. '#description' => t('Enter the name that will be displayed for this saved search.'),
  728. '#maxlength' => 50,
  729. );
  730. }
  731. else {
  732. $form['#prefix'] = '<div id="search-api-saved-searches-save-form-wrapper">';
  733. $form['#suffix'] = '</div>';
  734. if (empty($settings->options['choose_name'])) {
  735. $form['name'] = array(
  736. '#type' => 'value',
  737. '#value' => _search_api_saved_searches_create_name($form_state['query']),
  738. );
  739. }
  740. else {
  741. $form['name'] = array(
  742. '#type' => 'textfield',
  743. '#title' => t('Name'),
  744. '#maxlength' => 50,
  745. '#size' => 16,
  746. '#required' => TRUE,
  747. '#default_value' => _search_api_saved_searches_create_name($form_state['query']),
  748. );
  749. }
  750. }
  751. if (empty($user->mail) || $settings->options['registered_choose_mail']) {
  752. $form['mail'] = array(
  753. '#type' => 'textfield',
  754. '#title' => t('E-mail address'),
  755. '#maxlength' => 100,
  756. '#size' => 16,
  757. '#default_value' => isset($user->mail) ? $user->mail : '',
  758. '#required' => TRUE,
  759. );
  760. }
  761. else {
  762. $form['mail'] = array(
  763. '#type' => 'value',
  764. '#value' => $user->mail,
  765. );
  766. }
  767. if ($settings->options['user_select_interval'] && count($settings->options['interval_options']) > 1) {
  768. $form['notify_interval'] = array(
  769. '#type' => 'select',
  770. '#title' => t('Notification interval'),
  771. '#options' => $settings->getTranslatedOption('interval_options'),
  772. '#required' => TRUE,
  773. );
  774. }
  775. else {
  776. $form['notify_interval'] = array(
  777. '#type' => 'value',
  778. '#value' => $settings->options['user_select_interval'] ? reset($settings->options['interval_options']) : $settings->options['set_interval'],
  779. );
  780. }
  781. if (!empty($form_state['query'])) {
  782. $form_state['page'] = array(
  783. 'path' => $_GET['q'],
  784. 'query' => drupal_get_query_parameters(),
  785. );
  786. }
  787. $form['submit'] = array(
  788. '#type' => 'submit',
  789. '#value' => t('Save search'),
  790. '#ajax' => array(
  791. 'callback' => 'search_api_saved_searches_save_form_ajax',
  792. 'wrapper' => 'search-api-saved-searches-save-form-wrapper',
  793. 'effect' => 'fade',
  794. 'method' => 'replace',
  795. ),
  796. '#executes_submit_callback' => TRUE,
  797. );
  798. // For manual search creation we don't need AJAX functionality.
  799. if (empty($form_state['query'])) {
  800. unset($form['submit']['#ajax']);
  801. }
  802. return $form;
  803. }
  804. /**
  805. * Helper function for creating a form for manually creating a saved search.
  806. */
  807. function _search_api_saved_searches_create_search_form(SearchApiSavedSearchesSettings $settings) {
  808. $index = $settings->index();
  809. $wrapper = $index->entityWrapper();
  810. $options = isset($settings->options['manual']) ? $settings->options['manual'] : array();
  811. $form['#tree'] = TRUE;
  812. $form['fields'] = array(
  813. '#type' => 'fieldset',
  814. '#title' => t('Search'),
  815. );
  816. if (!empty($options['fulltext'])) {
  817. $form['fields']['search_api_saved_searches_fulltext'] = array(
  818. '#type' => 'textfield',
  819. '#title' => t('Keywords'),
  820. );
  821. }
  822. if (!empty($options['fields'])) {
  823. foreach ($options['fields'] as $field) {
  824. if (!empty($index->options['fields'][$field])) {
  825. // Extract the necessary field information out of the wrapper.
  826. $tmp = $wrapper;
  827. foreach (explode(':', $field) as $part) {
  828. if (!isset($tmp->$part)) {
  829. continue 2;
  830. }
  831. $tmp = $tmp->$part;
  832. }
  833. $info = $tmp->info();
  834. $form['fields'][$field]['#title'] = isset($info['label']) ? $info['label'] : $field;
  835. if ($optList = $tmp->optionsList('view')) {
  836. $optList = array(NULL => t('- Any -')) + $optList;
  837. $form['fields'][$field]['#type'] = 'select';
  838. $form['fields'][$field]['#options'] = $optList;
  839. }
  840. else {
  841. $form['fields'][$field]['#type'] = 'textfield';
  842. }
  843. }
  844. }
  845. }
  846. return $form;
  847. }
  848. /**
  849. * AJAX submit handler for search_api_saved_searches_save_form().
  850. */
  851. function search_api_saved_searches_save_form_ajax(array $form, array &$form_state) {
  852. return form_get_errors() ? $form : array('#theme' => 'status_messages');
  853. }
  854. /**
  855. * Form validation handler for search_api_saved_searches_save_form().
  856. *
  857. * @see search_api_saved_searches_save_form()
  858. * @see search_api_saved_searches_save_form_submit()
  859. */
  860. function search_api_saved_searches_save_form_validate(array $form, array &$form_state) {
  861. if ($msg = user_validate_mail($form_state['values']['mail'])) {
  862. form_error($form['mail'], $msg);
  863. }
  864. }
  865. /**
  866. * Form validation handler for search_api_saved_searches_save_form().
  867. *
  868. * @return boolean
  869. * TRUE iff the search was successfully saved.
  870. *
  871. * @see search_api_saved_searches_save_form()
  872. * @see search_api_saved_searches_save_form_validate()
  873. */
  874. function search_api_saved_searches_save_form_submit(array $form, array &$form_state) {
  875. global $user;
  876. $values = $form_state['values'];
  877. $settings = $form_state['settings'];
  878. if (empty($form_state['query'])) {
  879. $fields = $values['query']['fields'];
  880. $query = array(
  881. 'keys' => isset($fields['search_api_saved_searches_fulltext']) ? $fields['search_api_saved_searches_fulltext'] : NULL,
  882. 'fields' => NULL,
  883. 'filters' => array(),
  884. 'options' => array(
  885. 'search id' => $settings->delta . ':' . 'saved-search',
  886. ),
  887. );
  888. unset($fields['search_api_saved_searches_fulltext']);
  889. foreach ($fields as $field => $value) {
  890. if ($value || is_numeric($value)) {
  891. $query['filters'][] = array($field, $value, '=');
  892. }
  893. else {
  894. unset($fields[$field]);
  895. }
  896. }
  897. if (empty($values['name'])) {
  898. $query['original_keys'] = $query['keys'];
  899. $values['name'] = _search_api_saved_searches_create_name($query);
  900. unset($query['original_keys']);
  901. }
  902. if (empty($form_state['page']) && !empty($settings->options['manual']['page']['path'])) {
  903. $page_options = $settings->options['manual']['page'];
  904. $form_state['page'] = array(
  905. 'path' => $page_options['path'],
  906. 'query' => array(),
  907. );
  908. if (isset($query['keys'])) {
  909. if (empty($page_options['fulltext'])) {
  910. $form_state['page']['path'] .= '/' . $query['keys'];
  911. }
  912. else {
  913. $form_state['page']['query'][$page_options['fulltext']] = $query['keys'];
  914. }
  915. }
  916. foreach ($fields as $field => $value) {
  917. if (empty($page_options['direct_filter_params'])) {
  918. $form_state['page']['query']['filter'][$field][] = '"' . $value . '"';
  919. }
  920. else {
  921. $form_state['page']['query'][$field] = $value;
  922. }
  923. }
  924. }
  925. }
  926. else {
  927. $query = array_intersect_key($form_state['query'], drupal_map_assoc(array('keys', 'fields', 'filters', 'options')));
  928. }
  929. // Enable the saved search right away, if a logged-in user uses their own mail
  930. // address, or when they have admin privileges, or when activation mails are
  931. // generally deactivated, or if there are already active saved searches for
  932. // that user with that mail address. Otherwise, an activation mail will be
  933. // sent.
  934. $enabled = (!empty($user->mail) && $user->mail == $values['mail'])
  935. || user_access('administer search_api_saved_searches')
  936. || empty($settings->options['mail']['activate']['send'])
  937. || ($user->uid && search_api_saved_search_load_multiple(FALSE, array('enabled' => TRUE, 'uid' => $user->uid, 'mail' => $values['mail'])));
  938. // If an anonymous user uses an existing user's mail address to create a
  939. // saved search, file the saved search under that user right away.
  940. $uid = $user->uid;
  941. if (!$uid && ($users = user_load_multiple(FALSE, array('mail' => $values['mail'], 'status' => 1)))) {
  942. $uid = key($users);
  943. }
  944. $search = entity_create('search_api_saved_search', array(
  945. 'uid' => $uid,
  946. 'settings_id' => $settings->delta,
  947. 'enabled' => $enabled,
  948. 'name' => $values['name'],
  949. 'mail' => $values['mail'],
  950. 'created' => REQUEST_TIME,
  951. 'last_queued' => REQUEST_TIME,
  952. 'last_execute' => REQUEST_TIME,
  953. 'notify_interval' => $values['notify_interval'],
  954. 'query' => $query,
  955. 'options' => array(),
  956. ));
  957. // Choose where to redirect.
  958. if (!empty($form_state['page'])) {
  959. $search->options['page'] = $form_state['page'];
  960. $form_state['redirect'] = array($form_state['page']['path'], $form_state['page']);
  961. }
  962. elseif ($user->uid) {
  963. $form_state['redirect'] = 'user/' . $user->uid . '/saved-searches';
  964. }
  965. // Save saved search.
  966. $ret = $search->save();
  967. // Display success or error message.
  968. if (!$ret) {
  969. drupal_set_message(t('An error occurred while trying to save the search. Please contact the site administrator.'), 'error');
  970. $form_state['rebuild'] = TRUE;
  971. return FALSE;
  972. }
  973. else {
  974. if ($enabled) {
  975. if ($search->notify_interval < 0) {
  976. drupal_set_message(t('Your saved search was successfully created.'));
  977. }
  978. else {
  979. drupal_set_message(t('Your saved search was successfully created. You will receive e-mail notifications for new results in the future.'));
  980. }
  981. }
  982. else {
  983. drupal_set_message(t('Your saved search was successfully created. You will soon receive an e-mail with a confirmation link to activate it.'));
  984. }
  985. return TRUE;
  986. }
  987. }
  988. /**
  989. * Helper function for creating a name for a saved search with the given query.
  990. */
  991. function _search_api_saved_searches_create_name(array $query) {
  992. if (!empty($query['original_keys']) && is_scalar($query['original_keys'])) {
  993. $ret[] = $query['original_keys'];
  994. }
  995. $name = isset($ret) ? implode(' / ', $ret) : t('Saved search');
  996. drupal_alter('search_api_saved_search_create_name', $name, $query);
  997. return $name;
  998. }
  999. /**
  1000. * Implements hook_mail().
  1001. *
  1002. * Two mails are provided, which expect the following values in the $params
  1003. * array:
  1004. * - activate:
  1005. * - search: The SearchApiSavedSearch object that should be activated.
  1006. * - user: The user object to which the saved search belongs.
  1007. * - notify:
  1008. * - user: The user to which the executed searches belong.
  1009. * - settings: The settings with which the searches are associated.
  1010. * - searches: An array containing arrays with the following keys:
  1011. * - search: A SearchApiSavedSearch object that was checked.
  1012. * - num_results: The number of new results for that saved search.
  1013. * - results: An array of entities representing the new results for that
  1014. * saved search.
  1015. */
  1016. function search_api_saved_searches_mail($key, array &$message, array $params) {
  1017. $language = $message['language'];
  1018. switch ($key) {
  1019. case 'activate':
  1020. $search = $params['search'];
  1021. $settings = $search->settings();
  1022. $data = array(
  1023. 'user' => $params['user'],
  1024. 'search_api_saved_search_info' => array(
  1025. 'search' => $search,
  1026. 'results' => array(),
  1027. ),
  1028. );
  1029. $title = $settings->getTranslatedOption('mail.activate.title', $language->language);
  1030. $message['subject'] .= token_replace($title, $data, array('language' => $language, 'sanitize' => FALSE));
  1031. $body = $settings->getTranslatedOption('mail.activate.body', $language->language);
  1032. $message['body'][] = token_replace($body, $data, array('language' => $language, 'sanitize' => FALSE));
  1033. break;
  1034. case 'notify':
  1035. $settings = $params['settings'];
  1036. $search = $params['searches'][0]['search'];
  1037. $data = array(
  1038. 'user' => $params['user'],
  1039. 'search_api_saved_searches' => $params['searches'],
  1040. 'search_api_saved_search_info' => array(
  1041. 'search' => $search,
  1042. 'results' => array(),
  1043. ),
  1044. );
  1045. $title = $settings->getTranslatedOption('mail.notify.title', $language->language);
  1046. $message['subject'] .= token_replace($title, $data, array('language' => $language, 'sanitize' => FALSE));
  1047. $body = $settings->getTranslatedOption('mail.notify.body', $language->language);
  1048. $message['body'][] = token_replace($body, $data, array('language' => $language, 'sanitize' => FALSE));
  1049. break;
  1050. }
  1051. }
  1052. /**
  1053. * Implements hook_cron().
  1054. *
  1055. * Queue the saved searches that should be checked for new items.
  1056. */
  1057. function search_api_saved_searches_cron() {
  1058. // Get all searches whose last execution lies more than the notify_interval
  1059. // in the past. Add a small amount to the current time, so small differences
  1060. // in execution time don't result in a delay until the next cron run.
  1061. $ids = db_select('search_api_saved_search', 's')
  1062. ->fields('s', array('id'))
  1063. ->condition('enabled', 1)
  1064. ->condition('notify_interval', 0, '>=')
  1065. ->where('last_execute >= last_queued')
  1066. ->where('last_queued + notify_interval < :time', array(':time' => REQUEST_TIME + 15))
  1067. ->execute()
  1068. ->fetchCol();
  1069. if (!$ids) {
  1070. return;
  1071. }
  1072. // Get the queue and load the queries.
  1073. $queue = DrupalQueue::get('search_api_saved_searches_check_updates');
  1074. $searches = search_api_saved_search_load_multiple($ids);
  1075. // Group the search according to mail and settings. Grouping by mail prevents
  1076. // a user from getting several mails at once, for different searches. Grouping
  1077. // by settings is necessary since the mails can differ between settings.
  1078. $user_searches = array();
  1079. foreach ($searches as $search) {
  1080. $user_searches[$search->mail . ' ' . $search->settings_id][] = $search->id;
  1081. // Set the last execution timestamp now, so the interval doesn't move and we
  1082. // don't get problems if the next cron run occurs before the queue is
  1083. // completely executed.
  1084. $search->last_queued = REQUEST_TIME;
  1085. $search->save();
  1086. }
  1087. foreach ($user_searches as $searches) {
  1088. $queue->createItem($searches);
  1089. }
  1090. }
  1091. /**
  1092. * Implements hook_cron_queue_info().
  1093. *
  1094. * Defines a queue for saved searches that should be checked for new items.
  1095. */
  1096. function search_api_saved_searches_cron_queue_info() {
  1097. return array(
  1098. 'search_api_saved_searches_check_updates' => array(
  1099. 'worker callback' => 'search_api_saved_searches_check_updates',
  1100. 'time' => 10,
  1101. ),
  1102. );
  1103. }
  1104. /**
  1105. * Checks for new results for saved searches, and sends a mail if necessary.
  1106. *
  1107. * Used as a worker callback for the homonymous cron queue.
  1108. *
  1109. * @param int[] $search_ids
  1110. * The IDs of the saved searches to check for new results. All of these should
  1111. * have the same mail address and base settings.
  1112. *
  1113. * @throws SearchApiException
  1114. * If an error occurred in one of the searches.
  1115. *
  1116. * @see search_api_saved_searches_cron_queue_info()
  1117. */
  1118. function search_api_saved_searches_check_updates(array $search_ids) {
  1119. if (!$search_ids) {
  1120. return;
  1121. }
  1122. // Since in earlier versions this function got the loaded searches passed
  1123. // directly instead of just IDs, and there might still be some such items in
  1124. // the queue when updating to the new style, we have to stay
  1125. // backwards-compatible here. So, when an array of loaded searches is passed,
  1126. // we first replace them with their IDs and only then load them again.
  1127. if (!is_scalar(reset($search_ids))) {
  1128. /** @var SearchApiSavedSearch[] $searches */
  1129. $searches = $search_ids;
  1130. $search_ids = array();
  1131. foreach ($searches as $search) {
  1132. $search_ids[] = $search->id;
  1133. }
  1134. }
  1135. $searches = search_api_saved_search_load_multiple($search_ids, array('enabled' => 1));
  1136. if (!$searches) {
  1137. return;
  1138. }
  1139. $search = $searches[key($searches)];
  1140. $settings = $search->settings();
  1141. $index = $settings->index();
  1142. $mail_params = array();
  1143. foreach ($searches as $search) {
  1144. try {
  1145. // Make sure we run the query as the user who owns the saved search.
  1146. // Otherwise node access will not work properly.
  1147. $search->query['options']['search_api_access_account'] = $search->uid;
  1148. // Get actual results for the query.
  1149. $query = $search->query();
  1150. // If a date field is set, use that to filter results.
  1151. if (!empty($settings->options['date_field'])) {
  1152. $query->condition($settings->options['date_field'], $search->last_execute, '>');
  1153. }
  1154. $response = $query->execute();
  1155. if (!empty($response['results'])) {
  1156. $old = array();
  1157. $new = $results = drupal_map_assoc(array_keys($response['results']));
  1158. if (empty($settings->options['date_field'])) {
  1159. // ID-based method: Compare these results to the old ones.
  1160. $old = drupal_map_assoc(explode(',', $search->results));
  1161. $new = array_diff_key($results, $old);
  1162. }
  1163. if ($new) {
  1164. // We have new results: send them to the user.
  1165. // Only load those items that will be sent.
  1166. $sent_new = $new;
  1167. if (!empty($settings->options['mail']['notify']['max_results'])) {
  1168. $sent_new = array_slice($new, 0, $settings->options['mail']['notify']['max_results']);
  1169. }
  1170. $sent_new = $index->loadItems($sent_new);
  1171. $new_results = $sent_new + $new;
  1172. // Let other modules alter these results.
  1173. drupal_alter('search_api_saved_searches_new_results', $new_results, $search);
  1174. if ($new_results) {
  1175. // We have to slice again in case some items were moved around or
  1176. // removed by alter hooks.
  1177. $sent_new = $new_results;
  1178. if (!empty($settings->options['mail']['notify']['max_results'])) {
  1179. $sent_new = array_slice($new_results, 0, $settings->options['mail']['notify']['max_results']);
  1180. // Now some of the top results might still be unloaded.
  1181. if ($unloaded = array_filter($sent_new, 'is_scalar')) {
  1182. $sent_new = $index->loadItems($unloaded) + $sent_new;
  1183. }
  1184. }
  1185. $num_results = count($new_results);
  1186. $mail_params['searches'][] = array(
  1187. 'search' => $search,
  1188. 'num_results' => $num_results,
  1189. 'results' => $sent_new,
  1190. );
  1191. }
  1192. }
  1193. if (empty($settings->options['date_field']) && ($new || array_diff($old, $results))) {
  1194. // The results changed in some way: store the latest version.
  1195. $search->results = implode(',', $results);
  1196. }
  1197. }
  1198. // Use time() instead of REQUEST_TIME to minimize the potential of sending
  1199. // duplicate results due to longer-running cron queue workers.
  1200. $search->last_execute = time();
  1201. $search->save();
  1202. }
  1203. catch (SearchApiException $e) {
  1204. $args = _drupal_decode_exception($e);
  1205. $args['@id'] = $search->id;
  1206. throw new SearchApiException(t('%type while trying to check for new results on saved search @id: !message in %function (line %line of %file).', $args));
  1207. }
  1208. }
  1209. // If we set any searches in the mail parameters, send the mail.
  1210. if ($mail_params) {
  1211. $mail_params['user'] = user_load($search->uid);
  1212. $mail_params['settings'] = $settings;
  1213. $message = drupal_mail('search_api_saved_searches', 'notify', $search->mail,
  1214. user_preferred_language($mail_params['user']), $mail_params);
  1215. if ($message['result']) {
  1216. watchdog('search_api_saved_searches', 'A mail with new saved search results was sent to @mail.',
  1217. array('@mail' => $search->mail), WATCHDOG_INFO);
  1218. }
  1219. }
  1220. }