<?php

/**
 * Implementation of hook_help().
 */
function find_path_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Adds a "Find alias" tab to "URL alias admin" page.');
      break;
  }
}

/**
 * Implementation of hook_menu().
 */
function find_path_menu($may_cache) {
  global $user;
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/build/path/find',
      'title' => t('Find alias'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('find_path_page'),
      'access' => user_access('administer url aliases'),
      'type' => MENU_LOCAL_TASK,
    );
  }
  return $items;
}

function find_path_page() {
  $form = array();
  $form['path'] = array(
    '#type' => 'textfield',
    '#title' => t('Aliased path (you can use % as a wildcard)'),
    '#size' => 60,
  );
  $form['exact'] = array(
    '#type' => 'checkbox',
    '#title' => t('Exact Match?'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find All'),
  );
  return $form;
}


function find_path_page_submit($form_id, $form_values) {
  $path = $form_values['path'];
  $exact = $form_values['exact'];

  $form = drupal_retrieve_form( 'find_path_page' );
  drupal_prepare_form( 'find_path_page', $form );
  $output .= drupal_render_form( 'find_path_page', $form );
  $output .= find_path_results($path, $exact);
  print theme( 'page', $output );
  exit; // need to exit to avoid "cannot modify header" error
}


function theme_find_path_page($form) {
  $path = $form['path']['#value'];
  $exact = $form['exact']['#value'];

  $row = array();
  $row[] = drupal_render( $form['path'] );
  $row[] = drupal_render( $form['exact'] );
  $row[] = drupal_render( $form['submit'] );
  $output =  theme('table', array(), array($row) );
  $output .= '<br />';
  $output .= drupal_render( $form );
  return $output;
}


function find_path_results( $path, $exact ) {
//  drupal_set_title("Looking for alias: '$path'");
  drupal_set_title(t('Looking for alias: %path', array('%path' => $path)));
  if( empty($path) ) {
    return;
  }
  $admin_path = 'admin/build';
  $found = array();
  if( !$exact ) {
    $path = "%$path%";
  }

  // #1: look for nodes and taxonomies
  $result = db_query("SELECT src, pid, dst FROM {url_alias} WHERE dst LIKE '%s'", $path);

  while ($url = db_fetch_array($result)) {
    // list all the aliases for this path
    $aliases = array();
    $results = db_query("SELECT dst, pid FROM {url_alias} WHERE src='%s'", $url['src']);
    while ($alias = db_fetch_array($results)) {
      $aliases[] = array(
/*
      '', 
      '<b>'. $alias['dst'] .'</b>', 
      'Alias of '. $url['src'],
      '',
      l('Edit Alias', "$admin_path/path/edit/". $alias['pid']),
      l('Delete Alias', "$admin_path/path/delete/". $alias['pid'])
*/      
        '<strong>'. $alias['dst'] .'</strong>', 
        t('Alias of @url', array('@url' => $url['src'])),
        l(t('Edit Alias'), "$admin_path/path/edit/". $alias['pid']),
        l(t('Delete Alias'), "$admin_path/path/delete/". $alias['pid']),
      );
    }
    if ( preg_match( '/node\/\d+/', $url['src'] ) ) {
      $title = array(
        $url['dst'],
        $url['src'],
        l(t('View Node'), $url['src']),
        l(t('Edit Node'), $url['src'] .'/edit'),
      );
    }
    else {
      $title = array($url['dst'], $url['src'], '', '');
    }
    $found[] = array( 'title' => $title, 'aliases' => $aliases );
  }

  // #2: look for aliases managed by panels
  if (module_exists('panels')) {
    if (db_table_exists('panels_page')) { // Panels 2
      $result = db_query("SELECT did, title, path FROM {panels_page} WHERE path LIKE '%s'", $path);
    }
    else { // Panels 1
      $result = db_query("SELECT did, title, path FROM {panels_info} WHERE path LIKE '%s'", $path);
    }
    while ($panel = db_fetch_array($result)) {
      $found[] = array( 'title' => array (
        $panel['path'],
        $panel['title'],
        l(t('View Panel'), $panel['path']),
        l(t('Edit Panel'), "$admin_path/panels/edit/". $panel['did'])
      ));
    }
  }

  // #3: look for aliases managed by views
  if (module_exists('views')) {
    $result = db_query("SELECT vid, name, url FROM {view_view} WHERE url LIKE '%s'", $path);
    while ($view = db_fetch_array($result)) {
      $found[] = array( 'title' => array (
        $view['url'],
        $view['name'],
        l(t('View View'), $view['url']),
        l(t('Edit View'), "$admin_path/views/edit/". $view['vid'])
      ));
    }
  }

  if( count($found) ) {
    sort($found);
    foreach( $found as $item ) {
      $fs['#title'] = '<strong>'. array_shift( $item['title'] ) .'</strong> : ' . implode( ' : ', $item['title'] );
      if( !empty($item['aliases']) ) {
        $fs['#children'] = theme('table', array(), $item['aliases']);
      }
      $results .= theme('fieldset', $fs );
    }
  }
  else {
    $results = t('Alias Not Found');
  }
  return $results;
}
