<?php

/**
 * @file
 * Integrates client-side editors with Drupal.
 */
require_once 'includes/styling.inc';

/**
 * Implements hook_entity_info().
 */
function wysiwyg_entity_info() {
  $types['wysiwyg_profile'] = array(
    'label' => t('Wysiwyg profile'),
    'base table' => 'wysiwyg',
    'controller class' => 'WysiwygProfileController',
    'fieldable' => FALSE,
    // When loading all entities, DrupalDefaultEntityController::load() ignores
    // its static cache. Therefore, wysiwyg_profile_load_all() implements a
    // custom static cache.
    'static cache' => FALSE,
    'entity keys' => array(
      'id' => 'format',
    ),
  );
  return $types;
}

/**
 * Controller class for Wysiwyg profiles.
 */
class WysiwygProfileController extends DrupalDefaultEntityController {
  /**
   * Overrides DrupalDefaultEntityController::attachLoad().
   */
  function attachLoad(&$queried_entities, $revision_id = FALSE) {
    // Unserialize the profile settings.
    foreach ($queried_entities as $key => $record) {
      $settings = unserialize($record->settings);
      // Profile preferences are stored with the editor settings to avoid adding
      // an extra table column.
      if (isset($settings['_profile_preferences'])) {
        $preferences = $settings['_profile_preferences'];
        unset($settings['_profile_preferences']);
      }
      else {
        $preferences = array();
      }
      $queried_entities[$key]->settings = $settings;
      $queried_entities[$key]->preferences = $preferences;
      // @todo Store the name in the profile when allowing more than one per
      // format.
      $queried_entities[$key]->name = 'format' . $record->format;
    }
    // Call the default attachLoad() method.
    parent::attachLoad($queried_entities, $revision_id);
  }
}

/**
 * Implementation of hook_menu().
 */
function wysiwyg_menu() {
  $items['admin/config/content/wysiwyg'] = array(
    'title' => 'Wysiwyg profiles',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wysiwyg_profile_overview'),
    'description' => 'Configure client-side editors.',
    'access arguments' => array('administer filters'),
    'file' => 'wysiwyg.admin.inc',
  );
  $items['admin/config/content/wysiwyg/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/content/wysiwyg/profile/%wysiwyg_ui_profile_cache'] = array(
    'title callback' => 'wysiwyg_admin_profile_title',
    'title arguments' => array(5),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wysiwyg_profile_form', 5),
    'access arguments' => array('administer filters'),
    'file' => 'wysiwyg.admin.inc',
  );
  $items['admin/config/content/wysiwyg/profile/%wysiwyg_ui_profile_cache/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/content/wysiwyg/profile/%wysiwyg_ui_profile_cache/delete'] = array(
    'title' => 'Remove',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wysiwyg_profile_delete_confirm', 5),
    'access arguments' => array('administer filters'),
    'file' => 'wysiwyg.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
  $items['admin/config/content/wysiwyg/profile/%wysiwyg_ui_profile_cache/break-lock'] = array(
    'title' => 'Break lock',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wysiwyg_profile_break_lock_confirm', 5),
    'access arguments' => array('administer filters'),
    'file' => 'wysiwyg.admin.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
  );
  // @see wysiwyg_dialog()
  $items['wysiwyg/%'] = array(
    'page callback' => 'wysiwyg_dialog',
    'page arguments' => array(1),
    'delivery callback' => 'wysiwyg_deliver_dialog_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'wysiwyg.dialog.inc',
  );
  $items['wysiwyg_theme/%'] = array(
    'theme callback' => '_wysiwyg_theme_callback',
    'theme arguments' => array(1),
    'page callback' => '_wysiwyg_theme_check_active',
    'page arguments' => array(1),
    'delivery callback' => '_wysiwyg_delivery_dummy',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['wysiwyg/xss'] = array(
    'title' => 'XSS Filter',
    'description' => 'XSS Filter.',
    'page callback' => 'wysiwyg_filter_xss_page_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Display an editor profile title.
 *
 * @param $profile
 *   An editor profile object.
 *
 * @return
 *   The unfiltered name of an editor profile.
 *   Currently the same as the text format name.
 */
function wysiwyg_admin_profile_title($profile) {
  $format = filter_format_load($profile->format);
  return $format->name;
}

/**
 * Implements hook_admin_menu_map().
 */
function wysiwyg_admin_menu_map() {
  if (!user_access('administer filters')) {
    return;
  }

  $profiles = wysiwyg_profile_load_all();
  $map['admin/config/content/wysiwyg/profile/%wysiwyg_ui_profile_cache'] = array(
    'parent' => 'admin/config/content/wysiwyg',
    'hide' => 'admin/config/content/wysiwyg/list',
    'arguments' => array(
      array('%wysiwyg_ui_profile_cache' => array_keys($profiles)),
    ),
  );
  return $map;
}

/**
 * Implements hook_element_info().
 */
function wysiwyg_element_info() {
  // @see wysiwyg_dialog()
  $types['wysiwyg_dialog_page'] = array(
    '#theme' => 'wysiwyg_dialog_page',
    '#theme_wrappers' => array('html'),
    '#show_messages' => TRUE,
  );
  return $types;
}

/**
 * Implementation of hook_theme().
 *
 * @see drupal_common_theme(), common.inc
 * @see template_preprocess_page(), theme.inc
 */
function wysiwyg_theme() {
  return array(
    'wysiwyg_profile_overview' => array(
      'render element' => 'form',
    ),
    'wysiwyg_admin_button_table' => array(
      'render element' => 'form',
    ),
    // @see wysiwyg_dialog()
    'wysiwyg_dialog_page' => array(
      'render element' => 'page',
      'file' => 'wysiwyg.dialog.inc',
      'template' => 'wysiwyg-dialog-page',
    ),
  );
}

/**
 * Implementation of hook_help().
 */
function wysiwyg_help($path, $arg) {
  switch ($path) {
    case 'admin/config/content/wysiwyg':
      $output = '<p>' . t('A Wysiwyg profile is associated with a text format. A Wysiwyg profile defines which client-side editor is loaded with a particular text format, what buttons or themes are enabled for the editor, how the editor is displayed, and a few other editor-specific functions.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_element_info_alter().
 */
function wysiwyg_element_info_alter(&$types) {
  $types['text_format']['#pre_render'][] = 'wysiwyg_pre_render_text_format';
  // For filtering stylesheets before Core aggregates them.
  array_unshift($types['styles']['#pre_render'], '_wysiwyg_filter_editor_styles');
  // For recording and caching the added stylesheets.
  $types['styles']['#pre_render'][] = '_wysiwyg_pre_render_styles';
}


/**
 * Process a text format widget to load and attach editors.
 *
 * The element's #id is used as reference to attach client-side editors.
 */
function wysiwyg_pre_render_text_format($element) {
  global $user;
  static $is_running = FALSE;
  // filter_process_format() copies properties to the expanded 'value' child
  // element. Skip this text format widget, if it contains no 'format' or when
  // the current user does not have access to edit the value.
  // Simplify module creates an extra incomplete 'format' on the base field.
  if (!isset($element['format']['format']) || !empty($element['value']['#disabled'])) {
    return $element;
  }
  // Allow modules to programmatically enforce no client-side editor by setting
  // the #wysiwyg property to FALSE.
  if (isset($element['#wysiwyg']) && !$element['#wysiwyg']) {
    return $element;
  }

  $format_field = &$element['format'];
  $field = &$element['value'];
  $settings = array(
    'field' => $field['#id'],
  );

  // If this textarea is #resizable the 'none' editor will attach/detach it to
  // avoid hi-jacking the UI.
  if (!empty($field['#resizable'])) {
    $settings['resizable'] = 1;
  }
  if (isset($element['summary']) && $element['summary']['#type'] == 'textarea') {
    $settings['summary'] = $element['summary']['#id'];
  }

  if (!$format_field['format']['#access'] || (isset($format_field['#access']) && !$format_field['#access'])) {
    // Directly specify which the single available format is.
    $available_formats = array($format_field['format']['#value'] => $format_field['format']['#options'][$format_field['format']['#value']]);
    $settings['activeFormat'] = $format_field['format']['#value'];
  }
  else {
    // Let the client check the selectbox for the active format.
    $available_formats = $format_field['format']['#options'];
    $settings['select'] = $format_field['format']['#id'];
  }
  // Determine the available text formats.
  foreach ($available_formats as $format_id => $format_name) {
    $format = 'format' . $format_id;

    // Fetch the profile associated to this text format.
    $profile = wysiwyg_get_profile($format_id);
    if ($profile) {
      // Initialize default settings, defaulting to 'none' editor.
      $settings[$format] = array(
        'editor' => 'none',
        'status' => 1,
        'toggle' => 1,
      );
      $loaded = TRUE;
      if (isset($profile->preferences['add_to_summaries']) && !$profile->preferences['add_to_summaries']) {
        $settings[$format]['skip_summary'] = 1;
      }
      $settings[$format]['editor'] = $profile->editor;
      $settings[$format]['status'] = (int) wysiwyg_user_get_status($profile);
      if (isset($profile->preferences['show_toggle'])) {
        $settings[$format]['toggle'] = (int) $profile->preferences['show_toggle'];
      }
      if (!$is_running) {
        // By default sessions are not started automatically for anonymous
        // users. Start one for editing content so that we have a consistent
        // token that is used in XSS filtering.
        if (empty($user->uid)) {
          drupal_session_start();
          $_SESSION['wysiwyg_anonymous_user'] = TRUE;
          drupal_page_is_cacheable(FALSE);
        }
        $is_running = TRUE;
      }
      // Check editor theme (and reset it if not/no longer available).
      $theme = wysiwyg_get_editor_themes($profile, (isset($profile->settings['theme']) ? $profile->settings['theme'] : ''));

      // Add plugin settings (first) for this text format.
      wysiwyg_add_plugin_settings($profile);
      // Add profile settings for this text format.
      wysiwyg_add_editor_settings($profile, $theme);
    }
  }

  $format = filter_format_load($format_field['format']['#value']);
  $active_format = 'format' . $format_field['format']['#value'];
  $enabled = !empty($settings[$active_format]) && $settings[$active_format]['editor'] !== 'none' && !empty($settings[$active_format]['status']);
  // Store the unaltered content so it can be restored if no changes
  // intentionally made by the user were detected, such as those caused by
  // WYSIWYG editors when initially parsing and loading content.
  if (!empty($element['value']['#value'])) {
    $original = $element['value']['#value'];
    $element['value']['#attributes']['data-wysiwyg-value-original'] = $original;
    $element['value']['#attributes']['data-wysiwyg-value-is-changed'] = 'false';
    if ($enabled) {
      $filtered = wysiwyg_filter_xss($original, $format);
      if ($filtered !== FALSE) {
        $element['value']['#attributes']['data-wysiwyg-value-filtered'] = $filtered;
      }
    }
  }
  if (!empty($element['summary']['#value']) && $element['summary']['#type'] === 'textarea') {
    $original = $element['summary']['#value'];
    $element['summary']['#attributes']['data-wysiwyg-value-original'] = $original;
    $element['summary']['#attributes']['data-wysiwyg-value-is-changed'] = 'false';
    if ($enabled && empty($settings[$active_format]['skip_summary'])) {
      $filtered = wysiwyg_filter_xss($original, $format);
      if ($filtered !== FALSE) {
        $element['summary']['#attributes']['data-wysiwyg-value-filtered'] = $filtered;
      }
    }
  }

  $element['value']['#attributes']['class'][] = 'wysiwyg';
  $element['#attached']['js'][] = array(
    'data' => array(
      'wysiwyg' => array(
        'triggers' => array(
          $element['value']['#id'] => $settings,
        ),
      ),
    ),
    'type' => 'setting',
  );
  return $element;
}

/**
 * Determine the profile to use for a given input format id.
 *
 * This function also performs sanity checks for the configured editor in a
 * profile to ensure that we do not load a malformed editor.
 *
 * @param $format
 *   The internal id of an input format.
 *
 * @return
 *   A wysiwyg profile.
 *
 * @see wysiwyg_load_editor(), wysiwyg_get_editor()
 */
function wysiwyg_get_profile($format) {
  if ($profile = wysiwyg_profile_load($format)) {
    if (wysiwyg_load_editor($profile)) {
      return $profile;
    }
  }
  return FALSE;
}

/**
 * Load an editor library and initialize basic Wysiwyg settings.
 *
 * @param $profile
 *   A wysiwyg editor profile.
 *
 * @return
 *   TRUE if the editor has been loaded, FALSE if not.
 *
 * @see wysiwyg_get_profile()
 */
function wysiwyg_load_editor($profile) {
  static $settings_added;
  static $loaded = array();
  $path = drupal_get_path('module', 'wysiwyg');

  $name = $profile->editor;
  // Library files must be loaded only once.
  if (!isset($loaded[$name])) {
    // Load editor.
    $editor = wysiwyg_get_editor($name);
    if ($editor) {
      $default_library_options = array(
        'type' => 'file',
        'scope' => 'header',
        'defer' => FALSE,
        'cache' => TRUE,
        'preprocess' => TRUE,
      );
      // Determine library files to load.
      // @todo Allow to configure the library/execMode to use.
      if (isset($profile->preferences['library']) && isset($editor['libraries'][$profile->preferences['library']])) {
        $library = $profile->preferences['library'];
        $files = $editor['libraries'][$library]['files'];
      }
      else {
        // Fallback to the first defined library by default (external libraries can change).
        $library = key($editor['libraries']);
        $files = array_shift($editor['libraries']);
        $files = $files['files'];
      }

      // Check whether the editor requires an initialization script.
      if (!empty($editor['init callback'])) {
        $init = $editor['init callback']($editor, $library, $profile);
        if (!empty($init)) {
          // Build a file for each of the editors to hold the init scripts.
          // @todo Aggregate all initialization scripts into one file.
          $uri = 'public://js/wysiwyg/wysiwyg_' . $name . '_' . drupal_hash_base64($init) . '.js';
          $init_exists = file_exists($uri);
          if (!$init_exists) {
            $js_path = dirname($uri);
            file_prepare_directory($js_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
          }
          // Attempt to create the file, or fall back to an inline script (which
          // will not work in Ajax calls).
          if (!$init_exists && !file_unmanaged_save_data($init, $uri, FILE_EXISTS_REPLACE)) {
            drupal_add_js($init, array('type' => 'inline') + $default_library_options);
          }
          else {
            drupal_add_js($uri, $default_library_options);
          }
        }
      }

      foreach ($files as $file => $options) {
        if (is_array($options)) {
          $options += $default_library_options;
          drupal_add_js($editor['library path'] . '/' . $file, $options);
        }
        else {
          drupal_add_js($editor['library path'] . '/' . $options);
        }
      }
      // If editor defines an additional load callback, invoke it.
      // @todo Isn't the settings callback sufficient?
      if (isset($editor['load callback']) && function_exists($editor['load callback'])) {
        $editor['load callback']($editor, $library);
      }
      // Load JavaScript integration files for this editor.
      $files = array();
      if (isset($editor['js files'])) {
        $files = $editor['js files'];
      }
      foreach ($files as $file) {
        drupal_add_js($editor['js path'] . '/' . $file);
      }
      // Load CSS stylesheets for this editor.
      $files = array();
      if (isset($editor['css files'])) {
        $files = $editor['css files'];
      }
      foreach ($files as $file) {
        drupal_add_css($editor['css path'] . '/' . $file);
      }
      $loaded[$name] = TRUE;
    }
    else {
      $loaded[$name] = FALSE;
    }
  }

  // Check if settings were already added on the page that makes an AJAX call.
  if (isset($_POST['ajax_page_state']) && !empty($_POST['ajax_page_state']['js'][$path . '/wysiwyg.js'])) {
    $settings_added = TRUE;
  }

  // Add basic Wysiwyg settings if any editor has been added.
  if (!isset($settings_added) && $loaded[$name]) {
    drupal_add_js(array('wysiwyg' => array(
      'configs' => array(),
      'plugins' => array(),
      'disable' => t('Disable rich-text'),
      'enable' => t('Enable rich-text'),
      'ajaxToken' => drupal_get_token('wysiwygAjaxCall'),
      'xss_url' => url('wysiwyg/xss'),
    )), 'setting');

    // Initialize our namespaces in the *header* to do not force editor
    // integration scripts to check and define Drupal.wysiwyg on its own.
    drupal_add_js($path . '/wysiwyg.init.js', array('group' => JS_LIBRARY));

    // The 'none' editor is a special editor implementation, allowing us to
    // attach and detach regular Drupal behaviors just like any other editor.
    drupal_add_js($path . '/editors/js/none.js');

    // Add wysiwyg.js to the footer to ensure it's executed after the
    // Drupal.settings array has been rendered and populated. Also, since editor
    // library initialization functions must be loaded first by the browser,
    // and Drupal.wysiwygInit() must be executed AFTER editors registered
    // their callbacks and BEFORE Drupal.behaviors are applied, this must come
    // last.
    drupal_add_js($path . '/wysiwyg.js', array('scope' => 'footer'));

    $settings_added = TRUE;
  }

  return $loaded[$name];
}

/**
 * Add editor settings for a given input format.
 */
function wysiwyg_add_editor_settings($profile, $theme) {
  static $formats = array();

  if (!isset($formats[$profile->format])) {
    $config = wysiwyg_get_editor_config($profile, $theme);
    // drupal_to_js() does not properly convert numeric array keys, so we need
    // to use a string instead of the format id.
    if ($config) {
      drupal_add_js(array('wysiwyg' => array('configs' => array($profile->editor => array('format' . $profile->format => $config)))), 'setting');
    }
    $formats[$profile->format] = TRUE;
  }
}

/**
 * Add settings for external plugins.
 *
 * Plugins can be used in multiple profiles, but not necessarily in all. Because
 * of that, we need to process plugins for each profile, even if most of their
 * settings are not stored per profile.
 *
 * Implementations of hook_wysiwyg_plugin() may execute different code for each
 * editor. Therefore, we have to invoke those implementations for each editor,
 * but process the resulting plugins separately for each profile.
 *
 * Drupal plugins differ to native plugins in that they have plugin-specific
 * definitions and settings, which need to be processed only once. But they are
 * also passed to the editor to prepare settings specific to the editor.
 * Therefore, we load and process the Drupal plugins only once, and hand off the
 * effective definitions for each profile to the editor.
 *
 * @param $profile
 *   A wysiwyg editor profile.
 *
 * @todo Rewrite wysiwyg_process_form() to build a registry of effective
 *   profiles in use, so we can process plugins in multiple profiles in one shot
 *   and simplify this entire function.
 */
function wysiwyg_add_plugin_settings($profile) {
  static $plugins = array();
  static $processed_plugins = array();
  static $processed_formats = array();

  // Each input format must only processed once.
  // @todo ...as long as we do not have multiple profiles per format.
  if (isset($processed_formats[$profile->format])) {
    return;
  }
  $processed_formats[$profile->format] = TRUE;

  $editor = wysiwyg_get_editor($profile->editor);

  // Collect native plugins for this editor provided via hook_wysiwyg_plugin()
  // and Drupal plugins provided via hook_wysiwyg_include_directory().
  if (!array_key_exists($editor['name'], $plugins)) {
    $plugins[$editor['name']] = wysiwyg_get_plugins($editor['name']);
  }

  // Nothing to do, if there are no plugins.
  if (empty($plugins[$editor['name']])) {
    return;
  }

  // Determine name of proxy plugin for Drupal plugins.
  $proxy = (isset($editor['proxy plugin']) ? key($editor['proxy plugin']) : '');

  // Process native editor plugins.
  $profile_plugins_native = array();
  foreach ($plugins[$editor['name']] as $plugin => $meta) {
    // Skip Drupal plugins (handled below) and 'core' functionality.
    if ($plugin === $proxy || $plugin === 'default') {
      continue;
    }
    // Only keep native plugins that are enabled in this profile.
    if (isset($profile->settings['buttons'][$plugin])) {
      $profile_plugins_native[$plugin] = $meta;
      if (!isset($processed_plugins[$editor['name']][$plugin])) {
        if (isset($editor['plugin meta callback'])) {
          // Invoke the editor's plugin meta callback, so it can populate the
          // global metadata for native plugins with required values.
          $meta['name'] = $plugin;
          if (($native_meta = call_user_func($editor['plugin meta callback'], $editor, $meta))) {
            drupal_add_js(array('wysiwyg' => array('plugins' => array('native' => array($editor['name'] => array($plugin => $native_meta))))), 'setting');
          }
        }
        $processed_plugins[$editor['name']][$plugin] = $meta;
      }
    }
  }
  if (!empty($profile_plugins_native) && isset($editor['plugin settings callback'])) {
    // Invoke the editor's plugin settings callback, so it can populate the
    // format specific settings for native plugins with required values.
    if (($settings_native = call_user_func($editor['plugin settings callback'], $editor, $profile, $profile_plugins_native))) {
      drupal_add_js(array('wysiwyg' => array('plugins' => array('format' . $profile->format => array('native' => $settings_native)))), 'setting');
    }
  }

  // Process Drupal plugins.
  if ($proxy && isset($editor['proxy plugin settings callback'])) {
    $profile_plugins_drupal = array();
    foreach (wysiwyg_get_all_plugins() as $plugin => $meta) {
      if (isset($profile->settings['buttons'][$proxy][$plugin])) {
        // JavaScript and plugin-specific settings for Drupal plugins must be
        // loaded and processed only once. Plugin information is cached
        // statically to pass it to the editor's proxy plugin settings callback.
        if (!isset($processed_plugins[$proxy][$plugin])) {
          $profile_plugins_drupal[$plugin] = $processed_plugins[$proxy][$plugin] = $meta;
          // Load the Drupal plugin's JavaScript.
          drupal_add_js($meta['js path'] . '/' . $meta['js file']);
          // Add plugin-specific settings.
          $settings = (isset($meta['settings']) ? $meta['settings'] : array());
          $settings['title'] = $meta['title'];
          $settings['icon'] = base_path() . $meta['icon path'] . '/' . $meta['icon file'];
          if (!empty($meta['css path']) && !empty($meta['css file'])) {
            $settings['css'] = base_path() . $meta['css path'] . '/' . $meta['css file'];
          }
          drupal_add_js(array('wysiwyg' => array('plugins' => array('drupal' => array($plugin => $settings)))), 'setting');
        }
        else {
          $profile_plugins_drupal[$plugin] = $processed_plugins[$proxy][$plugin];
        }
      }
    }
    // Invoke the editor's proxy plugin settings callback, so it can populate
    // the settings for Drupal plugins with custom, required values.
    $settings_drupal = call_user_func($editor['proxy plugin settings callback'], $editor, $profile, $profile_plugins_drupal);

    if ($settings_drupal) {
      drupal_add_js(array('wysiwyg' => array('plugins' => array('format' . $profile->format => array('drupal' => $settings_drupal)))), 'setting');
    }
  }
}

/**
 * Retrieve available themes for an editor.
 *
 * Editor themes control the visual presentation of an editor.
 *
 * @param $profile
 *   A wysiwyg editor profile; passed/altered by reference.
 * @param $selected_theme
 *   An optional theme name that ought to be used.
 *
 * @return
 *   An array of theme names, or a single, checked theme name if $selected_theme
 *   was given.
 */
function wysiwyg_get_editor_themes(&$profile, $selected_theme = NULL) {
  static $themes = array();

  if (!isset($themes[$profile->editor])) {
    $editor = wysiwyg_get_editor($profile->editor);
    if (isset($editor['themes callback']) && function_exists($editor['themes callback'])) {
      $themes[$editor['name']] = $editor['themes callback']($editor, $profile);
    }
    // Fallback to 'default' otherwise.
    else {
      $themes[$editor['name']] = array('default');
    }
  }

  // Check optional $selected_theme argument, if given.
  if (isset($selected_theme)) {
    // If the passed theme name does not exist, use the first available.
    if (!in_array($selected_theme, $themes[$profile->editor])) {
      $selected_theme = $profile->settings['theme'] = $themes[$profile->editor][0];
    }
  }

  return isset($selected_theme) ? $selected_theme : $themes[$profile->editor];
}

/**
 * Return plugin metadata from the plugin registry.
 *
 * @param $editor_name
 *   The internal name of an editor to return plugins for.
 *
 * @return
 *   An array for each plugin.
 */
function wysiwyg_get_plugins($editor_name) {
  $plugins = array();
  if (!empty($editor_name)) {
    $editor = wysiwyg_get_editor($editor_name);
    // Add internal editor plugins.
    if (isset($editor['plugin callback']) && function_exists($editor['plugin callback'])) {
      $plugins = $editor['plugin callback']($editor);
    }
    // Add editor plugins provided via hook_wysiwyg_plugin().
    $plugins = array_merge($plugins, module_invoke_all('wysiwyg_plugin', $editor['name'], $editor['installed version']));
    // Add API plugins provided by Drupal modules.
    // @todo We need to pass the filepath to the plugin icon for Drupal plugins.
    if (isset($editor['proxy plugin'])) {
      $plugins += $editor['proxy plugin'];
      $proxy = key($editor['proxy plugin']);
      foreach (wysiwyg_get_all_plugins() as $plugin_name => $info) {
        $plugins[$proxy]['buttons'][$plugin_name] = $info['title'];
      }
    }
  }
  return $plugins;
}

/**
 * Return an array of initial editor settings for a Wysiwyg profile.
 */
function wysiwyg_get_editor_config($profile, $theme) {
  $editor = wysiwyg_get_editor($profile->editor);
  $settings = array();
  $installed_version = $editor['installed version'];
  $settings = $profile->settings;
  if (!empty($editor['settings callback']) && function_exists($editor['settings callback'])) {
    if (!empty($profile->preferences['version']) && !empty($installed_version)) {
      $profile_version = $profile->preferences['version'];
      $version_status = version_compare($profile_version, $installed_version);
      if ($version_status !== 0) {
        // Installed version is different from profile version. Silently migrate
        // the stored editor settings to the installed version if possible.
        $migrated = FALSE;
        if (!empty($editor['migrate settings callback']) && function_exists($editor['migrate settings callback'])) {
          $migrated = $editor['migrate settings callback']($settings, $editor, $profile_version, $installed_version);
        }
      }
    }
    $settings = $editor['settings callback']($editor, $settings, $theme);

    // Allow other modules to alter the editor settings for this format.
    $context = array('editor' => $editor, 'profile' => $profile, 'theme' => $theme);
    drupal_alter('wysiwyg_editor_settings', $settings, $context);
  }
  return $settings;
}

/**
 * Retrieve stylesheets for HTML/IFRAME-based editors.
 *
 * This assumes that the content editing area only needs stylesheets defined
 * for the scope 'theme'.
 *
 * When the stylesheets a theme uses are not yet known it will return a single
 * URL pointing to a page which will gather the stylesheets so they can be
 * loaded indirectly via import rules.
 *
 * Note: if set to explicitly use the current admin theme by name, no access
 * check on the 'view the administration theme' permission is performed.
 *
 * @param $theme
 *   The id of a theme to get stylesheets for. Defaults to the current theme.
 *
 * @return
 *   An array containing CSS files, including proper base path.
 */
function wysiwyg_get_css($theme = NULL) {
  // Default to the node edit theme, if the user has access.
  if (empty($theme)) {
    $theme = variable_get('node_admin_theme') && user_access('view the administration theme') ? variable_get('admin_theme') : variable_get('theme_default', 'bartik');
  }
  // If set to use the admin theme, ensure the user has access.
  elseif ($theme == 'wysiwyg_theme_admin' && user_access('view the administration theme') && $admin_theme = variable_get('admin_theme')) {
    $theme = $admin_theme;
  }
  // Make sure the theme system is initialized.
  $themes = list_themes();
  if (!isset($themes[$theme])) {
    drupal_theme_initialize();
  }
  // Ensure the selected theme is enabled (or is the admin theme).
  if (!drupal_theme_access($theme)) {
    $theme = variable_get('theme_default', 'bartik');
  }
  $cached = cache_get('wysiwyg_css');
  $css = array();
  // Trigger a cache update if:
  // this is NOT the wysiwyg_theme page (avoid loop),
  // the cache is empty or does not have the current theme,
  // the CSS/JS cache-busting query string has changed,
  // or the theme's aggregation state has changed.
  $update_cache = strpos(current_path(), 'wysiwyg_theme/') === FALSE && (
    !$cached || (
      empty($cached->data[$theme])
      || $cached->data[$theme]['aggregated'] !== variable_get('preprocess_css', FALSE))
      || $cached->data['_css_js_query_string'] !== variable_get('css_js_query_string'));
  if ($update_cache) {
    // Make the client perform another request to update css caches.
    $css[] = url('wysiwyg_theme/' . $theme, array('absolute' => TRUE));
  }
  elseif (!empty($cached->data[$theme])) {
    $css = $cached->data[$theme]['files'];
  }
  return $css;
}

/**
 * Implements hook_themes_enabled().
 */
function wysiwyg_themes_enabled($theme_list) {
  $cached = cache_get('wysiwyg_css');
  if ($cached && !empty($cached->data)) {
    $css = $cached->data;
    foreach ($theme_list as $theme) {
      unset($css[$theme]);
    }
    cache_set('wysiwyg_css', $css);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the system's theme settings form to react when themes change.
 */
function wysiwyg_form_system_theme_settings_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_wysiwyg_system_theme_settings_submit';
}

/**
 * Submit callback for the theme settings form.
 *
 * Removes the edited theme from the cache.
 */
function _wysiwyg_system_theme_settings_submit($form, &$form_state) {
  $theme = NULL;
  if ($form_state['build_info']['form_id'] == 'system_theme_settings' && !empty($form_state['build_info']['args'])) {
    $theme = $form_state['build_info']['args'][0];
  }
  if ($theme !== NULL) {
    $cached = cache_get('wysiwyg_css');
    if ($cached && !empty($cached->data)) {
      $css = $cached->data;
      unset($css[$theme]);
      cache_set('wysiwyg_css', $css);
    }
  }
  wysiwyg_get_css($theme);
}

/**
 * Loads a profile for a given text format.
 *
 * Since there are commonly not many text formats, and each text format-enabled
 * form element will possibly have to load every single profile, all existing
 * profiles are loaded and cached once to reduce the amount of database queries.
 *
 * @param $format
 *   The machine-name of a text format.
 *
 * @return A profile if found, else FALSE.
 */
function wysiwyg_profile_load($format) {
  $profiles = wysiwyg_profile_load_all();
  return (isset($profiles[$format]) ? $profiles[$format] : FALSE);
}

/**
 * Loads all profiles.
 *
 * @return An array of profiles keyed by format name.
 */
function wysiwyg_profile_load_all() {
  // entity_load(..., FALSE) does not re-use its own static cache upon
  // repetitive calls, so a custom static cache is required.
  // @see wysiwyg_entity_info()
  $profiles = &drupal_static(__FUNCTION__);

  if (!isset($profiles)) {
    // Additional database cache to support alternative caches like memcache.
    if ($cached = cache_get('wysiwyg_profiles')) {
      $profiles = $cached->data;
    }
    else {
      $profiles = entity_load('wysiwyg_profile', FALSE);
      $formats = filter_formats();
      foreach ($profiles as $key => $profile) {
        if (empty($profile->editor) || !isset($formats[$profile->format])) {
          unset($profiles[$key]);
        }
      }
      cache_set('wysiwyg_profiles', $profiles);
    }
  }
  return $profiles;
}

/**
 * Deletes a profile from the database.
 */
function wysiwyg_profile_delete($profile) {
  db_delete('wysiwyg')
    ->condition('format', $profile->format)
    ->execute();
  // Clear the editing caches.
  if (module_exists('ctools')) {
    ctools_include('object-cache');
    ctools_object_cache_clear_all('wysiwyg_profile', $profile->name);
  }
  else {
    cache_clear_all('wysiwyg_profile:' . $profile->name, 'cache');
  }
  wysiwyg_profile_cache_clear();
}

/**
 * Specialized menu callback to load a profile and check its locked status.
 *
 * @param $name
 *   The machine name of the profile.
 *
 * @return
 *   The profile object, with a "locked" property indicating whether or not
 *   someone else is already editing the profile.
 */
function wysiwyg_ui_profile_cache_load($format) {
  $original_profile = wysiwyg_profile_load($format);
  $profile = FALSE;
  $name = ($original_profile ? $original_profile->name : 'format' . $format);
  $profile = wysiwyg_ui_profile_cache_get($name);
  if (empty($profile)) {
    $profile = $original_profile;
  }
  if (!empty($profile)) {
    $profile->editing = TRUE;
    return $profile;
  }
  return FALSE;
}

/**
 * Specialized cache function to load a profile from the editing cache.
 *
 * @param $name
 *   The name of a profile to load. Currently the format name prefixed by
 *   'format'.
 * @return
 *  The profile object, with a "locked" property indicating whether or not
 *  someone else is already editing the profile, or FALSE if not cached.
 */
function wysiwyg_ui_profile_cache_get($name) {
  $profile = FALSE;
  if (module_exists('ctools')) {
    ctools_include('object-cache');
    $profile = ctools_object_cache_get('wysiwyg_profile', $name);
    if ($profile) {
      $profile->locked = ctools_object_cache_test('wysiwyg_profile', $name);
    }
  }
  else {
    // Fall back on simple caching in its own bin without locking.
    $cached = cache_get('wysiwyg_profile:' . $name);
    if ($cached) {
      $profile = $cached->data;
      $profile->locked = FALSE;
    }
  }
  return $profile;
}

/**
 * Specialized cache function to add a profile to the editing cache.
 */
function wysiwyg_ui_profile_cache_set(&$profile) {
  if (!empty($profile->locked)) {
    drupal_set_message(t('Changes can not be made to a locked profile.'), 'error');
    return;
  }
  $profile->changed = TRUE;
  if (module_exists('ctools')) {
    ctools_include('object-cache');
    ctools_object_cache_set('wysiwyg_profile', $profile->name, $profile);
  }
  else {
    cache_set('wysiwyg_profile:' . $profile->name, $profile);
  }
}

/**
 * Clear all Wysiwyg profile caches.
 */
function wysiwyg_profile_cache_clear() {
  if (module_exists('wysiwyg')) {
    // Skip this if the module is not enabled as entity_get_info() returns null.
    entity_get_controller('wysiwyg_profile')->resetCache();
  }
  drupal_static_reset('wysiwyg_profile_load_all');
  cache_clear_all('wysiwyg_profiles', 'cache');
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function wysiwyg_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#user_category'] != 'account') {
    return;
  }
  $account = $form['#user'];
  $user_formats = filter_formats($account);
  $options = array();
  $options_default = array();
  foreach (wysiwyg_profile_load_all() as $format => $profile) {
    // Only show profiles that have user_choose enabled.
    if (!empty($profile->preferences['user_choose']) && isset($user_formats[$format])) {
      $options[$format] = check_plain($user_formats[$format]->name);
      if (wysiwyg_user_get_status($profile, $account)) {
        $options_default[] = $format;
      }
    }
  }
  if (!empty($options)) {
    $form['wysiwyg']['wysiwyg_status'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Text formats enabled for rich-text editing'),
      '#options' => $options,
      '#default_value' => $options_default,
    );
  }
}

/**
 * Implements hook_user_insert().
 *
 * Wysiwyg's user preferences are normally not exposed on the user registration
 * form, but in case they are manually altered in, we invoke
 * wysiwyg_user_update() accordingly.
 */
function wysiwyg_user_insert(&$edit, $account, $category) {
  wysiwyg_user_update($edit, $account, $category);
}

/**
 * Implements hook_user_update().
 */
function wysiwyg_user_update(&$edit, $account, $category) {
  if (isset($edit['wysiwyg_status'])) {
    db_delete('wysiwyg_user')
      ->condition('uid', $account->uid)
      ->execute();
    $query = db_insert('wysiwyg_user')
      ->fields(array('uid', 'format', 'status'));
    foreach ($edit['wysiwyg_status'] as $format => $status) {
      $query->values(array(
        'uid' => $account->uid,
        'format' => $format,
        'status' => (int) (bool) $status,
      ));
    }
    $query->execute();
  }
}

function wysiwyg_user_get_status($profile, $account = NULL) {
  global $user;

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

  // Default wysiwyg editor status information is only required on forms, so we
  // do not pre-emptively load and attach this information on every user_load().
  if (!isset($account->wysiwyg_status)) {
    $account->wysiwyg_status = db_query("SELECT format, status FROM {wysiwyg_user} WHERE uid = :uid", array(
      ':uid' => $account->uid,
    ))->fetchAllKeyed();
  }

  if (!empty($profile->preferences['user_choose']) && isset($account->wysiwyg_status[$profile->format])) {
    $status = $account->wysiwyg_status[$profile->format];
  }
  else {
    $status = isset($profile->preferences['default']) ? $profile->preferences['default'] : TRUE;
  }

  return (bool) $status;
}

/**
 * @defgroup wysiwyg_api Wysiwyg API
 * @{
 *
 * @todo Forked from Panels; abstract into a separate API module that allows
 *   contrib modules to define supported include/plugin types.
 */

/**
 * Return library information for a given editor.
 *
 * @param $name
 *   The internal name of an editor.
 *
 * @return
 *   The library information for the editor, or FALSE if $name is unknown or not
 *   installed properly.
 */
function wysiwyg_get_editor($name) {
  $editors = wysiwyg_get_all_editors();
  return isset($editors[$name]) && $editors[$name]['installed'] ? $editors[$name] : FALSE;
}

/**
 * Compile a list holding all supported editors including installed editor version information.
 */
function wysiwyg_get_all_editors() {
  static $editors;

  if (isset($editors)) {
    return $editors;
  }

  $editors = wysiwyg_load_includes('editors', 'editor');
  foreach ($editors as $editor => $properties) {
    // Fill in required properties.
    $editors[$editor] += array(
      'title' => '',
      'vendor url' => '',
      'download url' => '',
      'editor path' => wysiwyg_get_path($editors[$editor]['name']),
      'library path' => wysiwyg_get_path($editors[$editor]['name']),
      'libraries' => array(),
      'installed' => FALSE,
      'version callback' => NULL,
      'themes callback' => NULL,
      'settings form callback' => NULL,
      'settings callback' => NULL,
      'plugin callback' => NULL,
      'plugin settings callback' => NULL,
      'versions' => array(),
      'js path' => $editors[$editor]['path'] . '/js',
      'css path' => $editors[$editor]['path'] . '/css',
    );
    // Check whether library is present.
    if (!$editors[$editor]['installed'] && !($editors[$editor]['installed'] = file_exists($editors[$editor]['library path']))) {
      // Find the latest supported version.
      ksort($editors[$editor]['versions']);
      $version = key($editors[$editor]['versions']);
      foreach ($editors[$editor]['versions'] as $supported_version => $version_properties) {
        if (version_compare($version, $supported_version, '<')) {
          $version = $supported_version;
        }
      }
      // Apply library version specific definitions and overrides.
      // This is to show the newest installation instructions.
      $editors[$editor] = array_merge($editors[$editor], $editors[$editor]['versions'][$version]);
      continue;
    }
    $installed_version = NULL;
    // Detect library version.
    if (function_exists($editors[$editor]['version callback'])) {
      $installed_version = $editors[$editor]['installed version'] = $editors[$editor]['version callback']($editors[$editor]);
    }
    if (empty($installed_version)) {
      $editors[$editor]['error'] = t('The version of %editor could not be detected.', array('%editor' => $properties['title']));
      $editors[$editor]['installed'] = FALSE;
      continue;
    }
    $editors[$editor]['installed version verified'] = TRUE;
    if (!empty($editors[$editor]['verified version range'])) {
      $version_range = $editors[$editor]['verified version range'];
      if (version_compare($installed_version, $version_range[0], '<') || version_compare($installed_version, $version_range[1], '>')) {
        $editors[$editor]['installed version verified'] = FALSE;
      }
    }
    // Determine to which supported version the installed version maps.
    ksort($editors[$editor]['versions']);
    $version = 0;
    foreach ($editors[$editor]['versions'] as $supported_version => $version_properties) {
      if (version_compare($installed_version, $supported_version, '>=')) {
        $version = $supported_version;
      }
    }
    if (!$version) {
      $editors[$editor]['error'] = t('The installed version %version of %editor is not supported.', array('%version' => $installed_version, '%editor' => $editors[$editor]['title']));
      $editors[$editor]['installed'] = FALSE;
      continue;
    }
    // Apply library version specific definitions and overrides.
    $editors[$editor] = array_merge($editors[$editor], $editors[$editor]['versions'][$version]);
    unset($editors[$editor]['versions']);
  }
  drupal_alter('wysiwyg_editor', $editors);
  return $editors;
}

/**
 * Invoke hook_wysiwyg_plugin() in all modules.
 */
function wysiwyg_get_all_plugins() {
  static $plugins;

  if (isset($plugins)) {
    return $plugins;
  }

  $plugins = wysiwyg_load_includes('plugins', 'plugin');
  foreach ($plugins as $name => $properties) {
    $plugin = &$plugins[$name];
    // Fill in required/default properties.
    $plugin += array(
      'title' => $plugin['name'],
      'vendor url' => '',
      'js path' => $plugin['path'] . '/' . $plugin['name'],
      'js file' => $plugin['name'] . '.js',
      'css path' => $plugin['path'] . '/' . $plugin['name'],
      'css file' => $plugin['name'] . '.css',
      'icon path' => $plugin['path'] . '/' . $plugin['name'] . '/images',
      'icon file' => $plugin['name'] . '.png',
      'dialog path' => $plugin['name'],
      'dialog settings' => array(),
      'settings callback' => NULL,
      'settings form callback' => NULL,
    );
    // Fill in default settings.
    $plugin['settings'] += array(
      'path' => base_path() . $plugin['path'] . '/' . $plugin['name'],
    );
    // Check whether library is present.
    if (!($plugin['installed'] = file_exists($plugin['js path'] . '/' . $plugin['js file']))) {
      continue;
    }
  }
  return $plugins;
}

/**
 * Load include files for wysiwyg implemented by all modules.
 *
 * @param $type
 *   The type of includes to search for, can be 'editors'.
 * @param $hook
 *   The hook name to invoke.
 * @param $file
 *   An optional include file name without .inc extension to limit the search to.
 *
 * @see wysiwyg_get_directories(), _wysiwyg_process_include()
 */
function wysiwyg_load_includes($type = 'editors', $hook = 'editor', $file = NULL) {
  // Determine implementations.
  $directories = wysiwyg_get_directories($type);
  $directories['wysiwyg'] = drupal_get_path('module', 'wysiwyg') . '/' . $type;
  $file_list = array();
  foreach ($directories as $module => $path) {
    $file_list[$module] = drupal_system_listing("/{$file}.inc\$/", $path, 'name', 0);
  }

  // Load implementations.
  $info = array();
  foreach (array_filter($file_list) as $module => $files) {
    foreach ($files as $file) {
      include_once './' . $file->uri;
      $result = _wysiwyg_process_include($module, $module . '_' . $file->name, dirname($file->uri), $hook);
      if (is_array($result)) {
        $info = array_merge($info, $result);
      }
    }
  }
  drupal_alter('wysiwyg_load_includes', $info, $hook);
  return $info;
}

/**
 * Helper function to build paths to libraries.
 *
 * @param $library
 *   The external library name to return the path for.
 * @param $base_path
 *   Whether to prefix the resulting path with base_path().
 *
 * @return
 *   The path to the specified library.
 *
 * @ingroup libraries
 */
function wysiwyg_get_path($library, $base_path = FALSE) {
  static $libraries;

  if (!isset($libraries)) {
    $libraries = wysiwyg_get_libraries();
  }
  if (!isset($libraries[$library])) {
    // Most often, external libraries can be shared across multiple sites.
    return 'sites/all/libraries/' . $library;
  }

  $path = ($base_path ? base_path() : '');
  $path .= $libraries[$library];

  return $path;
}

/**
 * Return an array of library directories.
 *
 * Returns an array of library directories from the all-sites directory
 * (i.e. sites/all/libraries/), the profiles directory, and site-specific
 * directory (i.e. sites/somesite/libraries/). The returned array will be keyed
 * by the library name. Site-specific libraries are prioritized over libraries
 * in the default directories. That is, if a library with the same name appears
 * in both the site-wide directory and site-specific directory, only the
 * site-specific version will be listed.
 *
 * @return
 *   A list of library directories.
 *
 * @ingroup libraries
 */
function wysiwyg_get_libraries() {
  if (function_exists('libraries_get_libraries')) {
    $directories = libraries_get_libraries();
  }
  else {
    global $profile;

    // When this function is called during Drupal's initial installation process,
    // the name of the profile that is about to be installed is stored in the
    // global $profile variable. At all other times, the regular system variable
    // contains the name of the current profile, and we can call variable_get()
    // to determine the profile.
    if (!isset($profile)) {
      $profile = variable_get('install_profile', 'default');
    }

    $directory = 'libraries';
    $searchdir = array();
    $config = conf_path();

    // The 'profiles' directory contains pristine collections of modules and
    // themes as organized by a distribution.  It is pristine in the same way
    // that /modules is pristine for core; users should avoid changing anything
    // there in favor of sites/all or sites/<domain> directories.
    if (file_exists("profiles/$profile/$directory")) {
      $searchdir[] = "profiles/$profile/$directory";
    }

    // Always search sites/all/*.
    $searchdir[] = 'sites/all/' . $directory;

    // Also search sites/<domain>/*.
    if (file_exists("$config/$directory")) {
      $searchdir[] = "$config/$directory";
    }

    // Retrieve list of directories.
    // @todo Core: Allow to scan for directories.
    $directories = array();
    $nomask = array('CVS');
    foreach ($searchdir as $dir) {
      if (is_dir($dir) && $handle = opendir($dir)) {
        while (FALSE !== ($file = readdir($handle))) {
          if (!in_array($file, $nomask) && $file[0] != '.') {
            if (is_dir("$dir/$file")) {
              $directories[$file] = "$dir/$file";
            }
          }
        }
        closedir($handle);
      }
    }
  }

  return $directories;
}

/**
 * Return a list of directories by modules implementing wysiwyg_include_directory().
 *
 * @param $plugintype
 *   The type of a plugin; can be 'editors'.
 *
 * @return
 *   An array containing module names suffixed with '_' and their defined
 *   directory.
 *
 * @see wysiwyg_load_includes(), _wysiwyg_process_include()
 */
function wysiwyg_get_directories($plugintype) {
  $directories = array();
  foreach (module_implements('wysiwyg_include_directory') as $module) {
    $result = module_invoke($module, 'wysiwyg_include_directory', $plugintype);
    if (isset($result) && is_string($result)) {
      $directories[$module] = drupal_get_path('module', $module) . '/' . $result;
    }
  }
  return $directories;
}

/**
 * Create a placeholder structure for JavaScript callbacks.
 *
 * @param $name
 *  A string with the name of the callback, use 'object.subobject.method'
 *  syntax for methods in nested objects.
 * @param $context
 *  An optional string with the name of an object for overriding 'this' inside
 *  the function. Use 'object.subobject' syntax for nested objects. Defaults to
 *  the window object.
 *
 * @return
 *  An array with placeholder information for creating a JavaScript function
 *  reference on the client.
 */
function wysiwyg_wrap_js_callback($name, $context = NULL) {
  $obj = array(
    'drupalWysiwygType' => 'callback',
    'name' => $name,
  );
  if ($context) {
    $obj['context'] = $context;
  }
  return $obj;
}

/**
 * Create a placeholder structure for JavaScript RegExp objects.
 *
 * @param $regexp
 *  A JavaScript Regular Expression as a string, without / wrappers.
 * @param $modifiers
 *  An optional string with modifiers for the RegExp object.
 *
 * @return
 *  An array with placeholder information for creating a JavaScript RegExp
 *  object on the client.
 */
function wysiwyg_wrap_js_regexp($regexp, $modifiers = NULL) {
  $obj = array(
    'drupalWysiwygType' => 'regexp',
    'regexp' => $regexp,
  );
  if ($modifiers) {
    $obj['modifiers'] = $modifiers;
  }
  return $obj;
}

/**
 * Process a single hook implementation of a wysiwyg editor.
 *
 * @param $module
 *   The module that owns the hook.
 * @param $identifier
 *   Either the module or 'wysiwyg_' . $file->name
 * @param $hook
 *   The name of the hook being invoked.
 */
function _wysiwyg_process_include($module, $identifier, $path, $hook) {
  $function = $identifier . '_' . $hook;
  if (!function_exists($function)) {
    return NULL;
  }
  $result = $function();
  if (!isset($result) || !is_array($result)) {
    return NULL;
  }

  // Fill in defaults.
  foreach ($result as $editor => $properties) {
    $result[$editor]['module'] = $module;
    $result[$editor]['name'] = $editor;
    $result[$editor]['path'] = $path;
  }
  return $result;
}

/**
 * @} End of "defgroup wysiwyg_api".
 */

/**
 * Return an install note about deprecation.
 *
 * @param array $editor
 *   The definition for a an editor plugin with a 'deprecation message' key.
 */
function wysiwyg_deprecation_install_note($editor) {
  $output = '<p class="warning">' . $editor['deprecation message'] . '</p>';
  return $output;
}

/**
 * Implements hook_features_api().
 */
function wysiwyg_features_api() {
  return array(
    'wysiwyg' => array(
      'name' => t('Wysiwyg profiles'),
      'default_hook' => 'wysiwyg_default_profiles',
      'default_file' => FEATURES_DEFAULTS_INCLUDED,
      'feature_source' => TRUE,
      'file' => drupal_get_path('module', 'wysiwyg') . '/wysiwyg.features.inc',
    ),
  );
}

/**
 * AJAX callback - XSS filter.
 */
function wysiwyg_filter_xss_page_callback() {
  $GLOBALS['devel_shutdown'] = FALSE;

  if (!isset($_POST['text']) || !is_string($_POST['text']) || !isset($_POST['input_format']) || !is_string($_POST['input_format']) || !isset($_POST['token']) || !drupal_valid_token($_POST['token'], 'wysiwygAjaxCall', FALSE)) {
    drupal_add_http_header('Status', '403 Forbidden');
    exit;
  }

  $format = filter_format_load($_POST['input_format']);
  if ($format == FALSE || !is_object($format) || !filter_access($format)) {
    drupal_add_http_header('Status', '403 Forbidden');
    exit;
  }

  $original_format = !empty($_POST['original_input_format']) ? $_POST['original_input_format'] : NULL;
  if ($original_format !== NULL) {
    $original_format = filter_format_load($original_format);
    if ($original_format == FALSE || !is_object($original_format) || !filter_access($original_format)) {
      drupal_add_http_header('Status', '403 Forbidden');
      exit;
    }
  }

  return drupal_json_output(wysiwyg_filter_xss($_POST['text'], $format, $original_format));
}

/**
 * Apply text editor XSS filtering.
 *
 * Based on ckeditor.module's ckeditor_filter_xss() and Editor module in D8.
 * Invokes one of hook_[wysiwyg|ckeditor]_filter_xss_allowed_tags().
 *
 * @param $html
 *   The HTML string that will be passed to the text editor.
 * @param $format
 *   The loaded text format object to get filters from.
 * @param $original_format
 *   An optional previous text format object being switched from.
 *
 * @return string|FALSE
 *   The filtered HTML, or FALSE if no filtering was possible or needed.
 */
function wysiwyg_filter_xss($html, $format, $original_format = NULL) {
  $editor = wysiwyg_get_profile($format->format);
  // If no editor is attached with this format, there is no need to perform
  // XSS filtering.
  if (!$editor) {
    return FALSE;
  }
  // If there was a previous format we must apply any security filters from
  // it in case they were more restrictive than the current format. Otherwise
  // an anonymous user could create content in Filtered HTML without an editor,
  // an admin user edits it (then no XSS filtering is applied), and switches to
  // Full HTML with an editor. Then XSS filtering must be applied to protect the
  // admin user.
  if ($original_format !== NULL) {
    $filtered_original = _wysiwyg_apply_format_filters($html, $original_format);
    // If filtering was needed for the previous format use its output as the
    // input markup for the current format.
    if ($filtered_original !== FALSE) {
      $html = $filtered_original;
    }
    // Apply security filters from the current format.
    $filtered_current = _wysiwyg_apply_format_filters($html, $format);
    // If no filtering was needed for either format, just return FALSE.
    if ($filtered_original === FALSE && $filtered_current === FALSE) {
      return FALSE;
    }
    // If the current format did no filtering, use the result of the original.
    if ($filtered_current === FALSE) {
      return $filtered_original;
    }
    // Only the current format needed to apply filtering.
    return $filtered_current;
  }
  // Only apply security filters from the current format.
  return _wysiwyg_apply_format_filters($html, $format);
}

/**
 * Apply security filters from a format on input markup.
 *
 * @param $html
 *   The HTML string that will be passed to the text editor.
 * @param $format
 *   The loaded text format to get filters from.
 *
 * @return string|FALSE
 *   The filtered HTML, or FALSE if no filtering was possible or needed.
 */
function _wysiwyg_apply_format_filters($html, $format) {
  $filters = filter_get_filters();
  $security_filters = wysiwyg_security_filters();
  $format_filters = filter_list_format($format->format);
  $cache_id = $format->format . '::' . hash('sha256', $html);
  $did_filter = FALSE;

  foreach ((array) $format_filters as $name => $object) {
    // If the filter is not a security filter, does not exist, cannot be called
    // or isn't enabled in the selected text format then skip it.
    if (!isset($security_filters['filters'][$name]) || !isset($filters[$name]) || !isset($filters[$name]['process callback']) || $object->status == 0) {
      continue;
    }

    // Built-in filter module, a special case where we would like to strip XSS
    // and nothing more.
    if ($name == 'filter_html' && $security_filters['filters']['filter_html'] == 1) {
      preg_match_all("|</?([a-z][a-z0-9]*)(?:\b[^>]*)>|i", $html, $matches);
      if ($matches[1]) {

        // Sources of inspiration:
        // https://www.w3.org/TR/html4/index/elements.html
        // https://www.w3.org/TR/html-markup/elements.html
        // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
        // https://drupal.org/project/ckeditor
        $base_allowed_tags = array('a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont',
          'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
          'command', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'figcaption',
          'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img',
          'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'main', 'map', 'mark', 'menu', 'menuitem', 'meter',
          'nav', 'noframes', 'noscript', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt',
          'ruby', 's', 'samp', 'section', 'select', 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table',
          'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr',
        );

        // Get tags allowed in filter settings.
        $filter_allowed_tags = preg_split('/\s+|<|>/', $object->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);

        // Combine allowed tags.
        $tags = array_merge($base_allowed_tags, $filter_allowed_tags);

        // Tags provided by hook.
        $hooks_allowed_tags = _wysiwyg_invoke_security_hook('filter_xss_allowed_tags');
        if (!empty($hooks_allowed_tags) && is_array($hooks_allowed_tags)) {
          foreach ($hooks_allowed_tags as $tag) {
            if (!empty($tag) && is_string($tag) && !in_array($tag, $tags)) {
              array_push($tags, $tag);
            }
          }
        }
        $html = filter_xss($html, $tags);
        $did_filter = TRUE;
      }
      continue;
    }
    $html = $filters[$name]['process callback']($html, $format_filters[$name], $format, '', TRUE, $cache_id);
    $did_filter = TRUE;
  }

  return ($did_filter ? $html : FALSE);
}

/**
 * Return all modules that provide security filters.
 *
 * Based on ckeditor.module's ckeditor_security_filters().
 */
function wysiwyg_security_filters() {
  $security_filters = array();

  $security_filters['modules'] = array(
    'htmLawed' => array(
      'title' => 'htmLawed',
      'project_page' => 'https://drupal.org/project/htmLawed',
      'weight' => 0,
      'installed' => FALSE,
      'filters' => array(),
    ),
    'htmltidy' => array(
      'title' => 'HTML Tidy',
      'project_page' => 'https://drupal.org/project/htmltidy',
      'weight' => 0,
      'installed' => FALSE,
      'filters' => array(),
    ),
    'htmlpurifier' => array(
      'title' => 'HTML Purifier',
      'project_page' => 'https://drupal.org/project/htmlpurifier',
      'weight' => 0,
      'installed' => FALSE,
      'filters' => array(),
    ),
    'wysiwyg_filter' => array(
      'title' => 'WYSIWYG Filter',
      'project_page' => 'https://drupal.org/project/wysiwyg_filter',
      'weight' => 0,
      'installed' => FALSE,
      'filters' => array(),
    ),
  );

  $security_filters['filters'] = array();

  foreach ($security_filters['modules'] as $module_name => $module_conf) {
    if (module_exists($module_name)) {
      $security_filters['modules'][$module_name]['installed'] = TRUE;
      $module_filters = module_invoke($module_name, 'filter_info');
      foreach ($module_filters as $module_filter_name => $module_filter_conf) {
        $security_filters['modules'][$module_name]['filters'][$module_filter_name] = $module_filter_conf;
        $security_filters['filters'][$module_filter_name] = TRUE;
      }
    }
  }

  // Add filters from Drupal Core.
  $security_filters['modules']['__drupal'] = array(
    'title' => t('Drupal core'),
    'project_page' => FALSE,
    'weight' => -1,
    'installed' => TRUE,
    'filters' => array(
      'filter_html' => array(
        'title' => t('Limit allowed HTML tags'),
        'description' => t('Removes the attributes that the built-in "Limit allowed HTML tags"-filter does not allow inside HTML elements/tags.'),
      ),
    ),
  );
  $security_filters['filters']['filter_html'] = TRUE;

  // Load security filters added via the ckeditor.module or wysiwyg module APIs.
  $external_module_filters = _wysiwyg_invoke_security_hook('security_filter');
  if (count($external_module_filters) > 0) {
    $security_filters['modules']['__external'] = array(
      'title' => t('External filters'),
      'project_page' => FALSE,
      'weight' => 1,
      'installed' => TRUE,
      'filters' => array(),
    );
    foreach ($external_module_filters as $module_filter_name => $module_filter_conf) {
      $security_filters['modules']['__external']['filters'][$module_filter_name] = $module_filter_conf;
      $security_filters['filters'][$module_filter_name] = TRUE;
    }
  }
  // Pass along some context to let modules implementing both alter hooks know
  // which module is calling them to allow separate alterations if needed.
  $context = array(
    'caller' => 'wysiwyg',
  );
  // Pass a dummy value in case ckeditor.module needs the second argument later.
  $reserved = NULL;
  drupal_alter('ckeditor_security_filter', $security_filters, $reserved, $context);
  $reserved = NULL;
  drupal_alter('wysiwyg_security_filter', $security_filters, $reserved, $context);

  return $security_filters;
}

/**
 * A custom version of module_invoke_all().
 *
 * Allows calling just one of hook_wysiwyg_FOO() and hook_ckeditor_FOO() for
 * each implementing module. Wysiwyg hooks take precedence if defined.
 *
 * @param $hook_base
 *   The base name of a hook to call, without module prefix.
 *
 * @see module_invoke_all()
 */
function _wysiwyg_invoke_security_hook($hook_base) {
  $implements_wysiwyg = module_implements('wysiwyg_' . $hook_base);
  $implements_ckeditor = module_implements('ckeditor_' . $hook_base);
  // Ignore the hook_ckeditor_* implementation if a module also has a
  // hook_wysiwyg_* implementation.
  $implements_ckeditor = array_diff($implements_ckeditor, $implements_wysiwyg);
  // Everything below is based on module_invoke_all().
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  // Call ckeditor.module hooks.
  $hook = 'ckeditor_' . $hook_base;
  foreach ($implements_ckeditor as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }
  // Call wysiwyg.module hooks.
  $hook = 'wysiwyg_' . $hook_base;
  foreach ($implements_wysiwyg as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}
