search_api.module 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352
  1. <?php
  2. /**
  3. * Default number of items indexed per cron batch for each enabled index.
  4. */
  5. define('SEARCH_API_DEFAULT_CRON_LIMIT', 50);
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function search_api_menu() {
  10. $pre = 'admin/config/search/search_api';
  11. $items[$pre] = array(
  12. 'title' => 'Search API',
  13. 'description' => 'Create and configure search engines.',
  14. 'page callback' => 'search_api_admin_overview',
  15. 'access arguments' => array('administer search_api'),
  16. 'file' => 'search_api.admin.inc',
  17. );
  18. $items[$pre . '/overview'] = array(
  19. 'title' => 'Overview',
  20. 'type' => MENU_DEFAULT_LOCAL_TASK,
  21. 'weight' => -10,
  22. );
  23. $items[$pre . '/add_server'] = array(
  24. 'title' => 'Add server',
  25. 'description' => 'Create a new search server.',
  26. 'page callback' => 'drupal_get_form',
  27. 'page arguments' => array('search_api_admin_add_server'),
  28. 'access arguments' => array('administer search_api'),
  29. 'file' => 'search_api.admin.inc',
  30. 'weight' => -1,
  31. 'type' => MENU_LOCAL_ACTION,
  32. );
  33. $items[$pre . '/add_index'] = array(
  34. 'title' => 'Add index',
  35. 'description' => 'Create a new search index.',
  36. 'page callback' => 'drupal_get_form',
  37. 'page arguments' => array('search_api_admin_add_index'),
  38. 'access arguments' => array('administer search_api'),
  39. 'file' => 'search_api.admin.inc',
  40. 'type' => MENU_LOCAL_ACTION,
  41. );
  42. $items[$pre . '/server/%search_api_server'] = array(
  43. 'title' => 'View server',
  44. 'title callback' => 'search_api_admin_item_title',
  45. 'title arguments' => array(5),
  46. 'description' => 'View server details.',
  47. 'page callback' => 'search_api_admin_server_view',
  48. 'page arguments' => array(5),
  49. 'access arguments' => array('administer search_api'),
  50. 'file' => 'search_api.admin.inc',
  51. );
  52. $items[$pre . '/server/%search_api_server/view'] = array(
  53. 'title' => 'View',
  54. 'weight' => -10,
  55. 'type' => MENU_DEFAULT_LOCAL_TASK,
  56. );
  57. $items[$pre . '/server/%search_api_server/edit'] = array(
  58. 'title' => 'Edit',
  59. 'description' => 'Edit server details.',
  60. 'page callback' => 'drupal_get_form',
  61. 'page arguments' => array('search_api_admin_server_edit', 5),
  62. 'access arguments' => array('administer search_api'),
  63. 'file' => 'search_api.admin.inc',
  64. 'weight' => -1,
  65. 'type' => MENU_LOCAL_TASK,
  66. );
  67. $items[$pre . '/server/%search_api_server/delete'] = array(
  68. 'title' => 'Delete',
  69. 'title callback' => 'search_api_title_delete_page',
  70. 'title arguments' => array(5),
  71. 'description' => 'Delete server.',
  72. 'page callback' => 'drupal_get_form',
  73. 'page arguments' => array('search_api_admin_confirm', 'server', 'delete', 5),
  74. 'access callback' => 'search_api_access_delete_page',
  75. 'access arguments' => array(5),
  76. 'file' => 'search_api.admin.inc',
  77. 'type' => MENU_LOCAL_TASK,
  78. );
  79. $items[$pre . '/index/%search_api_index'] = array(
  80. 'title' => 'View index',
  81. 'title callback' => 'search_api_admin_item_title',
  82. 'title arguments' => array(5),
  83. 'description' => 'View index details.',
  84. 'page callback' => 'search_api_admin_index_view',
  85. 'page arguments' => array(5),
  86. 'access arguments' => array('administer search_api'),
  87. 'file' => 'search_api.admin.inc',
  88. );
  89. $items[$pre . '/index/%search_api_index/view'] = array(
  90. 'title' => 'View',
  91. 'type' => MENU_DEFAULT_LOCAL_TASK,
  92. 'weight' => -10,
  93. );
  94. $items[$pre . '/index/%search_api_index/status'] = array(
  95. 'title' => 'Status',
  96. 'description' => 'Display and work on index status.',
  97. 'page callback' => 'drupal_get_form',
  98. 'page arguments' => array('search_api_admin_index_status_form', 5),
  99. 'access arguments' => array('administer search_api'),
  100. 'file' => 'search_api.admin.inc',
  101. 'weight' => -8,
  102. 'type' => MENU_LOCAL_TASK,
  103. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  104. );
  105. $items[$pre . '/index/%search_api_index/edit'] = array(
  106. 'title' => 'Settings',
  107. 'description' => 'Edit index settings.',
  108. 'page callback' => 'drupal_get_form',
  109. 'page arguments' => array('search_api_admin_index_edit', 5),
  110. 'access arguments' => array('administer search_api'),
  111. 'file' => 'search_api.admin.inc',
  112. 'weight' => -6,
  113. 'type' => MENU_LOCAL_TASK,
  114. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  115. );
  116. $items[$pre . '/index/%search_api_index/fields'] = array(
  117. 'title' => 'Fields',
  118. 'description' => 'Select indexed fields.',
  119. 'page callback' => 'drupal_get_form',
  120. 'page arguments' => array('search_api_admin_index_fields', 5),
  121. 'access arguments' => array('administer search_api'),
  122. 'file' => 'search_api.admin.inc',
  123. 'weight' => -4,
  124. 'type' => MENU_LOCAL_TASK,
  125. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  126. );
  127. $items[$pre . '/index/%search_api_index/workflow'] = array(
  128. 'title' => 'Workflow',
  129. 'description' => 'Edit index workflow.',
  130. 'page callback' => 'drupal_get_form',
  131. 'page arguments' => array('search_api_admin_index_workflow', 5),
  132. 'access arguments' => array('administer search_api'),
  133. 'file' => 'search_api.admin.inc',
  134. 'weight' => -2,
  135. 'type' => MENU_LOCAL_TASK,
  136. 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  137. );
  138. $items[$pre . '/index/%search_api_index/delete'] = array(
  139. 'title' => 'Delete',
  140. 'title callback' => 'search_api_title_delete_page',
  141. 'title arguments' => array(5),
  142. 'description' => 'Delete index.',
  143. 'page callback' => 'drupal_get_form',
  144. 'page arguments' => array('search_api_admin_confirm', 'index', 'delete', 5),
  145. 'access callback' => 'search_api_access_delete_page',
  146. 'access arguments' => array(5),
  147. 'file' => 'search_api.admin.inc',
  148. 'type' => MENU_LOCAL_TASK,
  149. );
  150. return $items;
  151. }
  152. /**
  153. * Implements hook_theme().
  154. */
  155. function search_api_theme() {
  156. $themes['search_api_server'] = array(
  157. 'variables' => array(
  158. 'id' => NULL,
  159. 'name' => '',
  160. 'machine_name' => '',
  161. 'description' => NULL,
  162. 'enabled' => NULL,
  163. 'class_name' => NULL,
  164. 'class_description' => NULL,
  165. 'options' => array(),
  166. 'status' => ENTITY_CUSTOM,
  167. ),
  168. 'file' => 'search_api.admin.inc',
  169. );
  170. $themes['search_api_index'] = array(
  171. 'variables' => array(
  172. 'id' => NULL,
  173. 'name' => '',
  174. 'machine_name' => '',
  175. 'description' => NULL,
  176. 'item_type' => NULL,
  177. 'enabled' => NULL,
  178. 'server' => NULL,
  179. 'options' => array(),
  180. 'fields' => array(),
  181. 'indexed_items' => 0,
  182. 'total_items' => 0,
  183. 'status' => ENTITY_CUSTOM,
  184. 'read_only' => 0,
  185. ),
  186. 'file' => 'search_api.admin.inc',
  187. );
  188. $themes['search_api_admin_item_order'] = array(
  189. 'render element' => 'element',
  190. 'file' => 'search_api.admin.inc',
  191. );
  192. $themes['search_api_admin_fields_table'] = array(
  193. 'render element' => 'element',
  194. 'file' => 'search_api.admin.inc',
  195. );
  196. return $themes;
  197. }
  198. /**
  199. * Implements hook_permission().
  200. */
  201. function search_api_permission() {
  202. return array(
  203. 'administer search_api' => array(
  204. 'title' => t('Administer Search API'),
  205. 'description' => t('Create and configure Search API servers and indexes.'),
  206. ),
  207. );
  208. }
  209. /**
  210. * Implements hook_cron().
  211. *
  212. * Will index $options['cron-limit'] items for each enabled index.
  213. */
  214. function search_api_cron() {
  215. $queue = DrupalQueue::get('search_api_indexing_queue');
  216. foreach (search_api_index_load_multiple(FALSE, array('enabled' => TRUE, 'read_only' => 0)) as $index) {
  217. $limit = isset($index->options['cron_limit'])
  218. ? $index->options['cron_limit']
  219. : SEARCH_API_DEFAULT_CRON_LIMIT;
  220. if ($limit) {
  221. try {
  222. $task = array('index' => $index->machine_name);
  223. $ids = search_api_get_items_to_index($index, -1);
  224. if (!$ids) {
  225. continue;
  226. }
  227. $batches = $limit > 0 ? array_chunk($ids, $limit, TRUE) : array($ids);
  228. foreach ($batches as $batch) {
  229. $task['items'] = $batch;
  230. $queue->createItem($task);
  231. }
  232. // Mark items as queued so they won't be inserted into the queue again
  233. // on the next cron run.
  234. search_api_track_item_queued($index, $ids);
  235. }
  236. catch (SearchApiException $e) {
  237. watchdog_exception('search_api', $e);
  238. }
  239. }
  240. }
  241. }
  242. /**
  243. * Implements hook_cron_queue_info().
  244. *
  245. * Defines a queue for saved searches that should be checked for new items.
  246. */
  247. function search_api_cron_queue_info() {
  248. return array(
  249. 'search_api_indexing_queue' => array(
  250. 'worker callback' => '_search_api_indexing_queue_process',
  251. 'time' => variable_get('search_api_index_worker_callback_runtime', 15),
  252. ),
  253. );
  254. }
  255. /**
  256. * Implements hook_entity_info().
  257. */
  258. function search_api_entity_info() {
  259. $info['search_api_server'] = array(
  260. 'label' => t('Search server'),
  261. 'controller class' => 'EntityAPIControllerExportable',
  262. 'metadata controller class' => FALSE,
  263. 'entity class' => 'SearchApiServer',
  264. 'base table' => 'search_api_server',
  265. 'uri callback' => 'search_api_server_url',
  266. 'module' => 'search_api',
  267. 'exportable' => TRUE,
  268. 'entity keys' => array(
  269. 'id' => 'id',
  270. 'label' => 'name',
  271. 'name' => 'machine_name',
  272. ),
  273. );
  274. $info['search_api_index'] = array(
  275. 'label' => t('Search index'),
  276. 'controller class' => 'EntityAPIControllerExportable',
  277. 'metadata controller class' => FALSE,
  278. 'entity class' => 'SearchApiIndex',
  279. 'base table' => 'search_api_index',
  280. 'uri callback' => 'search_api_index_url',
  281. 'module' => 'search_api',
  282. 'exportable' => TRUE,
  283. 'entity keys' => array(
  284. 'id' => 'id',
  285. 'label' => 'name',
  286. 'name' => 'machine_name',
  287. ),
  288. );
  289. return $info;
  290. }
  291. /**
  292. * Implements hook_entity_property_info().
  293. */
  294. function search_api_entity_property_info() {
  295. $info['search_api_server']['properties'] = array(
  296. 'id' => array(
  297. 'label' => t('ID'),
  298. 'type' => 'integer',
  299. 'description' => t('The primary identifier for a server.'),
  300. 'schema field' => 'id',
  301. 'validation callback' => 'entity_metadata_validate_integer_positive',
  302. ),
  303. 'name' => array(
  304. 'label' => t('Name'),
  305. 'type' => 'text',
  306. 'description' => t('The displayed name for a server.'),
  307. 'schema field' => 'name',
  308. 'required' => TRUE,
  309. ),
  310. 'machine_name' => array(
  311. 'label' => t('Machine name'),
  312. 'type' => 'token',
  313. 'description' => t('The internally used machine name for a server.'),
  314. 'schema field' => 'machine_name',
  315. 'required' => TRUE,
  316. ),
  317. 'description' => array(
  318. 'label' => t('Description'),
  319. 'type' => 'text',
  320. 'description' => t('The displayed description for a server.'),
  321. 'schema field' => 'description',
  322. 'sanitize' => 'filter_xss',
  323. ),
  324. 'class' => array(
  325. 'label' => t('Service class'),
  326. 'type' => 'text',
  327. 'description' => t('The ID of the service class to use for this server.'),
  328. 'schema field' => 'class',
  329. 'required' => TRUE,
  330. ),
  331. 'enabled' => array(
  332. 'label' => t('Enabled'),
  333. 'type' => 'boolean',
  334. 'description' => t('A flag indicating whether the server is enabled.'),
  335. 'schema field' => 'enabled',
  336. ),
  337. );
  338. $info['search_api_index']['properties'] = array(
  339. 'id' => array(
  340. 'label' => t('ID'),
  341. 'type' => 'integer',
  342. 'description' => t('An integer identifying the index.'),
  343. 'schema field' => 'id',
  344. 'validation callback' => 'entity_metadata_validate_integer_positive',
  345. ),
  346. 'name' => array(
  347. 'label' => t('Name'),
  348. 'type' => 'text',
  349. 'description' => t('A name to be displayed for the index.'),
  350. 'schema field' => 'name',
  351. 'required' => TRUE,
  352. ),
  353. 'machine_name' => array(
  354. 'label' => t('Machine name'),
  355. 'type' => 'token',
  356. 'description' => t('The internally used machine name for an index.'),
  357. 'schema field' => 'machine_name',
  358. 'required' => TRUE,
  359. ),
  360. 'description' => array(
  361. 'label' => t('Description'),
  362. 'type' => 'text',
  363. 'description' => t("A string describing the index' use to users."),
  364. 'schema field' => 'description',
  365. 'sanitize' => 'filter_xss',
  366. ),
  367. 'server' => array(
  368. 'label' => t('Server ID'),
  369. 'type' => 'token',
  370. 'description' => t('The machine name of the search_api_server with which data should be indexed.'),
  371. 'schema field' => 'server',
  372. ),
  373. 'server_entity' => array(
  374. 'label' => t('Server'),
  375. 'type' => 'search_api_server',
  376. 'description' => t('The search_api_server with which data should be indexed.'),
  377. 'getter callback' => 'search_api_index_get_server',
  378. ),
  379. 'item_type' => array(
  380. 'label' => t('Item type'),
  381. 'type' => 'token',
  382. 'description' => t('The type of items stored in this index.'),
  383. 'schema field' => 'item_type',
  384. 'required' => TRUE,
  385. ),
  386. 'enabled' => array(
  387. 'label' => t('Enabled'),
  388. 'type' => 'boolean',
  389. 'description' => t('A flag indicating whether the index is enabled.'),
  390. 'schema field' => 'enabled',
  391. ),
  392. 'read_only' => array(
  393. 'label' => t('Read only'),
  394. 'type' => 'boolean',
  395. 'description' => t('A flag indicating whether the index is read-only.'),
  396. 'schema field' => 'read_only',
  397. ),
  398. );
  399. return $info;
  400. }
  401. /**
  402. * Implements hook_search_api_server_insert().
  403. *
  404. * Calls the postCreate() method for the server.
  405. */
  406. function search_api_search_api_server_insert(SearchApiServer $server) {
  407. $server->postCreate();
  408. }
  409. /**
  410. * Implements hook_search_api_server_update().
  411. *
  412. * Calls the server's postUpdate() method and marks all of this server's indexes
  413. * for reindexing, if necessary.
  414. */
  415. function search_api_search_api_server_update(SearchApiServer $server) {
  416. if ($server->postUpdate()) {
  417. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  418. $index->reindex();
  419. }
  420. }
  421. if ($server->enabled != $server->original->enabled) {
  422. if ($server->enabled) {
  423. // Were there any changes in the server's indexes while it was disabled?
  424. $tasks = variable_get('search_api_tasks', array());
  425. if (isset($tasks[$server->machine_name])) {
  426. foreach ($tasks[$server->machine_name] as $index_id => $index_tasks) {
  427. $index = search_api_index_load($index_id);
  428. foreach ($index_tasks as $task) {
  429. switch ($task) {
  430. case 'add':
  431. $server->addIndex($index);
  432. break;
  433. case 'clear':
  434. $server->deleteItems('all', $index);
  435. break;
  436. case 'clear all':
  437. // Would normally be used with a fake index ID of "", since it doesn't matter.
  438. $server->deleteItems('all');
  439. break;
  440. case 'fields':
  441. if ($server->fieldsUpdated($index)) {
  442. _search_api_index_reindex($index);
  443. }
  444. break;
  445. case 'remove':
  446. $server->removeIndex($index ? $index : $index_id);
  447. break;
  448. default:
  449. if (substr($task, 0, 7) == 'delete-') {
  450. $id = substr($task, 7);
  451. $server->deleteItems(array($id), $index);
  452. }
  453. else {
  454. watchdog('search_api', t('Unknown task "@task" for server "@name".', array('@task' => $task, '@name' => $server->machine_name)), NULL, WATCHDOG_WARNING);
  455. }
  456. }
  457. }
  458. }
  459. unset($tasks[$server->machine_name]);
  460. variable_set('search_api_tasks', $tasks);
  461. }
  462. }
  463. else {
  464. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name, 'enabled' => 1)) as $index) {
  465. $index->update(array('enabled' => 0));
  466. }
  467. }
  468. }
  469. }
  470. /**
  471. * Implements hook_search_api_server_delete().
  472. *
  473. * Calls the preDelete() method for the server.
  474. */
  475. function search_api_search_api_server_delete(SearchApiServer $server) {
  476. $server->preDelete();
  477. // Only react on real delete, not revert.
  478. if (!$server->hasStatus(ENTITY_IN_CODE)) {
  479. foreach (search_api_index_load_multiple(FALSE, array('server' => $server->machine_name)) as $index) {
  480. $index->update(array('server' => NULL, 'enabled' => FALSE));
  481. }
  482. }
  483. $tasks = variable_get('search_api_tasks', array());
  484. unset($tasks[$server->machine_name]);
  485. variable_set('search_api_tasks', $tasks);
  486. }
  487. /**
  488. * Implements hook_search_api_index_insert().
  489. *
  490. * Adds the index to its server (if any) and starts tracking indexed items (if
  491. * the index is enabled).
  492. */
  493. function search_api_search_api_index_insert(SearchApiIndex $index) {
  494. $index->postCreate();
  495. }
  496. /**
  497. * Implements hook_search_api_index_update().
  498. */
  499. function search_api_search_api_index_update(SearchApiIndex $index) {
  500. // If the server was changed, we have to call the appropriate service class
  501. // hook methods.
  502. if ($index->server != $index->original->server) {
  503. // Server changed - inform old and new ones.
  504. if ($index->original->server) {
  505. $old_server = search_api_server_load($index->original->server);
  506. // The server might have changed because the old one was deleted:
  507. if ($old_server) {
  508. if ($old_server->enabled) {
  509. $old_server->removeIndex($index);
  510. }
  511. else {
  512. $tasks = variable_get('search_api_tasks', array());
  513. // When we add or remove an index, we can ignore all other tasks.
  514. $tasks[$old_server->machine_name][$index->machine_name] = array('remove');
  515. variable_set('search_api_tasks', $tasks);
  516. }
  517. }
  518. }
  519. if ($index->server) {
  520. $new_server = $index->server(TRUE);
  521. // If the server is enabled, we call addIndex(); otherwise, we save the task.
  522. if ($new_server->enabled) {
  523. $new_server->addIndex($index);
  524. }
  525. else {
  526. $tasks = variable_get('search_api_tasks', array());
  527. // When we add or remove an index, we can ignore all other tasks.
  528. $tasks[$new_server->machine_name][$index->machine_name] = array('add');
  529. variable_set('search_api_tasks', $tasks);
  530. unset($new_server);
  531. }
  532. }
  533. // We also have to re-index all content
  534. _search_api_index_reindex($index);
  535. }
  536. // If the fields were changed, call the appropriate service class hook method
  537. // and re-index the content, if necessary.
  538. $old_fields = $index->original->options + array('fields' => array());
  539. $old_fields = $old_fields['fields'];
  540. $new_fields = $index->options + array('fields' => array());
  541. $new_fields = $new_fields['fields'];
  542. if ($old_fields != $new_fields) {
  543. if ($index->server && $index->server()->fieldsUpdated($index)) {
  544. _search_api_index_reindex($index);
  545. }
  546. }
  547. // If the index's enabled or read-only status is being changed, queue or
  548. // dequeue items for indexing.
  549. if (!$index->read_only && $index->enabled != $index->original->enabled) {
  550. if ($index->enabled) {
  551. $index->queueItems();
  552. }
  553. else {
  554. $index->dequeueItems();
  555. }
  556. }
  557. elseif ($index->read_only != $index->original->read_only) {
  558. if ($index->read_only) {
  559. $index->dequeueItems();
  560. }
  561. else {
  562. $index->queueItems();
  563. }
  564. }
  565. // If the cron batch size changed, empty the cron queue for this index.
  566. $old_cron = $index->original->options + array('cron_limit' => NULL);
  567. $old_cron = $old_cron['cron_limit'];
  568. $new_cron = $index->options + array('cron_limit' => NULL);
  569. $new_cron = $new_cron['cron_limit'];
  570. if ($old_cron !== $new_cron) {
  571. _search_api_empty_cron_queue($index, TRUE);
  572. }
  573. }
  574. /**
  575. * Implements hook_search_api_index_delete().
  576. *
  577. * Removes all data for indexes not available any more.
  578. */
  579. function search_api_search_api_index_delete(SearchApiIndex $index) {
  580. $index->postDelete();
  581. }
  582. /**
  583. * Implements hook_features_export_alter().
  584. *
  585. * Adds dependency information for exported servers.
  586. */
  587. function search_api_features_export_alter(&$export, $module_name) {
  588. if (isset($export['features']['search_api_server'])) {
  589. // Get a list of the modules that provide storage engines.
  590. $hook = 'search_api_service_info';
  591. $classes = array();
  592. foreach (module_implements('search_api_service_info') as $module) {
  593. $function = $module . '_' . $hook;
  594. $engines = $function();
  595. foreach ($engines as $service => $specs) {
  596. $classes[$service] = $module;
  597. }
  598. }
  599. // Check all of the exported server specifications.
  600. foreach ($export['features']['search_api_server'] as $server_name) {
  601. // Load the server's object.
  602. $server = search_api_server_load($server_name);
  603. $module = $classes[$server->class];
  604. // Ensure that the module responsible for the server object is listed as
  605. // a dependency.
  606. if (!isset($export['dependencies'][$module])) {
  607. $export['dependencies'][$module] = $module;
  608. }
  609. }
  610. // Ensure the dependencies list is still sorted alphabetically.
  611. ksort($export['dependencies']);
  612. }
  613. }
  614. /**
  615. * Implements hook_entity_insert().
  616. *
  617. * Marks the new item as to-index for all indexes on entities of the specified
  618. * type.
  619. *
  620. * @param $entity
  621. * The new entity.
  622. * @param $type
  623. * The entity's type.
  624. */
  625. function search_api_entity_insert($entity, $type) {
  626. // When inserting a new search index, the new index was already inserted into
  627. // the tracking table. This would lead to a duplicate-key issue, if we would
  628. // continue.
  629. // We also only react on entity operations for types with property
  630. // information, as we don't provide search integration for the others.
  631. if ($type == 'search_api_index' || !entity_get_property_info($type)) {
  632. return;
  633. }
  634. list($id) = entity_extract_ids($type, $entity);
  635. if (isset($id)) {
  636. search_api_track_item_insert($type, array($id));
  637. }
  638. }
  639. /**
  640. * Implements hook_entity_update().
  641. *
  642. * Marks the item as changed for all indexes on entities of the specified type.
  643. *
  644. * @param $entity
  645. * The updated entity.
  646. * @param $type
  647. * The entity's type.
  648. */
  649. function search_api_entity_update($entity, $type) {
  650. // We only react on entity operations for types with property information, as
  651. // we don't provide search integration for the others.
  652. if (!entity_get_property_info($type)) {
  653. return;
  654. }
  655. list($id) = entity_extract_ids($type, $entity);
  656. if (isset($id)) {
  657. search_api_track_item_change($type, array($id));
  658. }
  659. }
  660. /**
  661. * Implements hook_entity_delete().
  662. *
  663. * Removes the item from the tracking table and deletes it from all indexes.
  664. *
  665. * @param $entity
  666. * The updated entity.
  667. * @param $type
  668. * The entity's type.
  669. */
  670. function search_api_entity_delete($entity, $type) {
  671. // We only react on entity operations for types with property information, as
  672. // we don't provide search integration for the others.
  673. if (!entity_get_property_info($type)) {
  674. return;
  675. }
  676. list($id) = entity_extract_ids($type, $entity);
  677. if (isset($id)) {
  678. search_api_track_item_delete($type, array($id));
  679. }
  680. }
  681. /**
  682. * Implements hook_search_api_item_type_info().
  683. *
  684. * Adds item types for all entity types with property information.
  685. */
  686. function search_api_search_api_item_type_info() {
  687. $types = array();
  688. foreach (entity_get_property_info() as $type => $property_info) {
  689. if ($info = entity_get_info($type)) {
  690. $types[$type] = array(
  691. 'name' => $info['label'],
  692. 'datasource controller' => 'SearchApiEntityDataSourceController',
  693. );
  694. }
  695. }
  696. return $types;
  697. }
  698. /**
  699. * Implements hook_modules_enabled().
  700. */
  701. function search_api_modules_enabled(array $modules) {
  702. // New modules might offer additional entity types, invalidating the cached
  703. // item type information.
  704. drupal_static_reset('search_api_get_item_type_info');
  705. }
  706. /**
  707. * Implements hook_modules_disabled().
  708. */
  709. function search_api_modules_disabled(array $modules) {
  710. // The disabled modules might have offered entity types, which are now
  711. // invalid. Therefore, clear the cached item type informaiton.
  712. drupal_static_reset('search_api_get_item_type_info');
  713. }
  714. /**
  715. * Implements hook_search_api_alter_callback_info().
  716. */
  717. function search_api_search_api_alter_callback_info() {
  718. $callbacks['search_api_alter_bundle_filter'] = array(
  719. 'name' => t('Bundle filter'),
  720. 'description' => t('Exclude items from indexing based on their bundle (content type, vocabulary, …).'),
  721. 'class' => 'SearchApiAlterBundleFilter',
  722. // Filters should be executed first.
  723. 'weight' => -10,
  724. );
  725. $callbacks['search_api_alter_add_url'] = array(
  726. 'name' => t('URL field'),
  727. 'description' => t("Adds the item's URL to the indexed data."),
  728. 'class' => 'SearchApiAlterAddUrl',
  729. );
  730. $callbacks['search_api_alter_add_aggregation'] = array(
  731. 'name' => t('Aggregated fields'),
  732. 'description' => t('Gives you the ability to define additional fields, containing data from one or more other fields.'),
  733. 'class' => 'SearchApiAlterAddAggregation',
  734. );
  735. $callbacks['search_api_alter_add_viewed_entity'] = array(
  736. 'name' => t('Complete entity view'),
  737. 'description' => t('Adds an additional field containing the whole HTML content of the entity when viewed.'),
  738. 'class' => 'SearchApiAlterAddViewedEntity',
  739. );
  740. $callbacks['search_api_alter_add_hierarchy'] = array(
  741. 'name' => t('Index hierarchy'),
  742. 'description' => t('Allows to index hierarchical fields along with all their ancestors.'),
  743. 'class' => 'SearchApiAlterAddHierarchy',
  744. );
  745. $callbacks['search_api_alter_language_control'] = array(
  746. 'name' => t('Language control'),
  747. 'description' => t('Lets you determine the language of items in the index.'),
  748. 'class' => 'SearchApiAlterLanguageControl',
  749. );
  750. $callbacks['search_api_alter_node_access'] = array(
  751. 'name' => t('Node access'),
  752. 'description' => t('Add node access information to the index.'),
  753. 'class' => 'SearchApiAlterNodeAccess',
  754. );
  755. $callbacks['search_api_alter_node_status'] = array(
  756. 'name' => t('Exclude unpublished nodes'),
  757. 'description' => t('Exclude unpublished nodes from the index.'),
  758. 'class' => 'SearchApiAlterNodeStatus',
  759. );
  760. return $callbacks;
  761. }
  762. /**
  763. * Implements hook_search_api_processor_info().
  764. */
  765. function search_api_search_api_processor_info() {
  766. $processors['search_api_case_ignore'] = array(
  767. 'name' => t('Ignore case'),
  768. 'description' => t('This processor will make searches case-insensitive for all fulltext fields (and, optionally, also for filters on string fields).'),
  769. 'class' => 'SearchApiIgnoreCase',
  770. );
  771. $processors['search_api_html_filter'] = array(
  772. 'name' => t('HTML filter'),
  773. 'description' => t('Strips HTML tags from fulltext fields and decodes HTML entities. ' .
  774. 'Use this processor when indexing HTML data, e.g., node bodies for certain text formats.<br />' .
  775. 'The processor also allows to boost (or ignore) the contents of specific elements.'),
  776. 'class' => 'SearchApiHtmlFilter',
  777. 'weight' => 10,
  778. );
  779. $processors['search_api_tokenizer'] = array(
  780. 'name' => t('Tokenizer'),
  781. 'description' => t('Tokenizes fulltext data by stripping whitespace. ' .
  782. 'This processor allows you to specify which characters make up words and which characters should be ignored, using regular expression syntax. ' .
  783. 'Otherwise it is up to the search server implementation to decide how to split indexed fulltext data.'),
  784. 'class' => 'SearchApiTokenizer',
  785. 'weight' => 20,
  786. );
  787. $processors['search_api_stopwords'] = array(
  788. 'name' => t('Stopwords'),
  789. 'description' => t('This processor prevents certain words from being indexed and removes them from search terms. ' .
  790. 'For best results, it should only be executed after tokenizing.'),
  791. 'class' => 'SearchApiStopWords',
  792. 'weight' => 30,
  793. );
  794. return $processors;
  795. }
  796. /**
  797. * Inserts new unindexed items for all indexes on the specified type.
  798. *
  799. * @param $type
  800. * The item type of the new items.
  801. * @param array $item_id
  802. * The IDs of the new items.
  803. */
  804. function search_api_track_item_insert($type, array $item_ids) {
  805. $conditions = array(
  806. 'enabled' => 1,
  807. 'item_type' => $type,
  808. 'read_only' => 0,
  809. );
  810. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  811. if (!$indexes) {
  812. return;
  813. }
  814. search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
  815. foreach ($indexes as $index) {
  816. if (!empty($index->options['index_directly'])) {
  817. $indexed = search_api_index_specific_items_delayed($index, $item_ids);
  818. }
  819. }
  820. }
  821. /**
  822. * Mark the items with the specified IDs as "dirty", i.e., as needing to be reindexed.
  823. *
  824. * For indexes for which items should be indexed immediately, the items are
  825. * indexed directly, instead.
  826. *
  827. * @param $type
  828. * The type of items, specific to the data source.
  829. * @param array $item_ids
  830. * The IDs of the items to be marked dirty.
  831. */
  832. function search_api_track_item_change($type, array $item_ids) {
  833. $conditions = array(
  834. 'enabled' => 1,
  835. 'item_type' => $type,
  836. 'read_only' => 0,
  837. );
  838. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  839. if (!$indexes) {
  840. return;
  841. }
  842. search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
  843. foreach ($indexes as $index) {
  844. if (!empty($index->options['index_directly'])) {
  845. // For indexes with the index_directly option set, queue the items to be
  846. // indexed at the end of the request.
  847. try {
  848. search_api_index_specific_items_delayed($index, $item_ids);
  849. }
  850. catch (SearchApiException $e) {
  851. watchdog_exception('search_api', $e);
  852. }
  853. }
  854. }
  855. }
  856. /**
  857. * Marks items as queued for indexing for the specified index.
  858. *
  859. * @param SearchApiIndex $index
  860. * The index on which items were queued.
  861. * @param array $item_ids
  862. * The ids of the queued items.
  863. */
  864. function search_api_track_item_queued(SearchApiIndex $index, array $item_ids) {
  865. $index->datasource()->trackItemQueued($item_ids, $index);
  866. }
  867. /**
  868. * Marks items as successfully indexed for the specified index.
  869. *
  870. * @param SearchApiIndex $index
  871. * The index on which items were indexed.
  872. * @param array $item_ids
  873. * The ids of the indexed items.
  874. */
  875. function search_api_track_item_indexed(SearchApiIndex $index, array $item_ids) {
  876. $index->datasource()->trackItemIndexed($item_ids, $index);
  877. }
  878. /**
  879. * Removes items from all indexes.
  880. *
  881. * @param $type
  882. * The type of the items.
  883. * @param array $item_ids
  884. * The IDs of the deleted items.
  885. */
  886. function search_api_track_item_delete($type, array $item_ids) {
  887. // First, delete the item from the tracking table.
  888. $conditions = array(
  889. 'enabled' => 1,
  890. 'item_type' => $type,
  891. 'read_only' => 0,
  892. );
  893. $indexes = search_api_index_load_multiple(FALSE, $conditions);
  894. if ($indexes) {
  895. search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
  896. }
  897. // Then, delete it from all servers. Servers of disabled indexes have to be
  898. // considered, too!
  899. unset($conditions['enabled']);
  900. foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
  901. if ($index->server) {
  902. $server = $index->server();
  903. if ($server->enabled) {
  904. $server->deleteItems($item_ids, $index);
  905. }
  906. else {
  907. $tasks = variable_get('search_api_tasks', array());
  908. foreach ($item_ids as $id) {
  909. $tasks[$server->machine_name][$index->machine_name][] = 'delete-' . $id;
  910. }
  911. variable_set('search_api_tasks', $tasks);
  912. }
  913. }
  914. }
  915. }
  916. /**
  917. * Indexes items for the specified index. Only items marked as changed are
  918. * indexed, in their order of change (if known).
  919. *
  920. * @param SearchApiIndex $index
  921. * The index on which items should be indexed.
  922. * @param $limit
  923. * The number of items which should be indexed at most. -1 means no limit.
  924. *
  925. * @throws SearchApiException
  926. * If any error occurs during indexing.
  927. *
  928. * @return
  929. * Number of successfully indexed items.
  930. */
  931. function search_api_index_items(SearchApiIndex $index, $limit = -1) {
  932. // Don't try to index read-only indexes.
  933. if ($index->read_only) {
  934. return 0;
  935. }
  936. $queue = DrupalQueue::get('search_api_indexing_queue');
  937. $queue->createQueue();
  938. $indexed = 0;
  939. $unlimited = $limit < 0;
  940. $release_items = array();
  941. while (($unlimited || $indexed < $limit) && ($item = $queue->claimItem(30))) {
  942. if ($item->data['index'] === $index->machine_name) {
  943. $indexed += _search_api_indexing_queue_process($item->data);
  944. $queue->deleteItem($item);
  945. }
  946. else {
  947. $release_items[] = $item;
  948. }
  949. }
  950. foreach ($release_items as $item) {
  951. $queue->releaseItem($item);
  952. }
  953. if ($unlimited || $indexed < $limit) {
  954. $ids = search_api_get_items_to_index($index, $unlimited ? -1 : $limit - $indexed);
  955. if ($ids) {
  956. $indexed += count(search_api_index_specific_items($index, $ids));
  957. }
  958. }
  959. return $indexed;
  960. }
  961. /**
  962. * Indexes the specified items on the given index.
  963. *
  964. * Items which were successfully indexed are marked as such afterwards.
  965. *
  966. * @param SearchApiIndex $index
  967. * The index on which items should be indexed.
  968. * @param array $ids
  969. * The IDs of the items which should be indexed.
  970. *
  971. * @throws SearchApiException
  972. * If any error occurs during indexing.
  973. *
  974. * @return
  975. * The IDs of all successfully indexed items.
  976. */
  977. function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
  978. $items = $index->loadItems($ids);
  979. // Clone items because data alterations may alter them.
  980. $cloned_items = array();
  981. foreach ($items as $id => $item) {
  982. $cloned_items[$id] = clone $item;
  983. }
  984. $indexed = $items ? $index->index($cloned_items) : array();
  985. if ($indexed) {
  986. search_api_track_item_indexed($index, $indexed);
  987. // If some items could not be indexed, we don't want to try re-indexing
  988. // them right away, so we mark them as "freshly" changed. Sadly, there is
  989. // no better way than to mark them as indexed first...
  990. if (count($indexed) < count($ids)) {
  991. // Believe it or not but this is actually quite faster than the equivalent
  992. // $diff = array_diff($ids, $indexed);
  993. $diff = array_keys(array_diff_key(array_flip($ids), array_flip($indexed)));
  994. $index->datasource()->trackItemIndexed($diff, $index);
  995. $index->datasource()->trackItemChange($diff, array($index));
  996. }
  997. }
  998. return $indexed;
  999. }
  1000. /**
  1001. * Queues items for indexing at the end of the page request.
  1002. *
  1003. * @param SearchApiIndex $index
  1004. * The index on which items should be indexed.
  1005. * @param array $ids
  1006. * The IDs of the items which should be indexed.
  1007. *
  1008. * @return array
  1009. * The current contents of the queue, as a reference.
  1010. *
  1011. * @see search_api_index_specific_items()
  1012. * @see _search_api_index_queued_items()
  1013. */
  1014. function &search_api_index_specific_items_delayed(SearchApiIndex $index = NULL, array $ids = array()) {
  1015. // We cannot use drupal_static() here because the static cache is reset during
  1016. // batch processing, which breaks batch handling.
  1017. static $queue = array();
  1018. static $registered = FALSE;
  1019. // Only register the shutdown function once.
  1020. if (empty($registered)) {
  1021. drupal_register_shutdown_function('_search_api_index_queued_items');
  1022. $registered = TRUE;
  1023. }
  1024. // Allow for empty call to just retrieve the queue.
  1025. if ($index && $ids) {
  1026. $index_id = $index->machine_name;
  1027. $queue += array($index_id => array());
  1028. $queue[$index_id] += drupal_map_assoc($ids);
  1029. }
  1030. return $queue;
  1031. }
  1032. /**
  1033. * Returns a list of items that need to be indexed for the specified index.
  1034. *
  1035. * @param SearchApiIndex $index
  1036. * The index for which items should be retrieved.
  1037. * @param $limit
  1038. * The maximum number of items to retrieve. -1 means no limit.
  1039. *
  1040. * @return array
  1041. * An array of IDs of items that need to be indexed.
  1042. */
  1043. function search_api_get_items_to_index(SearchApiIndex $index, $limit = -1) {
  1044. if ($limit == 0) {
  1045. return array();
  1046. }
  1047. return $index->datasource()->getChangedItems($index, $limit);
  1048. }
  1049. /**
  1050. * Creates a search query on a specified search index.
  1051. *
  1052. * @param $id
  1053. * The ID or machine name of the index to execute the search on.
  1054. * @param $options
  1055. * An associative array of options. The following are recognized:
  1056. * - filters: Either a SearchApiQueryFilterInterface object or an array of
  1057. * filters used to filter the search.
  1058. * - sort: An array of sort directives of the form $field => $order, where
  1059. * $order is either 'ASC' or 'DESC'.
  1060. * - offset: The position of the first returned search results relative to the
  1061. * whole result in the index.
  1062. * - limit: The maximum number of search results to return. -1 means no limit.
  1063. * - 'query class': The query class to use. Must be a subtype of
  1064. * SearchApiQueryInterface.
  1065. * - conjunction: The type of conjunction to use for this query - either
  1066. * 'AND' or 'OR'. 'AND' by default.
  1067. * - 'parse mode': The mode with which to parse the $keys variable, if it
  1068. * is set and not already an array. See SearchApiQuery::parseModes() for
  1069. * parse modes recognized by the SearchApiQuery class.
  1070. * Subclasses might define additional modes.
  1071. *
  1072. * @return SearchApiQueryInterface
  1073. * An object for searching on the specified index.
  1074. */
  1075. function search_api_query($id, array $options = array()) {
  1076. $index = search_api_index_load($id);
  1077. if (!$index) {
  1078. throw new SearchApiException(t('Unknown index with ID @id.', array('@id' => $id)));
  1079. }
  1080. return $index->query($options);
  1081. }
  1082. /**
  1083. * Static store for the searches executed on the current page. Can either be
  1084. * used to store an executed search, or to retrieve a previously stored
  1085. * search.
  1086. *
  1087. * @param $search_id
  1088. * For pages displaying multiple searches, an optional ID identifying the
  1089. * search in questions. When storing a search, this is filled automatically,
  1090. * unless it is manually set.
  1091. * @param SearchApiQuery $query
  1092. * When storing an executed search, the query that was executed. NULL
  1093. * otherwise.
  1094. * @param array $results
  1095. * When storing an executed search, the returned results as specified by
  1096. * SearchApiQueryInterface::execute(). An empty array, otherwise.
  1097. *
  1098. * @return array
  1099. * If a search with the specified ID was executed, an array containing
  1100. * ($query, $results) as used in this function's parameters. If $search_id is
  1101. * NULL, an array of all executed searches will be returned, keyed by ID.
  1102. */
  1103. function search_api_current_search($search_id = NULL, SearchApiQuery $query = NULL, array $results = array()) {
  1104. $searches = &drupal_static(__FUNCTION__, array());
  1105. if (isset($query)) {
  1106. if (!isset($search_id)) {
  1107. $search_id = $query->getOption('search id');
  1108. }
  1109. $base = $search_id;
  1110. $i = 0;
  1111. while (isset($searches[$search_id])) {
  1112. $search_id = $base . '-' . ++$i;
  1113. }
  1114. $searches[$search_id] = array($query, $results);
  1115. }
  1116. if (isset($search_id)) {
  1117. return isset($searches[$search_id]) ? $searches[$search_id] : NULL;
  1118. }
  1119. return $searches;
  1120. }
  1121. /**
  1122. * Returns all field types recognized by the Search API framework.
  1123. *
  1124. * @return array
  1125. * An associative array with all recognized types as keys, mapped to their
  1126. * translated display names.
  1127. *
  1128. * @see search_api_default_field_types()
  1129. * @see search_api_get_data_type_info()
  1130. */
  1131. function search_api_field_types() {
  1132. $types = search_api_default_field_types();
  1133. foreach (search_api_get_data_type_info() as $id => $type) {
  1134. $types[$id] = $type['name'];
  1135. }
  1136. return $types;
  1137. }
  1138. /**
  1139. * Returns the default field types recognized by the Search API framework.
  1140. *
  1141. * @return array
  1142. * An associative array with the default types as keys, mapped to their
  1143. * translated display names.
  1144. */
  1145. function search_api_default_field_types() {
  1146. return array(
  1147. 'text' => t('Fulltext'),
  1148. 'string' => t('String'),
  1149. 'integer' => t('Integer'),
  1150. 'decimal' => t('Decimal'),
  1151. 'date' => t('Date'),
  1152. 'duration' => t('Duration'),
  1153. 'boolean' => t('Boolean'),
  1154. 'uri' => t('URI'),
  1155. );
  1156. }
  1157. /**
  1158. * Returns either all custom field type definitions, or a specific one.
  1159. *
  1160. * @param $type
  1161. * If specified, the type whose definition should be returned.
  1162. *
  1163. * @return array
  1164. * If $type was not given, an array containing all custom data types, in the
  1165. * format specified by hook_search_api_data_type_info().
  1166. * Otherwise, the definition for the given type, or NULL if it is unknown.
  1167. *
  1168. * @see hook_search_api_data_type_info()
  1169. */
  1170. function search_api_get_data_type_info($type = NULL) {
  1171. $types = &drupal_static(__FUNCTION__);
  1172. if (!isset($types)) {
  1173. $default_types = search_api_default_field_types();
  1174. $types = module_invoke_all('search_api_data_type_info');
  1175. $types = $types ? $types : array();
  1176. foreach ($types as &$type_info) {
  1177. if (!isset($type_info['fallback']) || !isset($default_types[$type_info['fallback']])) {
  1178. $type_info['fallback'] = 'string';
  1179. }
  1180. }
  1181. drupal_alter('search_api_data_type_info', $types);
  1182. }
  1183. if (isset($type)) {
  1184. return isset($types[$type]) ? $types[$type] : NULL;
  1185. }
  1186. return $types;
  1187. }
  1188. /**
  1189. * Returns either a list of all available service infos, or a specific one.
  1190. *
  1191. * @see hook_search_api_service_info()
  1192. *
  1193. * @param $id
  1194. * The ID of the service info to retrieve.
  1195. *
  1196. * @return array
  1197. * If $id was not specified, an array of all available service classes.
  1198. * Otherwise, either the service info with the specified id (if it exists),
  1199. * or NULL.
  1200. */
  1201. function search_api_get_service_info($id = NULL) {
  1202. $services = &drupal_static(__FUNCTION__);
  1203. if (!isset($services)) {
  1204. $services = module_invoke_all('search_api_service_info');
  1205. // Allow other modules to alter definitions
  1206. drupal_alter('search_api_service_info', $services);
  1207. }
  1208. if (isset($id)) {
  1209. return isset($services[$id]) ? $services[$id] : NULL;
  1210. }
  1211. return $services;
  1212. }
  1213. /**
  1214. * Returns information for either all item types, or a specific one.
  1215. *
  1216. * @param $type
  1217. * If set, the item type whose information should be returned.
  1218. *
  1219. * @return
  1220. * If $type is given, either an array containing the information of that item
  1221. * type, or NULL if it is unknown. Otherwise, an array keyed by type IDs
  1222. * containing the information for all item types. Item type information is
  1223. * formatted as specified by hook_search_api_item_type_info(), and has all
  1224. * optional fields filled with the defaults.
  1225. *
  1226. * @see hook_search_api_item_type_info()
  1227. */
  1228. function search_api_get_item_type_info($type = NULL) {
  1229. $types = &drupal_static(__FUNCTION__);
  1230. if (!isset($types)) {
  1231. $types = module_invoke_all('search_api_item_type_info');
  1232. drupal_alter('search_api_item_type_info', $types);
  1233. }
  1234. if (isset($type)) {
  1235. return isset($types[$type]) ? $types[$type] : NULL;
  1236. }
  1237. return $types;
  1238. }
  1239. /**
  1240. * Get a data source controller object for the specified type.
  1241. *
  1242. * @param $type
  1243. * The type whose data source controller should be returned.
  1244. *
  1245. * @return SearchApiDataSourceControllerInterface
  1246. * The type's data source controller.
  1247. *
  1248. * @throws SearchApiException
  1249. * If the type is unknown or specifies an invalid data source controller.
  1250. */
  1251. function search_api_get_datasource_controller($type) {
  1252. $datasources = &drupal_static(__FUNCTION__, array());
  1253. if (empty($datasources[$type])) {
  1254. $info = search_api_get_item_type_info($type);
  1255. if (isset($info['datasource controller']) && class_exists($info['datasource controller'])) {
  1256. $datasources[$type] = new $info['datasource controller']($type);
  1257. }
  1258. if (empty($datasources[$type]) || !($datasources[$type] instanceof SearchApiDataSourceControllerInterface)) {
  1259. unset($datasources[$type]);
  1260. throw new SearchApiException(t('Unknown or invalid item type @type.', array('@type' => $type)));
  1261. }
  1262. }
  1263. return $datasources[$type];
  1264. }
  1265. /**
  1266. * Returns a list of all available data alter callbacks.
  1267. *
  1268. * @see hook_search_api_alter_callback_info()
  1269. *
  1270. * @return array
  1271. * An array of all available data alter callbacks, keyed by function name.
  1272. */
  1273. function search_api_get_alter_callbacks() {
  1274. $callbacks = &drupal_static(__FUNCTION__);
  1275. if (!isset($callbacks)) {
  1276. $callbacks = module_invoke_all('search_api_alter_callback_info');
  1277. // Initialization of optional entries with default values
  1278. foreach ($callbacks as $id => $callback) {
  1279. $callbacks[$id] += array('enabled' => TRUE, 'weight' => 0);
  1280. }
  1281. }
  1282. return $callbacks;
  1283. }
  1284. /**
  1285. * Returns a list of all available pre- and post-processors.
  1286. *
  1287. * @see hook_search_api_processor_info()
  1288. *
  1289. * @return array
  1290. * An array of all available processors, keyed by id.
  1291. */
  1292. function search_api_get_processors() {
  1293. $processors = &drupal_static(__FUNCTION__);
  1294. if (!isset($processors)) {
  1295. $processors = module_invoke_all('search_api_processor_info');
  1296. // Initialization of optional entries with default values
  1297. foreach ($processors as $id => $processor) {
  1298. $processors[$id] += array('enabled pre' => TRUE, 'enabled post' => TRUE, 'weight' => 0);
  1299. }
  1300. }
  1301. return $processors;
  1302. }
  1303. /**
  1304. * Implements hook_search_api_query_alter().
  1305. *
  1306. * Adds node access to the query, if enabled.
  1307. *
  1308. * @param SearchApiQueryInterface $query
  1309. * The SearchApiQueryInterface object representing the search query.
  1310. */
  1311. function search_api_search_api_query_alter(SearchApiQueryInterface $query) {
  1312. $index = $query->getIndex();
  1313. // Only add node access if the necessary fields are indexed in the index, and
  1314. // unless disabled explicitly by the query.
  1315. $fields = $index->options['fields'];
  1316. if (!empty($fields['search_api_access_node']) && !empty($fields['status']) && !empty($fields['author']) && !$query->getOption('search_api_bypass_access')) {
  1317. $account = $query->getOption('search_api_access_account', $GLOBALS['user']);
  1318. if (is_numeric($account)) {
  1319. $account = user_load($account);
  1320. }
  1321. if (is_object($account)) {
  1322. try {
  1323. _search_api_query_add_node_access($account, $query);
  1324. }
  1325. catch (SearchApiException $e) {
  1326. watchdog_exception('search_api', $e);
  1327. }
  1328. }
  1329. else {
  1330. watchdog('search_api', 'An illegal user UID was given for node access: @uid.', array('@uid' => $query->getOption('search_api_access_account', $GLOBALS['user'])), WATCHDOG_WARNING);
  1331. }
  1332. }
  1333. }
  1334. /**
  1335. * Build a node access subquery.
  1336. *
  1337. * @param $account
  1338. * The user object, who searches.
  1339. *
  1340. * @return SearchApiQueryFilter
  1341. */
  1342. function _search_api_query_add_node_access($account, SearchApiQueryInterface $query) {
  1343. if (!user_access('access content', $account)) {
  1344. // Simple hack for returning no results.
  1345. $query->condition('status', 0);
  1346. $query->condition('status', 1);
  1347. watchdog('search_api', 'User @name tried to execute a search, but cannot access content.', array('@name' => theme('username', array('account' => $account))), WATCHDOG_NOTICE);
  1348. return;
  1349. }
  1350. // Only filter for user which don't have full node access.
  1351. if (!user_access('bypass node access', $account)) {
  1352. // Filter by node "published" status.
  1353. if (user_access('view own unpublished content')) {
  1354. $filter = $query->createFilter('OR');
  1355. $filter->condition('status', NODE_PUBLISHED);
  1356. $filter->condition('author', $account->uid);
  1357. $query->filter($filter);
  1358. }
  1359. else {
  1360. $query->condition('status', NODE_PUBLISHED);
  1361. }
  1362. // Filter by node access grants.
  1363. $filter = $query->createFilter('OR');
  1364. $grants = node_access_grants('view', $account);
  1365. foreach ($grants as $realm => $gids) {
  1366. foreach ($gids as $gid) {
  1367. $filter->condition('search_api_access_node', "node_access_$realm:$gid");
  1368. }
  1369. }
  1370. $filter->condition('search_api_access_node', 'node_access__all');
  1371. $query->filter($filter);
  1372. }
  1373. }
  1374. /**
  1375. * Utility function for determining whether a field of the given type contains
  1376. * text data.
  1377. *
  1378. * @param $type
  1379. * A string containing the type to check.
  1380. * @param array $allowed
  1381. * Optionally, an array of allowed types.
  1382. *
  1383. * @return
  1384. * TRUE if $type is either one of the specified types, or a list of such
  1385. * values. FALSE otherwise.
  1386. */
  1387. function search_api_is_text_type($type, array $allowed = array('text')) {
  1388. return array_search(search_api_extract_inner_type($type), $allowed) !== FALSE;
  1389. }
  1390. /**
  1391. * Utility function for determining whether a field of the given type contains
  1392. * a list of any kind.
  1393. *
  1394. * @param $type
  1395. * A string containing the type to check.
  1396. *
  1397. * @return
  1398. * TRUE iff $type is a list type ("list<*>").
  1399. */
  1400. function search_api_is_list_type($type) {
  1401. return substr($type, 0, 5) == 'list<';
  1402. }
  1403. /**
  1404. * Utility function for determining the nesting level of a list type.
  1405. *
  1406. * @param $type
  1407. * A string containing the type to check.
  1408. *
  1409. * @return
  1410. * The nesting level of the type. 0 for singular types, 1 for lists of
  1411. * singular types, etc.
  1412. */
  1413. function search_api_list_nesting_level($type) {
  1414. $level = 0;
  1415. while (search_api_is_list_type($type)) {
  1416. $type = substr($type, 5, -1);
  1417. ++$level;
  1418. }
  1419. return $level;
  1420. }
  1421. /**
  1422. * Utility function for nesting a type to the same level as another type.
  1423. * I.e., after <code>$t = search_api_nest_type($type, $nested_type);</code> is
  1424. * executed, the following statements will always be true:
  1425. * @code
  1426. * search_api_list_nesting_level($t) == search_api_list_nesting_level($nested_type);
  1427. * search_api_extract_inner_type($t) == search_api_extract_inner_type($type);
  1428. * @endcode
  1429. *
  1430. * @param $type
  1431. * The type to wrap.
  1432. * @param $nested_type
  1433. * Another type, determining the nesting level.
  1434. *
  1435. * @return
  1436. * A list version of $type, as specified above.
  1437. */
  1438. function search_api_nest_type($type, $nested_type) {
  1439. while (search_api_is_list_type($nested_type)) {
  1440. $nested_type = substr($nested_type, 5, -1);
  1441. $type = "list<$type>";
  1442. }
  1443. return $type;
  1444. }
  1445. /**
  1446. * Utility function for extracting the contained primitive type of a list type.
  1447. *
  1448. * @param $type
  1449. * A string containing the list type to process.
  1450. *
  1451. * @return
  1452. * A string containing the primitive type contained within the list, e.g.
  1453. * "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
  1454. * type, it is returned unchanged.
  1455. */
  1456. function search_api_extract_inner_type($type) {
  1457. while (search_api_is_list_type($type)) {
  1458. $type = substr($type, 5, -1);
  1459. }
  1460. return $type;
  1461. }
  1462. /**
  1463. * Utility function for extracting specific fields from an EntityMetadataWrapper
  1464. * object.
  1465. *
  1466. * @param EntityMetadataWrapper $wrapper
  1467. * The wrapper from which to extract fields.
  1468. * @param array $fields
  1469. * The fields to extract, as stored in an index. I.e., the array keys are
  1470. * field names, the values are arrays with the keys "name", "type", "boost"
  1471. * and "indexed" (although only "type" is used by this function).
  1472. * @param array $value_options
  1473. * An array of options that should be passed to the
  1474. * EntityMetadataWrapper::value() method (see there).
  1475. *
  1476. * @return
  1477. * The $fields array with additional "value" and "original_type" keys set.
  1478. */
  1479. function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
  1480. // If $wrapper is a list of entities, we have to aggregate their field values.
  1481. $wrapper_info = $wrapper->info();
  1482. if (search_api_is_list_type($wrapper_info['type'])) {
  1483. foreach ($fields as $field => &$info) {
  1484. $info['value'] = array();
  1485. $info['original_type'] = $info['type'];
  1486. }
  1487. unset($info);
  1488. try {
  1489. foreach ($wrapper as $i => $w) {
  1490. $nested_fields = search_api_extract_fields($w, $fields, $value_options);
  1491. foreach ($nested_fields as $field => $info) {
  1492. if (isset($info['value'])) {
  1493. $fields[$field]['value'][] = $info['value'];
  1494. }
  1495. if (isset($info['original_type'])) {
  1496. $fields[$field]['original_type'] = $info['original_type'];
  1497. }
  1498. }
  1499. }
  1500. }
  1501. catch (EntityMetadataWrapperException $e) {
  1502. // Catch exceptions caused by not set list values.
  1503. }
  1504. return $fields;
  1505. }
  1506. $nested = array();
  1507. $entity_infos = entity_get_info();
  1508. foreach ($fields as $field => &$info) {
  1509. $pos = strpos($field, ':');
  1510. if ($pos === FALSE) {
  1511. // Set "defaults" in case an error occurs later.
  1512. $info['value'] = NULL;
  1513. $info['original_type'] = $info['type'];
  1514. try {
  1515. $info['value'] = $wrapper->$field->value($value_options);
  1516. // For fulltext fields with options, also include the option labels.
  1517. if (search_api_is_text_type($info['type']) && $wrapper->$field->optionsList('view')) {
  1518. _search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
  1519. }
  1520. $property_info = $wrapper->$field->info();
  1521. $info['original_type'] = $property_info['type'];
  1522. // For entities, we extract the entity ID instead of the whole object.
  1523. // @todo Use 'identifier' => TRUE instead of always loading the object.
  1524. $t = search_api_extract_inner_type($property_info['type']);
  1525. if (isset($entity_infos[$t])) {
  1526. // If no object is set, set this field to NULL.
  1527. $info['value'] = $info['value'] ? _search_api_extract_entity_value($wrapper->$field, search_api_is_text_type($info['type'])) : NULL;
  1528. }
  1529. }
  1530. catch (EntityMetadataWrapperException $e) {
  1531. // This might happen for entity-typed properties that are NULL, e.g.,
  1532. // for comments without parent.
  1533. }
  1534. }
  1535. else {
  1536. list($prefix, $key) = explode(':', $field, 2);
  1537. $nested[$prefix][$key] = $info;
  1538. }
  1539. }
  1540. unset($info);
  1541. foreach ($nested as $prefix => $nested_fields) {
  1542. if (isset($wrapper->$prefix)) {
  1543. $nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
  1544. foreach ($nested_fields as $field => $info) {
  1545. $fields["$prefix:$field"] = $info;
  1546. }
  1547. }
  1548. else {
  1549. foreach ($nested_fields as $field => &$info) {
  1550. $info['value'] = NULL;
  1551. $info['original_type'] = $info['type'];
  1552. }
  1553. }
  1554. }
  1555. return $fields;
  1556. }
  1557. /**
  1558. * Helper method for adding additional text data to fields with an option list.
  1559. */
  1560. function _search_api_add_option_values(&$value, array $options) {
  1561. if (is_array($value)) {
  1562. foreach ($value as &$v) {
  1563. _search_api_add_option_values($v, $options);
  1564. }
  1565. return;
  1566. }
  1567. if (is_scalar($value) && isset($options[$value])) {
  1568. $value .= ' ' . $options[$value];
  1569. }
  1570. }
  1571. /**
  1572. * Helper method for extracting the ID (and possibly label) of an entity-valued field.
  1573. */
  1574. function _search_api_extract_entity_value(EntityMetadataWrapper $wrapper, $fulltext = FALSE) {
  1575. $v = $wrapper->value();
  1576. if (is_array($v)) {
  1577. $ret = array();
  1578. foreach ($wrapper as $item) {
  1579. $values = _search_api_extract_entity_value($item, $fulltext);
  1580. if ($values) {
  1581. $ret[] = $values;
  1582. }
  1583. }
  1584. return $ret;
  1585. }
  1586. if ($v) {
  1587. $ret = $wrapper->getIdentifier();
  1588. if ($fulltext && ($label = $wrapper->label())) {
  1589. $ret .= ' ' . $label;
  1590. }
  1591. return $ret;
  1592. }
  1593. return NULL;
  1594. }
  1595. /**
  1596. * Load the search server with the specified id.
  1597. *
  1598. * @param $id
  1599. * The search server's id.
  1600. * @param $reset
  1601. * Whether to reset the internal cache.
  1602. *
  1603. * @return SearchApiServer
  1604. * An object representing the server with the specified id.
  1605. */
  1606. function search_api_server_load($id, $reset = FALSE) {
  1607. $ret = search_api_server_load_multiple(array($id), array(), $reset);
  1608. return $ret ? reset($ret) : FALSE;
  1609. }
  1610. /**
  1611. * Load multiple servers at once, determined by IDs or machine names, or by
  1612. * other conditions.
  1613. *
  1614. * @see entity_load()
  1615. *
  1616. * @param $ids
  1617. * An array of server IDs or machine names, or FALSE to load all servers.
  1618. * @param $conditions
  1619. * An array of conditions on the {search_api_server} table in the form
  1620. * 'field' => $value.
  1621. * @param $reset
  1622. * Whether to reset the internal entity_load cache.
  1623. *
  1624. * @return array
  1625. * An array of server objects keyed by machine name.
  1626. */
  1627. function search_api_server_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  1628. return entity_load_multiple_by_name('search_api_server', $ids, $conditions, $reset);
  1629. }
  1630. /**
  1631. * Entity uri callback.
  1632. */
  1633. function search_api_server_url(SearchApiServer $server) {
  1634. return array(
  1635. 'path' => 'admin/config/search/search_api/server/' . $server->machine_name,
  1636. 'options' => array(),
  1637. );
  1638. }
  1639. /**
  1640. * Title callback for determining which title should be displayed for the
  1641. * "delete" local task.
  1642. *
  1643. * @param Entity $entity
  1644. * The server or index for which the menu link is displayed.
  1645. *
  1646. * @return string
  1647. * A translated version of either "Delete" or "Revert".
  1648. */
  1649. function search_api_title_delete_page(Entity $entity) {
  1650. return $entity->hasStatus(ENTITY_OVERRIDDEN) ? t('Revert') : t('Delete');
  1651. }
  1652. /**
  1653. * Access callback for determining if a server's or index' "delete" page should
  1654. * be accessible.
  1655. *
  1656. * @param Entity $entity
  1657. * The server or index for which the access to the delete page is checked.
  1658. *
  1659. * @return
  1660. * TRUE if the delete page can be accessed by the user, FALSE otherwise.
  1661. */
  1662. function search_api_access_delete_page(Entity $entity) {
  1663. return user_access('administer search_api') && $entity->hasStatus(ENTITY_CUSTOM);
  1664. }
  1665. /**
  1666. * Inserts a new search server into the database.
  1667. *
  1668. * @param array $values
  1669. * An array containing the values to be inserted.
  1670. *
  1671. * @return
  1672. * The newly inserted server's id, or FALSE on error.
  1673. */
  1674. function search_api_server_insert(array $values) {
  1675. $server = entity_create('search_api_server', $values);
  1676. $server->is_new = TRUE;
  1677. $server->save();
  1678. return $server->id;
  1679. }
  1680. /**
  1681. * Changes a server's settings.
  1682. *
  1683. * @param $id
  1684. * The ID or machine name of the server whose values should be changed.
  1685. * @param array $fields
  1686. * The new field values to set. The enabled field can't be set this way, use
  1687. * search_api_server_enable() and search_api_server_disable() instead.
  1688. *
  1689. * @return
  1690. * 1 if fields were changed, 0 if the fields already had the desired values.
  1691. * FALSE on failure.
  1692. */
  1693. function search_api_server_edit($id, array $fields) {
  1694. $server = search_api_server_load($id, TRUE);
  1695. $ret = $server->update($fields);
  1696. return $ret ? 1 : $ret;
  1697. }
  1698. /**
  1699. * Enables a search server. Will also check for remembered tasks for this server
  1700. * and execute them.
  1701. *
  1702. * @param $id
  1703. * The ID or machine name of the server to enable.
  1704. *
  1705. * @return
  1706. * 1 on success, 0 or FALSE on failure.
  1707. */
  1708. function search_api_server_enable($id) {
  1709. $server = search_api_server_load($id, TRUE);
  1710. $ret = $server->update(array('enabled' => 1));
  1711. return $ret ? 1 : $ret;
  1712. }
  1713. /**
  1714. * Disables a search server, along with all associated indexes.
  1715. *
  1716. * @param $id
  1717. * The ID or machine name of the server to disable.
  1718. *
  1719. * @return
  1720. * 1 on success, 0 or FALSE on failure.
  1721. */
  1722. function search_api_server_disable($id) {
  1723. $server = search_api_server_load($id, TRUE);
  1724. $ret = $server->update(array('enabled' => 0));
  1725. return $ret ? 1 : $ret;
  1726. }
  1727. /**
  1728. * Deletes a search server and disables all associated indexes.
  1729. *
  1730. * @param $id
  1731. * The ID or machine name of the server to delete.
  1732. *
  1733. * @return
  1734. * 1 on success, 0 or FALSE on failure.
  1735. */
  1736. function search_api_server_delete($id) {
  1737. $server = search_api_server_load($id, TRUE);
  1738. $server->delete();
  1739. return 1;
  1740. }
  1741. /**
  1742. * Loads the Search API index with the specified id.
  1743. *
  1744. * @param $id
  1745. * The index' id.
  1746. * @param $reset
  1747. * Whether to reset the internal cache.
  1748. *
  1749. * @return SearchApiIndex
  1750. * A completely loaded index object, or NULL if no such index exists.
  1751. */
  1752. function search_api_index_load($id, $reset = FALSE) {
  1753. $ret = search_api_index_load_multiple(array($id), array(), $reset);
  1754. return $ret ? reset($ret) : FALSE;
  1755. }
  1756. /**
  1757. * Load multiple indexes at once, determined by IDs or machine names, or by
  1758. * other conditions.
  1759. *
  1760. * @see entity_load()
  1761. *
  1762. * @param $ids
  1763. * An array of index IDs or machine names, or FALSE to load all indexes.
  1764. * @param $conditions
  1765. * An array of conditions on the {search_api_index} table in the form
  1766. * 'field' => $value.
  1767. * @param $reset
  1768. * Whether to reset the internal entity_load cache.
  1769. *
  1770. * @return array
  1771. * An array of index objects keyed by machine name.
  1772. */
  1773. function search_api_index_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  1774. // This line is a workaround for a weird PDO bug in PHP 5.2.
  1775. // See http://drupal.org/node/889286.
  1776. new SearchApiIndex();
  1777. return entity_load_multiple_by_name('search_api_index', $ids, $conditions, $reset);
  1778. }
  1779. /**
  1780. * Determines a search index' indexing status.
  1781. *
  1782. * @param SearchApiIndex $index
  1783. * The index whose indexing status should be determined.
  1784. *
  1785. * @return array
  1786. * An associative array containing two keys (in this order):
  1787. * - indexed: The number of items already indexed in their latest version.
  1788. * - total: The total number of items that have to be indexed for this index.
  1789. */
  1790. function search_api_index_status(SearchApiIndex $index) {
  1791. return $index->datasource()->getIndexStatus($index);
  1792. }
  1793. /**
  1794. * Entity uri callback.
  1795. */
  1796. function search_api_index_url(SearchApiIndex $index) {
  1797. return array(
  1798. 'path' => 'admin/config/search/search_api/index/' . $index->machine_name,
  1799. 'options' => array(),
  1800. );
  1801. }
  1802. /**
  1803. * Property callback.
  1804. *
  1805. * @return SearchApiServer
  1806. * The server this index currently resides on, or NULL if the index
  1807. * is currently unassigned.
  1808. */
  1809. function search_api_index_get_server(SearchApiIndex $index) {
  1810. return $index->server();
  1811. }
  1812. /**
  1813. * Inserts a new search index into the database.
  1814. *
  1815. * @param array $values
  1816. * An array containing the values to be inserted.
  1817. *
  1818. * @return
  1819. * The newly inserted index' id, or FALSE on error.
  1820. */
  1821. function search_api_index_insert(array $values) {
  1822. $index = entity_create('search_api_index', $values);
  1823. $index->is_new = TRUE;
  1824. $index->save();
  1825. return $index->id;
  1826. }
  1827. /**
  1828. * Changes an index' settings.
  1829. *
  1830. * @param $id
  1831. * The edited index' id.
  1832. * @param array $fields
  1833. * The new field values to set.
  1834. *
  1835. * @return
  1836. * 1 if fields were changed, 0 if the fields already had the desired values.
  1837. * FALSE on failure.
  1838. */
  1839. function search_api_index_edit($id, array $fields) {
  1840. $index = search_api_index_load($id, TRUE);
  1841. $ret = $index->update($fields);
  1842. return $ret ? 1 : $ret;
  1843. }
  1844. /**
  1845. * Changes an index' indexed field settings.
  1846. *
  1847. * @param $id
  1848. * The ID or machine name of the index whose fields should be changed.
  1849. * @param array $fields
  1850. * The new indexed field settings.
  1851. *
  1852. * @return
  1853. * 1 if the field settings were changed, 0 if they already had the desired
  1854. * values. FALSE on failure.
  1855. */
  1856. function search_api_index_edit_fields($id, array $fields) {
  1857. $index = search_api_index_load($id, TRUE);
  1858. $options = $index->options;
  1859. $options['fields'] = $fields;
  1860. $ret = $index->update(array('options' => $options));
  1861. return $ret ? 1 : $ret;
  1862. }
  1863. /**
  1864. * Enables a search index.
  1865. *
  1866. * @param $id
  1867. * The ID or machine name of the index to enable.
  1868. *
  1869. * @throws SearchApiException
  1870. * If the index' server isn't enabled.
  1871. *
  1872. * @return
  1873. * 1 on success, 0 or FALSE on failure.
  1874. */
  1875. function search_api_index_enable($id) {
  1876. $index = search_api_index_load($id, TRUE);
  1877. $ret = $index->update(array('enabled' => 1));
  1878. return $ret ? 1 : $ret;
  1879. }
  1880. /**
  1881. * Disables a search index.
  1882. *
  1883. * @param $id
  1884. * The ID or machine name of the index to disable.
  1885. *
  1886. * @return
  1887. * 1 on success, 0 or FALSE on failure.
  1888. */
  1889. function search_api_index_disable($id) {
  1890. $index = search_api_index_load($id, TRUE);
  1891. $ret = $index->update(array('enabled' => 0));
  1892. return $ret ? 1 : $ret;
  1893. }
  1894. /**
  1895. * Schedules a search index for re-indexing.
  1896. *
  1897. * @param $id
  1898. * The ID or machine name of the index to re-index.
  1899. *
  1900. * @return
  1901. * TRUE on success, FALSE on failure.
  1902. */
  1903. function search_api_index_reindex($id) {
  1904. $index = search_api_index_load($id);
  1905. return $index->reindex();
  1906. }
  1907. /**
  1908. * Helper method for marking all items on an index as needing re-indexing.
  1909. *
  1910. * @param SearchApiIndex $index
  1911. * The index whose items should be re-indexed.
  1912. */
  1913. function _search_api_index_reindex(SearchApiIndex $index) {
  1914. $index->datasource()->trackItemChange(FALSE, array($index), TRUE);
  1915. _search_api_empty_cron_queue($index);
  1916. }
  1917. /**
  1918. * Helper method for removing all of an index's jobs from the cron queue.
  1919. *
  1920. * @param SearchApiIndex $index
  1921. * The index whose jobs should be removed.
  1922. * @param $mark_changed
  1923. * If TRUE, mark all items in the queue as "changed" again. Defaults to FALSE.
  1924. */
  1925. function _search_api_empty_cron_queue(SearchApiIndex $index, $mark_changed = FALSE) {
  1926. $index_id = $index->machine_name;
  1927. $queue = DrupalQueue::get('search_api_indexing_queue');
  1928. $queue->createQueue();
  1929. $ids = array();
  1930. $release_items = array();
  1931. while ($item = $queue->claimItem()) {
  1932. if ($item->data['index'] === $index_id) {
  1933. $queue->deleteItem($item);
  1934. if ($mark_changed) {
  1935. $ids = array_merge($ids, $item->data['items']);
  1936. }
  1937. }
  1938. else {
  1939. $release_items[] = $item;
  1940. }
  1941. }
  1942. foreach ($release_items as $item) {
  1943. $queue->releaseItem($item);
  1944. }
  1945. if ($ids) {
  1946. $index->datasource()->trackItemChange($ids, array($index), TRUE);
  1947. }
  1948. }
  1949. /**
  1950. * Clears a search index and schedules all of its items for re-indexing.
  1951. *
  1952. * @param $id
  1953. * The ID or machine name of the index to clear.
  1954. *
  1955. * @return
  1956. * TRUE on success, FALSE on failure.
  1957. */
  1958. function search_api_index_clear($id) {
  1959. $index = search_api_index_load($id);
  1960. return $index->clear();
  1961. }
  1962. /**
  1963. * Deletes a search index.
  1964. *
  1965. * @param $id
  1966. * The ID or machine name of the index to delete.
  1967. *
  1968. * @return
  1969. * TRUE on success, FALSE on failure.
  1970. */
  1971. function search_api_index_delete($id) {
  1972. $index = search_api_index_load($id);
  1973. if (!$index) {
  1974. return FALSE;
  1975. }
  1976. $index->delete();
  1977. return TRUE;
  1978. }
  1979. /**
  1980. * Options list callback for search indexes.
  1981. *
  1982. * @return array
  1983. * An array of search index machine names mapped to their human-readable
  1984. * names.
  1985. */
  1986. function search_api_index_options_list() {
  1987. $ret = array(
  1988. NULL => '- ' . t('All') . ' -',
  1989. );
  1990. foreach (search_api_index_load_multiple(FALSE) as $id => $index) {
  1991. $ret[$id] = $index->name;
  1992. }
  1993. return $ret;
  1994. }
  1995. /**
  1996. * Cron queue worker callback for indexing some items.
  1997. *
  1998. * @param array $task
  1999. * An associative array containing:
  2000. * - index: The ID of the index on which items should be indexed.
  2001. * - items: The items that should be indexed.
  2002. *
  2003. * @return
  2004. * The number of successfully indexed items.
  2005. */
  2006. function _search_api_indexing_queue_process(array $task) {
  2007. $index = search_api_index_load($task['index']);
  2008. try {
  2009. if ($index && $index->enabled && !$index->read_only && $task['items']) {
  2010. $indexed = search_api_index_specific_items($index, $task['items']);
  2011. $num = count($indexed);
  2012. // If some items couldn't be indexed, mark them as dirty again.
  2013. if ($num < count($task['items'])) {
  2014. // Believe it or not but this is actually quite faster than the equivalent
  2015. // $diff = array_diff($task['items'], $indexed);
  2016. $diff = array_keys(array_diff_key(array_flip($task['items']), array_flip($indexed)));
  2017. // Mark the items as dirty again.
  2018. $index->datasource()->trackItemChange($diff, array($index), TRUE);
  2019. }
  2020. if ($num) {
  2021. watchdog('search_api', t('Indexed @num items for index @name', array('@num' => $num, '@name' => $index->name)), NULL, WATCHDOG_INFO);
  2022. }
  2023. return $num;
  2024. }
  2025. }
  2026. catch (SearchApiException $e) {
  2027. watchdog_exception('search_api', $e);
  2028. }
  2029. }
  2030. /**
  2031. * Shutdown function which indexes all queued items, if any.
  2032. */
  2033. function _search_api_index_queued_items() {
  2034. $queue = &search_api_index_specific_items_delayed();
  2035. try {
  2036. if ($queue) {
  2037. $indexes = search_api_index_load_multiple(array_keys($queue));
  2038. foreach ($indexes as $index_id => $index) {
  2039. search_api_index_specific_items($index, $queue[$index_id]);
  2040. }
  2041. }
  2042. // Reset the queue so we don't index the items twice by accident.
  2043. $queue = array();
  2044. }
  2045. catch (SearchApiException $e) {
  2046. watchdog_exception('search_api', $e);
  2047. }
  2048. }
  2049. /**
  2050. * Helper function to be used as a "property info alter" callback.
  2051. *
  2052. * If a wrapped entity is passed to this function, all its available properties
  2053. * and fields, regardless of bundle, are added to the wrapper.
  2054. */
  2055. function _search_api_wrapper_add_all_properties(EntityMetadataWrapper $wrapper, array $property_info) {
  2056. if ($properties = entity_get_all_property_info($wrapper->type())) {
  2057. $property_info['properties'] = $properties;
  2058. }
  2059. return $property_info;
  2060. }
  2061. /**
  2062. * Helper function for converting data to a custom type.
  2063. */
  2064. function _search_api_convert_custom_type($callback, $value, $original_type, $type, $nesting_level) {
  2065. if ($nesting_level == 0) {
  2066. return call_user_func($callback, $value, $original_type, $type);
  2067. }
  2068. if (!is_array($value)) {
  2069. return NULL;
  2070. }
  2071. --$nesting_level;
  2072. $values = array();
  2073. foreach ($value as $v) {
  2074. $v = _search_api_convert_custom_type($callback, $v, $original_type, $type, $nesting_level);
  2075. if (isset($v) && !(is_array($v) && !$v)) {
  2076. $values[] = $v;
  2077. }
  2078. }
  2079. return $values;
  2080. }
  2081. /**
  2082. * Create and set a batch for indexing items.
  2083. *
  2084. * @param SearchApiIndex $index
  2085. * The index for which items should be indexed.
  2086. * @param $batch_size
  2087. * Number of items to index per batch.
  2088. * @param $limit
  2089. * Maximum number of items to index.
  2090. * @param $remaining
  2091. * Remaining items to index.
  2092. * @param $drush
  2093. * Boolean specifying whether this was called from drush or not.
  2094. */
  2095. function _search_api_batch_indexing_create(SearchApiIndex $index, $batch_size, $limit, $remaining, $drush = FALSE) {
  2096. if ($limit !== 0 && $batch_size !== 0) {
  2097. $t = !empty($drush) ? 'dt' : 't';
  2098. if ($limit < 0 || $limit > $remaining) {
  2099. $limit = $remaining;
  2100. }
  2101. if ($batch_size < 0) {
  2102. $batch_size = $remaining;
  2103. }
  2104. $batch = array(
  2105. 'title' => $t('Indexing items'),
  2106. 'operations' => array(
  2107. array('_search_api_batch_indexing_callback', array($index, $batch_size, $limit, $drush)),
  2108. ),
  2109. 'progress_message' => $t('Completed about @percentage% of the indexing operation.'),
  2110. 'finished' => '_search_api_batch_indexing_finished',
  2111. 'file' => drupal_get_path('module', 'search_api') . '/search_api.module',
  2112. );
  2113. batch_set($batch);
  2114. return TRUE;
  2115. }
  2116. return FALSE;
  2117. }
  2118. /**
  2119. * Batch API callback for the indexing functionality.
  2120. *
  2121. * @param SearchApiIndex $index
  2122. * The index for which items should be indexed.
  2123. * @param integer $batch_size
  2124. * Number of items to index per batch.
  2125. * @param integer $limit
  2126. * Maximum number of items to index.
  2127. * @param boolean $drush
  2128. * Boolean specifying whether this was called from drush or not.
  2129. * @param array $context
  2130. * The batch context.
  2131. */
  2132. function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, $limit, $drush = FALSE, array &$context) {
  2133. // Persistent data among batch runs.
  2134. if (!isset($context['sandbox']['limit'])) {
  2135. $context['sandbox']['limit'] = $limit;
  2136. $context['sandbox']['batch_size'] = $batch_size;
  2137. $context['sandbox']['progress'] = 0;
  2138. }
  2139. // Persistent data for results.
  2140. if (!isset($context['results']['indexed'])) {
  2141. $context['results']['indexed'] = 0;
  2142. $context['results']['not indexed'] = 0;
  2143. $context['results']['drush'] = $drush;
  2144. }
  2145. // Number of items to index for this run.
  2146. $to_index = min($context['sandbox']['limit'] - $context['sandbox']['progress'], $context['sandbox']['batch_size']);
  2147. // Index the items.
  2148. $indexed = search_api_index_items($index, $to_index);
  2149. $context['results']['indexed'] += $indexed;
  2150. // Display progress message.
  2151. if ($indexed > 0) {
  2152. $format_plural = $context['results']['drush'] === TRUE ? '_search_api_drush_format_plural' : 'format_plural';
  2153. $context['message'] = $format_plural($context['results']['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.');
  2154. }
  2155. // Some items couldn't be indexed.
  2156. if ($indexed !== $to_index) {
  2157. $context['results']['not indexed'] += $to_index - $indexed;
  2158. }
  2159. $context['sandbox']['progress'] += $to_index;
  2160. // Everything has been indexed.
  2161. if ($indexed === 0 || $context['sandbox']['progress'] >= $context['sandbox']['limit']) {
  2162. $context['finished'] = 1;
  2163. }
  2164. else {
  2165. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['limit'];
  2166. }
  2167. }
  2168. /**
  2169. * Batch API finishing callback for the indexing functionality.
  2170. *
  2171. * @param boolean $success
  2172. * Result of the batch operation.
  2173. * @param array $results
  2174. * Results.
  2175. * @param array $operations
  2176. * Remaining batch operation to process.
  2177. */
  2178. function _search_api_batch_indexing_finished($success, $results, $operations) {
  2179. // Check if called from drush.
  2180. if (!empty($results['drush'])) {
  2181. $drupal_set_message = 'drush_log';
  2182. $format_plural = '_search_api_drush_format_plural';
  2183. $t = 'dt';
  2184. $success_message = 'success';
  2185. }
  2186. else {
  2187. $drupal_set_message = 'drupal_set_message';
  2188. $format_plural = 'format_plural';
  2189. $t = 't';
  2190. $success_message = 'status';
  2191. }
  2192. // Display result messages.
  2193. if ($success) {
  2194. if (!empty($results['indexed'])) {
  2195. $drupal_set_message($format_plural($results['indexed'], 'Successfully indexed 1 item.', 'Successfully indexed @count items.'), $success_message);
  2196. if (!empty($results['not indexed'])) {
  2197. $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');
  2198. }
  2199. }
  2200. else {
  2201. $drupal_set_message($t("Couldn't index items. Check the logs for details."), 'error');
  2202. }
  2203. }
  2204. else {
  2205. $drupal_set_message($t("An error occurred while trying to index items. Check the logs for details."), 'error');
  2206. }
  2207. }