<?php

/**
 * @file
 * CTools primary module file.
 *
 * Most of the CTools tools are in their own .inc files. This contains
 * nothing more than a few convenience functions and some hooks that
 * must be implemented in the module file.
 */

define('CTOOLS_API_VERSION', '2.0.9');

/**
 * The current working ctools version.
 *
 * In a release, it should be 7.x-1.x, which should match what drush make will
 * create. In a dev format, it should be 7.x-1.(x+1)-dev, which will allow
 * modules depending on new features in ctools to depend on ctools > 7.x-1.x.
 *
 * To define a specific version of CTools as a dependency for another module,
 * simply include a dependency line in that module's info file, e.g.:
 *   ; Requires CTools v7.x-1.4 or newer.
 *   dependencies[] = ctools (>=1.4)
 */
define('CTOOLS_MODULE_VERSION', '7.x-1.13');

/**
 * Test the CTools API version.
 *
 * This function can always be used to safely test if CTools has the minimum
 * API version that your module can use. It can also try to protect you from
 * running if the CTools API version is too new, but if you do that you need
 * to be very quick about watching CTools API releases and release new versions
 * of your software as soon as the new release is made, or people might end up
 * updating CTools and having your module shut down without any recourse.
 *
 * It is recommended that every hook of your module that might use CTools or
 * might lead to a use of CTools be guarded like this:
 *
 * @code
 * if (!module_invoke('ctools', 'api_version', '1.0')) {
 *   return;
 * }
 * @endcode
 *
 * Note that some hooks such as _menu() or _theme() must return an array().
 *
 * You can use it in your hook_requirements to report this error condition
 * like this:
 *
 * @code
 * define('MODULENAME_MINIMUM_CTOOLS_API_VERSION', '1.0');
 * define('MODULENAME_MAXIMUM_CTOOLS_API_VERSION', '1.1');
 *
 * function MODULENAME_requirements($phase) {
 *   $requirements = array();
 *   if (!module_invoke('ctools', 'api_version', MODULENAME_MINIMUM_CTOOLS_API_VERSION, MODULENAME_MAXIMUM_CTOOLS_API_VERSION)) {
 *      $requirements['MODULENAME_ctools'] = array(
 *        'title' => $t('MODULENAME required Chaos Tool Suite (CTools) API Version'),
 *        'value' => t('Between @a and @b', array('@a' => MODULENAME_MINIMUM_CTOOLS_API_VERSION, '@b' => MODULENAME_MAXIMUM_CTOOLS_API_VERSION)),
 *        'severity' => REQUIREMENT_ERROR,
 *      );
 *   }
 *   return $requirements;
 * }
 * @endcode
 *
 * Please note that the version is a string, not an floating point number.
 * This will matter once CTools reaches version 1.10.
 *
 * A CTools API changes history will be kept in API.txt. Not every new
 * version of CTools will necessarily update the API version.
 * @param $minimum
 *   The minimum version of CTools necessary for your software to run with it.
 * @param $maximum
 *   The maximum version of CTools allowed for your software to run with it.
 *
 * @return bool
 *   TRUE if the running ctools is usable, FALSE otherwise.
 */
function ctools_api_version($minimum, $maximum = NULL) {
  if (version_compare(CTOOLS_API_VERSION, $minimum, '<')) {
    return FALSE;
  }

  if (isset($maximum) && version_compare(CTOOLS_API_VERSION, $maximum, '>')) {
    return FALSE;
  }

  return TRUE;
}

// -----------------------------------------------------------------------
// General utility functions.
/**
 * Include .inc files as necessary.
 *
 * This fuction is helpful for including .inc files for your module. The
 * general case is including ctools funcitonality like this:
 *
 * @code
 * ctools_include('plugins');
 * @endcode
 *
 * Similar funcitonality can be used for other modules by providing the $module
 * and $dir arguments like this:
 *
 * @code
 * // include mymodule/includes/import.inc
 * ctools_include('import', 'mymodule');
 * // include mymodule/plugins/foobar.inc
 * ctools_include('foobar', 'mymodule', 'plugins');
 * @endcode
 *
 * @param $file
 *   The base file name to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 */

function ctools_include($file, $module = 'ctools', $dir = 'includes') {
  static $used = array();

  $dir = '/' . ($dir ? $dir . '/' : '');

  if (!isset($used[$module][$dir][$file])) {
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "$dir$file.inc";
    $used[$module][$dir][$file] = TRUE;
  }
}

/**
 * Include .inc files in a form context.
 *
 * This is a variant of ctools_include that will save information in the
 * the form_state so that cached forms will properly include things.
 */
function ctools_form_include(&$form_state, $file, $module = 'ctools', $dir = 'includes') {
  if (!isset($form_state['build_info']['args'])) {
    $form_state['build_info']['args'] = array();
  }

  $dir = '/' . ($dir ? $dir . '/' : '');
  form_load_include($form_state, 'inc', $module, $dir . $file);
}

/**
 * Add an arbitrary path to the $form_state so it can work with form cache.
 *
 * The module_load_include() function uses an unfortunately annoying syntax to
 * work, making it difficult to translate the more simple $path + $file syntax.
 */
function ctools_form_include_file(&$form_state, $filename) {
  if (!isset($form_state['build_info']['args'])) {
    $form_state['build_info']['args'] = array();
  }

  // Now add this to the build info files so that AJAX requests will know to load it.
  $form_state['build_info']['files']["$filename"] = $filename;
  require_once DRUPAL_ROOT . '/' . $filename;
}

/**
 * Provide the proper path to an image as necessary.
 *
 * This helper function is used by ctools but can also be used in other
 * modules in the same way as explained in the comments of ctools_include.
 *
 * @param $image
 *   The base file name (with extension)  of the image to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 *
 * @return string
 *   A string containing the appropriate path from drupal root.
 */
function ctools_image_path($image, $module = 'ctools', $dir = 'images') {
  return drupal_get_path('module', $module) . "/$dir/" . $image;
}

/**
 * Include css files as necessary.
 *
 * This helper function is used by ctools but can also be used in other
 * modules in the same way as explained in the comments of ctools_include.
 *
 * @param $file
 *   The base file name to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 */
function ctools_add_css($file, $module = 'ctools', $dir = 'css') {
  drupal_add_css(drupal_get_path('module', $module) . "/$dir/$file.css");
}

/**
 * Format a css file name for use with $form['#attached']['css'].
 *
 * This helper function is used by ctools but can also be used in other
 * modules in the same way as explained in the comments of ctools_include.
 *
 * @code
 *   $form['#attached']['css'] = array(ctools_attach_css('collapsible-div'));
 *   $form['#attached']['css'][ctools_attach_css('collapsible-div')] = array('preprocess' => FALSE);
 * @endcode
 *
 * @param $file
 *   The base file name to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 *
 * @return string
 *   A string containing the appropriate path from drupal root.
 */
function ctools_attach_css($file, $module = 'ctools', $dir = 'css') {
  return drupal_get_path('module', $module) . "/$dir/$file.css";
}

/**
 * Include js files as necessary.
 *
 * This helper function is used by ctools but can also be used in other
 * modules in the same way as explained in the comments of ctools_include.
 *
 * @param $file
 *   The base file name to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 */
function ctools_add_js($file, $module = 'ctools', $dir = 'js') {
  drupal_add_js(drupal_get_path('module', $module) . "/$dir/$file.js");
}

/**
 * Format a javascript file name for use with $form['#attached']['js'].
 *
 * This helper function is used by ctools but can also be used in other
 * modules in the same way as explained in the comments of ctools_include.
 *
 * @code
 *   $form['#attached']['js'] = array(ctools_attach_js('auto-submit'));
 * @endcode
 *
 * @param $file
 *   The base file name to be included.
 * @param $module
 *   Optional module containing the include.
 * @param $dir
 *   Optional subdirectory containing the include file.
 *
 * @return string
 *   A string containing the appropriate path from drupal root.
 */
function ctools_attach_js($file, $module = 'ctools', $dir = 'js') {
  return drupal_get_path('module', $module) . "/$dir/$file.js";
}

/**
 * Get a list of roles in the system.
 *
 * @return
 *   An array of role names keyed by role ID.
 *
 * @deprecated
 *    user_roles() should be used instead.
 */
function ctools_get_roles() {
  return user_roles();
}

/**
 * Parse integer sequences of the form "x,y,z" or "x+y+z" into separate values.
 *
 * A string with integers separated by comma (,) is reported as an 'and' set;
 * separation by a plus sign (+) or a space ( ) is an 'or' set. The meaning
 * of this is up to the caller. Negative or fractional numbers are not
 * recognised.
 *
 * Additional space characters within or around the sequence are not allowed.
 *
 * @param $str
 *   The string to parse.
 *
 * @return object
 *   An object containing the properties:
 *
 *   - operator: Either 'and' or 'or' when there are multiple matched values.
 *   Absent when invalid_input is TRUE or there is only one value.
 *   - value: An array of integers (never strings) from $str. An empty array is
 *   returned if the input is empty. A single integer input is returned
 *   as a single value, but no 'operator' is defined.
 *   - invalid_input: TRUE if input could not be parsed and the values array
 *   will contain just -1. This property is otherwise absent.
 */
function ctools_break_phrase($str) {
  $object = new stdClass();

  if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {
    // The '+' character in a query string may be parsed as ' '.
    $object->operator = 'or';
    $object->value = preg_split('/[+ ]/', $str);
  }
  elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
    $object->operator = 'and';
    $object->value = explode(',', $str);
  }

  // Keep an 'error' value if invalid strings were given.
  if (!empty($str) && (empty($object->value) || !is_array($object->value))) {
    $object->value = array(-1);
    $object->invalid_input = TRUE;
    return $object;
  }

  if (empty($object->value)) {
    $object->value = array();
  }

  // Doubly ensure that all values are numeric only.
  foreach ($object->value as $id => $value) {
    $object->value[$id] = (int) $value;
  }

  return $object;
}

/**
 * Set a token/value pair to be replaced later in the request, specifically in
 * ctools_page_token_processing().
 *
 * @param string $token
 *   The token to be replaced later, during page rendering.  This should
 *   ideally be a string inside of an HTML comment, so that if there is
 *   no replacement, the token will not render on the page.
 *   If $token is NULL, the token set is not changed, but is still
 *   returned.
 * @param string $type
 *   The type of the token. Can be either 'variable', which will pull data
 *   directly from the page variables, or 'callback', which causes a function
 *   to be called to calculate the value. No other values are supported.
 * @param string|array $argument
 *   For $type of:
 *   - 'variable': argument should be the key to fetch from the $variables.
 *   - 'callback': then it should either be the callback function name as a
 *     string, or an array that will be sent to call_user_func_array(). Argument
 *     arrays must not use array keys (i.e. $a[0] is the first and $a[1] the
 *     second element, etc.)
 *
 * @return array
 *   A array of token/variable names to be replaced.
 */
function ctools_set_page_token($token = NULL, $type = NULL, $argument = NULL) {
  $tokens = &drupal_static('ctools_set_page_token', array());

  if (isset($token)) {
    $tokens[$token] = array($type, $argument);
  }
  return $tokens;
}

/**
 * Reset the defined page tokens within this request.
 *
 * Introduced for simpletest purposes. Normally not needed.
 */
function ctools_reset_page_tokens() {
  drupal_static_reset('ctools_set_page_token');
}

/**
 * Set a replacement token from the containing element's children during #post_render.
 *
 * This function can be used like this:
 *   $token = ctools_set_variable_token('tabs');
 *
 * The token "<!-- ctools-page-tabs -->" would then be replaced by the value of
 * this element's (sibling) render array key 'tabs' during post-render (or be
 * deleted if there was no such key by that point).
 *
 * @param string $token
 *   The token string for the page callback, e.g. 'title'.
 *
 * @return string
 *   The constructed token.
 *
 * @see ctools_set_callback_token()
 * @see ctools_page_token_processing()
 */
function ctools_set_variable_token($token) {
  $string = '<!-- ctools-page-' . $token . ' -->';
  ctools_set_page_token($string, 'variable', $token);
  return $string;
}

/**
 * Set a replacement token from the value of a function during #post_render.
 *
 * This function can be used like this:
 *   $token = ctools_set_callback_token('id', 'mymodule_myfunction');
 *
 * Or this (from its use in ctools_page_title_content_type_render):
 *   $token = ctools_set_callback_token('title', array(
 *       'ctools_page_title_content_type_token', $conf['markup'], $conf['id'], $conf['class']
 *     )
 *   );
 *
 * The token (e.g: "<!-- ctools-page-id-1b7f84d1c8851290cc342631ac663053 -->")
 * would then be replaced during post-render by the return value of:
 *
 *   ctools_page_title_content_type_token($value_markup, $value_id, $value_class);
 *
 * @param string $token
 *   The token string for the page callback, e.g. 'title'.
 *
 * @param string|array $callback
 *   For callback functions that require no args, the name of the function as a
 *   string; otherwise an array of two or more elements: the function name
 *   followed by one or more function arguments.
 *
 *   NB: the value of $callback must be a procedural (non-class) function that
 *   passes the php function_exists() check.
 *
 *   The callback function itself will be called with args dependent
 *   on $callback. If:
 *    - $callback is a string, the function is called with a reference to the
 *      render array;
 *    - $callback is an array, the function is called with $callback merged
 *      with an array containing a reference to the render array.
 *
 * @return string
 *   The constructed token.
 *
 * @see ctools_set_variable_token()
 * @see ctools_page_token_processing()
 */
function ctools_set_callback_token($token, $callback) {
  // If the callback uses arguments they are considered in the token.
  if (is_array($callback)) {
    $token .= '-' . md5(serialize($callback));
  }
  $string = '<!-- ctools-page-' . $token . ' -->';
  ctools_set_page_token($string, 'callback', $callback);
  return $string;
}

/**
 * Tell CTools that sidebar blocks should not be rendered.
 *
 * It is often desirable to not display sidebars when rendering a page,
 * particularly when using Panels. This informs CTools to alter out any
 * sidebar regions during block render.
 */
function ctools_set_no_blocks($blocks = FALSE) {
  $status = &drupal_static(__FUNCTION__, TRUE);
  $status = $blocks;
}

/**
 * Wrapper function to create UUIDs via ctools, falls back on UUID module
 * if it is enabled. This code is a copy of uuid.inc from the uuid module.
 *
 * @see http://php.net/uniqid#65879
 */
function ctools_uuid_generate() {
  if (!module_exists('uuid')) {
    ctools_include('uuid');

    $callback = drupal_static(__FUNCTION__);

    if (empty($callback)) {
      if (function_exists('uuid_create') && !function_exists('uuid_make')) {
        $callback = '_ctools_uuid_generate_pecl';
      }
      elseif (function_exists('com_create_guid')) {
        $callback = '_ctools_uuid_generate_com';
      }
      else {
        $callback = '_ctools_uuid_generate_php';
      }
    }
    return $callback();
  }
  else {
    return uuid_generate();
  }
}

/**
 * Check that a string appears to be in the format of a UUID.
 *
 * @see http://drupal.org/project/uuid
 *
 * @param $uuid
 *   The string to test.
 *
 * @return
 *   TRUE if the string is well formed.
 */
function ctools_uuid_is_valid($uuid = '') {
  if (empty($uuid)) {
    return FALSE;
  }
  if (function_exists('uuid_is_valid') || module_exists('uuid')) {
    return uuid_is_valid($uuid);
  }
  else {
    ctools_include('uuid');
    return uuid_is_valid($uuid);
  }
}

/**
 * Add an array of classes to the body.
 *
 * @param mixed $classes
 *   A string or an array of class strings to add.
 * @param string $hook
 *   The theme hook to add the class to. The default is 'html' which will
 *   affect the body tag.
 */
function ctools_class_add($classes, $hook = 'html') {
  if (!is_array($classes)) {
    $classes = array($classes);
  }

  $static = &drupal_static('ctools_process_classes', array());
  if (!isset($static[$hook]['add'])) {
    $static[$hook]['add'] = array();
  }
  foreach ($classes as $class) {
    $static[$hook]['add'][] = $class;
  }
}

/**
 * Remove an array of classes from the body.
 *
 * @param mixed $classes
 *   A string or an array of class strings to remove.
 * @param string $hook
 *   The theme hook to remove the class from. The default is 'html' which will
 *   affect the body tag.
 */
function ctools_class_remove($classes, $hook = 'html') {
  if (!is_array($classes)) {
    // @todo Consider using explode(' ', $classes);
    // @todo Consider checking that $classes is a string before adding.
    $classes = array($classes);
  }

  $static = &drupal_static('ctools_process_classes', array());
  if (!isset($static[$hook]['remove'])) {
    $static[$hook]['remove'] = array();
  }
  foreach ($classes as $class) {
    $static[$hook]['remove'][] = $class;
  }
}

/**
 * Reset the storage used for ctools_class_add and ctools_class_remove.
 *
 * @see ctools_class_add()
 * @see ctools_class_remove()
 */
function ctools_class_reset() {
  drupal_static_reset('ctools_process_classes');
}

/**
 * Return the classes for the body (added by ctools_class_add).
 *
 * @return array
 *   A copy of the array of classes to add to the body tag. If none have been
 *   added, this will be an empty array.
 *
 * @see ctools_class_add()
 */
function ctools_get_classes() {
  return drupal_static('ctools_process_classes', array());
}

// -----------------------------------------------------------------------
// Drupal core hooks.
/**
 * Implement hook_init to keep our global CSS at the ready.
 */

function ctools_init() {
  ctools_add_css('ctools');
  // If we are sure that CTools' AJAX is in use, change the error handling.
  if (!empty($_REQUEST['ctools_ajax'])) {
    ini_set('display_errors', 0);
    register_shutdown_function('ctools_shutdown_handler');
  }

  // Clear plugin cache on the module page submit.
  if ($_GET['q'] == 'admin/modules/list/confirm' && !empty($_POST)) {
    cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
  }
}

/**
 * Shutdown handler used during ajax operations to help catch fatal errors.
 */
function ctools_shutdown_handler() {
  if (function_exists('error_get_last') && ($error = error_get_last())) {
    switch ($error['type']) {
      case E_ERROR:
      case E_CORE_ERROR:
      case E_COMPILE_ERROR:
      case E_USER_ERROR:
        // Do this manually because including files here is dangerous.
        $commands = array(
          array(
            'command' => 'alert',
            'title' => t('Error'),
            'text' => t('Unable to complete operation. Fatal error in @file on line @line: @message', array(
              '@file' => $error['file'],
              '@line' => $error['line'],
              '@message' => $error['message'],
            )),
          ),
        );

        // Change the status code so that the client will read the AJAX returned.
        header('HTTP/1.1 200 OK');
        drupal_json($commands);
    }
  }
}

/**
 * Implements hook_theme().
 */
function ctools_theme() {
  ctools_include('utility');
  $items = array();
  ctools_passthrough('ctools', 'theme', $items);
  return $items;
}

/**
 * Implements hook_menu().
 */
function ctools_menu() {
  ctools_include('utility');
  $items = array();
  ctools_passthrough('ctools', 'menu', $items);
  return $items;
}

/**
 * Implements hook_permission().
 */
function ctools_permission() {
  return array(
    'use ctools import' => array(
      'title' => t('Use CTools importer'),
      'description' => t('The import functionality allows users to execute arbitrary PHP code, so extreme caution must be taken.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implementation of hook_cron. Clean up old caches.
 */
function ctools_cron() {
  ctools_include('utility');
  $items = array();
  ctools_passthrough('ctools', 'cron', $items);
}

/**
 * Implements hook_flush_caches().
 */
function ctools_flush_caches() {
  // Only return the CSS cache bin if it has been activated, to avoid
  // drupal_flush_all_caches() from trying to truncate a non-existing table.
  return variable_get('cache_class_cache_ctools_css', FALSE) ? array('cache_ctools_css') : array();
}

/**
 * Implements hook_element_info_alter().
 */
function ctools_element_info_alter(&$type) {
  ctools_include('dependent');
  ctools_dependent_element_info_alter($type);
}

/**
 * Implementation of hook_file_download()
 *
 * When using the private file system, we have to let Drupal know it's ok to
 * download CSS and image files from our temporary directory.
 */
function ctools_file_download($filepath) {
  if (strpos($filepath, 'ctools') === 0) {
    $mime = file_get_mimetype($filepath);
    // For safety's sake, we allow only text and images.
    if (strpos($mime, 'text') === 0 || strpos($mime, 'image') === 0) {
      return array('Content-type:' . $mime);
    }
  }
}

/**
 * Implements hook_registry_files_alter().
 *
 * Alter the registry of files to automagically include all classes in
 * class-based plugins.
 */
function ctools_registry_files_alter(&$files, $indexed_modules) {
  ctools_include('registry');
  return _ctools_registry_files_alter($files, $indexed_modules);
}

// -----------------------------------------------------------------------
// FAPI hooks that must be in the .module file.
/**
 * Alter the comment form to get a little more control over it.
 */

function ctools_form_comment_form_alter(&$form, &$form_state) {
  if (!empty($form_state['ctools comment alter'])) {
    // Force the form to post back to wherever we are.
    $form['#action'] = url($_GET['q'], array('fragment' => 'comment-form'));
    if (empty($form['#submit'])) {
      $form['#submit'] = array('comment_form_submit');
    }
    $form['#submit'][] = 'ctools_node_comment_form_submit';
  }
}

function ctools_node_comment_form_submit(&$form, &$form_state) {
  $form_state['redirect'][0] = $_GET['q'];
}

// -----------------------------------------------------------------------
// CTools hook implementations.
/**
 * Implementation of hook_ctools_plugin_directory() to let the system know
 * where all our own plugins are.
 */

function ctools_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'ctools') {
    return 'plugins/' . $plugin_type;
  }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function ctools_ctools_plugin_type() {
  ctools_include('utility');
  $items = array();
  // Add all the plugins that have their own declaration space elsewhere.
  ctools_passthrough('ctools', 'plugin-type', $items);

  return $items;
}

// -----------------------------------------------------------------------
// Drupal theme preprocess hooks that must be in the .module file.
/**
 * A theme preprocess function to automatically allow panels-based node
 * templates based upon input when the panel was configured.
 */

function ctools_preprocess_node(&$vars) {
  // The 'ctools_template_identifier' attribute of the node is added when the pane is
  // rendered.
  if (!empty($vars['node']->ctools_template_identifier)) {
    $vars['ctools_template_identifier'] = check_plain($vars['node']->ctools_template_identifier);
    $vars['theme_hook_suggestions'][] = 'node__panel__' . check_plain($vars['node']->ctools_template_identifier);
  }
}

/**
 * Implements hook_page_alter().
 *
 * Last ditch attempt to remove sidebar regions if the "no blocks"
 * functionality has been activated.
 *
 * @see ctools_block_list_alter()
 */
function ctools_page_alter(&$page) {
  $check = drupal_static('ctools_set_no_blocks', TRUE);
  if (!$check) {
    foreach ($page as $region_id => $region) {
      // @todo -- possibly we can set configuration for this so that users can
      // specify which blocks will not get rendered.
      if (strpos($region_id, 'sidebar') !== FALSE) {
        unset($page[$region_id]);
      }
    }
  }
  $page['#post_render'][] = 'ctools_page_token_processing';
}

/**
 * A theme post_render callback to allow content type plugins to use page
 * template variables which are not yet available when the content type is
 * rendered.
 */
function ctools_page_token_processing($children, $elements) {
  $tokens = ctools_set_page_token();
  if (!empty($tokens)) {
    foreach ($tokens as $token => $key) {
      list($type, $argument) = $key;
      switch ($type) {
        case 'variable':
          $tokens[$token] = isset($elements[$argument]) ? $elements[$argument] : '';
          break;

        case 'callback':
          if (is_string($argument) && function_exists($argument)) {
            $tokens[$token] = $argument($elements);
          }
          if (is_array($argument) && function_exists($argument[0])) {
            $function = array_shift($argument);
            $argument = array_merge(array(&$elements), $argument);
            $tokens[$token] = call_user_func_array($function, $argument);
          }
          break;
      }
    }
    $children = strtr($children, $tokens);
  }
  return $children;
}

/**
 * Implements hook_process().
 *
 * Add and remove CSS classes from the variables array. We use process so that
 * we alter anything added in the preprocess hooks.
 */
function ctools_process(&$variables, $hook) {
  if (!isset($variables['classes'])) {
    return;
  }

  $classes = ctools_get_classes();

  // Process the classses to add.
  if (!empty($classes[$hook]['add'])) {
    $add_classes = array_map('drupal_clean_css_identifier', $classes[$hook]['add']);
    $variables['classes_array'] = array_unique(array_merge($variables['classes_array'], $add_classes));
  }

  // Process the classes to remove.
  if (!empty($classes[$hook]['remove'])) {
    $remove_classes = array_map('drupal_clean_css_identifier', $classes[$hook]['remove']);
    $variables['classes_array'] = array_diff($variables['classes_array'], $remove_classes);
  }

  // Since this runs after template_process(), we need to re-implode the
  // classes array.
  $variables['classes'] = implode(' ', $variables['classes_array']);
}

// -----------------------------------------------------------------------
// Menu callbacks that must be in the .module file.
/**
 * Determine if the current user has access via a plugin.
 *
 * This function is meant to be embedded in the Drupal menu system, and
 * therefore is in the .module file since sub files can't be loaded, and
 * takes arguments a little bit more haphazardly than ctools_access().
 *
 * @param $access
 *   An access control array which contains the following information:
 *   - 'logic': and or or. Whether all tests must pass or one must pass.
 *   - 'plugins': An array of access plugins. Each contains:
 *   - - 'name': The name of the plugin
 *   - - 'settings': The settings from the plugin UI.
 *   - - 'context': Which context to use.
 * @param ...
 *   zero or more context arguments generated from argument plugins. These
 *   contexts must have an 'id' attached to them so that they can be
 *   properly associated. The argument plugin system should set this, but
 *   if the context is coming from elsewhere it will need to be set manually.
 *
 * @return
 *   TRUE if access is granted, false if otherwise.
 */

function ctools_access_menu($access) {
  // Short circuit everything if there are no access tests.
  if (empty($access['plugins'])) {
    return TRUE;
  }

  $contexts = array();
  foreach (func_get_args() as $arg) {
    if (is_object($arg) && get_class($arg) == 'ctools_context') {
      $contexts[$arg->id] = $arg;
    }
  }

  ctools_include('context');
  return ctools_access($access, $contexts);
}

/**
 * Determine if the current user has access via checks to multiple different
 * permissions.
 *
 * This function is a thin wrapper around user_access that allows multiple
 * permissions to be easily designated for use on, for example, a menu callback.
 *
 * @param ...
 *   An indexed array of zero or more permission strings to be checked by
 *   user_access().
 *
 * @return bool
 *   Iff all checks pass will this function return TRUE. If an invalid argument
 *   is passed (e.g., not a string), this function errs on the safe said and
 *   returns FALSE.
 */
function ctools_access_multiperm() {
  foreach (func_get_args() as $arg) {
    if (!is_string($arg) || !user_access($arg)) {
      return FALSE;
    }
  }
  return TRUE;
}

/**
 * Check to see if the incoming menu item is js capable or not.
 *
 * This can be used as %ctools_js as part of a path in hook menu. CTools
 * ajax functions will automatically change the phrase 'nojs' to 'ajax'
 * when it attaches ajax to a link. This can be used to autodetect if
 * that happened.
 */
function ctools_js_load($js) {
  if ($js == 'ajax') {
    return TRUE;
  }
  return 0;
}

/**
 * Provides the default value for %ctools_js.
 *
 * This allows drupal_valid_path() to work with %ctools_js.
 */
function ctools_js_to_arg($arg) {
  return empty($arg) || $arg == '%' ? 'nojs' : $arg;
}

/**
 * Menu _load hook.
 *
 * This function will be called to load an object as a replacement for
 * %ctools_export_ui in menu paths.
 */
function ctools_export_ui_load($item_name, $plugin_name) {
  $return = &drupal_static(__FUNCTION__, FALSE);

  if (!$return) {
    ctools_include('export-ui');
    $plugin = ctools_get_export_ui($plugin_name);
    $handler = ctools_export_ui_get_handler($plugin);

    if ($handler) {
      return $handler->load_item($item_name);
    }
  }

  return $return;
}

// -----------------------------------------------------------------------
// Caching callbacks on behalf of export-ui.
/**
 * Menu access callback for various tasks of export-ui.
 */
function ctools_export_ui_task_access($plugin_name, $op, $item = NULL) {
  ctools_include('export-ui');
  $plugin = ctools_get_export_ui($plugin_name);
  $handler = ctools_export_ui_get_handler($plugin);

  if ($handler) {
    return $handler->access($op, $item);
  }

  // Deny access if the handler cannot be found.
  return FALSE;
}

/**
 * Callback for access control ajax form on behalf of export ui.
 *
 * Returns the cached access config and contexts used.
 * Note that this is assuming that access will be in $item->access -- if it
 * is not, an export UI plugin will have to make its own callbacks.
 */
function ctools_export_ui_ctools_access_get($argument) {
  ctools_include('export-ui');
  list($plugin_name, $key) = explode(':', $argument, 2);

  $plugin = ctools_get_export_ui($plugin_name);
  $handler = ctools_export_ui_get_handler($plugin);

  if ($handler) {
    ctools_include('context');
    $item = $handler->edit_cache_get($key);
    if (!$item) {
      $item = ctools_export_crud_load($handler->plugin['schema'], $key);
    }

    $contexts = ctools_context_load_contexts($item);
    return array($item->access, $contexts);
  }
}

/**
 * Callback for access control ajax form on behalf of export ui.
 *
 * Returns the cached access config and contexts used.
 * Note that this is assuming that access will be in $item->access -- if it
 * is not, an export UI plugin will have to make its own callbacks.
 */
function ctools_export_ui_ctools_access_set($argument, $access) {
  ctools_include('export-ui');
  list($plugin_name, $key) = explode(':', $argument, 2);

  $plugin = ctools_get_export_ui($plugin_name);
  $handler = ctools_export_ui_get_handler($plugin);

  if ($handler) {
    ctools_include('context');
    $item = $handler->edit_cache_get($key);
    if (!$item) {
      $item = ctools_export_crud_load($handler->plugin['schema'], $key);
    }
    $item->access = $access;
    return $handler->edit_cache_set_key($item, $key);
  }
}

/**
 * Implements hook_menu_local_tasks_alter().
 */
function ctools_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  ctools_include('menu');
  _ctools_menu_add_dynamic_items($data, $router_item, $root_path);
}

/**
 * Implements hook_block_list_alter().
 *
 * Used to potentially remove blocks.
 * This exists in order to replicate Drupal 6's "no blocks" functionality.
 */
function ctools_block_list_alter(&$blocks) {
  $check = drupal_static('ctools_set_no_blocks', TRUE);
  if (!$check) {
    foreach ($blocks as $block_id => $block) {
      // @todo -- possibly we can set configuration for this so that users can
      // specify which blocks will not get rendered.
      if (strpos($block->region, 'sidebar') !== FALSE) {
        unset($blocks[$block_id]);
      }
    }
  }
}

/**
 * Implements hook_modules_enabled().
 *
 * Clear caches for detecting new plugins.
 */
function ctools_modules_enabled($modules) {
  ctools_include('plugins');
  ctools_get_plugins_reset();
  cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
}

/**
 * Implements hook_modules_disabled().
 *
 * Clear caches for removing disabled plugins.
 */
function ctools_modules_disabled($modules) {
  ctools_include('plugins');
  ctools_get_plugins_reset();
  cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
}

/**
 * Menu theme callback.
 *
 * This simply ensures that Panels ajax calls are rendered in the same
 * theme as the original page to prevent .css file confusion.
 *
 * To use this, set this as the theme callback on AJAX related menu
 * items. Since the ajax page state won't be sent during ajax requests,
 * it should be safe to use even if ajax isn't invoked.
 */
function ctools_ajax_theme_callback() {
  if (!empty($_POST['ajax_page_state']['theme'])) {
    return $_POST['ajax_page_state']['theme'];
  }
}

/**
 * Implements hook_ctools_entity_context_alter().
 */
function ctools_ctools_entity_context_alter(&$plugin, &$entity, $plugin_id) {
  ctools_include('context');
  switch ($plugin_id) {
    case 'entity_id:taxonomy_term':
      $plugin['no ui'] = TRUE;
      break;

    case 'entity:user':
      $plugin = ctools_get_context('user');
      unset($plugin['no ui']);
      unset($plugin['no required context ui']);
      break;
  }

  // Apply restrictions on taxonomy term reverse relationships whose
  // restrictions are in the settings on the field.
  if (!empty($plugin['parent']) &&
      $plugin['parent'] == 'entity_from_field' &&
      !empty($plugin['reverse']) &&
      $plugin['to entity'] == 'taxonomy_term') {
    $field = field_info_field($plugin['field name']);
    if (isset($field['settings']['allowed_values'][0]['vocabulary'])) {
      $plugin['required context']->restrictions = array('vocabulary' => array($field['settings']['allowed_values'][0]['vocabulary']));
    }
  }
}

/**
 * Implements hook_field_create_field().
 */
function ctools_field_create_field($field) {
  ctools_flush_field_caches();
}

/**
 * Implements hook_field_create_instance().
 */
function ctools_field_create_instance($instance) {
  ctools_flush_field_caches();
}

/**
 * Implements hook_field_delete_field().
 */
function ctools_field_delete_field($field) {
  ctools_flush_field_caches();
}

/**
 * Implements hook_field_delete_instance().
 */
function ctools_field_delete_instance($instance) {
  ctools_flush_field_caches();
}

/**
 * Implements hook_field_update_field().
 */
function ctools_field_update_field($field, $prior_field, $has_data) {
  ctools_flush_field_caches();
}

/**
 * Implements hook_field_update_instance().
 */
function ctools_field_update_instance($instance, $prior_instance) {
  ctools_flush_field_caches();
}

/**
 * Clear field related caches.
 */
function ctools_flush_field_caches() {
  // Clear caches of 'Entity field' content type plugin.
  cache_clear_all('ctools_entity_field_content_type_content_types', 'cache');
}
