remote__data.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. /**
  3. * @class
  4. * Purpose:
  5. *
  6. * Data:
  7. * Assumptions:
  8. */
  9. class remote__data extends WebServicesField {
  10. // --------------------------------------------------------------------------
  11. // EDITABLE STATIC CONSTANTS
  12. //
  13. // The following constants SHOULD be set for each descendant class. They are
  14. // used by the static functions to provide information to Drupal about
  15. // the field and it's default widget and formatter.
  16. // --------------------------------------------------------------------------
  17. // The default label for this field.
  18. public static $default_label = 'Remote Tripal Site';
  19. // The default description for this field.
  20. public static $default_description = 'Allows for inclusion of remote data from another Tripal site.';
  21. // The default widget for this field.
  22. public static $default_widget = 'remote__data_widget';
  23. // The default formatter for this field.
  24. public static $default_formatter = 'remote__data_formatter';
  25. // The module that manages this field.
  26. public static $module = 'tripal_ws';
  27. // A list of global settings. These can be accessed within the
  28. // globalSettingsForm. When the globalSettingsForm is submitted then
  29. // Drupal will automatically change these settings for all fields.
  30. // Once instances exist for a field type then these settings cannot be
  31. // changed.
  32. public static $default_settings = array(
  33. 'storage' => 'field_tripal_ws_storage',
  34. // It is expected that all fields set a 'value' in the load() function.
  35. // In many cases, the value may be an associative array of key/value pairs.
  36. // In order for Tripal to provide context for all data, the keys should
  37. // be a controlled vocabulary term (e.g. rdfs:type). Keys in the load()
  38. // function that are supported by the query() function should be
  39. // listed here.
  40. 'searchable_keys' => array(),
  41. );
  42. // Provide a list of instance specific settings. These can be access within
  43. // the instanceSettingsForm. When the instanceSettingsForm is submitted
  44. // then Drupal with automatically change these settings for the instance.
  45. // It is recommended to put settings at the instance level whenever possible.
  46. // If you override this variable in a child class be sure to replicate the
  47. // term_name, term_vocab, term_accession and term_fixed keys as these are
  48. // required for all TripalFields.
  49. public static $default_instance_settings = array(
  50. // The short name for the vocabulary (e.g. schema, SO, GO, PATO, etc.).
  51. 'term_vocabulary' => 'schema',
  52. // The name of the term.
  53. 'term_name' => 'Thing',
  54. // The unique ID (i.e. accession) of the term.
  55. 'term_accession' => 'property',
  56. // Set to TRUE if the site admin is not allowed to change the term
  57. // type, otherwise the admin can change the term mapped to a field.
  58. 'term_fixed' => FALSE,
  59. // Indicates if this field should be automatically attached to display
  60. // or web services or if this field should be loaded separately. This
  61. // is convenient for speed. Fields that are slow should for loading
  62. // should have auto_attach set to FALSE so tha their values can be
  63. // attached asynchronously.
  64. 'auto_attach' => FALSE,
  65. // Settings to allow the site admin to set the remote data source info.
  66. 'data_info' => array(
  67. 'query' => '',
  68. 'remote_site' => '',
  69. 'description' => '',
  70. 'rd_field_name' => '',
  71. 'site_logo' => '',
  72. ),
  73. );
  74. // A boolean specifying that users should not be allowed to create
  75. // fields and instances of this field type through the UI. Such
  76. // fields can only be created programmatically with field_create_field()
  77. // and field_create_instance().
  78. public static $no_ui = FALSE;
  79. // A boolean specifying that the field will not contain any data. This
  80. // should exclude the field from web services or downloads. An example
  81. // could be a quick search field that appears on the page that redirects
  82. // the user but otherwise provides no data.
  83. public static $no_data = FALSE;
  84. // Holds an object describing the remote site that tihs field connects to.
  85. private $remote_site = NULL;
  86. // Set to TRUE if this field is being loaded via web services. WE don't
  87. // want remote fields loaded when a web-service call is made.
  88. private $loaded_via_ws = FALSE;
  89. public function __construct($field, $instance) {
  90. parent::__construct($field, $instance);
  91. // This field should not do anything if it is loaded via web-services.
  92. // We don't want remote content to be available in web services. There
  93. // is an if statement to not show this field in the web services but the
  94. // entity_load function doesn't know this field shouldn't be loaded so
  95. // we need to short-circuit that.
  96. $_SERVER['REQUEST_URI'];
  97. if (preg_match('/^web-services/', $_SERVER['REQUEST_URI'])) {
  98. $this->loaded_via_ws = TRUE;
  99. return;
  100. }
  101. // Get the site url from the tripal_sites table.
  102. if (array_key_exists('data_info', $instance['settings'])) {
  103. $site_id_ws = $instance['settings']['data_info']['remote_site'];
  104. if ($site_id_ws) {
  105. $this->remote_site = db_select('tripal_sites', 'ts')
  106. ->fields('ts')
  107. ->condition('ts.id', $site_id_ws)
  108. ->execute()
  109. ->fetchObject();
  110. }
  111. }
  112. }
  113. /**
  114. * @see WebServicesField::load()
  115. */
  116. public function load($entity) {
  117. $field_name = $this->field['field_name'];
  118. $field_type = $this->field['type'];
  119. // Set some defaults for the empty record.
  120. $entity->{$field_name}['und'][0] = array(
  121. 'value' => array(),
  122. 'remote_entity' => array(),
  123. );
  124. // If this field is being loaded via web services then just return.
  125. if ($this->loaded_via_ws == TRUE) {
  126. return;
  127. }
  128. // Get the query set by the admin for this field and replace any tokesn
  129. $query_str = $this->instance['settings']['data_info']['query'];
  130. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  131. $query_str = tripal_replace_entity_tokens($query_str, $entity, $bundle);
  132. // Make the request.
  133. $data = $this->makeRemoteRequest($query_str);
  134. if(!$data){
  135. return;
  136. }
  137. $total_items = $data['totalItems'];
  138. // Iterate through the members returned and save those for the field.
  139. for ($i = 0; $i < count($data['members']); $i++) {
  140. $member = $data['members'][$i];
  141. // Get the cotent type and remote entity id
  142. $content_type = $member['@type'];
  143. $remote_entity_id = $member['@id'];
  144. $remote_entity_id = preg_replace('/^.*\/(\d+)/', '$1', $remote_entity_id);
  145. // Save the member information for use later.
  146. $entity->{$field_name}['und'][$i]['remote_entity'] = $member;
  147. // Separate the query_field if it has subfields.
  148. $rd_field_name = $this->instance['settings']['data_info']['rd_field_name'];
  149. $subfields = explode(',', $rd_field_name);
  150. $query_field = $subfields[0];
  151. // Next get the the details about this member.
  152. $query_field_url = $content_type . '/' . $remote_entity_id . '/' . $query_field;
  153. $field_data = $this->makeRemoteRequest($query_field_url);
  154. if(!$field_data){
  155. // If we encounter any type of error, we'll reset the field and return.
  156. $entity->{$field_name}['und'] = array();
  157. $entity->{$field_name}['und'][0] = array(
  158. 'value' => array(),
  159. 'remote_entity' => array(),
  160. );
  161. return;
  162. }
  163. // Set the field data as the value.
  164. $field_data_type = $field_data['@type'];
  165. $entity->{$field_name}['und'][$i]['value'] = $field_data;
  166. }
  167. }
  168. /**
  169. * Makes a request to a remote Tripal web services site.
  170. *
  171. * @param $query
  172. * The query string. This string is added to the URL for the remote
  173. * website.
  174. */
  175. private function makeRemoteRequest($query) {
  176. $ctype = $query;
  177. $qdata = '';
  178. if (preg_match('/\?/', $query)) {
  179. list($ctype, $qdata) = explode('?', $query);
  180. }
  181. $data = tripal_get_remote_content($this->remote_site->id, $query);
  182. return $data;
  183. }
  184. /**
  185. *
  186. * @see TripalField::settingsForm()
  187. */
  188. public function instanceSettingsForm() {
  189. $element = parent::instanceSettingsForm();
  190. // Get the setting for the option for how this widget.
  191. $instance = $this->instance;
  192. $settings = '';
  193. $site_list = '';
  194. $tokens = array();
  195. // Get the form info from the bundle about to be saved.
  196. $bundle = tripal_load_bundle_entity(array('name' => $instance['bundle']));
  197. // Retrieve all available tokens.
  198. $tokens = tripal_get_entity_tokens($bundle);
  199. $element['data_info'] = array(
  200. '#type' => 'fieldset',
  201. '#title' => 'Remote Data Settings',
  202. '#description' => 'These settings allow you to provide a Tripal web
  203. services query to identify content on another Tripal site and display
  204. that here within this field. You must specify the query to execute and
  205. the field to display.',
  206. '#collapsible' => TRUE,
  207. '#collapsed' => FALSE,
  208. '#prefix' => "<div id='set_titles-fieldset'>",
  209. '#suffix' => '</div>',
  210. );
  211. // Get the site info from the tripal_sites table.
  212. $sites = db_select('tripal_sites', 's')
  213. ->fields('s')
  214. ->execute()->fetchAll();
  215. foreach ($sites as $site) {
  216. $rows[$site->id] =$site->name;
  217. }
  218. $element['data_info']['remote_site'] = array(
  219. '#type' => 'select',
  220. '#title' => t('Remote Tripal Site'),
  221. '#options' => $rows,
  222. '#default_value' => $this->instance['settings']['data_info']['remote_site'],
  223. );
  224. $element['data_info']['query'] = array(
  225. '#type' => 'textarea',
  226. '#title' => 'Query to Execute',
  227. '#description' => 'Build the query string that should be appended after the url. The tokens
  228. listed below may be used in your query build.',
  229. '#default_value' => $this->instance['settings']['data_info']['query'],
  230. '#rows' => 5,
  231. '#required' => TRUE
  232. );
  233. $element['data_info']['rd_field_name'] = array(
  234. '#type' => 'textfield',
  235. '#title' => 'Field to Display',
  236. '#description' => 'The results returned by the query should match
  237. entities (or records) from the selected remote site. That entity
  238. will have multiple fields. Only one remote field can be shown by
  239. this field. Please enter the name of the field you would like
  240. to display. Some fields have "subfields". You can display a subfield
  241. rather than the entire field by entering a comma-separated sequence
  242. of subfields. For example, for relationships, you may only want to
  243. show the "clause", therefore, the entry here would be: realtionship,clause.',
  244. '#default_value' => $this->instance['settings']['data_info']['rd_field_name'],
  245. '#required' => TRUE
  246. );
  247. $element['data_info']['token_display']['tokens'] = array(
  248. '#type' => 'hidden',
  249. '#value' => serialize($tokens)
  250. );
  251. $element['data_info']['token_display'] = array(
  252. '#type' => 'fieldset',
  253. '#title' => 'Available Tokens',
  254. '#description' => 'Copy the token and paste it into the "Query" text field above.',
  255. '#collapsible' => TRUE,
  256. '#collapsed' => TRUE
  257. );
  258. $element['data_info']['token_display']['content'] = array(
  259. '#type' => 'item',
  260. '#markup' => theme_token_list($tokens),
  261. );
  262. $element['data_info']['description'] = array(
  263. '#type' => 'textarea',
  264. '#title' => 'Description',
  265. '#description' => 'Describe the data being pulled in.',
  266. '#default_value' => $this->instance['settings']['data_info']['description'],
  267. '#rows' => 1
  268. );
  269. $fid = $this->instance['settings']['data_info']['site_logo'] ? $this->instance['settings']['data_info']['site_logo'] : NULL;
  270. $file = NULL;
  271. if ($fid) {
  272. $file = file_load($fid);
  273. }
  274. $element['data_info']['site_logo'] = array(
  275. '#title' => 'Remote Site Logo',
  276. '#description' => t('When data is taken from a remote site and shown to the user,
  277. the site from which the data was retrieved is indicated. If you would like to
  278. include the logo for the remote site, please upload an image here.'),
  279. '#type' => 'managed_file',
  280. '#default_value' => $file ? $file->fid : NULL,
  281. '#theme' => 'image_widget',
  282. '#attached' => array(
  283. 'css' => array(
  284. 'image-preview' => drupal_get_path('module', 'image') . '/image.css',
  285. ),
  286. ),
  287. 'preview' => array(
  288. '#markup' => theme('image_style', array('style_name' => 'thumbnail', 'path' => $file ? $file->uri : '')),
  289. ),
  290. );
  291. return $element;
  292. }
  293. /**
  294. *
  295. * @param unknown $form
  296. * @param unknown $form_state
  297. */
  298. public function instanceSettingsFormValidate($form, &$form_state) {
  299. $site_logo = $form_state['values']['instance']['settings']['data_info']['site_logo'];
  300. // If we have a site logo then add usage information.
  301. if ($site_logo) {
  302. $file = file_load($site_logo);
  303. $file_usage = file_usage_list($file);
  304. if (!array_key_exists('tripal_ws', $file_usage)) {
  305. file_usage_add($file, 'tripal_ws', 'site-logo', 1);
  306. }
  307. }
  308. }
  309. }