source: tags/2.1.5/lib/SpellCheck.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

File size: 14.9 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2010 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * SpellCheck.inc.php
25 *
26 * Interface to PHP's pspell functions.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 1.1
30 */
31
32/* Implementation example:
33--------------------------------------------------------------------------------
34include_once dirname(__FILE__) . '/_config.inc.php';
35include 'codebase/lib/SpellCheck.inc.php';
36
37// Instantiate with parameters. In this example we'll set the language and the path to the personal wordlist file.
38$spell = new SpellCheck(array(
39    'language' => 'en',
40    'personal_wordlist' => '/tmp/my_custom_dict'
41));
42
43// Just for the heck of it add a new word to persistent personal wordlist file.
44$spell->add('mealworm');
45
46$text_to_check = 'donky rinds taste like mealworm paste';
47
48if (!$spell->checkString($text_to_check)) {
49    $suggestions = $spell->getStringSuggestions($text_to_check);
50    echo 'Spelling errors! Here are suggested alternatives:';
51    print_r($suggestions);
52} else {
53    echo 'No spelling errors';
54}
55
56// Save added words to persistent custom wordlist file.
57$spell->save();
58--------------------------------------------------------------------------------
59*/
60
61class SpellCheck {
62
63    var $_params = array(
64        'language' => 'en',
65        'personal_wordlist' => '', // Text file to save custom words to.
66        'skip_length' => 3, // Words with this many chars or less will not be checked.
67        'mode' => PSPELL_NORMAL, // PSPELL_FAST, PSPELL_NORMAL, or PSPELL_BAD_SPELLERS.
68        'highlight_start' => '<strong style="color:red;">',
69        'highlight_end' => '</strong>',
70    );
71
72    var $_pspell_cfg_handle;
73    var $_pspell_handle;
74    var $_use_personal_wordlist = false;
75    var $_errors = array();
76
77    /**
78     * Constructor.
79     *
80     * @param  array    $params     Array of parameters (key => val pairs).
81     */
82    function SpellCheck($params)
83    {
84        $app =& App::getInstance();
85
86        if (!extension_loaded('pspell')) {
87            trigger_error('Pspell module not installed', E_USER_ERROR);
88        }
89
90        if (!is_array($params) || empty($params)) {
91            trigger_error('SpellCheck parameters not set properly', E_USER_ERROR);
92        }
93
94        $this->setParam($params);
95
96        $this->_pspell_cfg_handle = pspell_config_create($this->getParam('language'));
97
98        pspell_config_ignore($this->_pspell_cfg_handle, $this->getParam('skip_length'));
99        pspell_config_mode($this->_pspell_cfg_handle, $this->getParam('mode'));
100
101        if ('' != $this->getParam('personal_wordlist')) {
102            if (!is_writable(dirname($this->getParam('personal_wordlist'))) || !is_writable($this->getParam('personal_wordlist'))) {
103                $app->logMsg(sprintf('Personal wordlist file not writable: %s', $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
104            } else {
105                pspell_config_personal($this->_pspell_cfg_handle, $this->getParam('personal_wordlist'));
106                $this->_use_personal_wordlist = true;
107                $app->logMsg(sprintf('Using personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
108            }
109        }
110
111        $this->_pspell_handle = pspell_new_config($this->_pspell_cfg_handle);
112    }
113
114    /**
115     * Set (or overwrite existing) parameters by passing an array of new parameters.
116     *
117     * @access public
118     * @param  array    $params     Array of parameters (key => val pairs).
119     */
120    function setParam($params)
121    {
122        $app =& App::getInstance();
123
124        if (isset($params) && is_array($params)) {
125            // Merge new parameters with old overriding only those passed.
126            $this->_params = array_merge($this->_params, $params);
127        } else {
128            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
129        }
130    }
131
132    /**
133     * Return the value of a parameter, if it exists.
134     *
135     * @access public
136     * @param string $param        Which parameter to return.
137     * @return mixed               Configured parameter value.
138     */
139    function getParam($param)
140    {
141        $app =& App::getInstance();
142   
143        if (isset($this->_params[$param])) {
144            return $this->_params[$param];
145        } else {
146            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
147            return null;
148        }
149    }
150
151    /**
152     * Check whether any errors have been triggered.
153     *
154     * @return bool   True if any errors were found, false otherwise.
155     */
156    function anyErrors()
157    {
158        return (sizeof($this->_errors) > 0);
159    }
160
161    /**
162     * Reset the error list.
163     */
164    function resetErrorList()
165    {
166        $this->_errors = array();
167    }
168
169    /**
170     * Check one word.
171     *
172     * @access  public
173     * @param   string  $word
174     * @return  bool    True if word is correct.
175     * @author  Quinn Comendant <quinn@strangecode.com>
176     * @version 1.0
177     * @since   09 Jun 2005 18:23:51
178     */
179    function check($word)
180    {
181        if (pspell_check($this->_pspell_handle, $word)) {
182            return true;
183        } else {
184            $this->_errors[] = $word;
185            return false;
186        }
187    }
188
189    /**
190     * Suggest the correct spelling for one misspelled word.
191     *
192     * @access  public
193     * @param   string  $word
194     * @return  array   Word suggestions.
195     * @author  Quinn Comendant <quinn@strangecode.com>
196     * @version 1.0
197     * @since   09 Jun 2005 18:23:51
198     */
199    function suggest($word)
200    {
201        return pspell_suggest($this->_pspell_handle, $word);
202    }
203
204    /**
205     * Add a word to a personal list.
206     *
207     * @access  public
208     * @param   string  $word
209     * @return  array   Word suggestions.
210     * @author  Quinn Comendant <quinn@strangecode.com>
211     * @version 1.0
212     * @since   09 Jun 2005 18:23:51
213     */
214    function add($word)
215    {
216        $app =& App::getInstance();
217
218        if ($this->_use_personal_wordlist) {
219            if (pspell_add_to_personal($this->_pspell_handle, $word)) {
220                $app->logMsg(sprintf('Added "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
221                return true;
222            } else {
223                $app->logMsg(sprintf('Failed adding "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
224                return false;
225            }
226        }
227    }
228
229    /**
230     * Save personal list to file.
231     *
232     * @access  public
233     * @param   string  $word
234     * @return  array   Word suggestions.
235     * @author  Quinn Comendant <quinn@strangecode.com>
236     * @version 1.0
237     * @since   09 Jun 2005 18:23:51
238     */
239    function save()
240    {
241        $app =& App::getInstance();
242
243        if ($this->_use_personal_wordlist) {
244            if (pspell_save_wordlist($this->_pspell_handle)) {
245                $app->logMsg(sprintf('Saved personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
246                return true;
247            } else {
248                $app->logMsg(sprintf('Failed saving personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_ERR, __FILE__, __LINE__);
249                return false;
250            }
251        }
252    }
253
254    /**
255     * Returns an array of suggested words for each misspelled word in the given text.
256     * The first word of the returned array is the (possibly) misspelled word.
257     *
258     * @access  public
259     * @param   string  $string String to get suggestions for.
260     * @return  mixed   Array of suggested words or false if none.
261     * @author  Quinn Comendant <quinn@strangecode.com>
262     * @version 1.0
263     * @since   09 Jun 2005 21:29:49
264     */
265    function getStringSuggestions($string)
266    {
267        $corrections = array();
268        $words = preg_split('/([\W]+?)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
269        // Remove non-word elements.
270        $words = preg_grep('/\w+/', $words);
271
272        if (is_array($words) && !empty($words)) {
273            foreach ($words as $i => $word) {
274                if (!$this->check($word)) {
275                    $corrections[$i] = $this->suggest($word);
276                    // Keep the original spelling as one of the suggestions.
277                    array_unshift($corrections[$i], $word);
278                    array_unique($corrections[$i]);
279                }
280            }
281        }
282        if (is_array($corrections) && !empty($corrections)) {
283            return $corrections;
284        } else {
285            return false;
286        }
287    }
288
289    /**
290     * Checks all words in a given string.
291     *
292     * @access  public
293     * @param   string  $string     String to check.
294     * @return  void
295     * @author  Quinn Comendant <quinn@strangecode.com>
296     * @version 1.0
297     * @since   09 Jun 2005 22:11:27
298     */
299    function checkString($string)
300    {
301        $errors = array();
302        $words = preg_split('/([\W]+?)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
303        // Remove non-word elements.
304        $check_words = preg_grep('/\w+/', $words);
305
306        if (is_array($check_words) && !empty($check_words)) {
307            foreach ($check_words as $i => $word) {
308                if (!$this->check($word)) {
309                    $errors[] = $word;
310                }
311            }
312        }
313        if (empty($errors)) {
314            return true;
315        } else {
316            $this->_errors = $errors + $this->_errors;
317            return false;
318        }
319    }
320
321    /**
322     * Returns a given string with misspelled words highlighted.
323     *
324     * @access  public
325     * @param   string  $string     Text to highlight.
326     * @return  string  Highlighted text.
327     * @author  Quinn Comendant <quinn@strangecode.com>
328     * @version 1.0
329     * @since   09 Jun 2005 21:29:49
330     */
331    function getStringHighlighted($string, $show_footnote=false)
332    {
333        $words = preg_split('/([\W]+?)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
334        $check_words = preg_grep('/\w+/', $words);
335        $cnt = 0;
336        if (is_array($check_words) && !empty($check_words)) {
337            foreach ($check_words as $i => $word) {
338                if (!$this->check($word)) {
339                    $footnote = $show_footnote ? '<sup>' . ++$cnt . '</sup>' : '';
340                    $words[$i] = $this->getParam('highlight_start') . $word . $this->getParam('highlight_end') . $footnote;
341                }
342            }
343        }
344        return join('', $words);
345    }
346
347    /**
348     * Prints the HTML for correcting all misspellings found in the text of one $_FORM element.
349     *
350     * @access  public
351     * @param   string  $form_name  Name of the form to check.
352     * @return  void
353     * @author  Quinn Comendant <quinn@strangecode.com>
354     * @version 1.0
355     * @since   09 Jun 2005 21:29:49
356     */
357    function printCorrectionForm($form_name)
358    {
359        ?>
360        <input name="<?php echo $form_name ?>" type="hidden" value="<?php echo getFormData($form_name) ?>" />
361        <?php
362
363        $form_words = $this->getStringSuggestions(getFormData($form_name));
364        if (is_array($form_words) && !empty($form_words)) {
365            ?><ol><?php
366            foreach ($form_words as $i => $words) {
367                ?>
368                <li>
369                <select name="spelling_suggestions[<?php echo $form_name ?>][<?php echo $i ?>]" onchange"document.forms[0].elements['spelling_corrections[<?php echo $form_name ?>][<?php echo $i ?>]'].value = this.value;">
370                <?php $original_word = array_shift($words); ?>
371                <option value="<?php echo $original_word ?>">(<?php echo $original_word ?>)</option>
372                <?php
373
374                foreach ($words as $suggestion) {
375                    ?>
376                    <option value="<?php echo $suggestion ?>"><?php echo $suggestion ?></option>
377                    <?php
378                }
379
380                ?>
381                </select>
382                <input type="text" name="spelling_corrections[<?php echo $form_name ?>][<?php echo $i ?>]" value="<?php echo $original_word ?>" class="sc-small" />
383                <?php if ($this->_use_personal_wordlist) { ?>
384                <input name="save_to_personal_wordlist[]" type="checkbox" value="<?php echo $i ?>" /><?php echo _("Learn spelling") ?>
385                <?php } ?>
386                </li>
387                <?php
388            }
389            ?></ol><?php
390        }
391    }
392
393    /**
394     * Tests if any form spelling corrections have been submitted.
395     *
396     * @access  public
397     * @return  bool    True if form spelling has been checked.
398     * @author  Quinn Comendant <quinn@strangecode.com>
399     * @version 1.0
400     * @since   09 Jun 2005 23:15:35
401     */
402    function anyFormCorrections()
403    {
404        return (false !== getFormData('spelling_suggestions', false)) || (false !== getFormData('spelling_corrections', false));
405    }
406
407    /**
408     * Replace the misspelled words in the text of a specified form with the corrections.
409     *
410     * @access  public
411     * @param   string  $form_name      Name of form to apply corrections to.
412     * @return  string  Corrected form text.
413     * @author  Quinn Comendant <quinn@strangecode.com>
414     * @version 1.0
415     * @since   09 Jun 2005 23:18:51
416     */
417    function applyFormCorrections($form_name)
418    {
419        $form_words = preg_split('/([\W]+?)/', getFormData($form_name), -1, PREG_SPLIT_DELIM_CAPTURE);
420        $suggestions = getFormData('spelling_suggestions');
421        $corrections = getFormData('spelling_corrections');
422
423        $form_words = array_diff($corrections[$form_name], array('')) + $suggestions[$form_name] + $form_words;
424        ksort($form_words);
425
426        if ($this->_use_personal_wordlist) {
427            $save_to_personal_wordlist = getFormData('save_to_personal_wordlist');
428            if (is_array($save_to_personal_wordlist) && !empty($save_to_personal_wordlist)) {
429                foreach ($save_to_personal_wordlist as $cust) {
430                    $this->add($form_words[$cust]);
431                }
432            }
433            $this->save();
434        }
435
436        if (is_array($form_words) && !empty($form_words)) {
437            return join('', $form_words);
438        } else {
439            return getFormData($form_name);
440        }
441    }
442
443} // End.
444
445?>
Note: See TracBrowser for help on using the repository browser.