search_api.module 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. <?php
  2. /**
  3. * @file
  4. * Provides a flexible framework for implementing search services.
  5. */
  6. /**
  7. * Default number of items indexed per cron batch for each enabled index.
  8. */
  9. define('SEARCH_API_DEFAULT_CRON_LIMIT', 50);
  10. /**
  11. * Implements hook_menu().
  12. */
  13. function search_api_menu() {
  14. $pre = 'admin/config/search/search_api';
  15. $items[$pre] = array(
  16. 'title' => 'Search API',
  17. 'description' => 'Create and configure search engines.',
  18. 'page callback' => 'search_api_admin_overview',
  19. 'access arguments' => array('administer search_api'),
  20. 'file' => 'search_api.admin.inc',
  21. );
  22. $items[$pre . '/overview'] = array(
  23. 'title' => 'Overview',
  24. 'type' => MENU_DEFAULT_LOCAL_TASK,
  25. 'weight' => -10,
  26. );
  27. $items[$pre . '/add_server'] = array(
  28. 'title' => 'Add server',
  29. 'description' => 'Create a new search server.',
  30. 'page callback' => 'drupal_get_form',
  31. 'page arguments' => array('search_api_admin_add_server'),
  32. 'access arguments' => array('administer search_api'),
  33. 'file' => 'search_api.admin.inc',
  34. 'weight' => -1,
  35. 'type' => MENU_LOCAL_ACTION,
  36. );
  37. $items[$pre . '/add_index'] = array(
  38. 'title' => 'Add index',
  39. 'description' => 'Create a new search index.',
  40. 'page callback' => 'drupal_get_form',
  41. 'page arguments' => array('search_api_admin_add_index'),
  42. 'access arguments' => array('administer search_api'),
  43. 'file' => 'search_api.admin.inc',
  44. 'type' => MENU_LOCAL_ACTION,
  45. );
  46. $items[$pre . '/server/%search_api_server'] = array(
  47. 'title' => 'View server',
  48. 'title callback' => 'search_api_admin_item_title',
  49. 'title arguments' => array(5),
  50. 'description' => 'View server details.',
  51. 'page callback' => 'search_api_admin_server_view',
  52. 'page arguments' => array(5),
  53. 'access arguments' => array('administer search_api'),
  54. 'file' => 'search_api.admin.inc',
  55. );
  56. $items[$pre . '/server/%search_api_server/view'] = array(
  57. 'title' => 'View',
  58. 'type' => MENU_DEFAULT_LOCAL_TASK,
  59. 'weight' => -10,
  60. );
  61. $items[$pre . '/server/%search_api_server/edit'] = array(
  62. 'title' => 'Edit',
  63. 'description' => 'Edit server details.',
  64. 'page callback' => 'drupal_get_form',
  65. 'page arguments' => array('search_api_admin_server_edit', 5),
  66. 'access arguments' => array('administer search_api'),
  67. 'file' => 'search_api.admin.inc',
  68. 'weight' => -1,
  69. 'type' => MENU_LOCAL_TASK,
  70. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  71. );
  72. $items[$pre . '/server/%search_api_server/disable'] = array(
  73. 'title' => 'Disable',
  74. 'description' => 'Disable index.',
  75. 'page callback' => 'search_api_admin_server_view',
  76. 'page arguments' => array(5, 6),
  77. 'access callback' => 'search_api_access_disable_page',
  78. 'access arguments' => array(5),
  79. 'file' => 'search_api.admin.inc',
  80. 'type' => MENU_LOCAL_TASK,
  81. 'context' => MENU_CONTEXT_INLINE,
  82. 'weight' => 8,
  83. );
  84. $items[$pre . '/server/%search_api_server/delete'] = array(
  85. 'title' => 'Delete',
  86. 'title callback' => 'search_api_title_delete_page',
  87. 'title arguments' => array(5),
  88. 'description' => 'Delete server.',
  89. 'page callback' => 'drupal_get_form',
  90. 'page arguments' => array('search_api_admin_confirm', 'server', 'delete', 5),
  91. 'access callback' => 'search_api_access_delete_page',
  92. 'access arguments' => array(5),
  93. 'file' => 'search_api.admin.inc',
  94. 'type' => MENU_LOCAL_TASK,
  95. 'context' => MENU_CONTEXT_INLINE,
  96. 'weight' => 10,
  97. );
  98. $items[$pre . '/index/%search_api_index'] = array(
  99. 'title' => 'View index',
  100. 'title callback' => 'search_api_admin_item_title',
  101. 'title arguments' => array(5),
  102. 'description' => 'View index details.',
  103. 'page callback' => 'search_api_admin_index_view',
  104. 'page arguments' => array(5),
  105. 'access arguments' => array('administer search_api'),
  106. 'file' => 'search_api.admin.inc',
  107. );
  108. $items[$pre . '/index/%search_api_index/view'] = array(
  109. 'title' => 'View',
  110. 'type' => MENU_DEFAULT_LOCAL_TASK,
  111. 'weight' => -10,
  112. );
  113. $items[$pre . '/index/%search_api_index/edit'] = array(
  114. 'title' => 'Edit',
  115. 'description' => 'Edit index settings.',
  116. 'page callback' => 'drupal_get_form',
  117. 'page arguments' => array('search_api_admin_index_edit', 5),
  118. 'access arguments' => array('administer search_api'),
  119. 'file' => 'search_api.admin.inc',
  120. 'type' => MENU_LOCAL_TASK,
  121. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  122. 'weight' => -6,
  123. );
  124. $items[$pre . '/index/%search_api_index/fields'] = array(
  125. 'title' => 'Fields',
  126. 'description' => 'Select indexed fields.',
  127. 'page callback' => 'drupal_get_form',
  128. 'page arguments' => array('search_api_admin_index_fields', 5),
  129. 'access arguments' => array('administer search_api'),
  130. 'file' => 'search_api.admin.inc',
  131. 'type' => MENU_LOCAL_TASK,
  132. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  133. 'weight' => -4,
  134. );
  135. $items[$pre . '/index/%search_api_index/workflow'] = array(
  136. 'title' => 'Filters',
  137. 'description' => 'Edit indexing workflow.',
  138. 'page callback' => 'drupal_get_form',
  139. 'page arguments' => array('search_api_admin_index_workflow', 5),
  140. 'access arguments' => array('administer search_api'),
  141. 'file' => 'search_api.admin.inc',
  142. 'type' => MENU_LOCAL_TASK,
  143. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  144. 'weight' => -2,
  145. );
  146. $items[$pre . '/index/%search_api_index/disable'] = array(
  147. 'title' => 'Disable',
  148. 'description' => 'Disable index.',
  149. 'page callback' => 'search_api_admin_index_view',
  150. 'page arguments' => array(5, 6),
  151. 'access callback' => 'search_api_access_disable_page',
  152. 'access arguments' => array(5),
  153. 'file' => 'search_api.admin.inc',
  154. 'type' => MENU_LOCAL_TASK,
  155. 'context' => MENU_CONTEXT_INLINE,
  156. 'weight' => 8,
  157. );
  158. $items[$pre . '/index/%search_api_index/delete'] = array(
  159. 'title' => 'Delete',
  160. 'title callback' => 'search_api_title_delete_page',
  161. 'title arguments' => array(5),
  162. 'description' => 'Delete index.',
  163. 'page callback' => 'drupal_get_form',
  164. 'page arguments' => array('search_api_admin_confirm', 'index', 'delete', 5),
  165. 'access callback' => 'search_api_access_delete_page',
  166. 'access arguments' => array(5),
  167. 'file' => 'search_api.admin.inc',
  168. 'type' => MENU_LOCAL_TASK,
  169. 'context' => MENU_CONTEXT_INLINE,
  170. 'weight' => 10,
  171. );
  172. return $items;
  173. }
  174. /**
  175. * Implements hook_help().
  176. */
  177. function search_api_help($path) {
  178. switch ($path) {
  179. case 'admin/help#search_api':
  180. $classes = array();
  181. foreach (search_api_get_service_info() as $id => $info) {
  182. $id = drupal_clean_css_identifier($id);
  183. $name = check_plain($info['name']);
  184. $description = isset($info['description']) ? $info['description'] : '';
  185. $classes[] = "<h2 id=\"$id\">$name</h2>\n$description";
  186. }
  187. $output = '';
  188. if ($classes) {
  189. $output .= '<p>' . t('The following service classes are available for creating a search server.') . "</p>\n";
  190. $output .= implode("\n\n", $classes);
  191. }
  192. return $output;
  193. case 'admin/config/search/search_api':
  194. return '<p>' . t('A search server and search index are used to execute searches. Several indexes can exist per server.<br />You need at least one server and one index to create searches on your site.') . '</p>';
  195. }
  196. }
  197. /**
  198. * Implements hook_hook_info().
  199. */
  200. function search_api_hook_info() {
  201. // We use the same group for all hooks, so save code lines.
  202. $hook_info = array(
  203. 'group' => 'search_api',
  204. );
  205. return array(
  206. 'search_api_service_info' => $hook_info,
  207. 'search_api_service_info_alter' => $hook_info,
  208. 'search_api_item_type_info' => $hook_info,
  209. 'search_api_item_type_info_alter' => $hook_info,
  210. 'search_api_data_type_info' => $hook_info,
  211. 'search_api_data_type_info_alter' => $hook_info,
  212. 'search_api_alter_callback_info' => $hook_info,
  213. 'search_api_processor_info' => $hook_info,
  214. 'search_api_index_items_alter' => $hook_info,
  215. 'search_api_items_indexed' => $hook_info,
  216. 'search_api_query_alter' => $hook_info,
  217. 'search_api_server_load' => $hook_info,
  218. 'search_api_server_insert' => $hook_info,
  219. 'search_api_server_update' => $hook_info,
  220. 'search_api_server_delete' => $hook_info,
  221. 'default_search_api_server' => $hook_info,
  222. 'default_search_api_server_alter' => $hook_info,
  223. 'search_api_index_load' => $hook_info,
  224. 'search_api_index_insert' => $hook_info,
  225. 'search_api_index_update' => $hook_info,
  226. 'search_api_index_reindex' => $hook_info,
  227. 'search_api_index_delete' => $hook_info,
  228. 'default_search_api_index' => $hook_info,
  229. 'default_search_api_index_alter' => $hook_info,
  230. );
  231. }
  232. /**
  233. * Implements hook_theme().
  234. */
  235. function search_api_theme() {
  236. $themes['search_api_dropbutton'] = array(
  237. 'variables' => array(
  238. 'links' => array(),
  239. ),
  240. 'file' => 'search_api.admin.inc',
  241. );
  242. $themes['search_api_server'] = array(
  243. 'variables' => array(
  244. 'id' => NULL,
  245. 'name' => '',
  246. 'machine_name' => '',
  247. 'description' => NULL,
  248. 'enabled' => NULL,
  249. 'class_id' => NULL,
  250. 'class_name' => NULL,
  251. 'class_description' => NULL,
  252. 'indexes' => array(),
  253. 'options' => array(),
  254. 'status' => ENTITY_CUSTOM,
  255. 'extra' => array(),
  256. ),
  257. 'file' => 'search_api.admin.inc',
  258. );
  259. $themes['search_api_index'] = array(
  260. 'variables' => array(
  261. 'id' => NULL,
  262. 'name' => '',
  263. 'machine_name' => '',
  264. 'description' => NULL,
  265. 'item_type' => NULL,
  266. 'datasource_config' => NULL,
  267. 'enabled' => NULL,
  268. 'server' => NULL,
  269. 'options' => array(),
  270. 'fields' => array(),
  271. 'indexed_items' => 0,
  272. 'on_server' => NULL,
  273. 'total_items' => 0,
  274. 'status' => ENTITY_CUSTOM,
  275. 'read_only' => 0,
  276. ),
  277. 'file' => 'search_api.admin.inc',
  278. );
  279. $themes['search_api_admin_item_order'] = array(
  280. 'render element' => 'element',
  281. 'file' => 'search_api.admin.inc',
  282. );
  283. $themes['search_api_admin_fields_table'] = array(
  284. 'render element' => 'element',
  285. 'file' => 'search_api.admin.inc',
  286. );
  287. return $themes;
  288. }
  289. /**
  290. * Implements hook_permission().
  291. */
  292. function search_api_permission() {
  293. return array(
  294. 'administer search_api' => array(
  295. 'title' => t('Administer Search API'),
  296. 'description' => t('Create and configure Search API servers and indexes.'),
  297. ),
  298. );
  299. }
  300. /**
  301. * Implements hook_cron().
  302. *
  303. * This will first execute any pending server tasks. After that, items will
  304. * be indexed on all enabled indexes with a non-zero cron limit. Indexing will
  305. * run for the time set in the search_api_index_worker_callback_runtime variable
  306. * (defaulting to 15 seconds), but will at least index one batch of items on
  307. * each index.
  308. *
  309. * @see search_api_server_tasks_check()
  310. */
  311. function search_api_cron() {
  312. // Execute pending server tasks.
  313. search_api_server_tasks_check();
  314. // Load all enabled, not read-only indexes.
  315. $conditions = array(
  316. 'enabled' => TRUE,
  317. 'read_only' => 0
  318. );
  319. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  320. if (!$indexes) {
  321. return;
  322. }
  323. // Remember servers which threw an exception.
  324. $ignored_servers = array();
  325. // Continue indexing, one batch from each index, until the time is up, but at
  326. // least index one batch per index.
  327. $end = time() + variable_get('search_api_index_worker_callback_runtime', 15);
  328. $first_pass = TRUE;
  329. while (TRUE) {
  330. if (!$indexes) {
  331. break;
  332. }
  333. foreach ($indexes as $id => $index) {
  334. if (!$first_pass && time() >= $end) {
  335. break 2;
  336. }
  337. if (!empty($ignored_servers[$index->server])) {
  338. continue;
  339. }
  340. $limit = isset($index->options['cron_limit'])
  341. ? $index->options['cron_limit']
  342. : SEARCH_API_DEFAULT_CRON_LIMIT;
  343. $num = 0;
  344. if ($limit) {
  345. try {
  346. $num = search_api_index_items($index, $limit);
  347. if ($num) {
  348. $variables = array(
  349. '@num' => $num,
  350. '%name' => $index->name
  351. );
  352. watchdog('search_api', 'Indexed @num items for index %name.', $variables, WATCHDOG_INFO);
  353. }
  354. }
  355. catch (SearchApiException $e) {
  356. // Exceptions will probably be caused by the server in most cases.
  357. // Therefore, don't index for any index on this server.
  358. $ignored_servers[$index->server] = TRUE;
  359. $vars['%index'] = $index->name;
  360. watchdog_exception('search_api', $e, '%type while trying to index items on %index: !message in %function (line %line of %file).', $vars);
  361. }
  362. }
  363. if (!$num) {
  364. // Couldn't index any items => stop indexing for this index in this
  365. // cron run.
  366. unset($indexes[$id]);
  367. }
  368. }
  369. $first_pass = FALSE;
  370. }
  371. }
  372. /**
  373. * Implements hook_entity_info().
  374. */
  375. function search_api_entity_info() {
  376. $info['search_api_server'] = array(
  377. 'label' => t('Search server'),
  378. 'controller class' => 'EntityAPIControllerExportable',
  379. 'metadata controller class' => FALSE,
  380. 'entity class' => 'SearchApiServer',
  381. 'base table' => 'search_api_server',
  382. 'uri callback' => 'search_api_server_url',
  383. 'access callback' => 'search_api_entity_access',
  384. 'module' => 'search_api',
  385. 'exportable' => TRUE,
  386. 'entity keys' => array(
  387. 'id' => 'id',
  388. 'label' => 'name',
  389. 'name' => 'machine_name',
  390. ),
  391. );
  392. $info['search_api_index'] = array(
  393. 'label' => t('Search index'),
  394. 'controller class' => 'EntityAPIControllerExportable',
  395. 'metadata controller class' => FALSE,
  396. 'entity class' => 'SearchApiIndex',
  397. 'base table' => 'search_api_index',
  398. 'uri callback' => 'search_api_index_url',
  399. 'access callback' => 'search_api_entity_access',
  400. 'module' => 'search_api',
  401. 'exportable' => TRUE,
  402. 'entity keys' => array(
  403. 'id' => 'id',
  404. 'label' => 'name',
  405. 'name' => 'machine_name',
  406. ),
  407. );
  408. return $info;
  409. }
  410. /**
  411. * Implements hook_entity_property_info().
  412. */
  413. function search_api_entity_property_info() {
  414. $info['search_api_server']['properties'] = array(
  415. 'id' => array(
  416. 'label' => t('ID'),
  417. 'type' => 'integer',
  418. 'description' => t('The primary identifier for a server.'),
  419. 'schema field' => 'id',
  420. 'validation callback' => 'entity_metadata_validate_integer_positive',
  421. ),
  422. 'name' => array(
  423. 'label' => t('Name'),
  424. 'type' => 'text',
  425. 'description' => t('The displayed name for a server.'),
  426. 'schema field' => 'name',
  427. 'required' => TRUE,
  428. ),
  429. 'machine_name' => array(
  430. 'label' => t('Machine name'),
  431. 'type' => 'token',
  432. 'description' => t('The internally used machine name for a server.'),
  433. 'schema field' => 'machine_name',
  434. 'required' => TRUE,
  435. ),
  436. 'description' => array(
  437. 'label' => t('Description'),
  438. 'type' => 'text',
  439. 'description' => t('The displayed description for a server.'),
  440. 'schema field' => 'description',
  441. 'sanitize' => 'filter_xss',
  442. ),
  443. 'class' => array(
  444. 'label' => t('Service class'),
  445. 'type' => 'text',
  446. 'description' => t('The ID of the service class to use for this server.'),
  447. 'schema field' => 'class',
  448. 'required' => TRUE,
  449. ),
  450. 'enabled' => array(
  451. 'label' => t('Enabled'),
  452. 'type' => 'boolean',
  453. 'description' => t('A flag indicating whether the server is enabled.'),
  454. 'schema field' => 'enabled',
  455. ),
  456. 'status' => array(
  457. 'label' => t('Status'),
  458. 'type' => 'integer',
  459. 'description' => t('Search API server status property'),
  460. 'schema field' => 'status',
  461. 'options list' => 'search_api_status_options_list',
  462. ),
  463. 'module' => array(
  464. 'label' => t('Module'),
  465. 'type' => 'text',
  466. 'description' => t('The name of the module from which this server originates.'),
  467. 'schema field' => 'module',
  468. ),
  469. );
  470. $info['search_api_index']['properties'] = array(
  471. 'id' => array(
  472. 'label' => t('ID'),
  473. 'type' => 'integer',
  474. 'description' => t('An integer identifying the index.'),
  475. 'schema field' => 'id',
  476. 'validation callback' => 'entity_metadata_validate_integer_positive',
  477. ),
  478. 'name' => array(
  479. 'label' => t('Name'),
  480. 'type' => 'text',
  481. 'description' => t('A name to be displayed for the index.'),
  482. 'schema field' => 'name',
  483. 'required' => TRUE,
  484. ),
  485. 'machine_name' => array(
  486. 'label' => t('Machine name'),
  487. 'type' => 'token',
  488. 'description' => t('The internally used machine name for an index.'),
  489. 'schema field' => 'machine_name',
  490. 'required' => TRUE,
  491. ),
  492. 'description' => array(
  493. 'label' => t('Description'),
  494. 'type' => 'text',
  495. 'description' => t("A string describing the index' use to users."),
  496. 'schema field' => 'description',
  497. 'sanitize' => 'filter_xss',
  498. ),
  499. 'server' => array(
  500. 'label' => t('Server ID'),
  501. 'type' => 'token',
  502. 'description' => t('The machine name of the search_api_server with which data should be indexed.'),
  503. 'schema field' => 'server',
  504. ),
  505. 'server_entity' => array(
  506. 'label' => t('Server'),
  507. 'type' => 'search_api_server',
  508. 'description' => t('The search_api_server with which data should be indexed.'),
  509. 'getter callback' => 'search_api_index_get_server',
  510. ),
  511. 'item_type' => array(
  512. 'label' => t('Item type'),
  513. 'type' => 'token',
  514. 'description' => t('The type of items stored in this index.'),
  515. 'schema field' => 'item_type',
  516. 'required' => TRUE,
  517. ),
  518. 'enabled' => array(
  519. 'label' => t('Enabled'),
  520. 'type' => 'boolean',
  521. 'description' => t('A flag indicating whether the index is enabled.'),
  522. 'schema field' => 'enabled',
  523. ),
  524. 'read_only' => array(
  525. 'label' => t('Read only'),
  526. 'type' => 'boolean',
  527. 'description' => t('A flag indicating whether the index is read-only.'),
  528. 'schema field' => 'read_only',
  529. ),
  530. 'status' => array(
  531. 'label' => t('Status'),
  532. 'type' => 'integer',
  533. 'description' => t('Search API index status property'),
  534. 'schema field' => 'status',
  535. 'options list' => 'search_api_status_options_list',
  536. ),
  537. 'module' => array(
  538. 'label' => t('Module'),
  539. 'type' => 'text',
  540. 'description' => t('The name of the module from which this index originates.'),
  541. 'schema field' => 'module',
  542. ),
  543. );
  544. return $info;
  545. }
  546. /**
  547. * Implements hook_search_api_server_insert().
  548. *
  549. * Calls the postCreate() method for the server.
  550. */
  551. function search_api_search_api_server_insert(SearchApiServer $server) {
  552. // Check whether this is actually part of a revert.
  553. $reverts = &drupal_static('search_api_search_api_server_delete', array());
  554. if (isset($reverts[$server->machine_name])) {
  555. $server->original = $reverts[$server->machine_name];
  556. unset($reverts[$server->machine_name]);
  557. search_api_search_api_server_update($server);
  558. unset($server->original);
  559. return;
  560. }
  561. $server->postCreate();
  562. }
  563. /**
  564. * Implements hook_search_api_server_update().
  565. *
  566. * Calls the server's postUpdate() method and marks all of this server's indexes
  567. * for reindexing, if necessary.
  568. */
  569. function search_api_search_api_server_update(SearchApiServer $server) {
  570. if ($server->postUpdate()) {
  571. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  572. $index->reindex();
  573. }
  574. }
  575. if (!empty($server->original) && $server->enabled != $server->original->enabled) {
  576. if ($server->enabled) {
  577. search_api_server_tasks_check($server);
  578. }
  579. else {
  580. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  581. $index->update(array('enabled' => 0, 'server' => NULL));
  582. }
  583. }
  584. }
  585. }
  586. /**
  587. * Implements hook_search_api_server_delete().
  588. *
  589. * Calls the preDelete() method for the server.
  590. */
  591. function search_api_search_api_server_delete(SearchApiServer $server) {
  592. // Only react on real delete, not revert.
  593. if ($server->hasStatus(ENTITY_IN_CODE)) {
  594. $reverts = &drupal_static(__FUNCTION__, array());
  595. $reverts[$server->machine_name] = $server;
  596. return;
  597. }
  598. $server->preDelete();
  599. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  600. $index->update(array('server' => NULL, 'enabled' => FALSE));
  601. }
  602. search_api_server_tasks_delete(NULL, $server);
  603. }
  604. /**
  605. * Implements hook_search_api_index_insert().
  606. *
  607. * Adds the index to its server (if any) and starts tracking indexed items (if
  608. * the index is enabled).
  609. */
  610. function search_api_search_api_index_insert(SearchApiIndex $index) {
  611. // Check whether this is actually part of a revert.
  612. $reverts = &drupal_static('search_api_search_api_index_delete', array());
  613. if (isset($reverts[$index->machine_name])) {
  614. $index->original = $reverts[$index->machine_name];
  615. unset($reverts[$index->machine_name]);
  616. search_api_search_api_index_update($index);
  617. unset($index->original);
  618. return;
  619. }
  620. $index->postCreate();
  621. }
  622. /**
  623. * Implements hook_search_api_index_update().
  624. */
  625. function search_api_search_api_index_update(SearchApiIndex $index) {
  626. // Call the datasource update function with the tables this module provides.
  627. search_api_index_update_datasource($index, 'search_api_item');
  628. search_api_index_update_datasource($index, 'search_api_item_string_id');
  629. // If the server was changed, we have to call the appropriate service class
  630. // hook methods.
  631. if ($index->server != $index->original->server) {
  632. // Server changed - inform old and new ones.
  633. if ($index->original->server) {
  634. $old_server = search_api_server_load($index->original->server);
  635. // The server might have changed because the old one was deleted:
  636. if ($old_server) {
  637. $old_server->removeIndex($index);
  638. }
  639. }
  640. if ($index->server) {
  641. try {
  642. $new_server = $index->server(TRUE);
  643. // If the server is enabled, we call addIndex(); otherwise, we save the task.
  644. $new_server->addIndex($index);
  645. }
  646. catch (SearchApiException $e) {
  647. watchdog_exception('search_api', $e);
  648. // If the new server doesn't exist, we remove the index from all
  649. // servers. Note that saving an entity in its own update hook is usually
  650. // a recipe for disaster, but since we are only doing this if a server
  651. // is set and remove the server here before saving, it should be safe
  652. // enough.
  653. $index->server = NULL;
  654. $index->save();
  655. }
  656. }
  657. // We also have to re-index all content.
  658. _search_api_index_reindex($index);
  659. }
  660. // If the fields were changed, call the appropriate service class hook method
  661. // and re-index the content, if necessary.
  662. $old_fields = $index->original->options + array('fields' => array());
  663. $old_fields = $old_fields['fields'];
  664. $new_fields = $index->options + array('fields' => array());
  665. $new_fields = $new_fields['fields'];
  666. if ($old_fields != $new_fields) {
  667. if ($index->server) {
  668. $index->server()->fieldsUpdated($index);
  669. }
  670. }
  671. // If the index's enabled or read-only status is being changed, queue or
  672. // dequeue items for indexing.
  673. if (!$index->read_only && $index->enabled != $index->original->enabled) {
  674. if ($index->enabled) {
  675. $index->queueItems();
  676. }
  677. else {
  678. $index->dequeueItems();
  679. }
  680. }
  681. elseif ($index->read_only != $index->original->read_only) {
  682. if ($index->read_only) {
  683. $index->dequeueItems();
  684. }
  685. else {
  686. $index->queueItems();
  687. }
  688. }
  689. }
  690. /**
  691. * Implements hook_search_api_index_delete().
  692. *
  693. * Removes all data for indexes not available any more.
  694. */
  695. function search_api_search_api_index_delete(SearchApiIndex $index) {
  696. // Only react on real delete, not revert.
  697. if ($index->hasStatus(ENTITY_IN_CODE)) {
  698. $reverts = &drupal_static(__FUNCTION__, array());
  699. $reverts[$index->machine_name] = $index;
  700. return;
  701. }
  702. cache_clear_all($index->getCacheId(''), 'cache', TRUE);
  703. $index->postDelete();
  704. }
  705. /**
  706. * Implements hook_features_export_alter().
  707. *
  708. * Adds dependency information for exported servers.
  709. */
  710. function search_api_features_export_alter(&$export) {
  711. if (isset($export['features']['search_api_server'])) {
  712. // Get a list of the modules that provide storage engines.
  713. $hook = 'search_api_service_info';
  714. $classes = array();
  715. foreach (module_implements('search_api_service_info') as $module) {
  716. $function = $module . '_' . $hook;
  717. $engines = $function();
  718. foreach ($engines as $service => $specs) {
  719. $classes[$service] = $module;
  720. }
  721. }
  722. // Check all of the exported server specifications.
  723. foreach ($export['features']['search_api_server'] as $server_name) {
  724. // Load the server's object.
  725. $server = search_api_server_load($server_name);
  726. $module = $classes[$server->class];
  727. // Ensure that the module responsible for the server object is listed as
  728. // a dependency.
  729. if (!isset($export['dependencies'][$module])) {
  730. $export['dependencies'][$module] = $module;
  731. }
  732. }
  733. // Ensure the dependencies list is still sorted alphabetically.
  734. ksort($export['dependencies']);
  735. }
  736. }
  737. /**
  738. * Implements hook_system_info_alter().
  739. *
  740. * Checks if the module provides any search item types or service classes. If it
  741. * does, and there are search indexes using those item types, respectively
  742. * servers using those service classes, the module is set to "required".
  743. *
  744. * Heavily borrowed from field_system_info_alter().
  745. *
  746. * @see hook_search_api_item_type_info()
  747. */
  748. function search_api_system_info_alter(&$info, $file, $type) {
  749. if ($type != 'module' || $file->name == 'search_api') {
  750. return;
  751. }
  752. // Check for defined item types.
  753. if (module_hook($file->name, 'search_api_item_type_info')) {
  754. $types = array();
  755. foreach (search_api_get_item_type_info() as $type => $type_info) {
  756. if ($type_info['module'] == $file->name) {
  757. $types[] = $type;
  758. }
  759. }
  760. if ($types) {
  761. $sql = 'SELECT machine_name, name FROM {search_api_index} WHERE item_type IN (:types)';
  762. $indexes = db_query($sql, array(':types' => $types))->fetchAllKeyed();
  763. if ($indexes) {
  764. $info['required'] = TRUE;
  765. $links = array();
  766. foreach ($indexes as $id => $name) {
  767. $url = url("admin/config/search/search_api/index/$id");
  768. $links[] = '<a href="' . check_plain($url) . '">' . check_plain($name) . '</a>';
  769. }
  770. $args = array('!indexes' => implode(', ', $links));
  771. $info['explanation'] = format_plural(count($indexes), 'Item type in use by the following index: !indexes.', 'Item type(s) in use by the following indexes: !indexes.', $args);
  772. }
  773. }
  774. }
  775. // Check for defined service classes.
  776. if (module_hook($file->name, 'search_api_service_info')) {
  777. $classes = array();
  778. foreach (search_api_get_service_info() as $class => $class_info) {
  779. if ($class_info['module'] == $file->name) {
  780. $classes[] = $class;
  781. }
  782. }
  783. if ($classes) {
  784. $sql = 'SELECT machine_name, name FROM {search_api_server} WHERE class IN (:classes)';
  785. $servers = db_query($sql, array(':classes' => $classes))->fetchAllKeyed();
  786. if ($servers) {
  787. $info['required'] = TRUE;
  788. $links = array();
  789. foreach ($servers as $id => $name) {
  790. $url = url("admin/config/search/search_api/server/$id");
  791. $links[] = '<a href="' . check_plain($url) . '">' . check_plain($name) . '</a>';
  792. }
  793. $args = array('!servers' => implode(', ', $links));
  794. $explanation = format_plural(count($servers), 'Service class in use by the following server: !servers.', 'Service class(es) in use by the following servers: !servers.', $args);
  795. $info['explanation'] = (!empty($info['explanation']) ? $info['explanation'] . ' ' : '') . $explanation;
  796. }
  797. }
  798. }
  799. }
  800. /**
  801. * Implements hook_entity_insert().
  802. *
  803. * This is implemented on behalf of the SearchApiEntityDataSourceController
  804. * datasource controller and calls search_api_track_item_insert() for the
  805. * inserted items.
  806. *
  807. * @see search_api_search_api_item_type_info()
  808. */
  809. function search_api_entity_insert($entity, $type) {
  810. // When inserting a new search index, the new index was already inserted into
  811. // the tracking table. This would lead to a duplicate-key issue, if we would
  812. // continue.
  813. // We also only react on entity operations for types with property
  814. // information, as we don't provide search integration for the others.
  815. if ($type == 'search_api_index' || !entity_get_property_info($type)) {
  816. return;
  817. }
  818. list($id) = entity_extract_ids($type, $entity);
  819. if (isset($id)) {
  820. search_api_track_item_insert($type, array($id));
  821. $combined_id = $type . '/' . $id;
  822. search_api_track_item_insert('multiple', array($combined_id));
  823. }
  824. }
  825. /**
  826. * Implements hook_entity_update().
  827. *
  828. * This is implemented on behalf of the SearchApiEntityDataSourceController
  829. * datasource controller and calls search_api_track_item_change() for the
  830. * updated items.
  831. *
  832. * It also checks whether the entity's bundle changed and acts accordingly.
  833. *
  834. * @see search_api_search_api_item_type_info()
  835. */
  836. function search_api_entity_update($entity, $type) {
  837. // We only react on entity operations for types with property information, as
  838. // we don't provide search integration for the others.
  839. if (!entity_get_property_info($type)) {
  840. return;
  841. }
  842. list($id, , $new_bundle) = entity_extract_ids($type, $entity);
  843. // Check if the entity's bundle changed.
  844. if (!empty($entity->original)) {
  845. list(, , $old_bundle) = entity_extract_ids($type, $entity->original);
  846. if ($new_bundle != $old_bundle) {
  847. _search_api_entity_datasource_bundle_change($type, $id, $old_bundle, $new_bundle);
  848. }
  849. }
  850. if (isset($id)) {
  851. search_api_track_item_change($type, array($id));
  852. $combined_id = $type . '/' . $id;
  853. search_api_track_item_change('multiple', array($combined_id));
  854. }
  855. }
  856. /**
  857. * Implements hook_entity_delete().
  858. *
  859. * This is implemented on behalf of the SearchApiEntityDataSourceController
  860. * datasource controller and calls search_api_track_item_delete() for the
  861. * deleted items.
  862. *
  863. * @see search_api_search_api_item_type_info()
  864. */
  865. function search_api_entity_delete($entity, $type) {
  866. // We only react on entity operations for types with property information, as
  867. // we don't provide search integration for the others.
  868. if (!entity_get_property_info($type)) {
  869. return;
  870. }
  871. list($id) = entity_extract_ids($type, $entity);
  872. if (isset($id)) {
  873. search_api_track_item_delete($type, array($id));
  874. $combined_id = $type . '/' . $id;
  875. search_api_track_item_delete('multiple', array($combined_id));
  876. }
  877. }
  878. /**
  879. * Implements hook_field_attach_rename_bundle().
  880. *
  881. * This is implemented on behalf of the SearchApiEntityDataSourceController
  882. * datasource controller, to update any bundle settings that contain the changed
  883. * bundle.
  884. */
  885. function search_api_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  886. foreach (search_api_index_load_multiple(FALSE, array('item_type' => $entity_type)) as $index) {
  887. $bundles = &$index->options['datasource']['bundles'];
  888. if (isset($bundles) && ($pos = array_search($bundle_old, $bundles)) !== FALSE) {
  889. $bundles[$pos] = $bundle_new;
  890. $index->save();
  891. // Clear all caches that could contain the bundle information.
  892. $index->resetCaches();
  893. drupal_static_reset('search_api_get_datasource_controller');
  894. }
  895. }
  896. }
  897. /**
  898. * Implements hook_field_update_field().
  899. *
  900. * Recalculates fields settings if the cardinality of the field has changed from
  901. * or to 1.
  902. */
  903. function search_api_field_update_field($field, $prior_field) {
  904. $before = $prior_field['cardinality'];
  905. $after = $field['cardinality'];
  906. if ($before != $after && ($before == 1 || $after == 1)) {
  907. // Unfortunately, we cannot call this right away since the field information
  908. // is only stored after the hook is called.
  909. drupal_register_shutdown_function('search_api_index_recalculate_fields');
  910. }
  911. }
  912. /**
  913. * Implements hook_flush_caches().
  914. *
  915. * Recalculates fields settings in case the schema (in most cases: the
  916. * multiplicity) of a property has changed.
  917. */
  918. function search_api_flush_caches() {
  919. search_api_index_recalculate_fields();
  920. }
  921. /**
  922. * Implements hook_search_api_item_type_info().
  923. *
  924. * Adds item types for all entity types with property information.
  925. */
  926. function search_api_search_api_item_type_info() {
  927. $types = array();
  928. foreach (search_api_entity_type_options_list() as $type => $label) {
  929. $types[$type] = array(
  930. 'name' => $label,
  931. 'datasource controller' => 'SearchApiEntityDataSourceController',
  932. 'entity_type' => $type,
  933. );
  934. }
  935. $types['multiple'] = array(
  936. 'name' => t('Multiple types'),
  937. 'datasource controller' => 'SearchApiCombinedEntityDataSourceController',
  938. );
  939. return $types;
  940. }
  941. /**
  942. * Implements hook_modules_enabled().
  943. */
  944. function search_api_modules_enabled() {
  945. // New modules might offer additional item types or service classes,
  946. // invalidating the cached information.
  947. drupal_static_reset('search_api_get_item_type_info');
  948. drupal_static_reset('search_api_get_service_info');
  949. }
  950. /**
  951. * Implements hook_modules_disabled().
  952. */
  953. function search_api_modules_disabled() {
  954. // The disabled modules might have offered item types or service classes,
  955. // invalidating the cached information.
  956. drupal_static_reset('search_api_get_item_type_info');
  957. drupal_static_reset('search_api_get_service_info');
  958. }
  959. /**
  960. * Implements hook_search_api_alter_callback_info().
  961. */
  962. function search_api_search_api_alter_callback_info() {
  963. $callbacks['search_api_alter_bundle_filter'] = array(
  964. 'name' => t('Bundle filter'),
  965. 'description' => t('Exclude items from indexing based on their bundle (content type, vocabulary, …).'),
  966. 'class' => 'SearchApiAlterBundleFilter',
  967. // Filters should be executed first.
  968. 'weight' => -10,
  969. );
  970. $callbacks['search_api_alter_role_filter'] = array(
  971. 'name' => t('Role filter'),
  972. 'description' => t('Exclude users from indexing based on their role.'),
  973. 'class' => 'SearchApiAlterRoleFilter',
  974. // Filters should be executed first.
  975. 'weight' => -10,
  976. );
  977. $callbacks['search_api_alter_add_url'] = array(
  978. 'name' => t('URL field'),
  979. 'description' => t("Adds the item's URL to the indexed data."),
  980. 'class' => 'SearchApiAlterAddUrl',
  981. );
  982. $callbacks['search_api_alter_add_aggregation'] = array(
  983. 'name' => t('Aggregated fields'),
  984. 'description' => t('Gives you the ability to define additional fields, containing data from one or more other fields.'),
  985. 'class' => 'SearchApiAlterAddAggregation',
  986. );
  987. $callbacks['search_api_alter_add_viewed_entity'] = array(
  988. 'name' => t('Complete entity view'),
  989. 'description' => t('Adds an additional field containing the whole HTML content of the entity when viewed.'),
  990. 'class' => 'SearchApiAlterAddViewedEntity',
  991. );
  992. $callbacks['search_api_alter_add_hierarchy'] = array(
  993. 'name' => t('Index hierarchy'),
  994. 'description' => t('Allows to index hierarchical fields along with all their ancestors.'),
  995. 'class' => 'SearchApiAlterAddHierarchy',
  996. );
  997. $callbacks['search_api_alter_language_control'] = array(
  998. 'name' => t('Language control'),
  999. 'description' => t('Lets you determine the language of items in the index.'),
  1000. 'class' => 'SearchApiAlterLanguageControl',
  1001. );
  1002. $callbacks['search_api_alter_node_access'] = array(
  1003. 'name' => t('Node access'),
  1004. 'description' => t('Add node access information to the index. <strong>Caution:</strong> This only affects the indexed nodes themselves, not any node reference fields that are indexed with them, or displayed in search results.'),
  1005. 'class' => 'SearchApiAlterNodeAccess',
  1006. );
  1007. $callbacks['search_api_alter_comment_access'] = array(
  1008. 'name' => t('Access check'),
  1009. 'description' => t('Add node access information to the index. <strong>Caution:</strong> This only affects the indexed nodes themselves, not any node reference fields that are indexed with them, or displayed in search results.'),
  1010. 'class' => 'SearchApiAlterCommentAccess',
  1011. );
  1012. $callbacks['search_api_alter_node_status'] = array(
  1013. 'name' => t('Exclude unpublished nodes'),
  1014. 'description' => t('Exclude unpublished nodes from the index. <strong>Caution:</strong> This only affects the indexed nodes themselves. If an enabled node has references to disabled nodes, those will still be indexed (or displayed) normally.'),
  1015. 'class' => 'SearchApiAlterNodeStatus',
  1016. );
  1017. $callbacks['search_api_alter_user_status'] = array(
  1018. 'name' => t('Exclude blocked users'),
  1019. 'description' => t('Exclude blocked users from the index. <strong>Caution:</strong> This only affects the indexed users themselves. If an active user account includes a reference to a disabled user, that reference will still be indexed (or displayed) normally.'),
  1020. 'class' => 'SearchApiAlterUserStatus',
  1021. );
  1022. return $callbacks;
  1023. }
  1024. /**
  1025. * Implements hook_search_api_processor_info().
  1026. */
  1027. function search_api_search_api_processor_info() {
  1028. $processors['search_api_case_ignore'] = array(
  1029. 'name' => t('Ignore case'),
  1030. 'description' => t('This processor will make searches case-insensitive for fulltext or string fields.'),
  1031. 'class' => 'SearchApiIgnoreCase',
  1032. );
  1033. $processors['search_api_html_filter'] = array(
  1034. 'name' => t('HTML filter'),
  1035. 'description' => t('Strips HTML tags from fulltext fields and decodes HTML entities. ' .
  1036. 'Use this processor when indexing HTML data, e.g., node bodies for certain text formats.<br />' .
  1037. 'The processor also allows to boost (or ignore) the contents of specific elements.'),
  1038. 'class' => 'SearchApiHtmlFilter',
  1039. 'weight' => 10,
  1040. );
  1041. if (module_exists('transliteration')) {
  1042. $processors['search_api_transliteration'] = array(
  1043. 'name' => t('Transliteration'),
  1044. 'description' => t('This processor will make searches insensitive to accents and other non-ASCII characters.'),
  1045. 'class' => 'SearchApiTransliteration',
  1046. 'weight' => 15,
  1047. );
  1048. }
  1049. $processors['search_api_tokenizer'] = array(
  1050. 'name' => t('Tokenizer'),
  1051. 'description' => t('Tokenizes fulltext data by stripping whitespace. ' .
  1052. 'This processor allows you to specify which characters make up words and which characters should be ignored, using regular expression syntax. ' .
  1053. 'Otherwise it is up to the search server implementation to decide how to split indexed fulltext data.'),
  1054. 'class' => 'SearchApiTokenizer',
  1055. 'weight' => 20,
  1056. );
  1057. $processors['search_api_stopwords'] = array(
  1058. 'name' => t('Stopwords'),
  1059. 'description' => t('This processor prevents certain words from being indexed and removes them from search terms. ' .
  1060. 'For best results, it should only be executed after tokenizing.'),
  1061. 'class' => 'SearchApiStopWords',
  1062. 'weight' => 30,
  1063. );
  1064. $processors['search_api_highlighting'] = array(
  1065. 'name' => t('Highlighting'),
  1066. 'description' => t('Adds highlighting for search results.'),
  1067. 'class' => 'SearchApiHighlight',
  1068. 'weight' => 35,
  1069. );
  1070. return $processors;
  1071. }
  1072. /**
  1073. * Inserts new unindexed items for all indexes on the specified type.
  1074. *
  1075. * @param string $type
  1076. * The item type of the new items.
  1077. * @param array $item_ids
  1078. * The IDs of the new items.
  1079. */
  1080. function search_api_track_item_insert($type, array $item_ids) {
  1081. $conditions = array(
  1082. 'enabled' => 1,
  1083. 'item_type' => $type,
  1084. 'read_only' => 0,
  1085. );
  1086. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1087. if (!$indexes) {
  1088. return;
  1089. }
  1090. try {
  1091. $returned_indexes = search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
  1092. if (isset($returned_indexes)) {
  1093. $indexes = $returned_indexes;
  1094. }
  1095. }
  1096. catch (SearchApiException $e) {
  1097. $vars['%item_type'] = $type;
  1098. watchdog_exception('search_api', $e, '%type while inserting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1099. return;
  1100. }
  1101. foreach ($indexes as $index) {
  1102. if (!empty($index->options['index_directly'])) {
  1103. search_api_index_specific_items_delayed($index, $item_ids);
  1104. }
  1105. }
  1106. }
  1107. /**
  1108. * Mark the items with the specified IDs as "dirty", i.e., as needing to be reindexed.
  1109. *
  1110. * For indexes for which items should be indexed immediately, the items are
  1111. * indexed directly, instead.
  1112. *
  1113. * @param $type
  1114. * The type of items, specific to the data source.
  1115. * @param array $item_ids
  1116. * The IDs of the items to be marked dirty.
  1117. */
  1118. function search_api_track_item_change($type, array $item_ids) {
  1119. $conditions = array(
  1120. 'enabled' => 1,
  1121. 'item_type' => $type,
  1122. 'read_only' => 0,
  1123. );
  1124. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1125. if (!$indexes) {
  1126. return;
  1127. }
  1128. try {
  1129. $returned_indexes = search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
  1130. if (isset($returned_indexes)) {
  1131. $indexes = $returned_indexes;
  1132. }
  1133. foreach ($indexes as $index) {
  1134. if (!empty($index->options['index_directly'])) {
  1135. // For indexes with the index_directly option set, queue the items to be
  1136. // indexed at the end of the request.
  1137. try {
  1138. search_api_index_specific_items_delayed($index, $item_ids);
  1139. }
  1140. catch (SearchApiException $e) {
  1141. watchdog_exception('search_api', $e);
  1142. }
  1143. }
  1144. }
  1145. }
  1146. catch (SearchApiException $e) {
  1147. $vars['%item_type'] = $type;
  1148. watchdog_exception('search_api', $e, '%type while updating items of type %item_type: !message in %function (line %line of %file).', $vars);
  1149. return;
  1150. }
  1151. }
  1152. /**
  1153. * Marks items as queued for indexing for the specified index.
  1154. *
  1155. * @param SearchApiIndex $index
  1156. * The index on which items were queued.
  1157. * @param array $item_ids
  1158. * The ids of the queued items.
  1159. *
  1160. * @deprecated
  1161. * As of Search API 1.10, the cron queue is not used for indexing anymore,
  1162. * therefore this function has become useless. It will, along with
  1163. * SearchApiDataSourceControllerInterface::trackItemQueued(), be removed in
  1164. * the Drupal 8 version of this module.
  1165. */
  1166. function search_api_track_item_queued(SearchApiIndex $index, array $item_ids) {
  1167. try {
  1168. $index->datasource()->trackItemQueued($item_ids, $index);
  1169. }
  1170. catch (SearchApiException $e) {
  1171. watchdog_exception('search_api', $e);
  1172. }
  1173. }
  1174. /**
  1175. * Marks items as successfully indexed for the specified index.
  1176. *
  1177. * @param SearchApiIndex $index
  1178. * The index on which items were indexed.
  1179. * @param array $item_ids
  1180. * The ids of the indexed items.
  1181. */
  1182. function search_api_track_item_indexed(SearchApiIndex $index, array $item_ids) {
  1183. $index->datasource()->trackItemIndexed($item_ids, $index);
  1184. module_invoke_all('search_api_items_indexed', $index, $item_ids);
  1185. }
  1186. /**
  1187. * Removes items from all indexes.
  1188. *
  1189. * @param $type
  1190. * The type of the items.
  1191. * @param array $item_ids
  1192. * The IDs of the deleted items.
  1193. */
  1194. function search_api_track_item_delete($type, array $item_ids) {
  1195. // First, delete the item from the tracking table.
  1196. $conditions = array(
  1197. 'enabled' => 1,
  1198. 'item_type' => $type,
  1199. 'read_only' => 0,
  1200. );
  1201. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1202. if ($indexes) {
  1203. try {
  1204. $changed_indexes = search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
  1205. if (isset($changed_indexes)) {
  1206. $indexes = $changed_indexes;
  1207. }
  1208. }
  1209. catch (SearchApiException $e) {
  1210. $vars['%item_type'] = $type;
  1211. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1212. }
  1213. }
  1214. // Then, delete it from all servers. Servers of disabled indexes have to be
  1215. // considered, too!
  1216. $conditions['enabled'] = 0;
  1217. $indexes = array_merge($indexes, search_api_index_load_multiple(FALSE, $conditions));
  1218. foreach ($indexes as $index) {
  1219. try {
  1220. if ($server = $index->server()) {
  1221. $server->deleteItems($item_ids, $index);
  1222. }
  1223. }
  1224. catch (Exception $e) {
  1225. $vars['%item_type'] = $type;
  1226. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1227. }
  1228. }
  1229. }
  1230. /**
  1231. * Checks for pending tasks on one or all enabled search servers.
  1232. *
  1233. * @param SearchApiServer|null $server
  1234. * (optional) The server whose tasks should be checked. If not given, the
  1235. * tasks for all enabled servers are checked.
  1236. *
  1237. * @return bool
  1238. * TRUE if all tasks (for the specific server, if $server was given) were
  1239. * executed successfully, or if there were no tasks. FALSE if there are still
  1240. * pending tasks.
  1241. */
  1242. function search_api_server_tasks_check(SearchApiServer $server = NULL) {
  1243. $select = db_select('search_api_task', 't')
  1244. ->fields('t')
  1245. // Only retrieve tasks we can handle.
  1246. ->condition('t.type', array('addIndex', 'fieldsUpdated', 'removeIndex', 'deleteItems'));
  1247. if ($server) {
  1248. $select->condition('t.server_id', $server->machine_name);
  1249. }
  1250. else {
  1251. $select->innerJoin('search_api_server', 's', 't.server_id = s.machine_name AND s.enabled = 1');
  1252. // By ordering by the server, we can later just load them when we reach them
  1253. // while looping through the tasks. It is very unlikely there will be tasks
  1254. // for more than one or two servers, so a *_load_multiple() probably
  1255. // wouldn't bring any significant advantages, but complicate the code.
  1256. $select->orderBy('t.server_id');
  1257. }
  1258. // Store a count query for later checking whether all tasks were processed
  1259. // successfully.
  1260. $count_query = $select->countQuery();
  1261. // Sometimes the order of tasks might be important, so make sure to order by
  1262. // the task ID (which should be in order of insertion).
  1263. $select->orderBy('t.id');
  1264. $tasks = $select->execute();
  1265. $executed_tasks = array();
  1266. foreach ($tasks as $task) {
  1267. if (!$server || $server->machine_name != $task->server_id) {
  1268. $server = search_api_server_load($task->server_id);
  1269. if (!$server) {
  1270. continue;
  1271. }
  1272. }
  1273. switch ($task->type) {
  1274. case 'addIndex':
  1275. $index = search_api_index_load($task->index_id);
  1276. if ($index) {
  1277. $server->addIndex($index);
  1278. }
  1279. break;
  1280. case 'fieldsUpdated':
  1281. $index = search_api_index_load($task->index_id);
  1282. if ($index) {
  1283. if ($task->data) {
  1284. $index->original = unserialize($task->data);
  1285. }
  1286. $server->fieldsUpdated($index);
  1287. }
  1288. break;
  1289. case 'removeIndex':
  1290. $index = search_api_index_load($task->index_id);
  1291. if ($index) {
  1292. $server->removeIndex($index ? $index : $task->index_id);
  1293. }
  1294. break;
  1295. case 'deleteItems':
  1296. $ids = $task->data ? unserialize($task->data) : 'all';
  1297. $index = $task->index_id ? search_api_index_load($task->index_id) : NULL;
  1298. // Since a failed load returns (for stupid menu handler reasons) FALSE,
  1299. // not NULL, we have to make doubly sure here not to pass an invalid
  1300. // value (and cause a fatal error).
  1301. $index = $index ? $index : NULL;
  1302. $server->deleteItems($ids, $index);
  1303. break;
  1304. default:
  1305. // This should never happen.
  1306. continue;
  1307. }
  1308. $executed_tasks[] = $task->id;
  1309. }
  1310. // If there were no tasks (we recognized), return TRUE.
  1311. if (!$executed_tasks) {
  1312. return TRUE;
  1313. }
  1314. // Otherwise, delete the executed tasks and check if new tasks were created.
  1315. search_api_server_tasks_delete($executed_tasks);
  1316. return $count_query->execute()->fetchField() === 0;
  1317. }
  1318. /**
  1319. * Adds an entry into a server's list of pending tasks.
  1320. *
  1321. * @param SearchApiServer $server
  1322. * The server for which a task should be remembered.
  1323. * @param $type
  1324. * The type of task to perform.
  1325. * @param SearchApiIndex|string|null $index
  1326. * (optional) If applicable, the index to which the task pertains (or its
  1327. * machine name).
  1328. * @param mixed $data
  1329. * (optional) If applicable, some further data necessary for the task.
  1330. */
  1331. function search_api_server_tasks_add(SearchApiServer $server, $type, $index = NULL, $data = NULL) {
  1332. db_insert('search_api_task')
  1333. ->fields(array(
  1334. 'server_id' => $server->machine_name,
  1335. 'type' => $type,
  1336. 'index_id' => $index ? (is_object($index) ? $index->machine_name : $index) : NULL,
  1337. 'data' => isset($data) ? serialize($data) : NULL,
  1338. ))
  1339. ->execute();
  1340. }
  1341. /**
  1342. * Removes pending server tasks from the list.
  1343. *
  1344. * @param array|null $ids
  1345. * (optional) The IDs of the pending server tasks to delete. Set to NULL
  1346. * to not filter by IDs.
  1347. * @param SearchApiServer|null $server
  1348. * (optional) A server for which the tasks should be deleted. Set to NULL to
  1349. * delete tasks from all servers.
  1350. * @param SearchApiIndex|string|null $index
  1351. * (optional) An index (or its machine name) for which the tasks should be
  1352. * deleted. Set to NULL to delete tasks for all indexes.
  1353. */
  1354. function search_api_server_tasks_delete(array $ids = NULL, SearchApiServer $server = NULL, $index = NULL) {
  1355. $delete = db_delete('search_api_task');
  1356. if ($ids) {
  1357. $delete->condition('id', $ids);
  1358. }
  1359. if ($server) {
  1360. $delete->condition('server_id', $server->machine_name);
  1361. }
  1362. if ($index) {
  1363. $delete->condition('index_id', $index->machine_name);
  1364. }
  1365. $delete->execute();
  1366. }
  1367. /**
  1368. * Recalculates the saved fields of an index.
  1369. *
  1370. * This is mostly necessary when the multiplicity of the underlying properties
  1371. * change. The method will re-examine the data structure of the entities in each
  1372. * index and, if a discrepancy is spotted, re-save that index with updated
  1373. * fields options (thus, of course, also triggering a re-indexing operation).
  1374. *
  1375. * @param SearchApiIndex[]|false $indexes
  1376. * An array of SearchApiIndex objects on which to perform the operation, or
  1377. * FALSE to perform it on all indexes.
  1378. */
  1379. function search_api_index_recalculate_fields($indexes = FALSE) {
  1380. if (!is_array($indexes)) {
  1381. $indexes = search_api_index_load_multiple(FALSE);
  1382. }
  1383. $stored_keys = drupal_map_assoc(array('type', 'entity_type', 'real_type', 'boost'));
  1384. foreach ($indexes as $index) {
  1385. if (empty($index->options['fields'])) {
  1386. continue;
  1387. }
  1388. // We have to clear the cache, both static and stored, before using
  1389. // getFields(). Otherwise, we'd just use the stale data which the fields
  1390. // options are probably already based on.
  1391. cache_clear_all($index->getCacheId() . '-1-0', 'cache');
  1392. $index->resetCaches();
  1393. // getFields() automatically uses the actual data types to correct possible
  1394. // stale data.
  1395. $fields = $index->getFields();
  1396. foreach ($fields as $key => $field) {
  1397. $fields[$key] = array_intersect_key($field, $stored_keys);
  1398. if (isset($fields[$key]['boost']) && $fields[$key]['boost'] == '1.0') {
  1399. unset($fields[$key]['boost']);
  1400. }
  1401. }
  1402. // Use a more accurate method of determining if the fields settings are
  1403. // equal to avoid needlessly re-indexing the whole index.
  1404. if ($fields != $index->options['fields']) {
  1405. $options = $index->options;
  1406. $options['fields'] = $fields;
  1407. $index->update(array('options' => $options));
  1408. }
  1409. }
  1410. }
  1411. /**
  1412. * Test two setting arrays (or individual settings) for equality.
  1413. *
  1414. * @param mixed $setting1
  1415. * The first setting (array).
  1416. * @param mixed $setting2
  1417. * The second setting (array).
  1418. *
  1419. * @return bool
  1420. * TRUE if both settings are identical, FALSE otherwise.
  1421. *
  1422. * @deprecated The simple "==" operator will achieve the same.
  1423. */
  1424. function _search_api_settings_equals($setting1, $setting2) {
  1425. if (!is_array($setting1) || !is_array($setting2)) {
  1426. return $setting1 == $setting2;
  1427. }
  1428. foreach ($setting1 as $key => $value) {
  1429. if (!array_key_exists($key, $setting2)) {
  1430. return FALSE;
  1431. }
  1432. if (!_search_api_settings_equals($value, $setting2[$key])) {
  1433. return FALSE;
  1434. }
  1435. unset($setting2[$key]);
  1436. }
  1437. // If any keys weren't unset previously, they are not present in $setting1 and
  1438. // the two are different.
  1439. return !$setting2;
  1440. }
  1441. /**
  1442. * Indexes items for the specified index.
  1443. *
  1444. * Only items marked as changed are indexed, in their order of change (if
  1445. * known).
  1446. *
  1447. * @param SearchApiIndex $index
  1448. * The index on which items should be indexed.
  1449. * @param int $limit
  1450. * (optional) The number of items which should be indexed at most. Defaults to
  1451. * -1, which means that all changed items should be indexed.
  1452. *
  1453. * @return int
  1454. * Number of successfully indexed items.
  1455. *
  1456. * @throws SearchApiException
  1457. * If any error occurs during indexing.
  1458. */
  1459. function search_api_index_items(SearchApiIndex $index, $limit = -1) {
  1460. // Don't try to index on read-only indexes.
  1461. if ($index->read_only) {
  1462. return 0;
  1463. }
  1464. $ids = search_api_get_items_to_index($index, $limit);
  1465. return $ids ? count(search_api_index_specific_items($index, $ids)) : 0;
  1466. }
  1467. /**
  1468. * Indexes the specified items on the given index.
  1469. *
  1470. * Items which were successfully indexed are marked as such afterwards.
  1471. *
  1472. * @param SearchApiIndex $index
  1473. * The index on which items should be indexed.
  1474. * @param array $ids
  1475. * The IDs of the items which should be indexed.
  1476. *
  1477. * @return array
  1478. * The IDs of all successfully indexed items.
  1479. *
  1480. * @throws SearchApiException
  1481. * If any error occurs during indexing.
  1482. */
  1483. function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
  1484. // Before doing anything else, check whether there are pending tasks that need
  1485. // to be executed on the server. It might be important that they are executed
  1486. // before any indexing occurs.
  1487. if (!search_api_server_tasks_check($index->server())) {
  1488. throw new SearchApiException(t('Could not index items since important pending server tasks could not be performed.'));
  1489. }
  1490. $items = $index->loadItems($ids);
  1491. // Clone items because data alterations may alter them.
  1492. $cloned_items = array();
  1493. foreach ($items as $id => $item) {
  1494. if (is_object($item)) {
  1495. $cloned_items[$id] = clone $item;
  1496. }
  1497. else {
  1498. // Normally, items that can't be loaded shouldn't be returned by
  1499. // entity_load (and other loadItems() implementations). Therefore, this is
  1500. // an extremely rare case, which seems to happen during installation for
  1501. // some specific setups.
  1502. $type = search_api_get_item_type_info($index->item_type);
  1503. $type = $type ? $type['name'] : $index->item_type;
  1504. watchdog('search_api', "Error during indexing: invalid item loaded for @type with ID @id.", array('@id' => $id, '@type' => $type), WATCHDOG_WARNING);
  1505. }
  1506. }
  1507. $indexed = $items ? $index->index($cloned_items) : array();
  1508. if ($indexed) {
  1509. search_api_track_item_indexed($index, $indexed);
  1510. // If some items could not be indexed, we don't want to try re-indexing
  1511. // them right away, so we mark them as "freshly" changed. Sadly, there is
  1512. // no better way than to mark them as indexed first...
  1513. if (count($indexed) < count($ids)) {
  1514. // Believe it or not but this is actually quite faster than the equivalent
  1515. // $diff = array_diff($ids, $indexed);
  1516. $diff = array_keys(array_diff_key(array_flip($ids), array_flip($indexed)));
  1517. $index->datasource()->trackItemIndexed($diff, $index);
  1518. $index->datasource()->trackItemChange($diff, array($index));
  1519. }
  1520. }
  1521. return $indexed;
  1522. }
  1523. /**
  1524. * Queues items for indexing at the end of the page request.
  1525. *
  1526. * @param SearchApiIndex $index
  1527. * The index on which items should be indexed.
  1528. * @param array $ids
  1529. * The IDs of the items which should be indexed.
  1530. *
  1531. * @return array
  1532. * The current contents of the queue, as a reference.
  1533. *
  1534. * @see search_api_index_specific_items()
  1535. * @see _search_api_index_queued_items()
  1536. */
  1537. function &search_api_index_specific_items_delayed(SearchApiIndex $index = NULL, array $ids = array()) {
  1538. // We cannot use drupal_static() here because the static cache is reset during
  1539. // batch processing, which breaks batch handling.
  1540. static $queue = array();
  1541. static $registered = FALSE;
  1542. // Only register the shutdown function once.
  1543. if (empty($registered)) {
  1544. drupal_register_shutdown_function('_search_api_index_queued_items');
  1545. $registered = TRUE;
  1546. }
  1547. // Allow for empty call to just retrieve the queue.
  1548. if ($index && $ids) {
  1549. $index_id = $index->machine_name;
  1550. $queue += array($index_id => array());
  1551. $queue[$index_id] += drupal_map_assoc($ids);
  1552. }
  1553. return $queue;
  1554. }
  1555. /**
  1556. * Returns a list of items that need to be indexed for the specified index.
  1557. *
  1558. * @param SearchApiIndex $index
  1559. * The index for which items should be retrieved.
  1560. * @param $limit
  1561. * The maximum number of items to retrieve. -1 means no limit.
  1562. *
  1563. * @return array
  1564. * An array of IDs of items that need to be indexed.
  1565. */
  1566. function search_api_get_items_to_index(SearchApiIndex $index, $limit = -1) {
  1567. if ($limit == 0) {
  1568. return array();
  1569. }
  1570. return $index->datasource()->getChangedItems($index, $limit);
  1571. }
  1572. /**
  1573. * Creates a search query on a specified search index.
  1574. *
  1575. * @param $id
  1576. * The ID or machine name of the index to execute the search on.
  1577. * @param $options
  1578. * An associative array of options to be passed to
  1579. * SearchApiQueryInterface::__construct().
  1580. *
  1581. * @return SearchApiQueryInterface
  1582. * An object for searching on the specified index.
  1583. *
  1584. * @throws SearchApiException
  1585. * If the index is unknown or disabled, or some other error was encountered.
  1586. */
  1587. function search_api_query($id, array $options = array()) {
  1588. $index = search_api_index_load($id);
  1589. if (!$index) {
  1590. throw new SearchApiException(t('Unknown index with ID @id.', array('@id' => $id)));
  1591. }
  1592. return $index->query($options);
  1593. }
  1594. /**
  1595. * Stores or retrieves a search executed in this page request.
  1596. *
  1597. * Static storage for the searches executed during the current page request. Can
  1598. * used to store an executed search, or to retrieve a previously stored search.
  1599. *
  1600. * @param $search_id
  1601. * For pages displaying multiple searches, an optional ID identifying the
  1602. * search in questions. When storing a search, this is filled automatically,
  1603. * unless it is manually set.
  1604. * @param SearchApiQuery $query
  1605. * When storing an executed search, the query that was executed. NULL
  1606. * otherwise.
  1607. * @param array $results
  1608. * When storing an executed search, the returned results as specified by
  1609. * SearchApiQueryInterface::execute(). An empty array, otherwise.
  1610. *
  1611. * @return array
  1612. * If a search with the specified ID was executed, an array containing
  1613. * ($query, $results) as used in this function's parameters. If $search_id is
  1614. * NULL, an array of all executed searches will be returned, keyed by ID.
  1615. */
  1616. function search_api_current_search($search_id = NULL, SearchApiQuery $query = NULL, array $results = array()) {
  1617. $searches = &drupal_static(__FUNCTION__, array());
  1618. if (isset($query)) {
  1619. if (!isset($search_id)) {
  1620. $search_id = $query->getOption('search id');
  1621. }
  1622. $base = $search_id;
  1623. $i = 0;
  1624. while (isset($searches[$search_id])) {
  1625. $search_id = $base . '-' . ++$i;
  1626. }
  1627. $searches[$search_id] = array($query, $results);
  1628. }
  1629. if (isset($search_id)) {
  1630. return isset($searches[$search_id]) ? $searches[$search_id] : NULL;
  1631. }
  1632. return $searches;
  1633. }
  1634. /**
  1635. * Returns all field types recognized by the Search API framework.
  1636. *
  1637. * @return array
  1638. * An associative array with all recognized types as keys, mapped to their
  1639. * translated display names.
  1640. *
  1641. * @see search_api_default_field_types()
  1642. * @see search_api_get_data_type_info()
  1643. */
  1644. function search_api_field_types() {
  1645. $types = search_api_default_field_types();
  1646. foreach (search_api_get_data_type_info() as $id => $type) {
  1647. $types[$id] = $type['name'];
  1648. }
  1649. return $types;
  1650. }
  1651. /**
  1652. * Returns the default field types recognized by the Search API framework.
  1653. *
  1654. * @return array
  1655. * An associative array with the default types as keys, mapped to their
  1656. * translated display names.
  1657. */
  1658. function search_api_default_field_types() {
  1659. return array(
  1660. 'text' => t('Fulltext'),
  1661. 'string' => t('String'),
  1662. 'integer' => t('Integer'),
  1663. 'decimal' => t('Decimal'),
  1664. 'date' => t('Date'),
  1665. 'duration' => t('Duration'),
  1666. 'boolean' => t('Boolean'),
  1667. 'uri' => t('URI'),
  1668. );
  1669. }
  1670. /**
  1671. * Returns either all custom field type definitions, or a specific one.
  1672. *
  1673. * @param $type
  1674. * If specified, the type whose definition should be returned.
  1675. *
  1676. * @return array
  1677. * If $type was not given, an array containing all custom data types, in the
  1678. * format specified by hook_search_api_data_type_info().
  1679. * Otherwise, the definition for the given type, or NULL if it is unknown.
  1680. *
  1681. * @see hook_search_api_data_type_info()
  1682. */
  1683. function search_api_get_data_type_info($type = NULL) {
  1684. $types = &drupal_static(__FUNCTION__);
  1685. if (!isset($types)) {
  1686. $default_types = search_api_default_field_types();
  1687. $types = module_invoke_all('search_api_data_type_info');
  1688. $types = $types ? $types : array();
  1689. foreach ($types as &$type_info) {
  1690. if (!isset($type_info['fallback']) || !isset($default_types[$type_info['fallback']])) {
  1691. $type_info['fallback'] = 'string';
  1692. }
  1693. }
  1694. drupal_alter('search_api_data_type_info', $types);
  1695. }
  1696. if (isset($type)) {
  1697. return isset($types[$type]) ? $types[$type] : NULL;
  1698. }
  1699. return $types;
  1700. }
  1701. /**
  1702. * Returns either a list of all available service infos, or a specific one.
  1703. *
  1704. * @see hook_search_api_service_info()
  1705. *
  1706. * @param string|null $id
  1707. * The ID of the service info to retrieve.
  1708. *
  1709. * @return array
  1710. * If $id was not specified, an array of all available service classes.
  1711. * Otherwise, either the service info with the specified id (if it exists),
  1712. * or NULL. Service class information is formatted as specified by
  1713. * hook_search_api_service_info(), with the addition of a "module" key
  1714. * specifying the module that adds a certain class.
  1715. */
  1716. function search_api_get_service_info($id = NULL) {
  1717. $services = &drupal_static(__FUNCTION__);
  1718. if (!isset($services)) {
  1719. // Inlined version of module_invoke_all() to add "module" keys.
  1720. $services = array();
  1721. foreach (module_implements('search_api_service_info') as $module) {
  1722. $function = $module . '_search_api_service_info';
  1723. if (function_exists($function)) {
  1724. $new_services = $function();
  1725. if (isset($new_services) && is_array($new_services)) {
  1726. foreach ($new_services as $service => $info) {
  1727. $new_services[$service] += array('module' => $module);
  1728. }
  1729. }
  1730. $services += $new_services;
  1731. }
  1732. }
  1733. // Same for drupal_alter().
  1734. foreach (module_implements('search_api_service_info_alter') as $module) {
  1735. $function = $module . '_search_api_service_info_alter';
  1736. if (function_exists($function)) {
  1737. $old = $services;
  1738. $function($services);
  1739. if ($new_services = array_diff_key($services, $old)) {
  1740. foreach ($new_services as $service => $info) {
  1741. $services[$service] += array('module' => $module);
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. if (isset($id)) {
  1748. return isset($services[$id]) ? $services[$id] : NULL;
  1749. }
  1750. return $services;
  1751. }
  1752. /**
  1753. * Returns information for either all item types, or a specific one.
  1754. *
  1755. * @param string|null $type
  1756. * If set, the item type whose information should be returned.
  1757. *
  1758. * @return array|null
  1759. * If $type is given, either an array containing the information of that item
  1760. * type, or NULL if it is unknown. Otherwise, an array keyed by type IDs
  1761. * containing the information for all item types. Item type information is
  1762. * formatted as specified by hook_search_api_item_type_info(), with the
  1763. * addition of a "module" key specifying the module that adds a certain type.
  1764. *
  1765. * @see hook_search_api_item_type_info()
  1766. */
  1767. function search_api_get_item_type_info($type = NULL) {
  1768. $types = &drupal_static(__FUNCTION__);
  1769. if (!isset($types)) {
  1770. // Inlined version of module_invoke_all() to add "module" keys.
  1771. $types = array();
  1772. foreach (module_implements('search_api_item_type_info') as $module) {
  1773. $function = $module . '_search_api_item_type_info';
  1774. if (function_exists($function)) {
  1775. $new_types = $function();
  1776. if (isset($new_types) && is_array($new_types)) {
  1777. foreach ($new_types as $id => $info) {
  1778. $new_types[$id] += array('module' => $module);
  1779. }
  1780. }
  1781. $types += $new_types;
  1782. }
  1783. }
  1784. // Same for drupal_alter().
  1785. foreach (module_implements('search_api_item_type_info_alter') as $module) {
  1786. $function = $module . '_search_api_item_type_info_alter';
  1787. if (function_exists($function)) {
  1788. $old = $types;
  1789. $function($types);
  1790. if ($new_types = array_diff_key($types, $old)) {
  1791. foreach ($new_types as $id => $info) {
  1792. $types[$id] += array('module' => $module);
  1793. }
  1794. }
  1795. }
  1796. }
  1797. }
  1798. if (isset($type)) {
  1799. return isset($types[$type]) ? $types[$type] : NULL;
  1800. }
  1801. return $types;
  1802. }
  1803. /**
  1804. * Get a data source controller object for the specified type.
  1805. *
  1806. * @param $type
  1807. * The type whose data source controller should be returned.
  1808. *
  1809. * @return SearchApiDataSourceControllerInterface
  1810. * The type's data source controller.
  1811. *
  1812. * @throws SearchApiException
  1813. * If the type is unknown or specifies an invalid data source controller.
  1814. */
  1815. function search_api_get_datasource_controller($type) {
  1816. $datasources = &drupal_static(__FUNCTION__, array());
  1817. if (empty($datasources[$type])) {
  1818. $info = search_api_get_item_type_info($type);
  1819. if (isset($info['datasource controller']) && class_exists($info['datasource controller'])) {
  1820. $datasources[$type] = new $info['datasource controller']($type);
  1821. }
  1822. if (empty($datasources[$type]) || !($datasources[$type] instanceof SearchApiDataSourceControllerInterface)) {
  1823. unset($datasources[$type]);
  1824. throw new SearchApiException(t('Unknown or invalid item type @type.', array('@type' => $type)));
  1825. }
  1826. }
  1827. return $datasources[$type];
  1828. }
  1829. /**
  1830. * Returns a list of all available data alter callbacks.
  1831. *
  1832. * @see hook_search_api_alter_callback_info()
  1833. *
  1834. * @return array
  1835. * An array of all available data alter callbacks, keyed by function name.
  1836. */
  1837. function search_api_get_alter_callbacks() {
  1838. $callbacks = &drupal_static(__FUNCTION__);
  1839. if (!isset($callbacks)) {
  1840. $callbacks = module_invoke_all('search_api_alter_callback_info');
  1841. // Fill optional settings with default values.
  1842. foreach ($callbacks as $id => $callback) {
  1843. $callbacks[$id] += array('weight' => 0);
  1844. }
  1845. // Invoke alter hook.
  1846. drupal_alter('search_api_alter_callback_info', $callbacks);
  1847. }
  1848. return $callbacks;
  1849. }
  1850. /**
  1851. * Returns a list of all available pre- and post-processors.
  1852. *
  1853. * @see hook_search_api_processor_info()
  1854. *
  1855. * @return array
  1856. * An array of all available processors, keyed by id.
  1857. */
  1858. function search_api_get_processors() {
  1859. $processors = &drupal_static(__FUNCTION__);
  1860. if (!isset($processors)) {
  1861. $processors = module_invoke_all('search_api_processor_info');
  1862. // Fill optional settings with default values.
  1863. foreach ($processors as $id => $processor) {
  1864. $processors[$id] += array('weight' => 0);
  1865. }
  1866. // Invoke alter hook.
  1867. drupal_alter('search_api_processor_info', $processors);
  1868. }
  1869. return $processors;
  1870. }
  1871. /**
  1872. * Implements hook_search_api_query_alter().
  1873. *
  1874. * Adds node access to the query, if enabled.
  1875. *
  1876. * @param SearchApiQueryInterface $query
  1877. * The SearchApiQueryInterface object representing the search query.
  1878. */
  1879. function search_api_search_api_query_alter(SearchApiQueryInterface $query) {
  1880. global $user;
  1881. $index = $query->getIndex();
  1882. // Only add node access if the necessary fields are indexed in the index, and
  1883. // unless disabled explicitly by the query.
  1884. $type = $index->getEntityType();
  1885. if (!empty($index->options['data_alter_callbacks']["search_api_alter_{$type}_access"]['status']) && !$query->getOption('search_api_bypass_access')) {
  1886. $account = $query->getOption('search_api_access_account', $user);
  1887. if (is_numeric($account)) {
  1888. $account = user_load($account);
  1889. }
  1890. if (is_object($account)) {
  1891. try {
  1892. _search_api_query_add_node_access($account, $query, $type);
  1893. }
  1894. catch (SearchApiException $e) {
  1895. watchdog_exception('search_api', $e);
  1896. }
  1897. }
  1898. else {
  1899. $account = $query->getOption('search_api_access_account', '(' . t('none') . ')');
  1900. if (is_object($account)) {
  1901. $account = $account->uid;
  1902. }
  1903. if (!is_scalar($account)) {
  1904. $account = var_export($account, TRUE);
  1905. }
  1906. watchdog('search_api', 'An illegal user UID was given for node access: @uid.', array('@uid' => $account), WATCHDOG_WARNING);
  1907. }
  1908. }
  1909. }
  1910. /**
  1911. * Adds a node access filter to a search query, if applicable.
  1912. *
  1913. * @param object $account
  1914. * The user object, who searches.
  1915. * @param SearchApiQueryInterface $query
  1916. * The query to which a node access filter should be added, if applicable.
  1917. * @param string $type
  1918. * (optional) The type of search – either "node" or "comment". Defaults to
  1919. * "node".
  1920. *
  1921. * @throws SearchApiException
  1922. * If not all necessary fields are indexed on the index.
  1923. */
  1924. function _search_api_query_add_node_access($account, SearchApiQueryInterface $query, $type = 'node') {
  1925. // Don't do anything if the user can access all content.
  1926. if (user_access('bypass node access', $account)) {
  1927. return;
  1928. }
  1929. $is_comment = ($type == 'comment');
  1930. // Check whether the necessary fields are indexed.
  1931. $fields = $query->getIndex()->options['fields'];
  1932. $required = array('search_api_access_node', 'status');
  1933. if (!$is_comment) {
  1934. $required[] = 'author';
  1935. }
  1936. foreach ($required as $field) {
  1937. if (empty($fields[$field])) {
  1938. $vars['@field'] = $field;
  1939. $vars['@index'] = $query->getIndex()->name;
  1940. throw new SearchApiException(t('Required field @field not indexed on index @index. Could not perform access checks.', $vars));
  1941. }
  1942. }
  1943. // If the user cannot access content/comments at all, return no results.
  1944. if (!user_access('access content', $account) || ($is_comment && !user_access('access content', $account))) {
  1945. // Simple hack for returning no results.
  1946. $query->condition('status', 0);
  1947. $query->condition('status', 1);
  1948. watchdog('search_api', 'User @name tried to execute a search, but cannot access content.', array('@name' => theme('username', array('account' => $account))), WATCHDOG_NOTICE);
  1949. return;
  1950. }
  1951. // Filter by the "published" status.
  1952. $published = $is_comment ? COMMENT_PUBLISHED : NODE_PUBLISHED;
  1953. if (!$is_comment && user_access('view own unpublished content')) {
  1954. $filter = $query->createFilter('OR');
  1955. $filter->condition('status', $published);
  1956. $filter->condition('author', $account->uid);
  1957. $query->filter($filter);
  1958. }
  1959. else {
  1960. $query->condition('status', $published);
  1961. }
  1962. // Filter by node access grants.
  1963. $filter = $query->createFilter('OR');
  1964. $grants = node_access_grants('view', $account);
  1965. foreach ($grants as $realm => $gids) {
  1966. foreach ($gids as $gid) {
  1967. $filter->condition('search_api_access_node', "node_access_$realm:$gid");
  1968. }
  1969. }
  1970. $filter->condition('search_api_access_node', 'node_access__all');
  1971. $query->filter($filter);
  1972. }
  1973. /**
  1974. * Determines whether a field of the given type contains text data.
  1975. *
  1976. * Can also be used to find other types.
  1977. *
  1978. * @param string $type
  1979. * The type for which to check.
  1980. * @param array $allowed
  1981. * Optionally, an array of allowed types.
  1982. *
  1983. * @return bool
  1984. * TRUE if $type is either one of the specified types or a list of such
  1985. * values. FALSE otherwise.
  1986. *
  1987. * @see search_api_extract_inner_type()
  1988. */
  1989. function search_api_is_text_type($type, array $allowed = array('text')) {
  1990. return array_search(search_api_extract_inner_type($type), $allowed) !== FALSE;
  1991. }
  1992. /**
  1993. * Utility function for determining whether a field of the given type contains
  1994. * a list of any kind.
  1995. *
  1996. * @param $type
  1997. * A string containing the type to check.
  1998. *
  1999. * @return bool
  2000. * TRUE iff $type is a list type ("list<*>").
  2001. */
  2002. function search_api_is_list_type($type) {
  2003. return substr($type, 0, 5) == 'list<';
  2004. }
  2005. /**
  2006. * Utility function for determining the nesting level of a list type.
  2007. *
  2008. * @param $type
  2009. * A string containing the type to check.
  2010. *
  2011. * @return int
  2012. * The nesting level of the type. 0 for singular types, 1 for lists of
  2013. * singular types, etc.
  2014. */
  2015. function search_api_list_nesting_level($type) {
  2016. $level = 0;
  2017. while (search_api_is_list_type($type)) {
  2018. $type = substr($type, 5, -1);
  2019. ++$level;
  2020. }
  2021. return $level;
  2022. }
  2023. /**
  2024. * Utility function for nesting a type to the same level as another type.
  2025. * I.e., after <code>$t = search_api_nest_type($type, $nested_type);</code> is
  2026. * executed, the following statements will always be true:
  2027. * @code
  2028. * search_api_list_nesting_level($t) == search_api_list_nesting_level($nested_type);
  2029. * search_api_extract_inner_type($t) == search_api_extract_inner_type($type);
  2030. * @endcode
  2031. *
  2032. * @param $type
  2033. * The type to wrap.
  2034. * @param $nested_type
  2035. * Another type, determining the nesting level.
  2036. *
  2037. * @return string
  2038. * A list version of $type, as specified above.
  2039. */
  2040. function search_api_nest_type($type, $nested_type) {
  2041. while (search_api_is_list_type($nested_type)) {
  2042. $nested_type = substr($nested_type, 5, -1);
  2043. $type = "list<$type>";
  2044. }
  2045. return $type;
  2046. }
  2047. /**
  2048. * Utility function for extracting the contained primitive type of a list type.
  2049. *
  2050. * @param $type
  2051. * A string containing the list type to process.
  2052. *
  2053. * @return string
  2054. * A string containing the primitive type contained within the list, e.g.
  2055. * "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
  2056. * type, it is returned unchanged.
  2057. */
  2058. function search_api_extract_inner_type($type) {
  2059. while (search_api_is_list_type($type)) {
  2060. $type = substr($type, 5, -1);
  2061. }
  2062. return $type;
  2063. }
  2064. /**
  2065. * Helper function for reacting to index updates with regards to the datasource.
  2066. *
  2067. * When an overridden index is reverted, its numerical ID will sometimes change.
  2068. * Since the default datasource implementation uses that for referencing
  2069. * indexes, the index ID in the items table must be updated accordingly. This is
  2070. * implemented in this function.
  2071. *
  2072. * Modules implementing other datasource controllers, that use a table other
  2073. * than {search_api_item}, can use this function, too. It should be called
  2074. * unconditionally in a hook_search_api_index_update() implementation. If this
  2075. * function isn't used, similar code should be added there.
  2076. *
  2077. * However, note that this is only necessary (and this function should only be
  2078. * called) if the indexes are referenced by numerical ID in the items table.
  2079. *
  2080. * @param SearchApiIndex $index
  2081. * The index that was changed.
  2082. * @param string $table
  2083. * The table containing items information, analogous to {search_api_item}.
  2084. * @param string $column
  2085. * The column in $table that holds the index's numerical ID.
  2086. */
  2087. function search_api_index_update_datasource(SearchApiIndex $index, $table, $column = 'index_id') {
  2088. if ($index->id != $index->original->id) {
  2089. db_update($table)
  2090. ->fields(array($column => $index->id))
  2091. ->condition($column, $index->original->id)
  2092. ->execute();
  2093. }
  2094. }
  2095. /**
  2096. * Extracts specific field values from an EntityMetadataWrapper object.
  2097. *
  2098. * @param EntityMetadataWrapper $wrapper
  2099. * The wrapper from which to extract fields.
  2100. * @param array $fields
  2101. * The fields to extract, as stored in an index. I.e., the array keys are
  2102. * field names, the values are arrays with at least a "type" key present.
  2103. * @param array $value_options
  2104. * An array of options that should be passed to the
  2105. * EntityMetadataWrapper::value() method (see there).
  2106. *
  2107. * @return array
  2108. * The $fields array with additional "value" and "original_type" keys set.
  2109. */
  2110. function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
  2111. $value_options += array(
  2112. 'identifier' => TRUE,
  2113. );
  2114. // If $wrapper is a list of entities, we have to aggregate their field values.
  2115. $wrapper_info = $wrapper->info();
  2116. if (search_api_is_list_type($wrapper_info['type'])) {
  2117. foreach ($fields as &$info) {
  2118. $info['value'] = array();
  2119. $info['original_type'] = $info['type'];
  2120. }
  2121. unset($info);
  2122. try {
  2123. foreach ($wrapper as $w) {
  2124. $nested_fields = search_api_extract_fields($w, $fields, $value_options);
  2125. foreach ($nested_fields as $field => $info) {
  2126. if (isset($info['value'])) {
  2127. $fields[$field]['value'][] = $info['value'];
  2128. }
  2129. if (isset($info['original_type'])) {
  2130. $fields[$field]['original_type'] = $info['original_type'];
  2131. }
  2132. }
  2133. }
  2134. }
  2135. catch (EntityMetadataWrapperException $e) {
  2136. // Catch exceptions caused by not set list values.
  2137. }
  2138. return $fields;
  2139. }
  2140. $nested = array();
  2141. $entity_infos = entity_get_info();
  2142. foreach ($fields as $field => &$info) {
  2143. $pos = strpos($field, ':');
  2144. if ($pos === FALSE) {
  2145. // Set "defaults" in case an error occurs later.
  2146. $info['value'] = NULL;
  2147. $info['original_type'] = $info['type'];
  2148. if (isset($wrapper->$field)) {
  2149. try {
  2150. // Set the original type according to the field wrapper's info.
  2151. $property_info = $wrapper->$field->info();
  2152. $info['original_type'] = $property_info['type'];
  2153. // Extract the basic value from the field wrapper.
  2154. $info['value'] = $wrapper->$field->value($value_options);
  2155. // For entities, we need to take care to differentiate between
  2156. // entities with ID 0 and empty fields. In the latter case, the
  2157. // wrapper's value() method returns, when called with "identifier =
  2158. // TRUE", FALSE instead of the (more logical) NULL.
  2159. $is_entity = isset($entity_infos[search_api_extract_inner_type($property_info['type'])]);
  2160. if ($is_entity && $info['value'] === FALSE) {
  2161. $info['value'] = NULL;
  2162. }
  2163. // If we index the field as fulltext, we also include the entity label
  2164. // or option list label, if applicable.
  2165. if (search_api_is_text_type($info['type']) && isset($info['value'])) {
  2166. if ($wrapper->$field->optionsList('view')) {
  2167. _search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
  2168. }
  2169. elseif ($is_entity) {
  2170. $info['value'] = _search_api_extract_entity_value($wrapper->$field, TRUE);
  2171. }
  2172. }
  2173. }
  2174. catch (EntityMetadataWrapperException $e) {
  2175. // This might happen for entity-typed properties that are NULL, e.g.,
  2176. // for comments without parent.
  2177. }
  2178. }
  2179. }
  2180. else {
  2181. list($prefix, $key) = explode(':', $field, 2);
  2182. $nested[$prefix][$key] = $info;
  2183. }
  2184. }
  2185. unset($info);
  2186. foreach ($nested as $prefix => $nested_fields) {
  2187. if (isset($wrapper->$prefix)) {
  2188. $nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
  2189. foreach ($nested_fields as $field => $info) {
  2190. $fields["$prefix:$field"] = $info;
  2191. }
  2192. }
  2193. else {
  2194. foreach ($nested_fields as &$info) {
  2195. $info['value'] = NULL;
  2196. $info['original_type'] = $info['type'];
  2197. }
  2198. }
  2199. }
  2200. return $fields;
  2201. }
  2202. /**
  2203. * Helper method for adding additional text data to fields with an option list.
  2204. */
  2205. function _search_api_add_option_values(&$value, array $options) {
  2206. if (is_array($value)) {
  2207. foreach ($value as &$v) {
  2208. _search_api_add_option_values($v, $options);
  2209. }
  2210. return;
  2211. }
  2212. if (is_scalar($value) && isset($options[$value])) {
  2213. $value .= ' ' . $options[$value];
  2214. }
  2215. }
  2216. /**
  2217. * Helper method for extracting the ID (and possibly label) of an entity-valued field.
  2218. */
  2219. function _search_api_extract_entity_value(EntityMetadataWrapper $wrapper, $fulltext = FALSE) {
  2220. $v = $wrapper->value();
  2221. if (is_array($v)) {
  2222. $ret = array();
  2223. foreach ($wrapper as $item) {
  2224. $values = _search_api_extract_entity_value($item, $fulltext);
  2225. if ($values) {
  2226. $ret[] = $values;
  2227. }
  2228. }
  2229. return $ret;
  2230. }
  2231. if ($v) {
  2232. $ret = $wrapper->getIdentifier();
  2233. if ($fulltext && ($label = $wrapper->label())) {
  2234. $ret .= ' ' . $label;
  2235. }
  2236. return $ret;
  2237. }
  2238. return NULL;
  2239. }
  2240. /**
  2241. * Load the search server with the specified id.
  2242. *
  2243. * @param $id
  2244. * The search server's id.
  2245. * @param $reset
  2246. * Whether to reset the internal cache.
  2247. *
  2248. * @return SearchApiServer
  2249. * An object representing the server with the specified id.
  2250. */
  2251. function search_api_server_load($id, $reset = FALSE) {
  2252. $ret = search_api_server_load_multiple(array($id), array(), $reset);
  2253. return $ret ? reset($ret) : FALSE;
  2254. }
  2255. /**
  2256. * Load multiple servers at once, determined by IDs or machine names, or by
  2257. * other conditions.
  2258. *
  2259. * @see entity_load()
  2260. *
  2261. * @param array|false $ids
  2262. * An array of server IDs or machine names, or FALSE to load all servers.
  2263. * @param array $conditions
  2264. * An array of conditions on the {search_api_server} table in the form
  2265. * 'field' => $value.
  2266. * @param bool $reset
  2267. * Whether to reset the internal entity_load cache.
  2268. *
  2269. * @return SearchApiServer[]
  2270. * An array of server objects keyed by machine name.
  2271. */
  2272. function search_api_server_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2273. $servers = entity_load('search_api_server', $ids, $conditions, $reset);
  2274. return entity_key_array_by_property($servers, 'machine_name');
  2275. }
  2276. /**
  2277. * Entity uri callback.
  2278. */
  2279. function search_api_server_url(SearchApiServer $server) {
  2280. return array(
  2281. 'path' => 'admin/config/search/search_api/server/' . $server->machine_name,
  2282. 'options' => array(),
  2283. );
  2284. }
  2285. /**
  2286. * Title callback for determining which title should be displayed for the
  2287. * "delete" local task.
  2288. *
  2289. * @param Entity $entity
  2290. * The server or index for which the menu link is displayed.
  2291. *
  2292. * @return string
  2293. * A translated version of either "Delete" or "Revert".
  2294. */
  2295. function search_api_title_delete_page(Entity $entity) {
  2296. return $entity->hasStatus(ENTITY_OVERRIDDEN) ? t('Revert') : t('Delete');
  2297. }
  2298. /**
  2299. * Determines whether the current user can disable a server or index.
  2300. *
  2301. * @param Entity $entity
  2302. * The server or index for which the access to the "disable" page is checked.
  2303. *
  2304. * @return bool
  2305. * TRUE if the "disable" page can be accessed by the user, FALSE otherwise.
  2306. */
  2307. function search_api_access_disable_page(Entity $entity) {
  2308. return user_access('administer search_api') && !empty($entity->enabled);
  2309. }
  2310. /**
  2311. * Access callback for determining if a server's or index' "delete" page should
  2312. * be accessible.
  2313. *
  2314. * @param Entity $entity
  2315. * The server or index for which the access to the delete page is checked.
  2316. *
  2317. * @return bool
  2318. * TRUE if the delete page can be accessed by the user, FALSE otherwise.
  2319. */
  2320. function search_api_access_delete_page(Entity $entity) {
  2321. return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
  2322. }
  2323. /**
  2324. * Determines whether a user can access a certain search server or index.
  2325. *
  2326. * Used as an access callback in search_api_entity_info().
  2327. */
  2328. function search_api_entity_access() {
  2329. return user_access('administer search_api');
  2330. }
  2331. /**
  2332. * Inserts a new search server into the database.
  2333. *
  2334. * @param array $values
  2335. * An array containing the values to be inserted.
  2336. *
  2337. * @return
  2338. * The newly inserted server's id, or FALSE on error.
  2339. */
  2340. function search_api_server_insert(array $values) {
  2341. $server = entity_create('search_api_server', $values);
  2342. $server->is_new = TRUE;
  2343. $server->save();
  2344. return $server->id;
  2345. }
  2346. /**
  2347. * Changes a server's settings.
  2348. *
  2349. * @param string|int $id
  2350. * The ID or machine name of the server whose values should be changed.
  2351. * @param array $fields
  2352. * The new field values to set. The enabled field can't be set this way, use
  2353. * search_api_server_enable() and search_api_server_disable() instead.
  2354. *
  2355. * @return int|false
  2356. * 1 if fields were changed, 0 if the fields already had the desired values.
  2357. * FALSE on failure.
  2358. */
  2359. function search_api_server_edit($id, array $fields) {
  2360. $server = search_api_server_load($id, TRUE);
  2361. $ret = $server->update($fields);
  2362. return $ret ? 1 : $ret;
  2363. }
  2364. /**
  2365. * Enables a search server.
  2366. *
  2367. * Will also check for remembered tasks for this server and execute them.
  2368. *
  2369. * @param string|int $id
  2370. * The ID or machine name of the server to enable.
  2371. *
  2372. * @return int|false
  2373. * 1 on success, 0 or FALSE on failure.
  2374. */
  2375. function search_api_server_enable($id) {
  2376. $server = search_api_server_load($id, TRUE);
  2377. $ret = $server->update(array('enabled' => 1));
  2378. return $ret ? 1 : $ret;
  2379. }
  2380. /**
  2381. * Disables a search server.
  2382. *
  2383. * Will also disable all associated indexes and remove them from the server.
  2384. *
  2385. * @param string|int $id
  2386. * The ID or machine name of the server to disable.
  2387. *
  2388. * @return int|false
  2389. * 1 on success, 0 or FALSE on failure.
  2390. */
  2391. function search_api_server_disable($id) {
  2392. $server = search_api_server_load($id, TRUE);
  2393. $ret = $server->update(array('enabled' => 0));
  2394. return $ret ? 1 : $ret;
  2395. }
  2396. /**
  2397. * Clears a search server.
  2398. *
  2399. * Will delete all items stored on the server and mark all associated indexes
  2400. * for re-indexing.
  2401. *
  2402. * @param int|string $id
  2403. * The ID or machine name of the server to clear.
  2404. *
  2405. * @return bool
  2406. * TRUE on success, FALSE on failure.
  2407. */
  2408. function search_api_server_clear($id) {
  2409. $server = search_api_server_load($id);
  2410. $success = TRUE;
  2411. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  2412. $success &= $index->reindex();
  2413. }
  2414. if ($success) {
  2415. $server->deleteItems();
  2416. }
  2417. return $success;
  2418. }
  2419. /**
  2420. * Deletes a search server and disables all associated indexes.
  2421. *
  2422. * @param $id
  2423. * The ID or machine name of the server to delete.
  2424. *
  2425. * @return int|false
  2426. * 1 on success, 0 or FALSE on failure.
  2427. */
  2428. function search_api_server_delete($id) {
  2429. $server = search_api_server_load($id, TRUE);
  2430. $server->delete();
  2431. return 1;
  2432. }
  2433. /**
  2434. * Loads the Search API index with the specified id.
  2435. *
  2436. * @param $id
  2437. * The index' id.
  2438. * @param $reset
  2439. * Whether to reset the internal cache.
  2440. *
  2441. * @return SearchApiIndex|false
  2442. * A completely loaded index object, or FALSE if no such index exists.
  2443. */
  2444. function search_api_index_load($id, $reset = FALSE) {
  2445. $ret = search_api_index_load_multiple(array($id), array(), $reset);
  2446. return reset($ret);
  2447. }
  2448. /**
  2449. * Load multiple indexes at once, determined by IDs or machine names, or by
  2450. * other conditions.
  2451. *
  2452. * @see entity_load()
  2453. *
  2454. * @param array|false $ids
  2455. * An array of index IDs or machine names, or FALSE to load all indexes.
  2456. * @param array $conditions
  2457. * An array of conditions on the {search_api_index} table in the form
  2458. * 'field' => $value.
  2459. * @param bool $reset
  2460. * Whether to reset the internal entity_load cache.
  2461. *
  2462. * @return SearchApiIndex[]
  2463. * An array of index objects keyed by machine name.
  2464. */
  2465. function search_api_index_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2466. // This line is a workaround for a weird PDO bug in PHP 5.2.
  2467. // See http://drupal.org/node/889286.
  2468. new SearchApiIndex();
  2469. $indexes = entity_load('search_api_index', $ids, $conditions, $reset);
  2470. return entity_key_array_by_property($indexes, 'machine_name');
  2471. }
  2472. /**
  2473. * Determines a search index' indexing status.
  2474. *
  2475. * @param SearchApiIndex $index
  2476. * The index whose indexing status should be determined.
  2477. *
  2478. * @return array
  2479. * An associative array containing two keys (in this order):
  2480. * - indexed: The number of items already indexed in their latest version.
  2481. * - total: The total number of items that have to be indexed for this index.
  2482. */
  2483. function search_api_index_status(SearchApiIndex $index) {
  2484. return $index->datasource()->getIndexStatus($index);
  2485. }
  2486. /**
  2487. * Entity uri callback.
  2488. */
  2489. function search_api_index_url(SearchApiIndex $index) {
  2490. return array(
  2491. 'path' => 'admin/config/search/search_api/index/' . $index->machine_name,
  2492. 'options' => array(),
  2493. );
  2494. }
  2495. /**
  2496. * Returns an index's server.
  2497. *
  2498. * Used as a property getter callback for the index's "server_entity" prioperty
  2499. * in search_api_entity_property_info().
  2500. *
  2501. * @param SearchApiIndex $index
  2502. * The index whose server should be returned.
  2503. *
  2504. * @return SearchApiServer|null
  2505. * The server this index currently resides on, or NULL if the index is
  2506. * currently unassigned.
  2507. */
  2508. function search_api_index_get_server(SearchApiIndex $index) {
  2509. try {
  2510. return $index->server();
  2511. }
  2512. catch (SearchApiException $e) {
  2513. watchdog_exception('search_api', $e);
  2514. return NULL;
  2515. }
  2516. }
  2517. /**
  2518. * Returns an options list for the "status" property.
  2519. *
  2520. * Used as an options list callback in search_api_entity_property_info().
  2521. *
  2522. * @return array
  2523. * An array of options, as defined by hook_options_list().
  2524. */
  2525. function search_api_status_options_list() {
  2526. return array(
  2527. ENTITY_CUSTOM => t('Custom'),
  2528. ENTITY_IN_CODE => t('Default'),
  2529. ENTITY_OVERRIDDEN => t('Overridden'),
  2530. ENTITY_FIXED => t('Fixed'),
  2531. );
  2532. }
  2533. /**
  2534. * Inserts a new search index into the database.
  2535. *
  2536. * @param array $values
  2537. * An array containing the values to be inserted.
  2538. *
  2539. * @return
  2540. * The newly inserted index' id, or FALSE on error.
  2541. */
  2542. function search_api_index_insert(array $values) {
  2543. $index = entity_create('search_api_index', $values);
  2544. $index->is_new = TRUE;
  2545. $index->save();
  2546. return $index->id;
  2547. }
  2548. /**
  2549. * Changes an index' settings.
  2550. *
  2551. * @param int|string $id
  2552. * The edited index' ID or machine name.
  2553. * @param array $fields
  2554. * The new field values to set.
  2555. *
  2556. * @return int|false
  2557. * 1 if fields were changed, 0 if the fields already had the desired values.
  2558. * FALSE on failure.
  2559. */
  2560. function search_api_index_edit($id, array $fields) {
  2561. $index = search_api_index_load($id, TRUE);
  2562. $ret = $index->update($fields);
  2563. return $ret ? 1 : $ret;
  2564. }
  2565. /**
  2566. * Changes an index' indexed field settings.
  2567. *
  2568. * @param int|string $id
  2569. * The ID or machine name of the index whose fields should be changed.
  2570. * @param array $fields
  2571. * The new indexed field settings.
  2572. *
  2573. * @return int|false
  2574. * 1 if the field settings were changed, 0 if they already had the desired
  2575. * values. FALSE on failure.
  2576. */
  2577. function search_api_index_edit_fields($id, array $fields) {
  2578. $index = search_api_index_load($id, TRUE);
  2579. $options = $index->options;
  2580. $options['fields'] = $fields;
  2581. $ret = $index->update(array('options' => $options));
  2582. return $ret ? 1 : $ret;
  2583. }
  2584. /**
  2585. * Enables a search index.
  2586. *
  2587. * @param string|int $id
  2588. * The ID or machine name of the index to enable.
  2589. *
  2590. * @return int|false
  2591. * 1 on success, 0 or FALSE on failure.
  2592. *
  2593. * @throws SearchApiException
  2594. * If the index's server doesn't exist.
  2595. */
  2596. function search_api_index_enable($id) {
  2597. $index = search_api_index_load($id, TRUE);
  2598. $ret = $index->update(array('enabled' => 1));
  2599. return $ret ? 1 : $ret;
  2600. }
  2601. /**
  2602. * Disables a search index.
  2603. *
  2604. * @param string|int $id
  2605. * The ID or machine name of the index to disable.
  2606. *
  2607. * @return int|false
  2608. * 1 on success, 0 or FALSE on failure.
  2609. *
  2610. * @throws SearchApiException
  2611. * If the index's server doesn't exist.
  2612. */
  2613. function search_api_index_disable($id) {
  2614. $index = search_api_index_load($id, TRUE);
  2615. $ret = $index->update(array('enabled' => 0));
  2616. return $ret ? 1 : $ret;
  2617. }
  2618. /**
  2619. * Schedules a search index for re-indexing.
  2620. *
  2621. * @param $id
  2622. * The ID or machine name of the index to re-index.
  2623. *
  2624. * @return bool
  2625. * TRUE on success, FALSE on failure.
  2626. */
  2627. function search_api_index_reindex($id) {
  2628. $index = search_api_index_load($id);
  2629. return $index->reindex();
  2630. }
  2631. /**
  2632. * Helper method for marking all items on an index as needing re-indexing.
  2633. *
  2634. * @param SearchApiIndex $index
  2635. * The index whose items should be re-indexed.
  2636. */
  2637. function _search_api_index_reindex(SearchApiIndex $index) {
  2638. $index->datasource()->trackItemChange(FALSE, array($index), TRUE);
  2639. }
  2640. /**
  2641. * Clears a search index and schedules all of its items for re-indexing.
  2642. *
  2643. * @param $id
  2644. * The ID or machine name of the index to clear.
  2645. *
  2646. * @return bool
  2647. * TRUE on success, FALSE on failure.
  2648. */
  2649. function search_api_index_clear($id) {
  2650. $index = search_api_index_load($id);
  2651. return $index->clear();
  2652. }
  2653. /**
  2654. * Deletes a search index.
  2655. *
  2656. * @param $id
  2657. * The ID or machine name of the index to delete.
  2658. *
  2659. * @return bool
  2660. * TRUE on success, FALSE on failure.
  2661. */
  2662. function search_api_index_delete($id) {
  2663. $index = search_api_index_load($id);
  2664. if (!$index) {
  2665. return FALSE;
  2666. }
  2667. $index->delete();
  2668. return TRUE;
  2669. }
  2670. /**
  2671. * Options list callback for search indexes.
  2672. *
  2673. * @return array
  2674. * An array of search index machine names mapped to their human-readable
  2675. * names.
  2676. */
  2677. function search_api_index_options_list() {
  2678. $ret = array(
  2679. NULL => '- ' . t('All') . ' -',
  2680. );
  2681. foreach (search_api_index_load_multiple(FALSE) as $id => $index) {
  2682. $ret[$id] = $index->name;
  2683. }
  2684. return $ret;
  2685. }
  2686. /**
  2687. * Options list callback for entity types.
  2688. *
  2689. * Will only include entity types which specify entity property information.
  2690. *
  2691. * @return string[]
  2692. * An array of entity type machine names mapped to their human-readable
  2693. * names.
  2694. */
  2695. function search_api_entity_type_options_list() {
  2696. $types = array();
  2697. foreach (array_keys(entity_get_property_info()) as $type) {
  2698. $info = entity_get_info($type);
  2699. if ($info) {
  2700. $types[$type] = $info['label'];
  2701. }
  2702. }
  2703. return $types;
  2704. }
  2705. /**
  2706. * Options list callback for entity type bundles.
  2707. *
  2708. * Will include all bundles for all entity types which specify entity property
  2709. * information, in a format combining both entity type and bundle.
  2710. *
  2711. * @return string[]
  2712. * An array of bundle identifiers mapped to their human-readable names.
  2713. */
  2714. function search_api_combined_bundle_options_list() {
  2715. $types = array();
  2716. foreach (array_keys(entity_get_property_info()) as $type) {
  2717. $info = entity_get_info($type);
  2718. if (!empty($info['bundles'])) {
  2719. foreach ($info['bundles'] as $bundle => $bundle_info) {
  2720. $types["$type:$bundle"] = $bundle_info['label'];
  2721. }
  2722. }
  2723. }
  2724. return $types;
  2725. }
  2726. /**
  2727. * Retrieves a human-readable label for a multi-type index item.
  2728. *
  2729. * Provided as a non-object alternative to
  2730. * SearchApiCombinedEntityDataSourceController::getItemLabel() so it can be used
  2731. * as a getter callback.
  2732. *
  2733. * @param object $item
  2734. * An item of the "multiple" item type.
  2735. *
  2736. * @return string|null
  2737. * Either a human-readable label for the item, or NULL if none is available.
  2738. */
  2739. function search_api_get_multi_type_item_label($item) {
  2740. $label = entity_label($item->item_type, $item->{$item->item_type});
  2741. return $label ? $label : NULL;
  2742. }
  2743. /**
  2744. * Shutdown function which indexes all queued items, if any.
  2745. */
  2746. function _search_api_index_queued_items() {
  2747. $queue = &search_api_index_specific_items_delayed();
  2748. try {
  2749. if ($queue) {
  2750. $indexes = search_api_index_load_multiple(array_keys($queue));
  2751. foreach ($indexes as $index_id => $index) {
  2752. search_api_index_specific_items($index, $queue[$index_id]);
  2753. }
  2754. }
  2755. // Reset the queue so we don't index the items twice by accident.
  2756. $queue = array();
  2757. }
  2758. catch (SearchApiException $e) {
  2759. watchdog_exception('search_api', $e);
  2760. }
  2761. }
  2762. /**
  2763. * Helper function to be used as a "property info alter" callback.
  2764. *
  2765. * If a wrapped entity is passed to this function, all its available properties
  2766. * and fields, regardless of bundle, are added to the wrapper.
  2767. */
  2768. function _search_api_wrapper_add_all_properties(EntityMetadataWrapper $wrapper, array $property_info) {
  2769. if ($properties = entity_get_all_property_info($wrapper->type())) {
  2770. $property_info['properties'] = $properties;
  2771. }
  2772. return $property_info;
  2773. }
  2774. /**
  2775. * Helper function for converting data to a custom type.
  2776. */
  2777. function _search_api_convert_custom_type($callback, $value, $original_type, $type, $nesting_level) {
  2778. if ($nesting_level == 0) {
  2779. return call_user_func($callback, $value, $original_type, $type);
  2780. }
  2781. if (!is_array($value)) {
  2782. return NULL;
  2783. }
  2784. --$nesting_level;
  2785. $values = array();
  2786. foreach ($value as $v) {
  2787. $v = _search_api_convert_custom_type($callback, $v, $original_type, $type, $nesting_level);
  2788. if (isset($v) && !(is_array($v) && !$v)) {
  2789. $values[] = $v;
  2790. }
  2791. }
  2792. return $values;
  2793. }
  2794. /**
  2795. * Determines the number of items indexed on a server for a certain index.
  2796. *
  2797. * Used as a helper function in search_api_admin_index_view().
  2798. *
  2799. * @param SearchApiIndex $index
  2800. * The index
  2801. *
  2802. * @return int
  2803. * The number of items found on the server for this index, if the latter is
  2804. * enabled. 0 otherwise.
  2805. *
  2806. * @throws SearchApiException
  2807. * If an error prevented the search from completing.
  2808. */
  2809. function _search_api_get_items_on_server(SearchApiIndex $index) {
  2810. if (!$index->enabled) {
  2811. return 0;
  2812. }
  2813. // We want the raw count, without facets or other filters. Therefore we don't
  2814. // use the query's execute() method but pass it straight to the server for
  2815. // evaluation. Since this circumvents the normal preprocessing, which sets the
  2816. // fields (on which some service classes might even rely when there are no
  2817. // keywords), we set them manually here.
  2818. $query = $index->query()
  2819. ->fields(array())
  2820. ->range(0, 0);
  2821. $response = $index->server()->search($query);
  2822. return $response['result count'];
  2823. }
  2824. /**
  2825. * Returns a deep copy of the input array.
  2826. *
  2827. * The behavior of PHP regarding arrays with references pointing to it is rather
  2828. * weird. Therefore, we use this helper function in theme_search_api_index() to
  2829. * create safe copies of such arrays.
  2830. *
  2831. * @param array $array
  2832. * The array to copy.
  2833. *
  2834. * @return array
  2835. * A deep copy of the array.
  2836. */
  2837. function _search_api_deep_copy(array $array) {
  2838. $copy = array();
  2839. foreach ($array as $k => $v) {
  2840. if (is_array($v)) {
  2841. $copy[$k] = _search_api_deep_copy($v);
  2842. }
  2843. elseif (is_object($v)) {
  2844. $copy[$k] = clone $v;
  2845. }
  2846. elseif ($v) {
  2847. $copy[$k] = $v;
  2848. }
  2849. }
  2850. return $copy;
  2851. }
  2852. /**
  2853. * Reacts to a change in the bundle of an entity.
  2854. *
  2855. * Used as a helper function in search_api_entity_update().
  2856. *
  2857. * @param $type
  2858. * The entity's type.
  2859. * @param $id
  2860. * The entity's ID.
  2861. * @param $old_bundle
  2862. * The entity's previous bundle.
  2863. * @param $new_bundle
  2864. * The entity's new bundle.
  2865. */
  2866. function _search_api_entity_datasource_bundle_change($type, $id, $old_bundle, $new_bundle) {
  2867. $controller = search_api_get_datasource_controller($type);
  2868. $conditions = array(
  2869. 'enabled' => 1,
  2870. 'item_type' => $type,
  2871. 'read_only' => 0,
  2872. );
  2873. foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
  2874. if (!empty($index->options['datasource']['bundles'])) {
  2875. $bundles = drupal_map_assoc($index->options['datasource']['bundles']);
  2876. if (empty($bundles[$new_bundle]) != empty($bundles[$old_bundle])) {
  2877. if (empty($bundles[$new_bundle])) {
  2878. $controller->trackItemDelete(array($id), array($index));
  2879. }
  2880. else {
  2881. $controller->trackItemInsert(array($id), array($index));
  2882. }
  2883. }
  2884. }
  2885. }
  2886. }
  2887. /**
  2888. * Creates and sets a batch for indexing items.
  2889. *
  2890. * @param SearchApiIndex $index
  2891. * The index for which items should be indexed.
  2892. * @param int $batch_size
  2893. * Number of items to index per batch.
  2894. * @param int $limit
  2895. * Maximum number of items to index. Negative values mean "no limit".
  2896. * @param int $remaining
  2897. * Remaining items to index.
  2898. * @param bool $drush
  2899. * Boolean specifying whether this was called from drush or not.
  2900. *
  2901. * @return bool
  2902. * Whether the batch was created and set successfully.
  2903. */
  2904. function _search_api_batch_indexing_create(SearchApiIndex $index, $batch_size, $limit, $remaining, $drush = FALSE) {
  2905. if ($limit !== 0 && $batch_size !== 0) {
  2906. $t = !empty($drush) ? 'dt' : 't';
  2907. if ($limit < 0 || $limit > $remaining) {
  2908. $limit = $remaining;
  2909. }
  2910. if ($batch_size < 0) {
  2911. $batch_size = $remaining;
  2912. }
  2913. $batch = array(
  2914. 'title' => $t('Indexing items'),
  2915. 'operations' => array(
  2916. array('_search_api_batch_indexing_callback', array($index, $batch_size, $limit, $drush)),
  2917. ),
  2918. 'progress_message' => $t('Completed about @percentage% of the indexing operation.'),
  2919. 'finished' => '_search_api_batch_indexing_finished',
  2920. 'file' => drupal_get_path('module', 'search_api') . '/search_api.module',
  2921. );
  2922. batch_set($batch);
  2923. return TRUE;
  2924. }
  2925. return FALSE;
  2926. }
  2927. /**
  2928. * Batch API callback for the indexing functionality.
  2929. *
  2930. * @param SearchApiIndex $index
  2931. * The index for which items should be indexed.
  2932. * @param integer $batch_size
  2933. * Number of items to index per batch.
  2934. * @param integer $limit
  2935. * Maximum number of items to index.
  2936. * @param boolean $drush
  2937. * Boolean specifying whether this was called from drush or not.
  2938. * @param $context
  2939. * An array (or object implementing ArrayAccess) containing the batch context.
  2940. */
  2941. function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, $limit, $drush = FALSE, &$context) {
  2942. // Persistent data among batch runs.
  2943. if (!isset($context['sandbox']['limit'])) {
  2944. $context['sandbox']['limit'] = $limit;
  2945. $context['sandbox']['batch_size'] = $batch_size;
  2946. $context['sandbox']['progress'] = 0;
  2947. }
  2948. // Persistent data for results.
  2949. if (!isset($context['results']['indexed'])) {
  2950. $context['results']['indexed'] = 0;
  2951. $context['results']['not indexed'] = 0;
  2952. $context['results']['drush'] = $drush;
  2953. }
  2954. // Number of items to index for this run.
  2955. $to_index = min($context['sandbox']['limit'] - $context['sandbox']['progress'], $context['sandbox']['batch_size']);
  2956. // Index the items.
  2957. try {
  2958. $indexed = search_api_index_items($index, $to_index);
  2959. $context['results']['indexed'] += $indexed;
  2960. }
  2961. catch (SearchApiException $e) {
  2962. watchdog_exception('search_api', $e);
  2963. $vars['@message'] = $e->getMessage();
  2964. $context['message'] = t('An error occurred during indexing: @message.', $vars);
  2965. $context['finished'] = 1;
  2966. $context['results']['not indexed'] += $context['sandbox']['limit'] - $context['sandbox']['progress'];
  2967. return;
  2968. }
  2969. // Display progress message.
  2970. if ($indexed > 0) {
  2971. $format_plural = $context['results']['drush'] === TRUE ? '_search_api_drush_format_plural' : 'format_plural';
  2972. $context['message'] = $format_plural($context['results']['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.');
  2973. }
  2974. // Some items couldn't be indexed.
  2975. if ($indexed !== $to_index) {
  2976. $context['results']['not indexed'] += $to_index - $indexed;
  2977. }
  2978. $context['sandbox']['progress'] += $to_index;
  2979. // Everything has been indexed.
  2980. if ($indexed === 0 || $context['sandbox']['progress'] >= $context['sandbox']['limit']) {
  2981. $context['finished'] = 1;
  2982. }
  2983. else {
  2984. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['limit'];
  2985. }
  2986. }
  2987. /**
  2988. * Batch API finishing callback for the indexing functionality.
  2989. *
  2990. * @param boolean $success
  2991. * Whether the batch finished successfully.
  2992. * @param array $results
  2993. * Detailed information about the result.
  2994. */
  2995. function _search_api_batch_indexing_finished($success, $results) {
  2996. // Check if called from drush.
  2997. if (!empty($results['drush'])) {
  2998. $drupal_set_message = 'drush_log';
  2999. $format_plural = '_search_api_drush_format_plural';
  3000. $t = 'dt';
  3001. $success_message = 'success';
  3002. }
  3003. else {
  3004. $drupal_set_message = 'drupal_set_message';
  3005. $format_plural = 'format_plural';
  3006. $t = 't';
  3007. $success_message = 'status';
  3008. }
  3009. // Display result messages.
  3010. if ($success) {
  3011. if (!empty($results['indexed'])) {
  3012. $drupal_set_message($format_plural($results['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.'), $success_message);
  3013. if (!empty($results['not indexed'])) {
  3014. $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');
  3015. }
  3016. }
  3017. else {
  3018. $drupal_set_message($t("Couldn't index items. Check the logs for details."), 'error');
  3019. }
  3020. }
  3021. else {
  3022. $drupal_set_message($t("An error occurred while trying to index items. Check the logs for details."), 'error');
  3023. }
  3024. }