search_api.module 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  1. <?php
  2. /**
  3. * Default number of items indexed per cron batch for each enabled index.
  4. */
  5. define('SEARCH_API_DEFAULT_CRON_LIMIT', 50);
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function search_api_menu() {
  10. $pre = 'admin/config/search/search_api';
  11. $items[$pre] = array(
  12. 'title' => 'Search API',
  13. 'description' => 'Create and configure search engines.',
  14. 'page callback' => 'search_api_admin_overview',
  15. 'access arguments' => array('administer search_api'),
  16. 'file' => 'search_api.admin.inc',
  17. );
  18. $items[$pre . '/overview'] = array(
  19. 'title' => 'Overview',
  20. 'type' => MENU_DEFAULT_LOCAL_TASK,
  21. 'weight' => -10,
  22. );
  23. $items[$pre . '/add_server'] = array(
  24. 'title' => 'Add server',
  25. 'description' => 'Create a new search server.',
  26. 'page callback' => 'drupal_get_form',
  27. 'page arguments' => array('search_api_admin_add_server'),
  28. 'access arguments' => array('administer search_api'),
  29. 'file' => 'search_api.admin.inc',
  30. 'weight' => -1,
  31. 'type' => MENU_LOCAL_ACTION,
  32. );
  33. $items[$pre . '/add_index'] = array(
  34. 'title' => 'Add index',
  35. 'description' => 'Create a new search index.',
  36. 'page callback' => 'drupal_get_form',
  37. 'page arguments' => array('search_api_admin_add_index'),
  38. 'access arguments' => array('administer search_api'),
  39. 'file' => 'search_api.admin.inc',
  40. 'type' => MENU_LOCAL_ACTION,
  41. );
  42. $items[$pre . '/server/%search_api_server'] = array(
  43. 'title' => 'View server',
  44. 'title callback' => 'search_api_admin_item_title',
  45. 'title arguments' => array(5),
  46. 'description' => 'View server details.',
  47. 'page callback' => 'search_api_admin_server_view',
  48. 'page arguments' => array(5),
  49. 'access arguments' => array('administer search_api'),
  50. 'file' => 'search_api.admin.inc',
  51. );
  52. $items[$pre . '/server/%search_api_server/view'] = array(
  53. 'title' => 'View',
  54. 'weight' => -10,
  55. 'type' => MENU_DEFAULT_LOCAL_TASK,
  56. );
  57. $items[$pre . '/server/%search_api_server/edit'] = array(
  58. 'title' => 'Edit',
  59. 'description' => 'Edit server details.',
  60. 'page callback' => 'drupal_get_form',
  61. 'page arguments' => array('search_api_admin_server_edit', 5),
  62. 'access arguments' => array('administer search_api'),
  63. 'file' => 'search_api.admin.inc',
  64. 'weight' => -1,
  65. 'type' => MENU_LOCAL_TASK,
  66. );
  67. $items[$pre . '/server/%search_api_server/delete'] = array(
  68. 'title' => 'Delete',
  69. 'title callback' => 'search_api_title_delete_page',
  70. 'title arguments' => array(5),
  71. 'description' => 'Delete server.',
  72. 'page callback' => 'drupal_get_form',
  73. 'page arguments' => array('search_api_admin_confirm', 'server', 'delete', 5),
  74. 'access callback' => 'search_api_access_delete_page',
  75. 'access arguments' => array(5),
  76. 'file' => 'search_api.admin.inc',
  77. 'type' => MENU_LOCAL_TASK,
  78. );
  79. $items[$pre . '/index/%search_api_index'] = array(
  80. 'title' => 'View index',
  81. 'title callback' => 'search_api_admin_item_title',
  82. 'title arguments' => array(5),
  83. 'description' => 'View index details.',
  84. 'page callback' => 'search_api_admin_index_view',
  85. 'page arguments' => array(5),
  86. 'access arguments' => array('administer search_api'),
  87. 'file' => 'search_api.admin.inc',
  88. );
  89. $items[$pre . '/index/%search_api_index/view'] = array(
  90. 'title' => 'View',
  91. 'type' => MENU_DEFAULT_LOCAL_TASK,
  92. 'weight' => -10,
  93. );
  94. $items[$pre . '/index/%search_api_index/status'] = array(
  95. 'title' => 'Status',
  96. 'description' => 'Display and work on index status.',
  97. 'page callback' => 'drupal_get_form',
  98. 'page arguments' => array('search_api_admin_index_status_form', 5),
  99. 'access arguments' => array('administer search_api'),
  100. 'file' => 'search_api.admin.inc',
  101. 'weight' => -8,
  102. 'type' => MENU_LOCAL_TASK,
  103. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  104. );
  105. $items[$pre . '/index/%search_api_index/edit'] = array(
  106. 'title' => 'Settings',
  107. 'description' => 'Edit index settings.',
  108. 'page callback' => 'drupal_get_form',
  109. 'page arguments' => array('search_api_admin_index_edit', 5),
  110. 'access arguments' => array('administer search_api'),
  111. 'file' => 'search_api.admin.inc',
  112. 'weight' => -6,
  113. 'type' => MENU_LOCAL_TASK,
  114. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  115. );
  116. $items[$pre . '/index/%search_api_index/fields'] = array(
  117. 'title' => 'Fields',
  118. 'description' => 'Select indexed fields.',
  119. 'page callback' => 'drupal_get_form',
  120. 'page arguments' => array('search_api_admin_index_fields', 5),
  121. 'access arguments' => array('administer search_api'),
  122. 'file' => 'search_api.admin.inc',
  123. 'weight' => -4,
  124. 'type' => MENU_LOCAL_TASK,
  125. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  126. );
  127. $items[$pre . '/index/%search_api_index/workflow'] = array(
  128. 'title' => 'Workflow',
  129. 'description' => 'Edit index workflow.',
  130. 'page callback' => 'drupal_get_form',
  131. 'page arguments' => array('search_api_admin_index_workflow', 5),
  132. 'access arguments' => array('administer search_api'),
  133. 'file' => 'search_api.admin.inc',
  134. 'weight' => -2,
  135. 'type' => MENU_LOCAL_TASK,
  136. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  137. );
  138. $items[$pre . '/index/%search_api_index/delete'] = array(
  139. 'title' => 'Delete',
  140. 'title callback' => 'search_api_title_delete_page',
  141. 'title arguments' => array(5),
  142. 'description' => 'Delete index.',
  143. 'page callback' => 'drupal_get_form',
  144. 'page arguments' => array('search_api_admin_confirm', 'index', 'delete', 5),
  145. 'access callback' => 'search_api_access_delete_page',
  146. 'access arguments' => array(5),
  147. 'file' => 'search_api.admin.inc',
  148. 'type' => MENU_LOCAL_TASK,
  149. );
  150. return $items;
  151. }
  152. /**
  153. * Implements hook_theme().
  154. */
  155. function search_api_theme() {
  156. $themes['search_api_server'] = array(
  157. 'variables' => array(
  158. 'id' => NULL,
  159. 'name' => '',
  160. 'machine_name' => '',
  161. 'description' => NULL,
  162. 'enabled' => NULL,
  163. 'class_name' => NULL,
  164. 'class_description' => NULL,
  165. 'options' => array(),
  166. 'status' => ENTITY_CUSTOM,
  167. ),
  168. 'file' => 'search_api.admin.inc',
  169. );
  170. $themes['search_api_index'] = array(
  171. 'variables' => array(
  172. 'id' => NULL,
  173. 'name' => '',
  174. 'machine_name' => '',
  175. 'description' => NULL,
  176. 'item_type' => NULL,
  177. 'enabled' => NULL,
  178. 'server' => NULL,
  179. 'options' => array(),
  180. 'fields' => array(),
  181. 'indexed_items' => 0,
  182. 'total_items' => 0,
  183. 'status' => ENTITY_CUSTOM,
  184. 'read_only' => 0,
  185. ),
  186. 'file' => 'search_api.admin.inc',
  187. );
  188. $themes['search_api_admin_item_order'] = array(
  189. 'render element' => 'element',
  190. 'file' => 'search_api.admin.inc',
  191. );
  192. $themes['search_api_admin_fields_table'] = array(
  193. 'render element' => 'element',
  194. 'file' => 'search_api.admin.inc',
  195. );
  196. return $themes;
  197. }
  198. /**
  199. * Implements hook_permission().
  200. */
  201. function search_api_permission() {
  202. return array(
  203. 'administer search_api' => array(
  204. 'title' => t('Administer Search API'),
  205. 'description' => t('Create and configure Search API servers and indexes.'),
  206. ),
  207. );
  208. }
  209. /**
  210. * Implements hook_cron().
  211. *
  212. * Will index $options['cron-limit'] items for each enabled index.
  213. */
  214. function search_api_cron() {
  215. $queue = DrupalQueue::get('search_api_indexing_queue');
  216. foreach (search_api_index_load_multiple(FALSE, array('enabled' => TRUE, 'read_only' => 0)) as $index) {
  217. $limit = isset($index->options['cron_limit'])
  218. ? $index->options['cron_limit']
  219. : SEARCH_API_DEFAULT_CRON_LIMIT;
  220. if ($limit) {
  221. try {
  222. $task = array('index' => $index->machine_name);
  223. $ids = search_api_get_items_to_index($index, -1);
  224. if (!$ids) {
  225. continue;
  226. }
  227. $batches = $limit > 0 ? array_chunk($ids, $limit, TRUE) : array($ids);
  228. foreach ($batches as $batch) {
  229. $task['items'] = $batch;
  230. $queue->createItem($task);
  231. }
  232. // Mark items as queued so they won't be inserted into the queue again
  233. // on the next cron run.
  234. search_api_track_item_queued($index, $ids);
  235. }
  236. catch (SearchApiException $e) {
  237. watchdog_exception('search_api', $e);
  238. }
  239. }
  240. }
  241. }
  242. /**
  243. * Implements hook_cron_queue_info().
  244. *
  245. * Defines a queue for saved searches that should be checked for new items.
  246. */
  247. function search_api_cron_queue_info() {
  248. return array(
  249. 'search_api_indexing_queue' => array(
  250. 'worker callback' => '_search_api_indexing_queue_process',
  251. 'time' => variable_get('search_api_index_worker_callback_runtime', 15),
  252. ),
  253. );
  254. }
  255. /**
  256. * Implements hook_entity_info().
  257. */
  258. function search_api_entity_info() {
  259. $info['search_api_server'] = array(
  260. 'label' => t('Search server'),
  261. 'controller class' => 'EntityAPIControllerExportable',
  262. 'metadata controller class' => FALSE,
  263. 'entity class' => 'SearchApiServer',
  264. 'base table' => 'search_api_server',
  265. 'uri callback' => 'search_api_server_url',
  266. 'module' => 'search_api',
  267. 'exportable' => TRUE,
  268. 'entity keys' => array(
  269. 'id' => 'id',
  270. 'label' => 'name',
  271. 'name' => 'machine_name',
  272. ),
  273. );
  274. $info['search_api_index'] = array(
  275. 'label' => t('Search index'),
  276. 'controller class' => 'EntityAPIControllerExportable',
  277. 'metadata controller class' => FALSE,
  278. 'entity class' => 'SearchApiIndex',
  279. 'base table' => 'search_api_index',
  280. 'uri callback' => 'search_api_index_url',
  281. 'module' => 'search_api',
  282. 'exportable' => TRUE,
  283. 'entity keys' => array(
  284. 'id' => 'id',
  285. 'label' => 'name',
  286. 'name' => 'machine_name',
  287. ),
  288. );
  289. return $info;
  290. }
  291. /**
  292. * Implements hook_entity_property_info().
  293. */
  294. function search_api_entity_property_info() {
  295. $info['search_api_server']['properties'] = array(
  296. 'id' => array(
  297. 'label' => t('ID'),
  298. 'type' => 'integer',
  299. 'description' => t('The primary identifier for a server.'),
  300. 'schema field' => 'id',
  301. 'validation callback' => 'entity_metadata_validate_integer_positive',
  302. ),
  303. 'name' => array(
  304. 'label' => t('Name'),
  305. 'type' => 'text',
  306. 'description' => t('The displayed name for a server.'),
  307. 'schema field' => 'name',
  308. 'required' => TRUE,
  309. ),
  310. 'machine_name' => array(
  311. 'label' => t('Machine name'),
  312. 'type' => 'token',
  313. 'description' => t('The internally used machine name for a server.'),
  314. 'schema field' => 'machine_name',
  315. 'required' => TRUE,
  316. ),
  317. 'description' => array(
  318. 'label' => t('Description'),
  319. 'type' => 'text',
  320. 'description' => t('The displayed description for a server.'),
  321. 'schema field' => 'description',
  322. 'sanitize' => 'filter_xss',
  323. ),
  324. 'class' => array(
  325. 'label' => t('Service class'),
  326. 'type' => 'text',
  327. 'description' => t('The ID of the service class to use for this server.'),
  328. 'schema field' => 'class',
  329. 'required' => TRUE,
  330. ),
  331. 'enabled' => array(
  332. 'label' => t('Enabled'),
  333. 'type' => 'boolean',
  334. 'description' => t('A flag indicating whether the server is enabled.'),
  335. 'schema field' => 'enabled',
  336. ),
  337. );
  338. $info['search_api_index']['properties'] = array(
  339. 'id' => array(
  340. 'label' => t('ID'),
  341. 'type' => 'integer',
  342. 'description' => t('An integer identifying the index.'),
  343. 'schema field' => 'id',
  344. 'validation callback' => 'entity_metadata_validate_integer_positive',
  345. ),
  346. 'name' => array(
  347. 'label' => t('Name'),
  348. 'type' => 'text',
  349. 'description' => t('A name to be displayed for the index.'),
  350. 'schema field' => 'name',
  351. 'required' => TRUE,
  352. ),
  353. 'machine_name' => array(
  354. 'label' => t('Machine name'),
  355. 'type' => 'token',
  356. 'description' => t('The internally used machine name for an index.'),
  357. 'schema field' => 'machine_name',
  358. 'required' => TRUE,
  359. ),
  360. 'description' => array(
  361. 'label' => t('Description'),
  362. 'type' => 'text',
  363. 'description' => t("A string describing the index' use to users."),
  364. 'schema field' => 'description',
  365. 'sanitize' => 'filter_xss',
  366. ),
  367. 'server' => array(
  368. 'label' => t('Server ID'),
  369. 'type' => 'token',
  370. 'description' => t('The machine name of the search_api_server with which data should be indexed.'),
  371. 'schema field' => 'server',
  372. ),
  373. 'server_entity' => array(
  374. 'label' => t('Server'),
  375. 'type' => 'search_api_server',
  376. 'description' => t('The search_api_server with which data should be indexed.'),
  377. 'getter callback' => 'search_api_index_get_server',
  378. ),
  379. 'item_type' => array(
  380. 'label' => t('Item type'),
  381. 'type' => 'token',
  382. 'description' => t('The type of items stored in this index.'),
  383. 'schema field' => 'item_type',
  384. 'required' => TRUE,
  385. ),
  386. 'enabled' => array(
  387. 'label' => t('Enabled'),
  388. 'type' => 'boolean',
  389. 'description' => t('A flag indicating whether the index is enabled.'),
  390. 'schema field' => 'enabled',
  391. ),
  392. 'read_only' => array(
  393. 'label' => t('Read only'),
  394. 'type' => 'boolean',
  395. 'description' => t('A flag indicating whether the index is read-only.'),
  396. 'schema field' => 'read_only',
  397. ),
  398. );
  399. return $info;
  400. }
  401. /**
  402. * Implements hook_search_api_server_insert().
  403. *
  404. * Calls the postCreate() method for the server.
  405. */
  406. function search_api_search_api_server_insert(SearchApiServer $server) {
  407. $server->postCreate();
  408. }
  409. /**
  410. * Implements hook_search_api_server_update().
  411. *
  412. * Calls the server's postUpdate() method and marks all of this server's indexes
  413. * for reindexing, if necessary.
  414. */
  415. function search_api_search_api_server_update(SearchApiServer $server) {
  416. if ($server->postUpdate()) {
  417. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  418. $index->reindex();
  419. }
  420. }
  421. if ($server->enabled != $server->original->enabled) {
  422. if ($server->enabled) {
  423. // Were there any changes in the server's indexes while it was disabled?
  424. $tasks = variable_get('search_api_tasks', array());
  425. if (isset($tasks[$server->machine_name])) {
  426. foreach ($tasks[$server->machine_name] as $index_id => $index_tasks) {
  427. $index = search_api_index_load($index_id);
  428. foreach ($index_tasks as $task) {
  429. switch ($task) {
  430. case 'add':
  431. $server->addIndex($index);
  432. break;
  433. case 'clear':
  434. $server->deleteItems('all', $index);
  435. break;
  436. case 'clear all':
  437. // Would normally be used with a fake index ID of "", since it doesn't matter.
  438. $server->deleteItems('all');
  439. break;
  440. case 'fields':
  441. if ($server->fieldsUpdated($index)) {
  442. _search_api_index_reindex($index);
  443. }
  444. break;
  445. case 'remove':
  446. $server->removeIndex($index ? $index : $index_id);
  447. break;
  448. default:
  449. if (substr($task, 0, 7) == 'delete-') {
  450. $id = substr($task, 7);
  451. $server->deleteItems(array($id), $index);
  452. }
  453. else {
  454. watchdog('search_api', t('Unknown task "@task" for server "@name".', array('@task' => $task, '@name' => $server->machine_name)), NULL, WATCHDOG_WARNING);
  455. }
  456. }
  457. }
  458. }
  459. unset($tasks[$server->machine_name]);
  460. variable_set('search_api_tasks', $tasks);
  461. }
  462. }
  463. else {
  464. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name, 'enabled' => 1)) as $index) {
  465. $index->update(array('enabled' => 0));
  466. }
  467. }
  468. }
  469. }
  470. /**
  471. * Implements hook_search_api_server_delete().
  472. *
  473. * Calls the preDelete() method for the server.
  474. */
  475. function search_api_search_api_server_delete(SearchApiServer $server) {
  476. $server->preDelete();
  477. // Only react on real delete, not revert.
  478. if (!$server->hasStatus(ENTITY_IN_CODE)) {
  479. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  480. $index->update(array('server' => NULL, 'enabled' => FALSE));
  481. }
  482. }
  483. $tasks = variable_get('search_api_tasks', array());
  484. unset($tasks[$server->machine_name]);
  485. variable_set('search_api_tasks', $tasks);
  486. }
  487. /**
  488. * Implements hook_search_api_index_insert().
  489. *
  490. * Adds the index to its server (if any) and starts tracking indexed items (if
  491. * the index is enabled).
  492. */
  493. function search_api_search_api_index_insert(SearchApiIndex $index) {
  494. $index->postCreate();
  495. }
  496. /**
  497. * Implements hook_search_api_index_update().
  498. */
  499. function search_api_search_api_index_update(SearchApiIndex $index) {
  500. // If the server was changed, we have to call the appropriate service class
  501. // hook methods.
  502. if ($index->server != $index->original->server) {
  503. // Server changed - inform old and new ones.
  504. if ($index->original->server) {
  505. $old_server = search_api_server_load($index->original->server);
  506. // The server might have changed because the old one was deleted:
  507. if ($old_server) {
  508. if ($old_server->enabled) {
  509. $old_server->removeIndex($index);
  510. }
  511. else {
  512. $tasks = variable_get('search_api_tasks', array());
  513. // When we add or remove an index, we can ignore all other tasks.
  514. $tasks[$old_server->machine_name][$index->machine_name] = array('remove');
  515. variable_set('search_api_tasks', $tasks);
  516. }
  517. }
  518. }
  519. if ($index->server) {
  520. $new_server = $index->server(TRUE);
  521. // If the server is enabled, we call addIndex(); otherwise, we save the task.
  522. if ($new_server->enabled) {
  523. $new_server->addIndex($index);
  524. }
  525. else {
  526. $tasks = variable_get('search_api_tasks', array());
  527. // When we add or remove an index, we can ignore all other tasks.
  528. $tasks[$new_server->machine_name][$index->machine_name] = array('add');
  529. variable_set('search_api_tasks', $tasks);
  530. unset($new_server);
  531. }
  532. }
  533. // We also have to re-index all content
  534. _search_api_index_reindex($index);
  535. }
  536. // If the fields were changed, call the appropriate service class hook method
  537. // and re-index the content, if necessary.
  538. $old_fields = $index->original->options + array('fields' => array());
  539. $old_fields = $old_fields['fields'];
  540. $new_fields = $index->options + array('fields' => array());
  541. $new_fields = $new_fields['fields'];
  542. if ($old_fields != $new_fields) {
  543. if ($index->server && $index->server()->fieldsUpdated($index)) {
  544. _search_api_index_reindex($index);
  545. }
  546. }
  547. // If the index's enabled or read-only status is being changed, queue or
  548. // dequeue items for indexing.
  549. if (!$index->read_only && $index->enabled != $index->original->enabled) {
  550. if ($index->enabled) {
  551. $index->queueItems();
  552. }
  553. else {
  554. $index->dequeueItems();
  555. }
  556. }
  557. elseif ($index->read_only != $index->original->read_only) {
  558. if ($index->read_only) {
  559. $index->dequeueItems();
  560. }
  561. else {
  562. $index->queueItems();
  563. }
  564. }
  565. // If the cron batch size changed, empty the cron queue for this index.
  566. $old_cron = $index->original->options + array('cron_limit' => NULL);
  567. $old_cron = $old_cron['cron_limit'];
  568. $new_cron = $index->options + array('cron_limit' => NULL);
  569. $new_cron = $new_cron['cron_limit'];
  570. if ($old_cron !== $new_cron) {
  571. _search_api_empty_cron_queue($index, TRUE);
  572. }
  573. }
  574. /**
  575. * Implements hook_search_api_index_delete().
  576. *
  577. * Removes all data for indexes not available any more.
  578. */
  579. function search_api_search_api_index_delete(SearchApiIndex $index) {
  580. $index->postDelete();
  581. }
  582. /**
  583. * Implements hook_features_export_alter().
  584. *
  585. * Adds dependency information for exported servers.
  586. */
  587. function search_api_features_export_alter(&$export, $module_name) {
  588. if (isset($export['features']['search_api_server'])) {
  589. // Get a list of the modules that provide storage engines.
  590. $hook = 'search_api_service_info';
  591. $classes = array();
  592. foreach (module_implements('search_api_service_info') as $module) {
  593. $function = $module . '_' . $hook;
  594. $engines = $function();
  595. foreach ($engines as $service => $specs) {
  596. $classes[$service] = $module;
  597. }
  598. }
  599. // Check all of the exported server specifications.
  600. foreach ($export['features']['search_api_server'] as $server_name) {
  601. // Load the server's object.
  602. $server = search_api_server_load($server_name);
  603. $module = $classes[$server->class];
  604. // Ensure that the module responsible for the server object is listed as
  605. // a dependency.
  606. if (!isset($export['dependencies'][$module])) {
  607. $export['dependencies'][$module] = $module;
  608. }
  609. }
  610. // Ensure the dependencies list is still sorted alphabetically.
  611. ksort($export['dependencies']);
  612. }
  613. }
  614. /**
  615. * Implements hook_entity_insert().
  616. *
  617. * Marks the new item as to-index for all indexes on entities of the specified
  618. * type.
  619. *
  620. * @param $entity
  621. * The new entity.
  622. * @param $type
  623. * The entity's type.
  624. */
  625. function search_api_entity_insert($entity, $type) {
  626. // When inserting a new search index, the new index was already inserted into
  627. // the tracking table. This would lead to a duplicate-key issue, if we would
  628. // continue.
  629. // We also only react on entity operations for types with property
  630. // information, as we don't provide search integration for the others.
  631. if ($type == 'search_api_index' || !entity_get_property_info($type)) {
  632. return;
  633. }
  634. list($id) = entity_extract_ids($type, $entity);
  635. if (isset($id)) {
  636. search_api_track_item_insert($type, array($id));
  637. }
  638. }
  639. /**
  640. * Implements hook_entity_update().
  641. *
  642. * Marks the item as changed for all indexes on entities of the specified type.
  643. *
  644. * @param $entity
  645. * The updated entity.
  646. * @param $type
  647. * The entity's type.
  648. */
  649. function search_api_entity_update($entity, $type) {
  650. // We only react on entity operations for types with property information, as
  651. // we don't provide search integration for the others.
  652. if (!entity_get_property_info($type)) {
  653. return;
  654. }
  655. list($id) = entity_extract_ids($type, $entity);
  656. if (isset($id)) {
  657. search_api_track_item_change($type, array($id));
  658. }
  659. }
  660. /**
  661. * Implements hook_entity_delete().
  662. *
  663. * Removes the item from the tracking table and deletes it from all indexes.
  664. *
  665. * @param $entity
  666. * The updated entity.
  667. * @param $type
  668. * The entity's type.
  669. */
  670. function search_api_entity_delete($entity, $type) {
  671. // We only react on entity operations for types with property information, as
  672. // we don't provide search integration for the others.
  673. if (!entity_get_property_info($type)) {
  674. return;
  675. }
  676. list($id) = entity_extract_ids($type, $entity);
  677. if (isset($id)) {
  678. search_api_track_item_delete($type, array($id));
  679. }
  680. }
  681. /**
  682. * Implements hook_search_api_item_type_info().
  683. *
  684. * Adds item types for all entity types with property information.
  685. */
  686. function search_api_search_api_item_type_info() {
  687. $types = array();
  688. foreach (entity_get_property_info() as $type => $property_info) {
  689. if ($info = entity_get_info($type)) {
  690. $types[$type] = array(
  691. 'name' => $info['label'],
  692. 'datasource controller' => 'SearchApiEntityDataSourceController',
  693. );
  694. }
  695. }
  696. return $types;
  697. }
  698. /**
  699. * Implements hook_modules_enabled().
  700. */
  701. function search_api_modules_enabled(array $modules) {
  702. // New modules might offer additional entity types, invalidating the cached
  703. // item type information.
  704. drupal_static_reset('search_api_get_item_type_info');
  705. }
  706. /**
  707. * Implements hook_modules_disabled().
  708. */
  709. function search_api_modules_disabled(array $modules) {
  710. // The disabled modules might have offered entity types, which are now
  711. // invalid. Therefore, clear the cached item type informaiton.
  712. drupal_static_reset('search_api_get_item_type_info');
  713. }
  714. /**
  715. * Implements hook_search_api_alter_callback_info().
  716. */
  717. function search_api_search_api_alter_callback_info() {
  718. $callbacks['search_api_alter_bundle_filter'] = array(
  719. 'name' => t('Bundle filter'),
  720. 'description' => t('Exclude items from indexing based on their bundle (content type, vocabulary, …).'),
  721. 'class' => 'SearchApiAlterBundleFilter',
  722. // Filters should be executed first.
  723. 'weight' => -10,
  724. );
  725. $callbacks['search_api_alter_add_url'] = array(
  726. 'name' => t('URL field'),
  727. 'description' => t("Adds the item's URL to the indexed data."),
  728. 'class' => 'SearchApiAlterAddUrl',
  729. );
  730. $callbacks['search_api_alter_add_aggregation'] = array(
  731. 'name' => t('Aggregated fields'),
  732. 'description' => t('Gives you the ability to define additional fields, containing data from one or more other fields.'),
  733. 'class' => 'SearchApiAlterAddAggregation',
  734. );
  735. $callbacks['search_api_alter_add_viewed_entity'] = array(
  736. 'name' => t('Complete entity view'),
  737. 'description' => t('Adds an additional field containing the whole HTML content of the entity when viewed.'),
  738. 'class' => 'SearchApiAlterAddViewedEntity',
  739. );
  740. $callbacks['search_api_alter_add_hierarchy'] = array(
  741. 'name' => t('Index hierarchy'),
  742. 'description' => t('Allows to index hierarchical fields along with all their ancestors.'),
  743. 'class' => 'SearchApiAlterAddHierarchy',
  744. );
  745. $callbacks['search_api_alter_language_control'] = array(
  746. 'name' => t('Language control'),
  747. 'description' => t('Lets you determine the language of items in the index.'),
  748. 'class' => 'SearchApiAlterLanguageControl',
  749. );
  750. $callbacks['search_api_alter_node_access'] = array(
  751. 'name' => t('Node access'),
  752. 'description' => t('Add node access information to the index.'),
  753. 'class' => 'SearchApiAlterNodeAccess',
  754. );
  755. $callbacks['search_api_alter_node_status'] = array(
  756. 'name' => t('Exclude unpublished nodes'),
  757. 'description' => t('Exclude unpublished nodes from the index.'),
  758. 'class' => 'SearchApiAlterNodeStatus',
  759. );
  760. return $callbacks;
  761. }
  762. /**
  763. * Implements hook_search_api_processor_info().
  764. */
  765. function search_api_search_api_processor_info() {
  766. $processors['search_api_case_ignore'] = array(
  767. 'name' => t('Ignore case'),
  768. 'description' => t('This processor will make searches case-insensitive for all fulltext fields (and, optionally, also for filters on string fields).'),
  769. 'class' => 'SearchApiIgnoreCase',
  770. );
  771. $processors['search_api_html_filter'] = array(
  772. 'name' => t('HTML filter'),
  773. 'description' => t('Strips HTML tags from fulltext fields and decodes HTML entities. ' .
  774. 'Use this processor when indexing HTML data, e.g., node bodies for certain text formats.<br />' .
  775. 'The processor also allows to boost (or ignore) the contents of specific elements.'),
  776. 'class' => 'SearchApiHtmlFilter',
  777. 'weight' => 10,
  778. );
  779. $processors['search_api_tokenizer'] = array(
  780. 'name' => t('Tokenizer'),
  781. 'description' => t('Tokenizes fulltext data by stripping whitespace. ' .
  782. 'This processor allows you to specify which characters make up words and which characters should be ignored, using regular expression syntax. ' .
  783. 'Otherwise it is up to the search server implementation to decide how to split indexed fulltext data.'),
  784. 'class' => 'SearchApiTokenizer',
  785. 'weight' => 20,
  786. );
  787. $processors['search_api_stopwords'] = array(
  788. 'name' => t('Stopwords'),
  789. 'description' => t('This processor prevents certain words from being indexed and removes them from search terms. ' .
  790. 'For best results, it should only be executed after tokenizing.'),
  791. 'class' => 'SearchApiStopWords',
  792. 'weight' => 30,
  793. );
  794. return $processors;
  795. }
  796. /**
  797. * Inserts new unindexed items for all indexes on the specified type.
  798. *
  799. * @param $type
  800. * The item type of the new items.
  801. * @param array $item_id
  802. * The IDs of the new items.
  803. */
  804. function search_api_track_item_insert($type, array $item_ids) {
  805. $conditions = array(
  806. 'enabled' => 1,
  807. 'item_type' => $type,
  808. 'read_only' => 0,
  809. );
  810. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  811. if (!$indexes) {
  812. return;
  813. }
  814. search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
  815. foreach ($indexes as $index) {
  816. if (!empty($index->options['index_directly'])) {
  817. $indexed = search_api_index_specific_items_delayed($index, $item_ids);
  818. }
  819. }
  820. }
  821. /**
  822. * Mark the items with the specified IDs as "dirty", i.e., as needing to be reindexed.
  823. *
  824. * For indexes for which items should be indexed immediately, the items are
  825. * indexed directly, instead.
  826. *
  827. * @param $type
  828. * The type of items, specific to the data source.
  829. * @param array $item_ids
  830. * The IDs of the items to be marked dirty.
  831. */
  832. function search_api_track_item_change($type, array $item_ids) {
  833. $conditions = array(
  834. 'enabled' => 1,
  835. 'item_type' => $type,
  836. 'read_only' => 0,
  837. );
  838. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  839. if (!$indexes) {
  840. return;
  841. }
  842. search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
  843. foreach ($indexes as $index) {
  844. if (!empty($index->options['index_directly'])) {
  845. // For indexes with the index_directly option set, queue the items to be
  846. // indexed at the end of the request.
  847. try {
  848. search_api_index_specific_items_delayed($index, $item_ids);
  849. }
  850. catch (SearchApiException $e) {
  851. watchdog_exception('search_api', $e);
  852. }
  853. }
  854. }
  855. }
  856. /**
  857. * Marks items as queued for indexing for the specified index.
  858. *
  859. * @param SearchApiIndex $index
  860. * The index on which items were queued.
  861. * @param array $item_ids
  862. * The ids of the queued items.
  863. */
  864. function search_api_track_item_queued(SearchApiIndex $index, array $item_ids) {
  865. $index->datasource()->trackItemQueued($item_ids, $index);
  866. }
  867. /**
  868. * Marks items as successfully indexed for the specified index.
  869. *
  870. * @param SearchApiIndex $index
  871. * The index on which items were indexed.
  872. * @param array $item_ids
  873. * The ids of the indexed items.
  874. */
  875. function search_api_track_item_indexed(SearchApiIndex $index, array $item_ids) {
  876. $index->datasource()->trackItemIndexed($item_ids, $index);
  877. }
  878. /**
  879. * Removes items from all indexes.
  880. *
  881. * @param $type
  882. * The type of the items.
  883. * @param array $item_ids
  884. * The IDs of the deleted items.
  885. */
  886. function search_api_track_item_delete($type, array $item_ids) {
  887. // First, delete the item from the tracking table.
  888. $conditions = array(
  889. 'enabled' => 1,
  890. 'item_type' => $type,
  891. 'read_only' => 0,
  892. );
  893. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  894. if ($indexes) {
  895. search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
  896. }
  897. // Then, delete it from all servers. Servers of disabled indexes have to be
  898. // considered, too!
  899. unset($conditions['enabled']);
  900. foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
  901. if ($index->server) {
  902. $server = $index->server();
  903. if ($server->enabled) {
  904. $server->deleteItems($item_ids, $index);
  905. }
  906. else {
  907. $tasks = variable_get('search_api_tasks', array());
  908. foreach ($item_ids as $id) {
  909. $tasks[$server->machine_name][$index->machine_name][] = 'delete-' . $id;
  910. }
  911. variable_set('search_api_tasks', $tasks);
  912. }
  913. }
  914. }
  915. }
  916. /**
  917. * Indexes items for the specified index. Only items marked as changed are
  918. * indexed, in their order of change (if known).
  919. *
  920. * @param SearchApiIndex $index
  921. * The index on which items should be indexed.
  922. * @param $limit
  923. * The number of items which should be indexed at most. -1 means no limit.
  924. *
  925. * @throws SearchApiException
  926. * If any error occurs during indexing.
  927. *
  928. * @return
  929. * Number of successfully indexed items.
  930. */
  931. function search_api_index_items(SearchApiIndex $index, $limit = -1) {
  932. // Don't try to index read-only indexes.
  933. if ($index->read_only) {
  934. return 0;
  935. }
  936. $queue = DrupalQueue::get('search_api_indexing_queue');
  937. $queue->createQueue();
  938. $indexed = 0;
  939. $unlimited = $limit < 0;
  940. $release_items = array();
  941. while (($unlimited || $indexed < $limit) && ($item = $queue->claimItem(30))) {
  942. if ($item->data['index'] === $index->machine_name) {
  943. $indexed += _search_api_indexing_queue_process($item->data);
  944. $queue->deleteItem($item);
  945. }
  946. else {
  947. $release_items[] = $item;
  948. }
  949. }
  950. foreach ($release_items as $item) {
  951. $queue->releaseItem($item);
  952. }
  953. if ($unlimited || $indexed < $limit) {
  954. $ids = search_api_get_items_to_index($index, $unlimited ? -1 : $limit - $indexed);
  955. if ($ids) {
  956. $indexed += count(search_api_index_specific_items($index, $ids));
  957. }
  958. }
  959. return $indexed;
  960. }
  961. /**
  962. * Indexes the specified items on the given index.
  963. *
  964. * Items which were successfully indexed are marked as such afterwards.
  965. *
  966. * @param SearchApiIndex $index
  967. * The index on which items should be indexed.
  968. * @param array $ids
  969. * The IDs of the items which should be indexed.
  970. *
  971. * @throws SearchApiException
  972. * If any error occurs during indexing.
  973. *
  974. * @return
  975. * The IDs of all successfully indexed items.
  976. */
  977. function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
  978. $items = $index->loadItems($ids);
  979. // Clone items because data alterations may alter them.
  980. $cloned_items = array();
  981. foreach ($items as $id => $item) {
  982. $cloned_items[$id] = clone $item;
  983. }
  984. $indexed = $items ? $index->index($cloned_items) : array();
  985. if ($indexed) {
  986. search_api_track_item_indexed($index, $indexed);
  987. // If some items could not be indexed, we don't want to try re-indexing
  988. // them right away, so we mark them as "freshly" changed. Sadly, there is
  989. // no better way than to mark them as indexed first...
  990. if (count($indexed) < count($ids)) {
  991. // Believe it or not but this is actually quite faster than the equivalent
  992. // $diff = array_diff($ids, $indexed);
  993. $diff = array_keys(array_diff_key(array_flip($ids), array_flip($indexed)));
  994. $index->datasource()->trackItemIndexed($diff, $index);
  995. $index->datasource()->trackItemChange($diff, array($index));
  996. }
  997. }
  998. return $indexed;
  999. }
  1000. /**
  1001. * Queues items for indexing at the end of the page request.
  1002. *
  1003. * @param SearchApiIndex $index
  1004. * The index on which items should be indexed.
  1005. * @param array $ids
  1006. * The IDs of the items which should be indexed.
  1007. *
  1008. * @return array
  1009. * The current contents of the queue, as a reference.
  1010. *
  1011. * @see search_api_index_specific_items()
  1012. * @see _search_api_index_queued_items()
  1013. */
  1014. function &search_api_index_specific_items_delayed(SearchApiIndex $index = NULL, array $ids = array()) {
  1015. // We cannot use drupal_static() here because the static cache is reset during
  1016. // batch processing, which breaks batch handling.
  1017. static $queue = array();
  1018. static $registered = FALSE;
  1019. // Only register the shutdown function once.
  1020. if (empty($registered)) {
  1021. drupal_register_shutdown_function('_search_api_index_queued_items');
  1022. $registered = TRUE;
  1023. }
  1024. // Allow for empty call to just retrieve the queue.
  1025. if ($index && $ids) {
  1026. $index_id = $index->machine_name;
  1027. $queue += array($index_id => array());
  1028. $queue[$index_id] += drupal_map_assoc($ids);
  1029. }
  1030. return $queue;
  1031. }
  1032. /**
  1033. * Returns a list of items that need to be indexed for the specified index.
  1034. *
  1035. * @param SearchApiIndex $index
  1036. * The index for which items should be retrieved.
  1037. * @param $limit
  1038. * The maximum number of items to retrieve. -1 means no limit.
  1039. *
  1040. * @return array
  1041. * An array of IDs of items that need to be indexed.
  1042. */
  1043. function search_api_get_items_to_index(SearchApiIndex $index, $limit = -1) {
  1044. if ($limit == 0) {
  1045. return array();
  1046. }
  1047. return $index->datasource()->getChangedItems($index, $limit);
  1048. }
  1049. /**
  1050. * Creates a search query on a specified search index.
  1051. *
  1052. * @param $id
  1053. * The ID or machine name of the index to execute the search on.
  1054. * @param $options
  1055. * An associative array of options. The following are recognized:
  1056. * - filters: Either a SearchApiQueryFilterInterface object or an array of
  1057. * filters used to filter the search.
  1058. * - sort: An array of sort directives of the form $field => $order, where
  1059. * $order is either 'ASC' or 'DESC'.
  1060. * - offset: The position of the first returned search results relative to the
  1061. * whole result in the index.
  1062. * - limit: The maximum number of search results to return. -1 means no limit.
  1063. * - 'query class': The query class to use. Must be a subtype of
  1064. * SearchApiQueryInterface.
  1065. * - conjunction: The type of conjunction to use for this query - either
  1066. * 'AND' or 'OR'. 'AND' by default.
  1067. * - 'parse mode': The mode with which to parse the $keys variable, if it
  1068. * is set and not already an array. See SearchApiQuery::parseModes() for
  1069. * parse modes recognized by the SearchApiQuery class.
  1070. * Subclasses might define additional modes.
  1071. *
  1072. * @return SearchApiQueryInterface
  1073. * An object for searching on the specified index.
  1074. */
  1075. function search_api_query($id, array $options = array()) {
  1076. $index = search_api_index_load($id);
  1077. if (!$index) {
  1078. throw new SearchApiException(t('Unknown index with ID @id.', array('@id' => $id)));
  1079. }
  1080. return $index->query($options);
  1081. }
  1082. /**
  1083. * Static store for the searches executed on the current page. Can either be
  1084. * used to store an executed search, or to retrieve a previously stored
  1085. * search.
  1086. *
  1087. * @param $search_id
  1088. * For pages displaying multiple searches, an optional ID identifying the
  1089. * search in questions. When storing a search, this is filled automatically,
  1090. * unless it is manually set.
  1091. * @param SearchApiQuery $query
  1092. * When storing an executed search, the query that was executed. NULL
  1093. * otherwise.
  1094. * @param array $results
  1095. * When storing an executed search, the returned results as specified by
  1096. * SearchApiQueryInterface::execute(). An empty array, otherwise.
  1097. *
  1098. * @return array
  1099. * If a search with the specified ID was executed, an array containing
  1100. * ($query, $results) as used in this function's parameters. If $search_id is
  1101. * NULL, an array of all executed searches will be returned, keyed by ID.
  1102. */
  1103. function search_api_current_search($search_id = NULL, SearchApiQuery $query = NULL, array $results = array()) {
  1104. $searches = &drupal_static(__FUNCTION__, array());
  1105. if (isset($query)) {
  1106. if (!isset($search_id)) {
  1107. $search_id = $query->getOption('search id');
  1108. }
  1109. $base = $search_id;
  1110. $i = 0;
  1111. while (isset($searches[$search_id])) {
  1112. $search_id = $base . '-' . ++$i;
  1113. }
  1114. $searches[$search_id] = array($query, $results);
  1115. }
  1116. if (isset($search_id)) {
  1117. return isset($searches[$search_id]) ? $searches[$search_id] : NULL;
  1118. }
  1119. return $searches;
  1120. }
  1121. /**
  1122. * Returns all field types recognized by the Search API framework.
  1123. *
  1124. * @return array
  1125. * An associative array with all recognized types as keys, mapped to their
  1126. * translated display names.
  1127. *
  1128. * @see search_api_default_field_types()
  1129. * @see search_api_get_data_type_info()
  1130. */
  1131. function search_api_field_types() {
  1132. $types = search_api_default_field_types();
  1133. foreach (search_api_get_data_type_info() as $id => $type) {
  1134. $types[$id] = $type['name'];
  1135. }
  1136. return $types;
  1137. }
  1138. /**
  1139. * Returns the default field types recognized by the Search API framework.
  1140. *
  1141. * @return array
  1142. * An associative array with the default types as keys, mapped to their
  1143. * translated display names.
  1144. */
  1145. function search_api_default_field_types() {
  1146. return array(
  1147. 'text' => t('Fulltext'),
  1148. 'string' => t('String'),
  1149. 'integer' => t('Integer'),
  1150. 'decimal' => t('Decimal'),
  1151. 'date' => t('Date'),
  1152. 'duration' => t('Duration'),
  1153. 'boolean' => t('Boolean'),
  1154. 'uri' => t('URI'),
  1155. );
  1156. }
  1157. /**
  1158. * Returns either all custom field type definitions, or a specific one.
  1159. *
  1160. * @param $type
  1161. * If specified, the type whose definition should be returned.
  1162. *
  1163. * @return array
  1164. * If $type was not given, an array containing all custom data types, in the
  1165. * format specified by hook_search_api_data_type_info().
  1166. * Otherwise, the definition for the given type, or NULL if it is unknown.
  1167. *
  1168. * @see hook_search_api_data_type_info()
  1169. */
  1170. function search_api_get_data_type_info($type = NULL) {
  1171. $types = &drupal_static(__FUNCTION__);
  1172. if (!isset($types)) {
  1173. $default_types = search_api_default_field_types();
  1174. $types = module_invoke_all('search_api_data_type_info');
  1175. $types = $types ? $types : array();
  1176. foreach ($types as &$type_info) {
  1177. if (!isset($type_info['fallback']) || !isset($default_types[$type_info['fallback']])) {
  1178. $type_info['fallback'] = 'string';
  1179. }
  1180. }
  1181. drupal_alter('search_api_data_type_info', $types);
  1182. }
  1183. if (isset($type)) {
  1184. return isset($types[$type]) ? $types[$type] : NULL;
  1185. }
  1186. return $types;
  1187. }
  1188. /**
  1189. * Returns either a list of all available service infos, or a specific one.
  1190. *
  1191. * @see hook_search_api_service_info()
  1192. *
  1193. * @param $id
  1194. * The ID of the service info to retrieve.
  1195. *
  1196. * @return array
  1197. * If $id was not specified, an array of all available service classes.
  1198. * Otherwise, either the service info with the specified id (if it exists),
  1199. * or NULL.
  1200. */
  1201. function search_api_get_service_info($id = NULL) {
  1202. $services = &drupal_static(__FUNCTION__);
  1203. if (!isset($services)) {
  1204. $services = module_invoke_all('search_api_service_info');
  1205. // Allow other modules to alter definitions
  1206. drupal_alter('search_api_service_info', $services);
  1207. }
  1208. if (isset($id)) {
  1209. return isset($services[$id]) ? $services[$id] : NULL;
  1210. }
  1211. return $services;
  1212. }
  1213. /**
  1214. * Returns information for either all item types, or a specific one.
  1215. *
  1216. * @param $type
  1217. * If set, the item type whose information should be returned.
  1218. *
  1219. * @return
  1220. * If $type is given, either an array containing the information of that item
  1221. * type, or NULL if it is unknown. Otherwise, an array keyed by type IDs
  1222. * containing the information for all item types. Item type information is
  1223. * formatted as specified by hook_search_api_item_type_info(), and has all
  1224. * optional fields filled with the defaults.
  1225. *
  1226. * @see hook_search_api_item_type_info()
  1227. */
  1228. function search_api_get_item_type_info($type = NULL) {
  1229. $types = &drupal_static(__FUNCTION__);
  1230. if (!isset($types)) {
  1231. $types = module_invoke_all('search_api_item_type_info');
  1232. drupal_alter('search_api_item_type_info', $types);
  1233. }
  1234. if (isset($type)) {
  1235. return isset($types[$type]) ? $types[$type] : NULL;
  1236. }
  1237. return $types;
  1238. }
  1239. /**
  1240. * Get a data source controller object for the specified type.
  1241. *
  1242. * @param $type
  1243. * The type whose data source controller should be returned.
  1244. *
  1245. * @return SearchApiDataSourceControllerInterface
  1246. * The type's data source controller.
  1247. *
  1248. * @throws SearchApiException
  1249. * If the type is unknown or specifies an invalid data source controller.
  1250. */
  1251. function search_api_get_datasource_controller($type) {
  1252. $datasources = &drupal_static(__FUNCTION__, array());
  1253. if (empty($datasources[$type])) {
  1254. $info = search_api_get_item_type_info($type);
  1255. if (isset($info['datasource controller']) && class_exists($info['datasource controller'])) {
  1256. $datasources[$type] = new $info['datasource controller']($type);
  1257. }
  1258. if (empty($datasources[$type]) || !($datasources[$type] instanceof SearchApiDataSourceControllerInterface)) {
  1259. unset($datasources[$type]);
  1260. throw new SearchApiException(t('Unknown or invalid item type @type.', array('@type' => $type)));
  1261. }
  1262. }
  1263. return $datasources[$type];
  1264. }
  1265. /**
  1266. * Returns a list of all available data alter callbacks.
  1267. *
  1268. * @see hook_search_api_alter_callback_info()
  1269. *
  1270. * @return array
  1271. * An array of all available data alter callbacks, keyed by function name.
  1272. */
  1273. function search_api_get_alter_callbacks() {
  1274. $callbacks = &drupal_static(__FUNCTION__);
  1275. if (!isset($callbacks)) {
  1276. $callbacks = module_invoke_all('search_api_alter_callback_info');
  1277. // Initialization of optional entries with default values
  1278. foreach ($callbacks as $id => $callback) {
  1279. $callbacks[$id] += array('enabled' => TRUE, 'weight' => 0);
  1280. }
  1281. }
  1282. return $callbacks;
  1283. }
  1284. /**
  1285. * Returns a list of all available pre- and post-processors.
  1286. *
  1287. * @see hook_search_api_processor_info()
  1288. *
  1289. * @return array
  1290. * An array of all available processors, keyed by id.
  1291. */
  1292. function search_api_get_processors() {
  1293. $processors = &drupal_static(__FUNCTION__);
  1294. if (!isset($processors)) {
  1295. $processors = module_invoke_all('search_api_processor_info');
  1296. // Initialization of optional entries with default values
  1297. foreach ($processors as $id => $processor) {
  1298. $processors[$id] += array('enabled pre' => TRUE, 'enabled post' => TRUE, 'weight' => 0);
  1299. }
  1300. }
  1301. return $processors;
  1302. }
  1303. /**
  1304. * Implements hook_search_api_query_alter().
  1305. *
  1306. * Adds node access to the query, if enabled.
  1307. *
  1308. * @param SearchApiQueryInterface $query
  1309. * The SearchApiQueryInterface object representing the search query.
  1310. */
  1311. function search_api_search_api_query_alter(SearchApiQueryInterface $query) {
  1312. $index = $query->getIndex();
  1313. // Only add node access if the necessary fields are indexed in the index, and
  1314. // unless disabled explicitly by the query.
  1315. $fields = $index->options['fields'];
  1316. if (!empty($fields['search_api_access_node']) && !empty($fields['status']) && !empty($fields['author']) && !$query->getOption('search_api_bypass_access')) {
  1317. $account = $query->getOption('search_api_access_account', $GLOBALS['user']);
  1318. if (is_numeric($account)) {
  1319. $account = user_load($account);
  1320. }
  1321. if (is_object($account)) {
  1322. try {
  1323. _search_api_query_add_node_access($account, $query);
  1324. }
  1325. catch (SearchApiException $e) {
  1326. watchdog_exception('search_api', $e);
  1327. }
  1328. }
  1329. else {
  1330. watchdog('search_api', 'An illegal user UID was given for node access: @uid.', array('@uid' => $query->getOption('search_api_access_account', $GLOBALS['user'])), WATCHDOG_WARNING);
  1331. }
  1332. }
  1333. }
  1334. /**
  1335. * Build a node access subquery.
  1336. *
  1337. * @param $account
  1338. * The user object, who searches.
  1339. *
  1340. * @return SearchApiQueryFilter
  1341. */
  1342. function _search_api_query_add_node_access($account, SearchApiQueryInterface $query) {
  1343. if (!user_access('access content', $account)) {
  1344. // Simple hack for returning no results.
  1345. $query->condition('status', 0);
  1346. $query->condition('status', 1);
  1347. watchdog('search_api', 'User @name tried to execute a search, but cannot access content.', array('@name' => theme('username', array('account' => $account))), WATCHDOG_NOTICE);
  1348. return;
  1349. }
  1350. // Only filter for user which don't have full node access.
  1351. if (!user_access('bypass node access', $account)) {
  1352. // Filter by node "published" status.
  1353. if (user_access('view own unpublished content')) {
  1354. $filter = $query->createFilter('OR');
  1355. $filter->condition('status', NODE_PUBLISHED);
  1356. $filter->condition('author', $account->uid);
  1357. $query->filter($filter);
  1358. }
  1359. else {
  1360. // $query->condition('status', NODE_PUBLISHED);
  1361. }
  1362. // Filter by node access grants.
  1363. $filter = $query->createFilter('OR');
  1364. $grants = node_access_grants('view', $account);
  1365. foreach ($grants as $realm => $gids) {
  1366. foreach ($gids as $gid) {
  1367. $filter->condition('search_api_access_node', "node_access_$realm:$gid");
  1368. }
  1369. }
  1370. $filter->condition('search_api_access_node', 'node_access__all');
  1371. $query->filter($filter);
  1372. }
  1373. }
  1374. /**
  1375. * Utility function for determining whether a field of the given type contains
  1376. * text data.
  1377. *
  1378. * @param $type
  1379. * A string containing the type to check.
  1380. * @param array $allowed
  1381. * Optionally, an array of allowed types.
  1382. *
  1383. * @return
  1384. * TRUE if $type is either one of the specified types, or a list of such
  1385. * values. FALSE otherwise.
  1386. */
  1387. function search_api_is_text_type($type, array $allowed = array('text')) {
  1388. return array_search(search_api_extract_inner_type($type), $allowed) !== FALSE;
  1389. }
  1390. /**
  1391. * Utility function for determining whether a field of the given type contains
  1392. * a list of any kind.
  1393. *
  1394. * @param $type
  1395. * A string containing the type to check.
  1396. *
  1397. * @return
  1398. * TRUE iff $type is a list type ("list<*>").
  1399. */
  1400. function search_api_is_list_type($type) {
  1401. return substr($type, 0, 5) == 'list<';
  1402. }
  1403. /**
  1404. * Utility function for determining the nesting level of a list type.
  1405. *
  1406. * @param $type
  1407. * A string containing the type to check.
  1408. *
  1409. * @return
  1410. * The nesting level of the type. 0 for singular types, 1 for lists of
  1411. * singular types, etc.
  1412. */
  1413. function search_api_list_nesting_level($type) {
  1414. $level = 0;
  1415. while (search_api_is_list_type($type)) {
  1416. $type = substr($type, 5, -1);
  1417. ++$level;
  1418. }
  1419. return $level;
  1420. }
  1421. /**
  1422. * Utility function for nesting a type to the same level as another type.
  1423. * I.e., after <code>$t = search_api_nest_type($type, $nested_type);</code> is
  1424. * executed, the following statements will always be true:
  1425. * @code
  1426. * search_api_list_nesting_level($t) == search_api_list_nesting_level($nested_type);
  1427. * search_api_extract_inner_type($t) == search_api_extract_inner_type($type);
  1428. * @endcode
  1429. *
  1430. * @param $type
  1431. * The type to wrap.
  1432. * @param $nested_type
  1433. * Another type, determining the nesting level.
  1434. *
  1435. * @return
  1436. * A list version of $type, as specified above.
  1437. */
  1438. function search_api_nest_type($type, $nested_type) {
  1439. while (search_api_is_list_type($nested_type)) {
  1440. $nested_type = substr($nested_type, 5, -1);
  1441. $type = "list<$type>";
  1442. }
  1443. return $type;
  1444. }
  1445. /**
  1446. * Utility function for extracting the contained primitive type of a list type.
  1447. *
  1448. * @param $type
  1449. * A string containing the list type to process.
  1450. *
  1451. * @return
  1452. * A string containing the primitive type contained within the list, e.g.
  1453. * "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
  1454. * type, it is returned unchanged.
  1455. */
  1456. function search_api_extract_inner_type($type) {
  1457. while (search_api_is_list_type($type)) {
  1458. $type = substr($type, 5, -1);
  1459. }
  1460. return $type;
  1461. }
  1462. /**
  1463. * Utility function for extracting specific fields from an EntityMetadataWrapper
  1464. * object.
  1465. *
  1466. * @param EntityMetadataWrapper $wrapper
  1467. * The wrapper from which to extract fields.
  1468. * @param array $fields
  1469. * The fields to extract, as stored in an index. I.e., the array keys are
  1470. * field names, the values are arrays with the keys "name", "type", "boost"
  1471. * and "indexed" (although only "type" is used by this function).
  1472. * @param array $value_options
  1473. * An array of options that should be passed to the
  1474. * EntityMetadataWrapper::value() method (see there).
  1475. *
  1476. * @return
  1477. * The $fields array with additional "value" and "original_type" keys set.
  1478. */
  1479. function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
  1480. // If $wrapper is a list of entities, we have to aggregate their field values.
  1481. $wrapper_info = $wrapper->info();
  1482. if (search_api_is_list_type($wrapper_info['type'])) {
  1483. foreach ($fields as $field => &$info) {
  1484. $info['value'] = array();
  1485. $info['original_type'] = $info['type'];
  1486. }
  1487. unset($info);
  1488. try {
  1489. foreach ($wrapper as $i => $w) {
  1490. $nested_fields = search_api_extract_fields($w, $fields, $value_options);
  1491. foreach ($nested_fields as $field => $info) {
  1492. if (isset($info['value'])) {
  1493. $fields[$field]['value'][] = $info['value'];
  1494. }
  1495. if (isset($info['original_type'])) {
  1496. $fields[$field]['original_type'] = $info['original_type'];
  1497. }
  1498. }
  1499. }
  1500. }
  1501. catch (EntityMetadataWrapperException $e) {
  1502. // Catch exceptions caused by not set list values.
  1503. }
  1504. return $fields;
  1505. }
  1506. $nested = array();
  1507. $entity_infos = entity_get_info();
  1508. foreach ($fields as $field => &$info) {
  1509. $pos = strpos($field, ':');
  1510. if ($pos === FALSE) {
  1511. // Set "defaults" in case an error occurs later.
  1512. $info['value'] = NULL;
  1513. $info['original_type'] = $info['type'];
  1514. try {
  1515. $info['value'] = $wrapper->$field->value($value_options);
  1516. // For fulltext fields with options, also include the option labels.
  1517. if (search_api_is_text_type($info['type']) && $wrapper->$field->optionsList('view')) {
  1518. _search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
  1519. }
  1520. $property_info = $wrapper->$field->info();
  1521. $info['original_type'] = $property_info['type'];
  1522. // For entities, we extract the entity ID instead of the whole object.
  1523. // @todo Use 'identifier' => TRUE instead of always loading the object.
  1524. $t = search_api_extract_inner_type($property_info['type']);
  1525. if (isset($entity_infos[$t])) {
  1526. // If no object is set, set this field to NULL.
  1527. $info['value'] = $info['value'] ? _search_api_extract_entity_value($wrapper->$field, search_api_is_text_type($info['type'])) : NULL;
  1528. }
  1529. }
  1530. catch (EntityMetadataWrapperException $e) {
  1531. // This might happen for entity-typed properties that are NULL, e.g.,
  1532. // for comments without parent.
  1533. }
  1534. }
  1535. else {
  1536. list($prefix, $key) = explode(':', $field, 2);
  1537. $nested[$prefix][$key] = $info;
  1538. }
  1539. }
  1540. unset($info);
  1541. foreach ($nested as $prefix => $nested_fields) {
  1542. if (isset($wrapper->$prefix)) {
  1543. $nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
  1544. # http://drupal.org/node/1873910#comment-6876200
  1545. // $subwrapper = $wrapper->$prefix;
  1546. // $subwrapper->language( $wrapper->language->value() );
  1547. // $nested_fields = search_api_extract_fields($subwrapper, $nested_fields, $value_options);
  1548. foreach ($nested_fields as $field => $info) {
  1549. $fields["$prefix:$field"] = $info;
  1550. }
  1551. }
  1552. else {
  1553. foreach ($nested_fields as $field => &$info) {
  1554. $info['value'] = NULL;
  1555. $info['original_type'] = $info['type'];
  1556. }
  1557. }
  1558. }
  1559. return $fields;
  1560. }
  1561. /**
  1562. * Helper method for adding additional text data to fields with an option list.
  1563. */
  1564. function _search_api_add_option_values(&$value, array $options) {
  1565. if (is_array($value)) {
  1566. foreach ($value as &$v) {
  1567. _search_api_add_option_values($v, $options);
  1568. }
  1569. return;
  1570. }
  1571. if (is_scalar($value) && isset($options[$value])) {
  1572. $value .= ' ' . $options[$value];
  1573. }
  1574. }
  1575. /**
  1576. * Helper method for extracting the ID (and possibly label) of an entity-valued field.
  1577. */
  1578. function _search_api_extract_entity_value(EntityMetadataWrapper $wrapper, $fulltext = FALSE) {
  1579. $v = $wrapper->value();
  1580. if (is_array($v)) {
  1581. $ret = array();
  1582. foreach ($wrapper as $item) {
  1583. $values = _search_api_extract_entity_value($item, $fulltext);
  1584. if ($values) {
  1585. $ret[] = $values;
  1586. }
  1587. }
  1588. return $ret;
  1589. }
  1590. if ($v) {
  1591. $ret = $wrapper->getIdentifier();
  1592. if ($fulltext && ($label = $wrapper->label())) {
  1593. $ret .= ' ' . $label;
  1594. }
  1595. return $ret;
  1596. }
  1597. return NULL;
  1598. }
  1599. /**
  1600. * Load the search server with the specified id.
  1601. *
  1602. * @param $id
  1603. * The search server's id.
  1604. * @param $reset
  1605. * Whether to reset the internal cache.
  1606. *
  1607. * @return SearchApiServer
  1608. * An object representing the server with the specified id.
  1609. */
  1610. function search_api_server_load($id, $reset = FALSE) {
  1611. $ret = search_api_server_load_multiple(array($id), array(), $reset);
  1612. return $ret ? reset($ret) : FALSE;
  1613. }
  1614. /**
  1615. * Load multiple servers at once, determined by IDs or machine names, or by
  1616. * other conditions.
  1617. *
  1618. * @see entity_load()
  1619. *
  1620. * @param $ids
  1621. * An array of server IDs or machine names, or FALSE to load all servers.
  1622. * @param $conditions
  1623. * An array of conditions on the {search_api_server} table in the form
  1624. * 'field' => $value.
  1625. * @param $reset
  1626. * Whether to reset the internal entity_load cache.
  1627. *
  1628. * @return array
  1629. * An array of server objects keyed by machine name.
  1630. */
  1631. function search_api_server_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  1632. return entity_load_multiple_by_name('search_api_server', $ids, $conditions, $reset);
  1633. }
  1634. /**
  1635. * Entity uri callback.
  1636. */
  1637. function search_api_server_url(SearchApiServer $server) {
  1638. return array(
  1639. 'path' => 'admin/config/search/search_api/server/' . $server->machine_name,
  1640. 'options' => array(),
  1641. );
  1642. }
  1643. /**
  1644. * Title callback for determining which title should be displayed for the
  1645. * "delete" local task.
  1646. *
  1647. * @param Entity $entity
  1648. * The server or index for which the menu link is displayed.
  1649. *
  1650. * @return string
  1651. * A translated version of either "Delete" or "Revert".
  1652. */
  1653. function search_api_title_delete_page(Entity $entity) {
  1654. return $entity->hasStatus(ENTITY_OVERRIDDEN) ? t('Revert') : t('Delete');
  1655. }
  1656. /**
  1657. * Access callback for determining if a server's or index' "delete" page should
  1658. * be accessible.
  1659. *
  1660. * @param Entity $entity
  1661. * The server or index for which the access to the delete page is checked.
  1662. *
  1663. * @return
  1664. * TRUE if the delete page can be accessed by the user, FALSE otherwise.
  1665. */
  1666. function search_api_access_delete_page(Entity $entity) {
  1667. return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
  1668. }
  1669. /**
  1670. * Inserts a new search server into the database.
  1671. *
  1672. * @param array $values
  1673. * An array containing the values to be inserted.
  1674. *
  1675. * @return
  1676. * The newly inserted server's id, or FALSE on error.
  1677. */
  1678. function search_api_server_insert(array $values) {
  1679. $server = entity_create('search_api_server', $values);
  1680. $server->is_new = TRUE;
  1681. $server->save();
  1682. return $server->id;
  1683. }
  1684. /**
  1685. * Changes a server's settings.
  1686. *
  1687. * @param $id
  1688. * The ID or machine name of the server whose values should be changed.
  1689. * @param array $fields
  1690. * The new field values to set. The enabled field can't be set this way, use
  1691. * search_api_server_enable() and search_api_server_disable() instead.
  1692. *
  1693. * @return
  1694. * 1 if fields were changed, 0 if the fields already had the desired values.
  1695. * FALSE on failure.
  1696. */
  1697. function search_api_server_edit($id, array $fields) {
  1698. $server = search_api_server_load($id, TRUE);
  1699. $ret = $server->update($fields);
  1700. return $ret ? 1 : $ret;
  1701. }
  1702. /**
  1703. * Enables a search server. Will also check for remembered tasks for this server
  1704. * and execute them.
  1705. *
  1706. * @param $id
  1707. * The ID or machine name of the server to enable.
  1708. *
  1709. * @return
  1710. * 1 on success, 0 or FALSE on failure.
  1711. */
  1712. function search_api_server_enable($id) {
  1713. $server = search_api_server_load($id, TRUE);
  1714. $ret = $server->update(array('enabled' => 1));
  1715. return $ret ? 1 : $ret;
  1716. }
  1717. /**
  1718. * Disables a search server, along with all associated indexes.
  1719. *
  1720. * @param $id
  1721. * The ID or machine name of the server to disable.
  1722. *
  1723. * @return
  1724. * 1 on success, 0 or FALSE on failure.
  1725. */
  1726. function search_api_server_disable($id) {
  1727. $server = search_api_server_load($id, TRUE);
  1728. $ret = $server->update(array('enabled' => 0));
  1729. return $ret ? 1 : $ret;
  1730. }
  1731. /**
  1732. * Deletes a search server and disables all associated indexes.
  1733. *
  1734. * @param $id
  1735. * The ID or machine name of the server to delete.
  1736. *
  1737. * @return
  1738. * 1 on success, 0 or FALSE on failure.
  1739. */
  1740. function search_api_server_delete($id) {
  1741. $server = search_api_server_load($id, TRUE);
  1742. $server->delete();
  1743. return 1;
  1744. }
  1745. /**
  1746. * Loads the Search API index with the specified id.
  1747. *
  1748. * @param $id
  1749. * The index' id.
  1750. * @param $reset
  1751. * Whether to reset the internal cache.
  1752. *
  1753. * @return SearchApiIndex
  1754. * A completely loaded index object, or NULL if no such index exists.
  1755. */
  1756. function search_api_index_load($id, $reset = FALSE) {
  1757. $ret = search_api_index_load_multiple(array($id), array(), $reset);
  1758. return $ret ? reset($ret) : FALSE;
  1759. }
  1760. /**
  1761. * Load multiple indexes at once, determined by IDs or machine names, or by
  1762. * other conditions.
  1763. *
  1764. * @see entity_load()
  1765. *
  1766. * @param $ids
  1767. * An array of index IDs or machine names, or FALSE to load all indexes.
  1768. * @param $conditions
  1769. * An array of conditions on the {search_api_index} table in the form
  1770. * 'field' => $value.
  1771. * @param $reset
  1772. * Whether to reset the internal entity_load cache.
  1773. *
  1774. * @return array
  1775. * An array of index objects keyed by machine name.
  1776. */
  1777. function search_api_index_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  1778. // This line is a workaround for a weird PDO bug in PHP 5.2.
  1779. // See http://drupal.org/node/889286.
  1780. new SearchApiIndex();
  1781. return entity_load_multiple_by_name('search_api_index', $ids, $conditions, $reset);
  1782. }
  1783. /**
  1784. * Determines a search index' indexing status.
  1785. *
  1786. * @param SearchApiIndex $index
  1787. * The index whose indexing status should be determined.
  1788. *
  1789. * @return array
  1790. * An associative array containing two keys (in this order):
  1791. * - indexed: The number of items already indexed in their latest version.
  1792. * - total: The total number of items that have to be indexed for this index.
  1793. */
  1794. function search_api_index_status(SearchApiIndex $index) {
  1795. return $index->datasource()->getIndexStatus($index);
  1796. }
  1797. /**
  1798. * Entity uri callback.
  1799. */
  1800. function search_api_index_url(SearchApiIndex $index) {
  1801. return array(
  1802. 'path' => 'admin/config/search/search_api/index/' . $index->machine_name,
  1803. 'options' => array(),
  1804. );
  1805. }
  1806. /**
  1807. * Property callback.
  1808. *
  1809. * @return SearchApiServer
  1810. * The server this index currently resides on, or NULL if the index
  1811. * is currently unassigned.
  1812. */
  1813. function search_api_index_get_server(SearchApiIndex $index) {
  1814. return $index->server();
  1815. }
  1816. /**
  1817. * Inserts a new search index into the database.
  1818. *
  1819. * @param array $values
  1820. * An array containing the values to be inserted.
  1821. *
  1822. * @return
  1823. * The newly inserted index' id, or FALSE on error.
  1824. */
  1825. function search_api_index_insert(array $values) {
  1826. $index = entity_create('search_api_index', $values);
  1827. $index->is_new = TRUE;
  1828. $index->save();
  1829. return $index->id;
  1830. }
  1831. /**
  1832. * Changes an index' settings.
  1833. *
  1834. * @param $id
  1835. * The edited index' id.
  1836. * @param array $fields
  1837. * The new field values to set.
  1838. *
  1839. * @return
  1840. * 1 if fields were changed, 0 if the fields already had the desired values.
  1841. * FALSE on failure.
  1842. */
  1843. function search_api_index_edit($id, array $fields) {
  1844. $index = search_api_index_load($id, TRUE);
  1845. $ret = $index->update($fields);
  1846. return $ret ? 1 : $ret;
  1847. }
  1848. /**
  1849. * Changes an index' indexed field settings.
  1850. *
  1851. * @param $id
  1852. * The ID or machine name of the index whose fields should be changed.
  1853. * @param array $fields
  1854. * The new indexed field settings.
  1855. *
  1856. * @return
  1857. * 1 if the field settings were changed, 0 if they already had the desired
  1858. * values. FALSE on failure.
  1859. */
  1860. function search_api_index_edit_fields($id, array $fields) {
  1861. $index = search_api_index_load($id, TRUE);
  1862. $options = $index->options;
  1863. $options['fields'] = $fields;
  1864. $ret = $index->update(array('options' => $options));
  1865. return $ret ? 1 : $ret;
  1866. }
  1867. /**
  1868. * Enables a search index.
  1869. *
  1870. * @param $id
  1871. * The ID or machine name of the index to enable.
  1872. *
  1873. * @throws SearchApiException
  1874. * If the index' server isn't enabled.
  1875. *
  1876. * @return
  1877. * 1 on success, 0 or FALSE on failure.
  1878. */
  1879. function search_api_index_enable($id) {
  1880. $index = search_api_index_load($id, TRUE);
  1881. $ret = $index->update(array('enabled' => 1));
  1882. return $ret ? 1 : $ret;
  1883. }
  1884. /**
  1885. * Disables a search index.
  1886. *
  1887. * @param $id
  1888. * The ID or machine name of the index to disable.
  1889. *
  1890. * @return
  1891. * 1 on success, 0 or FALSE on failure.
  1892. */
  1893. function search_api_index_disable($id) {
  1894. $index = search_api_index_load($id, TRUE);
  1895. $ret = $index->update(array('enabled' => 0));
  1896. return $ret ? 1 : $ret;
  1897. }
  1898. /**
  1899. * Schedules a search index for re-indexing.
  1900. *
  1901. * @param $id
  1902. * The ID or machine name of the index to re-index.
  1903. *
  1904. * @return
  1905. * TRUE on success, FALSE on failure.
  1906. */
  1907. function search_api_index_reindex($id) {
  1908. $index = search_api_index_load($id);
  1909. return $index->reindex();
  1910. }
  1911. /**
  1912. * Helper method for marking all items on an index as needing re-indexing.
  1913. *
  1914. * @param SearchApiIndex $index
  1915. * The index whose items should be re-indexed.
  1916. */
  1917. function _search_api_index_reindex(SearchApiIndex $index) {
  1918. $index->datasource()->trackItemChange(FALSE, array($index), TRUE);
  1919. _search_api_empty_cron_queue($index);
  1920. }
  1921. /**
  1922. * Helper method for removing all of an index's jobs from the cron queue.
  1923. *
  1924. * @param SearchApiIndex $index
  1925. * The index whose jobs should be removed.
  1926. * @param $mark_changed
  1927. * If TRUE, mark all items in the queue as "changed" again. Defaults to FALSE.
  1928. */
  1929. function _search_api_empty_cron_queue(SearchApiIndex $index, $mark_changed = FALSE) {
  1930. $index_id = $index->machine_name;
  1931. $queue = DrupalQueue::get('search_api_indexing_queue');
  1932. $queue->createQueue();
  1933. $ids = array();
  1934. $release_items = array();
  1935. while ($item = $queue->claimItem()) {
  1936. if ($item->data['index'] === $index_id) {
  1937. $queue->deleteItem($item);
  1938. if ($mark_changed) {
  1939. $ids = array_merge($ids, $item->data['items']);
  1940. }
  1941. }
  1942. else {
  1943. $release_items[] = $item;
  1944. }
  1945. }
  1946. foreach ($release_items as $item) {
  1947. $queue->releaseItem($item);
  1948. }
  1949. if ($ids) {
  1950. $index->datasource()->trackItemChange($ids, array($index), TRUE);
  1951. }
  1952. }
  1953. /**
  1954. * Clears a search index and schedules all of its items for re-indexing.
  1955. *
  1956. * @param $id
  1957. * The ID or machine name of the index to clear.
  1958. *
  1959. * @return
  1960. * TRUE on success, FALSE on failure.
  1961. */
  1962. function search_api_index_clear($id) {
  1963. $index = search_api_index_load($id);
  1964. return $index->clear();
  1965. }
  1966. /**
  1967. * Deletes a search index.
  1968. *
  1969. * @param $id
  1970. * The ID or machine name of the index to delete.
  1971. *
  1972. * @return
  1973. * TRUE on success, FALSE on failure.
  1974. */
  1975. function search_api_index_delete($id) {
  1976. $index = search_api_index_load($id);
  1977. if (!$index) {
  1978. return FALSE;
  1979. }
  1980. $index->delete();
  1981. return TRUE;
  1982. }
  1983. /**
  1984. * Options list callback for search indexes.
  1985. *
  1986. * @return array
  1987. * An array of search index machine names mapped to their human-readable
  1988. * names.
  1989. */
  1990. function search_api_index_options_list() {
  1991. $ret = array(
  1992. NULL => '- ' . t('All') . ' -',
  1993. );
  1994. foreach (search_api_index_load_multiple(FALSE) as $id => $index) {
  1995. $ret[$id] = $index->name;
  1996. }
  1997. return $ret;
  1998. }
  1999. /**
  2000. * Cron queue worker callback for indexing some items.
  2001. *
  2002. * @param array $task
  2003. * An associative array containing:
  2004. * - index: The ID of the index on which items should be indexed.
  2005. * - items: The items that should be indexed.
  2006. *
  2007. * @return
  2008. * The number of successfully indexed items.
  2009. */
  2010. function _search_api_indexing_queue_process(array $task) {
  2011. $index = search_api_index_load($task['index']);
  2012. try {
  2013. if ($index && $index->enabled && !$index->read_only && $task['items']) {
  2014. $indexed = search_api_index_specific_items($index, $task['items']);
  2015. $num = count($indexed);
  2016. // If some items couldn't be indexed, mark them as dirty again.
  2017. if ($num < count($task['items'])) {
  2018. // Believe it or not but this is actually quite faster than the equivalent
  2019. // $diff = array_diff($task['items'], $indexed);
  2020. $diff = array_keys(array_diff_key(array_flip($task['items']), array_flip($indexed)));
  2021. // Mark the items as dirty again.
  2022. $index->datasource()->trackItemChange($diff, array($index), TRUE);
  2023. }
  2024. if ($num) {
  2025. watchdog('search_api', t('Indexed @num items for index @name', array('@num' => $num, '@name' => $index->name)), NULL, WATCHDOG_INFO);
  2026. }
  2027. return $num;
  2028. }
  2029. }
  2030. catch (SearchApiException $e) {
  2031. watchdog_exception('search_api', $e);
  2032. }
  2033. }
  2034. /**
  2035. * Shutdown function which indexes all queued items, if any.
  2036. */
  2037. function _search_api_index_queued_items() {
  2038. $queue = &search_api_index_specific_items_delayed();
  2039. try {
  2040. if ($queue) {
  2041. $indexes = search_api_index_load_multiple(array_keys($queue));
  2042. foreach ($indexes as $index_id => $index) {
  2043. search_api_index_specific_items($index, $queue[$index_id]);
  2044. }
  2045. }
  2046. // Reset the queue so we don't index the items twice by accident.
  2047. $queue = array();
  2048. }
  2049. catch (SearchApiException $e) {
  2050. watchdog_exception('search_api', $e);
  2051. }
  2052. }
  2053. /**
  2054. * Helper function to be used as a "property info alter" callback.
  2055. *
  2056. * If a wrapped entity is passed to this function, all its available properties
  2057. * and fields, regardless of bundle, are added to the wrapper.
  2058. */
  2059. function _search_api_wrapper_add_all_properties(EntityMetadataWrapper $wrapper, array $property_info) {
  2060. if ($properties = entity_get_all_property_info($wrapper->type())) {
  2061. $property_info['properties'] = $properties;
  2062. }
  2063. return $property_info;
  2064. }
  2065. /**
  2066. * Helper function for converting data to a custom type.
  2067. */
  2068. function _search_api_convert_custom_type($callback, $value, $original_type, $type, $nesting_level) {
  2069. if ($nesting_level == 0) {
  2070. return call_user_func($callback, $value, $original_type, $type);
  2071. }
  2072. if (!is_array($value)) {
  2073. return NULL;
  2074. }
  2075. --$nesting_level;
  2076. $values = array();
  2077. foreach ($value as $v) {
  2078. $v = _search_api_convert_custom_type($callback, $v, $original_type, $type, $nesting_level);
  2079. if (isset($v) && !(is_array($v) && !$v)) {
  2080. $values[] = $v;
  2081. }
  2082. }
  2083. return $values;
  2084. }
  2085. /**
  2086. * Create and set a batch for indexing items.
  2087. *
  2088. * @param SearchApiIndex $index
  2089. * The index for which items should be indexed.
  2090. * @param $batch_size
  2091. * Number of items to index per batch.
  2092. * @param $limit
  2093. * Maximum number of items to index.
  2094. * @param $remaining
  2095. * Remaining items to index.
  2096. * @param $drush
  2097. * Boolean specifying whether this was called from drush or not.
  2098. */
  2099. function _search_api_batch_indexing_create(SearchApiIndex $index, $batch_size, $limit, $remaining, $drush = FALSE) {
  2100. if ($limit !== 0 && $batch_size !== 0) {
  2101. $t = !empty($drush) ? 'dt' : 't';
  2102. if ($limit < 0 || $limit > $remaining) {
  2103. $limit = $remaining;
  2104. }
  2105. if ($batch_size < 0) {
  2106. $batch_size = $remaining;
  2107. }
  2108. $batch = array(
  2109. 'title' => $t('Indexing items'),
  2110. 'operations' => array(
  2111. array('_search_api_batch_indexing_callback', array($index, $batch_size, $limit, $drush)),
  2112. ),
  2113. 'progress_message' => $t('Completed about @percentage% of the indexing operation.'),
  2114. 'finished' => '_search_api_batch_indexing_finished',
  2115. 'file' => drupal_get_path('module', 'search_api') . '/search_api.module',
  2116. );
  2117. batch_set($batch);
  2118. return TRUE;
  2119. }
  2120. return FALSE;
  2121. }
  2122. /**
  2123. * Batch API callback for the indexing functionality.
  2124. *
  2125. * @param SearchApiIndex $index
  2126. * The index for which items should be indexed.
  2127. * @param integer $batch_size
  2128. * Number of items to index per batch.
  2129. * @param integer $limit
  2130. * Maximum number of items to index.
  2131. * @param boolean $drush
  2132. * Boolean specifying whether this was called from drush or not.
  2133. * @param array $context
  2134. * The batch context.
  2135. */
  2136. function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, $limit, $drush = FALSE, array &$context) {
  2137. // Persistent data among batch runs.
  2138. if (!isset($context['sandbox']['limit'])) {
  2139. $context['sandbox']['limit'] = $limit;
  2140. $context['sandbox']['batch_size'] = $batch_size;
  2141. $context['sandbox']['progress'] = 0;
  2142. }
  2143. // Persistent data for results.
  2144. if (!isset($context['results']['indexed'])) {
  2145. $context['results']['indexed'] = 0;
  2146. $context['results']['not indexed'] = 0;
  2147. $context['results']['drush'] = $drush;
  2148. }
  2149. // Number of items to index for this run.
  2150. $to_index = min($context['sandbox']['limit'] - $context['sandbox']['progress'], $context['sandbox']['batch_size']);
  2151. // Index the items.
  2152. $indexed = search_api_index_items($index, $to_index);
  2153. $context['results']['indexed'] += $indexed;
  2154. // Display progress message.
  2155. if ($indexed > 0) {
  2156. $format_plural = $context['results']['drush'] === TRUE ? '_search_api_drush_format_plural' : 'format_plural';
  2157. $context['message'] = $format_plural($context['results']['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.');
  2158. }
  2159. // Some items couldn't be indexed.
  2160. if ($indexed !== $to_index) {
  2161. $context['results']['not indexed'] += $to_index - $indexed;
  2162. }
  2163. $context['sandbox']['progress'] += $to_index;
  2164. // Everything has been indexed.
  2165. if ($indexed === 0 || $context['sandbox']['progress'] >= $context['sandbox']['limit']) {
  2166. $context['finished'] = 1;
  2167. }
  2168. else {
  2169. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['limit'];
  2170. }
  2171. }
  2172. /**
  2173. * Batch API finishing callback for the indexing functionality.
  2174. *
  2175. * @param boolean $success
  2176. * Result of the batch operation.
  2177. * @param array $results
  2178. * Results.
  2179. * @param array $operations
  2180. * Remaining batch operation to process.
  2181. */
  2182. function _search_api_batch_indexing_finished($success, $results, $operations) {
  2183. // Check if called from drush.
  2184. if (!empty($results['drush'])) {
  2185. $drupal_set_message = 'drush_log';
  2186. $format_plural = '_search_api_drush_format_plural';
  2187. $t = 'dt';
  2188. $success_message = 'success';
  2189. }
  2190. else {
  2191. $drupal_set_message = 'drupal_set_message';
  2192. $format_plural = 'format_plural';
  2193. $t = 't';
  2194. $success_message = 'status';
  2195. }
  2196. // Display result messages.
  2197. if ($success) {
  2198. if (!empty($results['indexed'])) {
  2199. $drupal_set_message($format_plural($results['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.'), $success_message);
  2200. if (!empty($results['not indexed'])) {
  2201. $drupal_set_message($format_plural($results['not indexed'], '1 item could not be indexed. Check the logs for details.', '@count items could not be indexed. Check the logs for details.'), 'warning');
  2202. }
  2203. }
  2204. else {
  2205. $drupal_set_message($t("Couldn't index items. Check the logs for details."), 'error');
  2206. }
  2207. }
  2208. else {
  2209. $drupal_set_message($t("An error occurred while trying to index items. Check the logs for details."), 'error');
  2210. }
  2211. }