source: trunk/lib/SpellCheck.inc.php

Last change on this file was 710, checked in by anonymous, 4 years ago
File size: 16.2 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            }
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    public 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    public function getParam($param)
140    {
141        $app =& App::getInstance();
142
143        if (array_key_exists($param, $this->_params)) {
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    public function anyErrors()
157    {
158        return (sizeof($this->_errors) > 0);
159    }
160
161    /**
162     * Reset the error list.
163     */
164    public 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    public 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    public 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    public 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_NOTICE, __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    public 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    public function getStringSuggestions($string)
266    {
267        $corrections = array();
268        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
269        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
270        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
271        if (is_array($words) && !empty($words)) {
272            // Remove non-word elements.
273            $words = preg_grep('/\w+/', $words);
274            $words = array_map('strip_tags', $words);
275            foreach ($words as $i => $word) {
276                if (!$this->check($word)) {
277                    $corrections[$i] = $this->suggest($word);
278                    // Keep the original spelling as one of the suggestions.
279                    array_unshift($corrections[$i], $word);
280                    array_unique($corrections[$i]);
281                }
282            }
283        }
284        if (is_array($corrections) && !empty($corrections)) {
285            return $corrections;
286        } else {
287            return false;
288        }
289    }
290
291    /**
292     * Checks all words in a given string.
293     *
294     * @access  public
295     * @param   string  $string     String to check.
296     * @return  void
297     * @author  Quinn Comendant <quinn@strangecode.com>
298     * @version 1.0
299     * @since   09 Jun 2005 22:11:27
300     */
301    public function checkString($string)
302    {
303        $errors = array();
304        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
305        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
306        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
307        if (is_array($words) && !empty($words)) {
308            // Remove non-word elements.
309            $words = preg_grep('/\w+/', $words);
310            $words = array_map('strip_tags', $words);
311            foreach ($words as $i => $word) {
312                if (!$this->check($word)) {
313                    $errors[] = $word;
314                }
315            }
316        }
317        if (empty($errors)) {
318            return true;
319        } else {
320            $this->_errors = $errors + $this->_errors;
321            return false;
322        }
323    }
324
325    /**
326     * Returns a given string with misspelled words highlighted.
327     *
328     * @access  public
329     * @param   string  $string     Text to highlight.
330     * @return  string  Highlighted text.
331     * @author  Quinn Comendant <quinn@strangecode.com>
332     * @version 1.0
333     * @since   09 Jun 2005 21:29:49
334     */
335    public function getStringHighlighted($string, $show_footnote=false)
336    {
337        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
338        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
339        $words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
340        $cnt = 0;
341        if (is_array($words) && !empty($words)) {
342            $words = preg_grep('/\w+/', $words);
343            $words = array_map('strip_tags', $words);
344            foreach ($words as $i => $word) {
345                if (!$this->check($word)) {
346                    $footnote = $show_footnote ? '<sup style="color:#999;">' . ++$cnt . '</sup>' : '';
347                    $words[$i] = $this->getParam('highlight_start') . $word . $this->getParam('highlight_end') . $footnote;
348                    $string = preg_replace(sprintf('/\b%s\b/', preg_quote($word, '/')), $words[$i], $string);
349                }
350            }
351        }
352        return $string;
353    }
354
355    /**
356     * Prints the HTML for correcting all misspellings found in the text of one $_FORM element.
357     *
358     * @access  public
359     * @param   string  $form_name  Name of the form to check.
360     * @return  void
361     * @author  Quinn Comendant <quinn@strangecode.com>
362     * @version 1.0
363     * @since   09 Jun 2005 21:29:49
364     */
365    public function printCorrectionForm($form_name)
366    {
367        ?>
368        <input name="<?php echo $form_name ?>" type="hidden" value="<?php echo oTxt(getFormData($form_name)) ?>" />
369        <?php
370
371        $form_words = $this->getStringSuggestions(getFormData($form_name));
372        if (is_array($form_words) && !empty($form_words)) {
373            ?><ol><?php
374            foreach ($form_words as $i => $words) {
375                ?>
376                <li>
377                <label style="color:#999;"><sub style="vertical-align:text-top;"><?php echo $j++; ?></sub></label>
378                <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;">
379                <?php $original_word = array_shift($words); ?>
380                <option value="<?php echo $original_word ?>">(<?php echo $original_word ?>)</option>
381                <?php
382
383                foreach ($words as $suggestion) {
384                    ?>
385                    <option value="<?php echo $suggestion ?>"><?php echo $suggestion ?></option>
386                    <?php
387                }
388
389                ?>
390                </select>
391                <input type="text" name="spelling_corrections[<?php echo $form_name ?>][<?php echo $i ?>]" value="<?php echo oTxt($original_word) ?>" size="20">
392                <?php if ($this->_use_personal_wordlist) { ?>
393                <input name="save_to_personal_wordlist[]" type="checkbox" value="<?php echo $i ?>" /><?php echo _("Learn spelling") ?>
394                <?php } ?>
395                </li>
396                <?php
397            }
398            ?></ol><?php
399        }
400    }
401
402    /**
403     * Tests if any form spelling corrections have been submitted.
404     *
405     * @access  public
406     * @return  bool    True if form spelling has been checked.
407     * @author  Quinn Comendant <quinn@strangecode.com>
408     * @version 1.0
409     * @since   09 Jun 2005 23:15:35
410     */
411    public function anyFormCorrections()
412    {
413        return (false !== getFormData('spelling_suggestions', false)) || (false !== getFormData('spelling_corrections', false));
414    }
415
416    /**
417     * Replace the misspelled words in the text of a specified form with the corrections.
418     *
419     * @access  public
420     * @param   string  $form_name      Name of form to apply corrections to.
421     * @return  string  Corrected form text.
422     * @author  Quinn Comendant <quinn@strangecode.com>
423     * @version 1.0
424     * @since   09 Jun 2005 23:18:51
425     */
426    public function applyFormCorrections($form_name)
427    {
428        // Split words on punctuation except apostrophes (this regex is used in several places in this class).
429        // http://stackoverflow.com/questions/790596/split-a-text-into-single-words
430        $form_words = preg_split("/((?:^\p{P}+)|(?:\p{P}*\s+\p{P}*)|[\p{Pd}—–-]+|(?:\p{P}+$))/", getFormData($form_name), -1, PREG_SPLIT_DELIM_CAPTURE);
431        $suggestions = getFormData('spelling_suggestions');
432        $corrections = getFormData('spelling_corrections');
433
434        $form_words = array_diff($corrections[$form_name], array('')) + $suggestions[$form_name] + $form_words;
435        ksort($form_words);
436
437        if ($this->_use_personal_wordlist) {
438            $save_to_personal_wordlist = getFormData('save_to_personal_wordlist');
439            if (is_array($save_to_personal_wordlist) && !empty($save_to_personal_wordlist)) {
440                foreach ($save_to_personal_wordlist as $cust) {
441                    $this->add($form_words[$cust]);
442                }
443            }
444            $this->save();
445        }
446
447        if (is_array($form_words) && !empty($form_words)) {
448            return join('', $form_words);
449        } else {
450            return getFormData($form_name);
451        }
452    }
453
454} // End.
455
Note: See TracBrowser for help on using the repository browser.