remote__data.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. ),
  72. );
  73. // A boolean specifying that users should not be allowed to create
  74. // fields and instances of this field type through the UI. Such
  75. // fields can only be created programmatically with field_create_field()
  76. // and field_create_instance().
  77. public static $no_ui = FALSE;
  78. // A boolean specifying that the field will not contain any data. This
  79. // should exclude the field from web services or downloads. An example
  80. // could be a quick search field that appears on the page that redirects
  81. // the user but otherwise provides no data.
  82. public static $no_data = FALSE;
  83. // Holds an object describing the remote site that tihs field connects to.
  84. private $remote_site = NULL;
  85. // Set to TRUE if this field is being loaded via web services. WE don't
  86. // want remote fields loaded when a web-service call is made.
  87. private $loaded_via_ws = FALSE;
  88. public function __construct($field, $instance) {
  89. parent::__construct($field, $instance);
  90. // This field should not do anything if it is loaded via web-services.
  91. // We don't want remote content to be available in web services. There
  92. // is an if statement to not show this field in the web services but the
  93. // entity_load function doesn't know this field shouldn't be loaded so
  94. // we need to short-circuit that.
  95. if (preg_match('/^web-services/', $_SERVER['REQUEST_URI'])) {
  96. dpm('hi');
  97. $this->loaded_via_ws = TRUE;
  98. return;
  99. }
  100. // Get the site url from the tripal_sites table.
  101. $site_id_ws = $this->instance['settings']['data_info']['remote_site'];
  102. $this->remote_site = db_select('tripal_sites', 'ts')
  103. ->fields('ts')
  104. ->condition('ts.id', $site_id_ws)
  105. ->execute()
  106. ->fetchObject();
  107. }
  108. /**
  109. * @see WebServicesField::load()
  110. */
  111. public function load($entity) {
  112. $field_name = $this->field['field_name'];
  113. $field_type = $this->field['type'];
  114. // Set some defaults for the empty record.
  115. $entity->{$field_name}['und'][0] = array(
  116. 'value' => array(),
  117. 'remote_entity' => array(),
  118. );
  119. // If this field is being loaded via web services then just return.
  120. dpm($this->loaded_via_ws);
  121. return;
  122. if ($this->loaded_via_ws) {
  123. return;
  124. }
  125. // Get the query set by the admin for this field and replace any tokesn
  126. $query_str = $this->instance['settings']['data_info']['query'];
  127. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  128. $query_str = tripal_replace_entity_tokens($query_str, $entity, $bundle);
  129. // Make the request.
  130. $data = $this->makeRemoteRequest($query_str);
  131. if(!$data){
  132. return;
  133. }
  134. $total_items = $data['totalItems'];
  135. // Iterate through the members returned and save those for the field.
  136. for ($i = 0; $i < count($data['members']); $i++) {
  137. $member = $data['members'][$i];
  138. // Get the cotent type and remote entity id
  139. $content_type = $member['@type'];
  140. $remote_entity_id = $member['@id'];
  141. $remote_entity_id = preg_replace('/^.*\/(\d+)/', '$1', $remote_entity_id);
  142. // Save the member information for use later.
  143. $entity->{$field_name}['und'][$i]['remote_entity'] = $member;
  144. // Next get the the details about this member.
  145. $query_field = 'relationship';
  146. $query_field_url = $content_type . '/' . $remote_entity_id . '/' . $query_field;
  147. $field_data = $this->makeRemoteRequest($query_field_url);
  148. if(!$field_data){
  149. // If we encounter any type of error, we'll reset the field and return.
  150. $entity->{$field_name}['und'] = array();
  151. $entity->{$field_name}['und'][0] = array(
  152. 'value' => array(),
  153. );
  154. return;
  155. }
  156. // Set the field data as the value.
  157. $field_data_type = $field_data['@type'];
  158. $entity->{$field_name}['und'][$i]['value'] = $field_data;
  159. }
  160. }
  161. /**
  162. * Makes a request to a remote Tripal web services site.
  163. *
  164. * @param $query
  165. * The query string. This string is added to the URL for the remote
  166. * website.
  167. */
  168. private function makeRemoteRequest($query) {
  169. // Build the URL to the remote web services.
  170. $ws_url = $this->remote_site->url;
  171. $ws_url = trim($ws_url, '/');
  172. $ws_url .= '/web-services/content/v0.1';
  173. // Build the Query and make and substitions needed.
  174. $query_url = $ws_url . '/' . $query;
  175. $options = array('timeout' => 360);
  176. $data = drupal_http_request($query_url, $options);
  177. if (!$data) {
  178. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  179. t('Could not connect to the remote web service.'));
  180. return FALSE;
  181. }
  182. // If the data object has an error then this is some sort of
  183. // connection error (not a Tripal web servcies error).
  184. if (property_exists($data, 'error')) {
  185. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  186. 'Web Services error on remote site: %error.',
  187. array('%error' => $data->error));
  188. return FALSE;
  189. }
  190. // We got a response, so convert it to a PHP array.
  191. $data = drupal_json_decode($data->data);
  192. // Check if there was a Tripal Web Services error.
  193. if (array_key_exists('error', $data)) {
  194. $error = '</pre>' . print_r($data['error'], TRUE) . '</pre>';
  195. tripal_report_error('tripal_ws', TRIPAL_ERROR,
  196. 'Web Services error on remote site: %error.',
  197. array('%error' => $error));
  198. return FALSE;
  199. }
  200. return $data;
  201. }
  202. /**
  203. *
  204. * @see TripalField::settingsForm()
  205. */
  206. public function instanceSettingsForm() {
  207. $element = parent::instanceSettingsForm();
  208. // Get the setting for the option for how this widget.
  209. $instance = $this->instance;
  210. $settings = '';
  211. $site_list = '';
  212. $tokens = array();
  213. // Get the form info from the bundle about to be saved.
  214. $bundle_info = tripal_load_bundle_entity(array($instance['bundle']));
  215. // Retrieve all available tokens.
  216. $tokens = tripal_get_entity_tokens($bundle_info);
  217. $element['data_info'] = array(
  218. '#type' => 'fieldset',
  219. '#title' => 'Remote Data Settings',
  220. '#description' => 'Provide the site name, query and description for the remote data source.',
  221. '#collapsible' => TRUE,
  222. '#collapsed' => FALSE,
  223. '#prefix' => "<div id='set_titles-fieldset'>",
  224. '#suffix' => '</div>',
  225. );
  226. // Get the site info from the tripal_sites table.
  227. $sites = db_select('tripal_sites', 's')
  228. ->fields('s')
  229. ->execute()->fetchAll();
  230. foreach ($sites as $site) {
  231. $rows[$site->id] =$site->name;
  232. }
  233. $element['data_info']['remote_site'] = array(
  234. '#type' => 'select',
  235. '#title' => t('Site'),
  236. '#options' => $rows,
  237. '#default_value' => $this->instance['settings']['data_info']['remote_site'],
  238. );
  239. $element['data_info']['query'] = array(
  240. '#type' => 'textarea',
  241. '#title' => 'Query',
  242. '#description' => 'Build the query string that should be appended after the url. The tokens
  243. listed below may be used in your query build.',
  244. '#default_value' => $this->instance['settings']['data_info']['query'],
  245. '#rows' => 5,
  246. '#required' => TRUE
  247. );
  248. $element['data_info']['rd_field_name'] = array(
  249. '#type' => 'textfield',
  250. '#title' => 'Field',
  251. '#description' => 'Name of the field you would like to display.',
  252. '#default_value' => $this->instance['settings']['data_info']['rd_field_name'],
  253. '#required' => TRUE
  254. );
  255. $element['data_info']['token_display']['tokens'] = array(
  256. '#type' => 'hidden',
  257. '#value' => serialize($tokens)
  258. );
  259. $element['data_info']['token_display'] = array(
  260. '#type' => 'fieldset',
  261. '#title' => 'Available Tokens',
  262. '#description' => 'Copy the token and paste it into the "Query" text field above.',
  263. '#collapsible' => TRUE,
  264. '#collapsed' => TRUE
  265. );
  266. $element['data_info']['token_display']['content'] = array(
  267. '#type' => 'item',
  268. '#markup' => theme_token_list($tokens),
  269. );
  270. $element['data_info']['description'] = array(
  271. '#type' => 'textarea',
  272. '#title' => 'Description',
  273. '#description' => 'Describe the data being pulled in.',
  274. '#default_value' => $this->instance['settings']['data_info']['description'],
  275. '#rows' => 1
  276. );
  277. /*$element['test_button']['data'] = array(
  278. '#prefix' => '<div class="returned-data">',
  279. '#suffix' => '</div>',
  280. '#type' => 'container',
  281. //…
  282. );
  283. $element['test_button'] = array(
  284. '#type' => 'button',
  285. '#value' => t('Test Query'),
  286. '#ajax' => array(
  287. 'wrapper' => 'data-id',
  288. 'callback' => 'tripal_ws_url_query_test',
  289. ),
  290. //…
  291. );*/
  292. return $element;
  293. }
  294. /**
  295. *
  296. * @param unknown $form
  297. * @param unknown $form_state
  298. */
  299. public function instanceSettingsFormValidate($form, &$form_state) {
  300. }
  301. }