search_api.module 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047
  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' => NULL,
  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. try {
  640. $new_server = $index->server(TRUE);
  641. // If the server is enabled, we call addIndex(); otherwise, we save the task.
  642. $new_server->addIndex($index);
  643. }
  644. catch (SearchApiException $e) {
  645. watchdog_exception('search_api', $e);
  646. // If the new server doesn't exist, we remove the index from all
  647. // servers. Note that saving an entity in its own update hook is usually
  648. // a recipe for disaster, but since we are only doing this if a server
  649. // is set and remove the server here before saving, it should be safe
  650. // enough.
  651. $index->server = NULL;
  652. $index->save();
  653. }
  654. }
  655. // We also have to re-index all content.
  656. _search_api_index_reindex($index);
  657. }
  658. // If the fields were changed, call the appropriate service class hook method
  659. // and re-index the content, if necessary.
  660. $old_fields = $index->original->options + array('fields' => array());
  661. $old_fields = $old_fields['fields'];
  662. $new_fields = $index->options + array('fields' => array());
  663. $new_fields = $new_fields['fields'];
  664. if ($old_fields != $new_fields) {
  665. if ($index->server) {
  666. $index->server()->fieldsUpdated($index);
  667. }
  668. }
  669. // If the index's enabled or read-only status is being changed, queue or
  670. // dequeue items for indexing.
  671. if (!$index->read_only && $index->enabled != $index->original->enabled) {
  672. if ($index->enabled) {
  673. $index->queueItems();
  674. }
  675. else {
  676. $index->dequeueItems();
  677. }
  678. }
  679. elseif ($index->read_only != $index->original->read_only) {
  680. if ($index->read_only) {
  681. $index->dequeueItems();
  682. }
  683. else {
  684. $index->queueItems();
  685. }
  686. }
  687. }
  688. /**
  689. * Implements hook_search_api_index_delete().
  690. *
  691. * Removes all data for indexes not available any more.
  692. */
  693. function search_api_search_api_index_delete(SearchApiIndex $index) {
  694. // Only react on real delete, not revert.
  695. if ($index->hasStatus(ENTITY_IN_CODE)) {
  696. $reverts = &drupal_static(__FUNCTION__, array());
  697. $reverts[$index->machine_name] = $index;
  698. return;
  699. }
  700. cache_clear_all($index->getCacheId(''), 'cache', TRUE);
  701. $index->postDelete();
  702. }
  703. /**
  704. * Implements hook_features_export_alter().
  705. *
  706. * Adds dependency information for exported servers.
  707. */
  708. function search_api_features_export_alter(&$export) {
  709. if (isset($export['features']['search_api_server'])) {
  710. // Get a list of the modules that provide storage engines.
  711. $hook = 'search_api_service_info';
  712. $classes = array();
  713. foreach (module_implements('search_api_service_info') as $module) {
  714. $function = $module . '_' . $hook;
  715. $engines = $function();
  716. foreach ($engines as $service => $specs) {
  717. $classes[$service] = $module;
  718. }
  719. }
  720. // Check all of the exported server specifications.
  721. foreach ($export['features']['search_api_server'] as $server_name) {
  722. // Load the server's object.
  723. $server = search_api_server_load($server_name);
  724. $module = $classes[$server->class];
  725. // Ensure that the module responsible for the server object is listed as
  726. // a dependency.
  727. if (!isset($export['dependencies'][$module])) {
  728. $export['dependencies'][$module] = $module;
  729. }
  730. }
  731. // Ensure the dependencies list is still sorted alphabetically.
  732. ksort($export['dependencies']);
  733. }
  734. }
  735. /**
  736. * Implements hook_system_info_alter().
  737. *
  738. * Checks if the module provides any search item types or service classes. If it
  739. * does, and there are search indexes using those item types, respectively
  740. * servers using those service classes, the module is set to "required".
  741. *
  742. * Heavily borrowed from field_system_info_alter().
  743. *
  744. * @see hook_search_api_item_type_info()
  745. */
  746. function search_api_system_info_alter(&$info, $file, $type) {
  747. if ($type != 'module' || $file->name == 'search_api') {
  748. return;
  749. }
  750. // Check for defined item types.
  751. if (module_hook($file->name, 'search_api_item_type_info')) {
  752. $types = array();
  753. foreach (search_api_get_item_type_info() as $type => $type_info) {
  754. if ($type_info['module'] == $file->name) {
  755. $types[] = $type;
  756. }
  757. }
  758. if ($types) {
  759. $sql = 'SELECT machine_name, name FROM {search_api_index} WHERE item_type IN (:types)';
  760. $indexes = db_query($sql, array(':types' => $types))->fetchAllKeyed();
  761. if ($indexes) {
  762. $info['required'] = TRUE;
  763. $links = array();
  764. foreach ($indexes as $id => $name) {
  765. $url = url("admin/config/search/search_api/index/$id");
  766. $links[] = '<a href="' . check_plain($url) . '">' . check_plain($name) . '</a>';
  767. }
  768. $args = array('!indexes' => implode(', ', $links));
  769. $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);
  770. }
  771. }
  772. }
  773. // Check for defined service classes.
  774. if (module_hook($file->name, 'search_api_service_info')) {
  775. $classes = array();
  776. foreach (search_api_get_service_info() as $class => $class_info) {
  777. if ($class_info['module'] == $file->name) {
  778. $classes[] = $class;
  779. }
  780. }
  781. if ($classes) {
  782. $sql = 'SELECT machine_name, name FROM {search_api_server} WHERE class IN (:classes)';
  783. $servers = db_query($sql, array(':classes' => $classes))->fetchAllKeyed();
  784. if ($servers) {
  785. $info['required'] = TRUE;
  786. $links = array();
  787. foreach ($servers as $id => $name) {
  788. $url = url("admin/config/search/search_api/server/$id");
  789. $links[] = '<a href="' . check_plain($url) . '">' . check_plain($name) . '</a>';
  790. }
  791. $args = array('!servers' => implode(', ', $links));
  792. $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);
  793. $info['explanation'] = (!empty($info['explanation']) ? $info['explanation'] . ' ' : '') . $explanation;
  794. }
  795. }
  796. }
  797. }
  798. /**
  799. * Implements hook_entity_insert().
  800. *
  801. * This is implemented on behalf of the SearchApiEntityDataSourceController
  802. * datasource controller and calls search_api_track_item_insert() for the
  803. * inserted items.
  804. *
  805. * @see search_api_search_api_item_type_info()
  806. */
  807. function search_api_entity_insert($entity, $type) {
  808. // When inserting a new search index, the new index was already inserted into
  809. // the tracking table. This would lead to a duplicate-key issue, if we would
  810. // continue.
  811. // We also only react on entity operations for types with property
  812. // information, as we don't provide search integration for the others.
  813. if ($type == 'search_api_index' || !entity_get_property_info($type)) {
  814. return;
  815. }
  816. list($id) = entity_extract_ids($type, $entity);
  817. if (isset($id)) {
  818. search_api_track_item_insert($type, array($id));
  819. }
  820. }
  821. /**
  822. * Implements hook_entity_update().
  823. *
  824. * This is implemented on behalf of the SearchApiEntityDataSourceController
  825. * datasource controller and calls search_api_track_item_change() for the
  826. * updated items.
  827. *
  828. * @see search_api_search_api_item_type_info()
  829. */
  830. function search_api_entity_update($entity, $type) {
  831. // We only react on entity operations for types with property information, as
  832. // we don't provide search integration for the others.
  833. if (!entity_get_property_info($type)) {
  834. return;
  835. }
  836. list($id) = entity_extract_ids($type, $entity);
  837. if (isset($id)) {
  838. search_api_track_item_change($type, array($id));
  839. }
  840. }
  841. /**
  842. * Implements hook_entity_delete().
  843. *
  844. * This is implemented on behalf of the SearchApiEntityDataSourceController
  845. * datasource controller and calls search_api_track_item_delete() for the
  846. * deleted items.
  847. *
  848. * @see search_api_search_api_item_type_info()
  849. */
  850. function search_api_entity_delete($entity, $type) {
  851. // We only react on entity operations for types with property information, as
  852. // we don't provide search integration for the others.
  853. if (!entity_get_property_info($type)) {
  854. return;
  855. }
  856. list($id) = entity_extract_ids($type, $entity);
  857. if (isset($id)) {
  858. search_api_track_item_delete($type, array($id));
  859. }
  860. }
  861. /**
  862. * Implements hook_field_update_field().
  863. *
  864. * Recalculates fields settings if the cardinality of the field has changed from
  865. * or to 1.
  866. */
  867. function search_api_field_update_field($field, $prior_field) {
  868. $before = $prior_field['cardinality'];
  869. $after = $field['cardinality'];
  870. if ($before != $after && ($before == 1 || $after == 1)) {
  871. // Unfortunately, we cannot call this right away since the field information
  872. // is only stored after the hook is called.
  873. drupal_register_shutdown_function('search_api_index_recalculate_fields');
  874. }
  875. }
  876. /**
  877. * Implements hook_flush_caches().
  878. *
  879. * Recalculates fields settings in case the schema (in most cases: the
  880. * multiplicity) of a property has changed.
  881. */
  882. function search_api_flush_caches() {
  883. search_api_index_recalculate_fields();
  884. }
  885. /**
  886. * Implements hook_search_api_item_type_info().
  887. *
  888. * Adds item types for all entity types with property information.
  889. */
  890. function search_api_search_api_item_type_info() {
  891. $types = array();
  892. foreach (entity_get_property_info() as $type => $property_info) {
  893. if ($info = entity_get_info($type)) {
  894. $types[$type] = array(
  895. 'name' => $info['label'],
  896. 'datasource controller' => 'SearchApiEntityDataSourceController',
  897. 'entity_type' => $type,
  898. );
  899. }
  900. }
  901. return $types;
  902. }
  903. /**
  904. * Implements hook_modules_enabled().
  905. */
  906. function search_api_modules_enabled() {
  907. // New modules might offer additional item types or service classes,
  908. // invalidating the cached information.
  909. drupal_static_reset('search_api_get_item_type_info');
  910. drupal_static_reset('search_api_get_service_info');
  911. }
  912. /**
  913. * Implements hook_modules_disabled().
  914. */
  915. function search_api_modules_disabled() {
  916. // The disabled modules might have offered item types or service classes,
  917. // invalidating the cached information.
  918. drupal_static_reset('search_api_get_item_type_info');
  919. drupal_static_reset('search_api_get_service_info');
  920. }
  921. /**
  922. * Implements hook_search_api_alter_callback_info().
  923. */
  924. function search_api_search_api_alter_callback_info() {
  925. $callbacks['search_api_alter_bundle_filter'] = array(
  926. 'name' => t('Bundle filter'),
  927. 'description' => t('Exclude items from indexing based on their bundle (content type, vocabulary, …).'),
  928. 'class' => 'SearchApiAlterBundleFilter',
  929. // Filters should be executed first.
  930. 'weight' => -10,
  931. );
  932. $callbacks['search_api_alter_role_filter'] = array(
  933. 'name' => t('Role filter'),
  934. 'description' => t('Exclude users from indexing based on their role.'),
  935. 'class' => 'SearchApiAlterRoleFilter',
  936. // Filters should be executed first.
  937. 'weight' => -10,
  938. );
  939. $callbacks['search_api_alter_add_url'] = array(
  940. 'name' => t('URL field'),
  941. 'description' => t("Adds the item's URL to the indexed data."),
  942. 'class' => 'SearchApiAlterAddUrl',
  943. );
  944. $callbacks['search_api_alter_add_aggregation'] = array(
  945. 'name' => t('Aggregated fields'),
  946. 'description' => t('Gives you the ability to define additional fields, containing data from one or more other fields.'),
  947. 'class' => 'SearchApiAlterAddAggregation',
  948. );
  949. $callbacks['search_api_alter_add_viewed_entity'] = array(
  950. 'name' => t('Complete entity view'),
  951. 'description' => t('Adds an additional field containing the whole HTML content of the entity when viewed.'),
  952. 'class' => 'SearchApiAlterAddViewedEntity',
  953. );
  954. $callbacks['search_api_alter_add_hierarchy'] = array(
  955. 'name' => t('Index hierarchy'),
  956. 'description' => t('Allows to index hierarchical fields along with all their ancestors.'),
  957. 'class' => 'SearchApiAlterAddHierarchy',
  958. );
  959. $callbacks['search_api_alter_language_control'] = array(
  960. 'name' => t('Language control'),
  961. 'description' => t('Lets you determine the language of items in the index.'),
  962. 'class' => 'SearchApiAlterLanguageControl',
  963. );
  964. $callbacks['search_api_alter_node_access'] = array(
  965. 'name' => t('Node access'),
  966. '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.'),
  967. 'class' => 'SearchApiAlterNodeAccess',
  968. );
  969. $callbacks['search_api_alter_comment_access'] = array(
  970. 'name' => t('Access check'),
  971. '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.'),
  972. 'class' => 'SearchApiAlterCommentAccess',
  973. );
  974. $callbacks['search_api_alter_node_status'] = array(
  975. 'name' => t('Exclude unpublished nodes'),
  976. '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.'),
  977. 'class' => 'SearchApiAlterNodeStatus',
  978. );
  979. return $callbacks;
  980. }
  981. /**
  982. * Implements hook_search_api_processor_info().
  983. */
  984. function search_api_search_api_processor_info() {
  985. $processors['search_api_case_ignore'] = array(
  986. 'name' => t('Ignore case'),
  987. 'description' => t('This processor will make searches case-insensitive for fulltext or string fields.'),
  988. 'class' => 'SearchApiIgnoreCase',
  989. );
  990. $processors['search_api_html_filter'] = array(
  991. 'name' => t('HTML filter'),
  992. 'description' => t('Strips HTML tags from fulltext fields and decodes HTML entities. ' .
  993. 'Use this processor when indexing HTML data, e.g., node bodies for certain text formats.<br />' .
  994. 'The processor also allows to boost (or ignore) the contents of specific elements.'),
  995. 'class' => 'SearchApiHtmlFilter',
  996. 'weight' => 10,
  997. );
  998. if (module_exists('transliteration')) {
  999. $processors['search_api_transliteration'] = array(
  1000. 'name' => t('Transliteration'),
  1001. 'description' => t('This processor will make searches insensitive to accents and other non-ASCII characters.'),
  1002. 'class' => 'SearchApiTransliteration',
  1003. 'weight' => 15,
  1004. );
  1005. }
  1006. $processors['search_api_tokenizer'] = array(
  1007. 'name' => t('Tokenizer'),
  1008. 'description' => t('Tokenizes fulltext data by stripping whitespace. ' .
  1009. 'This processor allows you to specify which characters make up words and which characters should be ignored, using regular expression syntax. ' .
  1010. 'Otherwise it is up to the search server implementation to decide how to split indexed fulltext data.'),
  1011. 'class' => 'SearchApiTokenizer',
  1012. 'weight' => 20,
  1013. );
  1014. $processors['search_api_stopwords'] = array(
  1015. 'name' => t('Stopwords'),
  1016. 'description' => t('This processor prevents certain words from being indexed and removes them from search terms. ' .
  1017. 'For best results, it should only be executed after tokenizing.'),
  1018. 'class' => 'SearchApiStopWords',
  1019. 'weight' => 30,
  1020. );
  1021. $processors['search_api_highlighting'] = array(
  1022. 'name' => t('Highlighting'),
  1023. 'description' => t('Adds highlighting for search results.'),
  1024. 'class' => 'SearchApiHighlight',
  1025. 'weight' => 35,
  1026. );
  1027. return $processors;
  1028. }
  1029. /**
  1030. * Inserts new unindexed items for all indexes on the specified type.
  1031. *
  1032. * @param string $type
  1033. * The item type of the new items.
  1034. * @param array $item_ids
  1035. * The IDs of the new items.
  1036. */
  1037. function search_api_track_item_insert($type, array $item_ids) {
  1038. $conditions = array(
  1039. 'enabled' => 1,
  1040. 'item_type' => $type,
  1041. 'read_only' => 0,
  1042. );
  1043. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1044. if (!$indexes) {
  1045. return;
  1046. }
  1047. try {
  1048. search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
  1049. }
  1050. catch (SearchApiException $e) {
  1051. $vars['%item_type'] = $type;
  1052. watchdog_exception('search_api', $e, '%type while inserting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1053. return;
  1054. }
  1055. foreach ($indexes as $index) {
  1056. if (!empty($index->options['index_directly'])) {
  1057. search_api_index_specific_items_delayed($index, $item_ids);
  1058. }
  1059. }
  1060. }
  1061. /**
  1062. * Mark the items with the specified IDs as "dirty", i.e., as needing to be reindexed.
  1063. *
  1064. * For indexes for which items should be indexed immediately, the items are
  1065. * indexed directly, instead.
  1066. *
  1067. * @param $type
  1068. * The type of items, specific to the data source.
  1069. * @param array $item_ids
  1070. * The IDs of the items to be marked dirty.
  1071. */
  1072. function search_api_track_item_change($type, array $item_ids) {
  1073. $conditions = array(
  1074. 'enabled' => 1,
  1075. 'item_type' => $type,
  1076. 'read_only' => 0,
  1077. );
  1078. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1079. if (!$indexes) {
  1080. return;
  1081. }
  1082. try {
  1083. search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
  1084. foreach ($indexes as $index) {
  1085. if (!empty($index->options['index_directly'])) {
  1086. // For indexes with the index_directly option set, queue the items to be
  1087. // indexed at the end of the request.
  1088. try {
  1089. search_api_index_specific_items_delayed($index, $item_ids);
  1090. }
  1091. catch (SearchApiException $e) {
  1092. watchdog_exception('search_api', $e);
  1093. }
  1094. }
  1095. }
  1096. }
  1097. catch (SearchApiException $e) {
  1098. $vars['%item_type'] = $type;
  1099. watchdog_exception('search_api', $e, '%type while updating items of type %item_type: !message in %function (line %line of %file).', $vars);
  1100. return;
  1101. }
  1102. }
  1103. /**
  1104. * Marks items as queued for indexing for the specified index.
  1105. *
  1106. * @param SearchApiIndex $index
  1107. * The index on which items were queued.
  1108. * @param array $item_ids
  1109. * The ids of the queued items.
  1110. *
  1111. * @deprecated
  1112. * As of Search API 1.10, the cron queue is not used for indexing anymore,
  1113. * therefore this function has become useless. It will, along with
  1114. * SearchApiDataSourceControllerInterface::trackItemQueued(), be removed in
  1115. * the Drupal 8 version of this module.
  1116. */
  1117. function search_api_track_item_queued(SearchApiIndex $index, array $item_ids) {
  1118. try {
  1119. $index->datasource()->trackItemQueued($item_ids, $index);
  1120. }
  1121. catch (SearchApiException $e) {
  1122. watchdog_exception('search_api', $e);
  1123. }
  1124. }
  1125. /**
  1126. * Marks items as successfully indexed for the specified index.
  1127. *
  1128. * @param SearchApiIndex $index
  1129. * The index on which items were indexed.
  1130. * @param array $item_ids
  1131. * The ids of the indexed items.
  1132. */
  1133. function search_api_track_item_indexed(SearchApiIndex $index, array $item_ids) {
  1134. $index->datasource()->trackItemIndexed($item_ids, $index);
  1135. module_invoke_all('search_api_items_indexed', $index, $item_ids);
  1136. }
  1137. /**
  1138. * Removes items from all indexes.
  1139. *
  1140. * @param $type
  1141. * The type of the items.
  1142. * @param array $item_ids
  1143. * The IDs of the deleted items.
  1144. */
  1145. function search_api_track_item_delete($type, array $item_ids) {
  1146. // First, delete the item from the tracking table.
  1147. $conditions = array(
  1148. 'enabled' => 1,
  1149. 'item_type' => $type,
  1150. 'read_only' => 0,
  1151. );
  1152. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  1153. if ($indexes) {
  1154. try {
  1155. search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
  1156. }
  1157. catch (SearchApiException $e) {
  1158. $vars['%item_type'] = $type;
  1159. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1160. }
  1161. }
  1162. // Then, delete it from all servers. Servers of disabled indexes have to be
  1163. // considered, too!
  1164. unset($conditions['enabled']);
  1165. foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
  1166. try {
  1167. if ($server = $index->server()) {
  1168. $server->deleteItems($item_ids, $index);
  1169. }
  1170. }
  1171. catch (Exception $e) {
  1172. $vars['%item_type'] = $type;
  1173. watchdog_exception('search_api', $e, '%type while deleting items of type %item_type: !message in %function (line %line of %file).', $vars);
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * Checks for pending tasks on one or all enabled search servers.
  1179. *
  1180. * @param SearchApiServer|null $server
  1181. * (optional) The server whose tasks should be checked. If not given, the
  1182. * tasks for all enabled servers are checked.
  1183. *
  1184. * @return bool
  1185. * TRUE if all tasks (for the specific server, if $server was given) were
  1186. * executed successfully, or if there were no tasks. FALSE if there are still
  1187. * pending tasks.
  1188. */
  1189. function search_api_server_tasks_check(SearchApiServer $server = NULL) {
  1190. $select = db_select('search_api_task', 't')
  1191. ->fields('t')
  1192. // Only retrieve tasks we can handle.
  1193. ->condition('t.type', array('addIndex', 'fieldsUpdated', 'removeIndex', 'deleteItems'));
  1194. if ($server) {
  1195. $select->condition('t.server_id', $server->machine_name);
  1196. }
  1197. else {
  1198. $select->innerJoin('search_api_server', 's', 't.server_id = s.machine_name AND s.enabled = 1');
  1199. // By ordering by the server, we can later just load them when we reach them
  1200. // while looping through the tasks. It is very unlikely there will be tasks
  1201. // for more than one or two servers, so a *_load_multiple() probably
  1202. // wouldn't bring any significant advantages, but complicate the code.
  1203. $select->orderBy('t.server_id');
  1204. }
  1205. // Store a count query for later checking whether all tasks were processed
  1206. // successfully.
  1207. $count_query = $select->countQuery();
  1208. // Sometimes the order of tasks might be important, so make sure to order by
  1209. // the task ID (which should be in order of insertion).
  1210. $select->orderBy('t.id');
  1211. $tasks = $select->execute();
  1212. $executed_tasks = array();
  1213. foreach ($tasks as $task) {
  1214. if (!$server || $server->machine_name != $task->server_id) {
  1215. $server = search_api_server_load($task->server_id);
  1216. if (!$server) {
  1217. continue;
  1218. }
  1219. }
  1220. switch ($task->type) {
  1221. case 'addIndex':
  1222. $index = search_api_index_load($task->index_id);
  1223. if ($index) {
  1224. $server->addIndex($index);
  1225. }
  1226. break;
  1227. case 'fieldsUpdated':
  1228. $index = search_api_index_load($task->index_id);
  1229. if ($index) {
  1230. if ($task->data) {
  1231. $index->original = unserialize($task->data);
  1232. }
  1233. $server->fieldsUpdated($index);
  1234. }
  1235. break;
  1236. case 'removeIndex':
  1237. $index = search_api_index_load($task->index_id);
  1238. if ($index) {
  1239. $server->removeIndex($index ? $index : $task->index_id);
  1240. }
  1241. break;
  1242. case 'deleteItems':
  1243. $ids = $task->data ? unserialize($task->data) : 'all';
  1244. $index = $task->index_id ? search_api_index_load($task->index_id) : NULL;
  1245. // Since a failed load returns (for stupid menu handler reasons) FALSE,
  1246. // not NULL, we have to make doubly sure here not to pass an invalid
  1247. // value (and cause a fatal error).
  1248. $index = $index ? $index : NULL;
  1249. $server->deleteItems($ids, $index);
  1250. break;
  1251. default:
  1252. // This should never happen.
  1253. continue;
  1254. }
  1255. $executed_tasks[] = $task->id;
  1256. }
  1257. // If there were no tasks (we recognized), return TRUE.
  1258. if (!$executed_tasks) {
  1259. return TRUE;
  1260. }
  1261. // Otherwise, delete the executed tasks and check if new tasks were created.
  1262. search_api_server_tasks_delete($executed_tasks);
  1263. return $count_query->execute()->fetchField() === 0;
  1264. }
  1265. /**
  1266. * Adds an entry into a server's list of pending tasks.
  1267. *
  1268. * @param SearchApiServer $server
  1269. * The server for which a task should be remembered.
  1270. * @param $type
  1271. * The type of task to perform.
  1272. * @param SearchApiIndex|string|null $index
  1273. * (optional) If applicable, the index to which the task pertains (or its
  1274. * machine name).
  1275. * @param mixed $data
  1276. * (optional) If applicable, some further data necessary for the task.
  1277. */
  1278. function search_api_server_tasks_add(SearchApiServer $server, $type, $index = NULL, $data = NULL) {
  1279. db_insert('search_api_task')
  1280. ->fields(array(
  1281. 'server_id' => $server->machine_name,
  1282. 'type' => $type,
  1283. 'index_id' => $index ? (is_object($index) ? $index->machine_name : $index) : NULL,
  1284. 'data' => isset($data) ? serialize($data) : NULL,
  1285. ))
  1286. ->execute();
  1287. }
  1288. /**
  1289. * Removes pending server tasks from the list.
  1290. *
  1291. * @param array|null $ids
  1292. * (optional) The IDs of the pending server tasks to delete. Set to NULL
  1293. * to not filter by IDs.
  1294. * @param SearchApiServer|null $server
  1295. * (optional) A server for which the tasks should be deleted. Set to NULL to
  1296. * delete tasks from all servers.
  1297. * @param SearchApiIndex|string|null $index
  1298. * (optional) An index (or its machine name) for which the tasks should be
  1299. * deleted. Set to NULL to delete tasks for all indexes.
  1300. */
  1301. function search_api_server_tasks_delete(array $ids = NULL, SearchApiServer $server = NULL, $index = NULL) {
  1302. $delete = db_delete('search_api_task');
  1303. if ($ids) {
  1304. $delete->condition('id', $ids);
  1305. }
  1306. if ($server) {
  1307. $delete->condition('server_id', $server->machine_name);
  1308. }
  1309. if ($index) {
  1310. $delete->condition('index_id', $index->machine_name);
  1311. }
  1312. $delete->execute();
  1313. }
  1314. /**
  1315. * Recalculates the saved fields of an index.
  1316. *
  1317. * This is mostly necessary when the multiplicity of the underlying properties
  1318. * change. The method will re-examine the data structure of the entities in each
  1319. * index and, if a discrepancy is spotted, re-save that index with updated
  1320. * fields options (thus, of course, also triggering a re-indexing operation).
  1321. *
  1322. * @param SearchApiIndex[]|false $indexes
  1323. * An array of SearchApiIndex objects on which to perform the operation, or
  1324. * FALSE to perform it on all indexes.
  1325. */
  1326. function search_api_index_recalculate_fields($indexes = FALSE) {
  1327. if (!is_array($indexes)) {
  1328. $indexes = search_api_index_load_multiple(FALSE);
  1329. }
  1330. $stored_keys = drupal_map_assoc(array('type', 'entity_type', 'real_type', 'boost'));
  1331. foreach ($indexes as $index) {
  1332. if (empty($index->options['fields'])) {
  1333. continue;
  1334. }
  1335. // We have to clear the cache, both static and stored, before using
  1336. // getFields(). Otherwise, we'd just use the stale data which the fields
  1337. // options are probably already based on.
  1338. cache_clear_all($index->getCacheId() . '-1-0', 'cache');
  1339. $index->resetCaches();
  1340. // getFields() automatically uses the actual data types to correct possible
  1341. // stale data.
  1342. $fields = $index->getFields();
  1343. foreach ($fields as $key => $field) {
  1344. $fields[$key] = array_intersect_key($field, $stored_keys);
  1345. if (isset($fields[$key]['boost']) && $fields[$key]['boost'] == '1.0') {
  1346. unset($fields[$key]['boost']);
  1347. }
  1348. }
  1349. // Use a more accurate method of determining if the fields settings are
  1350. // equal to avoid needlessly re-indexing the whole index.
  1351. if ($fields != $index->options['fields']) {
  1352. $options = $index->options;
  1353. $options['fields'] = $fields;
  1354. $index->update(array('options' => $options));
  1355. }
  1356. }
  1357. }
  1358. /**
  1359. * Test two setting arrays (or individual settings) for equality.
  1360. *
  1361. * @param mixed $setting1
  1362. * The first setting (array).
  1363. * @param mixed $setting2
  1364. * The second setting (array).
  1365. *
  1366. * @return bool
  1367. * TRUE if both settings are identical, FALSE otherwise.
  1368. *
  1369. * @deprecated The simple "==" operator will achieve the same.
  1370. */
  1371. function _search_api_settings_equals($setting1, $setting2) {
  1372. if (!is_array($setting1) || !is_array($setting2)) {
  1373. return $setting1 == $setting2;
  1374. }
  1375. foreach ($setting1 as $key => $value) {
  1376. if (!array_key_exists($key, $setting2)) {
  1377. return FALSE;
  1378. }
  1379. if (!_search_api_settings_equals($value, $setting2[$key])) {
  1380. return FALSE;
  1381. }
  1382. unset($setting2[$key]);
  1383. }
  1384. // If any keys weren't unset previously, they are not present in $setting1 and
  1385. // the two are different.
  1386. return !$setting2;
  1387. }
  1388. /**
  1389. * Indexes items for the specified index.
  1390. *
  1391. * Only items marked as changed are indexed, in their order of change (if
  1392. * known).
  1393. *
  1394. * @param SearchApiIndex $index
  1395. * The index on which items should be indexed.
  1396. * @param int $limit
  1397. * (optional) The number of items which should be indexed at most. Defaults to
  1398. * -1, which means that all changed items should be indexed.
  1399. *
  1400. * @return int
  1401. * Number of successfully indexed items.
  1402. *
  1403. * @throws SearchApiException
  1404. * If any error occurs during indexing.
  1405. */
  1406. function search_api_index_items(SearchApiIndex $index, $limit = -1) {
  1407. // Don't try to index on read-only indexes.
  1408. if ($index->read_only) {
  1409. return 0;
  1410. }
  1411. $ids = search_api_get_items_to_index($index, $limit);
  1412. return $ids ? count(search_api_index_specific_items($index, $ids)) : 0;
  1413. }
  1414. /**
  1415. * Indexes the specified items on the given index.
  1416. *
  1417. * Items which were successfully indexed are marked as such afterwards.
  1418. *
  1419. * @param SearchApiIndex $index
  1420. * The index on which items should be indexed.
  1421. * @param array $ids
  1422. * The IDs of the items which should be indexed.
  1423. *
  1424. * @return array
  1425. * The IDs of all successfully indexed items.
  1426. *
  1427. * @throws SearchApiException
  1428. * If any error occurs during indexing.
  1429. */
  1430. function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
  1431. // Before doing anything else, check whether there are pending tasks that need
  1432. // to be executed on the server. It might be important that they are executed
  1433. // before any indexing occurs.
  1434. if (!search_api_server_tasks_check($index->server())) {
  1435. throw new SearchApiException(t('Could not index items since important pending server tasks could not be performed.'));
  1436. }
  1437. $items = $index->loadItems($ids);
  1438. // Clone items because data alterations may alter them.
  1439. $cloned_items = array();
  1440. foreach ($items as $id => $item) {
  1441. if (is_object($item)) {
  1442. $cloned_items[$id] = clone $item;
  1443. }
  1444. else {
  1445. // Normally, items that can't be loaded shouldn't be returned by
  1446. // entity_load (and other loadItems() implementations). Therefore, this is
  1447. // an extremely rare case, which seems to happen during installation for
  1448. // some specific setups.
  1449. $type = search_api_get_item_type_info($index->item_type);
  1450. $type = $type ? $type['name'] : $index->item_type;
  1451. watchdog('search_api', "Error during indexing: invalid item loaded for @type with ID @id.", array('@id' => $id, '@type' => $type), WATCHDOG_WARNING);
  1452. }
  1453. }
  1454. $indexed = $items ? $index->index($cloned_items) : array();
  1455. if ($indexed) {
  1456. search_api_track_item_indexed($index, $indexed);
  1457. // If some items could not be indexed, we don't want to try re-indexing
  1458. // them right away, so we mark them as "freshly" changed. Sadly, there is
  1459. // no better way than to mark them as indexed first...
  1460. if (count($indexed) < count($ids)) {
  1461. // Believe it or not but this is actually quite faster than the equivalent
  1462. // $diff = array_diff($ids, $indexed);
  1463. $diff = array_keys(array_diff_key(array_flip($ids), array_flip($indexed)));
  1464. $index->datasource()->trackItemIndexed($diff, $index);
  1465. $index->datasource()->trackItemChange($diff, array($index));
  1466. }
  1467. }
  1468. return $indexed;
  1469. }
  1470. /**
  1471. * Queues items for indexing at the end of the page request.
  1472. *
  1473. * @param SearchApiIndex $index
  1474. * The index on which items should be indexed.
  1475. * @param array $ids
  1476. * The IDs of the items which should be indexed.
  1477. *
  1478. * @return array
  1479. * The current contents of the queue, as a reference.
  1480. *
  1481. * @see search_api_index_specific_items()
  1482. * @see _search_api_index_queued_items()
  1483. */
  1484. function &search_api_index_specific_items_delayed(SearchApiIndex $index = NULL, array $ids = array()) {
  1485. // We cannot use drupal_static() here because the static cache is reset during
  1486. // batch processing, which breaks batch handling.
  1487. static $queue = array();
  1488. static $registered = FALSE;
  1489. // Only register the shutdown function once.
  1490. if (empty($registered)) {
  1491. drupal_register_shutdown_function('_search_api_index_queued_items');
  1492. $registered = TRUE;
  1493. }
  1494. // Allow for empty call to just retrieve the queue.
  1495. if ($index && $ids) {
  1496. $index_id = $index->machine_name;
  1497. $queue += array($index_id => array());
  1498. $queue[$index_id] += drupal_map_assoc($ids);
  1499. }
  1500. return $queue;
  1501. }
  1502. /**
  1503. * Returns a list of items that need to be indexed for the specified index.
  1504. *
  1505. * @param SearchApiIndex $index
  1506. * The index for which items should be retrieved.
  1507. * @param $limit
  1508. * The maximum number of items to retrieve. -1 means no limit.
  1509. *
  1510. * @return array
  1511. * An array of IDs of items that need to be indexed.
  1512. */
  1513. function search_api_get_items_to_index(SearchApiIndex $index, $limit = -1) {
  1514. if ($limit == 0) {
  1515. return array();
  1516. }
  1517. return $index->datasource()->getChangedItems($index, $limit);
  1518. }
  1519. /**
  1520. * Creates a search query on a specified search index.
  1521. *
  1522. * @param $id
  1523. * The ID or machine name of the index to execute the search on.
  1524. * @param $options
  1525. * An associative array of options to be passed to
  1526. * SearchApiQueryInterface::__construct().
  1527. *
  1528. * @return SearchApiQueryInterface
  1529. * An object for searching on the specified index.
  1530. *
  1531. * @throws SearchApiException
  1532. * If the index is unknown or disabled, or some other error was encountered.
  1533. */
  1534. function search_api_query($id, array $options = array()) {
  1535. $index = search_api_index_load($id);
  1536. if (!$index) {
  1537. throw new SearchApiException(t('Unknown index with ID @id.', array('@id' => $id)));
  1538. }
  1539. return $index->query($options);
  1540. }
  1541. /**
  1542. * Stores or retrieves a search executed in this page request.
  1543. *
  1544. * Static storage for the searches executed during the current page request. Can
  1545. * used to store an executed search, or to retrieve a previously stored search.
  1546. *
  1547. * @param $search_id
  1548. * For pages displaying multiple searches, an optional ID identifying the
  1549. * search in questions. When storing a search, this is filled automatically,
  1550. * unless it is manually set.
  1551. * @param SearchApiQuery $query
  1552. * When storing an executed search, the query that was executed. NULL
  1553. * otherwise.
  1554. * @param array $results
  1555. * When storing an executed search, the returned results as specified by
  1556. * SearchApiQueryInterface::execute(). An empty array, otherwise.
  1557. *
  1558. * @return array
  1559. * If a search with the specified ID was executed, an array containing
  1560. * ($query, $results) as used in this function's parameters. If $search_id is
  1561. * NULL, an array of all executed searches will be returned, keyed by ID.
  1562. */
  1563. function search_api_current_search($search_id = NULL, SearchApiQuery $query = NULL, array $results = array()) {
  1564. $searches = &drupal_static(__FUNCTION__, array());
  1565. if (isset($query)) {
  1566. if (!isset($search_id)) {
  1567. $search_id = $query->getOption('search id');
  1568. }
  1569. $base = $search_id;
  1570. $i = 0;
  1571. while (isset($searches[$search_id])) {
  1572. $search_id = $base . '-' . ++$i;
  1573. }
  1574. $searches[$search_id] = array($query, $results);
  1575. }
  1576. if (isset($search_id)) {
  1577. return isset($searches[$search_id]) ? $searches[$search_id] : NULL;
  1578. }
  1579. return $searches;
  1580. }
  1581. /**
  1582. * Returns all field types recognized by the Search API framework.
  1583. *
  1584. * @return array
  1585. * An associative array with all recognized types as keys, mapped to their
  1586. * translated display names.
  1587. *
  1588. * @see search_api_default_field_types()
  1589. * @see search_api_get_data_type_info()
  1590. */
  1591. function search_api_field_types() {
  1592. $types = search_api_default_field_types();
  1593. foreach (search_api_get_data_type_info() as $id => $type) {
  1594. $types[$id] = $type['name'];
  1595. }
  1596. return $types;
  1597. }
  1598. /**
  1599. * Returns the default field types recognized by the Search API framework.
  1600. *
  1601. * @return array
  1602. * An associative array with the default types as keys, mapped to their
  1603. * translated display names.
  1604. */
  1605. function search_api_default_field_types() {
  1606. return array(
  1607. 'text' => t('Fulltext'),
  1608. 'string' => t('String'),
  1609. 'integer' => t('Integer'),
  1610. 'decimal' => t('Decimal'),
  1611. 'date' => t('Date'),
  1612. 'duration' => t('Duration'),
  1613. 'boolean' => t('Boolean'),
  1614. 'uri' => t('URI'),
  1615. );
  1616. }
  1617. /**
  1618. * Returns either all custom field type definitions, or a specific one.
  1619. *
  1620. * @param $type
  1621. * If specified, the type whose definition should be returned.
  1622. *
  1623. * @return array
  1624. * If $type was not given, an array containing all custom data types, in the
  1625. * format specified by hook_search_api_data_type_info().
  1626. * Otherwise, the definition for the given type, or NULL if it is unknown.
  1627. *
  1628. * @see hook_search_api_data_type_info()
  1629. */
  1630. function search_api_get_data_type_info($type = NULL) {
  1631. $types = &drupal_static(__FUNCTION__);
  1632. if (!isset($types)) {
  1633. $default_types = search_api_default_field_types();
  1634. $types = module_invoke_all('search_api_data_type_info');
  1635. $types = $types ? $types : array();
  1636. foreach ($types as &$type_info) {
  1637. if (!isset($type_info['fallback']) || !isset($default_types[$type_info['fallback']])) {
  1638. $type_info['fallback'] = 'string';
  1639. }
  1640. }
  1641. drupal_alter('search_api_data_type_info', $types);
  1642. }
  1643. if (isset($type)) {
  1644. return isset($types[$type]) ? $types[$type] : NULL;
  1645. }
  1646. return $types;
  1647. }
  1648. /**
  1649. * Returns either a list of all available service infos, or a specific one.
  1650. *
  1651. * @see hook_search_api_service_info()
  1652. *
  1653. * @param string|null $id
  1654. * The ID of the service info to retrieve.
  1655. *
  1656. * @return array
  1657. * If $id was not specified, an array of all available service classes.
  1658. * Otherwise, either the service info with the specified id (if it exists),
  1659. * or NULL. Service class information is formatted as specified by
  1660. * hook_search_api_service_info(), with the addition of a "module" key
  1661. * specifying the module that adds a certain class.
  1662. */
  1663. function search_api_get_service_info($id = NULL) {
  1664. $services = &drupal_static(__FUNCTION__);
  1665. if (!isset($services)) {
  1666. // Inlined version of module_invoke_all() to add "module" keys.
  1667. $services = array();
  1668. foreach (module_implements('search_api_service_info') as $module) {
  1669. $function = $module . '_search_api_service_info';
  1670. if (function_exists($function)) {
  1671. $new_services = $function();
  1672. if (isset($new_services) && is_array($new_services)) {
  1673. foreach ($new_services as $service => $info) {
  1674. $new_services[$service] += array('module' => $module);
  1675. }
  1676. }
  1677. $services += $new_services;
  1678. }
  1679. }
  1680. // Same for drupal_alter().
  1681. foreach (module_implements('search_api_service_info_alter') as $module) {
  1682. $function = $module . '_search_api_service_info_alter';
  1683. if (function_exists($function)) {
  1684. $old = $services;
  1685. $function($services);
  1686. if ($new_services = array_diff_key($services, $old)) {
  1687. foreach ($new_services as $service => $info) {
  1688. $services[$service] += array('module' => $module);
  1689. }
  1690. }
  1691. }
  1692. }
  1693. }
  1694. if (isset($id)) {
  1695. return isset($services[$id]) ? $services[$id] : NULL;
  1696. }
  1697. return $services;
  1698. }
  1699. /**
  1700. * Returns information for either all item types, or a specific one.
  1701. *
  1702. * @param string|null $type
  1703. * If set, the item type whose information should be returned.
  1704. *
  1705. * @return array|null
  1706. * If $type is given, either an array containing the information of that item
  1707. * type, or NULL if it is unknown. Otherwise, an array keyed by type IDs
  1708. * containing the information for all item types. Item type information is
  1709. * formatted as specified by hook_search_api_item_type_info(), with the
  1710. * addition of a "module" key specifying the module that adds a certain type.
  1711. *
  1712. * @see hook_search_api_item_type_info()
  1713. */
  1714. function search_api_get_item_type_info($type = NULL) {
  1715. $types = &drupal_static(__FUNCTION__);
  1716. if (!isset($types)) {
  1717. // Inlined version of module_invoke_all() to add "module" keys.
  1718. $types = array();
  1719. foreach (module_implements('search_api_item_type_info') as $module) {
  1720. $function = $module . '_search_api_item_type_info';
  1721. if (function_exists($function)) {
  1722. $new_types = $function();
  1723. if (isset($new_types) && is_array($new_types)) {
  1724. foreach ($new_types as $id => $info) {
  1725. $new_types[$id] += array('module' => $module);
  1726. }
  1727. }
  1728. $types += $new_types;
  1729. }
  1730. }
  1731. // Same for drupal_alter().
  1732. foreach (module_implements('search_api_item_type_info_alter') as $module) {
  1733. $function = $module . '_search_api_item_type_info_alter';
  1734. if (function_exists($function)) {
  1735. $old = $types;
  1736. $function($types);
  1737. if ($new_types = array_diff_key($types, $old)) {
  1738. foreach ($new_types as $id => $info) {
  1739. $types[$id] += array('module' => $module);
  1740. }
  1741. }
  1742. }
  1743. }
  1744. }
  1745. if (isset($type)) {
  1746. return isset($types[$type]) ? $types[$type] : NULL;
  1747. }
  1748. return $types;
  1749. }
  1750. /**
  1751. * Get a data source controller object for the specified type.
  1752. *
  1753. * @param $type
  1754. * The type whose data source controller should be returned.
  1755. *
  1756. * @return SearchApiDataSourceControllerInterface
  1757. * The type's data source controller.
  1758. *
  1759. * @throws SearchApiException
  1760. * If the type is unknown or specifies an invalid data source controller.
  1761. */
  1762. function search_api_get_datasource_controller($type) {
  1763. $datasources = &drupal_static(__FUNCTION__, array());
  1764. if (empty($datasources[$type])) {
  1765. $info = search_api_get_item_type_info($type);
  1766. if (isset($info['datasource controller']) && class_exists($info['datasource controller'])) {
  1767. $datasources[$type] = new $info['datasource controller']($type);
  1768. }
  1769. if (empty($datasources[$type]) || !($datasources[$type] instanceof SearchApiDataSourceControllerInterface)) {
  1770. unset($datasources[$type]);
  1771. throw new SearchApiException(t('Unknown or invalid item type @type.', array('@type' => $type)));
  1772. }
  1773. }
  1774. return $datasources[$type];
  1775. }
  1776. /**
  1777. * Returns a list of all available data alter callbacks.
  1778. *
  1779. * @see hook_search_api_alter_callback_info()
  1780. *
  1781. * @return array
  1782. * An array of all available data alter callbacks, keyed by function name.
  1783. */
  1784. function search_api_get_alter_callbacks() {
  1785. $callbacks = &drupal_static(__FUNCTION__);
  1786. if (!isset($callbacks)) {
  1787. $callbacks = module_invoke_all('search_api_alter_callback_info');
  1788. // Fill optional settings with default values.
  1789. foreach ($callbacks as $id => $callback) {
  1790. $callbacks[$id] += array('weight' => 0);
  1791. }
  1792. // Invoke alter hook.
  1793. drupal_alter('search_api_alter_callback_info', $callbacks);
  1794. }
  1795. return $callbacks;
  1796. }
  1797. /**
  1798. * Returns a list of all available pre- and post-processors.
  1799. *
  1800. * @see hook_search_api_processor_info()
  1801. *
  1802. * @return array
  1803. * An array of all available processors, keyed by id.
  1804. */
  1805. function search_api_get_processors() {
  1806. $processors = &drupal_static(__FUNCTION__);
  1807. if (!isset($processors)) {
  1808. $processors = module_invoke_all('search_api_processor_info');
  1809. // Fill optional settings with default values.
  1810. foreach ($processors as $id => $processor) {
  1811. $processors[$id] += array('weight' => 0);
  1812. }
  1813. // Invoke alter hook.
  1814. drupal_alter('search_api_processor_info', $processors);
  1815. }
  1816. return $processors;
  1817. }
  1818. /**
  1819. * Implements hook_search_api_query_alter().
  1820. *
  1821. * Adds node access to the query, if enabled.
  1822. *
  1823. * @param SearchApiQueryInterface $query
  1824. * The SearchApiQueryInterface object representing the search query.
  1825. */
  1826. function search_api_search_api_query_alter(SearchApiQueryInterface $query) {
  1827. global $user;
  1828. $index = $query->getIndex();
  1829. // Only add node access if the necessary fields are indexed in the index, and
  1830. // unless disabled explicitly by the query.
  1831. $type = $index->getEntityType();
  1832. if (!empty($index->options['data_alter_callbacks']["search_api_alter_{$type}_access"]['status']) && !$query->getOption('search_api_bypass_access')) {
  1833. $account = $query->getOption('search_api_access_account', $user);
  1834. if (is_numeric($account)) {
  1835. $account = user_load($account);
  1836. }
  1837. if (is_object($account)) {
  1838. try {
  1839. _search_api_query_add_node_access($account, $query, $type);
  1840. }
  1841. catch (SearchApiException $e) {
  1842. watchdog_exception('search_api', $e);
  1843. }
  1844. }
  1845. else {
  1846. $account = $query->getOption('search_api_access_account', '(' . t('none') . ')');
  1847. if (is_object($account)) {
  1848. $account = $account->uid;
  1849. }
  1850. if (!is_scalar($account)) {
  1851. $account = var_export($account, TRUE);
  1852. }
  1853. watchdog('search_api', 'An illegal user UID was given for node access: @uid.', array('@uid' => $account), WATCHDOG_WARNING);
  1854. }
  1855. }
  1856. }
  1857. /**
  1858. * Adds a node access filter to a search query, if applicable.
  1859. *
  1860. * @param object $account
  1861. * The user object, who searches.
  1862. * @param SearchApiQueryInterface $query
  1863. * The query to which a node access filter should be added, if applicable.
  1864. * @param string $type
  1865. * (optional) The type of search – either "node" or "comment". Defaults to
  1866. * "node".
  1867. *
  1868. * @throws SearchApiException
  1869. * If not all necessary fields are indexed on the index.
  1870. */
  1871. function _search_api_query_add_node_access($account, SearchApiQueryInterface $query, $type = 'node') {
  1872. // Don't do anything if the user can access all content.
  1873. if (user_access('bypass node access', $account)) {
  1874. return;
  1875. }
  1876. $is_comment = ($type == 'comment');
  1877. // Check whether the necessary fields are indexed.
  1878. $fields = $query->getIndex()->options['fields'];
  1879. $required = array('search_api_access_node', 'status');
  1880. if (!$is_comment) {
  1881. $required[] = 'author';
  1882. }
  1883. foreach ($required as $field) {
  1884. if (empty($fields[$field])) {
  1885. $vars['@field'] = $field;
  1886. $vars['@index'] = $query->getIndex()->name;
  1887. throw new SearchApiException(t('Required field @field not indexed on index @index. Could not perform access checks.', $vars));
  1888. }
  1889. }
  1890. // If the user cannot access content/comments at all, return no results.
  1891. if (!user_access('access content', $account) || ($is_comment && !user_access('access content', $account))) {
  1892. // Simple hack for returning no results.
  1893. $query->condition('status', 0);
  1894. $query->condition('status', 1);
  1895. watchdog('search_api', 'User @name tried to execute a search, but cannot access content.', array('@name' => theme('username', array('account' => $account))), WATCHDOG_NOTICE);
  1896. return;
  1897. }
  1898. // Filter by the "published" status.
  1899. $published = $is_comment ? COMMENT_PUBLISHED : NODE_PUBLISHED;
  1900. if (!$is_comment && user_access('view own unpublished content')) {
  1901. $filter = $query->createFilter('OR');
  1902. $filter->condition('status', $published);
  1903. $filter->condition('author', $account->uid);
  1904. $query->filter($filter);
  1905. }
  1906. else {
  1907. $query->condition('status', $published);
  1908. }
  1909. // Filter by node access grants.
  1910. $filter = $query->createFilter('OR');
  1911. $grants = node_access_grants('view', $account);
  1912. foreach ($grants as $realm => $gids) {
  1913. foreach ($gids as $gid) {
  1914. $filter->condition('search_api_access_node', "node_access_$realm:$gid");
  1915. }
  1916. }
  1917. $filter->condition('search_api_access_node', 'node_access__all');
  1918. $query->filter($filter);
  1919. }
  1920. /**
  1921. * Determines whether a field of the given type contains text data.
  1922. *
  1923. * Can also be used to find other types.
  1924. *
  1925. * @param string $type
  1926. * The type for which to check.
  1927. * @param array $allowed
  1928. * Optionally, an array of allowed types.
  1929. *
  1930. * @return
  1931. * TRUE if $type is either one of the specified types, or a list of such
  1932. * values. FALSE otherwise.
  1933. *
  1934. * @see search_api_extract_inner_type()
  1935. */
  1936. function search_api_is_text_type($type, array $allowed = array('text')) {
  1937. return array_search(search_api_extract_inner_type($type), $allowed) !== FALSE;
  1938. }
  1939. /**
  1940. * Utility function for determining whether a field of the given type contains
  1941. * a list of any kind.
  1942. *
  1943. * @param $type
  1944. * A string containing the type to check.
  1945. *
  1946. * @return
  1947. * TRUE iff $type is a list type ("list<*>").
  1948. */
  1949. function search_api_is_list_type($type) {
  1950. return substr($type, 0, 5) == 'list<';
  1951. }
  1952. /**
  1953. * Utility function for determining the nesting level of a list type.
  1954. *
  1955. * @param $type
  1956. * A string containing the type to check.
  1957. *
  1958. * @return
  1959. * The nesting level of the type. 0 for singular types, 1 for lists of
  1960. * singular types, etc.
  1961. */
  1962. function search_api_list_nesting_level($type) {
  1963. $level = 0;
  1964. while (search_api_is_list_type($type)) {
  1965. $type = substr($type, 5, -1);
  1966. ++$level;
  1967. }
  1968. return $level;
  1969. }
  1970. /**
  1971. * Utility function for nesting a type to the same level as another type.
  1972. * I.e., after <code>$t = search_api_nest_type($type, $nested_type);</code> is
  1973. * executed, the following statements will always be true:
  1974. * @code
  1975. * search_api_list_nesting_level($t) == search_api_list_nesting_level($nested_type);
  1976. * search_api_extract_inner_type($t) == search_api_extract_inner_type($type);
  1977. * @endcode
  1978. *
  1979. * @param $type
  1980. * The type to wrap.
  1981. * @param $nested_type
  1982. * Another type, determining the nesting level.
  1983. *
  1984. * @return
  1985. * A list version of $type, as specified above.
  1986. */
  1987. function search_api_nest_type($type, $nested_type) {
  1988. while (search_api_is_list_type($nested_type)) {
  1989. $nested_type = substr($nested_type, 5, -1);
  1990. $type = "list<$type>";
  1991. }
  1992. return $type;
  1993. }
  1994. /**
  1995. * Utility function for extracting the contained primitive type of a list type.
  1996. *
  1997. * @param $type
  1998. * A string containing the list type to process.
  1999. *
  2000. * @return
  2001. * A string containing the primitive type contained within the list, e.g.
  2002. * "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
  2003. * type, it is returned unchanged.
  2004. */
  2005. function search_api_extract_inner_type($type) {
  2006. while (search_api_is_list_type($type)) {
  2007. $type = substr($type, 5, -1);
  2008. }
  2009. return $type;
  2010. }
  2011. /**
  2012. * Helper function for reacting to index updates with regards to the datasource.
  2013. *
  2014. * When an overridden index is reverted, its numerical ID will sometimes change.
  2015. * Since the default datasource implementation uses that for referencing
  2016. * indexes, the index ID in the items table must be updated accordingly. This is
  2017. * implemented in this function.
  2018. *
  2019. * Modules implementing other datasource controllers, that use a table other
  2020. * than {search_api_item}, can use this function, too. It should be called
  2021. * uncoditionally in a hook_search_api_index_update() implementation. If this
  2022. * function isn't used, similar code should be added there.
  2023. *
  2024. * However, note that this is only necessary (and this function should only be
  2025. * called) if the indexes are referenced by numerical ID in the items table.
  2026. *
  2027. * @param SearchApiIndex $index
  2028. * The index that was changed.
  2029. * @param string $table
  2030. * The table containing items information, analogous to {search_api_item}.
  2031. * @param string $column
  2032. * The column in $table that holds the index's numerical ID.
  2033. */
  2034. function search_api_index_update_datasource(SearchApiIndex $index, $table, $column = 'index_id') {
  2035. if ($index->id != $index->original->id) {
  2036. db_update($table)
  2037. ->fields(array($column => $index->id))
  2038. ->condition($column, $index->original->id)
  2039. ->execute();
  2040. }
  2041. }
  2042. /**
  2043. * Extracts specific field values from an EntityMetadataWrapper object.
  2044. *
  2045. * @param EntityMetadataWrapper $wrapper
  2046. * The wrapper from which to extract fields.
  2047. * @param array $fields
  2048. * The fields to extract, as stored in an index. I.e., the array keys are
  2049. * field names, the values are arrays with at least a "type" key present.
  2050. * @param array $value_options
  2051. * An array of options that should be passed to the
  2052. * EntityMetadataWrapper::value() method (see there).
  2053. *
  2054. * @return array
  2055. * The $fields array with additional "value" and "original_type" keys set.
  2056. */
  2057. function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
  2058. // If $wrapper is a list of entities, we have to aggregate their field values.
  2059. $wrapper_info = $wrapper->info();
  2060. if (search_api_is_list_type($wrapper_info['type'])) {
  2061. foreach ($fields as &$info) {
  2062. $info['value'] = array();
  2063. $info['original_type'] = $info['type'];
  2064. }
  2065. unset($info);
  2066. try {
  2067. foreach ($wrapper as $w) {
  2068. $nested_fields = search_api_extract_fields($w, $fields, $value_options);
  2069. foreach ($nested_fields as $field => $info) {
  2070. if (isset($info['value'])) {
  2071. $fields[$field]['value'][] = $info['value'];
  2072. }
  2073. if (isset($info['original_type'])) {
  2074. $fields[$field]['original_type'] = $info['original_type'];
  2075. }
  2076. }
  2077. }
  2078. }
  2079. catch (EntityMetadataWrapperException $e) {
  2080. // Catch exceptions caused by not set list values.
  2081. }
  2082. return $fields;
  2083. }
  2084. $nested = array();
  2085. $entity_infos = entity_get_info();
  2086. foreach ($fields as $field => &$info) {
  2087. $pos = strpos($field, ':');
  2088. if ($pos === FALSE) {
  2089. // Set "defaults" in case an error occurs later.
  2090. $info['value'] = NULL;
  2091. $info['original_type'] = $info['type'];
  2092. if (isset($wrapper->$field)) {
  2093. try {
  2094. $info['value'] = $wrapper->$field->value($value_options);
  2095. // For fulltext fields with options, also include the option labels.
  2096. if (search_api_is_text_type($info['type']) && $wrapper->$field->optionsList('view')) {
  2097. _search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
  2098. }
  2099. $property_info = $wrapper->$field->info();
  2100. $info['original_type'] = $property_info['type'];
  2101. // For entities, we extract the entity ID instead of the whole object.
  2102. // @todo Use 'identifier' => TRUE instead of always loading the object.
  2103. $t = search_api_extract_inner_type($property_info['type']);
  2104. if (isset($entity_infos[$t])) {
  2105. // If no object is set, set this field to NULL.
  2106. $info['value'] = $info['value'] ? _search_api_extract_entity_value($wrapper->$field, search_api_is_text_type($info['type'])) : NULL;
  2107. }
  2108. }
  2109. catch (EntityMetadataWrapperException $e) {
  2110. // This might happen for entity-typed properties that are NULL, e.g.,
  2111. // for comments without parent.
  2112. }
  2113. }
  2114. }
  2115. else {
  2116. list($prefix, $key) = explode(':', $field, 2);
  2117. $nested[$prefix][$key] = $info;
  2118. }
  2119. }
  2120. unset($info);
  2121. foreach ($nested as $prefix => $nested_fields) {
  2122. if (isset($wrapper->$prefix)) {
  2123. $nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
  2124. # http://drupal.org/node/1873910#comment-6876200
  2125. // $subwrapper = $wrapper->$prefix;
  2126. // $subwrapper->language( $wrapper->language->value() );
  2127. // $nested_fields = search_api_extract_fields($subwrapper, $nested_fields, $value_options);
  2128. foreach ($nested_fields as $field => $info) {
  2129. $fields["$prefix:$field"] = $info;
  2130. }
  2131. }
  2132. else {
  2133. foreach ($nested_fields as &$info) {
  2134. $info['value'] = NULL;
  2135. $info['original_type'] = $info['type'];
  2136. }
  2137. }
  2138. }
  2139. return $fields;
  2140. }
  2141. /**
  2142. * Helper method for adding additional text data to fields with an option list.
  2143. */
  2144. function _search_api_add_option_values(&$value, array $options) {
  2145. if (is_array($value)) {
  2146. foreach ($value as &$v) {
  2147. _search_api_add_option_values($v, $options);
  2148. }
  2149. return;
  2150. }
  2151. if (is_scalar($value) && isset($options[$value])) {
  2152. $value .= ' ' . $options[$value];
  2153. }
  2154. }
  2155. /**
  2156. * Helper method for extracting the ID (and possibly label) of an entity-valued field.
  2157. */
  2158. function _search_api_extract_entity_value(EntityMetadataWrapper $wrapper, $fulltext = FALSE) {
  2159. $v = $wrapper->value();
  2160. if (is_array($v)) {
  2161. $ret = array();
  2162. foreach ($wrapper as $item) {
  2163. $values = _search_api_extract_entity_value($item, $fulltext);
  2164. if ($values) {
  2165. $ret[] = $values;
  2166. }
  2167. }
  2168. return $ret;
  2169. }
  2170. if ($v) {
  2171. $ret = $wrapper->getIdentifier();
  2172. if ($fulltext && ($label = $wrapper->label())) {
  2173. $ret .= ' ' . $label;
  2174. }
  2175. return $ret;
  2176. }
  2177. return NULL;
  2178. }
  2179. /**
  2180. * Load the search server with the specified id.
  2181. *
  2182. * @param $id
  2183. * The search server's id.
  2184. * @param $reset
  2185. * Whether to reset the internal cache.
  2186. *
  2187. * @return SearchApiServer
  2188. * An object representing the server with the specified id.
  2189. */
  2190. function search_api_server_load($id, $reset = FALSE) {
  2191. $ret = search_api_server_load_multiple(array($id), array(), $reset);
  2192. return $ret ? reset($ret) : FALSE;
  2193. }
  2194. /**
  2195. * Load multiple servers at once, determined by IDs or machine names, or by
  2196. * other conditions.
  2197. *
  2198. * @see entity_load()
  2199. *
  2200. * @param array|false $ids
  2201. * An array of server IDs or machine names, or FALSE to load all servers.
  2202. * @param array $conditions
  2203. * An array of conditions on the {search_api_server} table in the form
  2204. * 'field' => $value.
  2205. * @param bool $reset
  2206. * Whether to reset the internal entity_load cache.
  2207. *
  2208. * @return SearchApiServer[]
  2209. * An array of server objects keyed by machine name.
  2210. */
  2211. function search_api_server_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2212. $servers = entity_load('search_api_server', $ids, $conditions, $reset);
  2213. return entity_key_array_by_property($servers, 'machine_name');
  2214. }
  2215. /**
  2216. * Entity uri callback.
  2217. */
  2218. function search_api_server_url(SearchApiServer $server) {
  2219. return array(
  2220. 'path' => 'admin/config/search/search_api/server/' . $server->machine_name,
  2221. 'options' => array(),
  2222. );
  2223. }
  2224. /**
  2225. * Title callback for determining which title should be displayed for the
  2226. * "delete" local task.
  2227. *
  2228. * @param Entity $entity
  2229. * The server or index for which the menu link is displayed.
  2230. *
  2231. * @return string
  2232. * A translated version of either "Delete" or "Revert".
  2233. */
  2234. function search_api_title_delete_page(Entity $entity) {
  2235. return $entity->hasStatus(ENTITY_OVERRIDDEN) ? t('Revert') : t('Delete');
  2236. }
  2237. /**
  2238. * Determines whether the current user can disable a server or index.
  2239. *
  2240. * @param Entity $entity
  2241. * The server or index for which the access to the "disable" page is checked.
  2242. *
  2243. * @return bool
  2244. * TRUE if the "disable" page can be accessed by the user, FALSE otherwise.
  2245. */
  2246. function search_api_access_disable_page(Entity $entity) {
  2247. return user_access('administer search_api') && !empty($entity->enabled);
  2248. }
  2249. /**
  2250. * Access callback for determining if a server's or index' "delete" page should
  2251. * be accessible.
  2252. *
  2253. * @param Entity $entity
  2254. * The server or index for which the access to the delete page is checked.
  2255. *
  2256. * @return
  2257. * TRUE if the delete page can be accessed by the user, FALSE otherwise.
  2258. */
  2259. function search_api_access_delete_page(Entity $entity) {
  2260. return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
  2261. }
  2262. /**
  2263. * Determines whether a user can access a certain search server or index.
  2264. *
  2265. * Used as an access callback in search_api_entity_info().
  2266. */
  2267. function search_api_entity_access() {
  2268. return user_access('administer search_api');
  2269. }
  2270. /**
  2271. * Inserts a new search server into the database.
  2272. *
  2273. * @param array $values
  2274. * An array containing the values to be inserted.
  2275. *
  2276. * @return
  2277. * The newly inserted server's id, or FALSE on error.
  2278. */
  2279. function search_api_server_insert(array $values) {
  2280. $server = entity_create('search_api_server', $values);
  2281. $server->is_new = TRUE;
  2282. $server->save();
  2283. return $server->id;
  2284. }
  2285. /**
  2286. * Changes a server's settings.
  2287. *
  2288. * @param string|int $id
  2289. * The ID or machine name of the server whose values should be changed.
  2290. * @param array $fields
  2291. * The new field values to set. The enabled field can't be set this way, use
  2292. * search_api_server_enable() and search_api_server_disable() instead.
  2293. *
  2294. * @return int|false
  2295. * 1 if fields were changed, 0 if the fields already had the desired values.
  2296. * FALSE on failure.
  2297. */
  2298. function search_api_server_edit($id, array $fields) {
  2299. $server = search_api_server_load($id, TRUE);
  2300. $ret = $server->update($fields);
  2301. return $ret ? 1 : $ret;
  2302. }
  2303. /**
  2304. * Enables a search server.
  2305. *
  2306. * Will also check for remembered tasks for this server and execute them.
  2307. *
  2308. * @param string|int $id
  2309. * The ID or machine name of the server to enable.
  2310. *
  2311. * @return int|false
  2312. * 1 on success, 0 or FALSE on failure.
  2313. */
  2314. function search_api_server_enable($id) {
  2315. $server = search_api_server_load($id, TRUE);
  2316. $ret = $server->update(array('enabled' => 1));
  2317. return $ret ? 1 : $ret;
  2318. }
  2319. /**
  2320. * Disables a search server.
  2321. *
  2322. * Will also disable all associated indexes and remove them from the server.
  2323. *
  2324. * @param string|int $id
  2325. * The ID or machine name of the server to disable.
  2326. *
  2327. * @return int|false
  2328. * 1 on success, 0 or FALSE on failure.
  2329. */
  2330. function search_api_server_disable($id) {
  2331. $server = search_api_server_load($id, TRUE);
  2332. $ret = $server->update(array('enabled' => 0));
  2333. return $ret ? 1 : $ret;
  2334. }
  2335. /**
  2336. * Clears a search server.
  2337. *
  2338. * Will delete all items stored on the server and mark all associated indexes
  2339. * for re-indexing.
  2340. *
  2341. * @param int|string $id
  2342. * The ID or machine name of the server to clear.
  2343. *
  2344. * @return bool
  2345. * TRUE on success, FALSE on failure.
  2346. */
  2347. function search_api_server_clear($id) {
  2348. $server = search_api_server_load($id);
  2349. $success = TRUE;
  2350. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  2351. $success &= $index->reindex();
  2352. }
  2353. if ($success) {
  2354. $server->deleteItems();
  2355. }
  2356. return $success;
  2357. }
  2358. /**
  2359. * Deletes a search server and disables all associated indexes.
  2360. *
  2361. * @param $id
  2362. * The ID or machine name of the server to delete.
  2363. *
  2364. * @return
  2365. * 1 on success, 0 or FALSE on failure.
  2366. */
  2367. function search_api_server_delete($id) {
  2368. $server = search_api_server_load($id, TRUE);
  2369. $server->delete();
  2370. return 1;
  2371. }
  2372. /**
  2373. * Loads the Search API index with the specified id.
  2374. *
  2375. * @param $id
  2376. * The index' id.
  2377. * @param $reset
  2378. * Whether to reset the internal cache.
  2379. *
  2380. * @return SearchApiIndex|false
  2381. * A completely loaded index object, or FALSE if no such index exists.
  2382. */
  2383. function search_api_index_load($id, $reset = FALSE) {
  2384. $ret = search_api_index_load_multiple(array($id), array(), $reset);
  2385. return reset($ret);
  2386. }
  2387. /**
  2388. * Load multiple indexes at once, determined by IDs or machine names, or by
  2389. * other conditions.
  2390. *
  2391. * @see entity_load()
  2392. *
  2393. * @param array|false $ids
  2394. * An array of index IDs or machine names, or FALSE to load all indexes.
  2395. * @param array $conditions
  2396. * An array of conditions on the {search_api_index} table in the form
  2397. * 'field' => $value.
  2398. * @param bool $reset
  2399. * Whether to reset the internal entity_load cache.
  2400. *
  2401. * @return SearchApiIndex[]
  2402. * An array of index objects keyed by machine name.
  2403. */
  2404. function search_api_index_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  2405. // This line is a workaround for a weird PDO bug in PHP 5.2.
  2406. // See http://drupal.org/node/889286.
  2407. new SearchApiIndex();
  2408. $indexes = entity_load('search_api_index', $ids, $conditions, $reset);
  2409. return entity_key_array_by_property($indexes, 'machine_name');
  2410. }
  2411. /**
  2412. * Determines a search index' indexing status.
  2413. *
  2414. * @param SearchApiIndex $index
  2415. * The index whose indexing status should be determined.
  2416. *
  2417. * @return array
  2418. * An associative array containing two keys (in this order):
  2419. * - indexed: The number of items already indexed in their latest version.
  2420. * - total: The total number of items that have to be indexed for this index.
  2421. */
  2422. function search_api_index_status(SearchApiIndex $index) {
  2423. return $index->datasource()->getIndexStatus($index);
  2424. }
  2425. /**
  2426. * Entity uri callback.
  2427. */
  2428. function search_api_index_url(SearchApiIndex $index) {
  2429. return array(
  2430. 'path' => 'admin/config/search/search_api/index/' . $index->machine_name,
  2431. 'options' => array(),
  2432. );
  2433. }
  2434. /**
  2435. * Returns an index's server.
  2436. *
  2437. * Used as a property getter callback for the index's "server_entity" prioperty
  2438. * in search_api_entity_property_info().
  2439. *
  2440. * @param SearchApiIndex $index
  2441. * The index whose server should be returned.
  2442. *
  2443. * @return SearchApiServer|null
  2444. * The server this index currently resides on, or NULL if the index is
  2445. * currently unassigned.
  2446. */
  2447. function search_api_index_get_server(SearchApiIndex $index) {
  2448. try {
  2449. return $index->server();
  2450. }
  2451. catch (SearchApiException $e) {
  2452. watchdog_exception('search_api', $e);
  2453. return NULL;
  2454. }
  2455. }
  2456. /**
  2457. * Returns an options list for the "status" property.
  2458. *
  2459. * Used as an options list callback in search_api_entity_property_info().
  2460. *
  2461. * @return array
  2462. * An array of options, as defined by hook_options_list().
  2463. */
  2464. function search_api_status_options_list() {
  2465. return array(
  2466. ENTITY_CUSTOM => t('Custom'),
  2467. ENTITY_IN_CODE => t('Default'),
  2468. ENTITY_OVERRIDDEN => t('Overridden'),
  2469. ENTITY_FIXED => t('Fixed'),
  2470. );
  2471. }
  2472. /**
  2473. * Inserts a new search index into the database.
  2474. *
  2475. * @param array $values
  2476. * An array containing the values to be inserted.
  2477. *
  2478. * @return
  2479. * The newly inserted index' id, or FALSE on error.
  2480. */
  2481. function search_api_index_insert(array $values) {
  2482. $index = entity_create('search_api_index', $values);
  2483. $index->is_new = TRUE;
  2484. $index->save();
  2485. return $index->id;
  2486. }
  2487. /**
  2488. * Changes an index' settings.
  2489. *
  2490. * @param int|string $id
  2491. * The edited index' ID or machine name.
  2492. * @param array $fields
  2493. * The new field values to set.
  2494. *
  2495. * @return int|false
  2496. * 1 if fields were changed, 0 if the fields already had the desired values.
  2497. * FALSE on failure.
  2498. */
  2499. function search_api_index_edit($id, array $fields) {
  2500. $index = search_api_index_load($id, TRUE);
  2501. $ret = $index->update($fields);
  2502. return $ret ? 1 : $ret;
  2503. }
  2504. /**
  2505. * Changes an index' indexed field settings.
  2506. *
  2507. * @param int|string $id
  2508. * The ID or machine name of the index whose fields should be changed.
  2509. * @param array $fields
  2510. * The new indexed field settings.
  2511. *
  2512. * @return int|false
  2513. * 1 if the field settings were changed, 0 if they already had the desired
  2514. * values. FALSE on failure.
  2515. */
  2516. function search_api_index_edit_fields($id, array $fields) {
  2517. $index = search_api_index_load($id, TRUE);
  2518. $options = $index->options;
  2519. $options['fields'] = $fields;
  2520. $ret = $index->update(array('options' => $options));
  2521. return $ret ? 1 : $ret;
  2522. }
  2523. /**
  2524. * Enables a search index.
  2525. *
  2526. * @param string|int $id
  2527. * The ID or machine name of the index to enable.
  2528. *
  2529. * @return int|false
  2530. * 1 on success, 0 or FALSE on failure.
  2531. *
  2532. * @throws SearchApiException
  2533. * If the index's server doesn't exist.
  2534. */
  2535. function search_api_index_enable($id) {
  2536. $index = search_api_index_load($id, TRUE);
  2537. $ret = $index->update(array('enabled' => 1));
  2538. return $ret ? 1 : $ret;
  2539. }
  2540. /**
  2541. * Disables a search index.
  2542. *
  2543. * @param string|int $id
  2544. * The ID or machine name of the index to disable.
  2545. *
  2546. * @return int|false
  2547. * 1 on success, 0 or FALSE on failure.
  2548. *
  2549. * @throws SearchApiException
  2550. * If the index's server doesn't exist.
  2551. */
  2552. function search_api_index_disable($id) {
  2553. $index = search_api_index_load($id, TRUE);
  2554. $ret = $index->update(array('enabled' => 0));
  2555. return $ret ? 1 : $ret;
  2556. }
  2557. /**
  2558. * Schedules a search index for re-indexing.
  2559. *
  2560. * @param $id
  2561. * The ID or machine name of the index to re-index.
  2562. *
  2563. * @return
  2564. * TRUE on success, FALSE on failure.
  2565. */
  2566. function search_api_index_reindex($id) {
  2567. $index = search_api_index_load($id);
  2568. return $index->reindex();
  2569. }
  2570. /**
  2571. * Helper method for marking all items on an index as needing re-indexing.
  2572. *
  2573. * @param SearchApiIndex $index
  2574. * The index whose items should be re-indexed.
  2575. */
  2576. function _search_api_index_reindex(SearchApiIndex $index) {
  2577. $index->datasource()->trackItemChange(FALSE, array($index), TRUE);
  2578. }
  2579. /**
  2580. * Clears a search index and schedules all of its items for re-indexing.
  2581. *
  2582. * @param $id
  2583. * The ID or machine name of the index to clear.
  2584. *
  2585. * @return
  2586. * TRUE on success, FALSE on failure.
  2587. */
  2588. function search_api_index_clear($id) {
  2589. $index = search_api_index_load($id);
  2590. return $index->clear();
  2591. }
  2592. /**
  2593. * Deletes a search index.
  2594. *
  2595. * @param $id
  2596. * The ID or machine name of the index to delete.
  2597. *
  2598. * @return
  2599. * TRUE on success, FALSE on failure.
  2600. */
  2601. function search_api_index_delete($id) {
  2602. $index = search_api_index_load($id);
  2603. if (!$index) {
  2604. return FALSE;
  2605. }
  2606. $index->delete();
  2607. return TRUE;
  2608. }
  2609. /**
  2610. * Options list callback for search indexes.
  2611. *
  2612. * @return array
  2613. * An array of search index machine names mapped to their human-readable
  2614. * names.
  2615. */
  2616. function search_api_index_options_list() {
  2617. $ret = array(
  2618. NULL => '- ' . t('All') . ' -',
  2619. );
  2620. foreach (search_api_index_load_multiple(FALSE) as $id => $index) {
  2621. $ret[$id] = $index->name;
  2622. }
  2623. return $ret;
  2624. }
  2625. /**
  2626. * Shutdown function which indexes all queued items, if any.
  2627. */
  2628. function _search_api_index_queued_items() {
  2629. $queue = &search_api_index_specific_items_delayed();
  2630. try {
  2631. if ($queue) {
  2632. $indexes = search_api_index_load_multiple(array_keys($queue));
  2633. foreach ($indexes as $index_id => $index) {
  2634. search_api_index_specific_items($index, $queue[$index_id]);
  2635. }
  2636. }
  2637. // Reset the queue so we don't index the items twice by accident.
  2638. $queue = array();
  2639. }
  2640. catch (SearchApiException $e) {
  2641. watchdog_exception('search_api', $e);
  2642. }
  2643. }
  2644. /**
  2645. * Helper function to be used as a "property info alter" callback.
  2646. *
  2647. * If a wrapped entity is passed to this function, all its available properties
  2648. * and fields, regardless of bundle, are added to the wrapper.
  2649. */
  2650. function _search_api_wrapper_add_all_properties(EntityMetadataWrapper $wrapper, array $property_info) {
  2651. if ($properties = entity_get_all_property_info($wrapper->type())) {
  2652. $property_info['properties'] = $properties;
  2653. }
  2654. return $property_info;
  2655. }
  2656. /**
  2657. * Helper function for converting data to a custom type.
  2658. */
  2659. function _search_api_convert_custom_type($callback, $value, $original_type, $type, $nesting_level) {
  2660. if ($nesting_level == 0) {
  2661. return call_user_func($callback, $value, $original_type, $type);
  2662. }
  2663. if (!is_array($value)) {
  2664. return NULL;
  2665. }
  2666. --$nesting_level;
  2667. $values = array();
  2668. foreach ($value as $v) {
  2669. $v = _search_api_convert_custom_type($callback, $v, $original_type, $type, $nesting_level);
  2670. if (isset($v) && !(is_array($v) && !$v)) {
  2671. $values[] = $v;
  2672. }
  2673. }
  2674. return $values;
  2675. }
  2676. /**
  2677. * Determines the number of items indexed on a server for a certain index.
  2678. *
  2679. * Used as a helper function in search_api_admin_index_view().
  2680. *
  2681. * @param SearchApiIndex $index
  2682. * The index
  2683. *
  2684. * @return int
  2685. * The number of items found on the server for this index, if the latter is
  2686. * enabled. 0 otherwise.
  2687. *
  2688. * @throws SearchApiException
  2689. * If an error prevented the search from completing.
  2690. */
  2691. function _search_api_get_items_on_server(SearchApiIndex $index) {
  2692. if (!$index->enabled) {
  2693. return 0;
  2694. }
  2695. // We want the raw count, without facets or other filters. Therefore we don't
  2696. // use the query's execute() method but pass it straight to the server for
  2697. // evaluation. Since this circumvents the normal preprocessing, which sets the
  2698. // fields (on which some service classes might even rely when there are no
  2699. // keywords), we set them manually here.
  2700. $query = $index->query()
  2701. ->fields(array())
  2702. ->range(0, 0);
  2703. $response = $index->server()->search($query);
  2704. return $response['result count'];
  2705. }
  2706. /**
  2707. * Returns a deep copy of the input array.
  2708. *
  2709. * The behavior of PHP regarding arrays with references pointing to it is rather
  2710. * weird. Therefore, we use this helper function in theme_search_api_index() to
  2711. * create safe copies of such arrays.
  2712. *
  2713. * @param array $array
  2714. * The array to copy.
  2715. *
  2716. * @return array
  2717. * A deep copy of the array.
  2718. */
  2719. function _search_api_deep_copy(array $array) {
  2720. $copy = array();
  2721. foreach ($array as $k => $v) {
  2722. if (is_array($v)) {
  2723. $copy[$k] = _search_api_deep_copy($v);
  2724. }
  2725. elseif (is_object($v)) {
  2726. $copy[$k] = clone $v;
  2727. }
  2728. elseif ($v) {
  2729. $copy[$k] = $v;
  2730. }
  2731. }
  2732. return $copy;
  2733. }
  2734. /**
  2735. * Creates and sets a batch for indexing items.
  2736. *
  2737. * @param SearchApiIndex $index
  2738. * The index for which items should be indexed.
  2739. * @param int $batch_size
  2740. * Number of items to index per batch.
  2741. * @param int $limit
  2742. * Maximum number of items to index. Negative values mean "no limit".
  2743. * @param int $remaining
  2744. * Remaining items to index.
  2745. * @param bool $drush
  2746. * Boolean specifying whether this was called from drush or not.
  2747. *
  2748. * @return bool
  2749. * Whether the batch was created and set successfully.
  2750. */
  2751. function _search_api_batch_indexing_create(SearchApiIndex $index, $batch_size, $limit, $remaining, $drush = FALSE) {
  2752. if ($limit !== 0 && $batch_size !== 0) {
  2753. $t = !empty($drush) ? 'dt' : 't';
  2754. if ($limit < 0 || $limit > $remaining) {
  2755. $limit = $remaining;
  2756. }
  2757. if ($batch_size < 0) {
  2758. $batch_size = $remaining;
  2759. }
  2760. $batch = array(
  2761. 'title' => $t('Indexing items'),
  2762. 'operations' => array(
  2763. array('_search_api_batch_indexing_callback', array($index, $batch_size, $limit, $drush)),
  2764. ),
  2765. 'progress_message' => $t('Completed about @percentage% of the indexing operation.'),
  2766. 'finished' => '_search_api_batch_indexing_finished',
  2767. 'file' => drupal_get_path('module', 'search_api') . '/search_api.module',
  2768. );
  2769. batch_set($batch);
  2770. return TRUE;
  2771. }
  2772. return FALSE;
  2773. }
  2774. /**
  2775. * Batch API callback for the indexing functionality.
  2776. *
  2777. * @param SearchApiIndex $index
  2778. * The index for which items should be indexed.
  2779. * @param integer $batch_size
  2780. * Number of items to index per batch.
  2781. * @param integer $limit
  2782. * Maximum number of items to index.
  2783. * @param boolean $drush
  2784. * Boolean specifying whether this was called from drush or not.
  2785. * @param $context
  2786. * An array (or object implementing ArrayAccess) containing the batch context.
  2787. */
  2788. function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, $limit, $drush = FALSE, &$context) {
  2789. // Persistent data among batch runs.
  2790. if (!isset($context['sandbox']['limit'])) {
  2791. $context['sandbox']['limit'] = $limit;
  2792. $context['sandbox']['batch_size'] = $batch_size;
  2793. $context['sandbox']['progress'] = 0;
  2794. }
  2795. // Persistent data for results.
  2796. if (!isset($context['results']['indexed'])) {
  2797. $context['results']['indexed'] = 0;
  2798. $context['results']['not indexed'] = 0;
  2799. $context['results']['drush'] = $drush;
  2800. }
  2801. // Number of items to index for this run.
  2802. $to_index = min($context['sandbox']['limit'] - $context['sandbox']['progress'], $context['sandbox']['batch_size']);
  2803. // Index the items.
  2804. try {
  2805. $indexed = search_api_index_items($index, $to_index);
  2806. $context['results']['indexed'] += $indexed;
  2807. }
  2808. catch (SearchApiException $e) {
  2809. watchdog_exception('search_api', $e);
  2810. $vars['@message'] = $e->getMessage();
  2811. $context['message'] = t('An error occurred during indexing: @message.', $vars);
  2812. $context['finished'] = 1;
  2813. $context['results']['not indexed'] += $context['sandbox']['limit'] - $context['sandbox']['progress'];
  2814. return;
  2815. }
  2816. // Display progress message.
  2817. if ($indexed > 0) {
  2818. $format_plural = $context['results']['drush'] === TRUE ? '_search_api_drush_format_plural' : 'format_plural';
  2819. $context['message'] = $format_plural($context['results']['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.');
  2820. }
  2821. // Some items couldn't be indexed.
  2822. if ($indexed !== $to_index) {
  2823. $context['results']['not indexed'] += $to_index - $indexed;
  2824. }
  2825. $context['sandbox']['progress'] += $to_index;
  2826. // Everything has been indexed.
  2827. if ($indexed === 0 || $context['sandbox']['progress'] >= $context['sandbox']['limit']) {
  2828. $context['finished'] = 1;
  2829. }
  2830. else {
  2831. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['limit'];
  2832. }
  2833. }
  2834. /**
  2835. * Batch API finishing callback for the indexing functionality.
  2836. *
  2837. * @param boolean $success
  2838. * Whether the batch finished successfully.
  2839. * @param array $results
  2840. * Detailed informations about the result.
  2841. */
  2842. function _search_api_batch_indexing_finished($success, $results) {
  2843. // Check if called from drush.
  2844. if (!empty($results['drush'])) {
  2845. $drupal_set_message = 'drush_log';
  2846. $format_plural = '_search_api_drush_format_plural';
  2847. $t = 'dt';
  2848. $success_message = 'success';
  2849. }
  2850. else {
  2851. $drupal_set_message = 'drupal_set_message';
  2852. $format_plural = 'format_plural';
  2853. $t = 't';
  2854. $success_message = 'status';
  2855. }
  2856. // Display result messages.
  2857. if ($success) {
  2858. if (!empty($results['indexed'])) {
  2859. $drupal_set_message($format_plural($results['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.'), $success_message);
  2860. if (!empty($results['not indexed'])) {
  2861. $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');
  2862. }
  2863. }
  2864. else {
  2865. $drupal_set_message($t("Couldn't index items. Check the logs for details."), 'error');
  2866. }
  2867. }
  2868. else {
  2869. $drupal_set_message($t("An error occurred while trying to index items. Check the logs for details."), 'error');
  2870. }
  2871. }