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

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

Many minor fixes during pulso development

File size: 15.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                $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
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);
272        // Remove non-word elements.
273        $words = preg_grep('/\w+/', $words);
274
275        if (is_array($words) && !empty($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        $words = preg_split('/([\W]+?)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
306        // Remove non-word elements.
307        $check_words = preg_grep('/\w+/', $words);
308
309        if (is_array($check_words) && !empty($check_words)) {
310            foreach ($check_words as $i => $word) {
311                if (!$this->check($word)) {
312                    $errors[] = $word;
313                }
314            }
315        }
316        if (empty($errors)) {
317            return true;
318        } else {
319            $this->_errors = $errors + $this->_errors;
320            return false;
321        }
322    }
323
324    /**
325     * Returns a given string with misspelled words highlighted.
326     *
327     * @access  public
328     * @param   string  $string     Text to highlight.
329     * @return  string  Highlighted text.
330     * @author  Quinn Comendant <quinn@strangecode.com>
331     * @version 1.0
332     * @since   09 Jun 2005 21:29:49
333     */
334    public function getStringHighlighted($string, $show_footnote=false)
335    {
336        $words = preg_split('/([\W]+?)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
337        $check_words = preg_grep('/\w+/', $words);
338        $cnt = 0;
339        if (is_array($check_words) && !empty($check_words)) {
340            foreach ($check_words as $i => $word) {
341                if (!$this->check($word)) {
342                    $footnote = $show_footnote ? '<sup>' . ++$cnt . '</sup>' : '';
343                    $words[$i] = $this->getParam('highlight_start') . $word . $this->getParam('highlight_end') . $footnote;
344                }
345            }
346        }
347        return join('', $words);
348    }
349
350    /**
351     * Prints the HTML for correcting all misspellings found in the text of one $_FORM element.
352     *
353     * @access  public
354     * @param   string  $form_name  Name of the form to check.
355     * @return  void
356     * @author  Quinn Comendant <quinn@strangecode.com>
357     * @version 1.0
358     * @since   09 Jun 2005 21:29:49
359     */
360    public function printCorrectionForm($form_name)
361    {
362        ?>
363        <input name="<?php echo $form_name ?>" type="hidden" value="<?php echo getFormData($form_name) ?>" />
364        <?php
365
366        $form_words = $this->getStringSuggestions(getFormData($form_name));
367        if (is_array($form_words) && !empty($form_words)) {
368            ?><ol><?php
369            foreach ($form_words as $i => $words) {
370                ?>
371                <li>
372                <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;">
373                <?php $original_word = array_shift($words); ?>
374                <option value="<?php echo $original_word ?>">(<?php echo $original_word ?>)</option>
375                <?php
376
377                foreach ($words as $suggestion) {
378                    ?>
379                    <option value="<?php echo $suggestion ?>"><?php echo $suggestion ?></option>
380                    <?php
381                }
382
383                ?>
384                </select>
385                <input type="text" name="spelling_corrections[<?php echo $form_name ?>][<?php echo $i ?>]" value="<?php echo $original_word ?>" class="sc-small" />
386                <?php if ($this->_use_personal_wordlist) { ?>
387                <input name="save_to_personal_wordlist[]" type="checkbox" value="<?php echo $i ?>" /><?php echo _("Learn spelling") ?>
388                <?php } ?>
389                </li>
390                <?php
391            }
392            ?></ol><?php
393        }
394    }
395
396    /**
397     * Tests if any form spelling corrections have been submitted.
398     *
399     * @access  public
400     * @return  bool    True if form spelling has been checked.
401     * @author  Quinn Comendant <quinn@strangecode.com>
402     * @version 1.0
403     * @since   09 Jun 2005 23:15:35
404     */
405    public function anyFormCorrections()
406    {
407        return (false !== getFormData('spelling_suggestions', false)) || (false !== getFormData('spelling_corrections', false));
408    }
409
410    /**
411     * Replace the misspelled words in the text of a specified form with the corrections.
412     *
413     * @access  public
414     * @param   string  $form_name      Name of form to apply corrections to.
415     * @return  string  Corrected form text.
416     * @author  Quinn Comendant <quinn@strangecode.com>
417     * @version 1.0
418     * @since   09 Jun 2005 23:18:51
419     */
420    public function applyFormCorrections($form_name)
421    {
422        $form_words = preg_split('/([\W]+?)/', getFormData($form_name), -1, PREG_SPLIT_DELIM_CAPTURE);
423        $suggestions = getFormData('spelling_suggestions');
424        $corrections = getFormData('spelling_corrections');
425
426        $form_words = array_diff($corrections[$form_name], array('')) + $suggestions[$form_name] + $form_words;
427        ksort($form_words);
428
429        if ($this->_use_personal_wordlist) {
430            $save_to_personal_wordlist = getFormData('save_to_personal_wordlist');
431            if (is_array($save_to_personal_wordlist) && !empty($save_to_personal_wordlist)) {
432                foreach ($save_to_personal_wordlist as $cust) {
433                    $this->add($form_words[$cust]);
434                }
435            }
436            $this->save();
437        }
438
439        if (is_array($form_words) && !empty($form_words)) {
440            return join('', $form_words);
441        } else {
442            return getFormData($form_name);
443        }
444    }
445
446} // End.
447
Note: See TracBrowser for help on using the repository browser.