source: trunk/lib/SpellCheck.inc.php @ 503

Last change on this file since 503 was 503, checked in by anonymous, 9 years ago

Backported spellcheck fixes

File size: 16.4 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-2012 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
64    protected $_params = array(
65        'language' => 'en',
66        'personal_wordlist' => '', // Text file to save custom words to.
67        'skip_length' => 3, // Words with this many chars or less will not be checked.
68        'mode' => PSPELL_NORMAL, // PSPELL_FAST, PSPELL_NORMAL, or PSPELL_BAD_SPELLERS.
69        'highlight_start' => '<strong style="color:red;">',
70        'highlight_end' => '</strong>',
71    );
72
73    protected $_pspell_cfg_handle;
74    protected $_pspell_handle;
75    protected $_use_personal_wordlist = false;
76    protected $_errors = array();
77
78    /**
79     * Constructor.
80     *
81     * @param  array    $params     Array of parameters (key => val pairs).
82     */
83    public function __construct($params)
84    {
85        $app =& App::getInstance();
86
87        if (!extension_loaded('pspell')) {
88            trigger_error('Pspell module not installed', E_USER_ERROR);
89        }
90
91        if (!is_array($params) || empty($params)) {
92            trigger_error('SpellCheck parameters not set properly', E_USER_ERROR);
93        }
94
95        $this->setParam($params);
96
97        $this->_pspell_cfg_handle = pspell_config_create($this->getParam('language'));
98
99        pspell_config_ignore($this->_pspell_cfg_handle, $this->getParam('skip_length'));
100        pspell_config_mode($this->_pspell_cfg_handle, $this->getParam('mode'));
101
102        if ('' != $this->getParam('personal_wordlist')) {
103            if (!is_writable(dirname($this->getParam('personal_wordlist'))) || !is_writable($this->getParam('personal_wordlist'))) {
104                $app->logMsg(sprintf('Personal wordlist file not writable: %s', $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
105            } else {
106                pspell_config_personal($this->_pspell_cfg_handle, $this->getParam('personal_wordlist'));
107                $this->_use_personal_wordlist = true;
108                $app->logMsg(sprintf('Using personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
109            }
110        }
111
112        $this->_pspell_handle = pspell_new_config($this->_pspell_cfg_handle);
113    }
114
115    /**
116     * Set (or overwrite existing) parameters by passing an array of new parameters.
117     *
118     * @access public
119     * @param  array    $params     Array of parameters (key => val pairs).
120     */
121    public function setParam($params)
122    {
123        $app =& App::getInstance();
124
125        if (isset($params) && is_array($params)) {
126            // Merge new parameters with old overriding only those passed.
127            $this->_params = array_merge($this->_params, $params);
128        } else {
129            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
130        }
131    }
132
133    /**
134     * Return the value of a parameter, if it exists.
135     *
136     * @access public
137     * @param string $param        Which parameter to return.
138     * @return mixed               Configured parameter value.
139     */
140    public function getParam($param)
141    {
142        $app =& App::getInstance();
143
144        if (array_key_exists($param, $this->_params)) {
145            return $this->_params[$param];
146        } else {
147            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
148            return null;
149        }
150    }
151
152    /**
153     * Check whether any errors have been triggered.
154     *
155     * @return bool   True if any errors were found, false otherwise.
156     */
157    public function anyErrors()
158    {
159        return (sizeof($this->_errors) > 0);
160    }
161
162    /**
163     * Reset the error list.
164     */
165    public function resetErrorList()
166    {
167        $this->_errors = array();
168    }
169
170    /**
171     * Check one word.
172     *
173     * @access  public
174     * @param   string  $word
175     * @return  bool    True if word is correct.
176     * @author  Quinn Comendant <quinn@strangecode.com>
177     * @version 1.0
178     * @since   09 Jun 2005 18:23:51
179     */
180    public function check($word)
181    {
182        if (pspell_check($this->_pspell_handle, $word)) {
183            return true;
184        } else {
185            $this->_errors[] = $word;
186            return false;
187        }
188    }
189
190    /**
191     * Suggest the correct spelling for one misspelled word.
192     *
193     * @access  public
194     * @param   string  $word
195     * @return  array   Word suggestions.
196     * @author  Quinn Comendant <quinn@strangecode.com>
197     * @version 1.0
198     * @since   09 Jun 2005 18:23:51
199     */
200    public function suggest($word)
201    {
202        return pspell_suggest($this->_pspell_handle, $word);
203    }
204
205    /**
206     * Add a word to a personal list.
207     *
208     * @access  public
209     * @param   string  $word
210     * @return  array   Word suggestions.
211     * @author  Quinn Comendant <quinn@strangecode.com>
212     * @version 1.0
213     * @since   09 Jun 2005 18:23:51
214     */
215    public function add($word)
216    {
217        $app =& App::getInstance();
218
219        if ($this->_use_personal_wordlist) {
220            if (pspell_add_to_personal($this->_pspell_handle, $word)) {
221                $app->logMsg(sprintf('Added "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
222                return true;
223            } else {
224                $app->logMsg(sprintf('Failed adding "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
225                return false;
226            }
227        }
228    }
229
230    /**
231     * Save personal list to file.
232     *
233     * @access  public
234     * @param   string  $word
235     * @return  array   Word suggestions.
236     * @author  Quinn Comendant <quinn@strangecode.com>
237     * @version 1.0
238     * @since   09 Jun 2005 18:23:51
239     */
240    public function save()
241    {
242        $app =& App::getInstance();
243
244        if ($this->_use_personal_wordlist) {
245            if (pspell_save_wordlist($this->_pspell_handle)) {
246                $app->logMsg(sprintf('Saved personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
247                return true;
248            } else {
249                $app->logMsg(sprintf('Failed saving personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_ERR, __FILE__, __LINE__);
250                return false;
251            }
252        }
253    }
254
255    /**
256     * Returns an array of suggested words for each misspelled word in the given text.
257     * The first word of the returned array is the (possibly) misspelled word.
258     *
259     * @access  public
260     * @param   string  $string String to get suggestions for.
261     * @return  mixed   Array of suggested words or false if none.
262     * @author  Quinn Comendant <quinn@strangecode.com>
263     * @version 1.0
264     * @since   09 Jun 2005 21:29:49
265     */
266    public function getStringSuggestions($string)
267    {
268        $corrections = array();
269        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
270        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
271        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
272        if (is_array($words) && !empty($words)) {
273            // Remove non-word elements.
274            $words = preg_grep('/\w+/', $words);
275            $words = array_map('strip_tags', $words);
276            foreach ($words as $i => $word) {
277                if (!$this->check($word)) {
278                    $corrections[$i] = $this->suggest($word);
279                    // Keep the original spelling as one of the suggestions.
280                    array_unshift($corrections[$i], $word);
281                    array_unique($corrections[$i]);
282                }
283            }
284        }
285        if (is_array($corrections) && !empty($corrections)) {
286            return $corrections;
287        } else {
288            return false;
289        }
290    }
291
292    /**
293     * Checks all words in a given string.
294     *
295     * @access  public
296     * @param   string  $string     String to check.
297     * @return  void
298     * @author  Quinn Comendant <quinn@strangecode.com>
299     * @version 1.0
300     * @since   09 Jun 2005 22:11:27
301     */
302    public function checkString($string)
303    {
304        $errors = array();
305        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
306        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
307        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
308        if (is_array($words) && !empty($words)) {
309            // Remove non-word elements.
310            $words = preg_grep('/\w+/', $words);
311            $words = array_map('strip_tags', $words);
312            foreach ($words as $i => $word) {
313                if (!$this->check($word)) {
314                    $errors[] = $word;
315                }
316            }
317        }
318        if (empty($errors)) {
319            return true;
320        } else {
321            $this->_errors = $errors + $this->_errors;
322            return false;
323        }
324    }
325
326    /**
327     * Returns a given string with misspelled words highlighted.
328     *
329     * @access  public
330     * @param   string  $string     Text to highlight.
331     * @return  string  Highlighted text.
332     * @author  Quinn Comendant <quinn@strangecode.com>
333     * @version 1.0
334     * @since   09 Jun 2005 21:29:49
335     */
336    public function getStringHighlighted($string, $show_footnote=false)
337    {
338        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
339        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
340        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
341        $cnt = 0;
342        if (is_array($words) && !empty($words)) {
343            $words = preg_grep('/\w+/', $words);
344            $words = array_map('strip_tags', $words);
345            foreach ($words as $i => $word) {
346                if (!$this->check($word)) {
347                    $footnote = $show_footnote ? '<sup style="color:#999;">' . ++$cnt . '</sup>' : '';
348                    $words[$i] = $this->getParam('highlight_start') . $word . $this->getParam('highlight_end') . $footnote;
349                    $string = preg_replace(sprintf('/\b%s\b/', preg_quote($word, '/')), $words[$i], $string);
350                }
351            }
352        }
353        return $string;
354    }
355
356    /**
357     * Prints the HTML for correcting all misspellings found in the text of one $_FORM element.
358     *
359     * @access  public
360     * @param   string  $form_name  Name of the form to check.
361     * @return  void
362     * @author  Quinn Comendant <quinn@strangecode.com>
363     * @version 1.0
364     * @since   09 Jun 2005 21:29:49
365     */
366    public function printCorrectionForm($form_name)
367    {
368        ?>
369        <input name="<?php echo $form_name ?>" type="hidden" value="<?php echo oTxt(getFormData($form_name)) ?>" />
370        <?php
371
372        $form_words = $this->getStringSuggestions(getFormData($form_name));
373        if (is_array($form_words) && !empty($form_words)) {
374            ?><ol><?php
375            foreach ($form_words as $i => $words) {
376                ?>
377                <li>
378                <label style="color:#999;"><sub style="vertical-align:text-top;"><?php echo $j++; ?></sub></label>
379                <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;">
380                <?php $original_word = array_shift($words); ?>
381                <option value="<?php echo $original_word ?>">(<?php echo $original_word ?>)</option>
382                <?php
383
384                foreach ($words as $suggestion) {
385                    ?>
386                    <option value="<?php echo $suggestion ?>"><?php echo $suggestion ?></option>
387                    <?php
388                }
389
390                ?>
391                </select>
392                <input type="text" name="spelling_corrections[<?php echo $form_name ?>][<?php echo $i ?>]" value="<?php echo oTxt($original_word) ?>" size="20">
393                <?php if ($this->_use_personal_wordlist) { ?>
394                <input name="save_to_personal_wordlist[]" type="checkbox" value="<?php echo $i ?>" /><?php echo _("Learn spelling") ?>
395                <?php } ?>
396                </li>
397                <?php
398            }
399            ?></ol><?php
400        }
401    }
402
403    /**
404     * Tests if any form spelling corrections have been submitted.
405     *
406     * @access  public
407     * @return  bool    True if form spelling has been checked.
408     * @author  Quinn Comendant <quinn@strangecode.com>
409     * @version 1.0
410     * @since   09 Jun 2005 23:15:35
411     */
412    public function anyFormCorrections()
413    {
414        return (false !== getFormData('spelling_suggestions', false)) || (false !== getFormData('spelling_corrections', false));
415    }
416
417    /**
418     * Replace the misspelled words in the text of a specified form with the corrections.
419     *
420     * @access  public
421     * @param   string  $form_name      Name of form to apply corrections to.
422     * @return  string  Corrected form text.
423     * @author  Quinn Comendant <quinn@strangecode.com>
424     * @version 1.0
425     * @since   09 Jun 2005 23:18:51
426     */
427    public function applyFormCorrections($form_name)
428    {
429        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
430        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
431        $form_words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", getFormData($form_name), -1, PREG_SPLIT_DELIM_CAPTURE);
432        $suggestions = getFormData('spelling_suggestions');
433        $corrections = getFormData('spelling_corrections');
434
435        $form_words = array_diff($corrections[$form_name], array('')) + $suggestions[$form_name] + $form_words;
436        ksort($form_words);
437
438        if ($this->_use_personal_wordlist) {
439            $save_to_personal_wordlist = getFormData('save_to_personal_wordlist');
440            if (is_array($save_to_personal_wordlist) && !empty($save_to_personal_wordlist)) {
441                foreach ($save_to_personal_wordlist as $cust) {
442                    $this->add($form_words[$cust]);
443                }
444            }
445            $this->save();
446        }
447
448        if (is_array($form_words) && !empty($form_words)) {
449            return join('', $form_words);
450        } else {
451            return getFormData($form_name);
452        }
453    }
454
455} // End.
456
Note: See TracBrowser for help on using the repository browser.