tripal_views.api.inc

  1. 2.x tripal_views/api/tripal_views.api.inc
  2. 1.x tripal_views/api/tripal_views.api.inc

API functions for Tripal Views Integration

File

tripal_views/api/tripal_views.api.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API functions for Tripal Views Integration
  5. */
  6. /**
  7. * @defgroup tripal_views_api Tripal Views Module API
  8. * @ingroup tripal_api
  9. * @{
  10. * Provides functions to help extension modules add their own tripal views integrations
  11. * as well as functions for managing default views.
  12. *
  13. * Managing Default Views:
  14. *
  15. * When you create administrative default views (or really any default view) you really
  16. * have no way to ensure that the site administrator keeps these views enabled. In some
  17. * cases this is a good thing and provides the site administrator the ability to disable
  18. * views that don't apply to their particular installation or to replace your default view
  19. * with a custom view of their own. But in other cases, particularily for administration
  20. * views, you want to gaurd against accidental disabling of your views.
  21. *
  22. * One way to do this is to add a landing page using a heook_menu() definition to a custom
  23. * callback returning HTML. You can use this page to render the view if it is enabled but
  24. * provide logic to display a message if the view is disabled. Furthermore, it's often
  25. * helpful to provide a link allowing site administrators to enable the view from your
  26. * page rather than expecting them to go to the views administration UI. This is done for
  27. * all the administration views provided by Tripal. The following is an example of how to
  28. * achomplish this functionality for your own module:
  29. * @code
  30. function mymodule_menu() {
  31. $items = array();
  32. // Create the landing page
  33. $items['admin/tripal/<PATH-TO-YOUR-LANDING-PAGE>'] = array(
  34. 'title' => 'MyModule Administration',
  35. 'description' => 'Administration of my module.',
  36. 'page callback' => 'mymodule_admin_landing_page',
  37. 'access arguments' => array('<YOUR-PERMISSION-KEY>'),
  38. 'type' => MENU_NORMAL_ITEM,
  39. );
  40. // Create one of these for each of your default views
  41. $items['admin/tripal/<PATH-TO-YOUR-ADMIN-SECTION>/views/<VIEW-MACHINE-NAME>/enable'] = array(
  42. 'title' => 'Enable <VIEW-HUMAN-READABLE-NAME>',
  43. 'page callback' => 'tripal_enable_view',
  44. 'page arguments' => array('<VIEW-MACHINE-NAME>', '<PATH-TO-REDIRECT-TO-AFTERWARDS>'),
  45. 'access arguments' => array('<YOUR-PERMISSION-KEY>'),
  46. 'type' => MENU_CALLBACK,
  47. );
  48. return $items;
  49. }
  50. function mymodule_admin_landing_page() {
  51. // Get the View Embed Code
  52. // This function will return FALSE if your view is not enabled
  53. $view_code = views_embed_view('<VIEW-MACHINE-NAME>', '<DISPLAY-MACHINE-NAME');
  54. // If your view is enabled then embed it in this page by returning the embed code
  55. if (isset($view_code)) {
  56. $output .= $view_code;
  57. }
  58. else {
  59. // Provide the landing page with links to the menu item created in hook_menu to
  60. // to enable your view
  61. $output .= '<p>The My Module module uses primarily views to provide an '
  62. . 'administrative interface. Currently one or more views needed for this '
  63. . 'administrative interface are disabled. <strong>Click each of the following links to '
  64. . 'enable the pertinent views</strong>:</p>';
  65. $output .= '<ul>';
  66. // NOTE: <URL-FROM-MENU-TO-ENABLE-VIEW> is
  67. // admin/tripal/<PATH-TO-YOUR-ADMIN-SECTION>/views/<VIEW-MACHINE-NAME>/enable
  68. // from above hook_menu().
  69. $output .= '<li>' . l('<VIEW-HUMAN-RADABLE-NAME>', '<URL-FROM-MENU-TO-ENABLE-VIEW>') . '</li>';
  70. $output .= '</ul>';
  71. }
  72. return $output;
  73. }
  74. * @endcode
  75. *
  76. * Adding your own Tripal Views Integrations:
  77. *
  78. * One of the main ways the Tripal View API is likely to be used is if your module needs
  79. * to create it's own tripal views integration. You might need to do this for any number of
  80. * reasons but the following examples are thought to be the most common:
  81. *
  82. * 1) Your module wants to add handlers with better functionality to fields it has more
  83. * knowledge of than the general integration for all tables
  84. * @code
  85. mymodule_views_data() {
  86. // First check that your integration has not already been added
  87. // When selecting a priority, do not choose -10 or -9 and make sure it is below 0
  88. // so that individual sites still have the ability to override it, if needed
  89. $table_name = 'my_chado_table';
  90. $priority = -5;
  91. if (!tripal_is_table_integrated($table_name, $priority)) {
  92. // If you really only need to tweak an existing integration you can clone it
  93. // If you want to clone the integration that is currently taking priority
  94. // then use tripal_get_lightest_views_integration_priority() as below
  95. $lightest_priority = tripal_get_lightest_views_integration_priority($table_name);
  96. $setup_id = tripal_clone_views_integration($table_name, $priority, $lightest_priority);
  97. // And then make a few changes
  98. // First get the definition array created via the clone above
  99. $defn_array = tripal_export_views_integration($setup_id);
  100. // Then make some changes to the array here
  101. // And finally save the changes to the integration
  102. tripal_update_views_integration($setup_id, $defn_array);
  103. }
  104. }
  105. * @endcode
  106. * 2) Your module creates a chado table that is not already integrated.
  107. * @code
  108. mymodule_views_data() {
  109. // First check that your integration has not already been added
  110. // When selecting a priority, do not choose 10 or 9 and make sure it is below 0
  111. // so that individual sites still have the ability to override it, if needed
  112. $table_name = 'my_chado_table';
  113. $priority = 5;
  114. if (!tripal_is_table_integrated($table_name, $priority)) {
  115. // Describe your table using a large array as specified by tripal_add_views_integration().
  116. $defn_array = array(
  117. 'table' => $table_name, //tablename or materialized view name
  118. 'name' => 'My Chado Table', // Human readable name
  119. 'type' => 'chado', //either chado or mview depending on tablename
  120. 'description' => 'Create a listing from my chado table.', //description seen when creating a view of this type
  121. 'priority' => $priority, //For Base tripal modules: 10; custom modules: 9 to 0;
  122. 'base_table' => TRUE //either TRUE or FALSE depending on whether the current table should show up in the add view list
  123. 'fields' => array(
  124. 'feature_id' => array(
  125. 'name' => 'feature_id', //field name in database
  126. 'title' => 'Feature ID', //human-readable name -seen in Views UI
  127. 'description' => 'This is the unique identifier for features', //help/description seen in Views UI
  128. 'type' => 'int', // the type of field
  129. 'handlers' => array( //possible keys are field, filter, sort, argument, relationship
  130. 'field' => array(
  131. 'name' => 'chado_views_handler_numeric' //name of handler
  132. ),
  133. 'filter' => array( ... ),
  134. ...
  135. ),
  136. // Describe any joins involving this field.
  137. // Note: you can include both foreign keys (feature.type_id => cvterm.cvterm_id)
  138. // and referring tables (ie: feature.feature_id <= feature_relationship.subject_id)
  139. 'joins' => array(
  140. 'feature_relationship' => array( //table to join to.
  141. 'subject_id' => array( //field in above table (feature_relationship)
  142. 'table' => 'featureprop', //table to join to
  143. 'field' => 'feature_id', //field in above table (feature_relationship)
  144. 'handler' => 'views_join', //handler to use for joining
  145. 'relationship_handler' => 'views_handler_relationship', //handler to use when a relationship is added.
  146. 'relationship_only' => FALSE, //whether to join automatically (FALSE) or not (TRUE)
  147. ),
  148. ...
  149. ),
  150. ...
  151. ),
  152. )
  153. ),
  154. );
  155. // Actually create the entry
  156. tripal_add_views_integration($defn_array);
  157. }
  158. }
  159. * @endcode
  160. * @}
  161. */
  162. /**
  163. * Programatically enable view
  164. *
  165. * This should be used in a hook_menu definition as the callback to provide a link
  166. * to enable the view (first example). It can also be called directly if needed (second example).
  167. * @code
  168. // Create a URL that when the user navigates there, a given view will be enabled.
  169. // You will still need to provide a link to this menu item somewhere appropriate (ie: an admin landing page).
  170. function mymodule_menu() {
  171. $items = array();
  172. // Create one of these for each of your default views
  173. $items['admin/tripal/<PATH-TO-YOUR-ADMIN-SECTION>/views/<VIEW-MACHINE-NAME>/enable'] = array(
  174. 'title' => 'Enable <VIEW-HUMAN-READABLE-NAME>',
  175. 'page callback' => 'tripal_enable_view',
  176. 'page arguments' => array('<VIEW-MACHINE-NAME>', '<PATH-TO-REDIRECT-TO-AFTERWARDS>'),
  177. 'access arguments' => array('<YOUR-PERMISSION-KEY>'),
  178. 'type' => MENU_CALLBACK,
  179. );
  180. return $items;
  181. }
  182. // Call this function directly to disable a view
  183. // The example shows enabling your own default view when your module is enabled.
  184. // This might be useful if you disable your view when your module is disabled.
  185. function mymodule_enable() {
  186. $view_name = '<VIEW-MACHINE-NAME>';
  187. tripal_enable_view($view_name);
  188. }
  189. * @endcode
  190. *
  191. * @param $view_name
  192. * The machine-name of the view to be enabled
  193. * @param $redirect_link
  194. * The path to redirect to. FALSE if no redirect needed
  195. *
  196. * @ingroup tripal_views_api
  197. */
  198. function tripal_enable_view($view_name, $redirect_link = FALSE) {
  199. $status = variable_get('views_defaults', array());
  200. if (isset($status[$view_name])) {
  201. $status[$view_name] = FALSE;
  202. variable_set('views_defaults', $status);
  203. drupal_set_message("Successfully Enabled $view_name");
  204. }
  205. else {
  206. drupal_set_message("Unable to find a view by the name of '$view_name'. Unable to enable this view.",'error');
  207. }
  208. if ($redirect_link) {
  209. drupal_goto($redirect_link);
  210. }
  211. }
  212. /**
  213. * Programatically disable view.
  214. *
  215. * This should be used in a hook_menu definition as the callback to provide a link
  216. * to disable the view (first example). It can also be called directly if needed (second example).
  217. * @code
  218. // Create a URL that when the user navigates there, a given view will be disabled.
  219. // You will still need to provide a link to this menu item somewhere appropriate.
  220. function mymodule_menu() {
  221. $items = array();
  222. // Create one of these for each of your default views
  223. $items['admin/tripal/<PATH-TO-YOUR-ADMIN-SECTION>/views/<VIEW-MACHINE-NAME>/disable'] = array(
  224. 'title' => 'Disable <VIEW-HUMAN-READABLE-NAME>',
  225. 'page callback' => 'tripal_disable_view',
  226. 'page arguments' => array('<VIEW-MACHINE-NAME>', '<PATH-TO-REDIRECT-TO-AFTERWARDS>'),
  227. 'access arguments' => array('<YOUR-PERMISSION-KEY>'),
  228. 'type' => MENU_CALLBACK,
  229. );
  230. return $items;
  231. }
  232. // Call this function directly to disable a view
  233. // The example shows disabling your own default view when your module is uninstalled
  234. function mymodule_uninstall() {
  235. $view_name = '<VIEW-MACHINE-NAME>';
  236. tripal_disable_view($view_name);
  237. }
  238. * @endcode
  239. *
  240. * @param $view_name
  241. * The machine-name of the view to be enabled
  242. * @param $redirect_link
  243. * The path to redirect to. FALSE if no redirect needed
  244. *
  245. * @ingroup tripal_views_api
  246. */
  247. function tripal_disable_view($view_name, $redirect_link = FALSE) {
  248. $status = variable_get('views_defaults', array());
  249. if (isset($status[$view_name])) {
  250. $status[$view_name] = TRUE;
  251. variable_set('views_defaults', $status);
  252. drupal_set_message("Disabled $view_name");
  253. }
  254. else {
  255. drupal_set_message("Unable to find a view by the name of '$view_name'. Unable to disable this view.",'error');
  256. }
  257. if ($redirect_link) {
  258. drupal_goto($redirect_link);
  259. }
  260. }
  261. /**
  262. * Remove any drupal fields from a chado-based default view definition if chado is external.
  263. * This ensures compatibility with an external chado database.
  264. *
  265. * You should be calling this function in your hook_views_default_views(). This function
  266. * will only remove drupal tables if chado is external; thus you do not need to worry about
  267. * checking yourself. For example, the following is a good hook_views_default_views():
  268. * @code
  269. function mymodule_views_default_views() {
  270. $views = array();
  271. // NOTE: <VIEW-TYPE> describes the type of view:
  272. // - 'admin' for views used for administration of your module
  273. // - 'search' for views used to search data
  274. // - 'list' for views used primarily as data listings
  275. // <VIEW-HUMAN-READABLE-NAME>
  276. $view = mymodule_defaultview_<VIEW-TYPE>_<VIEW-MACHINE-NAME>();
  277. $view = tripal_make_view_compatible_with_external($view);
  278. $views[$view->name] = $view;
  279. // <VIEW-HUMAN-READABLE-NAME>
  280. $view = mymodule_defaultview_<VIEW-TYPE>_<VIEW-MACHINE-NAME>();
  281. $view = tripal_make_view_compatible_with_external($view);
  282. $views[$view->name] = $view;
  283. return $views;
  284. }
  285. function mymodule_defaultview_<VIEW-TYPE>_<VIEW-MACHINE-NAME>() {
  286. // PASTE VIEWS EXPORT CODE HERE
  287. return $view;
  288. }
  289. function mymodule_defaultview_<VIEW-TYPE>_<VIEW-MACHINE-NAME>() {
  290. // PASTE VIEWS EXPORT CODE HERE
  291. return $view;
  292. }
  293. * @endcode
  294. * Notice that the actual views export code is in a separate function. This makes your
  295. * hook_views_default_views() more readable.
  296. *
  297. * NOTE: Currently assumes all tables not in the tripal views integration tables are Drupal tables.
  298. *
  299. * @param $view
  300. * The default view definition object
  301. * @return
  302. * The default view with all relationships, fields, filters, sorts, arguments for
  303. * Drupal tables removed.
  304. */
  305. function tripal_make_view_compatible_with_external($view) {
  306. $remove_table = array();
  307. // First check that the base table for the view is a chado table
  308. // If it's not then don't do any filtering
  309. $setup_id = tripal_is_table_integrated($view->base_table);
  310. if (!$setup_id) {
  311. return $view;
  312. }
  313. // IF chado is external then remove all config relating to drupal tables
  314. if (!chado_is_local()) {
  315. // Iterate through all displays
  316. foreach ($view->display as $display_name => $display) {
  317. $display_options = $display->handler->display->display_options;
  318. $sections = array('fields', 'filters', 'sorts', 'relationships');
  319. foreach ($sections as $section) {
  320. $display_options[$section] = (isset($display_options[$section])) ? $display_options[$section] : array();
  321. foreach ($display_options[$section] as $key => $defn) {
  322. // If the table has not already been encountered; check if it's in tripal_views
  323. if (!isset($remove_table[ $defn['table'] ])) {
  324. // If the table is view then this is a general handler; thus keep
  325. if ($defn['table'] == 'views') {
  326. $remove_table[ $defn['table'] ] = FALSE;
  327. }
  328. // If this table is integrated then it is chado; thus keep
  329. $setup_id = tripal_is_table_integrated($defn['table']);
  330. if ($setup_id) {
  331. $remove_table[ $defn['table'] ] = FALSE;
  332. }
  333. else {
  334. $remove_table[ $defn['table'] ] = TRUE;
  335. }
  336. }
  337. // Based on the $remove_table array, unset this field if its from a drupal table
  338. if ($remove_table[ $defn['table'] ]) {
  339. unset($view->display[$display_name]->handler->display->display_options[$section][$key]);
  340. }
  341. }
  342. }
  343. }
  344. }
  345. return $view;
  346. }
  347. /**
  348. * Retrieve the priority of the lightest priority for a given table.
  349. *
  350. * NOTE: Uses lightest priority (drupal-style) where the range is from -10 to 10
  351. * and -10 is of highest priority.
  352. *
  353. * @param $table_name
  354. * The name of the table to retrieve the setup ID for. This can be either a materialized
  355. * view or a chado table
  356. *
  357. * @return
  358. * returns the lowest priority. If the table has not been integrated, a priority of 10
  359. * is returned.
  360. *
  361. * @ingroup tripal_views_api
  362. */
  363. function tripal_get_lightest_views_integration_priority($table_name) {
  364. // D7 TODO: Check DBTNG changes work
  365. $sql = "SELECT priority FROM {tripal_views} WHERE table_name=:table ORDER BY priority ASC";
  366. $setup = db_query($sql, array(':table' => $table_name));
  367. $setup = $setup->fetchObject();
  368. if ($setup) {
  369. return $setup->priority;
  370. }
  371. else {
  372. // default priority is 10
  373. return 10;
  374. }
  375. }
  376. /**
  377. * Retrieve the views integration setup_id with the lightest priority for a given table
  378. *
  379. * NOTE: Uses lightest priority (drupal-style) where the range is from -10 to 10
  380. * and -10 is of highest priority.
  381. *
  382. * @param $table_name
  383. * The name of the table to retrieve the setup ID for. This can be either a materialized
  384. * view or a chado table
  385. *
  386. * @return
  387. * On success, the setup_id to use for integration of this table; otherwise FALSE
  388. *
  389. * @ingroup tripal_views_api
  390. */
  391. function tripal_get_lightest_views_integration_setup($table_name) {
  392. // D7 TODO: Check DBTNG changes work
  393. $sql = "SELECT setup_id FROM {tripal_views} WHERE table_name=:table ORDER BY priority ASC";
  394. $setup = db_query($sql, array(':table' => $table_name));
  395. $setup = $setup->fetchObject();
  396. if ($setup) {
  397. return $setup->setup_id;
  398. }
  399. else {
  400. return FALSE;
  401. }
  402. }
  403. /**
  404. * Retrieve the views integration setup_id with the given priority/table combination.
  405. *
  406. * @param $table_name
  407. * The name of the table to retrieve the setup ID for. This can be either a materialized
  408. * view or a chado table
  409. * @param $priority
  410. * The priority of the integration to retrieve the setup_id for
  411. *
  412. * @return
  413. * On success, the setup_id to use for integration of this table; otherwise FALSE
  414. *
  415. * @ingroup tripal_views_api
  416. */
  417. function tripal_get_views_integration_setup_id($table_name, $priority) {
  418. // D7 TODO: Check DBTNG changes work
  419. $sql = "SELECT setup_id FROM {tripal_views} WHERE table_name=:table AND priority=:priority ORDER BY priority ASC";
  420. $setup = db_query($sql, array(':table' => $table_name, ':priority' => $priority));
  421. $setup = $setup->fetchObject();
  422. if ($setup) {
  423. return $setup->setup_id;
  424. }
  425. else {
  426. return FALSE;
  427. }
  428. }
  429. /**
  430. * Check to see if this table already has an integration record with the given priority.
  431. *
  432. * @param $table_name
  433. * The name of the table to check for integration
  434. * @param $priority (optional)
  435. * The priority of record to check for
  436. *
  437. * @return
  438. * If the table is already integrated, the setup_id of the existing integration
  439. * record is returned (If priority is not specified this will be the lightest record);
  440. * Otherwise the table is not already integrated and FALSE is returned.
  441. *
  442. * @ingroup tripal_views_api
  443. */
  444. function tripal_is_table_integrated($table_name, $priority = NULL) {
  445. if ($priority) {
  446. // D7 TODO: Check DBTNG changes work
  447. $sql = "SELECT setup_id FROM {tripal_views} WHERE table_name=:table AND priority=:priority";
  448. $setup = db_query($sql, array(':table' => $table_name, ':priority' => $priority));
  449. $setup = $setup->fetchObject();
  450. }
  451. else {
  452. // D7 TODO: Check DBTNG changes work
  453. $sql = "SELECT setup_id FROM {tripal_views} WHERE table_name=:table ORDER BY priority ASC";
  454. $setup = db_query($sql, array(':table' => $table_name));
  455. $setup = $setup->fetchObject();
  456. }
  457. if ($setup) {
  458. return $setup->setup_id;
  459. }
  460. else {
  461. return FALSE;
  462. }
  463. }
  464. /**
  465. * Checks if you are dealing with the lightest priority setup for a given table. This is a
  466. * good way to determine whether your modules integration is being used by views.
  467. *
  468. * @param $setup_id
  469. * The ID of the setup to check (is this setup the lightest one?)
  470. * @param $table_name
  471. * The name of the table associated with this setup
  472. *
  473. * @return TRUE is this is the lightest priority; FALSE otherwise
  474. *
  475. * @ingroup tripal_views_api
  476. */
  477. function tripal_is_lightest_priority_setup($setup_id, $table_name) {
  478. $lightest_priority_setup_id = tripal_get_lightest_views_integration_setup($table_name);
  479. if ($lightest_priority_setup_id == $setup_id) {
  480. return TRUE;
  481. }
  482. else {
  483. return FALSE;
  484. }
  485. }
  486. /**
  487. * Rebuilds all the default integrations.
  488. *
  489. * This essentially clears the cache in case you mess up the integrations in your site.
  490. * This should not be used during module development since it really only rebuilds the
  491. * integrations described by all enabled modules in the site and if $delete_first is
  492. * TRUE it can delete custom integrations created by site administrators which will not
  493. * make your module popular.
  494. *
  495. * @param $delete_first
  496. * If TRUE then all integrations are first deleted.
  497. *
  498. * @ingroup tripal_views_api
  499. */
  500. function tripal_rebuild_views_integrations($delete_first = FALSE) {
  501. if ($delete_first) {
  502. tripal_views_delete_all_integrations();
  503. }
  504. tripal_views_integrate_all_chado_tables();
  505. // TODO: the function above should have a return value from which we can
  506. // determine if the message below is approprite.
  507. drupal_set_message('Successfully rebuilt default Tripal Views Integrations');
  508. }
  509. /**
  510. * Add views integration records into the tripal_views* tables.
  511. *
  512. * This is the programatic way to add your own integrations to the tripal views integrations
  513. * list. Keep in mind that the priority set in your $defn_array needs to be lighter than
  514. * any existing integrations to be used by views and that it should still be below 0
  515. * in order to allow site administrators to override it should they need to.
  516. *
  517. * @param $defn_array
  518. * An array describing the structure and fields of the table
  519. *
  520. * @return
  521. * True/False if completed successfully/not
  522. *
  523. * Example usage (in hook_install()):
  524. * @code
  525. $defn_array = array(
  526. 'table' => 'feature', //tablename or materialized view name
  527. 'name' => 'Sequence Features', // Human readable name
  528. 'type' => 'chado', //either chado or mview depending on tablename
  529. 'description' => 'Create a listing of features.', //description seen when creating a view of this type
  530. 'priority' => 10, //For Base tripal modules: 10; custom modules: 9 to 0;
  531. 'base_table' => TRUE //either TRUE or FALSE depending on whether the current table should show up in the add view list
  532. 'fields' => array(
  533. 'feature_id' => array(
  534. 'name' => 'feature_id', //field name in database
  535. 'title' => 'Feature ID', //human-readable name -seen in Views UI
  536. 'description' => 'This is the unique identifier for features', //help/description seen in Views UI
  537. 'type' => 'int', // the type of field
  538. 'handlers' => array( //possible keys are field, filter, sort, argument, relationship
  539. 'field' => array(
  540. 'name' => 'chado_views_handler_numeric' //name of handler
  541. ),
  542. 'filter' => array( ... ),
  543. ...
  544. ),
  545. // Describe any joins involving this field.
  546. // Note: you can include both foreign keys (feature.type_id => cvterm.cvterm_id)
  547. // and referring tables (ie: feature.feature_id <= feature_relationship.subject_id)
  548. 'joins' => array(
  549. 'feature_relationship' => array( //table to join to.
  550. 'subject_id' => array( //field in above table (feature_relationship)
  551. 'table' => 'featureprop', //table to join to
  552. 'field' => 'feature_id', //field in above table (feature_relationship)
  553. 'handler' => 'views_join', //handler to use for joining
  554. 'relationship_handler' => 'views_handler_relationship', //handler to use when a relationship is added.
  555. 'relationship_only' => FALSE, //whether to join automatically (FALSE) or not (TRUE)
  556. ),
  557. ...
  558. ),
  559. ...
  560. ),
  561. )
  562. ),
  563. );
  564. tripal_add_views_integration($defn_array);
  565. * @endcode
  566. *
  567. * @ingroup tripal_views_api
  568. */
  569. function tripal_add_views_integration($defn_array, $setup_id = FALSE) {
  570. $no_errors = TRUE;
  571. if (empty($defn_array['table'])) {
  572. tripal_report_error('tripal_views', TRIPAL_WARNING, 'Recieved integration with no tablename: %defn', array('%defn' => print_r($defn_array,TRUE)));
  573. $no_errors = FALSE;
  574. return $no_errors;
  575. }
  576. // First insert into tripal_views
  577. $view_record = array(
  578. 'table_name' => $defn_array['table'],
  579. 'name' => $defn_array['name'],
  580. 'comment' => $defn_array['description'],
  581. 'priority' => $defn_array['priority'],
  582. 'base_table' => $defn_array['base_table'],
  583. );
  584. if ($setup_id) {
  585. $view_record['setup_id'] = $setup_id;
  586. }
  587. if ($defn_array['type'] == 'mview') {
  588. $mview = db_query("SELECT mview_id FROM {tripal_mviews} WHERE mv_table=:table", array(':table' => $defn_array['table']));
  589. $mview = $mview->fetchObject();
  590. $view_record['mview_id'] = $mview->mview_id;
  591. if (!$mview->mview_id) {
  592. return FALSE;
  593. }
  594. }
  595. if ($view_record['name']) { // && $view_record['comment']) { # SPF: commented out 9/24/2012 .. It's not required on the form
  596. if (isset($defn_array['additional_content'])) {
  597. // D7 TODO: Check DBTNG changes work
  598. $setup = db_query(
  599. "SELECT * FROM {tripal_views} WHERE table_name=:table AND priority=:priority",
  600. array(':table' => $view_record['table_name'], ':priority' => $view_record['priority'])
  601. );
  602. $setup = $setup->fetchObject();
  603. if (empty($setup->setup_id)) {
  604. $status = drupal_write_record('tripal_views', $view_record);
  605. }
  606. else {
  607. $view_record['setup_id'] = $setup->setup_id;
  608. $status = drupal_write_record('tripal_views', $view_record, 'setup_id');
  609. }
  610. }
  611. else {
  612. $status = drupal_write_record('tripal_views', $view_record);
  613. }
  614. }
  615. else {
  616. $status = FALSE;
  617. drupal_set_message(t('Unable to integrate "%table" table due to a missing name field.', array('%table' => $defn_array['table'])), 'error');
  618. }
  619. if ($status) {
  620. // Need to update the tripal_views record so base_table can be false
  621. // this is a fix because drupal_write_record() puts in defaults if !isset()
  622. // and a variable is considered not set if it's null!
  623. // D7 TODO: Check DBTNG changes work
  624. db_query(
  625. "UPDATE {tripal_views} SET base_table=:base WHERE table_name=:table AND priority=:priority",
  626. array(
  627. ':base' => $defn_array['base_table'],
  628. ':table' => $defn_array['table'],
  629. ':priority' => $defn_array['priority']
  630. )
  631. );
  632. // Insert Field Definitions
  633. foreach ($defn_array['fields'] as $field) {
  634. $field_record = array(
  635. 'setup_id' => $view_record['setup_id'],
  636. 'column_name' => $field['name'],
  637. 'name' => $field['title'],
  638. 'description' => $field['description'],
  639. 'type' => $field['type'],
  640. );
  641. if ($view_record['setup_id'] && $field['name'] && $field['title'] && $field['description'] && $field['type']) {
  642. if (isset($defn_array['additional_content'])) {
  643. // D7 TODO: Check DBTNG changes work
  644. $is_present = db_query(
  645. "SELECT true as present FROM {tripal_views_field} WHERE column_name=:column AND setup_id=:setup",
  646. array(
  647. ':column' => $field_record['column_name'],
  648. ':setup' => $field_record['setup_id']
  649. )
  650. );
  651. $is_present = $is_present->fetchField();
  652. if (!$is_present) {
  653. $status = drupal_write_record('tripal_views_field', $field_record);
  654. }
  655. else {
  656. $status = drupal_write_record('tripal_views_field', $field_record, array('setup_id', 'column_name'));
  657. }
  658. }
  659. else {
  660. $status = drupal_write_record('tripal_views_field', $field_record);
  661. }
  662. }
  663. else {
  664. drupal_set_message(t('Unable to integrate %name field due to missing required fields.', array('%name' => $field['name'])), 'error');
  665. $status = FALSE;
  666. }
  667. if ($status) {
  668. // Insert Handler Definitions
  669. foreach ($field['handlers'] as $handler_type => $handler) {
  670. $handler_record = array(
  671. 'setup_id' => $view_record['setup_id'],
  672. 'column_name' => $field['name'],
  673. 'handler_type' => $handler_type,
  674. 'handler_name' => $handler['name'],
  675. 'arguments' => serialize($handler)
  676. );
  677. if ($view_record['setup_id'] && $field['name'] && $handler_type && $handler['name'] && $handler) {
  678. $status = drupal_write_record('tripal_views_handlers', $handler_record);
  679. }
  680. else {
  681. $status = FALSE;
  682. }
  683. if (!$status) {
  684. drupal_set_message(t('Unable to integrate %handler_type handler: %handler_name', array('%handler_type' => $handler_type, '%handler_name' => $handler['name'])), 'error');
  685. $no_errors = FALSE;
  686. }
  687. }
  688. // Insert Joins
  689. // Note: The new defn_array structure accounts for 1+ joins to the same
  690. // table (ie: feature_relationship => feature : subject_id & object_id)
  691. // by making $field['joins'] an array of left_field keys.
  692. if (!is_array($field['joins'])) {
  693. $field['joins'] = array();
  694. }
  695. foreach ($field['joins'] as $joins) {
  696. // To keep backwards compatibility with the old defn_array which just
  697. // jumped right into the table definition allowing only a single join,
  698. // we need to check for old defn_arrays and transform them into the
  699. // new format.
  700. if (isset($joins['table'])) {
  701. $left_field = $joins['field'];
  702. $joins = array(
  703. $left_field => $joins
  704. );
  705. }
  706. // Loop on left fields
  707. foreach ($joins as $left_field => $join) {
  708. $join_record = array(
  709. 'setup_id' => $view_record['setup_id'],
  710. 'base_table' => $defn_array['table'],
  711. 'base_field' => $field['name'],
  712. 'left_table' => $join['table'],
  713. 'left_field' => $left_field,
  714. );
  715. $join_record['handler'] = (!empty($join['handler'])) ? $join['handler'] : 'views_join';
  716. $join_record['relationship_handler'] = (!empty($join['relationship_handler'])) ? $join['relationship_handler'] : 'views_handler_relationship';
  717. $join_record['relationship_only'] = (!empty($join['relationship_only'])) ? $join['relationship_only'] : 0;
  718. if ($view_record['setup_id'] && $defn_array['table'] && $field['name'] && $join['table'] && $left_field) {
  719. $status = drupal_write_record('tripal_views_join', $join_record);
  720. }
  721. else {
  722. $status = FALSE;
  723. }
  724. if (!$status) {
  725. drupal_set_message(
  726. t(
  727. 'Unable to join %left_table.%left_field with %table.%field',
  728. array(
  729. '%left_table' => $join['table'],
  730. '%left_field' => $left_field,
  731. '%table' => $defn_array['table'],
  732. '%field' => $field['name']
  733. )
  734. ),
  735. 'error'
  736. );
  737. $no_errors = FALSE;
  738. }
  739. }
  740. }
  741. }
  742. else {
  743. drupal_set_message(t('Unable to integrate %field_name field', array('%field_name' => $field['name'])), 'error');
  744. $no_errors = FALSE;
  745. }
  746. }
  747. }
  748. else {
  749. drupal_set_message(t('Unable to set default tripal views integration'), 'error');
  750. $no_errors = FALSE;
  751. }
  752. return $no_errors;
  753. }
  754. /**
  755. * Export Views integration records.
  756. *
  757. * This is a great way to create your own integration since it returns an already defined
  758. * integration in array form that you can modify. After modifications simply set the
  759. * priority to something lighter (but still below 0) than any existing integrations
  760. * and use tripal_add_views_integration() to add it to the list of integrations.
  761. *
  762. * @param $setup_id
  763. * The unique setup id of the tripal views integration
  764. *
  765. * @return
  766. * A views integration definition array as used by tripal_add_views_integration()
  767. *
  768. * @ingroup tripal_views_api
  769. */
  770. function tripal_export_views_integration($setup_id) {
  771. // Main setup details
  772. // D7 TODO: Check DBTNG changes work
  773. $r = db_query("SELECT * FROM {tripal_views} WHERE setup_id=:setup", array(':setup' => $setup_id));
  774. $r = $r->fetchObject();
  775. $defn_array = array(
  776. 'table' => $r->table_name,
  777. 'name' => $r->name,
  778. 'type' => ($r->mview_id) ? 'mview' : 'chado',
  779. 'description' => $r->comment,
  780. 'priority' => $r->priority,
  781. 'base_table' => $r->base_table,
  782. 'fields' => array(),
  783. );
  784. // Add fields
  785. $resource = db_query("SELECT * FROM {tripal_views_field} WHERE setup_id=:setup", array(':setup' => $setup_id));
  786. foreach ($resource as $r) {
  787. $defn_array['fields'][ $r->column_name ] = array(
  788. 'name' => $r->column_name,
  789. 'title' => $r->name,
  790. 'description' => $r->description,
  791. 'type' => $r->type,
  792. 'handlers' => array(),
  793. 'joins' => array()
  794. );
  795. }
  796. // Add handlers
  797. $resource = db_query("SELECT * FROM {tripal_views_handlers} WHERE setup_id=:setup", array(':setup' => $setup_id));
  798. foreach ($resource as $r) {
  799. $defn_array['fields'][ $r->column_name ]['handlers'][ $r->handler_type ] = array(
  800. 'name' => $r->handler_name
  801. );
  802. }
  803. // Add joins
  804. $resource = db_query("SELECT * FROM {tripal_views_join} WHERE setup_id=:setup", array(':setup' => $setup_id));
  805. foreach ($resource as $r) {
  806. $defn_array['fields'][ $r->base_field ]['joins'][ $r->left_table ][ $r->left_field ] = array(
  807. 'table' => $r->left_table,
  808. 'field' => $r->left_field,
  809. 'handler' => $r->handler,
  810. );
  811. }
  812. return $defn_array;
  813. }
  814. /**
  815. * Removes a View Integration Entry when you only know the table the integration was
  816. * created for and the priority.
  817. *
  818. * This should only be used to remove integrations created by your own module (possibly
  819. * on uninstall of your module). To override existing integrations simply create your own
  820. * integration with a lighter priority using tripal_clone_views_integration() or
  821. * tripal_export_views_integration() to create a template.
  822. *
  823. * @param $identifies
  824. * An array of identifiers where the keys indicate what the identifier is. One of the
  825. * following compinations must be present:
  826. * 1) table_name & priority: the name of the table & the priority to remove a views
  827. * integration entry for
  828. * 2) setup_id: the setup_id of the entry to remove
  829. * @param $options
  830. * An array of options, currently none are supported
  831. *
  832. * @return
  833. * TRUE on Success; FALSE otherwise
  834. *
  835. * @ingroup tripal_views_api
  836. */
  837. function tripal_remove_views_integration($identifiers, $options = array()) {
  838. // Remove the views integration using the table_name/priority combo
  839. if (isset($identifiers['table_name'])) {
  840. $table_name = $identifiers['table_name'];
  841. $priority = $identifiers['priority'];
  842. $views = db_query(
  843. "SELECT * FROM {tripal_views} WHERE table_name=:table AND priority=:priority",
  844. array(
  845. ':table' => $table_name,
  846. ':priority' => $priority
  847. )
  848. );
  849. $views = $views->fetchObject();
  850. if ($views->setup_id) {
  851. $identifiers['setup_id'] = $views->setup_id;
  852. }
  853. }
  854. // Remove the views integration using the setup_id
  855. if (isset($identifiers['setup_id'])) {
  856. db_query('DELETE FROM {tripal_views} WHERE setup_id=:setup', array(':setup' => $identifiers['setup_id']));
  857. db_query('DELETE FROM {tripal_views_field} WHERE setup_id=:setup', array(':setup' => $identifiers['setup_id']));
  858. db_query('DELETE FROM {tripal_views_handlers} WHERE setup_id=:setup', array(':setup' => $identifiers['setup_id']));
  859. db_query('DELETE FROM {tripal_views_join} WHERE setup_id=:setup', array(':setup' => $identifiers['setup_id']));
  860. return TRUE;
  861. }
  862. return FALSE;
  863. }
  864. /**
  865. * Update an existing Views Intregration Entry.
  866. * This essentially removes and then re-adds the integration.
  867. *
  868. * @param $setup_id
  869. * The setup ID of the views integration entry to update
  870. * @param $defn_array
  871. * An array describing the structure and fields of the table as is used in
  872. * tripal_add_views_integration().
  873. *
  874. * @ingroup tripal_views_api
  875. */
  876. function tripal_update_views_integration($setup_id, $defn_array) {
  877. tripal_remove_views_integration(array('setup_id' => $setup_id));
  878. $defn_array['additional_content'] = TRUE;
  879. tripal_add_views_integration($defn_array, $setup_id);
  880. }
  881. /**
  882. * Clone an integration. This is often a great way to create your own module-specific
  883. * integration while still benifiting from an existing (or even the lightest priority)
  884. * integration.
  885. *
  886. * @param $table_name
  887. * The table for which you'd like to clone an integration
  888. * @param $new_priority
  889. * The priority of the clone; this is the integration which will be created.
  890. * If no priority is supplied then one lighter then the $template_priority will be used.
  891. * @param $template_priority
  892. * The priority of the template to be used for the clone; this is an existing integration.
  893. * If no priority is supplied then the lightest priority will be used.
  894. *
  895. * @ingroup tripal_views_api
  896. */
  897. function tripal_clone_views_integration($table_name, $new_priority = NULL, $template_priority = NULL) {
  898. if (empty($template_priority)) {
  899. $template_setup_id = tripal_get_lightest_views_integration_setup($table_name);
  900. }
  901. else {
  902. $template_setup_id = tripal_get_views_integration_setup_id($table_name, $template_priority);
  903. }
  904. $defn_array = tripal_export_views_integration($template_setup_id);
  905. if (empty($new_priority)) {
  906. $defn_array['priority'] = $new_priority;
  907. }
  908. else {
  909. $new_priority = $defn_array['priority'] - 1;
  910. $defn_array['priority'] = $defn_array['priority'] - 1;
  911. }
  912. tripal_add_views_integration($defn_array);
  913. $setup_id = db_query(
  914. "SELECT setup_id FROM {tripal_views} WHERE table_name=:table AND priority=:priority",
  915. array(
  916. ':table' => $table_name,
  917. ':priority' => $new_priority
  918. )
  919. );
  920. $setup_id = $setup_id->fetchField();
  921. if (empty($setup_id)) {
  922. tripal_report_error('tripal_views', TRIPAL_ERROR, 'Unable to clone the setup for %table in order to add the following field to the integration: %field.',
  923. array('%table' => $table_name, '%field' => print_r($field_array,TRUE)));
  924. return FALSE;
  925. }
  926. else {
  927. return $setup_id;
  928. }
  929. }
  930. /**
  931. * Adds the given field to an existing or cloned integration. In the case of a cloned
  932. * integration, the lightest integration is used as the template for the clone.
  933. *
  934. * NOTE: If that field already exists in the specified integration then it will first be
  935. * deleted and the new one added.
  936. *
  937. * @param $table_name
  938. * The name of the table the integration is for
  939. * @param $priority
  940. * The priority of the integration to use; pass NULL to use the lightest integration
  941. * @param $field
  942. * An array describing the field ot add; uses the same format as the $defn_array
  943. *
  944. * @return
  945. * TRUE if the field was added successfully; FALSE otherwise
  946. *
  947. * @ingroup tripal_views_api
  948. */
  949. function tripal_add_field_to_views_integration($table_name, $priority, $field) {
  950. $no_errors = TRUE;
  951. // If no priority is supplied then add the field to the lightest integration
  952. if (empty($priority)) {
  953. $priority = tripal_get_lightest_views_integration_priority($table_name);
  954. }
  955. // First get the setup_id
  956. // D7 TODO: Check DBTNG changes work
  957. $setup_id = db_query(
  958. "SELECT setup_id FROM {tripal_views} WHERE table_name=:table AND priority=:priority",
  959. array(
  960. ':table' => $table_name,
  961. ':priority' => $priority
  962. )
  963. );
  964. $setup_id = $setup_id->fetchObject();
  965. // If there isn't an integration matching that table/priority combination
  966. // then clone the lightest priority integration
  967. if (empty($setup_id)) {
  968. $setup_id = tripal_clone_views_integration($table_name, $priority);
  969. }
  970. // Now delete any existing field
  971. db_query("DELETE FROM {tripal_views_field} WHERE setup_id=:setup AND column_name=:column",
  972. array(':setup' => $setup_id, 'column' => $field['name'])
  973. );
  974. db_query("DELETE FROM {tripal_views_handlers} WHERE setup_id=:setup AND column_name=:column",
  975. array(':setup' => $setup_id, 'column' => $field['name'])
  976. );
  977. db_query("DELETE FROM {tripal_views_join} WHERE setup_id=:setup AND base_table=:table AND base_field=:field",
  978. array(':setup' => $setup_id, ':table' => $table_name, ':field' => $field['name'])
  979. );
  980. // Now we need to add/update the field
  981. $field_record = array(
  982. 'setup_id' => $setup_id,
  983. 'column_name' => $field['name'],
  984. 'name' => $field['title'],
  985. 'description' => $field['description'],
  986. 'type' => $field['type'],
  987. );
  988. if ($setup_id && $field['name'] && $field['title'] && $field['description'] && $field['type']) {
  989. if ($defn_array['additional_content']) {
  990. // D7 TODO: Check DBTNG changes work
  991. $is = db_query(
  992. "SELECT true as present FROM {tripal_views_field} WHERE column_name=:column AND setup_id=:setup",
  993. array(':column' => $field_record['column_name'], ':setup' => $field_record['setup_id'])
  994. );
  995. $is = $is->fetchObject();
  996. if (!$is->present) {
  997. $status = drupal_write_record('tripal_views_field', $field_record);
  998. }
  999. else {
  1000. $status = drupal_write_record('tripal_views_field', $field_record, array('setup_id', 'column_name'));
  1001. }
  1002. }
  1003. else {
  1004. $status = drupal_write_record('tripal_views_field', $field_record);
  1005. }
  1006. }
  1007. else {
  1008. drupal_set_message(t('Unable to integrate %name field due to missing required fields.', array('%name' => $field['name'])), 'error');
  1009. $status = FALSE;
  1010. }
  1011. if ($status) {
  1012. // Insert Handler Definitions
  1013. foreach ($field['handlers'] as $handler_type => $handler) {
  1014. $handler_record = array(
  1015. 'setup_id' => $setup_id,
  1016. 'column_name' => $field['name'],
  1017. 'handler_type' => $handler_type,
  1018. 'handler_name' => $handler['name'],
  1019. 'arguments' => serialize($handler)
  1020. );
  1021. if ($setup_id && $field['name'] && $handler_type && $handler['name'] && $handler) {
  1022. $status = drupal_write_record('tripal_views_handlers', $handler_record);
  1023. }
  1024. else {
  1025. $status = FALSE;
  1026. }
  1027. if (!$status) {
  1028. drupal_set_message(t('Unable to integrate %handler_type handler: %handler_name', array('%handler_type' => $handler_type, '%handler_name' => $handler['name'])), 'error');
  1029. $no_errors = FALSE;
  1030. }
  1031. }
  1032. // Insert Joins
  1033. // Note: The new defn_array structure accounts for 1+ joins to the same
  1034. // table (ie: feature_relationship => feature : subject_id & object_id)
  1035. // by making $field['joins'] an array of left_field keys.
  1036. if (!is_array($field['joins'])) {
  1037. $field['joins'] = array();
  1038. }
  1039. foreach ($field['joins'] as $joins) {
  1040. // To keep backwards compatibility with the old defn_array which just
  1041. // jumped right into the table definition allowing only a single join,
  1042. // we need to check for old defn_arrays and transform them into the
  1043. // new format.
  1044. if (isset($joins['table'])) {
  1045. $left_field = $joins['field'];
  1046. $joins = array(
  1047. $left_field => $joins
  1048. );
  1049. }
  1050. // Loop on left fields
  1051. foreach ($joins as $left_field => $join) {
  1052. $join_record = array(
  1053. 'setup_id' => $setup_id,
  1054. 'base_table' => $defn_array['table'],
  1055. 'base_field' => $field['name'],
  1056. 'left_table' => $join['table'],
  1057. 'left_field' => $join['field'],
  1058. );
  1059. if (!empty($join['handler'])) {
  1060. $join_record['handler'] = $join['handler'];
  1061. }
  1062. else {
  1063. $join_record['handler'] = 'views_join';
  1064. }
  1065. if ($setup_id && $defn_array['table'] && $field['name'] && $join['table'] && $join['field']) {
  1066. $status = drupal_write_record('tripal_views_join', $join_record);
  1067. }
  1068. else {
  1069. $status = FALSE;
  1070. }
  1071. if (!$status) {
  1072. drupal_set_message(
  1073. t(
  1074. 'Unable to join %left_table.%left_field with %table.%field',
  1075. array(
  1076. '%left_table' => $join['table'],
  1077. '%left_field' => $join['field'],
  1078. '%table' => $defn_array['table'],
  1079. '%field' => $field['name']
  1080. )
  1081. ),
  1082. 'error'
  1083. );
  1084. $no_errors = FALSE;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. else {
  1090. drupal_set_message(t('Unable to integrate %field_name field', array('%field_name' => $field['name'])), 'error');
  1091. $no_errors = FALSE;
  1092. }
  1093. return $no_errors;
  1094. }
  1095. /**
  1096. * Adds the given field to an existing or cloned integration. In the case of a cloned
  1097. * integration, the lightest integration is used as the template for the clone.
  1098. *
  1099. * NOTE: If that field already exists in the specified integration then it will first be
  1100. * deleted and the new one added.
  1101. *
  1102. * @param $table_name
  1103. * The name of the table the integration is for
  1104. * @param $priority
  1105. * The priority of the integration to use; pass NULL to use the lightest integration
  1106. * @param $field
  1107. * An array describing the join to add. it should contain the following keys:
  1108. * base_table, base_field, left_table, left_field, handler, relationship_handler,
  1109. * relationship_only
  1110. *
  1111. * @return
  1112. * TRUE if the field was added successfully; FALSE otherwise
  1113. *
  1114. * @ingroup tripal_views_api
  1115. */
  1116. function tripal_add_join_to_views_integration($table_name, $priority, $join) {
  1117. $no_errors = TRUE;
  1118. // If no priority is supplied then add the field to the lightest integration
  1119. if (empty($priority)) {
  1120. $priority = tripal_get_lightest_views_integration_priority($table_name);
  1121. }
  1122. // First get the setup_id
  1123. $setup_id = db_query(
  1124. "SELECT setup_id FROM {tripal_views} WHERE table_name=:table AND priority=:priority",
  1125. array(
  1126. ':table' => $table_name,
  1127. ':priority' => $priority
  1128. )
  1129. );
  1130. $setup_id = $setup_id->fetchField();
  1131. // If there isn't an integration matching that table/priority combination
  1132. // then clone the lightest priority integration
  1133. if (empty($setup_id)) {
  1134. $setup_id = tripal_clone_views_integration($table_name, $priority);
  1135. }
  1136. // Add the setup_id to the join record passed in
  1137. $join['setup_id'] = $setup_id;
  1138. drupal_write_record('tripal_views_join', $join);
  1139. }
  1140. /**
  1141. * Remove a join from an integration. This is usually done after cloning an existing
  1142. * integration using tripal_clone_views_integration().
  1143. *
  1144. * @param $setup_id
  1145. * The setup_id of the integration to delete the join from
  1146. * @param $base_table
  1147. * The name of the base table involved the join
  1148. * @param $base_field
  1149. * The field from the base table involved in the join
  1150. * @param $left_table
  1151. * The name of the other table involved in the join
  1152. * @param $left_field
  1153. * The name of the field from the other table involved in the join
  1154. *
  1155. * @ingroup tripal_views_api
  1156. */
  1157. function tripal_remove_join_from_views_integration($setup_id, $base_table, $base_field, $left_table, $left_field) {
  1158. db_query(
  1159. "DELETE FROM {tripal_views_join} WHERE setup_id=:setup AND base_table=:base-table AND base_field=:base-field AND left_table=:left-table AND left_field=:left-field",
  1160. array(
  1161. ':setup' => $setup_id,
  1162. ':base-table' => $base_table,
  1163. ':base-field' => $base_field,
  1164. ':left-table' => $left_table,
  1165. ':left-field' => $left_field
  1166. )
  1167. );
  1168. }