search_api.module 106 KB

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