예제 #1
0
function showSuggestions($word, $id)
{
    global $editablePersonalDict;
    //bool to set editability of personal dictionary
    global $allowCustomInserts;
    //bool to set the option to allow custom text inserts
    global $pspell_link;
    //the global link to the pspell module
    global $cp;
    //the CPAINT object
    $retVal = "";
    $suggestions = pspell_suggest($pspell_link, utf8_decode($word));
    //an array of all the suggestions that psepll returns for $word.
    // If the number of suggestions returned by pspell is less than the maximum
    // number, just use the number of suggestions returned.
    $numSuggestions = count($suggestions);
    $tmpNum = min($numSuggestions, MAX_SUGGESTIONS);
    if ($tmpNum > 0) {
        //this creates the table of suggestions.
        //in the onclick event it has a call to the replaceWord javascript function which does the actual replacing on the page
        for ($i = 0; $i < $tmpNum; $i++) {
            $retVal .= "<div class=\"suggestion\"  onmouseover=\"this.className='suggestion_hover'\" onmouseout=\"this.className='suggestion'\" onclick=\"replaceWord('" . addslashes_custom($id) . "', '" . addslashes($suggestions[$i]) . "'); return false;\">" . $suggestions[$i] . "</div>";
        }
        if ($allowCustomInserts) {
            $retVal .= "<div class=\"customInsert\" onmouseover=\"this.className='customInsert_hover'\" onmouseout=\"this.className='customInsert'\"><form name=\"custom_form\" style=\"margin:0px;\"><input type=\"text\" id=\"custom_form_box\" class=\"customInsertText\" onclick=\"get_id('custom_form_box').focus(); return false;\"><input type=\"button\" value=\"Insert\" class=\"customInsertAdd\" onclick=\"addWord('" . addslashes_custom($id) . "'); return false;\"></form></div>";
        }
        if ($editablePersonalDict) {
            $retVal .= "<div class=\"addtoDictionary\" onmouseover=\"this.className='addtoDictionary_hover'\" onmouseout=\"this.className='addtoDictionary'\" onclick=\"addWord('" . addslashes_custom($id) . "'); return false;\">Add To Dictionary</div>";
        }
    } else {
        $retVal .= "No Suggestions";
    }
    $cp->set_data($retVal);
    //the return value - a string containing the table of suggestions.
}
예제 #2
0
 /**
  * Suggestion of words coming from the pspell dictionnary in french and english
  *
  * @param string $q Query string
  * @param string $jsfunc The JS function to launch and pass the query string to
  */
 public function spellingSuggestions($q, $jsfunc = 'sugg')
 {
     $toret = '';
     if ($q == '') {
         return ' ... No suggestion possible, the query is empty ... ';
     }
     if (function_exists(pspell_new)) {
         $ss = 0;
         foreach (array('en' => 'English', "fr" => 'French') as $k => $v) {
             $pspellLink = pspell_new($k);
             $suggs = pspell_suggest($pspellLink, $q);
             if (count($suggs) > 0) {
                 $ss++;
                 $toret .= "<b>In " . $v . "</b> : ";
                 foreach ($suggs as $sug) {
                     $toret .= '<a href="javascript:' . $jsfunc . '(\'' . addslashes($sug) . '\')">' . htmlentities($sug) . '</a> &nbsp; ';
                 }
                 $toret .= "<br>";
             }
         }
         if ($ss == 0) {
             $toret .= '... we could not find anything in our dictionnaries ...';
         }
     } else {
         return ' !!! ERROR: the pspell module is not installed !!! ';
     }
     return $toret;
 }
예제 #3
0
 /**
  * Check a word for spelling errors, add to $this->miss_spelled_words
  * array if miss spelled
  *
  * @param string $word
  * @return void
  */
 function check($word)
 {
     global $atmail;
     $word = preg_replace('/[^a-zA-Z\\-]/', '', $word);
     // if the word is in the personal_words array
     // or the ignore list then it is OK. If it is already
     // in the $suggestions array then ignore it
     if (in_array($word, $this->personal_words) || $atmail->isset_chk($this->suggestions[$word]) || in_array($word, $_SESSION['spellcheck_ignore'])) {
         return;
     }
     // if word is OK ignore it
     if ($this->use_pspell) {
         if (pspell_check($this->dict, $word)) {
             return;
         }
         $this->suggestions[$word] = pspell_suggest($this->dict, $word);
     } else {
         fwrite($this->aspell_input, "{$word}\n");
         $result = fgets($this->aspell_output);
         // remove trash from stream
         $trash = fgets($this->aspell_output);
         unset($trash);
         if (preg_match('/.+?\\d:(.+)/', $result, $m)) {
             $this->suggestions[$word] = explode(', ', $m[1]);
         } else {
             return;
         }
     }
 }
예제 #4
0
function getSuggestions($word)
{
    global $editablePersonalDict;
    //bool to set editability of personal dictionary
    global $pspell_link;
    //the global link to the pspell module
    $retVal = "";
    //an array of all the suggestions that psepll returns for $word.
    $suggestions = pspell_suggest($pspell_link, $word);
    // If the number of suggestions returned by pspell is less than the maximum
    // number, just use the number of suggestions returned.
    $numSuggestions = count($suggestions);
    $tmpNum = min($numSuggestions, MAX_SUGGESTIONS);
    if ($tmpNum > 0) {
        //this creates the table of suggestions.
        for ($i = 0; $i < $tmpNum; $i++) {
            $retVal .= '<div class="suggestion">' . $suggestions[$i] . '</div>';
        }
        if ($editablePersonalDict) {
            $retVal .= '<div class="addToDictionary">Add To Dictionary</div>';
        }
    } else {
        $retVal .= "No Suggestions";
    }
    echo $retVal;
    //the return value - a string containing the table of suggestions.
}
 private function pspell()
 {
     foreach ($_REQUEST as $key => $value) {
         ${$key} = html_entity_decode(urldecode(stripslashes(trim($value))));
     }
     // load the dictionary
     $pspell_link = pspell_new_personal($this->pspell_personal_dictionary, $this->lang);
     // return suggestions
     if (isset($suggest)) {
         exit(json_encode(pspell_suggest($pspell_link, urldecode($suggest))));
     } elseif (isset($text)) {
         $words = array();
         foreach ($text = explode(' ', urldecode($text)) as $word) {
             if (!pspell_check($pspell_link, $word) and !in_array($word, $words)) {
                 $words[] = $word;
             }
         }
         exit(json_encode($words));
     } elseif (isset($addtodictionary)) {
         $pspell_config = pspell_config_create('en');
         @pspell_config_personal($pspell_config, $this->pspell_personal_dictionary) or die('can\'t find pspell dictionary');
         $pspell_link = pspell_new_config($pspell_config);
         @pspell_add_to_personal($pspell_link, strtolower($addtodictionary)) or die('You can\'t add a word to the dictionary that contains any punctuation.');
         pspell_save_wordlist($pspell_link);
         exit(array());
     }
 }
예제 #6
0
function spellCheckWord($word)
{
    global $pspell, $bad;
    $autocorrect = TRUE;
    $ignore_words = array("wikihows", "blog", "online", "ipod", "nano");
    // Take the string match from preg_replace_callback's array
    $word = $word[0];
    // Ignore ALL CAPS, and numbers
    if (preg_match('/^[A-Z]*$/', $word)) {
        return;
    }
    if (preg_match('/^[0-9]*$/', $word)) {
        return;
    }
    if (in_array(strtolower($word), $ignore_words)) {
        return;
    }
    // Return dictionary words
    if (pspell_check($pspell, $word)) {
        // this word is OK
        return;
    }
    echo "Bad word {$word} - ";
    $bad++;
    $suggestions = pspell_suggest($pspell, $word);
    if (sizeof($suggestions) > 0) {
        if (sizeof($suggestions) > 5) {
            echo implode(",", array_splice($suggestions, 0, 5)) . "\n";
        } else {
            echo implode(",", $suggestions) . "\n";
        }
    } else {
        echo "no suggestions\n";
    }
}
예제 #7
0
 function getSuggestion($word)
 {
     if (!$this->plink) {
         $this->errorMsg[] = "No PSpell link found for getSuggestion.";
         return array();
     }
     return pspell_suggest($this->plink, $word);
 }
 /**
  * Use pspell to get word suggestions
  * @param string $word
  * @return array
  */
 public function suggest($word)
 {
     if (!pspell_check($this->pSpell, $word)) {
         return pspell_suggest($this->pSpell, $word);
     } else {
         return [$word];
     }
 }
 function suggest($mistake)
 {
     if ($mistake == FALSE) {
         $mistake = $this->lastword;
     }
     $suggest = pspell_suggest($this->resid, $mistake);
     return $suggest;
 }
예제 #10
0
 /**
  * Returns suggestions of for a specific word.
  *
  * @param {String} $lang Language code like sv or en.
  * @param {String} $word Specific word to get suggestions for.
  * @return {Array} Array of suggestions for the specified word.
  */
 function &getSuggestions($lang, $word)
 {
     $words = pspell_suggest($this->_getPLink($lang), $word);
     for ($i = 0; $i < count($words); $i++) {
         $words[$i] = utf8_encode($words[$i]);
     }
     return $words;
 }
예제 #11
0
function ewiki_spellcheck_list($ws)
{
    global $spell_bin, $pspell_h;
    #-- every word once only
    $words = array();
    foreach (array_unique($ws) as $word) {
        if (!empty($word)) {
            $words[] = $word;
        }
    }
    #print_r($words);
    #-- PHP internal pspell
    if ($pspell_h) {
        #-- build ispell like check list
        $results = array();
        foreach ($words as $w) {
            if (pspell_check($pspell_h, $w)) {
                $results[$word] = "*";
            } else {
                $results[$word] = "& " . implode(", ", pspell_suggest($pspell_h, $w));
            }
        }
    } elseif ($spell_bin) {
        #-- pipe word list through ispell
        $r = implode(" ", $words);
        $results = explode("\n", $r = `echo {$r} | {$spell_bin}`);
        $results = array_slice($results, 1);
    }
    #print_r($results);
    #-- build replacement html hash from results
    $r = array();
    foreach ($words as $n => $word) {
        if ($repl = $results[$n]) {
            switch ($repl[0]) {
                case "-":
                case "+":
                case "*":
                    $repl = $word;
                    break;
                default:
                    $repl = '<s title="' . htmlentities($repl) . '" style="color:#ff5555;" class="wrong">' . $word . '</s>';
            }
        } else {
            $repl = $word;
        }
        $r[$word] = $repl;
    }
    #print_r($r);
    return $r;
}
예제 #12
0
function x()
{
    $uncheckedDir = opendir('.');
    readdir($uncheckedDir);
    $uncheckedDir2 = bzopen('.');
    bzclose($uncheckedDir2);
    $uncheckedDir3 = fopen('.', 'r+');
    fclose($uncheckedDir3);
    readdir(opendir('uncheckedDir4'));
    readdir2(opendir('uncheckedDir5'));
    readdir(opendir2('uncheckedDir6'));
    $pspell_new = pspell_new('asdfasdf');
    while ($f = pspell_suggest($pspell_new)) {
        print "{$f}\n";
    }
}
예제 #13
0
 public function getCorrections()
 {
     $wordMatcher = "/\\w+/u";
     preg_match_all($wordMatcher, $this->rawInput, $words);
     if (count($words[0]) == 0) {
         return array();
     }
     foreach ($words[0] as $k => $word) {
         if (!pspell_check($this->pspell, $word)) {
             $suggestions = pspell_suggest($this->pspell, $word);
             $this->corrections[$word]['offset'] = $k;
             $this->corrections[$word]['suggestions'] = $suggestions;
         }
     }
     return $this->corrections;
 }
예제 #14
0
function check($word)
{
    $pspell_config = pspell_config_create("ru", "", "", "UTF-8");
    pspell_config_mode($pspell_config, PSPELL_FAST);
    $pspell_link = pspell_new_config($pspell_config);
    if (!pspell_check($pspell_link, $word)) {
        $arr = array();
        $suggestions = pspell_suggest($pspell_link, $word);
        foreach ($suggestions as $suggestion) {
            array_push($arr, $suggestion);
        }
        $json = json_encode($arr);
    } else {
        $json = true;
    }
    echo $json;
}
예제 #15
0
 function checkSpelling($text)
 {
     $list = array();
     $this->checked = array();
     $words = $this->getWords($text);
     foreach ($words as $k => $w) {
         // don't check the same word twice
         if (isset($this->checked[$w])) {
             if (is_array($this->checked[$w])) {
                 $list[] = array('word' => $this->escape($w), 'offset' => $k, 'length' => strlen($w), 'suggestions' => $this->escape($this->checked[$w]));
             }
             continue;
         }
         // if it's in the personal dictionary, it's valid
         if ($this->checkPersonal($w)) {
             $this->checked[$w] = true;
             continue;
         }
         // if it's in the suggestions table, we can avoid pspell
         $sug = $this->checkSuggestions($w);
         // if it's an array, the word is incorrect
         if (is_array($sug)) {
             $list[] = array('word' => $this->escape($w), 'offset' => $k, 'length' => strlen($w), 'suggestions' => $this->escape($sug));
             $this->checked[$w] = $sug;
             continue;
             // if it's a boolean true, the word is correct
         } elseif ($sug === true) {
             $this->checked[$w] = true;
             continue;
         }
         // finally, we check with pspell...
         // if it comes up false, it's a mistake
         if (!pspell_check($this->pspell, $w)) {
             $sug = pspell_suggest($this->pspell, $w);
             $list[] = array('word' => $this->escape($w), 'offset' => $k, 'length' => strlen($w), 'suggestions' => $this->escape($sug));
             $this->addSuggestion($w, $sug);
             $this->checked[$w] = $sug;
             // the word is correct, let's have Xspel learn it
         } else {
             $this->addSuggestion($w);
             $this->checked[$w] = true;
         }
     }
     return $list;
 }
 function getErrors($text, $max = 10)
 {
     $separator = "!\$%^&*()-_=+{}[]\\|;:\",.?/\n\r|\t ";
     $errors = array('word' => array(), 'suggest' => array());
     $word = strtok($text, $separator);
     while ($word !== false) {
         if (!is_numeric($word) && !in_array($word, $errors['word']) && !pspell_check($this->link, $word)) {
             $errors['word'][] = $word;
             $suggests = pspell_suggest($this->link, $word);
             if (array_key_exists($max, $suggests)) {
                 array_splice($suggests, $max);
             }
             $errors['suggest'][] = $suggests;
         }
         $word = strtok($separator);
     }
     return $errors;
 }
예제 #17
0
파일: SpellCheck.php 프로젝트: hjr3/phergie
 /**
  * Intercepts and handles requests for spell checks.
  *
  * @param string $word the string to perform checks against
  *
  * @return void
  */
 public function onCommandSpell($word)
 {
     $source = $this->event->getSource();
     $target = $this->event->getNick();
     $message = $target . ': The word "' . $word;
     $message .= '" seems to be spelled correctly.';
     if (!pspell_check($this->pspell, $word)) {
         $suggestions = pspell_suggest($this->pspell, $word);
         $message = $target;
         $message .= ': I could not find any suggestions for "' . $word . '".';
         if (!empty($suggestions)) {
             $suggestions = array_splice($suggestions, 0, $this->limit);
             $message = $target . ': Suggestions for "';
             $message .= $word . '": ' . implode(', ', $suggestions) . '.';
         }
     }
     $this->doPrivmsg($source, $message);
 }
 function check($string)
 {
     if (is_null($this->pspell_link)) {
         return NULL;
     }
     $words = explode(' ', $string);
     $new_words = array();
     foreach ($words as $word) {
         if (!pspell_check($this->pspell_link, $word)) {
             $suggestions = pspell_suggest($this->pspell_link, $word);
             // get suggestions from pspell
             // for now simply use the first suggestion in the list
             if (count($suggestions) > 0) {
                 $has_hyphen = strpos($word, '-') !== FALSE;
                 $suggestion = $suggestions[0];
                 // look for a suggestion that is one word (not two as pspell sometimes does)
                 // also ignore suggestions with hyphens if the given word is not hyphenated
                 if (strpos($suggestion, ' ') !== FALSE || !$has_hyphen && strpos($suggestion, '-') !== FALSE) {
                     // only search through the first 20 suggestions
                     $count = min(20, count($suggestions));
                     for ($i = 1; $i < $count; $i++) {
                         if (strpos($suggestions[$i], ' ') === FALSE && $has_hyphen) {
                             $suggestion = $suggestions[$i];
                             break;
                         } else {
                             if (strpos($suggestions[$i], ' ') === FALSE && !$has_hyphen && strpos($suggestions[$i], '-') === FALSE) {
                                 $suggestion = $suggestions[$i];
                                 break;
                             }
                         }
                     }
                 }
                 $new_words[] = strtolower($suggestion);
             } else {
                 $new_words[] = $word;
             }
         } else {
             $new_words[] = $word;
         }
     }
     $suggestion = join(' ', $new_words);
     return $suggestion != $string ? $suggestion : '';
 }
예제 #19
0
function find_my_page()
{
    // get the name of the 'missing' file
    $page = basename($_SERVER['REDIRECT_URL']);
    // used to pick the correct dictionary
    $dir = dirname($_SERVER['REDIRECT_URL']);
    $key = md5($dir);
    // load spelling dictionaries
    $ps = pspell_config_create("en");
    pspell_config_personal($ps, "./{$key}.pws");
    $pl = pspell_new_config($ps);
    // find alternatives
    $alt = pspell_suggest($pl, $page);
    if (!$alt) {
        // no matches, no choice but to show site map
        display_site_map();
        return;
    }
    // escape data for sqlite
    foreach ($alt as $key => $file) {
        $alt[$key] = sqlite_escape_string($file);
    }
    // fetch all matching pages;
    $db = new sqlite_db("./typos.sqlite");
    $alt = $db->single_query("SELECT url FROM typo WHERE key IN('" . implode("','", $alt) . "')");
    switch (@count($alt)) {
        case 1:
            // if only one suggestion is avaliable redirect the user to that page
            header("Location: {$alt[0]}");
            return;
            break;
        case 0:
            // no matches, no choice but to show site map
            display_site_map();
            break;
        default:
            // show the user possible alternatives if >1 is found
            echo "The page you requested, '{$_SERVER['REDIRECT_URL']}' cannot be found.<br />\nDid you mean:\n";
            foreach ($alt as $url) {
                echo "&nbsp;&nbsp;<a href='{$url}'>{$url}</a><br />\n";
            }
    }
}
예제 #20
0
 public function arrCheck($words)
 {
     //find misspelled words
     foreach ($words as $word) {
         if (!pspell_check($this->speller, $word)) {
             $misspelled[] = $word;
         }
     }
     $suggestions = array();
     if (!empty($misspelled)) {
         // return contains a list of suggestions for each mispelled words
         foreach ($misspelled as $value) {
             // don't get suggestions for the same word twice
             if (!array_key_exists($value, $suggestions)) {
                 $suggestions[$value] = pspell_suggest($this->speller, $value);
             }
         }
     }
     return $suggestions;
 }
예제 #21
0
 /**
  * 
  * @param string $psString
  * @param string $psLink
  * @param string $psTemplate
  * @return string
  */
 public static function spellCheck($psString, $psLink = null, $psTemplate = '<a href="#%LINK%#&q=#%QUERY%#">#%WORD%#</a>')
 {
     $psString = self::clearSignals($psString);
     $laWords = split(' ', $psString);
     $laSuggestions = array();
     foreach ($laWords as $lsValue) {
         $laSuggestions = pspell_suggest(pspell_new("pt"), $lsValue);
         if (count($laSuggestions) != 0) {
             foreach ($laSuggestions as $lsSuggestion) {
                 if (!empty($lsSuggestion)) {
                     $laTmp = split(" ", $lsSuggestion);
                     $lsTerm = substr($laTmp[4], 0, -1);
                     $lsTerm = self::removeAccentuation(strtolower($lsTerm));
                     if (strtolower($lsValue) != strtolower($lsTerm)) {
                         $laTerm[$laTmp[1]] = substr($laTmp[4], 0, -1);
                         $lbCorrected = true;
                     } else {
                         $laTerm[$lsValue] = $lsValue;
                     }
                 }
             }
         }
     }
     if ($lbCorrected) {
         foreach ($laTerm as $lsOriginal => $lsSuggestion) {
             if (strtolower($lsOriginal) != strtolower($lsSuggestion)) {
                 $lsString .= "<strong>{$lsSuggestion}</strong> ";
             } else {
                 $lsString .= "{$lsSuggestion} ";
             }
             $lsQuery .= "{$lsSuggestion} ";
         }
         $lsPattern = array("/#%LINK%#/", "/#%QUERY%#/", "/#%WORD%#/");
         $lsReplace = array($psLink, $lsQuery, $lsString);
         $lsString = preg_replace($lsPattern, $lsReplace, $psTemplate);
     }
     return $lsString;
 }
예제 #22
0
    function _spell($params)
    {
        $user = $params['user'];
        $channel = $params['channel'];
        $presence = DB::get()->row('SELECT status, data FROM presence WHERE user_id = :user_id AND data <> "" ORDER BY msgtime DESC LIMIT 1', array('user_id' => $user->id));
        $data = $presence->data;
        $words = preg_split('%\\W+%', $data);
        $words = array_unique($words);
        $words = array_combine($words, $words);
        $pspell_link = pspell_new("en");
        foreach ($words as $word) {
            if (!pspell_check($pspell_link, $word)) {
                $suggestions = pspell_suggest($pspell_link, $word);
                if (count($suggestions) > 0) {
                    $presence->data = str_replace($word, reset($suggestions), $presence->data);
                } else {
                    $presence->data = str_replace($word, '<s>' . $word . '</s>', $presence->data);
                }
            }
        }
        if ($presence->data == $data) {
            Immediate::ok('No spelling corrections.', $user);
        } else {
            include_once "Text/Diff.php";
            include_once "Text/Diff/Renderer.php";
            include_once "Text/Diff/Renderer/inline.php";
            $diff =& new Text_Diff(explode("\n", $data), explode("\n", htmlspecialchars_decode($presence->data)));
            $renderer =& new Text_Diff_Renderer_inline();
            $replacement = $renderer->render($diff);
            $replacement = addslashes($replacement);
            $replacement = str_replace("\n", '\\n', $replacement);
            $js = <<<REPLJS
retcon({$presence->status}, '{$replacement}');
REPLJS;
            Status::create()->user_id($user->id)->js($js)->channel($channel)->cssclass('spell')->insert();
        }
        return true;
    }
예제 #23
0
 /**
  * Handler for the content of a tag
  */
 public function spellCheckHandler($xml_parser, $string)
 {
     $incurrent = array();
     $stringText = $string;
     $words = preg_split($this->parserCharset == 'utf-8' ? '/\\P{L}+/u' : '/\\W+/', $stringText);
     foreach ($words as $word) {
         $word = preg_replace('/ /' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '', $word);
         if ($word && !is_numeric($word)) {
             if ($this->pspell_is_available && !$this->forceCommandMode) {
                 if (!pspell_check($this->pspell_link, $word)) {
                     if (!in_array($word, $this->misspelled)) {
                         if (sizeof($this->misspelled) != 0) {
                             $this->suggestedWords .= ',';
                         }
                         $suggest = array();
                         $suggest = pspell_suggest($this->pspell_link, $word);
                         if (sizeof($suggest) != 0) {
                             $this->suggestionCount++;
                             $this->suggestedWordCount += sizeof($suggest);
                         }
                         $this->suggestedWords .= '"' . $word . '":"' . implode(',', $suggest) . '"';
                         $this->misspelled[] = $word;
                         unset($suggest);
                     }
                     if (!in_array($word, $incurrent)) {
                         $stringText = preg_replace('/\\b' . $word . '\\b/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '<span class="htmlarea-spellcheck-error">' . $word . '</span>', $stringText);
                         $incurrent[] = $word;
                     }
                 }
             } else {
                 $tmpFileName = GeneralUtility::tempnam($this->filePrefix);
                 if (!($filehandle = fopen($tmpFileName, 'wb'))) {
                     echo 'SpellChecker tempfile open error';
                 }
                 if (!fwrite($filehandle, $word)) {
                     echo 'SpellChecker tempfile write error';
                 }
                 if (!fclose($filehandle)) {
                     echo 'SpellChecker tempfile close error';
                 }
                 $catCommand = TYPO3_OS === 'WIN' ? 'type' : 'cat';
                 $AspellCommand = $catCommand . ' ' . escapeshellarg($tmpFileName) . ' | ' . $this->AspellDirectory . ' -a check' . ' --mode=none' . ' --sug-mode=' . escapeshellarg($this->pspellMode) . ($this->personalDictionaryPath ? ' --home-dir=' . escapeshellarg($this->personalDictionaryPath) : '') . ' --lang=' . escapeshellarg($this->dictionary) . ' --encoding=' . escapeshellarg($this->aspellEncoding) . ' 2>&1';
                 $AspellAnswer = shell_exec($AspellCommand);
                 $AspellResultLines = array();
                 $AspellResultLines = GeneralUtility::trimExplode(LF, $AspellAnswer, TRUE);
                 if (substr($AspellResultLines[0], 0, 6) == 'Error:') {
                     echo '{' . $AspellAnswer . '}';
                 }
                 GeneralUtility::unlink_tempfile($tmpFileName);
                 if ($AspellResultLines['1'][0] !== '*') {
                     if (!in_array($word, $this->misspelled)) {
                         if (sizeof($this->misspelled) != 0) {
                             $this->suggestedWords .= ',';
                         }
                         $suggest = array();
                         $suggestions = array();
                         if ($AspellResultLines['1'][0] === '&') {
                             $suggestions = GeneralUtility::trimExplode(':', $AspellResultLines['1'], TRUE);
                             $suggest = GeneralUtility::trimExplode(',', $suggestions['1'], TRUE);
                         }
                         if (sizeof($suggest) != 0) {
                             $this->suggestionCount++;
                             $this->suggestedWordCount += sizeof($suggest);
                         }
                         $this->suggestedWords .= '"' . $word . '":"' . implode(',', $suggest) . '"';
                         $this->misspelled[] = $word;
                         unset($suggest);
                         unset($suggestions);
                     }
                     if (!in_array($word, $incurrent)) {
                         $stringText = preg_replace('/\\b' . $word . '\\b/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '<span class="htmlarea-spellcheck-error">' . $word . '</span>', $stringText);
                         $incurrent[] = $word;
                     }
                 }
                 unset($AspellResultLines);
             }
             $this->wordCount++;
         }
     }
     $this->text .= $stringText;
     unset($incurrent);
 }
예제 #24
0
        }
        //optionally skip all caps
        if ($ignoreAllCaps) {
            if (!preg_match('/[^\\p{Lu}]/', $word)) {
                continue;
            }
        }
        // Skip duplicates
        if (array_key_exists($word, $checked_words)) {
            continue;
        } else {
            $checked_words[$word] = 1;
        }
        // Check spelling
        if (!pspell_check($dictionary, $word)) {
            $suggestions = implode(",", pspell_suggest($dictionary, $word));
            $misspelled .= "{$word}:{$suggestions}\n";
        }
    }
    header("Content-Type: text/plain; charset=UTF-8");
    echo $misspelled;
} else {
    ?>

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Spell Checker</title>
 </head>
 <body>
예제 #25
0
	$pspell_config = pspell_config_create("en");
	pspell_config_personal($pspell_config, "./dict/".$user_dictionary_file);
	$int = pspell_new_config($pspell_config);
	
	if($_POST['dictadd']!="") {
		pspell_add_to_personal($int, $_POST['dictadd']);
		pspell_save_wordlist($int);
	}
	
	for($i=$start;$i<count($words);$i++) {
		$currentword=$words[$i];
		if(strlen(trim($words[$i]))>2) {
			
			if (!pspell_check($int, $currentword)) {
			   $suggestions = pspell_suggest($int, $currentword);
			   $found_misspell=true;
			   $start=$i;
			   $misspell_index=$i;
			   break;
   			}
		}
	}
	?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Spell Checker</title>
<link rel="stylesheet" type="text/css" href="easyspell.css" />
<script src="easyspell.js" type="text/javascript"></script>
</head>
예제 #26
0
function SpellCheck()
{
    global $txt, $context, $func;
    // A list of "words" we know about but pspell doesn't.
    $known_words = array('smf', 'php', 'mysql', 'www', 'gif', 'jpeg', 'png', 'http', 'smfisawesome', 'grandia', 'terranigma', 'rpgs');
    loadLanguage('Post');
    loadTemplate('Post');
    // Okay, this looks funny, but it actually fixes a weird bug.
    ob_start();
    $old = error_reporting(0);
    // See, first, some windows machines don't load pspell properly on the first try.  Dumb, but this is a workaround.
    pspell_new('en');
    // Next, the dictionary in question may not exist.  So, we try it... but...
    $pspell_link = pspell_new($txt['lang_dictionary'], $txt['lang_spelling'], '', strtr($context['character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
    error_reporting($old);
    ob_end_clean();
    // Most people don't have anything but english installed... so we use english as a last resort.
    if (!$pspell_link) {
        $pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
    }
    if (!isset($_POST['spellstring']) || !$pspell_link) {
        die;
    }
    // Construct a bit of Javascript code.
    $context['spell_js'] = '
		var txt = {"done": "' . $txt['spellcheck_done'] . '"};
		var mispstr = window.opener.document.forms[spell_formname][spell_fieldname].value;
		var misps = Array(';
    // Get all the words (Javascript already seperated them).
    $alphas = explode("\n", stripslashes(strtr($_POST['spellstring'], array("\r" => ''))));
    $found_words = false;
    for ($i = 0, $n = count($alphas); $i < $n; $i++) {
        // Words are sent like 'word|offset_begin|offset_end'.
        $check_word = explode('|', $alphas[$i]);
        // If the word is a known word, or spelled right...
        if (in_array($func['strtolower']($check_word[0]), $known_words) || pspell_check($pspell_link, $check_word[0]) || !isset($check_word[2])) {
            continue;
        }
        // Find the word, and move up the "last occurance" to here.
        $found_words = true;
        // Add on the javascript for this misspelling.
        $context['spell_js'] .= '
			new misp("' . strtr($check_word[0], array('\\' => '\\\\', '"' => '\\"', '<' => '', '&gt;' => '')) . '", ' . (int) $check_word[1] . ', ' . (int) $check_word[2] . ', [';
        // If there are suggestions, add them in...
        $suggestions = pspell_suggest($pspell_link, $check_word[0]);
        if (!empty($suggestions)) {
            $context['spell_js'] .= '"' . join('", "', $suggestions) . '"';
        }
        $context['spell_js'] .= ']),';
    }
    // If words were found, take off the last comma.
    if ($found_words) {
        $context['spell_js'] = substr($context['spell_js'], 0, -1);
    }
    $context['spell_js'] .= '
		);';
    // And instruct the template system to just show the spellcheck sub template.
    $context['template_layers'] = array();
    $context['sub_template'] = 'spellcheck';
}
 function pgw_pspell_suggest($dictionary_link, $word)
 {
     // http://rock.earthlink.net/manual/mod/mod_php4/function.pspell-suggest.html
     return pspell_suggest($dictionary_link, $word);
 }
예제 #28
0
 /**
  *	Build a word list from a product name to store in the product_words table.
  *	These will be used along with pSpell to provide search suggestions on the front end.
  *	This avoids needing to save a custom dictionary for technical words which will always
  *	trip off the spell checker. For example "mp3 player" returns 'did you mean "mp player"'
  *	which is incorrect, as MP3 is a common word. Any word that's searched for that's in
  *	the product_words table will not be checked against the spell checker.
  **/
 public function SaveProductWords($ProductName, $ProductId, $AddingOrEditing)
 {
     // If search suggestions aren't enabled, don't try to build the list of product words
     if (!GetConfig('SearchSuggest')) {
         return true;
     }
     $words_to_save = array();
     $words = preg_split("#[(\\s|\\(|\\)\\/)]+#", $ProductName);
     $pspell_installed = false;
     if (function_exists('pspell_new')) {
         $pspell_installed = true;
     }
     // Create a pSpell object if it's installed
     if ($pspell_installed) {
         $spell = @pspell_new("en");
     }
     foreach ($words as $word) {
         if (isc_strlen(trim($word)) > 2) {
             // Can we spell check against the word?
             if ($pspell_installed && $spell) {
                 if (!@pspell_check($spell, $word)) {
                     $suggestions = @pspell_suggest($spell, $word);
                     // If any suggestions are returned then the word generally misspelled
                     if (count($suggestions) > 0) {
                         array_push($words_to_save, isc_strtolower($word));
                     }
                 }
             } else {
                 // pSpell isn't installed so we'll go ahead and add the word anyway
                 array_push($words_to_save, isc_strtolower($word));
             }
         }
     }
     // If we're editing an existing product then we'll remove the words already in the product_words table
     if ($AddingOrEditing == "editing") {
         $query = sprintf("delete from [|PREFIX|]product_words where productid='%d'", $ProductId);
         $GLOBALS['ISC_CLASS_DB']->Query($query);
     }
     // Add the words to the product_words table
     foreach ($words_to_save as $word) {
         $newWord = array("word" => $word, "productid" => $ProductId);
         $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_words", $newWord);
     }
 }
예제 #29
0
 /**
  * Returns suggestions for misspelled word
  */
 private function _pspell_suggestions($word)
 {
     // init spellchecker
     $this->_pspell_init();
     if (!$this->plink) {
         return array();
     }
     $suggestions = pspell_suggest($this->plink, $word);
     if (sizeof($suggestions) > self::MAX_SUGGESTIONS) {
         $suggestions = array_slice($suggestions, 0, self::MAX_SUGGESTIONS);
     }
     return is_array($suggestions) ? $suggestions : array();
 }
예제 #30
0
 /** -----------------------------------------
 	/**  Spell Check for Textareas
 	/** -----------------------------------------*/
 function check($lang = 'en')
 {
     // Make a local reference to the ExpressionEngine super object
     $this->EE =& get_instance();
     /* -------------------------------------------
     		/*	Hidden Configuration Variable
     		/*
     		/*	- spellcheck_language_code => What is the two letter ISO 639 language
     		/*	  code for the spellcheck (ex: en, es, de)
     		/* -------------------------------------------*/
     if (ee()->config->item('spellcheck_language_code') !== FALSE && strlen(ee()->config->item('spellcheck_language_code')) == 2) {
         $lang = ee()->config->item('spellcheck_language_code');
     }
     // ----------------------------------
     //  These 100 words make up 1/2 of all written material
     //  and by not checking them we should be able to greatly
     //  speed up the spellchecker
     // ----------------------------------
     $common = array('the', 'of', 'and', 'a', 'to', 'in', 'is', 'you', 'that', 'it', 'he', 'was', 'for', 'on', 'are', 'as', 'with', 'his', 'they', 'I', 'at', 'be', 'this', 'have', 'from', 'or', 'one', 'had', 'by', 'word', 'but', 'not', 'what', 'all', 'were', 'we', 'when', 'your', 'can', 'said', 'there', 'use', 'an', 'each', 'which', 'she', 'do', 'how', 'their', 'if', 'will', 'up', 'other', 'about', 'out', 'many', 'then', 'them', 'these', 'so', 'some', 'her', 'would', 'make', 'like', 'him', 'into', 'time', 'has', 'look', 'two', 'more', 'write', 'go', 'see', 'number', 'no', 'way', 'could', 'people', 'my', 'than', 'first', 'water', 'been', 'call', 'who', 'oil', 'its', 'now', 'find', 'long', 'down', 'day', 'did', 'get', 'come', 'made', 'may', 'part');
     // The contents of the field are encoded by javascript before
     // they are sent to us so we have to decode them before processing.
     // We are also removing any HTML code and HTML code entities so that we
     // do not process them as misspelled words.
     $content = preg_replace("|<.*?" . ">|", '', rawurldecode(ee()->security->xss_clean(ee()->input->get_post('q'))));
     $content = str_replace(array('&amp;', '&lt;', '&gt;'), '', $content);
     $str = '<?xml version="1.0" encoding="UTF-8"?' . ">\n<items>\n";
     $items = array();
     $prechecked = array();
     if (!function_exists('pspell_new')) {
         $content = str_replace('&', ' ', stripslashes($content));
         // Google has silently changed the service internally, setting ignoredups="1" now causes results to
         // always return as spelled correctly.  -- changed 8/20/08 d.j.
         $payload = '<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="0"><text>' . $content . '</text></spellrequest>';
         $url = 'https://www.google.com/tbproxy/spell?lang=' . $lang . '&hl=' . $lang;
         if (function_exists('curl_init')) {
             $data = EE_Spellcheck::curl_process($url, $payload);
         } else {
             $data = EE_Spellcheck::fsockopen_process($url, $payload);
         }
         if ($data == '') {
             ee()->output->set_status_header(404);
             @header("Date: " . gmdate("D, d M Y H:i:s") . " GMT");
             exit('Unable to connect to spellcheck');
         }
         // suckz => <c o="10" l="5" s="0">sucks	sicks	suck	sacks	socks</c>
         if ($data != '' && preg_match_all("|<c\\s+(.*?)>(.*?)</c>|is", $data, $matches)) {
             for ($i = 0, $s = count($matches['0']); $i < $s; ++$i) {
                 $x = explode('"', $matches['1'][$i]);
                 $word = substr($content, $x['1'], $x['3']);
                 if (!in_array($word, $prechecked)) {
                     $sug = preg_split("|\\s+|s", $matches['2'][$i]);
                     natcasesort($sug);
                     $items[] = $word . ':' . implode(',', $sug) . '';
                     $prechecked[] = $word;
                 }
             }
         }
     } else {
         // Split it up by non-words
         preg_match_all("|[\\w\\']{2,20}|", stripslashes($content), $parts);
         $pspell = pspell_new($lang);
         for ($i = 0, $s = count($parts['0']); $i < $s; $i++) {
             if (!is_numeric($parts['0'][$i]) && !in_array(strtolower($parts['0'][$i]), $common) && !in_array($parts['0'][$i], $prechecked) && !pspell_check($pspell, $parts['0'][$i])) {
                 $sug = array();
                 if ($suggestions = pspell_suggest($pspell, $parts['0'][$i])) {
                     foreach ($suggestions as $suggest) {
                         $sug[] = $suggest;
                         if (count($sug) > 8) {
                             break;
                         }
                     }
                 }
                 natcasesort($sug);
                 $items[] = $parts['0'][$i] . ':' . implode(',', $sug) . '';
                 $prechecked[] = $parts['0'][$i];
             }
         }
     }
     $str .= count($items) == 0 ? '' : "<item>" . implode("</item>\n<item>", $items) . "</item>";
     $str .= "\n</items>";
     @header("Content-Type: text/xml");
     exit($str);
 }