search_api.module 111 KB

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