search_api.module 96 KB

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