Commit 6f41d692 authored by Dries's avatar Dries
Browse files

- Patch #559658 by sun, dropcube: store filter settings per format, general...

- Patch #559658 by sun, dropcube: store filter settings per format, general API clean-up and documentation improvements.
parent 0963bac7
......@@ -79,6 +79,7 @@ Drupal 7.0, xxxx-xx-xx (development version)
contributed date or event modules installed, user time zone settings will
fallback to the system time zone and will have to be reconfigured by each user.
- Filter system:
* Revamped the filter API and text format storage.
* Refactored the HTML corrector to take advantage of PHP 5 features.
- Removed ping module:
* Contributed modules with similar functionality are available.
......
......@@ -144,7 +144,7 @@ function filter_admin_format_form(&$form_state, $format) {
}
// Table with filters
$filter_info = filter_get_filters();
$enabled = filter_list_format($format->format);
$filters = filter_list_format($format->format);
$form['filters'] = array('#type' => 'fieldset',
'#title' => t('Filters'),
......@@ -155,7 +155,7 @@ function filter_admin_format_form(&$form_state, $format) {
$form['filters'][$name] = array(
'#type' => 'checkbox',
'#title' => $filter['title'],
'#default_value' => isset($enabled[$name]),
'#default_value' => isset($filters[$name]),
'#description' => $filter['description'],
);
}
......@@ -201,22 +201,15 @@ function filter_admin_format_form_submit($form, &$form_state) {
$format->format = isset($form_state['values']['format']) ? $form_state['values']['format'] : NULL;
$status = filter_format_save($format);
// If a new filter was added, return to the main list of filters.
// Otherwise, stay on edit filter page to show new changes.
$return = 'admin/settings/formats';
switch ($status) {
case SAVED_NEW:
drupal_set_message(t('Added text format %format.', array('%format' => $format->name)));
$return .= '/' . $format->format;
break;
case SAVED_UPDATED:
drupal_set_message(t('The text format settings have been updated.'));
break;
}
$form_state['redirect'] = $return;
return;
}
/**
......@@ -259,7 +252,6 @@ function filter_admin_delete_submit($form, &$form_state) {
$form_state['redirect'] = 'admin/settings/formats';
}
/**
* Menu callback; display settings defined by a format's filters.
*/
......@@ -269,39 +261,66 @@ function filter_admin_configure_page($format) {
}
/**
* Build a form to change the settings for a format's filters.
* Build a form to change the settings for filters in a text format.
*
* The form is built by merging the results of 'settings callback' for each
* enabled filter in the given format.
*
* @ingroup forms
*/
function filter_admin_configure(&$form_state, $format) {
$list = filter_list_format($format->format);
$filters = filter_list_format($format->format);
$filter_info = filter_get_filters();
$form = array();
foreach ($list as $name => $filter) {
$form['#format'] = $format;
foreach ($filters as $name => $filter) {
if (isset($filter_info[$name]['settings callback']) && function_exists($filter_info[$name]['settings callback'])) {
$form_module = call_user_func($filter_info[$name]['settings callback'], $format->format);
}
if (isset($form_module) && is_array($form_module)) {
$form = array_merge($form, $form_module);
// Pass along stored filter settings and default settings, but also the
// format object and all filters to allow for complex implementations.
$defaults = (isset($filter_info[$name]['default settings']) ? $filter_info[$name]['default settings'] : array());
$settings_form = $filter_info[$name]['settings callback']($form_state, $filters[$name], $defaults, $format, $filters);
if (isset($settings_form) && is_array($settings_form)) {
$form['settings'][$name] = array(
'#type' => 'fieldset',
'#title' => check_plain($filter->title),
);
$form['settings'][$name] += $settings_form;
}
}
}
if (!empty($form)) {
$form = system_settings_form($form, TRUE);
}
else {
if (empty($form['settings'])) {
$form['error'] = array('#markup' => t('No settings are available.'));
return $form;
}
$form['format'] = array('#type' => 'hidden', '#value' => $format->format);
$form['#submit'][] = 'filter_admin_configure_submit';
$form['settings']['#tree'] = TRUE;
$form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
return $form;
}
/**
* Clear the filter's cache when configuration settings are saved.
* Form submit handler for text format filter configuration form.
*
* @see filter_admin_configure()
*/
function filter_admin_configure_submit($form, &$form_state) {
cache_clear_all($form_state['values']['format'] . ':', 'cache_filter', TRUE);
$format = $form['#format'];
foreach ($form_state['values']['settings'] as $name => $settings) {
db_update('filter')
->fields(array(
'settings' => serialize($settings),
))
->condition('format', $format->format)
->condition('name', $name)
->execute();
}
// Clear the filter's cache when configuration settings are saved.
cache_clear_all($format->format . ':', 'cache_filter', TRUE);
drupal_set_message(t('The configuration options have been saved.'));
}
/**
......@@ -366,10 +385,14 @@ function theme_filter_admin_order($form) {
*/
function filter_admin_order_submit($form, &$form_state) {
foreach ($form_state['values']['weights'] as $name => $weight) {
db_update('filter')
->fields(array('weight' => $weight))
->condition('format', $form_state['values']['format'])
->condition('name', $name)
db_merge('filter')
->key(array(
'format' => $form_state['values']['format'],
'name' => $name,
))
->fields(array(
'weight' => $weight,
))
->execute();
}
drupal_set_message(t('The filter ordering has been saved.'));
......
......@@ -14,13 +14,32 @@
/**
* Define content filters.
*
* Content in Drupal is passed through a group of filters before it is
* output. This lets a module modify content to the site administrator's
* liking.
* Content in Drupal is passed through a group of filters before it is output.
* This lets a module modify content to the site administrator's liking.
*
* This hook allows modules to declare input filters they provide.
* This hook allows modules to declare input filters they provide. A module can
* contain as many filters as it wants.
*
* A module can contain as many filters as it wants.
* The overall, logical flow is as follows:
* - hook_filter_info() is invoked to retrieve one or more filter definitions.
* - The site administrator enables and configures the filter, where the
* following properties may be used:
* - 'title': The filter's title.
* - 'description': The filter's short-description.
* Additionally, if a filter is configurable:
* - 'settings callback': A form builder function name providing a settings
* form for the filter.
* - 'default settings': An array containing default settings for the filter.
* - When a form containing a text format-enabled text widget/textarea is
* rendered, the following property are checked:
* - 'tips callback': A function name providing filter guidelines to be
* displayed in the text format widget.
* - When a content using a text format is rendered, the following properties
* may be used:
* - 'prepare callback': A name of a function that escapes the to be filtered
* content before the actual filtering happens.
* - 'process callback': The name the function that performs the actual
* filtering.
*
* Filtering is a two-step process. First, the content is 'prepared' by calling
* the 'prepare callback' function for every filter. The purpose of the 'prepare
......@@ -32,19 +51,22 @@
* necessary, and they can just return the input without changes.
*
* Filters should not use the 'prepare callback' step for anything other than
* escaping, because that would short-circuits the control the user has over the
* escaping, because that would short-circuit the control the user has over the
* order in which filters are applied.
*
* The second step is the actual processing step. The result from the prepare
* step gets passed to all the filters again, this time with the 'process
* callback' function. It's here that filters should perform actual changing of
* callback' function. It's here where filters should perform actual changing of
* the content: transforming URLs into hyperlinks, converting smileys into
* images, etc.
*
* An important aspect of the filtering system is 'text formats'. Every text
* format is an entire filter setup: which filters to enable, in what order
* and with what settings. Filters that provide settings should usually store
* these settings per format.
* and with what settings.
*
* Filters that require settings should provide the form controls to configure
* the settings in a form builder function, specified in 'settings callback'.
* The filter system stores the settings in the database per text format.
*
* If the filter's behavior depends on an extensive list and/or external data
* (e.g. a list of smileys, a list of glossary terms) then filters are allowed
......@@ -52,11 +74,59 @@
* per format. In that case, there should be a link from the format-specific
* settings to the separate settings page.
*
* The $filter object with the current settings is passed to the 'settings
* callback' function. If 'default settings' were defined in hook_filter_info(),
* those are passed as second argument to the 'settings callback'. Each filter
* should apply either the default settings or the configured settings contained
* in $filter->settings.
*
* 'settings callback' is invoked with the following arguments (most filter
* implementations will only need the first 3):
* - &$form_state: The form state of the (entire) configuration form.
* - $filter: The filter object containing settings for the given format.
* - $defaults: The default settings for the filter, as defined in 'default
* settings' in hook_filter_info().
* - $format: The format object being configured.
* - $filters: Complete list of filter objects that are enabled for the given
* format.
*
* @code
* function mymodule_filter_settings(&$form_state, $filter, $defaults) {
* $form['mymodule_url_length'] = array(
* '#type' => 'textfield',
* '#title' => t('Maximum link text length'),
* '#default_value' => isset($filter->settings['mymodule_url_length']) ? $filter->settings['mymodule_url_length'] : $defaults['mymodule_url_length'],
* );
* return $form;
* }
* @endcode
*
* 'prepare callback' and 'process callback' are invoked with the following
* arguments:
* - $text: The text to be filtered.
* - $filter: The filter object containing settings for the given format.
* - $format: The format object of the text to be filtered.
* - $langcode: (optional) The language code of the text to be filtered.
* - $cache: Boolean whether check_markup() will cache the filtered $text in
* {cache_filter}.
* - $cache_id: The cache ID used for $text in {cache_filter} when $cache is
* TRUE.
*
* @see check_markup()
*
* 'prepare callback' and 'process callback' functions may access the filter
* settings in $filter->settings['mymodule_url_length'].
*
* 'tips callback' is invoked with the following parameters:
* - $filter: The filter object containing settings for the given format.
* - $format: The format object of the text to be filtered.
* - $long: Boolean whether to return long or short filter guidelines.
*
* For performance reasons content is only filtered once; the result is stored
* in the cache table and retrieved the next time the piece of content is
* displayed. If a filter's output is dynamic it can override the cache
* mechanism, but obviously this feature should be used with caution: having one
* filter that doesn't support caching in a particular text format disables
* in the cache table and retrieved from the cache the next time the same piece
* of content is displayed. If a filter's output is dynamic, it can override the
* cache mechanism, but obviously this should be used with caution: having one
* filter that does not support caching in a particular text format disables
* caching for the entire format, not just for one filter.
*
* Beware of the filter cache when developing your module: it is advised to set
......@@ -68,21 +138,25 @@
* An array of filter items. Each filter item has a unique name, prefixed
* with the name of the module that provides it. The item is an associative
* array that may contain the following key-value pairs:
* - 'title': Required. The title of the filter.
* - 'description': Short description of what this filter does.
* - 'prepare callback': The callback function to call in the 'prepare' step
* - 'title': (required) The administrative title of the filter.
* - 'description': A short, administrative description of what this filter
* does.
* - 'prepare callback': A callback function to call in the 'prepare' step
* of the filtering.
* - 'process callback': Required. The callback function to call in the
* - 'process callback': (required) The callback function to call in the
* 'process' step of the filtering.
* - 'settings callback': The callback function that provides form controls
* for the filter's settings. These settings are stored with variable_set()
* when the form is submitted. Remember to use the $format identifier in the
* variable and control names to store settings per text format (e.g.
* 'mymodule_setting_$format').
* - 'tips callback': The callback function that provide tips for using
* filters. A module's tips should be informative and to the point. Short
* - 'settings callback': A callback function that provides form controls
* for the filter's settings. Each filter should apply either the default
* settings or the configured settings contained in $filter->settings. The
* user submitted values are stored in the database.
* - 'default settings': An array containing default settings for a filter to
* be applied when the filter has not been configured yet.
* - 'tips callback': A callback function that provides tips for using the
* filter. A module's tips should be informative and to the point. Short
* tips are preferably one-liners.
* - 'cache': Specify if the filter result can be cached. TRUE by default.
* - 'cache': Specifies whether the filtered text can be cached. TRUE by
* default. Note that defining FALSE makes the entire text format not
* cacheable, which may have an impact on the site's overall performance.
*
* For a detailed usage example, see filter_example.module. For an example of
* using multiple filters in one module, see filter_filter_info().
......@@ -93,6 +167,11 @@ function hook_filter_info() {
'description' => t('Allows you to restrict the HTML tags the user can use. It will also remove harmful content such as JavaScript events, JavaScript URLs and CSS styles from those tags that are not removed.'),
'process callback' => '_filter_html',
'settings callback' => '_filter_html_settings',
'default settings' => array(
'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>',
'filter_html_help' => 1,
'filter_html_nofollow' => 0,
),
'tips callback' => '_filter_html_tips',
);
$filters['filter_autop'] = array(
......@@ -115,6 +194,11 @@ function hook_filter_info_alter(&$info) {
// Replace the PHP evaluator process callback with an improved
// PHP evaluator provided by a module.
$info['php_code']['process callback'] = 'my_module_php_evaluator';
// Alter the default settings of the URL filter provided by core.
$info['filter_url']['default settings'] = array(
'filter_url_length' => 100,
);
}
/**
......@@ -145,7 +229,7 @@ function hook_filter_format_insert($format) {
*/
function hook_filter_format_update($format) {
mymodule_cache_rebuild();
}
}
/**
* Perform actions when a text format has been deleted.
......
......@@ -13,11 +13,6 @@ function filter_schema() {
$schema['filter'] = array(
'description' => 'Table that maps filters (HTML corrector) to text formats (Filtered HTML).',
'fields' => array(
'fid' => array(
'type' => 'serial',
'not null' => TRUE,
'description' => 'Primary Key: Auto-incrementing filter ID.',
),
'format' => array(
'type' => 'int',
'not null' => TRUE,
......@@ -44,9 +39,22 @@ function filter_schema() {
'default' => 0,
'size' => 'tiny',
'description' => 'Weight of filter within format.',
)
),
'status' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Filter enabled status. (1 = enabled, 0 = disabled)',
),
'settings' => array(
'type' => 'text',
'not null' => FALSE,
'size' => 'big',
'serialize' => TRUE,
'description' => 'A serialized array of name value pairs that store the filter settings for the specific format.',
),
),
'primary key' => array('fid'),
'primary key' => array('format', 'name'),
'unique keys' => array(
'fmn' => array('format', 'module', 'name'),
),
......@@ -187,3 +195,68 @@ function filter_update_7003() {
return $ret;
}
/**
* Move filter settings storage into {filter} table.
*
* - Remove {filter}.fid.
* - Add (format, name) as primary key for {filter}.
* - Add {filter}.status.
* - Add {filter}.settings.
*/
function filter_update_7004() {
$ret = array();
db_drop_field($ret, 'filter', 'fid');
db_add_primary_key($ret, 'filter', array('format', 'name'));
db_add_field($ret, 'filter', 'status',
array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Filter enabled status. (1 = enabled, 0 = disabled)',
)
);
db_add_field($ret, 'filter', 'settings',
array(
'type' => 'text',
'not null' => FALSE,
'size' => 'big',
'serialize' => TRUE,
'description' => 'A serialized array of name value pairs that store the filter settings for the specific format.',
)
);
// Enable all existing filters ({filter} contained only enabled previously).
$ret[] = update_sql("UPDATE {filter} SET status = 1");
// Move filter settings from system variables into {filter}.settings.
$filters = db_query("SELECT * FROM {filter} WHERE module = :name", array(':name' => 'filter'));
foreach ($filters as $filter) {
$settings = array();
if ($filter->name == 'filter_html') {
if ($setting = variable_get("allowed_html_{$filter->format}", NULL)) {
$settings['allowed_html'] = $setting;
variable_del("allowed_html_{$filter->format}");
}
if ($setting = variable_get("filter_html_help_{$filter->format}", NULL)) {
$settings['filter_html_help'] = $setting;
variable_del("filter_html_help_{$filter->format}");
}
if ($setting = variable_get("filter_html_nofollow_{$filter->format}", NULL)) {
$settings['filter_html_nofollow'] = $setting;
variable_del("filter_html_nofollow_{$filter->format}");
}
}
elseif ($filter->name == 'filter_url') {
if ($setting = variable_get("filter_url_length_{$filter->format}", NULL)) {
$settings['filter_url_length'] = $setting;
variable_del("filter_url_length_{$filter->format}");
}
}
if (!empty($settings)) {
$ret[] = update_sql("UPDATE {filter} SET settings = '" . serialize($settings) . "' WHERE format = {$filter->format} AND name = '{$filter->name}'");
}
}
return $ret;
}
......@@ -140,8 +140,17 @@ function filter_menu() {
return $items;
}
function filter_format_load($arg) {
return filter_formats($arg);
/**
* Load a text format object from the database.
*
* @param $format
* The format ID.
*
* @return
* A fully-populated text format object.
*/
function filter_format_load($format) {
return filter_formats($format);
}
/**
......@@ -155,45 +164,47 @@ function filter_format_save($format) {
// We should always set all roles to TRUE when saving the default format.
// We use leading and trailing comma's to allow easy substring matching.
$roles = array_filter($format->roles);
if ($format->format == variable_get('filter_default_format', 1)) {
if (!empty($format->format) && $format->format == variable_get('filter_default_format', 1)) {
$roles = ',' . implode(',', array_keys(user_roles())) . ',';
}
else {
$roles = ',' . implode(',',array_keys($roles)) . ',';
$roles = ',' . implode(',', array_keys($roles)) . ',';
}
$format->roles = $roles;
$format->name = trim($format->name);
// Add a new text format.
if (empty($format->format)) {
$status = drupal_write_record('filter_format', $format);
$return = drupal_write_record('filter_format', $format);
}
else {
$status = drupal_write_record('filter_format', $format, 'format');
$return = drupal_write_record('filter_format', $format, 'format');
}
db_delete('filter')
->condition('format', $format->format)
->execute();
// Get the filters currently active in the format, to add new filters
// to the bottom.
$current = filter_list_format($format->format);
$query = db_insert('filter')->fields(array('format', 'name', 'weight'));
$filters = $format->filters;
foreach (array_keys(array_filter($filters)) as $name) {
foreach ($filters as $name => $status) {
$fields = array();
// Add new filters to the bottom.
$weight = isset($current[$name]->weight) ? $current[$name]->weight : 10;
$query->values(array(
'format' => $format->format,
'name' => $name,
'weight' => $weight,
));
$fields['weight'] = isset($current[$name]->weight) ? $current[$name]->weight : 10;
$fields['status'] = $status;
// Only update settings if there are any.
if (!empty($format->settings[$name])) {
$fields['settings'] = serialize($format->settings[$name]);
}
db_merge('filter')
->key(array(
'format' => $format->format,
'name' => $name,
))
->fields($fields)
->execute();
}
$query->execute();
if ($status == SAVED_NEW) {
if ($return == SAVED_NEW) {
module_invoke_all('filter_format_insert', $format);
}
else {
......@@ -202,7 +213,7 @@ function filter_format_save($format) {
cache_clear_all($format->format . ':', 'cache_filter', TRUE);
return $status;
return $return;
}
/**
......@@ -259,12 +270,12 @@ function filter_cron() {
* @{
* Filters implemented by the filter.module.
*/
function _filter_html_tips($format, $long = FALSE) {
function _filter_html_tips($filter, $format, $long = FALSE) {
global $base_url;
if ($allowed_html = variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>')) {
if ($allowed_html = $filter->settings['allowed_html']) {
if ($long) {
$output = '<p>' . t('Allowed HTML tags: @tags', array('@tags' => $allowed_html)) . '</p>';
if (!variable_get("filter_html_help_$format", 1)) {
if (!$filter->settings['filter_html_help']) {
return $output;
}
......@@ -355,7 +366,7 @@ function _filter_html_tips($format, $long = FALSE) {
}
}
function _filter_autop_tips($format, $long = FALSE) {
function _filter_autop_tips($filter, $format, $long = FALSE) {
if ($long) {
return t('Lines and paragraphs are automatically recognized. The &lt;br /&gt; line break, &lt;p&gt; paragraph and &lt;/p&gt; close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.');
}
......@@ -364,11 +375,11 @@ function _filter_autop_tips($format, $long = FALSE) {
}
}
function _filter_url_tips() {
function _filter_url_tips($filter, $format, $long = FALSE) {
return t('Web page addresses and e-mail addresses turn into links automatically.');
}
function _filter_html_escape_tips() {
function _filter_html_escape_tips($filter, $format, $long = FALSE) {
return t('No HTML tags allowed.');
}
......@@ -462,6 +473,11 @@ function filter_format_allowcache($format) {
/**
* Retrieve a list of filters for a certain format.
*
* @param $format
* The format ID.
* @return
* An array of filter objects assosiated to the given format.
*/
function filter_list_format($format) {
static $filters = array();
......@@ -469,10 +485,28 @@ function filter_list_format($format) {
if (!isset($filters[$format])) {
$filters[$format] = array();
$result = db_query("SELECT * FROM {filter} WHERE format = :format ORDER BY weight, module, name", array(':format' => (int) $format));
$result = db_select('filter', 'filter')
->fields('filter')
->condition('format', $format)
->condition('status', 1)
->orderBy('weight')
->orderBy('module')
->orderBy('name')
->execute();
foreach ($result as $filter) {
if (isset($filter_info[$filter->name])) {