<?php

/**
 * Implementation of hook_permissions().
 */
function page_manager_pathauto_permissions() {
  return array(
    'manage page_manager aliases' => array(
      'title' => t('Administer Page Manage Page Aliases'), 
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implementation of hook_page_manager_variant_operations_alter().
 *
 * Adds a custom administrative interface per variant for creating path
 * aliases.
 */
function page_manager_pathauto_page_manager_variant_operations_alter(&$operations, &$handler) {
  if ($handler->task == 'page' && user_access('manage page_manager aliases')) {
    $keys = array_keys($operations['children']);
    $before = array_slice($operations['children'], 0, array_search('settings', $keys) +1);
    $after = array_slice($operations['children'], array_search('settings', $keys) + 1);
    $pathauto = array(
      'pathauto' => array (
        'title' => t('Pathauto Alias'),
        'description' => t('Allow a given variant to provide a path alias for its specific menu items.'),
        'form' => 'page_manager_pathauto_subtask_form',
      ),
    );
    $operations['children'] = array_merge($before, $pathauto, $after);
  }
}

/**
 * Form callback for the administrative interface to add path aliases.
 */
function page_manager_pathauto_subtask_form($form, $form_state) {
  ctools_include('context-task-handler');
  $contexts = ctools_context_handler_get_all_contexts($form_state['task'], $form_state['subtask'], $form_state['handler']);
  $conf = $form_state['handler']->conf;
  unset($form_state['page']);
  $form['conf']['pathalias'] = array(
    '#title' => t('@title: Pathauto Alias', array('@title' => $conf['title'])),
    '#type' => 'textfield',
    '#default_value' => isset($conf['pathalias']) ? $conf['pathalias'] : NULL,
  );
  $rows = array();
  foreach ($contexts as $context) {
    $context = (object) $context;
    foreach (ctools_context_get_converters('%' . check_plain($context->keyword) . ':', $context) as $keyword => $title) {
      $rows[] = array(
        check_plain($keyword),
        t('@identifier: @title', array('@title' => $title, '@identifier' => $context->identifier)),
      );
    }
  }

  $header = array(t('Keyword'), t('Value'));
  $form['substitutions'] = array(
    '#type' => 'fieldset',
    '#title' => t('Substitutions'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#value' => theme('table', array('header' => $header, 'rows' => $rows)),
  );
  return $form;
}

/**
 * Form validation callback.
 */
function page_manager_pathauto_subtask_form_validate(&$form, &$form_state) {
  $alias = $form_state['values']['pathalias'];
  $alias = str_replace('%', '', $alias);
  if (!preg_match('|^[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $alias)) {
    form_set_error('pathalias', t('You must submit a valid url string.'));
  }
}

/**
 * Form submit callback.
 */
function page_manager_pathauto_subtask_form_submit($form, &$form_state) {
  $form_state['handler']->conf['pathalias'] = $form_state['values']['pathalias'];
}

/**
 * Since page_manager pages can be very convoluted and don't necessarily
 * require an entity as an argument, determining all aliases for a page can be
 * quite complex. This alter will populate aliases as pages are visited as a
 * final fallback for all other attempts at aliasing pages.
 *
 * This only works against pages that don't already have an alias.
 */
function page_manager_pathauto_ctools_render_alter($info, $page, $context) {
  global $language;
  $lang_name = $language->language;
  module_load_include('inc', 'pathauto');
  $page_manager_process = (current_path() == request_path());
  $drush_task = drupal_static('drush_page_manager_pathauto_subtask_alias_generate');
  if (($page_manager_process || $drush_task) && !_pathauto_existing_alias_data(current_path(), $lang_name)) {
    $conf = $context['handler']->conf;
    if (isset($conf['pathalias']) && $conf['pathalias']) {
      ctools_include('context');
      $handler = $context['handler'];
      $contexts = $context['contexts'];
      $object = ctools_context_handler_get_handler_object($handler);
      $contexts = ctools_context_load_contexts($object, FALSE, $contexts);

      $alias = ctools_context_keyword_substitute($conf['pathalias'], array(), $contexts);
      $new_alias = array();
      foreach (explode('/', $alias) as $string) {
        $new_alias[] = pathauto_cleanstring($string);
      }
      $new_alias = implode('/', $new_alias);
      $existing_alias = _pathauto_existing_alias_data($alias['source']);
      if (!$existing_alias) {
        $existing_alias = NULL;
      }
      pathauto_alias_uniquify($new_alias, current_path(), $lang_name);
      $alias = array(
        'source' => current_path(),
        'alias' => $new_alias,
        'language' => $lang_name,
      );
      _pathauto_set_alias($alias, $existing_alias);
    }
  }
}

/**
 * Implementation of hook_ctools_plugin_directory().
 */
function page_manager_pathauto_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager_pathauto') {
    return 'plugins/' . $plugin_type;
  }
}

/**
 * Implementation of hook_ctools_plugin_type().
 */
function page_manager_pathauto_ctools_plugin_type() {
  return array(
    'context_indexes' => array(
      'child plugins' => TRUE,
    ),
  );
}
