search_api.module 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  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' || !module_exists($file->name)) {
  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_porter_stemmer'] = array(
  1098. 'name' => t('Stem words'),
  1099. 'description' => t('This processor reduces words to a stem (e.g., "talking" to "talk"). For best results, it should only be executed after tokenizing.'),
  1100. 'class' => 'SearchApiPorterStemmer',
  1101. 'weight' => 35,
  1102. );
  1103. $processors['search_api_highlighting'] = array(
  1104. 'name' => t('Highlighting'),
  1105. 'description' => t('Adds highlighting for search results.'),
  1106. 'class' => 'SearchApiHighlight',
  1107. 'weight' => 40,
  1108. );
  1109. return $processors;
  1110. }
  1111. /**
  1112. * Inserts new unindexed items for all indexes on the specified type.
  1113. *
  1114. * @param string $type
  1115. * The item type of the new items.
  1116. * @param array $item_ids
  1117. * The IDs of the new items.
  1118. */
  1119. function search_api_track_item_insert($type, array $item_ids) {
  1120. $conditions = array(
  1121. 'enabled' => 1,
  1122. 'item_type' => $type,
  1123. 'read_only' => 0,
  1124. );
  1125. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1126. if (!$indexes) {
  1127. return;
  1128. }
  1129. try {
  1130. $returned_indexes = search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
  1131. if (isset($returned_indexes)) {
  1132. $indexes = $returned_indexes;
  1133. }
  1134. }
  1135. catch (SearchApiException $e) {
  1136. $vars['%item_type'] = $type;
  1137. watchdog_exception('search_api', $e, '%type while inserting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1138. return;
  1139. }
  1140. foreach ($indexes as $index) {
  1141. if (!empty($index->options['index_directly'])) {
  1142. search_api_index_specific_items_delayed($index, $item_ids);
  1143. }
  1144. }
  1145. }
  1146. /**
  1147. * Mark the items with the specified IDs as "dirty", i.e., as needing to be reindexed.
  1148. *
  1149. * For indexes for which items should be indexed immediately, the items are
  1150. * indexed directly, instead.
  1151. *
  1152. * @param $type
  1153. * The type of items, specific to the data source.
  1154. * @param array $item_ids
  1155. * The IDs of the items to be marked dirty.
  1156. */
  1157. function search_api_track_item_change($type, array $item_ids) {
  1158. $conditions = array(
  1159. 'enabled' => 1,
  1160. 'item_type' => $type,
  1161. 'read_only' => 0,
  1162. );
  1163. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1164. if (!$indexes) {
  1165. return;
  1166. }
  1167. search_api_track_item_change_for_indexes($type, $item_ids, $indexes);
  1168. }
  1169. /**
  1170. * Marks the items with the specified IDs as "dirty" for the given indexes.
  1171. *
  1172. * @param string $type
  1173. * The item type of the items.
  1174. * @param array $item_ids
  1175. * The item IDs.
  1176. * @param SearchApiIndex[] $indexes
  1177. * The indexes for which to mark the items as "dirty".
  1178. */
  1179. function search_api_track_item_change_for_indexes($type, array $item_ids, $indexes) {
  1180. try {
  1181. $returned_indexes = search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
  1182. if (isset($returned_indexes)) {
  1183. $indexes = $returned_indexes;
  1184. }
  1185. foreach ($indexes as $index) {
  1186. if (!empty($index->options['index_directly'])) {
  1187. // For indexes with the index_directly option set, queue the items to be
  1188. // indexed at the end of the request.
  1189. try {
  1190. search_api_index_specific_items_delayed($index, $item_ids);
  1191. }
  1192. catch (SearchApiException $e) {
  1193. watchdog_exception('search_api', $e);
  1194. }
  1195. }
  1196. }
  1197. }
  1198. catch (SearchApiException $e) {
  1199. $vars['%item_type'] = $type;
  1200. watchdog_exception('search_api', $e, '%type while updating items of type %item_type: !message in %function (line %line of %file).', $vars);
  1201. }
  1202. }
  1203. /**
  1204. * Marks items as queued for indexing for the specified index.
  1205. *
  1206. * @param SearchApiIndex $index
  1207. * The index on which items were queued.
  1208. * @param array $item_ids
  1209. * The ids of the queued items.
  1210. *
  1211. * @deprecated
  1212. * As of Search API 1.10, the cron queue is not used for indexing anymore,
  1213. * therefore this function has become useless. It will, along with
  1214. * SearchApiDataSourceControllerInterface::trackItemQueued(), be removed in
  1215. * the Drupal 8 version of this module.
  1216. */
  1217. function search_api_track_item_queued(SearchApiIndex $index, array $item_ids) {
  1218. try {
  1219. $index->datasource()->trackItemQueued($item_ids, $index);
  1220. }
  1221. catch (SearchApiException $e) {
  1222. watchdog_exception('search_api', $e);
  1223. }
  1224. }
  1225. /**
  1226. * Marks items as successfully indexed for the specified index.
  1227. *
  1228. * @param SearchApiIndex $index
  1229. * The index on which items were indexed.
  1230. * @param array $item_ids
  1231. * The ids of the indexed items.
  1232. */
  1233. function search_api_track_item_indexed(SearchApiIndex $index, array $item_ids) {
  1234. $index->datasource()->trackItemIndexed($item_ids, $index);
  1235. module_invoke_all('search_api_items_indexed', $index, $item_ids);
  1236. }
  1237. /**
  1238. * Removes items from all indexes.
  1239. *
  1240. * @param $type
  1241. * The type of the items.
  1242. * @param array $item_ids
  1243. * The IDs of the deleted items.
  1244. */
  1245. function search_api_track_item_delete($type, array $item_ids) {
  1246. // First, delete the item from the tracking table.
  1247. $conditions = array(
  1248. 'enabled' => 1,
  1249. 'item_type' => $type,
  1250. 'read_only' => 0,
  1251. );
  1252. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1253. if ($indexes) {
  1254. try {
  1255. $changed_indexes = search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
  1256. if (isset($changed_indexes)) {
  1257. $indexes = $changed_indexes;
  1258. }
  1259. }
  1260. catch (SearchApiException $e) {
  1261. $vars['%item_type'] = $type;
  1262. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1263. }
  1264. }
  1265. // Then, delete it from all servers. Servers of disabled indexes have to be
  1266. // considered, too!
  1267. $conditions['enabled'] = 0;
  1268. $indexes = array_merge($indexes, search_api_index_load_multiple(FALSE, $conditions));
  1269. foreach ($indexes as $index) {
  1270. try {
  1271. if ($server = $index->server()) {
  1272. $server->deleteItems($item_ids, $index);
  1273. }
  1274. }
  1275. catch (Exception $e) {
  1276. $vars['%item_type'] = $type;
  1277. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1278. }
  1279. }
  1280. }
  1281. /**
  1282. * Checks for pending tasks on one or all enabled search servers.
  1283. *
  1284. * @param SearchApiServer|null $server
  1285. * (optional) The server whose tasks should be checked. If not given, the
  1286. * tasks for all enabled servers are checked.
  1287. *
  1288. * @return bool
  1289. * TRUE if all tasks (for the specific server, if $server was given) were
  1290. * executed successfully, or if there were no tasks. FALSE if there are still
  1291. * pending tasks.
  1292. */
  1293. function search_api_server_tasks_check(SearchApiServer $server = NULL) {
  1294. $select = db_select('search_api_task', 't')
  1295. ->fields('t')
  1296. // Only retrieve tasks we can handle.
  1297. ->condition('t.type', array('addIndex', 'fieldsUpdated', 'removeIndex', 'deleteItems'));
  1298. if ($server) {
  1299. $select->condition('t.server_id', $server->machine_name);
  1300. }
  1301. else {
  1302. $select->innerJoin('search_api_server', 's', 't.server_id = s.machine_name AND s.enabled = 1');
  1303. // By ordering by the server, we can later just load them when we reach them
  1304. // while looping through the tasks. It is very unlikely there will be tasks
  1305. // for more than one or two servers, so a *_load_multiple() probably
  1306. // wouldn't bring any significant advantages, but complicate the code.
  1307. $select->orderBy('t.server_id');
  1308. }
  1309. // Store a count query for later checking whether all tasks were processed
  1310. // successfully.
  1311. $count_query = $select->countQuery();
  1312. // Sometimes the order of tasks might be important, so make sure to order by
  1313. // the task ID (which should be in order of insertion).
  1314. $select->orderBy('t.id');
  1315. $tasks = $select->execute();
  1316. $executed_tasks = array();
  1317. foreach ($tasks as $task) {
  1318. if (!$server || $server->machine_name != $task->server_id) {
  1319. $server = search_api_server_load($task->server_id);
  1320. if (!$server) {
  1321. continue;
  1322. }
  1323. }
  1324. switch ($task->type) {
  1325. case 'addIndex':
  1326. $index = search_api_index_load($task->index_id);
  1327. if ($index) {
  1328. $server->addIndex($index);
  1329. }
  1330. break;
  1331. case 'fieldsUpdated':
  1332. $index = search_api_index_load($task->index_id);
  1333. if ($index) {
  1334. if ($task->data) {
  1335. $index->original = unserialize($task->data);
  1336. }
  1337. $server->fieldsUpdated($index);
  1338. }
  1339. break;
  1340. case 'removeIndex':
  1341. $index = search_api_index_load($task->index_id);
  1342. if ($index) {
  1343. $server->removeIndex($index ? $index : $task->index_id);
  1344. }
  1345. break;
  1346. case 'deleteItems':
  1347. $ids = $task->data ? unserialize($task->data) : 'all';
  1348. $index = $task->index_id ? search_api_index_load($task->index_id) : NULL;
  1349. // Since a failed load returns (for stupid menu handler reasons) FALSE,
  1350. // not NULL, we have to make doubly sure here not to pass an invalid
  1351. // value (and cause a fatal error).
  1352. $index = $index ? $index : NULL;
  1353. $server->deleteItems($ids, $index);
  1354. break;
  1355. default:
  1356. // This should never happen.
  1357. continue;
  1358. }
  1359. $executed_tasks[] = $task->id;
  1360. }
  1361. // If there were no tasks (we recognized), return TRUE.
  1362. if (!$executed_tasks) {
  1363. return TRUE;
  1364. }
  1365. // Otherwise, delete the executed tasks and check if new tasks were created.
  1366. search_api_server_tasks_delete($executed_tasks);
  1367. return $count_query->execute()->fetchField() === 0;
  1368. }
  1369. /**
  1370. * Adds an entry into a server's list of pending tasks.
  1371. *
  1372. * @param SearchApiServer $server
  1373. * The server for which a task should be remembered.
  1374. * @param $type
  1375. * The type of task to perform.
  1376. * @param SearchApiIndex|string|null $index
  1377. * (optional) If applicable, the index to which the task pertains (or its
  1378. * machine name).
  1379. * @param mixed $data
  1380. * (optional) If applicable, some further data necessary for the task.
  1381. */
  1382. function search_api_server_tasks_add(SearchApiServer $server, $type, $index = NULL, $data = NULL) {
  1383. db_insert('search_api_task')
  1384. ->fields(array(
  1385. 'server_id' => $server->machine_name,
  1386. 'type' => $type,
  1387. 'index_id' => $index ? (is_object($index) ? $index->machine_name : $index) : NULL,
  1388. 'data' => isset($data) ? serialize($data) : NULL,
  1389. ))
  1390. ->execute();
  1391. }
  1392. /**
  1393. * Removes pending server tasks from the list.
  1394. *
  1395. * @param array|null $ids
  1396. * (optional) The IDs of the pending server tasks to delete. Set to NULL
  1397. * to not filter by IDs.
  1398. * @param SearchApiServer|null $server
  1399. * (optional) A server for which the tasks should be deleted. Set to NULL to
  1400. * delete tasks from all servers.
  1401. * @param SearchApiIndex|string|null $index
  1402. * (optional) An index (or its machine name) for which the tasks should be
  1403. * deleted. Set to NULL to delete tasks for all indexes.
  1404. */
  1405. function search_api_server_tasks_delete(array $ids = NULL, SearchApiServer $server = NULL, $index = NULL) {
  1406. $delete = db_delete('search_api_task');
  1407. if ($ids) {
  1408. $delete->condition('id', $ids);
  1409. }
  1410. if ($server) {
  1411. $delete->condition('server_id', $server->machine_name);
  1412. }
  1413. if ($index) {
  1414. $delete->condition('index_id', $index->machine_name);
  1415. }
  1416. $delete->execute();
  1417. }
  1418. /**
  1419. * Recalculates the saved fields of an index.
  1420. *
  1421. * This is mostly necessary when the multiplicity of the underlying properties
  1422. * change. The method will re-examine the data structure of the entities in each
  1423. * index and, if a discrepancy is spotted, re-save that index with updated
  1424. * fields options (thus, of course, also triggering a re-indexing operation).
  1425. *
  1426. * @param SearchApiIndex[]|false $indexes
  1427. * An array of SearchApiIndex objects on which to perform the operation, or
  1428. * FALSE to perform it on all indexes.
  1429. */
  1430. function search_api_index_recalculate_fields($indexes = FALSE) {
  1431. if (!is_array($indexes)) {
  1432. $indexes = search_api_index_load_multiple(FALSE);
  1433. }
  1434. $stored_keys = drupal_map_assoc(array('type', 'entity_type', 'real_type', 'boost'));
  1435. foreach ($indexes as $index) {
  1436. if (empty($index->options['fields'])) {
  1437. continue;
  1438. }
  1439. // We have to clear the cache, both static and stored, before using
  1440. // getFields(). Otherwise, we'd just use the stale data which the fields
  1441. // options are probably already based on.
  1442. cache_clear_all($index->getCacheId() . '-1-0', 'cache');
  1443. $index->resetCaches();
  1444. // getFields() automatically uses the actual data types to correct possible
  1445. // stale data.
  1446. $fields = $index->getFields();
  1447. foreach ($fields as $key => $field) {
  1448. $fields[$key] = array_intersect_key($field, $stored_keys);
  1449. if (isset($fields[$key]['boost']) && $fields[$key]['boost'] == '1.0') {
  1450. unset($fields[$key]['boost']);
  1451. }
  1452. }
  1453. // Use a more accurate method of determining if the fields settings are
  1454. // equal to avoid needlessly re-indexing the whole index.
  1455. if ($fields != $index->options['fields']) {
  1456. $options = $index->options;
  1457. $options['fields'] = $fields;
  1458. $index->update(array('options' => $options));
  1459. }
  1460. }
  1461. }
  1462. /**
  1463. * Test two setting arrays (or individual settings) for equality.
  1464. *
  1465. * @param mixed $setting1
  1466. * The first setting (array).
  1467. * @param mixed $setting2
  1468. * The second setting (array).
  1469. *
  1470. * @return bool
  1471. * TRUE if both settings are identical, FALSE otherwise.
  1472. *
  1473. * @deprecated The simple "==" operator will achieve the same.
  1474. */
  1475. function _search_api_settings_equals($setting1, $setting2) {
  1476. if (!is_array($setting1) || !is_array($setting2)) {
  1477. return $setting1 == $setting2;
  1478. }
  1479. foreach ($setting1 as $key => $value) {
  1480. if (!array_key_exists($key, $setting2)) {
  1481. return FALSE;
  1482. }
  1483. if (!_search_api_settings_equals($value, $setting2[$key])) {
  1484. return FALSE;
  1485. }
  1486. unset($setting2[$key]);
  1487. }
  1488. // If any keys weren't unset previously, they are not present in $setting1 and
  1489. // the two are different.
  1490. return !$setting2;
  1491. }
  1492. /**
  1493. * Indexes items for the specified index.
  1494. *
  1495. * Only items marked as changed are indexed, in their order of change (if
  1496. * known).
  1497. *
  1498. * @param SearchApiIndex $index
  1499. * The index on which items should be indexed.
  1500. * @param int $limit
  1501. * (optional) The number of items which should be indexed at most. Defaults to
  1502. * -1, which means that all changed items should be indexed.
  1503. *
  1504. * @return int
  1505. * Number of successfully indexed items.
  1506. *
  1507. * @throws SearchApiException
  1508. * If any error occurs during indexing.
  1509. */
  1510. function search_api_index_items(SearchApiIndex $index, $limit = -1) {
  1511. // Don't try to index on read-only indexes.
  1512. if ($index->read_only) {
  1513. return 0;
  1514. }
  1515. $ids = search_api_get_items_to_index($index, $limit);
  1516. return $ids ? count(search_api_index_specific_items($index, $ids)) : 0;
  1517. }
  1518. /**
  1519. * Indexes the specified items on the given index.
  1520. *
  1521. * Items which were successfully indexed are marked as such afterwards.
  1522. *
  1523. * @param SearchApiIndex $index
  1524. * The index on which items should be indexed.
  1525. * @param array $ids
  1526. * The IDs of the items which should be indexed.
  1527. *
  1528. * @return array
  1529. * The IDs of all successfully indexed items.
  1530. *
  1531. * @throws SearchApiException
  1532. * If any error occurs during indexing.
  1533. */
  1534. function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
  1535. // Before doing anything else, check whether there are pending tasks that need
  1536. // to be executed on the server. It might be important that they are executed
  1537. // before any indexing occurs.
  1538. if (!search_api_server_tasks_check($index->server())) {
  1539. throw new SearchApiException(t('Could not index items since important pending server tasks could not be performed.'));
  1540. }
  1541. $items = $index->loadItems($ids);
  1542. // Clone items because data alterations may alter them.
  1543. $cloned_items = array();
  1544. foreach ($items as $id => $item) {
  1545. if (is_object($item)) {
  1546. $cloned_items[$id] = clone $item;
  1547. }
  1548. else {
  1549. // Normally, items that can't be loaded shouldn't be returned by
  1550. // entity_load (and other loadItems() implementations). Therefore, this is
  1551. // an extremely rare case, which seems to happen during installation for
  1552. // some specific setups.
  1553. $type = search_api_get_item_type_info($index->item_type);
  1554. $type = $type ? $type['name'] : $index->item_type;
  1555. watchdog('search_api', "Error during indexing: invalid item loaded for @type with ID @id.", array('@id' => $id, '@type' => $type), WATCHDOG_WARNING);
  1556. }
  1557. }
  1558. $indexed = $items ? $index->index($cloned_items) : array();
  1559. if ($indexed) {
  1560. search_api_track_item_indexed($index, $indexed);
  1561. // If some items could not be indexed, we don't want to try re-indexing
  1562. // them right away, so we mark them as "freshly" changed. Sadly, there is
  1563. // no better way than to mark them as indexed first...
  1564. if (count($indexed) < count($ids)) {
  1565. // Believe it or not but this is actually quite faster than the equivalent
  1566. // $diff = array_diff($ids, $indexed);
  1567. $diff = array_keys(array_diff_key(array_flip($ids), array_flip($indexed)));
  1568. $index->datasource()->trackItemIndexed($diff, $index);
  1569. $index->datasource()->trackItemChange($diff, array($index));
  1570. }
  1571. }
  1572. return $indexed;
  1573. }
  1574. /**
  1575. * Queues items for indexing at the end of the page request.
  1576. *
  1577. * @param SearchApiIndex $index
  1578. * The index on which items should be indexed.
  1579. * @param array $ids
  1580. * The IDs of the items which should be indexed.
  1581. *
  1582. * @return array
  1583. * The current contents of the queue, as a reference.
  1584. *
  1585. * @see search_api_index_specific_items()
  1586. * @see _search_api_index_queued_items()
  1587. */
  1588. function &search_api_index_specific_items_delayed(SearchApiIndex $index = NULL, array $ids = array()) {
  1589. // We cannot use drupal_static() here because the static cache is reset during
  1590. // batch processing, which breaks batch handling.
  1591. static $queue = array();
  1592. static $registered = FALSE;
  1593. // Only register the shutdown function once.
  1594. if (empty($registered)) {
  1595. drupal_register_shutdown_function('_search_api_index_queued_items');
  1596. $registered = TRUE;
  1597. }
  1598. // Allow for empty call to just retrieve the queue.
  1599. if ($index && $ids) {
  1600. $index_id = $index->machine_name;
  1601. $queue += array($index_id => array());
  1602. $queue[$index_id] += drupal_map_assoc($ids);
  1603. }
  1604. return $queue;
  1605. }
  1606. /**
  1607. * Returns a list of items that need to be indexed for the specified index.
  1608. *
  1609. * @param SearchApiIndex $index
  1610. * The index for which items should be retrieved.
  1611. * @param $limit
  1612. * The maximum number of items to retrieve. -1 means no limit.
  1613. *
  1614. * @return array
  1615. * An array of IDs of items that need to be indexed.
  1616. */
  1617. function search_api_get_items_to_index(SearchApiIndex $index, $limit = -1) {
  1618. if ($limit == 0) {
  1619. return array();
  1620. }
  1621. return $index->datasource()->getChangedItems($index, $limit);
  1622. }
  1623. /**
  1624. * Creates a search query on a specified search index.
  1625. *
  1626. * @param $id
  1627. * The ID or machine name of the index to execute the search on.
  1628. * @param $options
  1629. * An associative array of options to be passed to
  1630. * SearchApiQueryInterface::__construct().
  1631. *
  1632. * @return SearchApiQueryInterface
  1633. * An object for searching on the specified index.
  1634. *
  1635. * @throws SearchApiException
  1636. * If the index is unknown or disabled, or some other error was encountered.
  1637. */
  1638. function search_api_query($id, array $options = array()) {
  1639. $index = search_api_index_load($id);
  1640. if (!$index) {
  1641. throw new SearchApiException(t('Unknown index with ID @id.', array('@id' => $id)));
  1642. }
  1643. return $index->query($options);
  1644. }
  1645. /**
  1646. * Stores or retrieves a search executed in this page request.
  1647. *
  1648. * Static storage for the searches executed during the current page request. Can
  1649. * used to store an executed search, or to retrieve a previously stored search.
  1650. *
  1651. * @param $search_id
  1652. * For pages displaying multiple searches, an optional ID identifying the
  1653. * search in questions. When storing a search, this is filled automatically,
  1654. * unless it is manually set.
  1655. * @param SearchApiQuery $query
  1656. * When storing an executed search, the query that was executed. NULL
  1657. * otherwise.
  1658. * @param array $results
  1659. * When storing an executed search, the returned results as specified by
  1660. * SearchApiQueryInterface::execute(). An empty array, otherwise.
  1661. *
  1662. * @return array
  1663. * If a search with the specified ID was executed, an array containing
  1664. * ($query, $results) as used in this function's parameters. If $search_id is
  1665. * NULL, an array of all executed searches will be returned, keyed by ID.
  1666. */
  1667. function search_api_current_search($search_id = NULL, SearchApiQuery $query = NULL, array $results = array()) {
  1668. $searches = &drupal_static(__FUNCTION__, array());
  1669. if (isset($query)) {
  1670. if (!isset($search_id)) {
  1671. $search_id = $query->getOption('search id');
  1672. }
  1673. $base = $search_id;
  1674. $i = 0;
  1675. while (isset($searches[$search_id])) {
  1676. $search_id = $base . '-' . ++$i;
  1677. }
  1678. $searches[$search_id] = array($query, $results);
  1679. }
  1680. if (isset($search_id)) {
  1681. return isset($searches[$search_id]) ? $searches[$search_id] : NULL;
  1682. }
  1683. return $searches;
  1684. }
  1685. /**
  1686. * Returns all field types recognized by the Search API framework.
  1687. *
  1688. * @return array
  1689. * An associative array with all recognized types as keys, mapped to their
  1690. * translated display names.
  1691. *
  1692. * @see search_api_default_field_types()
  1693. * @see search_api_get_data_type_info()
  1694. */
  1695. function search_api_field_types() {
  1696. $types = search_api_default_field_types();
  1697. foreach (search_api_get_data_type_info() as $id => $type) {
  1698. $types[$id] = $type['name'];
  1699. }
  1700. return $types;
  1701. }
  1702. /**
  1703. * Returns the default field types recognized by the Search API framework.
  1704. *
  1705. * @return array
  1706. * An associative array with the default types as keys, mapped to their
  1707. * translated display names.
  1708. */
  1709. function search_api_default_field_types() {
  1710. return array(
  1711. 'text' => t('Fulltext'),
  1712. 'string' => t('String'),
  1713. 'integer' => t('Integer'),
  1714. 'decimal' => t('Decimal'),
  1715. 'date' => t('Date'),
  1716. 'duration' => t('Duration'),
  1717. 'boolean' => t('Boolean'),
  1718. 'uri' => t('URI'),
  1719. );
  1720. }
  1721. /**
  1722. * Returns either all custom field type definitions, or a specific one.
  1723. *
  1724. * @param $type
  1725. * If specified, the type whose definition should be returned.
  1726. *
  1727. * @return array
  1728. * If $type was not given, an array containing all custom data types, in the
  1729. * format specified by hook_search_api_data_type_info().
  1730. * Otherwise, the definition for the given type, or NULL if it is unknown.
  1731. *
  1732. * @see hook_search_api_data_type_info()
  1733. */
  1734. function search_api_get_data_type_info($type = NULL) {
  1735. $types = &drupal_static(__FUNCTION__);
  1736. if (!isset($types)) {
  1737. $default_types = search_api_default_field_types();
  1738. $types = module_invoke_all('search_api_data_type_info');
  1739. $types = $types ? $types : array();
  1740. foreach ($types as &$type_info) {
  1741. if (!isset($type_info['fallback']) || !isset($default_types[$type_info['fallback']])) {
  1742. $type_info['fallback'] = 'string';
  1743. }
  1744. }
  1745. drupal_alter('search_api_data_type_info', $types);
  1746. }
  1747. if (isset($type)) {
  1748. return isset($types[$type]) ? $types[$type] : NULL;
  1749. }
  1750. return $types;
  1751. }
  1752. /**
  1753. * Returns either a list of all available service infos, or a specific one.
  1754. *
  1755. * @see hook_search_api_service_info()
  1756. *
  1757. * @param string|null $id
  1758. * The ID of the service info to retrieve.
  1759. *
  1760. * @return array
  1761. * If $id was not specified, an array of all available service classes.
  1762. * Otherwise, either the service info with the specified id (if it exists),
  1763. * or NULL. Service class information is formatted as specified by
  1764. * hook_search_api_service_info(), with the addition of a "module" key
  1765. * specifying the module that adds a certain class.
  1766. */
  1767. function search_api_get_service_info($id = NULL) {
  1768. $services = &drupal_static(__FUNCTION__);
  1769. if (!isset($services)) {
  1770. // Inlined version of module_invoke_all() to add "module" keys.
  1771. $services = array();
  1772. foreach (module_implements('search_api_service_info') as $module) {
  1773. $function = $module . '_search_api_service_info';
  1774. if (function_exists($function)) {
  1775. $new_services = $function();
  1776. if (isset($new_services) && is_array($new_services)) {
  1777. foreach ($new_services as $service => $info) {
  1778. $new_services[$service] += array('module' => $module);
  1779. }
  1780. }
  1781. $services += $new_services;
  1782. }
  1783. }
  1784. // Same for drupal_alter().
  1785. foreach (module_implements('search_api_service_info_alter') as $module) {
  1786. $function = $module . '_search_api_service_info_alter';
  1787. if (function_exists($function)) {
  1788. $old = $services;
  1789. $function($services);
  1790. if ($new_services = array_diff_key($services, $old)) {
  1791. foreach ($new_services as $service => $info) {
  1792. $services[$service] += array('module' => $module);
  1793. }
  1794. }
  1795. }
  1796. }
  1797. }
  1798. if (isset($id)) {
  1799. return isset($services[$id]) ? $services[$id] : NULL;
  1800. }
  1801. return $services;
  1802. }
  1803. /**
  1804. * Returns information for either all item types, or a specific one.
  1805. *
  1806. * @param string|null $type
  1807. * If set, the item type whose information should be returned.
  1808. *
  1809. * @return array|null
  1810. * If $type is given, either an array containing the information of that item
  1811. * type, or NULL if it is unknown. Otherwise, an array keyed by type IDs
  1812. * containing the information for all item types. Item type information is
  1813. * formatted as specified by hook_search_api_item_type_info(), with the
  1814. * addition of a "module" key specifying the module that adds a certain type.
  1815. *
  1816. * @see hook_search_api_item_type_info()
  1817. */
  1818. function search_api_get_item_type_info($type = NULL) {
  1819. $types = &drupal_static(__FUNCTION__);
  1820. if (!isset($types)) {
  1821. // Inlined version of module_invoke_all() to add "module" keys.
  1822. $types = array();
  1823. foreach (module_implements('search_api_item_type_info') as $module) {
  1824. $function = $module . '_search_api_item_type_info';
  1825. if (function_exists($function)) {
  1826. $new_types = $function();
  1827. if (isset($new_types) && is_array($new_types)) {
  1828. foreach ($new_types as $id => $info) {
  1829. $new_types[$id] += array('module' => $module);
  1830. }
  1831. }
  1832. $types += $new_types;
  1833. }
  1834. }
  1835. // Same for drupal_alter().
  1836. foreach (module_implements('search_api_item_type_info_alter') as $module) {
  1837. $function = $module . '_search_api_item_type_info_alter';
  1838. if (function_exists($function)) {
  1839. $old = $types;
  1840. $function($types);
  1841. if ($new_types = array_diff_key($types, $old)) {
  1842. foreach ($new_types as $id => $info) {
  1843. $types[$id] += array('module' => $module);
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. if (isset($type)) {
  1850. return isset($types[$type]) ? $types[$type] : NULL;
  1851. }
  1852. return $types;
  1853. }
  1854. /**
  1855. * Get a data source controller object for the specified type.
  1856. *
  1857. * @param $type
  1858. * The type whose data source controller should be returned.
  1859. *
  1860. * @return SearchApiDataSourceControllerInterface
  1861. * The type's data source controller.
  1862. *
  1863. * @throws SearchApiException
  1864. * If the type is unknown or specifies an invalid data source controller.
  1865. */
  1866. function search_api_get_datasource_controller($type) {
  1867. $datasources = &drupal_static(__FUNCTION__, array());
  1868. if (empty($datasources[$type])) {
  1869. $info = search_api_get_item_type_info($type);
  1870. if (isset($info['datasource controller']) && class_exists($info['datasource controller'])) {
  1871. $datasources[$type] = new $info['datasource controller']($type);
  1872. }
  1873. if (empty($datasources[$type]) || !($datasources[$type] instanceof SearchApiDataSourceControllerInterface)) {
  1874. unset($datasources[$type]);
  1875. throw new SearchApiException(t('Unknown or invalid item type @type.', array('@type' => $type)));
  1876. }
  1877. }
  1878. return $datasources[$type];
  1879. }
  1880. /**
  1881. * Returns a list of all available data alter callbacks.
  1882. *
  1883. * @see hook_search_api_alter_callback_info()
  1884. *
  1885. * @return array
  1886. * An array of all available data alter callbacks, keyed by function name.
  1887. */
  1888. function search_api_get_alter_callbacks() {
  1889. $callbacks = &drupal_static(__FUNCTION__);
  1890. if (!isset($callbacks)) {
  1891. $callbacks = module_invoke_all('search_api_alter_callback_info');
  1892. // Fill optional settings with default values.
  1893. foreach ($callbacks as $id => $callback) {
  1894. $callbacks[$id] += array('weight' => 0);
  1895. }
  1896. // Invoke alter hook.
  1897. drupal_alter('search_api_alter_callback_info', $callbacks);
  1898. }
  1899. return $callbacks;
  1900. }
  1901. /**
  1902. * Returns a list of all available pre- and post-processors.
  1903. *
  1904. * @see hook_search_api_processor_info()
  1905. *
  1906. * @return array
  1907. * An array of all available processors, keyed by id.
  1908. */
  1909. function search_api_get_processors() {
  1910. $processors = &drupal_static(__FUNCTION__);
  1911. if (!isset($processors)) {
  1912. $processors = module_invoke_all('search_api_processor_info');
  1913. // Fill optional settings with default values.
  1914. foreach ($processors as $id => $processor) {
  1915. $processors[$id] += array('weight' => 0);
  1916. }
  1917. // Invoke alter hook.
  1918. drupal_alter('search_api_processor_info', $processors);
  1919. }
  1920. return $processors;
  1921. }
  1922. /**
  1923. * Implements hook_search_api_query_alter().
  1924. *
  1925. * Adds node access to the query, if enabled.
  1926. *
  1927. * @param SearchApiQueryInterface $query
  1928. * The SearchApiQueryInterface object representing the search query.
  1929. */
  1930. function search_api_search_api_query_alter(SearchApiQueryInterface $query) {
  1931. global $user;
  1932. $index = $query->getIndex();
  1933. // Only add node access if the necessary fields are indexed in the index, and
  1934. // unless disabled explicitly by the query.
  1935. $type = $index->getEntityType();
  1936. if (!empty($index->options['data_alter_callbacks']["search_api_alter_{$type}_access"]['status']) && !$query->getOption('search_api_bypass_access')) {
  1937. $account = $query->getOption('search_api_access_account', $user);
  1938. if (is_numeric($account)) {
  1939. $account = user_load($account);
  1940. }
  1941. if (is_object($account)) {
  1942. try {
  1943. _search_api_query_add_node_access($account, $query, $type);
  1944. }
  1945. catch (SearchApiException $e) {
  1946. watchdog_exception('search_api', $e);
  1947. }
  1948. }
  1949. else {
  1950. $account = $query->getOption('search_api_access_account', '(' . t('none') . ')');
  1951. if (is_object($account)) {
  1952. $account = $account->uid;
  1953. }
  1954. if (!is_scalar($account)) {
  1955. $account = var_export($account, TRUE);
  1956. }
  1957. watchdog('search_api', 'An illegal user UID was given for node access: @uid.', array('@uid' => $account), WATCHDOG_WARNING);
  1958. }
  1959. }
  1960. }
  1961. /**
  1962. * Adds a node access filter to a search query, if applicable.
  1963. *
  1964. * @param object $account
  1965. * The user object, who searches.
  1966. * @param SearchApiQueryInterface $query
  1967. * The query to which a node access filter should be added, if applicable.
  1968. * @param string $type
  1969. * (optional) The type of search – either "node" or "comment". Defaults to
  1970. * "node".
  1971. *
  1972. * @throws SearchApiException
  1973. * If not all necessary fields are indexed on the index.
  1974. */
  1975. function _search_api_query_add_node_access($account, SearchApiQueryInterface $query, $type = 'node') {
  1976. // Don't do anything if the user can access all content.
  1977. if (user_access('bypass node access', $account)) {
  1978. return;
  1979. }
  1980. $is_comment = ($type == 'comment');
  1981. // Check whether the necessary fields are indexed.
  1982. $fields = $query->getIndex()->options['fields'];
  1983. $required = array('search_api_access_node', 'status');
  1984. if (!$is_comment) {
  1985. $required[] = 'author';
  1986. }
  1987. foreach ($required as $field) {
  1988. if (empty($fields[$field])) {
  1989. $vars['@field'] = $field;
  1990. $vars['@index'] = $query->getIndex()->name;
  1991. throw new SearchApiException(t('Required field @field not indexed on index @index. Could not perform access checks.', $vars));
  1992. }
  1993. }
  1994. // If the user cannot access content/comments at all, return no results.
  1995. if (!user_access('access content', $account) || ($is_comment && !user_access('access comments', $account))) {
  1996. // Simple hack for returning no results.
  1997. $query->condition('status', 0);
  1998. $query->condition('status', 1);
  1999. watchdog('search_api', 'User @name tried to execute a search, but cannot access content.', array('@name' => theme('username', array('account' => $account))), WATCHDOG_NOTICE);
  2000. return;
  2001. }
  2002. // Filter by the "published" status.
  2003. $published = $is_comment ? COMMENT_PUBLISHED : NODE_PUBLISHED;
  2004. if (!$is_comment && user_access('view own unpublished content')) {
  2005. $filter = $query->createFilter('OR');
  2006. $filter->condition('status', $published);
  2007. $filter->condition('author', $account->uid);
  2008. $query->filter($filter);
  2009. }
  2010. else {
  2011. $query->condition('status', $published);
  2012. }
  2013. // Filter by node access grants.
  2014. $filter = $query->createFilter('OR');
  2015. $grants = node_access_grants('view', $account);
  2016. foreach ($grants as $realm => $gids) {
  2017. foreach ($gids as $gid) {
  2018. $filter->condition('search_api_access_node', "node_access_$realm:$gid");
  2019. }
  2020. }
  2021. $filter->condition('search_api_access_node', 'node_access__all');
  2022. $query->filter($filter);
  2023. }
  2024. /**
  2025. * Determines whether a field of the given type contains text data.
  2026. *
  2027. * Can also be used to find other types.
  2028. *
  2029. * @param string $type
  2030. * The type for which to check.
  2031. * @param array $allowed
  2032. * Optionally, an array of allowed types.
  2033. *
  2034. * @return bool
  2035. * TRUE if $type is either one of the specified types or a list of such
  2036. * values. FALSE otherwise.
  2037. *
  2038. * @see search_api_extract_inner_type()
  2039. */
  2040. function search_api_is_text_type($type, array $allowed = array('text')) {
  2041. return array_search(search_api_extract_inner_type($type), $allowed) !== FALSE;
  2042. }
  2043. /**
  2044. * Utility function for determining whether a field of the given type contains
  2045. * a list of any kind.
  2046. *
  2047. * @param $type
  2048. * A string containing the type to check.
  2049. *
  2050. * @return bool
  2051. * TRUE iff $type is a list type ("list<*>").
  2052. */
  2053. function search_api_is_list_type($type) {
  2054. return substr($type, 0, 5) == 'list<';
  2055. }
  2056. /**
  2057. * Utility function for determining the nesting level of a list type.
  2058. *
  2059. * @param $type
  2060. * A string containing the type to check.
  2061. *
  2062. * @return int
  2063. * The nesting level of the type. 0 for singular types, 1 for lists of
  2064. * singular types, etc.
  2065. */
  2066. function search_api_list_nesting_level($type) {
  2067. $level = 0;
  2068. while (search_api_is_list_type($type)) {
  2069. $type = substr($type, 5, -1);
  2070. ++$level;
  2071. }
  2072. return $level;
  2073. }
  2074. /**
  2075. * Utility function for nesting a type to the same level as another type.
  2076. * I.e., after <code>$t = search_api_nest_type($type, $nested_type);</code> is
  2077. * executed, the following statements will always be true:
  2078. * @code
  2079. * search_api_list_nesting_level($t) == search_api_list_nesting_level($nested_type);
  2080. * search_api_extract_inner_type($t) == search_api_extract_inner_type($type);
  2081. * @endcode
  2082. *
  2083. * @param $type
  2084. * The type to wrap.
  2085. * @param $nested_type
  2086. * Another type, determining the nesting level.
  2087. *
  2088. * @return string
  2089. * A list version of $type, as specified above.
  2090. */
  2091. function search_api_nest_type($type, $nested_type) {
  2092. while (search_api_is_list_type($nested_type)) {
  2093. $nested_type = substr($nested_type, 5, -1);
  2094. $type = "list<$type>";
  2095. }
  2096. return $type;
  2097. }
  2098. /**
  2099. * Utility function for extracting the contained primitive type of a list type.
  2100. *
  2101. * @param $type
  2102. * A string containing the list type to process.
  2103. *
  2104. * @return string
  2105. * A string containing the primitive type contained within the list, e.g.
  2106. * "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
  2107. * type, it is returned unchanged.
  2108. */
  2109. function search_api_extract_inner_type($type) {
  2110. while (search_api_is_list_type($type)) {
  2111. $type = substr($type, 5, -1);
  2112. }
  2113. return $type;
  2114. }
  2115. /**
  2116. * Helper function for reacting to index updates with regards to the datasource.
  2117. *
  2118. * When an overridden index is reverted, its numerical ID will sometimes change.
  2119. * Since the default datasource implementation uses that for referencing
  2120. * indexes, the index ID in the items table must be updated accordingly. This is
  2121. * implemented in this function.
  2122. *
  2123. * Modules implementing other datasource controllers, that use a table other
  2124. * than {search_api_item}, can use this function, too. It should be called
  2125. * unconditionally in a hook_search_api_index_update() implementation. If this
  2126. * function isn't used, similar code should be added there.
  2127. *
  2128. * However, note that this is only necessary (and this function should only be
  2129. * called) if the indexes are referenced by numerical ID in the items table.
  2130. *
  2131. * @param SearchApiIndex $index
  2132. * The index that was changed.
  2133. * @param string $table
  2134. * The table containing items information, analogous to {search_api_item}.
  2135. * @param string $column
  2136. * The column in $table that holds the index's numerical ID.
  2137. */
  2138. function search_api_index_update_datasource(SearchApiIndex $index, $table, $column = 'index_id') {
  2139. if ($index->id != $index->original->id) {
  2140. db_update($table)
  2141. ->fields(array($column => $index->id))
  2142. ->condition($column, $index->original->id)
  2143. ->execute();
  2144. }
  2145. }
  2146. /**
  2147. * Extracts specific field values from an EntityMetadataWrapper object.
  2148. *
  2149. * @param EntityMetadataWrapper $wrapper
  2150. * The wrapper from which to extract fields.
  2151. * @param array $fields
  2152. * The fields to extract, as stored in an index. I.e., the array keys are
  2153. * field names, the values are arrays with at least a "type" key present.
  2154. * @param array $value_options
  2155. * An array of options that should be passed to the
  2156. * EntityMetadataWrapper::value() method (see there).
  2157. *
  2158. * @return array
  2159. * The $fields array with additional "value" and "original_type" keys set.
  2160. */
  2161. function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
  2162. $value_options += array(
  2163. 'identifier' => TRUE,
  2164. );
  2165. // If $wrapper is a list of entities, we have to aggregate their field values.
  2166. $wrapper_info = $wrapper->info();
  2167. if (search_api_is_list_type($wrapper_info['type'])) {
  2168. foreach ($fields as &$info) {
  2169. $info['value'] = array();
  2170. $info['original_type'] = $info['type'];
  2171. }
  2172. unset($info);
  2173. try {
  2174. foreach ($wrapper as $w) {
  2175. $nested_fields = search_api_extract_fields($w, $fields, $value_options);
  2176. foreach ($nested_fields as $field => $info) {
  2177. if (isset($info['value'])) {
  2178. $fields[$field]['value'][] = $info['value'];
  2179. }
  2180. if (isset($info['original_type'])) {
  2181. $fields[$field]['original_type'] = $info['original_type'];
  2182. }
  2183. }
  2184. }
  2185. }
  2186. catch (EntityMetadataWrapperException $e) {
  2187. // Catch exceptions caused by not set list values.
  2188. }
  2189. return $fields;
  2190. }
  2191. $nested = array();
  2192. $entity_infos = entity_get_info();
  2193. foreach ($fields as $field => &$info) {
  2194. $pos = strpos($field, ':');
  2195. if ($pos === FALSE) {
  2196. // Set "defaults" in case an error occurs later.
  2197. $info['value'] = NULL;
  2198. $info['original_type'] = $info['type'];
  2199. if (isset($wrapper->$field)) {
  2200. try {
  2201. // Set the original type according to the field wrapper's info.
  2202. $property_info = $wrapper->$field->info();
  2203. $info['original_type'] = $property_info['type'];
  2204. // Extract the basic value from the field wrapper.
  2205. $info['value'] = $wrapper->$field->value($value_options);
  2206. // For entities, we need to take care to differentiate between
  2207. // entities with ID 0 and empty fields. In the latter case, the
  2208. // wrapper's value() method returns, when called with "identifier =
  2209. // TRUE", FALSE instead of the (more logical) NULL.
  2210. $is_entity = isset($entity_infos[search_api_extract_inner_type($property_info['type'])]);
  2211. if ($is_entity && $info['value'] === FALSE) {
  2212. $info['value'] = NULL;
  2213. }
  2214. // If we index the field as fulltext, we also include the entity label
  2215. // or option list label, if applicable.
  2216. if (search_api_is_text_type($info['type']) && isset($info['value'])) {
  2217. if ($wrapper->$field->optionsList('view')) {
  2218. _search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
  2219. }
  2220. elseif ($is_entity) {
  2221. $info['value'] = _search_api_extract_entity_value($wrapper->$field, TRUE);
  2222. }
  2223. }
  2224. }
  2225. catch (EntityMetadataWrapperException $e) {
  2226. // This might happen for entity-typed properties that are NULL, e.g.,
  2227. // for comments without parent.
  2228. }
  2229. }
  2230. }
  2231. else {
  2232. list($prefix, $key) = explode(':', $field, 2);
  2233. $nested[$prefix][$key] = $info;
  2234. }
  2235. }
  2236. unset($info);
  2237. foreach ($nested as $prefix => $nested_fields) {
  2238. if (isset($wrapper->$prefix)) {
  2239. $nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
  2240. foreach ($nested_fields as $field => $info) {
  2241. $fields["$prefix:$field"] = $info;
  2242. }
  2243. }
  2244. else {
  2245. foreach ($nested_fields as &$info) {
  2246. $info['value'] = NULL;
  2247. $info['original_type'] = $info['type'];
  2248. }
  2249. }
  2250. }
  2251. return $fields;
  2252. }
  2253. /**
  2254. * Helper method for adding additional text data to fields with an option list.
  2255. */
  2256. function _search_api_add_option_values(&$value, array $options) {
  2257. if (is_array($value)) {
  2258. foreach ($value as &$v) {
  2259. _search_api_add_option_values($v, $options);
  2260. }
  2261. return;
  2262. }
  2263. if (is_scalar($value) && isset($options[$value])) {
  2264. $value .= ' ' . $options[$value];
  2265. }
  2266. }
  2267. /**
  2268. * Helper method for extracting the ID (and possibly label) of an entity-valued field.
  2269. */
  2270. function _search_api_extract_entity_value(EntityMetadataWrapper $wrapper, $fulltext = FALSE) {
  2271. $v = $wrapper->value();
  2272. if (is_array($v)) {
  2273. $ret = array();
  2274. foreach ($wrapper as $item) {
  2275. $values = _search_api_extract_entity_value($item, $fulltext);
  2276. if ($values) {
  2277. $ret[] = $values;
  2278. }
  2279. }
  2280. return $ret;
  2281. }
  2282. if ($v) {
  2283. $ret = $wrapper->getIdentifier();
  2284. if ($fulltext && ($label = $wrapper->label())) {
  2285. $ret .= ' ' . $label;
  2286. }
  2287. return $ret;
  2288. }
  2289. return NULL;
  2290. }
  2291. /**
  2292. * Load the search server with the specified id.
  2293. *
  2294. * @param $id
  2295. * The search server's id.
  2296. * @param $reset
  2297. * Whether to reset the internal cache.
  2298. *
  2299. * @return SearchApiServer
  2300. * An object representing the server with the specified id.
  2301. */
  2302. function search_api_server_load($id, $reset = FALSE) {
  2303. $ret = search_api_server_load_multiple(array($id), array(), $reset);
  2304. return $ret ? reset($ret) : FALSE;
  2305. }
  2306. /**
  2307. * Load multiple servers at once, determined by IDs or machine names, or by
  2308. * other conditions.
  2309. *
  2310. * @see entity_load()
  2311. *
  2312. * @param array|false $ids
  2313. * An array of server IDs or machine names, or FALSE to load all servers.
  2314. * @param array $conditions
  2315. * An array of conditions on the {search_api_server} table in the form
  2316. * 'field' => $value.
  2317. * @param bool $reset
  2318. * Whether to reset the internal entity_load cache.
  2319. *
  2320. * @return SearchApiServer[]
  2321. * An array of server objects keyed by machine name.
  2322. */
  2323. function search_api_server_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2324. $servers = entity_load('search_api_server', $ids, $conditions, $reset);
  2325. return entity_key_array_by_property($servers, 'machine_name');
  2326. }
  2327. /**
  2328. * Entity uri callback.
  2329. */
  2330. function search_api_server_url(SearchApiServer $server) {
  2331. return array(
  2332. 'path' => 'admin/config/search/search_api/server/' . $server->machine_name,
  2333. 'options' => array(),
  2334. );
  2335. }
  2336. /**
  2337. * Title callback for viewing or editing a server or index.
  2338. */
  2339. function search_api_admin_item_title($object) {
  2340. return $object->name;
  2341. }
  2342. /**
  2343. * Title callback for determining which title should be displayed for the
  2344. * "delete" local task.
  2345. *
  2346. * @param Entity $entity
  2347. * The server or index for which the menu link is displayed.
  2348. *
  2349. * @return string
  2350. * A translated version of either "Delete" or "Revert".
  2351. */
  2352. function search_api_title_delete_page(Entity $entity) {
  2353. return $entity->hasStatus(ENTITY_OVERRIDDEN) ? t('Revert') : t('Delete');
  2354. }
  2355. /**
  2356. * Determines whether the current user can disable a server or index.
  2357. *
  2358. * @param Entity $entity
  2359. * The server or index for which the access to the "disable" page is checked.
  2360. *
  2361. * @return bool
  2362. * TRUE if the "disable" page can be accessed by the user, FALSE otherwise.
  2363. */
  2364. function search_api_access_disable_page(Entity $entity) {
  2365. return user_access('administer search_api') && !empty($entity->enabled);
  2366. }
  2367. /**
  2368. * Access callback for determining if a server's or index' "delete" page should
  2369. * be accessible.
  2370. *
  2371. * @param Entity $entity
  2372. * The server or index for which the access to the delete page is checked.
  2373. *
  2374. * @return bool
  2375. * TRUE if the delete page can be accessed by the user, FALSE otherwise.
  2376. */
  2377. function search_api_access_delete_page(Entity $entity) {
  2378. return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
  2379. }
  2380. /**
  2381. * Determines whether a user can access a certain search server or index.
  2382. *
  2383. * Used as an access callback in search_api_entity_info().
  2384. */
  2385. function search_api_entity_access() {
  2386. return user_access('administer search_api');
  2387. }
  2388. /**
  2389. * Inserts a new search server into the database.
  2390. *
  2391. * @param array $values
  2392. * An array containing the values to be inserted.
  2393. *
  2394. * @return
  2395. * The newly inserted server's id, or FALSE on error.
  2396. */
  2397. function search_api_server_insert(array $values) {
  2398. $server = entity_create('search_api_server', $values);
  2399. $server->is_new = TRUE;
  2400. $server->save();
  2401. return $server->id;
  2402. }
  2403. /**
  2404. * Changes a server's settings.
  2405. *
  2406. * @param string|int $id
  2407. * The ID or machine name of the server whose values should be changed.
  2408. * @param array $fields
  2409. * The new field values to set. The enabled field can't be set this way, use
  2410. * search_api_server_enable() and search_api_server_disable() instead.
  2411. *
  2412. * @return int|false
  2413. * 1 if fields were changed, 0 if the fields already had the desired values.
  2414. * FALSE on failure.
  2415. */
  2416. function search_api_server_edit($id, array $fields) {
  2417. $server = search_api_server_load($id, TRUE);
  2418. $ret = $server->update($fields);
  2419. return $ret ? 1 : $ret;
  2420. }
  2421. /**
  2422. * Enables a search server.
  2423. *
  2424. * Will also check for remembered tasks for this server and execute them.
  2425. *
  2426. * @param string|int $id
  2427. * The ID or machine name of the server to enable.
  2428. *
  2429. * @return int|false
  2430. * 1 on success, 0 or FALSE on failure.
  2431. */
  2432. function search_api_server_enable($id) {
  2433. $server = search_api_server_load($id, TRUE);
  2434. $ret = $server->update(array('enabled' => 1));
  2435. return $ret ? 1 : $ret;
  2436. }
  2437. /**
  2438. * Disables a search server.
  2439. *
  2440. * Will also disable all associated indexes and remove them from the server.
  2441. *
  2442. * @param string|int $id
  2443. * The ID or machine name of the server to disable.
  2444. *
  2445. * @return int|false
  2446. * 1 on success, 0 or FALSE on failure.
  2447. */
  2448. function search_api_server_disable($id) {
  2449. $server = search_api_server_load($id, TRUE);
  2450. $ret = $server->update(array('enabled' => 0));
  2451. return $ret ? 1 : $ret;
  2452. }
  2453. /**
  2454. * Clears a search server.
  2455. *
  2456. * Will delete all items stored on the server and mark all associated indexes
  2457. * for re-indexing.
  2458. *
  2459. * @param int|string $id
  2460. * The ID or machine name of the server to clear.
  2461. *
  2462. * @return bool
  2463. * TRUE on success, FALSE on failure.
  2464. */
  2465. function search_api_server_clear($id) {
  2466. $server = search_api_server_load($id);
  2467. $success = TRUE;
  2468. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  2469. $success &= $index->reindex();
  2470. }
  2471. if ($success) {
  2472. $server->deleteItems();
  2473. }
  2474. return $success;
  2475. }
  2476. /**
  2477. * Deletes a search server and disables all associated indexes.
  2478. *
  2479. * @param $id
  2480. * The ID or machine name of the server to delete.
  2481. *
  2482. * @return int|false
  2483. * 1 on success, 0 or FALSE on failure.
  2484. */
  2485. function search_api_server_delete($id) {
  2486. $server = search_api_server_load($id, TRUE);
  2487. $server->delete();
  2488. return 1;
  2489. }
  2490. /**
  2491. * Loads the Search API index with the specified id.
  2492. *
  2493. * @param $id
  2494. * The index' id.
  2495. * @param $reset
  2496. * Whether to reset the internal cache.
  2497. *
  2498. * @return SearchApiIndex|false
  2499. * A completely loaded index object, or FALSE if no such index exists.
  2500. */
  2501. function search_api_index_load($id, $reset = FALSE) {
  2502. $ret = search_api_index_load_multiple(array($id), array(), $reset);
  2503. return reset($ret);
  2504. }
  2505. /**
  2506. * Load multiple indexes at once, determined by IDs or machine names, or by
  2507. * other conditions.
  2508. *
  2509. * @see entity_load()
  2510. *
  2511. * @param array|false $ids
  2512. * An array of index IDs or machine names, or FALSE to load all indexes.
  2513. * @param array $conditions
  2514. * An array of conditions on the {search_api_index} table in the form
  2515. * 'field' => $value.
  2516. * @param bool $reset
  2517. * Whether to reset the internal entity_load cache.
  2518. *
  2519. * @return SearchApiIndex[]
  2520. * An array of index objects keyed by machine name.
  2521. */
  2522. function search_api_index_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2523. // This line is a workaround for a weird PDO bug in PHP 5.2.
  2524. // See http://drupal.org/node/889286.
  2525. new SearchApiIndex();
  2526. $indexes = entity_load('search_api_index', $ids, $conditions, $reset);
  2527. return entity_key_array_by_property($indexes, 'machine_name');
  2528. }
  2529. /**
  2530. * Determines a search index' indexing status.
  2531. *
  2532. * @param SearchApiIndex $index
  2533. * The index whose indexing status should be determined.
  2534. *
  2535. * @return array
  2536. * An associative array containing two keys (in this order):
  2537. * - indexed: The number of items already indexed in their latest version.
  2538. * - total: The total number of items that have to be indexed for this index.
  2539. */
  2540. function search_api_index_status(SearchApiIndex $index) {
  2541. return $index->datasource()->getIndexStatus($index);
  2542. }
  2543. /**
  2544. * Entity uri callback.
  2545. */
  2546. function search_api_index_url(SearchApiIndex $index) {
  2547. return array(
  2548. 'path' => 'admin/config/search/search_api/index/' . $index->machine_name,
  2549. 'options' => array(),
  2550. );
  2551. }
  2552. /**
  2553. * Returns an index's server.
  2554. *
  2555. * Used as a property getter callback for the index's "server_entity" prioperty
  2556. * in search_api_entity_property_info().
  2557. *
  2558. * @param SearchApiIndex $index
  2559. * The index whose server should be returned.
  2560. *
  2561. * @return SearchApiServer|null
  2562. * The server this index currently resides on, or NULL if the index is
  2563. * currently unassigned.
  2564. */
  2565. function search_api_index_get_server(SearchApiIndex $index) {
  2566. try {
  2567. return $index->server();
  2568. }
  2569. catch (SearchApiException $e) {
  2570. watchdog_exception('search_api', $e);
  2571. return NULL;
  2572. }
  2573. }
  2574. /**
  2575. * Returns an options list for the "status" property.
  2576. *
  2577. * Used as an options list callback in search_api_entity_property_info().
  2578. *
  2579. * @return array
  2580. * An array of options, as defined by hook_options_list().
  2581. */
  2582. function search_api_status_options_list() {
  2583. return array(
  2584. ENTITY_CUSTOM => t('Custom'),
  2585. ENTITY_IN_CODE => t('Default'),
  2586. ENTITY_OVERRIDDEN => t('Overridden'),
  2587. ENTITY_FIXED => t('Fixed'),
  2588. );
  2589. }
  2590. /**
  2591. * Inserts a new search index into the database.
  2592. *
  2593. * @param array $values
  2594. * An array containing the values to be inserted.
  2595. *
  2596. * @return
  2597. * The newly inserted index' id, or FALSE on error.
  2598. */
  2599. function search_api_index_insert(array $values) {
  2600. $index = entity_create('search_api_index', $values);
  2601. $index->is_new = TRUE;
  2602. $index->save();
  2603. return $index->id;
  2604. }
  2605. /**
  2606. * Changes an index' settings.
  2607. *
  2608. * @param int|string $id
  2609. * The edited index' ID or machine name.
  2610. * @param array $fields
  2611. * The new field values to set.
  2612. *
  2613. * @return int|false
  2614. * 1 if fields were changed, 0 if the fields already had the desired values.
  2615. * FALSE on failure.
  2616. */
  2617. function search_api_index_edit($id, array $fields) {
  2618. $index = search_api_index_load($id, TRUE);
  2619. $ret = $index->update($fields);
  2620. return $ret ? 1 : $ret;
  2621. }
  2622. /**
  2623. * Changes an index' indexed field settings.
  2624. *
  2625. * @param int|string $id
  2626. * The ID or machine name of the index whose fields should be changed.
  2627. * @param array $fields
  2628. * The new indexed field settings.
  2629. *
  2630. * @return int|false
  2631. * 1 if the field settings were changed, 0 if they already had the desired
  2632. * values. FALSE on failure.
  2633. */
  2634. function search_api_index_edit_fields($id, array $fields) {
  2635. $index = search_api_index_load($id, TRUE);
  2636. $options = $index->options;
  2637. $options['fields'] = $fields;
  2638. $ret = $index->update(array('options' => $options));
  2639. return $ret ? 1 : $ret;
  2640. }
  2641. /**
  2642. * Enables a search index.
  2643. *
  2644. * @param string|int $id
  2645. * The ID or machine name of the index to enable.
  2646. *
  2647. * @return int|false
  2648. * 1 on success, 0 or FALSE on failure.
  2649. *
  2650. * @throws SearchApiException
  2651. * If the index's server doesn't exist.
  2652. */
  2653. function search_api_index_enable($id) {
  2654. $index = search_api_index_load($id, TRUE);
  2655. $ret = $index->update(array('enabled' => 1));
  2656. return $ret ? 1 : $ret;
  2657. }
  2658. /**
  2659. * Disables a search index.
  2660. *
  2661. * @param string|int $id
  2662. * The ID or machine name of the index to disable.
  2663. *
  2664. * @return int|false
  2665. * 1 on success, 0 or FALSE on failure.
  2666. *
  2667. * @throws SearchApiException
  2668. * If the index's server doesn't exist.
  2669. */
  2670. function search_api_index_disable($id) {
  2671. $index = search_api_index_load($id, TRUE);
  2672. $ret = $index->update(array('enabled' => 0));
  2673. return $ret ? 1 : $ret;
  2674. }
  2675. /**
  2676. * Schedules a search index for re-indexing.
  2677. *
  2678. * @param $id
  2679. * The ID or machine name of the index to re-index.
  2680. *
  2681. * @return bool
  2682. * TRUE on success, FALSE on failure.
  2683. */
  2684. function search_api_index_reindex($id) {
  2685. $index = search_api_index_load($id);
  2686. return $index->reindex();
  2687. }
  2688. /**
  2689. * Helper method for marking all items on an index as needing re-indexing.
  2690. *
  2691. * @param SearchApiIndex $index
  2692. * The index whose items should be re-indexed.
  2693. */
  2694. function _search_api_index_reindex(SearchApiIndex $index) {
  2695. $index->datasource()->trackItemChange(FALSE, array($index), TRUE);
  2696. }
  2697. /**
  2698. * Clears a search index and schedules all of its items for re-indexing.
  2699. *
  2700. * @param $id
  2701. * The ID or machine name of the index to clear.
  2702. *
  2703. * @return bool
  2704. * TRUE on success, FALSE on failure.
  2705. */
  2706. function search_api_index_clear($id) {
  2707. $index = search_api_index_load($id);
  2708. return $index->clear();
  2709. }
  2710. /**
  2711. * Deletes a search index.
  2712. *
  2713. * @param $id
  2714. * The ID or machine name of the index to delete.
  2715. *
  2716. * @return bool
  2717. * TRUE on success, FALSE on failure.
  2718. */
  2719. function search_api_index_delete($id) {
  2720. $index = search_api_index_load($id);
  2721. if (!$index) {
  2722. return FALSE;
  2723. }
  2724. $index->delete();
  2725. return TRUE;
  2726. }
  2727. /**
  2728. * Sanitizes field values returned from the server.
  2729. *
  2730. * @param array $values
  2731. * The field values, as returned from the server. See
  2732. * SearchApiQueryInterface::execute() for documentation on the structure.
  2733. *
  2734. * @return array
  2735. * An associative array of field IDs mapped to their sanitized values (scalar
  2736. * or array-valued).
  2737. */
  2738. function search_api_get_sanitized_field_values(array $values) {
  2739. // Sanitize the field values returned from the server. Usually we use
  2740. // check_plain(), but this can be overridden by setting the field value to
  2741. // an array with "#value" and "#sanitize_callback" keys.
  2742. foreach ($values as $field_id => $field_value) {
  2743. if (is_array($field_value)
  2744. && isset($field_value['#sanitize_callback'])
  2745. && ($field_value['#sanitize_callback'] === FALSE || is_callable($field_value['#sanitize_callback']))
  2746. && array_key_exists('#value', $field_value)
  2747. ) {
  2748. $sanitize_callback = $field_value['#sanitize_callback'];
  2749. $field_value = $field_value['#value'];
  2750. }
  2751. else {
  2752. $sanitize_callback = 'check_plain';
  2753. }
  2754. if ($sanitize_callback !== FALSE) {
  2755. $field_value = search_api_sanitize_field_value($field_value, $sanitize_callback);
  2756. }
  2757. $values[$field_id] = $field_value;
  2758. }
  2759. return $values;
  2760. }
  2761. /**
  2762. * Sanitizes the given field value(s).
  2763. *
  2764. * @param mixed $field_value
  2765. * A scalar field value, or an array of field values.
  2766. * @param callable $sanitize_callback
  2767. * (optional) The callback to use for sanitizing a scalar value.
  2768. *
  2769. * @return mixed
  2770. * The sanitized field value(s).
  2771. */
  2772. function search_api_sanitize_field_value($field_value, $sanitize_callback = 'check_plain') {
  2773. if ($field_value === NULL) {
  2774. return $field_value;
  2775. }
  2776. if (is_scalar($field_value)) {
  2777. return call_user_func($sanitize_callback, $field_value);
  2778. }
  2779. foreach ($field_value as &$nested_value) {
  2780. $nested_value = search_api_sanitize_field_value($nested_value, $sanitize_callback);
  2781. }
  2782. return $field_value;
  2783. }
  2784. /**
  2785. * Options list callback for search indexes.
  2786. *
  2787. * @return array
  2788. * An array of search index machine names mapped to their human-readable
  2789. * names.
  2790. */
  2791. function search_api_index_options_list() {
  2792. $ret = array(
  2793. NULL => '- ' . t('All') . ' -',
  2794. );
  2795. foreach (search_api_index_load_multiple(FALSE) as $id => $index) {
  2796. $ret[$id] = $index->name;
  2797. }
  2798. return $ret;
  2799. }
  2800. /**
  2801. * Options list callback for entity types.
  2802. *
  2803. * Will only include entity types which specify entity property information.
  2804. *
  2805. * @return string[]
  2806. * An array of entity type machine names mapped to their human-readable
  2807. * names.
  2808. */
  2809. function search_api_entity_type_options_list() {
  2810. $types = array();
  2811. foreach (array_keys(entity_get_property_info()) as $type) {
  2812. $info = entity_get_info($type);
  2813. if ($info) {
  2814. $types[$type] = $info['label'];
  2815. }
  2816. }
  2817. return $types;
  2818. }
  2819. /**
  2820. * Options list callback for entity type bundles.
  2821. *
  2822. * Will include all bundles for all entity types which specify entity property
  2823. * information, in a format combining both entity type and bundle.
  2824. *
  2825. * @return string[]
  2826. * An array of bundle identifiers mapped to their human-readable names.
  2827. */
  2828. function search_api_combined_bundle_options_list() {
  2829. $types = array();
  2830. foreach (array_keys(entity_get_property_info()) as $type) {
  2831. $info = entity_get_info($type);
  2832. if (!empty($info['bundles'])) {
  2833. foreach ($info['bundles'] as $bundle => $bundle_info) {
  2834. $types["$type:$bundle"] = $bundle_info['label'];
  2835. }
  2836. }
  2837. }
  2838. return $types;
  2839. }
  2840. /**
  2841. * Retrieves a human-readable label for a multi-type index item.
  2842. *
  2843. * Provided as a non-object alternative to
  2844. * SearchApiCombinedEntityDataSourceController::getItemLabel() so it can be used
  2845. * as a getter callback.
  2846. *
  2847. * @param object $item
  2848. * An item of the "multiple" item type.
  2849. *
  2850. * @return string|null
  2851. * Either a human-readable label for the item, or NULL if none is available.
  2852. */
  2853. function search_api_get_multi_type_item_label($item) {
  2854. $label = entity_label($item->item_type, $item->{$item->item_type});
  2855. return $label ? $label : NULL;
  2856. }
  2857. /**
  2858. * Shutdown function which indexes all queued items, if any.
  2859. */
  2860. function _search_api_index_queued_items() {
  2861. $queue = &search_api_index_specific_items_delayed();
  2862. try {
  2863. if ($queue) {
  2864. $indexes = search_api_index_load_multiple(array_keys($queue));
  2865. foreach ($indexes as $index_id => $index) {
  2866. search_api_index_specific_items($index, $queue[$index_id]);
  2867. }
  2868. }
  2869. // Reset the queue so we don't index the items twice by accident.
  2870. $queue = array();
  2871. }
  2872. catch (SearchApiException $e) {
  2873. watchdog_exception('search_api', $e);
  2874. }
  2875. }
  2876. /**
  2877. * Helper function to be used as a "property info alter" callback.
  2878. *
  2879. * If a wrapped entity is passed to this function, all its available properties
  2880. * and fields, regardless of bundle, are added to the wrapper.
  2881. */
  2882. function _search_api_wrapper_add_all_properties(EntityMetadataWrapper $wrapper, array $property_info) {
  2883. if ($properties = entity_get_all_property_info($wrapper->type())) {
  2884. $property_info['properties'] = $properties;
  2885. }
  2886. return $property_info;
  2887. }
  2888. /**
  2889. * Helper function for converting data to a custom type.
  2890. */
  2891. function _search_api_convert_custom_type($callback, $value, $original_type, $type, $nesting_level) {
  2892. if ($nesting_level == 0) {
  2893. return call_user_func($callback, $value, $original_type, $type);
  2894. }
  2895. if (!is_array($value)) {
  2896. return NULL;
  2897. }
  2898. --$nesting_level;
  2899. $values = array();
  2900. foreach ($value as $v) {
  2901. $v = _search_api_convert_custom_type($callback, $v, $original_type, $type, $nesting_level);
  2902. if (isset($v) && !(is_array($v) && !$v)) {
  2903. $values[] = $v;
  2904. }
  2905. }
  2906. return $values;
  2907. }
  2908. /**
  2909. * Determines the number of items indexed on a server for a certain index.
  2910. *
  2911. * Used as a helper function in search_api_admin_index_view().
  2912. *
  2913. * @param SearchApiIndex $index
  2914. * The index
  2915. *
  2916. * @return int
  2917. * The number of items found on the server for this index, if the latter is
  2918. * enabled. 0 otherwise.
  2919. *
  2920. * @throws SearchApiException
  2921. * If an error prevented the search from completing.
  2922. */
  2923. function _search_api_get_items_on_server(SearchApiIndex $index) {
  2924. if (!$index->enabled) {
  2925. return 0;
  2926. }
  2927. // We want the raw count, without facets or other filters. Therefore we don't
  2928. // use the query's execute() method but pass it straight to the server for
  2929. // evaluation. Since this circumvents the normal preprocessing, which sets the
  2930. // fields (on which some service classes might even rely when there are no
  2931. // keywords), we set them manually here.
  2932. $query = $index->query()
  2933. ->fields(array())
  2934. ->range(0, 0);
  2935. $response = $index->server()->search($query);
  2936. return $response['result count'];
  2937. }
  2938. /**
  2939. * Returns a deep copy of the input array.
  2940. *
  2941. * The behavior of PHP regarding arrays with references pointing to it is rather
  2942. * weird. Therefore, we use this helper function in theme_search_api_index() to
  2943. * create safe copies of such arrays.
  2944. *
  2945. * @param array $array
  2946. * The array to copy.
  2947. *
  2948. * @return array
  2949. * A deep copy of the array.
  2950. */
  2951. function _search_api_deep_copy(array $array) {
  2952. $copy = array();
  2953. foreach ($array as $k => $v) {
  2954. if (is_array($v)) {
  2955. $copy[$k] = _search_api_deep_copy($v);
  2956. }
  2957. elseif (is_object($v)) {
  2958. $copy[$k] = clone $v;
  2959. }
  2960. elseif ($v) {
  2961. $copy[$k] = $v;
  2962. }
  2963. }
  2964. return $copy;
  2965. }
  2966. /**
  2967. * Reacts to a change in the bundle of an entity.
  2968. *
  2969. * Used as a helper function in search_api_entity_update().
  2970. *
  2971. * @param $type
  2972. * The entity's type.
  2973. * @param $id
  2974. * The entity's ID.
  2975. * @param $old_bundle
  2976. * The entity's previous bundle.
  2977. * @param $new_bundle
  2978. * The entity's new bundle.
  2979. */
  2980. function _search_api_entity_datasource_bundle_change($type, $id, $old_bundle, $new_bundle) {
  2981. $controller = search_api_get_datasource_controller($type);
  2982. $conditions = array(
  2983. 'enabled' => 1,
  2984. 'item_type' => $type,
  2985. 'read_only' => 0,
  2986. );
  2987. foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
  2988. if (!empty($index->options['datasource']['bundles'])) {
  2989. $bundles = drupal_map_assoc($index->options['datasource']['bundles']);
  2990. if (empty($bundles[$new_bundle]) != empty($bundles[$old_bundle])) {
  2991. if (empty($bundles[$new_bundle])) {
  2992. $controller->trackItemDelete(array($id), array($index));
  2993. }
  2994. else {
  2995. $controller->trackItemInsert(array($id), array($index));
  2996. }
  2997. }
  2998. }
  2999. }
  3000. }
  3001. /**
  3002. * Creates and sets a batch for indexing items.
  3003. *
  3004. * @param SearchApiIndex $index
  3005. * The index for which items should be indexed.
  3006. * @param int $batch_size
  3007. * Number of items to index per batch.
  3008. * @param int $limit
  3009. * Maximum number of items to index. Negative values mean "no limit".
  3010. * @param int $remaining
  3011. * Remaining items to index.
  3012. * @param bool $drush
  3013. * Boolean specifying whether this was called from drush or not.
  3014. *
  3015. * @return bool
  3016. * Whether the batch was created and set successfully.
  3017. */
  3018. function _search_api_batch_indexing_create(SearchApiIndex $index, $batch_size, $limit, $remaining, $drush = FALSE) {
  3019. if ($limit !== 0 && $batch_size !== 0) {
  3020. $t = !empty($drush) ? 'dt' : 't';
  3021. if ($limit < 0 || $limit > $remaining) {
  3022. $limit = $remaining;
  3023. }
  3024. if ($batch_size < 0) {
  3025. $batch_size = $remaining;
  3026. }
  3027. $batch = array(
  3028. 'title' => $t('Indexing items'),
  3029. 'operations' => array(
  3030. array('_search_api_batch_indexing_callback', array($index, $batch_size, $limit, $drush)),
  3031. ),
  3032. 'progress_message' => $t('Completed about @percentage% of the indexing operation.'),
  3033. 'finished' => '_search_api_batch_indexing_finished',
  3034. 'file' => drupal_get_path('module', 'search_api') . '/search_api.module',
  3035. );
  3036. batch_set($batch);
  3037. return TRUE;
  3038. }
  3039. return FALSE;
  3040. }
  3041. /**
  3042. * Batch API callback for the indexing functionality.
  3043. *
  3044. * @param SearchApiIndex $index
  3045. * The index for which items should be indexed.
  3046. * @param integer $batch_size
  3047. * Number of items to index per batch.
  3048. * @param integer $limit
  3049. * Maximum number of items to index.
  3050. * @param boolean $drush
  3051. * Boolean specifying whether this was called from drush or not.
  3052. * @param $context
  3053. * An array (or object implementing ArrayAccess) containing the batch context.
  3054. */
  3055. function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, $limit, $drush = FALSE, &$context) {
  3056. // Persistent data among batch runs.
  3057. if (!isset($context['sandbox']['limit'])) {
  3058. $context['sandbox']['limit'] = $limit;
  3059. $context['sandbox']['batch_size'] = $batch_size;
  3060. $context['sandbox']['progress'] = 0;
  3061. }
  3062. // Persistent data for results.
  3063. if (!isset($context['results']['indexed'])) {
  3064. $context['results']['indexed'] = 0;
  3065. $context['results']['not indexed'] = 0;
  3066. $context['results']['drush'] = $drush;
  3067. }
  3068. // Number of items to index for this run.
  3069. $to_index = min($context['sandbox']['limit'] - $context['sandbox']['progress'], $context['sandbox']['batch_size']);
  3070. // Index the items.
  3071. try {
  3072. $indexed = search_api_index_items($index, $to_index);
  3073. $context['results']['indexed'] += $indexed;
  3074. }
  3075. catch (SearchApiException $e) {
  3076. watchdog_exception('search_api', $e);
  3077. $vars['@message'] = $e->getMessage();
  3078. $context['message'] = t('An error occurred during indexing: @message.', $vars);
  3079. $context['finished'] = 1;
  3080. $context['results']['not indexed'] += $context['sandbox']['limit'] - $context['sandbox']['progress'];
  3081. return;
  3082. }
  3083. // Display progress message.
  3084. if ($indexed > 0) {
  3085. $format_plural = $context['results']['drush'] === TRUE ? '_search_api_drush_format_plural' : 'format_plural';
  3086. $context['message'] = $format_plural($context['results']['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.');
  3087. }
  3088. // Some items couldn't be indexed.
  3089. if ($indexed !== $to_index) {
  3090. $context['results']['not indexed'] += $to_index - $indexed;
  3091. }
  3092. $context['sandbox']['progress'] += $to_index;
  3093. // Everything has been indexed.
  3094. if ($indexed === 0 || $context['sandbox']['progress'] >= $context['sandbox']['limit']) {
  3095. $context['finished'] = 1;
  3096. }
  3097. else {
  3098. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['limit'];
  3099. }
  3100. }
  3101. /**
  3102. * Batch API finishing callback for the indexing functionality.
  3103. *
  3104. * @param boolean $success
  3105. * Whether the batch finished successfully.
  3106. * @param array $results
  3107. * Detailed information about the result.
  3108. */
  3109. function _search_api_batch_indexing_finished($success, $results) {
  3110. // Check if called from drush.
  3111. if (!empty($results['drush'])) {
  3112. $drupal_set_message = 'drush_log';
  3113. $format_plural = '_search_api_drush_format_plural';
  3114. $t = 'dt';
  3115. $success_message = 'success';
  3116. }
  3117. else {
  3118. $drupal_set_message = 'drupal_set_message';
  3119. $format_plural = 'format_plural';
  3120. $t = 't';
  3121. $success_message = 'status';
  3122. }
  3123. // Display result messages.
  3124. if ($success) {
  3125. if (!empty($results['indexed'])) {
  3126. $drupal_set_message($format_plural($results['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.'), $success_message);
  3127. if (!empty($results['not indexed'])) {
  3128. $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');
  3129. }
  3130. }
  3131. else {
  3132. $drupal_set_message($t("Couldn't index items. Check the logs for details."), 'error');
  3133. }
  3134. }
  3135. else {
  3136. $drupal_set_message($t("An error occurred while trying to index items. Check the logs for details."), 'error');
  3137. }
  3138. }