<?php

/**
 * @file
 * Allows to use PHP in views.
 */

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

/**
 * Menu access callback function; use PHP code to determine whether a user as
 * access.
 */
function views_php_check_access($php_access, $view_name, $display_id, $account = NULL) {
  global $user;
  static $function = array();

  if (!isset($account)) {
    $account = $user;
  }

  if (!isset($function[$view_name . ':' . $display_id])) {
    $function[$view_name . ':' . $display_id] = create_function('$view_name, $display_id, $account', $php_access . ';');
  }

  ob_start();
  $access = (bool) $function[$view_name . ':' . $display_id]($view_name, $display_id, $account);
  ob_end_clean();
  return $access;
}

/**
 * Helper function; builds form for PHP code options of views handlers/plugins.
 */
function views_php_form_element($handler, $checkbox = FALSE, $input, $variables = array()) {
  static $default_variables;
  if (!isset($default_variables)) {
    $default_variables = array(
      '$view'    => t('The view object.'),
      '$handler' => t('The handler object.'),
      '$plugin'  => t('The plugin object.'),
      '$static'  => t('A variable that can be used to store reusable data per row.'),
      '$row'     => t('Contains the retrieved record from the database (e.g. $data->nid).'),
      '$data'    => t('Contains the retrieved record from the database (e.g. $data->nid).'),
      '$results' => t('Array containing the view\'s result.'),
      '$cache'   => t('The cache object.'),
    );
  }

  list($name, $title, $description, $use_delimiters) = $input;
  $container = array(
    '#type' => 'container',
    // @todo #tree => FALSE doesn't work here.
    '#parents' => array('options'),
  );

  if (!empty($checkbox)) {
    list($checkbox_name, $checkbox_title, $checkbox_description) = $checkbox;
    $checkbox = array(
      '#type' => 'checkbox',
      '#title' => $checkbox_title,
      '#description' => $checkbox_description,
      '#default_value' => $handler->options[$checkbox_name] && !empty($handler->options[$name]),
    );
    $container['#states'] = array(
      'invisible' => array(
        'input[name="options[use_' . $name . ']"]' => array('checked' => FALSE),
      ),
    );
  }
  $container[$name] = array(
    '#type' => 'textarea',
    '#id' => drupal_html_id('edit-options-' . $name),
    '#title' => $title,
    '#default_value' => $handler->options[$name],
    '#rows' => 5,
    '#description' => $description . ' <strong>' . ($use_delimiters
      ? t('Use &lt;?php ?&gt; delimiters to enclose PHP code.')
      : t('Do not use &lt;?php ?&gt; delimiters.'))
      . '</strong>',
  );
  // Only users with use PHP permission can set/modify input.
  if (!user_access('use PHP for settings')) {
    $container[$name]['#disabled'] = TRUE;
    $container[$name]['#value'] = $container[$name]['#default_value'];
    $container[$name]['#description'] .= ' <strong>' . t('You do not have permission to modify this.') . '</strong>';
  }

  $items = array();
  foreach ($variables as $variable_name => $description) {
    if (is_int($variable_name)) {
      $variable_name = $description;
      $description = isset($default_variables[$description]) ? $default_variables[$description] : '';
    }
    $items[] = l($variable_name, '', array('fragment' => $container[$name]['#id'], 'external' => TRUE)) . ': ' . $description;

    if (strpos($variable_name, '$row') === 0) {
      foreach ($handler->view->display_handler->get_handlers('field') as $field => $field_handler) {
        $items[] = l($variable_name . '->' . $field, '', array('fragment' => $container[$name]['#id'], 'external' => TRUE)) . ': ' . $field_handler->ui_name();
      }
    }
  }
  $container[$name . '_variables'] = array(
    '#type' => 'fieldset',
    '#title' => t('Available variables'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#attributes' => array('class' => array('views-php-variables')),
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'views_php') . '/views_php.js'),
    )
  );
  $container[$name . '_variables']['variables'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
  );

  if (!empty($checkbox)) {
    return array($checkbox_name => $checkbox, $name => $container);
  }
  return array($name => $container);
}

/**
 * Implements hook_views_pre_execute().
 */
function views_php_views_pre_execute($view) {
  // Seize control over the query plugin if a views handler requested so.
  if (!empty($view->views_php)) {
    $query = new views_php_plugin_query();
    $query->php_wrap($view->query);
  }
}

/**
 * Implements hook_views_post_execute().
 */
function views_php_views_post_execute($view) {
  // Restore original query plugin if it was wrapped.
  if ($view->query instanceof views_php_plugin_wrapper) {
    $view->query->php_unwrap();
  }
}
