source: sandbox/expressoMail1_2/corretor_ortografico/spell_checker/spell_checker.php @ 2477

Revision 2477, 17.5 KB checked in by paula.franceschini, 14 years ago (diff)

Ticket #891 - modificações referentes ao corretor ortografico.

Line 
1<?php
2/**********************************************************************************************
3 * AJAX Spell Checker - Version 2.8
4 * (C) 2005 - Garrison Locke
5 *
6 * This spell checker is built in the style of the Gmail spell
7 * checker.  It uses AJAX to communicate with the backend without
8 * requiring the page be reloaded.  If you use this code, please
9 * give me credit and a link to my site would be nice.
10 * http://www.broken-notebook.com.
11 *
12 * Copyright (c) 2005, Garrison Locke
13 * All rights reserved.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions are met:
17 *
18 *   * Redistributions of source code must retain the above copyright notice,
19 *     this list of conditions and the following disclaimer.
20 *   * Redistributions in binary form must reproduce the above copyright notice,
21 *     this list of conditions and the following disclaimer in the documentation
22 *     and/or other materials provided with the distribution.
23 *   * Neither the name of the http://www.broken-notebook.com nor the names of its
24 *     contributors may be used to endorse or promote products derived from this
25 *     software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
31 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
34 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
36 * OF SUCH DAMAGE.
37 *
38 ***********************************************************************************************/
39
40// User-configurable list of allowed HTML tags and attributes.
41// Thanks to Jake Olefsky for this little addition
42//$allowed_html = '<strong><small><p><br><a><b><u><i><img><code><ul><ol><li>';  //Removed. Accept alll HTML tags.
43
44// Set the max number of suggestions to return at a time.
45define('MAX_SUGGESTIONS', 3);
46
47// Set whether to use a personal dictionary.
48$usePersonalDict = false;
49
50//Set whether users are allowed to update the personal dictionary.
51$editablePersonalDict = false;
52
53// If using a personal dictionary, set the path to it.  Default is in the
54// personal_dictionary subdirectory of the location of spell_checker.php.
55$path_to_personal_dictionary = dirname(__FILE__) . "/personal_dictionary/personal_dictionary.txt";
56
57//If pspell doesn't exist, then include the pspell wrapper for aspell.
58if(!function_exists('pspell_suggest'))
59{
60        // Set the path to aspell if you need to use it.
61        define('ASPELL_BIN','/usr/bin/aspell');
62        require_once ("pspell_comp.php");
63}
64
65// Create and configure a link to the pspell module.
66
67//$pspell_config = pspell_config_create("en");
68pspell_config_mode($pspell_config, PSPELL_FAST);
69
70if($usePersonalDict)
71{
72        // Allows the use of a custom dictionary (Thanks to Dylan Thurston for this addition).
73        pspell_config_personal($pspell_config, $path_to_personal_dictionary);
74}
75
76//$pspell_link = pspell_new_config($pspell_config);
77
78
79require_once("cpaint/cpaint2.inc.php"); //AJAX library file
80
81$cp = new cpaint();
82$cp->register('showSuggestions');
83$cp->register('spellCheck');
84$cp->register('switchText');
85$cp->register('addWord');
86$cp->start();
87$cp->return_data();
88
89
90/*************************************************************
91 * showSuggestions($word, $id)
92 *
93 * The showSuggestions function creates the list of up to 10
94 * suggestions to return for the given misspelled word.
95 *
96 * $word - The misspelled word that was clicked on
97 * $id - The id of the span containing the misspelled word.
98 *
99 *************************************************************/
100function showSuggestions($word, $id, $language)
101{
102        global $editablePersonalDict; //bool to set editability of personal dictionary
103        //global $pspell_link; //the global link to the pspell module
104        $pspell_link = pspell_new($language);
105        global $cp; //the CPAINT object
106       
107        $retVal = "";
108       
109        $suggestions = pspell_suggest($pspell_link, $word);  //an array of all the suggestions that psepll returns for $word.
110       
111        // If the number of suggestions returned by pspell is less than the maximum
112        // number, just use the number of suggestions returned.
113        $numSuggestions = count($suggestions);
114        $tmpNum = min($numSuggestions, MAX_SUGGESTIONS);
115                       
116        if($tmpNum > 0)
117        {
118                //this creates the table of suggestions.
119                //in the onclick event it has a call to the replaceWord javascript function which does the actual replacing on the page
120                for($i=0; $i<$tmpNum; $i++)
121                {
122                        $retVal .= "<div class=\"suggestion\" onclick=\"replaceWord('" . addslashes_custom($id) . "', '" . addslashes(utf8_encode($suggestions[$i])) . "'); return false;\">" . utf8_encode($suggestions[$i]) . "</div>";
123                }
124       
125                if($editablePersonalDict)
126                {
127                        $retVal .= "<div class=\"addtoDictionary\" onclick=\"addWord('" . addslashes_custom($id) . "'); return false;\">Add To Dictionary</div>";
128                }
129
130                //Ignore the suggestion - Added by Nathalie
131                $retVal .= "<div class=\"ignore\" onclick=\"replaceWord('" .  addslashes_custom($id)  . "', '" .   addslashes($word)   . "'); return false;\"> Ignorar </div>";
132
133
134        }
135        else
136        {
137                $retVal .= "Sem sugestão";
138        }
139       
140        $cp->set_data($retVal);  //the return value - a string containing the table of suggestions.
141       
142} // end showSuggestions
143
144 
145/*************************************************************
146 * spellCheck($string)
147 *
148 * The spellCheck function takes the string of text entered
149 * in the text box and spell checks it.  It splits the text
150 * on anything inside of < > in order to prevent html from being
151 * spell checked.  Then any text is split on spaces so that only
152 * one word is spell checked at a time.  This creates a multidimensional
153 * array.  The array is flattened.  The array is looped through
154 * ignoring the html lines and spell checking the others.  If a word
155 * is misspelled, code is wrapped around it to highlight it and to
156 * make it clickable to show the user the suggestions for that
157 * misspelled word.
158 *
159 * $string - The string of text from the text box that is to be
160 *           spell checked.
161 *
162 *************************************************************/
163function spellCheck($string, $varName, $language)
164{
165        //global $pspell_link; //the global link to the pspell module
166        $pspell_link = pspell_new($language);
167        global $cp; //the CPAINT object
168        $retVal = "";
169
170        $string = stripslashes_custom($string); //we only need to strip slashes if magic quotes are on
171
172        $string = remove_word_junk($string);
173
174        //make all the returns in the text look the same
175        $string = preg_replace("/\r?\n/", "\n", $string);
176   
177        //splits the string on any html tags, preserving the tags and putting them in the $words array
178        $words = preg_split("/(<[^<>]*>)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
179   
180        $numResults = count($words); //the number of elements in the array.
181
182        $misspelledCount = 0;   
183   
184        //this loop looks through the words array and splits any lines of text that aren't html tags on space, preserving the spaces.
185        for($i=0; $i<$numResults; $i++){
186                // Words alternate between real words and html tags, starting with words.
187                if(($i & 1) == 0) // Even-numbered entries are word sets.
188                {
189                        $words[$i] = preg_split("/(\s+)/", $words[$i], -1, PREG_SPLIT_DELIM_CAPTURE); //then split it on the spaces
190
191                        // Now go through each word and link up the misspelled ones.
192                        $numWords = count($words[$i]);
193                        for($j=0; $j<$numWords; $j++)
194                        {
195                                $word = utf8_decode($words[$i][$j]);
196
197                                $reg_expr = utf8_decode('A-ZáàâãÀéÚêëíìïîóòÎõöúùûÌÜÿçñÁÀÂÃÄÉÈÊËÍÌÏÎÓÒÔÕÖÚÙÛÜÝÇÑ');
198
199                                preg_match("/[$reg_expr]*/i", $word , $tmp); //get the word that is in the array slot $i
200
201                                $tmpWord = $tmp[0]; //should only have one element in the array anyway, so it's just assign it to $tmpWord
202                                $words[$i][$j] = utf8_decode($words[$i][$j]);
203
204                                //And we replace the word in the array with the span that highlights it and gives it an onClick parameter to show the suggestions.
205                                if(!pspell_check($pspell_link, $tmpWord))
206                                {                                       
207                                        $onClick = "onclick=\"setCurrentObject(" . $varName . "); showSuggestions('" . addslashes($tmpWord) . "', '" . $varName . "_" . $misspelledCount . "_" . addslashes($tmpWord) . "'); return false;\"";
208                                        $words[$i][$j] = str_replace($tmpWord, "<span " . $onClick . " id=\"" . $varName . "_" . $misspelledCount . "_" . $tmpWord . "\" class=\"highlight\">" . stripslashes($tmpWord) . " </span>", $words[$i][$j]);
209                                        $misspelledCount++;
210                                }
211                               
212                                $words[$i][$j] = str_replace("\n", "<br />", $words[$i][$j]); //replace any breaks with <br />'s, for html display
213                               
214                        }//end for $j
215                }//end if
216               
217                else //otherwise, we wrap all the html tags in comments to make them not displayed
218                {
219                        $words[$i] = str_replace("<", "<!--<", $words[$i]);
220                        $words[$i] = str_replace(">", ">-->", $words[$i]);
221                }
222        }//end for $i
223
224        $words = flattenArray($words); //flatten the array to be one dimensional.
225        $numResults = count($words); //the number of elements in the array after it's been flattened.
226       
227        $string = ""; //return string 
228   
229        //if there were no misspellings, start the string with a 0.
230        if($misspelledCount == 0)
231        {
232                $string = "0";
233        }
234       
235        else //else, there were misspellings, start the string with a 1.
236        {
237                $string = "1";
238        }
239       
240        // Concatenate all the words/tags/etc. back into a string and append it to the result.
241        $string .= implode('', $words);
242
243        $string = preg_replace("/<!--</i", "<", $string);  //Retira os comentários das tags HTML
244        $string = preg_replace("/>-->/i", ">", $string);
245       
246        ////Function Removed from the original. Accept alll HTML tags.
247        //remove comments from around all html tags except for <a> because we don't want the links to be clickable
248        //but we want the html to be rendered in the div for preview purposes.
249        /*$string = preg_replace("/<!--<br( [^>]*)?>-->/i", "<br />", $string);
250        $string = preg_replace("/<!--<p( [^>]*)?>-->/i", "<p>", $string);
251        $string = preg_replace("/<!--<\/p>-->/i", "</p>", $string);
252        $string = preg_replace("/<!--<b( [^>]*)?>-->/i", "<b>", $string);
253        $string = preg_replace("/<!--<\/b>-->/i", "</b>", $string);
254        $string = preg_replace("/<!--<strong( [^>]*)?>-->/i", "<strong>", $string);
255        $string = preg_replace("/<!--<\/strong>-->/i", "</strong>", $string);
256        $string = preg_replace("/<!--<i( [^>]*)?>-->/i", "<i>", $string);
257        $string = preg_replace("/<!--<\/i>-->/i", "</i>", $string);
258        $string = preg_replace("/<!--<small( [^>]*)?>-->/i", "<small>", $string);
259        $string = preg_replace("/<!--<\/small>-->/i", "</small>", $string);
260        $string = preg_replace("/<!--<ul( [^>]*)?>-->/i", "<ul>", $string);
261        $string = preg_replace("/<!--<\/ul>-->/i", "</ul>", $string);
262        $string = preg_replace("/<!--<li( [^>]*)?>-->/i", "<li>", $string);
263        $string = preg_replace("/<!--<\/li>-->/i", "</li>", $string);
264        $string = preg_replace("/<!--<img (?:[^>]+ )?src=\"?([^\"]*)\"?[^>]*>-->/i", "<img src=\"\\1\" />", $string);
265<<<<<<< .mine
266
267        $string = preg_replace("/<!--<table( [^>]*)?>-->/i", "<table border=\"\\\" >", $string);
268        $string = preg_replace("/<!--<\/table>-->/i", "</table>", $string);
269        $string = preg_replace("/<!--<td( [^>]*)?>-->/i", "<td>", $string);
270        $string = preg_replace("/<!--<\/td>-->/i", "</td>", $string);
271        $string = preg_replace("/<!--<tbody( [^>]*)?>-->/i", "<tbody>", $string);
272        $string = preg_replace("/<!--<\/tbody>-->/i", "</tbody>", $string);
273        $string = preg_replace("/<!--<tr( [^>]*)?>-->/i", "<tr>", $string);
274        $string = preg_replace("/<!--<\/tr>-->/i", "</tr>", $string);*/
275               
276        $cp->set_data(utf8_encode($string));  //return value - string containing all the markup for the misspelled words.
277
278} // end spellCheck
279
280
281/*************************************************************
282 * addWord($str)
283 *
284 * This function adds a word to the custom dictionary
285 *
286 * @param $str The word to be added
287 *************************************************************/
288function addWord($str)
289{
290        global $editablePersonalDict;
291        //global $pspell_link; //the global link to the pspell module
292        $pspell_link = pspell_new("pt_BR");
293        global $cp; //the CPAINT object
294        $retVal = "";
295        pspell_add_to_personal($pspell_link, $str);
296        if($editablePersonalDict && pspell_save_wordlist($pspell_link))
297        {
298                $retVal = "Save successful!";
299        }
300       
301        else
302        {
303                $retVal = "Save Failed!";
304        }
305       
306        $cp->set_data($retVal);
307} // end addWord
308
309
310
311/*************************************************************
312 * flattenArray($array)
313 *
314 * The flattenArray function is a recursive function that takes a
315 * multidimensional array and flattens it to be a one-dimensional
316 * array.  The one-dimensional flattened array is returned.
317 *
318 * $array - The array to be flattened.
319 *
320 *************************************************************/
321function flattenArray($array)
322{
323        $flatArray = array();
324        foreach($array as $subElement)
325        {
326        if(is_array($subElement))
327                {
328                        $flatArray = array_merge($flatArray, flattenArray($subElement));
329                }
330                else
331                {
332                        $flatArray[] = $subElement;
333                }
334        }
335       
336        return $flatArray;
337} // end flattenArray
338
339
340/*************************************************************
341 * stripslashes_custom($string)
342 *
343 * This is a custom stripslashes function that only strips
344 * the slashes if magic quotes are on.  This is written for
345 * compatibility with other servers in the event someone doesn't
346 * have magic quotes on.
347 *
348 * $string - The string that might need the slashes stripped.
349 *
350 *************************************************************/
351function stripslashes_custom($string)
352{
353        if(get_magic_quotes_gpc())
354        {
355                return stripslashes($string);
356        }
357        else
358        {
359                return $string;
360        }
361} // end stripslashes_custom
362
363/*************************************************************
364 * addslashes_custom($string)
365 *
366 * This is a custom addslashes function that only adds
367 * the slashes if magic quotes are off.  This is written for
368 * compatibility with other servers in the event someone doesn't
369 * have magic quotes on.
370 *
371 * $string - The string that might need the slashes added.
372 *
373 *************************************************************/
374function addslashes_custom($string)
375{
376        if(!get_magic_quotes_gpc())
377        {
378                return addslashes($string);
379        }
380        else
381        {
382                return $string;
383        }
384} // end addslashes_custom
385
386
387/*************************************************************
388 * remove_word_junk($t)
389 *
390 * This function strips out all the crap that Word tries to
391 * add to it's text in the even someone pastes in code from
392 * Word.
393 *
394 * $t - The text to be cleaned
395 *
396 *************************************************************/
397function remove_word_junk($t)
398{
399        $a=array(
400        "\xe2\x80\x9c"=>'"',
401        "\xe2\x80\x9d"=>'"',
402        "\xe2\x80\x99"=>"'",
403        "\xe2\x80\xa6"=>"...",
404        "\xe2\x80\x98"=>"'",
405        "\xe2\x80\x94"=>"---",
406        "\xe2\x80\x93"=>"--",
407        "\x85"=>"...",
408        "\221"=>"'",
409        "\222"=>"'",
410        "\223"=>'"',
411        "\224"=>'"',
412        "\x97"=>"---",
413        "\x96"=>"--"
414        );
415
416        foreach($a as $k=>$v){
417                $oa[]=$k;
418                $ra[]=$v;
419        }
420       
421        $t=trim(str_replace($oa,$ra,$t));
422        return $t;
423
424} // end remove_word_junk
425
426
427/*************************************************************
428 * switchText($string)
429 *
430 * This function prepares the text to be sent back to the text
431 * box from the div.  The comments are removed and breaks are
432 * converted back into \n's.  All the html tags that the user
433 * might have entered that aren't on the approved list:
434 * <p><br><a><b><strong><i><small><ul><li> are stripped out.
435 * The user-entered returns have already been replaced with
436 * $u2026 so that they can be preserved.  I replace all the
437 * \n's that might have been added by the browser (Firefox does
438 * this in trying to pretty up the HTML) with " " so that
439 * everything will look the way it did when the user typed it
440 * in the box the first time.
441 *
442 * $string - The string of html from the div that will be sent
443 *           back to the text box.
444 *
445 *************************************************************/
446function switchText($string)
447{
448        global $allowed_html;
449        global $cp; //the CPAINT object
450        $string = remove_word_junk($string);
451        $string = preg_replace("/<!--/", "", $string);
452        $string = preg_replace("/-->/", "", $string);   
453        $string = preg_replace("/\r?\n/", " ", $string);
454        $string = stripslashes_custom($string); //we only need to strip slashes if magic quotes are on
455        //$string = strip_tags($string, $allowed_html); //Removed. Accept all HTML tags.
456        $string = preg_replace('{&lt;/?span.*?&gt;}i', '', $string);
457        $string = html_entity_decode($string);
458
459        $cp->set_data($string); //the return value
460     
461       
462} // end switchText
463
464?>
Note: See TracBrowser for help on using the repository browser.