tripal_core.search.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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' => $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. /**
  88. * Currently I can't get facets to work so there is no use indexing this 2X
  89. *
  90. $keytoken = '[BASE.' . $left_field . '>' . $table . '.' . $right_field . ']';
  91. $format = chado_node_get_readable_format($keytoken);
  92. // First, create the key version. This is best used for facets since it
  93. // won't/can't be tokenized along with the other fields. This will be shared
  94. // among node types to facillitate use as a facet.
  95. $info['node']['properties'][$table . '.' . $right_field .' key'] = array(
  96. 'label' => $key_label . ' (All Content Types)',
  97. 'description' => $field_details['description'],
  98. 'type' => 'text',
  99. // We include both the token for the current node type and the token for
  100. // the parent table. That way the organism node will appear in the results
  101. // for the organism key.
  102. 'schema field' => $format,
  103. // The following getter callback is a generic function that can retrieve
  104. // values for any chado foreign key.
  105. 'getter callback' => 'tripal_search_chado_token_across_nodetypes_getter_callback'
  106. );
  107. */
  108. $pretoken = '[' . $n['chado_node_api']['base_table'] . '.' . $left_field . '>' . $table . '.' . $right_field . ']';
  109. $format = chado_node_get_readable_format($pretoken);
  110. // Add a more readable version that will be tokenized so users can
  111. // search for fruitfly and get all features with that as an organism.
  112. $info['node']['bundles'][ $n['base'] ]['properties'][$machine_name .' expanded'] = array(
  113. 'label' => $label . ' (Expanded)',
  114. 'description' => $field_details['description'],
  115. 'type' => 'text',
  116. 'schema field' => $format,
  117. // The following getter callback is a generic function that can retrieve
  118. // values for any chado foreign key.
  119. 'getter callback' => 'tripal_search_chado_token_getter_callback'
  120. );
  121. }
  122. }
  123. }
  124. }
  125. // Provide our own hook for altering properties to make it easier for our users.
  126. drupal_alter('tripal_search_properties', $info);
  127. }
  128. /**
  129. * Allows tripal admin to alter entity property information after it has. This is currently
  130. * being used to indicate chado fields to be indexed for search.
  131. *
  132. * NOTE: If you simply need to add a field to be indexed, use hook_search_include_chado_fields()
  133. * which provides the much easier method of simply listing fields to include.
  134. *
  135. * This function is most useful if you want to change the way the value is retrieved
  136. * (done by changing the 'getter callback') or add your own custom computed field.
  137. */
  138. function hook_tripal_search_properties_alter(&$info) { }
  139. /**
  140. * Implements a getter callback for chado token formats.
  141. *
  142. * A chado token format is a string containing chado tokens.
  143. *
  144. * Chado tokens are expected to follow the format of tokens auto-generated using
  145. * chado_node_generate_tokens(). For example, [feature.uniquename] indicates you
  146. * should return the uniquename of a feature node and [feature.organism_id>organism.species]
  147. * indicates you should return the organism genus of the feature node.
  148. *
  149. * The chado token format must be stored in the 'schema field' when defining the property in
  150. * hook_entity_property_info() in order for this getter to work.
  151. *
  152. * @param $data
  153. * The entity object (in our case the node we need to retrieve feature properties for).
  154. * @param $options
  155. * @param $field_name
  156. * The machine name for the entity property.
  157. * @param $info
  158. * The full property definition from entity property info.
  159. *
  160. * @return
  161. * A string representing the "value" of the field.
  162. */
  163. function tripal_search_chado_token_getter_callback($data, $options, $field_name, $type, $info) {
  164. if (isset($data->nid)) {
  165. if (isset($info['schema field'])) {
  166. $format = $info['schema field'];
  167. // Determine our base table so we know if this is even the right node type.
  168. if (preg_match('/\[(\w+)\.(\w+)/',$format, $matches)) {
  169. $base_table = $matches[1];
  170. $field_name = $matches[2];
  171. // For some weird reason nodes of all types are trying to get a value for fields
  172. // that we defined as specific to a given node type (ie: bundle). As such we need
  173. // this check here to ensure this field is actually for this node type.
  174. if (!isset($data->{$base_table})) return NULL;
  175. $format = tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info);
  176. return $format;
  177. }
  178. else {
  179. // Not able to determine table?
  180. tripal_report_error(
  181. 'tripal_search',
  182. TRIPAL_ERROR,
  183. 'Unable to extract the base table from the format (:format) for :field because it didn\'t match the expected format: [tablename.field...',
  184. array(':field' => $field_name, ':format' => $format)
  185. );
  186. return NULL;
  187. }
  188. }
  189. else {
  190. tripal_report_error(
  191. 'tripal_search',
  192. TRIPAL_ERROR,
  193. 'Unable to get value for :field because the schema field was not set.',
  194. array(':field' => $field_name)
  195. );
  196. return NULL;
  197. }
  198. }
  199. }
  200. /**
  201. * Implements a getter callback for foreign keys collon between content types.
  202. *
  203. * @param $data
  204. * The entity object (in our case the node we need to retrieve feature properties for).
  205. * @param $options
  206. * @param $field_name
  207. * The machine name for the entity property.
  208. * @param $info
  209. * The full property definition from entity property info.
  210. *
  211. * @return
  212. * A string representing the "value" of the field.
  213. */
  214. function tripal_search_chado_token_across_nodetypes_getter_callback($data, $options, $field_name, $type, $info) {
  215. // First, make sure this is a chado node.
  216. // Assumption #1: All chado node types are prefixed with chado_
  217. if (isset($data->nid)) {
  218. if (preg_match('/^chado_(\w+)/',$data->type,$matches)) {
  219. if (isset($info['schema field'])) {
  220. // Assumption #2: The base table is the suffix of the node type.
  221. $base_table = $matches[1];
  222. // Substitute in the base table for "BASE" in the schema field.
  223. $format = str_replace('BASE', $base_table, $info['schema field']);
  224. // Replace all tokens for values and return the result.
  225. $format = tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info);
  226. return $format;
  227. }
  228. else {
  229. // Not able to determine table?
  230. tripal_report_error(
  231. 'tripal_search',
  232. TRIPAL_ERROR,
  233. 'Unable to extract the base table from the format (:format) for :field because it didn\'t match the expected format: [tablename.field...',
  234. array(':field' => $field_name, ':format' => $format)
  235. );
  236. }
  237. }
  238. else {
  239. tripal_report_error(
  240. 'tripal_search',
  241. TRIPAL_ERROR,
  242. 'Unable to get value for :field because the schema field was not set.',
  243. array(':field' => $field_name)
  244. );
  245. }
  246. }
  247. return NULL;
  248. }
  249. /**
  250. * Retrieve values for all tokens for an entity property getter function.
  251. */
  252. function tripal_core_get_token_value_for_property($base_table, $field_name, $format, $data, $info) {
  253. // Determine which tokens were used in the format string
  254. if (preg_match_all('/\[[^]]+\]/', $format, $used_tokens)) {
  255. $used_tokens = $used_tokens[0];
  256. // If there are no tokens then return the format as is...
  257. if (empty($used_tokens)) {
  258. tripal_report_error(
  259. 'tripal_search',
  260. TRIPAL_NOTICE,
  261. 'Returned static text for :field since there were no tokens in the supplied format: :format',
  262. array(':field' => $field_name, ':format' => $format)
  263. );
  264. return $format;
  265. }
  266. // Get the value of each token.
  267. $null_tokens = array();
  268. foreach ($used_tokens as $token) {
  269. $token_info = array(
  270. 'name' => $info['label'],
  271. 'table' => $base_table,
  272. 'field' => $field_name,
  273. 'token' => $token,
  274. 'description' => $info['description'],
  275. 'location' => chado_node_get_location_from_token($token),
  276. );
  277. $value = chado_get_token_value($token_info, $data, array('supress_errors' => TRUE));
  278. if (empty($value)) $null_tokens[] = $token;
  279. // And sub it in to the format.
  280. $format = str_replace($token, $value, $format);
  281. }
  282. // If none of the tokens had values then this node doesn't have this field.
  283. // As such we return null so the search api doesn't bother indexing an empty format.
  284. if (sizeof($used_tokens) == sizeof($null_tokens)) return NULL;
  285. }
  286. else {
  287. tripal_report_error(
  288. 'tripal_search',
  289. TRIPAL_NOTICE,
  290. 'Returned static text for :field since there were no tokens of a recognized format in the supplied format: :format',
  291. array(':field' => $field_name, ':format' => $format)
  292. );
  293. }
  294. return $format;
  295. }
  296. /**
  297. * Implements hook_modules_enabled().
  298. *
  299. * This hook is called when ANY module is enabled. This allows us to update the
  300. * the search api "Default node index" when any Tripal module is enabled thus allowing us
  301. * to catch new node types right after they're created.
  302. */
  303. function tripal_core_modules_enabled($modules) {
  304. tripal_search_update_default_index();
  305. }
  306. /**
  307. * The Search API provides a default node index which has a number of
  308. * node-specific fields enabled by default. We want to ensure our
  309. * chado fields are also enabled by default thus making for easier
  310. * enabling of Tripal search.
  311. *
  312. * This function should be called whenever new nodes might have been
  313. * added to ensure that their fields are added as well.
  314. *
  315. * We should only modify the default node index if it has no database service yet.
  316. * That way we ensure we don't override user changes!
  317. */
  318. function tripal_search_update_default_index() {
  319. // First we need the index object for the "Default node index".
  320. $index_id = db_query('SELECT id FROM search_api_index WHERE machine_name=:name',
  321. array(':name' => 'default_node_index'))->fetchField();
  322. if (!$index_id) {
  323. // ERROR
  324. return FALSE;
  325. }
  326. $index = search_api_index_load($index_id);
  327. // Collect all the fields already added to the search index.
  328. $changes = array('options' => $index->options);
  329. // Now we only want to update the index if it's both enabled and has no server indicated.
  330. // That way we can be reasonably sure that it was been untouched by admin users.
  331. if ($index->enabled == FALSE AND $index->server == NULL) {
  332. // We need information about all the fields available to nodes before we can
  333. // go crazy enabling them... That information is stored as properties of nodes
  334. // so we'll grab that.
  335. $info = entity_get_property_info('node');
  336. // Now we want to loop through each node type and add all the properties for the
  337. // chado node types.
  338. // Assumption #1: We are assuming that all chado node types are prefixed 'chado_'.
  339. foreach ($info['bundles'] as $node_type => $details) {
  340. if (preg_match('/^chado_/', $node_type)) {
  341. // Now add each chado fields to the index but only if they are not already added.
  342. foreach ($details['properties'] as $field_name => $field_details) {
  343. if (!isset($changes['options']['fields'][$field_name])) {
  344. $changes['options']['fields'][$field_name]['type'] = ($field_details['type'] == 'varchar') ? 'text' : $field_details['type'];
  345. // Furthermore if this is a name then we want to add a boost to ensure it carries
  346. // more weight in the search results.
  347. if (preg_match('/name/',$field_name)) {
  348. $changes['options']['fields'][$field_name]['boost'] = '3.0';
  349. }
  350. }
  351. }
  352. }
  353. }
  354. // We also want to enable highlighting to ensure an excerpt is generated since this
  355. // will be used in the default search view distributed with Tripal.
  356. if (!isset($index->options['processors']['search_api_highlighting'])) {
  357. $changes['options']['processors']['search_api_highlighting'] = array(
  358. 'status' => 1,
  359. 'weight' => 35,
  360. 'settings' => array(
  361. 'prefix' => '<strong>',
  362. 'suffix' => '</strong>',
  363. 'excerpt' => 1,
  364. 'excerpt_length' => 256,
  365. 'exclude_fields' => array(),
  366. 'highlight' => 'always',
  367. ),
  368. );
  369. }
  370. else {
  371. $changes['options']['processors']['search_api_highlighting']['status'] = 1;
  372. $changes['options']['processors']['search_api_highlighting']['settings']['excerpt'] = 1;
  373. }
  374. // Finally we save all of our changes :-).
  375. search_api_index_edit($index_id, $changes);
  376. drupal_set_message('The Search API "Default Node Index" was updated.');
  377. }
  378. else {
  379. tripal_report_error(
  380. 'tripal_search',
  381. TRIPAL_NOTICE,
  382. '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.'
  383. );
  384. }
  385. }