<?php
/**
 * @file
 * The Tripal Core module
 */

// Import the full Tripal API into scope.
tripal_import_api();

require_once "includes/tripal.field_storage.inc";
require_once "includes/tripal.fields.inc";
require_once "includes/tripal.entity.inc";

require_once "includes/TripalVocab.inc";
require_once "includes/TripalVocabController.inc";
require_once "includes/TripalVocabViewsController.inc";
require_once "includes/TripalTerm.inc";
require_once "includes/TripalTermController.inc";
require_once "includes/TripalTermViewsController.inc";
require_once "includes/TripalEntity.inc";
require_once "includes/TripalEntityController.inc";
require_once "includes/TripalEntityUIController.inc";
require_once "includes/TripalEntityViewsController.inc";
require_once "includes/TripalBundle.inc";
require_once "includes/TripalBundleController.inc";
require_once "includes/TripalBundleUIController.inc";
require_once "includes/TripalBundleViewsController.inc";
require_once "includes/TripalFields/TripalField.inc";
require_once "includes/TripalFields/TripalFieldWidget.inc";
require_once "includes/TripalFields/TripalFieldFormatter.inc";
require_once "includes/TripalFieldQuery.inc";
require_once "includes/TripalJob.inc";
require_once "includes/TripalImporter.inc";

/**
 * @defgroup tripal Tripal Core Module
 * @ingroup tripal_modules
 * @{
 * Functionality useful for all other Tripal modules including the Tripal jobs, files,
 * materialized views and custom table functions.
 * @}
 */

/**
 * Implements hook_views_api().
 */
function tripal_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Implements hook_init().
 *
 * @ingroup tripal
 */
function tripal_init() {
  global $base_url;

  // add some variables for all javasript to use for building URLs
  $clean_urls = variable_get('clean_url', 0);
  $tripal_path = url(drupal_get_path('module', 'tripal'));
  drupal_add_js("
    var baseurl  = '$base_url';
    var isClean  =  $clean_urls;
    var tripal_path = '$tripal_path';",
    'inline', 'header');

  // make sure the date time settings are the way Tripal will insert them
  // otherwise PostgreSQL version that may have a different datestyle setting
  // will fail when inserting or updating a date column in a table.
  db_query("SET DATESTYLE TO :style", array(':style' => 'MDY'));

}

function tripal_menu_alter(&$items) {
  //drupal_debug($items);
}
/**
 * Implements hook_menu().
 * Defines all menu items needed by Tripal Core
 *
 * @ingroup tripal
 */
function tripal_menu() {
  $items = array();


  // Tripal setting groups
  $items['admin/tripal'] = array(
    'title' => 'Tripal',
    'description' => t("Manage the behavior or Tripal and its various modules."),
    'weight' => -8,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer tripal'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );

  $items['admin/tripal/storage'] = array(
    'title' => 'Data Storage',
    'description' => t("Tripal is designed to access biological
        data in any data storage back-end.  A storage back-end must have a
        module that can be installed that interfaces with Tripal.  By default
        the base Tripal package provides The Tripal Chado module for storing
        data in the GMOD Chado database schema.  All available storage backends
        and their administrative tools are found here."),
    'weight' => 8,
    'access arguments' => array('administer tripal'),
  );

  $items['admin/tripal/dashboard'] = array(
    'title' => 'Dashboard',
    'description' => t("A dashboard view of Tripal including new fields for entities."),
    'weight' => 0,
    'page callback' => 'tripal_admin_usage_page',
    'access arguments' => array('administer tripal'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/tripal_admin_usage_page.inc',
    'file path' => drupal_get_path('module', 'tripal'),
  );

//   $items['admin/tripal/loaders/obo_loader'] = array(
//     'title' => 'OBO Controlled Vocabulary Loader',
//     'description' => t("Import vocabularies and terms in OBO format."),
//     'access arguments' => array('administer tripal'),
//     'page callback' => 'drupal_get_form',
//     'page arguments' => array('tripal_vocabulary_import_form'),
//     'file' => 'includes/tripal.admin.inc',
//     'file path' => drupal_get_path('module', 'tripal'),
//     'type' => MENU_NORMAL_ITEM,
//   );

  $items['admin/tripal/extension'] = array(
    'title' => 'Extensions',
    'description' => t("Configuration and management pages for Tripal extension modules."),
    'weight' => 8,
    'access arguments' => array('administer tripal'),
  );

  // Menu items for facilitating import of extension modules.
  $items['admin/tripal/extension/available'] = array(
    'title' => 'Available Extensions',
    'description' => t('Look for extensions to add new functionality to this
        site. Tripal can be extended with new functionality developed
        by other Tripal site developers. These include modules with new or
        different functionality, bulk loading templates, or materialized
        views.  Anyone can create new extensions and share those for
        others to use.  Once shared they will appear in this list.'),
    'access arguments' => array('administer tripal'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_extensions_form'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/tripal.extensions.inc',
    'file path' => drupal_get_path('module', 'tripal'),
    'weight' => -100
  );
//   $items['admin/tripal/extension/import'] = array(
//     'title' => 'Import Extensions',
//     'description' => 'Provides a list of the available extensions that are registered at the tripal.info site. From this page you can easily import or install extensions to your site.',
//     'page callback' => 'drupal_get_form',
//     'page arguments' => array('tripal_extensions_form'),
//     'access arguments' => array('administer tripal'),
//     'type' => MENU_NORMAL_ITEM,
//     'file' =>  'includes/tripal.extensions.inc',
//     'file path' => drupal_get_path('module', 'tripal'),
//     'weight' => -100,
//   );

  // Jobs Management
  $items['admin/tripal/tripal_jobs'] = array(
    'title' => 'Jobs',
    'description' => t('Provides tools for managing jobs submitted to Tripal.  In some
        cases, long-running tasks are too slow to complete within a single
        browser session.  The Tripal jobs system allows long-running tasks
        to be submitted to a queue that can be executed manually by the
        site admin or automatically using a module such as the ') .
    l('Tripal Daemon', 'https://www.drupal.org/project/tripal_daemon', array('attributes' => array('target' => '_blank'))) .
    ' extension module.',
    'page callback' => 'tripal_jobs_admin_view',
    'access arguments' => array('administer tripal'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
    'file' => 'includes/tripal.jobs.inc',
  );
  $items['admin/tripal/tripal_jobs/help'] = array(
    'title' => 'Help',
    'description' => t('Help for the tripal job management system'),
    'page callback' => 'theme',
    'page arguments' => array('tripal_job_help'),
    'access arguments' => array('administer tripal'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10
  );
  $items['admin/tripal/tripal_jobs/cancel/%'] = array(
    'title' => 'Jobs',
    'description' => t('Cancel a pending job'),
    'page callback' => 'tripal_cancel_job',
    'page arguments' => array(4),
    'access arguments' => array('administer tripal'),
    'type' => MENU_CALLBACK,
    'file' => 'api/tripal.jobs.api.inc',
  );
  $items['admin/tripal/tripal_jobs/status/%'] = array(
    'page callback' => 'tripal_jobs_status_view',
    'page arguments' => array(4),
    'access arguments' => array('administer tripal'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal.jobs.inc',
  );
  $items['admin/tripal/tripal_jobs/rerun/%'] = array(
    'title' => 'Jobs',
    'description' => t('Re-run an existing job.'),
    'page callback' => 'tripal_rerun_job',
    'page arguments' => array(4),
    'access arguments' => array('administer tripal'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal.jobs.inc',
  );
  $items['admin/tripal/tripal_jobs/view/%'] = array(
    'title' => 'Jobs Details',
    'description' => t('View job details.'),
    'page callback' => 'tripal_jobs_view',
    'page arguments' => array(4),
    'access arguments' => array('administer tripal'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal.jobs.inc',
  );
  $items['admin/tripal/tripal_jobs/views/jobs/enable'] = array(
    'title' => 'Enable Jobs Administrative View',
    'page callback' => 'tripal_enable_view',
    'page arguments' => array('tripal_admin_jobs', 'admin/tripal/tripal_jobs'),
    'access arguments' => array('administer tripal'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal.jobs.inc',
  );



  /*
   * AJAX Callbacks.
   */
  $items['bio_data/ajax/field_attach/%'] = array(
    'page callback' => 'tripal_ajax_attach_field',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal.entity.inc',
    'file path' => drupal_get_path('module', 'tripal'),
  );

  /*
   * Dashboard Action Item callbacks.
   */
  $items['admin/disable/notification/%'] = array(
    'page callback' => 'tripal_disable_admin_notification',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal_admin_usage_page.inc',
    'file path' => drupal_get_path('module', 'tripal'),
  );

  $items['admin/import/field/%/%/%/%'] = array(
    'page callback' => 'tripal_admin_notification_import_field',
    'page arguments' => array(3, 4, 5, 6),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/tripal_admin_usage_page.inc',
    'file path' => drupal_get_path('module', 'tripal'),
  );

  /*
   * Term Lookup
   */
// TODO: finish this menu callback.
//   $items['cv/lookup'] = array(
//     'title' => 'Vocabulary Lookup',
//     'description' => t("Provides a tool to discover controlled vocabularies and their terms used by this site."),
//     'access arguments' => array('access content'),
//     'page callback' => 'drupal_get_form',
//     'page arguments' => array('tripal_vocabulary_lookup_form'),
//     'file' => 'includes/tripal.term_lookup.inc',
//     'file path' => drupal_get_path('module', 'tripal'),
//     'type' => MENU_NORMAL_ITEM,
//   );

  $items['cv/lookup/%/%'] = array(
    'title' => 'Vocabulary Lookup',
    'description' => t("Provides a tool to discover controlled vocabularies and their terms used by this site."),
    'access arguments' => array('access content'),
    'page callback' => 'tripal_vocabulary_lookup_term_page',
    'page arguments' => array(2, 3),
    'file' => 'includes/tripal.term_lookup.inc',
    'file path' => drupal_get_path('module', 'tripal'),
    'type' => MENU_CALLBACK,
  );

  // Adds a +Check for new fields link on the 'Tripal Content Types' page.
  $items['admin/structure/bio_data/manage/%/fields/check'] = array(
    'title' => 'Check for new fields',
    'description' => t('Check if new fields should be added to this content type.'),
    'page callback' => 'tripal_check_new_fields',
    'page arguments' => array(4),
    'access arguments' => array('administer tripal'),
    'file' => 'api/tripal.entities.api.inc',
    'file path' => drupal_get_path('module', 'tripal'),
    'type' => MENU_LOCAL_ACTION,
  );

  $items['tripal/upload'] = array(
    'page callback' => 'tripal_file_upload',
    'access arguments' => array('upload files'),
    'file' => '/includes/tripal.upload.inc',
    'type' => MENU_CALLBACK,
  );


  // Add in the loaders
  $importers = tripal_get_importers();
  foreach ($importers as $class_name) {
    tripal_load_include_importer_class($class_name);
    if (class_exists($class_name)) {
      $items['admin/tripal/loaders/' . $class_name::$machine_name] = array(
        'title' => $class_name::$name,
        'description' =>  $class_name::$description,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('tripal_get_importer_form', $class_name),
        'access arguments' => array('administer tripal'),
        'type' => MENU_NORMAL_ITEM,
        'file' => 'includes/tripal.importer.inc',
        'file path' => drupal_get_path('module', 'tripal'),
      );
    }
  }

  return $items;
}

/**
 * Implements hook_permission().
 */
function tripal_permission() {
  $permissions = array(
    'administer tripal' => array(
      'title' => t('Administer Tripal'),
      'description' => t('Allow the user to access administrative pages of Tripal. This includes management of jobs, the storage systems, extensions and the controlled vocabularies.'),
      'restrict access' => TRUE,
    ),
    'access tripal content overview' => array(
      'title' => t('Access the Tripal content overview page'),
      'description' => t('Get an overview of all Tripal content'),
      'restrict access' => TRUE,
    ),
    'manage tripal content types' => array(
      'title' => t('Manage Tripal content types'),
      'description' => t('Allows the user to create, update and delete Tripal content types.'),
      'restrict access' => TRUE,
    ),
    'upload files' => array(
      'title' => t('Upload Files'),
      'description' => t('Allows the user to upload files using Tripal\'s HTML5 loader.'),
    ),
    'view dev helps' => array(
      'title' => t('View Developer Hints'),
      'description' => t('Tripal will provide blue shaded boxes that provide
          instructions for how to customize or setup specific pages on a
          site.  This permission should be enabled for developers. But can
          be disabled once developers are accustomed to these hints.'),
      'restrict access' => TRUE,
    ),
  );

  // Add permissions for each content type.
  $bundles = tripal_get_content_types();
  foreach ($bundles as $bundle) {
    $permissions['view ' . $bundle->name] = array(
      'title' => t('%label: View Content', array('%label' => $bundle->label)),
      'description' => t('Allow the user to view %label content', array('%label' => $bundle->label)),
    );
    $permissions['create ' . $bundle->name] = array(
      'title' => t('%label: Create Content', array('%label' => $bundle->label)),
      'description' => t('Allow the user to create %label content', array('%label' => $bundle->label)),
      'restrict access' => TRUE,
    );
    $permissions['edit ' . $bundle->name] = array(
      'title' => t('%label: Edit Content', array('%label' => $bundle->label)),
      'description' => t('Allow the user to edit %label content', array('%label' => $bundle->label)),
      'restrict access' => TRUE,
    );
    $permissions['delete ' . $bundle->name] = array(
      'title' => t('%label: Delete Content', array('%label' => $bundle->label)),
      'description' => t('Allow the user to delete %label content', array('%label' => $bundle->label)),
      'restrict access' => TRUE,
    );
  }
  return $permissions;
}

/**
 * Implements hook_theme().
 * Registers template files/functions used by this module.
 *
 * @ingroup tripal
 */
function tripal_theme($existing, $type, $theme, $path) {
  $themes = array(
    // Admin messages theme
    'tripal_admin_message' => array(
      'function' => 'theme_tripal_admin_message',
      'variables' => array('message' => NULL),
    ),
    'tripal_entity' => array(
      'render element' => 'elements',
      'template' => 'tripal_entity',
      'path' => "$path/theme/templates"
    ),
    'tripal_add_list' => array(
      'variables' => array('content' => NULL),
    ),
    // Themeing for all fields.
    'tripal_field_default' => array(
      'render element' => 'element',
      'file' => 'includes/tripal.fields.inc',
    ),
  );

  return $themes;
}

/**
 * Implements hook_coder_ignore().
 * Defines the path to the file (tripal.coder_ignores.txt) where ignore rules for coder are stored
 */
function tripal_coder_ignore() {
  return array(
    'path' => drupal_get_path('module', 'tripal'),
    'line prefix' => drupal_get_path('module', 'tripal'),
  );
}


/**
 * Implements hook_libraries_info().
 */
function tripal_libraries_info() {
  $libraries = array();
  $libraries['d3'] = array(
    'name' => 'D3.js',
    'vendor url' => 'http://d3js.org/',
    'download url' => 'https://github.com/mbostock/d3',
    'version arguments' => array(
      'file' => 'd3.js',
      'pattern' => '/\s*version: "(\d+\.\d+\.\d+)"/',
    ),
    'files' => array(
      'js' => array(
        'd3.min.js',
      ),
    ),
  );

  return $libraries;
}

/**
 * Implements hook_admin_paths().
 * Define administrative paths.
 */
function tripal_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'bio_data/*/edit' => TRUE,
      'bio_data/*/delete' => TRUE,
      'bio_data/add' => TRUE,
      'bio_data/add/*' => TRUE,
    );
    return $paths;
  }
}

/**
 * Implements hook_menu_local_tasks_alter().
 *
 * Used to add action links to pages.
 */
function tripal_menu_local_tasks_alter(&$data, $router_item, $root_path) {

  // Add an "Add Tripal Content" action link to the Admin >> Content >>
  // Biological Content page.
  if ($root_path == 'admin/content/bio_data') {
    $item = menu_get_item('bio_data/add');
    if ($item['access']) {
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
}
/**
 * Implements hook_shortcut_default_set().
 * Modify the shortcut menu to include Biological content links.
 *
 * @param object $account
 *   The user account whose default shortcut set will be returned. If not provided, the
 *   function will return the currently logged-in user's default shortcut set.
 *
 * @return
 *   An object representing the default shortcut set.
 */
function tripal_shortcut_default_set($account) {
  $sets = shortcut_sets();
  $found = FALSE;
  foreach ($sets as $set) {
    if ($set->title == 'TripalDefault') {
      $found = TRUE;
    }
  }
  if (!$found) {
    $t = get_t();
    // Create an initial default shortcut set.
    $shortcut_set = new stdClass();
    $shortcut_set->title = $t('TripalDefault');
    $shortcut_set->links = array(
      array(
        'link_path' => 'node/add',
        'link_title' => $t('Add content'),
        'weight' => -35,
      ),
      array(
        'link_path' => 'bio_data/add',
        'link_title' => 'Add Tripal Content',
        'weight' => -30,
      ),
      array(
        'link_path' => 'admin/content',
        'link_title' => $t('Find content'),
        'weight' => -25,
      ),
      array(
        'link_path' => 'admin/content/bio_data',
        'link_title' => 'Find Tripal Content',
        'weight' => -20,
      ),
    );
    shortcut_set_save($shortcut_set);
  }

  $sets = shortcut_sets();
  foreach ($sets as $set) {
    if ($set->title == 'TripalDefault') {
      return $set->set_name;
    }
  }
}

/**
 * Menu argument loader; Load a tripal data type by string.
 *
 * This function is not meant to be used as an API function. It is only meant
 * for use in the menu to resolve the %tripal_bundle wildcard.
 *
 * @param $type
 *   The machine-readable name of a tripal data type to load.
 * @return
 *   A tripal data type array or FALSE if $type does not exist.
 */

function TripalBundle_load($bundle_type, $reset = FALSE) {
  // Get the type of entity by the ID.
  $bundle = db_select('tripal_bundle', 'tdt')
    ->fields('tdt')
    ->condition('name', $bundle_type)
    ->execute()
    ->fetchObject();
  if ($bundle) {
    $entity = entity_load('TripalBundle', array($bundle->id), array(), $reset);
    return reset($entity);
  }
  return FALSE;
}

/**
 * Allows the menu system to use a wildcard to fetch the entity.
 *
 * Make sure that the wildcard you choose in the tripal_entity entity
 * definition fits the function name here.
 *
 * This function is not meant to be used as an API function. It is only meant
 * for use in the menu to resolve the %tripal_entity wildcard.
 *
 * @param $id
 *   Integer specifying the tripal_entity id.
 * @param $reset
 *   A boolean indicating that the internal cache should be reset.
 * @return
 *   A fully-loaded $tripal_entity object or FALSE if it cannot be loaded.
 *
 * @see tripal_entity_load_multiple()
 */
function TripalEntity_load($id, $reset = FALSE) {
  // $entity = entity_load('TripalEntity', array($id), array(), $reset);
  $entity = tripal_load_entity('TripalEntity', array($id), $reset);
  return reset($entity);
}

/**
 * Imports all of the Tripal API into scope.
 *
 * Typically this function call is not necessary as all of the API is
 * automaticaly included by the tripal module.  However this function can
 * be useful in the .install files during a site upgrade when the tripal
 * module is not enabld.
 *
 * Example usage:
 * @code
 *   module_load_include('module', 'tripal', 'tripal');
 *   tripal_import_api();
 * @endcode
 *
 */
function tripal_import_api() {
  module_load_include('inc', 'tripal', 'api/tripal.d3js.api');
  module_load_include('inc', 'tripal', 'api/tripal.fields.api');
  module_load_include('inc', 'tripal', 'api/tripal.importer.api');
  module_load_include('inc', 'tripal', 'api/tripal.terms.api');
  module_load_include('inc', 'tripal', 'api/tripal.entities.api');
  module_load_include('inc', 'tripal', 'api/tripal.files.api');
  module_load_include('inc', 'tripal', 'api/tripal.jobs.api');
  module_load_include('inc', 'tripal', 'api/tripal.notice.api');
  module_load_include('inc', 'tripal', 'api/tripal.variables.api');
  module_load_include('inc', 'tripal', 'api/tripal.DEPRECATED.api');
}

/**
 * Implements hook_form_alter().
 */
function tripal_form_alter(&$form, $form_state, $form_id) {
  // If this is the field_ui_field_edit_form (i.e. the form that appears
  // when editing a field that is attached to an entity). Then we want
  // to add term settings for any field attached to a TripalEntity
  // content type.
  if ($form_id == 'field_ui_field_edit_form' and $form['#instance']['entity_type'] == 'TripalEntity') {
    tripal_field_instance_settings_form_alter($form, $form_state);
  }
}

function tripal_check_new_fields($bundle_name) {
  tripal_refresh_bundle_fields($bundle_name);
  drupal_goto("admin/structure/bio_data/manage/$bundle_name/fields");
}


/**
 * Implements hook_block_info().
 */
function tripal_block_info() {
  $blocks = array();

  $blocks['notifications_block'] = array(
    'info' => t('Dashboard Notifications'),
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'admin/tripal/dashboard',
    'status' => TRUE,
    'region' => 'content',
    'properties' => array(
      'administrative' => TRUE,
    ),
  );

  $blocks['powered_by_tripal'] = array(
    'info' => t('Powered by Tripal'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function tripal_block_view($delta = ''){
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'powered_by_tripal':
      $size = variable_get('powered_by_tripal_size', 'small');
      $type = variable_get('powered_by_tripal_type', 'bw');

      $image = 'powered_by_tripal_bw_small.png';
      if ($size == 'small' and $type == 'col') {
        $image = 'powered_by_tripal_small.png';
      }
      if ($size == 'large' and $type == 'bw') {
        $image = 'powered_by_tripal_bw.png';
      }
      if ($size == 'large' and $type == 'col') {
        $image = 'powered_by_tripal.png';
      }

      $block['title'] = '';
      $block['content'] = array(
        '#markup' => '<a href="http://tripal.info"><img border="0" src="' . drupal_get_path('module', 'tripal') . '/theme/images/' . $image . '"></a>',
      );
      break;

    case 'notifications_block':
      // Create your block content here
      $block['content'] = '';

      // Prepare table header
      $header = array(
        'title' => array('data' => t('Title')),
        'details' => array('data' => t('Details')),
        'type' => array('data' => t('Type'), 'field' => 'tan.type'),
        'actions' => array('data' => t('Actions'))
      );

      $query = db_select('tripal_admin_notfications', 'tan')
        ->extend('TableSort');

      $results = $query->fields('tan')
        ->condition('enabled', 1, '=')
        ->orderByHeader($header)
        ->execute()->fetchAll();
      $rows = array();

      foreach($results as $result){
        $data['operation'] = ' | ';
        $data['operation'] .= l(t('Dismiss Notification'), 'admin/disable/notification/' . $result->note_id);

        $actions = unserialize($result->actions);
        foreach($actions as $action){
          $label = key($actions);
          $link = $action;
        }

        $rows[] = array(
          'Title' => $result->title,
          'Details' => $result->details,
          'Type' => $result->type,
          'Actions' => l(t($label), $link) . $data['operation'],
        );
      }
      if(!empty($rows)) {
        //Number of records shown in per page
        $per_page = 10;
        $current_page = pager_default_initialize(count($rows), $per_page);
        $chunks = array_chunk($rows, $per_page, TRUE);

        // Output of table with the paging
        $table = theme('table',
          array(
            "header" => $header,
            "rows" => $chunks[ $current_page ],
            "attributes" => array(),
            "sticky" => TRUE,
            "caption" => "",
            "colgroups" => array(),
            "empty" => t("No notifications.")
          )
        );
        $table .= theme('pager', array('quantity', count($rows)));

        $fieldset_table = array(
          '#title' => t('Notifications'),
          '#collapsed' => FALSE,
          '#collapsible' => TRUE,
          '#attributes' => array('class' => array('collapsible')),
          '#children' => $table,
        );

        //return pager with limited number of records.
        $block['content'] = theme('fieldset', array('element' => $fieldset_table));
      }
      else {
        $block['content'] = 'There are no notifications at this time.';
      }
      break;
  }
  return $block;
}

/**
 * Implements hook_block_save().
 */
function tripal_block_save($delta = '', $edit = array()) {

  switch ($delta) {
    case 'powered_by_tripal':
      if (!empty($edit['logo_size'])) {
        variable_set('powered_by_tripal_size', $edit['logo_size']);
      }

      if (!empty($edit['logo_type'])) {
        variable_set('powered_by_tripal_type', $edit['logo_type']);
      }
  }
}
/**
 * Implements hook_block_configure().
 */
function tripal_block_configure ($delta = '') {
  $form = array();

  switch ($delta) {
    case 'powered_by_tripal':
      $form['logo_size'] = array(
        '#type' => 'radios',
        '#title' => t('Logo Size'),
        '#default_value' => variable_get('powered_by_tripal_size', 'small'),
        '#options' => array(
        'large' => t('Large'),
        'small' => t('Small')
      ),
      '#description' => t('Select if you would like a small or large "Powered by Tripal" logo.'),
      );
      $form['logo_type'] = array(
        '#type' => 'radios',
        '#title' => t('Logo Type'),
        '#default_value' => variable_get('powered_by_tripal_type', 'bw'),
        '#options' => array(
          'bw' => t('Gray scale'),
          'col' => t('Colored')
        ),
        '#description' => t('Select if you would like a black and white or colored "Powered by Tripal" logo.'),
      );
  }


  return $form;
}

/**
 * Implements hook_cron().
 */
function tripal_cron() {
  if (variable_get('tripal_admin_notification_creation_during_cron', TRUE)) {
    $modules = module_implements('tripal_cron_notification');
    foreach ($modules as $module) {
      $function = $module . '_tripal_cron_notification';
      $function();
    }
    watchdog('tripal_cron', 'tripal_cron ran');
  }
}

/**
 * Implements hook_element_info().
 *
 * Used for creating new form API elements.
 */
function tripal_element_info() {

  // Element for uploading large files.  This form element
  // accepts the following keys when using in a form:
  //   - #title:  The title that will appear above the element.
  //   - #description:  The description that will appear below the element.
  //   - #usage_type:  Required.  The type of file.  This will be stored in
  //     the 'type' column of the file_usage table.
  //   - #usage_id: Required. A unique numeric ID representing an entity, node
  //     or some other record identifier.  This can be any identifier that
  //     makes sense to the module that implements a form that uses this
  //     element.
  $elements['html5_file'] = array(
    '#input' => 'TRUE',
    '#process' => array('tripal_html5_file_process'),
    '#element_validate' => array('tripal_html5_file_validate'),
    '#value_callback' => 'tripal_html5_file_value',
  );
  return $elements;
}

/**
 *  The process function for the html5_file form element.
 */
function tripal_html5_file_process($element, $form_state, $complete_form) {

  $type = $element['#usage_id'] . '-' . $element['#usage_type'];
  $name = $element['#name'];
  $name = preg_replace('/[^\w]/', '_', $name);

  $headers = array(
    array('data' => 'File'),
    array('data' => 'Size', 'width' => '10%'),
    array('data' => 'Upload Progress', 'width' => '20%'),
    array('data' => 'Action', 'width' => '10%')
  );
  $rows = array();
  $table_vars = array(
    'header'      => $headers,
    'rows'        => $rows,
    'attributes'  => array(
      'class' => array('tripal-html5-file-upload-table'),
      'id' => 'tripal-html5-file-upload-table-' . $type
    ),
    'sticky'      => TRUE,
    'colgroups'   => array(),
    'empty'       => t('There are currently no files.'),
  );
  $element['html5_file_table_key'] = array(
    '#type' => 'hidden',
    '#value' => $type,
    '#attributes' => array(
      'class' => array('tripal-html5-file-upload-table-key')
    )
  );
  $element['html5_file_table'] = array(
    '#type' => 'item',
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#markup' => theme('table', $table_vars)
  );

  $element[$name] = array(
    '#type' => 'hidden',
    '#attributes' => array('id' => 'tripal-html5-upload-fid-' . $type),
    '#default_value' => $element['#value'],
  );
  $element['html5_file_submit'] = array(
    '#type'     => 'submit',
    '#value'    => 'Upload File',
    '#name' => 'tripal_html5_file_upload_submit-' . $type,
    // We don't want this button to submit as the file upload
    // is handled by the JavaScript code.
    '#attributes' => array(
      'id' => 'tripal-html5-file-upload-submit-' . $type,
      'onclick' => 'return (false);'
    )
  );

  drupal_add_js(drupal_get_path ('module', 'tripal') . '/theme/js/TripalUploader.js');
  drupal_add_js(drupal_get_path ('module', 'tripal') . '/theme/js/TripalUploadFile.js');
  drupal_add_js(drupal_get_path ('module', 'tripal') . '/theme/js/tripal.file.js');

  return $element;
}
/**
 *
 */
function tripal_html5_file_validate($element, &$form_state) {
  $is_required = $element['#required'];
  $fid = $element['#value'];

  if ($is_required and !$fid) {
    form_error($element, t('A file must be uploaded.'));
  }
}



/**
 * Implements hook_handle_uplaoded_file().
 */
function tripal_handle_uploaded_file($filename, $filepath, $type) {

  global $user;

  // Split the type into a node ID and form_key
  list($nid, $form_key) = explode('-', $type);

  // See if this file is already managed then add another entry fin the
  // usage table.
  $fid = db_select('file_managed', 'fm')
  ->fields('fm', array('fid'))
  ->condition('uri', $filepath)
  ->execute()
  ->fetchField();
  if ($fid) {
    $file = file_load($fid);
    file_usage_add($file, 'tripal', $form_key, $nid);
    return $fid;
  }

  // Create a file object.
  $file = new stdClass();
  $file->uri = $filepath;
  $file->filename = $filename;
  $file->filemime = file_get_mimetype($filepath);
  $file->uid = $user->uid;
  $file->status = FILE_STATUS_PERMANENT;
  $file = file_save($file);

  return $file->fid;
}

/**
 * Implements hook_value() for the html5_file form element.
 */
function tripal_html5_file_value($element, $input = FALSE, &$form_state) {

  if ($input) {
    if (is_array($input)) {
      $name = $element['#name'];
      $name = preg_replace('/[^\w]/', '_', $name);
      return $input[$name];
    }
    else {
      return $input;
    }
  }
}


/**
 *  Implements hook_field_display_alter().
 * @param $display
 * @param $context
 */
function tripal_field_display_alter(&$display, $context){
  $field_name = $context['field']['field_name'];
  $bundle = $context['entity']->bundle;
  $bundle_info = tripal_load_bundle_entity(array('name' => $bundle));
  $hide_variable = tripal_get_bundle_variable('hide_empty_field', $bundle_info->id, 'hide');

  if($hide_variable == 'hide'){
    $item = field_get_items('TripalEntity', $context['entity'], $field_name);
    if($item) {
      $field = field_info_field($field_name);
      if(tripal_field_is_empty($item[0], $field)) {
        // Stop the right rail element from rendering.
        drupal_add_css('.'.$field_name.' {display:none;}', 'inline');
      }
    }
  }
}

/**
 * Implements hook_field_group_table_rows_alter().
 *
 * This hook is used for hiding empty rows in a Field Group Table field group.
 *
 * @param $element
 *   The field group object.
 * @param $children
 *   An array of field names that are cpntained in the field group
 */
function tripal_field_group_table_rows_alter(&$element, &$children) {

  // Iterate through the children of this table field group.
  foreach ($children as $index => $child) {
    if (is_array($element[$child])) {
      $bundle = $element[$child]['#bundle'];
      $bundle_info = tripal_load_bundle_entity(array('name' => $bundle));

      // If the hide empty variable is turned on then remove fields from
      // the field group.
      $hide_variable = tripal_get_bundle_variable('hide_empty_field', $bundle_info->id, 'hide');
      if($hide_variable == 'hide'){
        $items = $element[$child]['#items'];
        // Case #1: there are no items.
        if (count($items) == 0) {
          unset($children[$index]);
          unset($element[$child]);
        }
        // Case #2: there is one item but the value is empty.
        if (count($items) == 1 and array_key_exists('value', $items[0]) and empty($items[0]['value'])) {
          unset($children[$index]);
          unset($element[$child]);
        }
      }
    }
  }
}

