Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
73
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 12 MANIPULATING USER INPUT: THE FILTER SYSTEM

Tip sha256 is an algorithm for computing the hash value of a string of text. Drupal uses this as an efficient index column in the database for finding the filtered data of a node.

Now you could get really clever and say, “Well, what if we resave the filtered text back to the node table in our node_view hook? Then it would behave the same as the filter system.” Although that certainly addresses the performance issue, you’d be breaking a fundamental concept of the Drupal architecture: never alter a user’s original data. Imagine that one of your novice users goes back to edit a post only to find it smothered in HTML angle brackets. You’ll most certainly be getting a tech support call on that one. The goal of the filter system is to leave the original data untouched while making cached copies of the filtered data available to the rest of the Drupal framework. You’ll see this principle over and over again with other Drupal APIs.

Note The filter system will cache its data even when caching is disabled at the page level in Drupal. If you’re seeing stale, filtered data, try emptying the cache_filter table by clicking the “Clear cached data” button at the top of the Configuration -> Performance page.

Creating a Custom Filter

Sure, Drupal filters can make links, format your content, and transform text to pirate-speak on the fly, but what would be really slick would be for it to write our blog entries for us, or at least help us get our creative juices flowing. Sure, it can do that, too! Let’s build a module with a filter to insert random sentences into a blog entry. We’ll set it up so that when you run out of juice in your post and need a creative spurt, you can simply type [juice!] while writing, and when you save your entry, it’ll be replaced with a randomly generated sentence. We’ll also make it so that if you need lots of creative juice, you can use the [juice!] tag multiple times per post.

Create a folder named creativejuice located in sites/all/modules/custom/. First, add the creativejuice.info file to the creativejuice folder:

name = Creative Juice

description = "Adds a random sentence filter to content." package = Pro Drupal Development

core = 7.x

files[] = creativejuice.module php = 5.2

301

CHAPTER 12 MANIPULATING USER INPUT: THE FILTER SYSTEM

Next, create the creativejuice.module file and add it, too:

<?php

/**

*@file

*A silly module to assist whizbang novelists who are in a rut by providing a

*random sentence generator for their posts.

*/

Implementing hook_filter_info()

Now that the basics of the module are in place, let’s add our implementation of hook_filter_info() to creativejuice.module:

/**

* Implement hook_filter_info(). */

function creativejuice_filter_info() { $filters = array(); $filters['creativejuice'] = array(

'title' => t('Creative Juice filter'),

'description' => t('Enables users to insert random sentences into their post'), 'process callback' => '_creativejuice_filter_process',

'tips callback' => '_creativejuice_filter_tips',

);

return $filters;

}

The Process Function

The process function creativejuice_filter_process is called every time a node is saved—when the input type set for the node matches a text filter where the creative juices filter is enabled.

/**

*Creativejuice filter process callback

*The actual filtering is performed here. The supplied text should be

*returned, once any necessary substitutions have taken place.

*/

function _creativejuice_filter_process($text, $filter, $format) { while (strpos($text, '[juice!]') !== FALSE) {

$sentence = creativejuice_sentence();

$text = preg_replace('&\[juice!\]&', $sentence, $text, 1);

}

return $text;

}

302

CHAPTER 12 MANIPULATING USER INPUT: THE FILTER SYSTEM

The function is relatively simple. The first step is to call a helper function that returns a random sentence, and the second line of code simply uses the PHP string replace function to replace every instance of [juice!] with the random string returned from the creativejuice_sentence helper function.

Helper Function

I’ve created a helper function that returns a random sentence that will be used by the filter to replace the [juice!] tag.

/**

* Generate a random sentence. */

function creativejuice_sentence() { $beginnings = array();

$beginnings[] = t('A majority of us believe'); $beginnings[] = t('Generally speaking,'); $beginnings[] = t('As times carry on'); $beginnings[] = t('Barren in intellect,'); $beginnings[] = t('Deficient in insight,');

$beginnings[] = t('As blazing blue sky pours down torrents of light,'); $beginnings[] = t('Aloof from the motley throng,');

$beginnings[] = t('While crafting a new Drupal module,');

$middles = array();

$middles[] = t('life flowed in its accustomed stream'); $middles[] = t('he ransacked the vocabulary');

$middles[] = t('the grimaces and caperings of buffoonery sting'); $middles[] = t('the mind freezes at the thought');

$middles[] = t('reverting to another matter enables freedom'); $middles[] = t('he lived as modestly as a hermit'); $middles[] = t('the coder repeatedly invoked hooks');

$ends =

array();

$ends[]

= t('through the red tape of officialdom.');

$ends[]

= t('as it set anew in some fresh and appealing form.');

$ends[]

= t('supported by evidence.');

$ends[]

= t('as fatal as the fang of the most venomous snake.');

$ends[]

= t('as full of spirit as a gray squirrel.');

$ends[]

= t('as dumb as a fish.');

$ends[]

= t('like a damp-handed auctioneer.');

$ends[]

= t('like a bald ferret.');

$ends[]

= t('with a frozen, sharpened badger.');

$ends[]

= t('and achieve CMS nirvanna.');

303

CHAPTER 12 MANIPULATING USER INPUT: THE FILTER SYSTEM

//For every phrase group, pick a random value. $sentence = array(

$beginnings[mt_rand(0, count($beginnings) - 1)], $middles[mt_rand(0, count($middles) - 1)], $ends[mt_rand(0, count($ends) - 1)],

);

//Take the three random values from the sentence groups,

//implode them together, and return the sentence. return implode(' ', $sentence);

}

The function is pretty simple—it creates an array of sentences and randomly picks a sentence to return to the calling function.

You use _creativejuice_filter_tips() to display help text to the end user. By default, a short message is shown with a link to http://example.com/?q=filter/tips, where more detailed instructions are given for each filter.

/**

*Filter tips callback for creative juice filter.

*The tips callback allows filters to provide help text to users during the content

*editing process. Short tips are provided on the content editing screen, while

*long tips are provided on a separate linked page. Short tips are optional,

*but long tips are highly recommended.

*/

function _creativejuice_filter_tips($filter, $format, $long = FALSE) {

return t('<em>[creativejuice]</em> is replaced with the random sentences.');

}

In the preceding code, you return the same text for either the brief or long help text page, but if you wanted to return a longer explanation of the text, you’d check the $long parameter as follows:

function _creativejuice filter_tips($filter, $format, $long = FALSE) { if ($long) {

// Detailed explanation for http://example.com/?q=filter/tips page. return t('The Creative Juice filter is for those times when your

brain is incapable of being creative. These times come for everyone, when even strong coffee and a barrel of jelly beans do not

create the desired effect. When that happens, you can simply enter the [juice!] tag into your posts...'

);

}

else {

// Short explanation for underneath a post's textarea.

return t('Insert a random sentence into your post with the [juice!] tag.');

}

}

304

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]