search_api.module 96 KB

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