tripal_core.search.inc

  1. 2.x tripal_core/includes/tripal_core.search.inc
  2. 3.x legacy/tripal_core/includes/tripal_core.search.inc

Adds support for Drupal indexing of Chado. It's important to note that not all of Chado is indexed but instead Only fields indicated in hook_search_include_chado_fields().

File

legacy/tripal_core/includes/tripal_core.search.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Adds support for Drupal indexing of Chado.
  5. * It's important to note that not all of Chado is indexed but instead
  6. * Only fields indicated in hook_search_include_chado_fields().
  7. */
  8. /**
  9. * Implements hook_search_include_chado_fields().
  10. *
  11. * This hook allows Tripal Admin/modules to specify which chado fields should be indexed
  12. * for searching in a simple manner.
  13. *
  14. * @return
  15. * An array of chado fields you would like available for indexing. Each element should
  16. * be the name of the table followed by the field and separated by a period. For example.
  17. * feature.uniquename to indicate the uniquename field from the feature table.
  18. */
  19. function tripal_core_search_include_chado_fields() {
  20. return array(
  21. 'organism.genus',
  22. 'organism.species',
  23. );
  24. }
  25. /**
  26. * Implements hook_entity_property_info_alter().
  27. *
  28. * This is where we actually add the properties to the node entity in order to indicate
  29. * which chado fields should be indexed.
  30. */
  31. function tripal_core_entity_property_info_alter(&$info) {
  32. // We provide a hook to allow Tripal admin to easily add fields to the search api.
  33. // We want to invoke all implementations of that hook now for use below.
  34. $fields_to_include = module_invoke_all('search_include_chado_fields');
  35. $fields_to_include = array_unique($fields_to_include);
  36. // Retrieve information for all nodes.
  37. // We focus on nodes at this point because we need to link search results back to
  38. // the entity and we have no entites for non-node chado content in Tripal2.
  39. $node_info = module_invoke_all('node_info');
  40. foreach ($node_info as $n) {
  41. // Now keep in mind this hook is defined for ALL THE NODE TYPES and we only want
  42. // to add extra support for chado so we onle care about chado node types.
  43. // We can distinguish chado node types from all others by the existence of
  44. // the 'chado_node_api' key which is used for all sorts of beautiful tripal/chado
  45. // node integration (ie: adding properties, relationships and dbxrefs to node forms).
  46. if (isset($n['chado_node_api'])) {
  47. $schema = chado_get_schema($n['chado_node_api']['base_table']);
  48. // Now we are going to start by adding some defaults. It feels safe to say, we
  49. // probably want to index all the "names" so we are going to look through
  50. // all the fields and if they contain "name" we are going to add them automatically.
  51. foreach ($schema['fields'] as $field_name => $details) {
  52. $machine_name = $n['chado_node_api']['base_table'] . '.' . $field_name;
  53. // Try to create a readable label.
  54. $label = ucwords(str_replace(array('.','_'),' ',$machine_name));
  55. // We want to add all name fields and any fields previously indicated to be indexed.
  56. if (preg_match('/name/', $field_name) OR in_array($machine_name, $fields_to_include)) {
  57. if (!isset($info['node']['bundles'][ $n['base'] ]['properties'][$machine_name])) {
  58. $info['node']['bundles'][ $n['base'] ]['properties'][$machine_name] = array(
  59. 'label' => $label,
  60. 'description' => (isset($details['description'])) ? $details['description'] : '',
  61. 'type' => ($details['type'] == 'varchar') ? 'text' : $details['type'],
  62. 'schema field' => '[' . $machine_name . ']',
  63. // The following getter callback is a generic function that can retrieve
  64. // values for any chado field.
  65. 'getter callback' => 'tripal_search_chado_token_getter_callback'
  66. );
  67. }
  68. }
  69. }
  70. // We want to add any base foreign keys. This allows you to search for all features
  71. // from a given organism. Furthermore, we want to add a single field for each foreign
  72. // key that will span content types in order to be exposed as facets.
  73. foreach ($schema['foreign keys'] as $table => $fk_details) {
  74. foreach ($fk_details['columns'] as $left_field => $right_field) {
  75. $machine_name = $n['chado_node_api']['base_table'] . '.' . $left_field;
  76. $field_details = $schema['fields'][$left_field];
  77. // Try to create a readable label.
  78. $label = $table . ' (' . $machine_name . ')';
  79. if (preg_match('/(\w+)_id/',$left_field,$matches)) {
  80. // Key only field.
  81. $key_label = ucwords(str_replace('_', ' ', $matches[1]));
  82. // Expanded field.
  83. $label = str_replace('_', ' ', $n['chado_node_api']['base_table']);
  84. $label .= ' ' . str_replace('_', ' ', $matches[1]);
  85. $label = ucwords($label);
  86. }
  87. $keytoken = '[BASE.' . $left_field . '>' . $table . '.' . $right_field . ']';
  88. $format = chado_node_get_readable_format($keytoken);
  89. // First, create the key version. This is best used for facets since it
  90. // won't/can't be tokenized along with the other fields. This will be shared
  91. // among node types to facillitate use as a facet.
  92. $info['node']['properties'][$table . '.' . $right_field .' key'] = array(
  93. 'label' => $key_label . ' (All Content Types)',
  94. 'description' => (isset($field_details['description'])) ? $field_details['description'] : '',
  95. 'type' => 'text',
  96. // We include both the token for the current node type and the token for
  97. // the parent table. That way the organism node will appear in the results
  98. // for the organism key.
  99. 'schema field' => $format,
  100. // The following getter callback is a generic function that can retrieve
  101. // values for any chado foreign key.
  102. 'getter callback' => 'tripal_search_chado_token_across_nodetypes_getter_callback'
  103. );
  104. $pretoken = '[' . $n['chado_node_api']['base_table'] . '.' . $left_field . '>' . $table . '.' . $right_field . ']';
  105. $format = chado_node_get_readable_format($pretoken);
  106. // Add a more readable version that will be tokenized so users can
  107. // search for fruitfly and get all features with that as an organism.
  108. $info['node']['bundles'][ $n['base'] ]['properties'][$machine_name .' expanded'] = array(
  109. 'label' => $label . ' (Expanded)',
  110. 'description' => (isset($field_details['description'])) ? $field_details['description'] : '',
  111. 'type' => 'text',
  112. 'schema field' => $format,
  113. // The following getter callback is a generic function that can retrieve
  114. // values for any chado foreign key.
  115. 'getter callback' => 'tripal_search_chado_token_getter_callback'
  116. );
  117. }
  118. }
  119. }
  120. }
  121. // Provide our own hook for altering properties to make it easier for our users.
  122. drupal_alter('tripal_search_properties', $info);
  123. }
  124. /**
  125. * Allows tripal admin to alter entity property information after it has. This is currently
  126. * being used to indicate chado fields to be indexed for search.
  127. *
  128. * NOTE: If you simply need to add a field to be indexed, use hook_search_include_chado_fields()
  129. * which provides the much easier method of simply listing fields to include.
  130. *
  131. * This function is most useful if you want to change the way the value is retrieved
  132. * (done by changing the 'getter callback') or add your own custom computed field.
  133. */
  134. function hook_tripal_search_properties_alter(&$info) { }
  135. /**
  136. * Implements a getter callback for chado token formats.
  137. *
  138. * A chado token format is a string containing chado tokens.
  139. *
  140. * Chado tokens are expected to follow the format of tokens auto-generated using
  141. * chado_node_generate_tokens(). For example, [feature.uniquename] indicates you
  142. * should return the uniquename of a feature node and [feature.organism_id>organism.species]
  143. * indicates you should return the organism genus of the feature node.
  144. *
  145. * The chado token format must be stored in the 'schema field' when defining the property in
  146. * hook_entity_property_info() in order for this getter to work.
  147. *
  148. * @param $data
  149. * The entity object (in our case the node we need to retrieve feature properties for).
  150. * @param $options
  151. * @param $field_name
  152. * The machine name for the entity property.
  153. * @param $info
  154. * The full property definition from entity property info.
  155. *
  156. * @return
  157. * A string representing the "value" of the field.
  158. */
  159. function tripal_search_chado_token_getter_callback($data, $options, $field_name, $type, $info) {
  160. if (isset($data->nid)) {
  161. if (isset($info['schema field'])) {
  162. $format = $info['schema field'];
  163. // Determine our base table so we know if this is even the right node type.
  164. if (preg_match('/\[(\w+)\.(\w+)/',$format, $matches)) {
  165. $base_table = $matches[1];
  166. $field_name = $matches[2];
  167. // For some weird reason nodes of all types are trying to get a value for fields
  168. // that we defined as specific to a given node type (ie: bundle). As such we need
  169. // this check here to ensure this field is actually for this node type.
  170. if (!isset($data->{$base_table})) return NULL;
  171. $format = tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info);
  172. return $format;
  173. }
  174. else {
  175. // Not able to determine table?
  176. tripal_report_error(
  177. 'tripal_search',
  178. TRIPAL_ERROR,
  179. 'Unable to extract the base table from the format (:format) for :field because it didn\'t match the expected format: [tablename.field...',
  180. array(':field' => $field_name, ':format' => $format)
  181. );
  182. return NULL;
  183. }
  184. }
  185. else {
  186. tripal_report_error(
  187. 'tripal_search',
  188. TRIPAL_ERROR,
  189. 'Unable to get value for :field because the schema field was not set.',
  190. array(':field' => $field_name)
  191. );
  192. return NULL;
  193. }
  194. }
  195. }
  196. /**
  197. * Implements a getter callback for foreign keys collon between content types.
  198. *
  199. * @param $data
  200. * The entity object (in our case the node we need to retrieve feature properties for).
  201. * @param $options
  202. * @param $field_name
  203. * The machine name for the entity property.
  204. * @param $info
  205. * The full property definition from entity property info.
  206. *
  207. * @return
  208. * A string representing the "value" of the field.
  209. */
  210. function tripal_search_chado_token_across_nodetypes_getter_callback($data, $options, $field_name, $type, $info) {
  211. // First, make sure this is a chado node.
  212. // Assumption #1: All chado node types are prefixed with chado_
  213. if (isset($data->nid)) {
  214. if (preg_match('/^chado_(\w+)/',$data->type,$matches)) {
  215. if (isset($info['schema field'])) {
  216. // Assumption #2: The base table is the suffix of the node type.
  217. $base_table = $matches[1];
  218. // Substitute in the base table for "BASE" in the schema field.
  219. $format = str_replace('BASE', $base_table, $info['schema field']);
  220. // Replace all tokens for values and return the result.
  221. $format = tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info);
  222. return $format;
  223. }
  224. else {
  225. // Not able to determine table?
  226. tripal_report_error(
  227. 'tripal_search',
  228. TRIPAL_ERROR,
  229. 'Unable to extract the base table from the format (:format) for :field because it didn\'t match the expected format: [tablename.field...',
  230. array(':field' => $field_name, ':format' => $format)
  231. );
  232. }
  233. }
  234. else {
  235. tripal_report_error(
  236. 'tripal_search',
  237. TRIPAL_ERROR,
  238. 'Unable to get value for :field because the schema field was not set.',
  239. array(':field' => $field_name)
  240. );
  241. }
  242. }
  243. return NULL;
  244. }
  245. /**
  246. * Retrieve values for all tokens for an entity property getter function.
  247. */
  248. function tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info) {
  249. // Determine which tokens were used in the format string
  250. if (preg_match_all('/\[[^]]+\]/', $format, $used_tokens)) {
  251. $used_tokens = $used_tokens[0];
  252. // If there are no tokens then return the format as is...
  253. if (empty($used_tokens)) {
  254. tripal_report_error(
  255. 'tripal_search',
  256. TRIPAL_NOTICE,
  257. 'Returned static text for :field since there were no tokens in the supplied format: :format',
  258. array(':field' => $field_name, ':format' => $format)
  259. );
  260. return $format;
  261. }
  262. // Get the value of each token.
  263. $null_tokens = array();
  264. foreach ($used_tokens as $token) {
  265. $token_info = array(
  266. 'name' => $info['label'],
  267. 'table' => $base_table,
  268. 'field' => $field_name,
  269. 'token' => $token,
  270. 'description' => $info['description'],
  271. 'location' => chado_node_get_location_from_token($token),
  272. );
  273. $value = chado_get_token_value($token_info, $data, array('supress_errors' => TRUE));
  274. if (empty($value)) $null_tokens[] = $token;
  275. // And sub it in to the format.
  276. $format = str_replace($token, $value, $format);
  277. }
  278. // If none of the tokens had values then this node doesn't have this field.
  279. // As such we return null so the search api doesn't bother indexing an empty format.
  280. if (sizeof($used_tokens) == sizeof($null_tokens)) return NULL;
  281. }
  282. else {
  283. tripal_report_error(
  284. 'tripal_search',
  285. TRIPAL_NOTICE,
  286. 'Returned static text for :field since there were no tokens of a recognized format in the supplied format: :format',
  287. array(':field' => $field_name, ':format' => $format)
  288. );
  289. }
  290. return $format;
  291. }
  292. /**
  293. * Implements hook_modules_enabled().
  294. *
  295. * This hook is called when ANY module is enabled. This allows us to update the
  296. * the search api "Default node index" when any Tripal module is enabled thus allowing us
  297. * to catch new node types right after they're created.
  298. */
  299. function tripal_core_modules_enabled($modules) {
  300. if (module_exists('search_api')) {
  301. $index_enabled = db_query('SELECT enabled FROM search_api_index WHERE machine_name=:name', array(':name' => 'default_node_index'))->fetchField();
  302. if ($index_enabled) {
  303. tripal_search_update_default_index();
  304. }
  305. }
  306. }
  307. /**
  308. * The Search API provides a default node index which has a number of
  309. * node-specific fields enabled by default. We want to ensure our
  310. * chado fields are also enabled by default thus making for easier
  311. * enabling of Tripal search.
  312. *
  313. * This function should be called whenever new nodes might have been
  314. * added to ensure that their fields are added as well.
  315. *
  316. * We should only modify the default node index if it has no database service yet.
  317. * That way we ensure we don't override user changes!
  318. */
  319. function tripal_search_update_default_index() {
  320. // First we need the index object for the "Default node index".
  321. $index_id = db_query('SELECT id FROM search_api_index WHERE machine_name=:name',
  322. array(':name' => 'default_node_index'))->fetchField();
  323. if (!$index_id) {
  324. // ERROR
  325. return FALSE;
  326. }
  327. $index = search_api_index_load($index_id);
  328. // Collect all the fields already added to the search index.
  329. $changes = array('options' => $index->options);
  330. // Now we only want to update the index if it's both enabled and has no server indicated.
  331. // That way we can be reasonably sure that it was been untouched by admin users.
  332. if ($index->enabled == FALSE AND $index->server == NULL) {
  333. // We need information about all the fields available to nodes before we can
  334. // go crazy enabling them... That information is stored as properties of nodes
  335. // so we'll grab that.
  336. $info = entity_get_property_info('node');
  337. // Now we want to loop through each node type and add all the properties for the
  338. // chado node types.
  339. // Assumption #1: We are assuming that all chado node types are prefixed 'chado_'.
  340. foreach ($info['bundles'] as $node_type => $details) {
  341. if (preg_match('/^chado_/', $node_type)) {
  342. // Now add each chado fields to the index but only if they are not already added.
  343. foreach ($details['properties'] as $field_name => $field_details) {
  344. if (!isset($changes['options']['fields'][$field_name])) {
  345. $changes['options']['fields'][$field_name]['type'] = ($field_details['type'] == 'varchar') ? 'text' : $field_details['type'];
  346. // Furthermore if this is a name then we want to add a boost to ensure it carries
  347. // more weight in the search results.
  348. if (preg_match('/name/',$field_name)) {
  349. $changes['options']['fields'][$field_name]['boost'] = '3.0';
  350. }
  351. }
  352. }
  353. }
  354. }
  355. // We also want to enable highlighting to ensure an excerpt is generated since this
  356. // will be used in the default search view distributed with Tripal.
  357. if (!isset($index->options['processors']['search_api_highlighting'])) {
  358. $changes['options']['processors']['search_api_highlighting'] = array(
  359. 'status' => 1,
  360. 'weight' => 35,
  361. 'settings' => array(
  362. 'prefix' => '<strong>',
  363. 'suffix' => '</strong>',
  364. 'excerpt' => 1,
  365. 'excerpt_length' => 256,
  366. 'exclude_fields' => array(),
  367. 'highlight' => 'always',
  368. ),
  369. );
  370. }
  371. else {
  372. $changes['options']['processors']['search_api_highlighting']['status'] = 1;
  373. $changes['options']['processors']['search_api_highlighting']['settings']['excerpt'] = 1;
  374. }
  375. // Finally we save all of our changes :-).
  376. search_api_index_edit($index_id, $changes);
  377. drupal_set_message('The Search API "Default Node Index" was updated.');
  378. }
  379. else {
  380. tripal_report_error(
  381. 'tripal_search',
  382. TRIPAL_NOTICE,
  383. 'The Search API "Default Node Index" was not updated with Tripal Fields. If you would like to enable more Tripal/Chado fields to be indexed, edit the Field Listing for the "Default Node Index" now.'
  384. );
  385. }
  386. }