search_api.module 86 KB

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