datasource_multiple.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. /**
  3. * @file
  4. * Contains SearchApiCombinedEntityDataSourceController.
  5. */
  6. /**
  7. * Provides a datasource for indexing multiple types of entities.
  8. */
  9. class SearchApiCombinedEntityDataSourceController extends SearchApiAbstractDataSourceController {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. protected $table = 'search_api_item_string_id';
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function getIdFieldInfo() {
  18. return array(
  19. 'key' => 'item_id',
  20. 'type' => 'string',
  21. );
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function loadItems(array $ids) {
  27. $ids_by_type = array();
  28. foreach ($ids as $id) {
  29. list($type, $entity_id) = explode('/', $id);
  30. $ids_by_type[$type][$entity_id] = $id;
  31. }
  32. $items = array();
  33. foreach ($ids_by_type as $type => $type_ids) {
  34. foreach (entity_load($type, array_keys($type_ids)) as $entity_id => $entity) {
  35. $id = $type_ids[$entity_id];
  36. $item = (object) array($type => $entity);
  37. $item->item_id = $id;
  38. $item->item_type = $type;
  39. $item->item_entity_id = $entity_id;
  40. $item->item_bundle = NULL;
  41. // Add the item language so the "search_api_language" field will work
  42. // correctly.
  43. $item->language = isset($entity->language) ? $entity->language : NULL;
  44. try {
  45. list(, , $bundle) = entity_extract_ids($type, $entity);
  46. $item->item_bundle = $bundle ? "$type:$bundle" : NULL;
  47. }
  48. catch (EntityMalformedException $e) {
  49. // Will probably make problems at some other place, but for extracting
  50. // the bundle it is really not critical enough to fail on – just
  51. // ignore this exception.
  52. }
  53. $items[$id] = $item;
  54. unset($type_ids[$entity_id]);
  55. }
  56. if ($type_ids) {
  57. search_api_track_item_delete($type, array_keys($type_ids));
  58. }
  59. }
  60. return $items;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. protected function getPropertyInfo() {
  66. $info = array(
  67. 'item_id' => array(
  68. 'label' => t('ID'),
  69. 'description' => t('The combined ID of the item, containing both entity type and entity ID.'),
  70. 'type' => 'token',
  71. ),
  72. 'item_type' => array(
  73. 'label' => t('Entity type'),
  74. 'description' => t('The entity type of the item.'),
  75. 'type' => 'token',
  76. 'options list' => 'search_api_entity_type_options_list',
  77. ),
  78. 'item_entity_id' => array(
  79. 'label' => t('Entity ID'),
  80. 'description' => t('The entity ID of the item.'),
  81. 'type' => 'token',
  82. ),
  83. 'item_bundle' => array(
  84. 'label' => t('Bundle'),
  85. 'description' => t('The bundle of the item, if applicable.'),
  86. 'type' => 'token',
  87. 'options list' => 'search_api_combined_bundle_options_list',
  88. ),
  89. 'item_label' => array(
  90. 'label' => t('Label'),
  91. 'description' => t('The label of the item.'),
  92. 'type' => 'text',
  93. // Since this needs a bit more computation than the others, we don't
  94. // include it always when loading the item but use a getter callback.
  95. 'getter callback' => 'search_api_get_multi_type_item_label',
  96. ),
  97. );
  98. foreach ($this->getSelectedEntityTypeOptions() as $type => $label) {
  99. $info[$type] = array(
  100. 'label' => $label,
  101. 'description' => t('The indexed entity, if it is of type %type.', array('%type' => $label)),
  102. 'type' => $type,
  103. );
  104. }
  105. return array('property info' => $info);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function getItemId($item) {
  111. return isset($item->item_id) ? $item->item_id : NULL;
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function getItemLabel($item) {
  117. return search_api_get_multi_type_item_label($item);
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function getItemUrl($item) {
  123. if ($item->item_type == 'file') {
  124. return array(
  125. 'path' => file_create_url($item->file->uri),
  126. 'options' => array(
  127. 'entity_type' => 'file',
  128. 'entity' => $item,
  129. ),
  130. );
  131. }
  132. $url = entity_uri($item->item_type, $item->{$item->item_type});
  133. return $url ? $url : NULL;
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function startTracking(array $indexes) {
  139. if (!$this->table) {
  140. return;
  141. }
  142. // We first clear the tracking table for all indexes, so we can just insert
  143. // all items again without any key conflicts.
  144. $this->stopTracking($indexes);
  145. foreach ($indexes as $index) {
  146. $types = $this->getEntityTypes($index);
  147. // Wherever possible, use a sub-select instead of the much slower
  148. // entity_load().
  149. foreach ($types as $type) {
  150. $entity_info = entity_get_info($type);
  151. if (!empty($entity_info['base table'])) {
  152. // Assumes that all entities use the "base table" property and the
  153. // "entity keys[id]" in the same way as the default controller.
  154. $id_field = $entity_info['entity keys']['id'];
  155. $table = $entity_info['base table'];
  156. // Select all entity ids.
  157. $query = db_select($table, 't');
  158. $query->addExpression("CONCAT(:prefix, t.$id_field)", 'item_id', array(':prefix' => $type . '/'));
  159. $query->addExpression(':index_id', 'index_id', array(':index_id' => $index->id));
  160. $query->addExpression('1', 'changed');
  161. // INSERT ... SELECT ...
  162. db_insert($this->table)
  163. ->from($query)
  164. ->execute();
  165. unset($types[$type]);
  166. }
  167. }
  168. // In the absence of a "base table", use the slow entity_load().
  169. if ($types) {
  170. foreach ($types as $type) {
  171. $query = new EntityFieldQuery();
  172. $query->entityCondition('entity_type', $type);
  173. $result = $query->execute();
  174. $ids = !empty($result[$type]) ? array_keys($result[$type]) : array();
  175. if ($ids) {
  176. foreach ($ids as $i => $id) {
  177. $ids[$i] = $type . '/' . $id;
  178. }
  179. $this->trackItemInsert($ids, array($index), TRUE);
  180. }
  181. }
  182. }
  183. }
  184. }
  185. /**
  186. * Starts tracking the index status for the given items on the given indexes.
  187. *
  188. * @param array $item_ids
  189. * The IDs of new items to track.
  190. * @param SearchApiIndex[] $indexes
  191. * The indexes for which items should be tracked.
  192. * @param bool $skip_type_check
  193. * (optional) If TRUE, don't check whether the type matches the index's
  194. * datasource configuration. Internal use only.
  195. *
  196. * @return SearchApiIndex[]|null
  197. * All indexes for which any items were added; or NULL if items were added
  198. * for all of them.
  199. *
  200. * @throws SearchApiDataSourceException
  201. * If any error state was encountered.
  202. */
  203. public function trackItemInsert(array $item_ids, array $indexes, $skip_type_check = FALSE) {
  204. $ret = array();
  205. foreach ($indexes as $index_id => $index) {
  206. $ids = drupal_map_assoc($item_ids);
  207. if (!$skip_type_check) {
  208. $types = $this->getEntityTypes($index);
  209. foreach ($ids as $id) {
  210. list($type) = explode('/', $id);
  211. if (!isset($types[$type])) {
  212. unset($ids[$id]);
  213. }
  214. }
  215. }
  216. if ($ids) {
  217. parent::trackItemInsert($ids, array($index));
  218. $ret[$index_id] = $index;
  219. }
  220. }
  221. return $ret;
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function configurationForm(array $form, array &$form_state) {
  227. $form['types'] = array(
  228. '#type' => 'checkboxes',
  229. '#title' => t('Entity types'),
  230. '#description' => t('Select the entity types which should be included in this index.'),
  231. '#options' => array_map('check_plain', search_api_entity_type_options_list()),
  232. '#attributes' => array('class' => array('search-api-checkboxes-list')),
  233. '#disabled' => !empty($form_state['index']),
  234. '#required' => TRUE,
  235. );
  236. if (!empty($form_state['index']->options['datasource']['types'])) {
  237. $form['types']['#default_value'] = $this->getEntityTypes($form_state['index']);
  238. }
  239. return $form;
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
  245. if (!empty($values['types'])) {
  246. $values['types'] = array_keys(array_filter($values['types']));
  247. }
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function getConfigurationSummary(SearchApiIndex $index) {
  253. if ($type_labels = $this->getSelectedEntityTypeOptions($index)) {
  254. $args['!types'] = implode(', ', $type_labels);
  255. return format_plural(count($type_labels), 'Indexed entity types: !types.', 'Indexed entity types: !types.', $args);
  256. }
  257. return NULL;
  258. }
  259. /**
  260. * Retrieves the index for which the current method was called.
  261. *
  262. * Very ugly method which uses the stack trace to find the right object.
  263. *
  264. * @return SearchApiIndex
  265. * The active index.
  266. *
  267. * @throws SearchApiException
  268. * Thrown if the active index could not be determined.
  269. */
  270. protected function getCallingIndex() {
  271. foreach (debug_backtrace() as $trace) {
  272. if (isset($trace['object']) && $trace['object'] instanceof SearchApiIndex) {
  273. return $trace['object'];
  274. }
  275. }
  276. // If there's only a single index on the site, it's also easy.
  277. $indexes = search_api_index_load_multiple(FALSE);
  278. if (count($indexes) === 1) {
  279. return reset($indexes);
  280. }
  281. throw new SearchApiException('Could not determine the active index of the datasource.');
  282. }
  283. /**
  284. * Returns the entity types for which this datasource is configured.
  285. *
  286. * Depends on the index from which this method is (indirectly) called.
  287. *
  288. * @param SearchApiIndex $index
  289. * (optional) The index for which to get the enabled entity types. If not
  290. * given, will be determined automatically.
  291. *
  292. * @return string[]
  293. * The machine names of the datasource's enabled entity types, as both keys
  294. * and values.
  295. *
  296. * @throws SearchApiException
  297. * Thrown if the active index could not be determined.
  298. */
  299. protected function getEntityTypes(SearchApiIndex $index = NULL) {
  300. if (!$index) {
  301. $index = $this->getCallingIndex();
  302. }
  303. if (isset($index->options['datasource']['types'])) {
  304. return drupal_map_assoc($index->options['datasource']['types']);
  305. }
  306. return array();
  307. }
  308. /**
  309. * Returns the selected entity type options for this datasource.
  310. *
  311. * Depends on the index from which this method is (indirectly) called.
  312. *
  313. * @param SearchApiIndex $index
  314. * (optional) The index for which to get the enabled entity types. If not
  315. * given, will be determined automatically.
  316. *
  317. * @return string[]
  318. * An associative array, mapping the machine names of the enabled entity
  319. * types to their labels.
  320. *
  321. * @throws SearchApiException
  322. * Thrown if the active index could not be determined.
  323. */
  324. protected function getSelectedEntityTypeOptions(SearchApiIndex $index = NULL) {
  325. return array_intersect_key(search_api_entity_type_options_list(), $this->getEntityTypes($index));
  326. }
  327. }