<?php
// $Id: bueditor.module,v 1.14.2.10 2009/06/24 12:28:43 ufku Exp $

/**
 * Implementation of hook_menu().
 */
function bueditor_menu() {
  $items = array();
  $path = 'admin/settings/bueditor';
  $access = array('administer bueditor');
  $items[$path] = array(
    'title' => 'BUEditor',
    'description' => 'Customize your text editor.',
    'page callback' => 'bueditor_admin',
    'access arguments' => $access,
    'file' => 'bueditor.admin.inc',
  );
  $items[$path .'/new'] = array(
    'title' => 'Add new editor',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bueditor_editor_form'),
    'access arguments' => $access,
    'type' => MENU_CALLBACK,
    'file' => 'bueditor.admin.inc',
  );
  $items[$path .'/%bueditor_editor'] = array(
    'title' => 'Editor settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bueditor_editor_form', 3),
    'access arguments' => $access,
    'type' => MENU_CALLBACK,
    'file' => 'bueditor.admin.inc',
  );
  $items[$path .'/%bueditor_editor/delete'] = array(
    'title' => 'Delete editor',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bueditor_delete_form', 3),
    'access arguments' => $access,
    'type' => MENU_CALLBACK,
    'file' => 'bueditor.admin.inc',
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function bueditor_perm() {
  return array('administer bueditor');
}

/**
 * Implementation of hook_theme().
 */
function bueditor_theme() {
  $theme['bueditor_admin']['function'] = 'bueditor_admin_theme';
  $theme['bueditor_editor']['function'] = 'bueditor_editor_theme';
  return $theme;
}

/**
 * Editor(s).
 */
function bueditor_editors($eid = 0) {
  static $editors = array(), $gotall = FALSE;
  if ($eid == 'all') {
    if (!$gotall) {
      $gotall = TRUE;
      $result = db_query("SELECT * FROM {bueditor_editors}");
      while ($editor = db_fetch_object($result)) {
        $editors[$editor->eid] = $editor;
      }
    }
    return $editors;
  }
  else if ($eid && !$gotall && !isset($editors[$eid])) {
    $editors[$eid] = db_fetch_object(db_query("SELECT * FROM {bueditor_editors} WHERE eid = %d", $eid));
  }
  return $editors[$eid];
}

/**
 * All buttons of an editor.
 */
function bueditor_buttons($eid) {
  $buttons = array();
  if ($eid) {
    $result = db_query("SELECT * FROM {bueditor_buttons} WHERE eid = %d ORDER BY weight, title", $eid);
    while ($button = db_fetch_object($result)) {
      $buttons[$button->bid] = $button;
    }
  }
  return $buttons;
}

/**
 * Processed buttons. Evaluate php code for php buttons and translate titles prefixed with t:.
 */
function bueditor_processed_buttons($eid) {
  $buttons = array();
  foreach (bueditor_buttons($eid) as $bid => $button) {
    if (substr($button->content, 0, 4) == 'php:') {
      if ($content = drupal_eval('<?php '. substr($button->content, 4) .' ?>')) {
        $button->content = $content;
      }
      else {//php returned false or nothing. dont include this button.
        continue;
      }
    }
    $button->title = substr($button->title, 0, 2) == 't:' ? t(trim(substr($button->title, 2))) : $button->title;
    $buttons[] = array($button->title, $button->content, $button->icon, $button->accesskey);
  }
  return $buttons;
}

/**
 * Implementation of hook_elements().
 */
function bueditor_elements() {
  return array('textarea' => array('#process' => array('bueditor_textarea')));
}

/**
 * Integrate the editor into textareas.
 */
function bueditor_textarea($element) {
  static $editors, $textareas = array();

  if (isset($textareas[$element['#id']])) {
    return $element;
  }
  $textareas[$element['#id']] = 1;

  //get editors
  if (!isset($editors)) {
    $editors = bueditor_user_eids($GLOBALS['user']);
    $editors[0] = bueditor_check_page($_GET['q'], $editors[0]);
  }

  //if the first editor does not settle try the second.
  if (!bueditor_preset_textarea($element['#id'], $editors[0]) && $editors[1]) {
    if (!isset($editors[1]->eid)) {
      $editors[1] = bueditor_check_page($_GET['q'], $editors[1]);
    }
    bueditor_preset_textarea($element['#id'], $editors[1]);
  }

  return $element;
}

/**
 * Insert textarea id into preset of the editor.
 */
function bueditor_preset_textarea($tid, $editor) {
  if ($editor && !bueditor_check_match($editor->excludes, $tid)) {
    bueditor_settle($editor);
    $settings['BUE']['preset'][$tid] = 'e'. $editor->eid;
    drupal_add_js($settings, 'setting');
    return TRUE;
  }
  return FALSE;
}

/**
 * Include necessary js and css files for editor settlement.
 */
function bueditor_settle($editor) {
  static $settled = array();
  if (is_numeric($editor)) {
    $editor = bueditor_editors($editor);
  }
  if ($editor && $editor->eid && !isset($settled[$editor->eid])) {
    $path = drupal_get_path('module', 'bueditor');
    $editor->librarypath = bueditor_path_tr($editor->librarypath);
    $editor->iconpath = bueditor_path_tr($editor->iconpath);
    drupal_add_css($path .'/bueditor.css');
    drupal_add_js($path .'/bueditor.js');
    bueditor_js_library($editor->librarypath);//load library files.
    $settings['BUE']['templates']['e'. $editor->eid] = array(
      'iconpath' => base_path() . $editor->iconpath,
      'buttons' => bueditor_processed_buttons($editor->eid),
    );
    drupal_add_js($settings, 'setting');
    $settled[$editor->eid] = TRUE;
    return TRUE;
  }
  return FALSE;
}

/**
 * Include all javascript files from library.
 */
function bueditor_js_library($path) {
  static $paths = array();
  if ($path && !isset($paths[$path])) {
    if ($handle = opendir($path)) {
      while (($file = readdir($handle)) !== FALSE) {
        if (substr($file, -3) == '.js') {
          drupal_add_js($path .'/'. $file);
        }
      }
      closedir($handle);
    }
    $paths[$path] = TRUE;
  }
}

/**
 * Return the editor ids assigned to the user.
 */
function bueditor_user_eids($user) {
  //user #1
  if ($user->uid == 1) {
    return array(variable_get('bueditor_user1', 1), variable_get('bueditor_user1_alt', 0));
  }
  $roles = variable_get('bueditor_roles', array());
  //anonymous user
  if (!$user->uid) {
    return array($roles[DRUPAL_ANONYMOUS_RID]['editor'], $roles[DRUPAL_ANONYMOUS_RID]['alt']);
  }
  //other users
  foreach ($roles as $rid => $role) {
    if (isset($user->roles[$rid])) {
      return array($role['editor'], $role['alt']);
    }
  }
}

/**
 * Check if the editor is visible in the page.
 */
function bueditor_check_page($page, $eid) {
  $editor = is_numeric($eid) ? bueditor_editors($eid) : $eid;
  if ($editor) {
    if (drupal_match_path($page, $editor->pages)) {
      return $editor;
    }
    $alias = drupal_get_path_alias($page);
    if ($alias != $page && drupal_match_path($alias, $editor->pages)) {
      return $editor;
    }
    if (arg(0) == 'node' && arg(2) == 'edit') {
      $node = node_load(arg(1));
      if ($node && strpos($editor->pages, 'node/add/'.  $node->type) !== FALSE) {
        return $editor;
      }
    }
  }

  return FALSE;
}

/**
 * Check matching lines of the needle in haystack.(page and textarea id)
 */
function bueditor_check_match($needle, $haystack) {
  if ($needle == '') {
    return FALSE;
  }
  $needle = '/^'. preg_replace("/\r\n?|\n/", '|', str_replace(array('*', '-', '/'), array('.*', '\\-', '\\/'), trim($needle))) .'$/';
  return preg_match($needle, $haystack);
}

/**
 * Translate editor paths
 */
function bueditor_path_tr($path) {
  if (!$path) {
    return $path;
  }
  static $tokens;
  if (!isset($tokens)) {
    $tokens = array(
      '%BUEDITOR' => drupal_get_path('module', 'bueditor'),
      '%FILES' => file_directory_path(),
      '%THEME' => path_to_theme()
    );
  }
  $dir = strtr($path, $tokens);
  //for themes missing icon or library directory, switch to default theme.
  if (!is_dir($dir) && substr($path, 0, 2) == '%T') {
    return str_replace('%THEME', drupal_get_path('theme', variable_get('theme_default', 'garland')), $path);
  }
  return $dir;
}

/**
 * load editor by id. used by menu system
 */
function bueditor_editor_load($eid) {
  return bueditor_editors($eid);
}