Ejemplo n.º 1
0
 /**
  * Constructor
  *
  * @param string $dict the dictionary (language) to use
  * @param string $account the current users account name
  */
 function spellChecker($dict, $account, $use_pspell = false)
 {
     global $atmail, $pref;
     $this->personal_words = $atmail->db->sqlarray("select Word from SpellCheck where SUnique='0' and Account=?", $account);
     $this->suggestions = array();
     // check for availability of pspell functions
     $this->use_pspell = $use_pspell && extension_loaded('pspell');
     //function_exists('pspell_new');
     // use pspell functions if they are available otherwise
     // use the aspell binary directly
     if ($this->use_pspell && function_exists('pspell_new')) {
         $this->dict = pspell_new($dict, null, null, 'utf-8', PSPELL_FAST);
     } else {
         $dict = escapeshellarg($dict);
         // Execute the aspell command and open file pointers for input/output
         $descriptorspec = array(array("pipe", "r"), array("pipe", "w"));
         $this->aspell_proc = proc_open("{$pref['aspell_path']} -a -l {$dict} --sug-mode=fast --encoding=utf-8", $descriptorspec, $pipes);
         $this->aspell_input = $pipes[0];
         $this->aspell_output = $pipes[1];
         // remove version info from stream
         $trash = fgets($this->aspell_output);
         unset($trash);
     }
     if (!$atmail->isset_chk($_SESSION['spellcheck_ignore'])) {
         $_SESSION['spellcheck_ignore'] = array();
     }
 }
Ejemplo n.º 2
0
 /**
  * Checks spelling.
  *
  * @since 150424 Adding password strength.
  *
  * @param string $word  Input word to check.
  * @param int    $flags Dictionary flags.
  *
  * @return bool True if spelled correctly.
  */
 public function __invoke(string $word, int $flags = PSPELL_NORMAL) : bool
 {
     if (is_null($dictionary =& $this->cacheKey(__FUNCTION__, $flags))) {
         $dictionary = pspell_new('en', '', '', 'utf-8', $flags);
     }
     return pspell_check($dictionary, $word);
 }
 /**
  * Returns pspell resource
  * @return int
  */
 protected function getPspell()
 {
     if ($this->pspell === null) {
         $this->pspell = pspell_new($this->language, "", "", "UTF-8");
     }
     return $this->pspell;
 }
Ejemplo n.º 4
0
 /**
  * Spellchecks an array of words.
  *
  * @param String $lang Selected language code (like en_US or de_DE). Shortcodes like "en" and "de" work with enchant >= 1.4.1
  * @param Array $words Array of words to check.
  * @return Name/value object with arrays of suggestions.
  */
 public function getSuggestions($lang, $words)
 {
     $config = $this->getConfig();
     switch ($config['PSpell.mode']) {
         case "fast":
             $mode = PSPELL_FAST;
             break;
         case "slow":
             $mode = PSPELL_SLOW;
             break;
         default:
             $mode = PSPELL_NORMAL;
     }
     // Setup PSpell link
     $plink = pspell_new($lang, $config['pspell.spelling'], $config['pspell.jargon'], $config['pspell.encoding'], $mode);
     if (!$plink) {
         throw new Exception("No PSpell link found opened.");
     }
     $outWords = array();
     foreach ($words as $word) {
         if (!pspell_check($plink, trim($word))) {
             $outWords[] = utf8_encode($word);
         }
     }
     return $outWords;
 }
Ejemplo n.º 5
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;
 }
Ejemplo n.º 6
0
 /**
  * Set up custom PSpell dictionary.
  */
 private function configurePSpell()
 {
     $this->pspellLink = pspell_new('en');
     foreach ($this->config['spellcheck']['custom_words'] as $word) {
         pspell_add_to_session($this->pspellLink, $word);
     }
 }
Ejemplo n.º 7
0
 public static function get_pspell()
 {
     if (!isset(self::$_pspell_instance)) {
         self::$_pspell_instance = pspell_new('en');
     }
     return self::$_pspell_instance;
 }
Ejemplo n.º 8
0
function obtainData($objDb, $id)
{
    $aRes = $objDb->GetDetails($id);
    $sText = $objDb->GetRawText($id);
    if ($aRes === FALSE || $sText === FALSE) {
        // No such record!
        return FALSE;
    }
    // Clean up list of words
    $aWords = array_filter(array_unique(str_word_count($sText, 1)), "filter_words");
    // Split words into likely and unlikely (based on spelling)
    $aLikely = array();
    $aUnlikely = array();
    $hSpell = pspell_new("en");
    if ($hSpell !== FALSE) {
        foreach ($aWords as $sWord) {
            // Make a spellcheck on it
            if (pspell_check($hSpell, $sWord)) {
                array_push($aLikely, $sWord);
            } else {
                array_push($aUnlikely, $sWord);
            }
        }
    } else {
        $aLikely = $aWords;
    }
    return array("likely" => $aLikely, "unlikely" => $aUnlikely);
}
function SpellCheck($text)
{
    //depends on fnSpell()
    // Extracts text from HTML code. In addition to normal word separators,  HTML tags
    // and HTML entities also function as word delimiters
    $pspell_link = pspell_new("en_GB");
    //0. Get the dictionary
    $strings = explode(">", $text);
    //1. Split $text on '>' to give us $strings with 0 or 1 HTML tags at the end
    $nStrings = count($strings);
    for ($cStrings = 0; $cStrings < $nStrings; $cStrings++) {
        $string = $strings[$cStrings];
        //2. For each string from 1
        if ($string == '') {
            continue;
        }
        $temp = explode('<', $string);
        //2.1   Split $string from $strings on '>' to give us a $tag and $cdata
        $tag = $temp[1];
        $cdata = $temp[0];
        $subCdatas = explode(";", $cdata);
        //2.2 Split &cdata on ';' to give $subcdatas with 0 or 1 HTML entities on the end
        $nSubCdatas = count($subCdatas);
        //2.3   For each $subCdata from $subcdatas in 2.2
        for ($cSubCdatas = 0; $cSubCdatas < $nSubCdatas; $cSubCdatas++) {
            $subCdata = $subCdatas[$cSubCdatas];
            if ($subCdata == '') {
                continue;
            }
            $temp = explode('&', $subCdata);
            //2.3.1     Split the $subCdata on '&' to give us a $subCdataEntity and a $subCdataWithNoEntities
            $subCdataEntity = $temp[1];
            $subCdataWithNoEntities = $temp[0];
            $subCdataWithNoEntities = fnSpell($pspell_link, $subCdataWithNoEntities);
            //2.3.2     Spellcheck the $cdataWithNoEntities
            if (!$subCdataEntity) {
                //2.3.3        Put the $subCdataEntity, a '&' and the $cdataWithNoEntities back into the $subCdata from 2.2
                $subCdata = $subCdataWithNoEntities;
            } else {
                $subCdata = $subCdataWithNoEntities . '&' . $subCdataEntity . ';';
            }
            $subCdatas[$cSubCdatas] = $subCdata;
            //2.3.4        Put the $subCdata back into the array of $subCdatas
        }
        $cdata = implode("", $subCdatas);
        //2.4    Implode the array of $subCdatas back into the $cdata
        if ($tag) {
            //2.5    Put the $tag , '>' and $cdata back into $string
            $string = $cdata . '<' . $tag . '>';
        } else {
            $string = $cdata;
        }
        $strings[$cStrings] = $string;
        //2.6    Put $string back in its place in $strings
    }
    $text = implode('', $strings);
    //3  Implode the $strings back into $text
    return $text;
}
 function __construct()
 {
     if (!function_exists('pspell_new')) {
         $this->pspell_link = NULL;
     } else {
         $this->pspell_link = pspell_new($this->dict, "", "", "", PSPELL_FAST);
     }
 }
Ejemplo n.º 11
0
 public function __construct($language, $input)
 {
     $this->language = $language;
     $this->rawInput = $input;
     $this->pspell = pspell_new($this->language, "", "", "utf-8");
     // Set up config
     //$this->loadReplacements();
 }
Ejemplo n.º 12
0
function testPspell($isocode)
{
    if (function_exists('pspell_new') && @pspell_new($isocode)) {
        return 1;
    } else {
        return 0;
    }
}
Ejemplo n.º 13
0
 /**
  * Constructor
  *
  * @see     php://pspell_new
  * @param   string language
  * @param   string spelling
  * @param   string jargon
  * @param   string encoding 
  * @param   int mode 
  * @throws  lang.IllegalArgumentException
  */
 public function __construct($language, $spelling = NULL, $jargon = NULL, $encoding = NULL, $mode = PSPELL_NORMAL)
 {
     if (FALSE === ($this->handle = pspell_new($language, $spelling, $jargon, $encoding, $mode))) {
         $e = new IllegalArgumentException('Could not create spell checker');
         xp::gc(__FILE__);
         throw $e;
     }
 }
Ejemplo n.º 14
0
function ewiki_spellcheck_init($lang = "en")
{
    global $spell_bin, $pspell_h;
    $pspell_h = 0;
    $spell_bin = 0;
    if (function_exists("pspell_new")) {
        $pspell_h = pspell_new($lang, "", "", "iso8859-1", PSPELL_FAST | PSPELL_RUN_TOGETHER);
    } else {
        $spell_bin = trim(`which aspell`) and $spell_bin .= " -a -B --lang={$lang} " or $spell_bin = trim(`which ispell`) and $spell_bin .= " -a -B ";
    }
}
Ejemplo n.º 15
0
 private function misspellingsOnly(array $arr)
 {
     $pspell = pspell_new("en", "", "", "", PSPELL_FAST | PSPELL_RUN_TOGETHER);
     $miss = [];
     foreach ($arr as $w) {
         if (!pspell_check($pspell, $w)) {
             $miss[] = $w;
         }
     }
     return $miss;
 }
Ejemplo n.º 16
0
 function TinyPSpell(&$config, $lang, $mode, $spelling, $jargon, $encoding)
 {
     $this->lang = $lang;
     $this->mode = $mode;
     $this->plink = false;
     $this->errorMsg = array();
     if (!function_exists("pspell_new")) {
         $this->errorMsg[] = "PSpell not found.";
         return;
     }
     $this->plink = pspell_new($this->lang, $this->spelling, $this->jargon, $this->encoding, $this->mode);
 }
Ejemplo n.º 17
0
 function Xspel($lang = 'en')
 {
     $this->lang = $lang;
     ob_start();
     $this->pspell = pspell_new($lang);
     $str = ob_get_contents();
     ob_end_clean();
     if (!empty($str)) {
         $this->error = $str;
     }
     $this->getPersonal();
 }
	/**
	 * Constructs a new Spellcheck object.
	 *
	 * The language parameter is the language code which consists of the two letter ISO 639 language
	 * code and an optional two letter ISO 3166 country code after an underscore.
	 * Throws a core exception if pspell extension is not available or initialization failed.
	 *
	 * @param string Langauge code and additional country code separated by an underscore.
	 * @throws CoreException
	 */
	public function __construct($language) {
		$this->word = '';
		if (extension_loaded('pspell') == true && function_exists('pspell_new') == true) {
			$this->handle = pspell_new($language, "", "", "", PSPELL_NORMAL);
			if ($this->handle === false) {
				throw new CoreException('Could not load spellcheck instance');
			}
		}
		else {
			throw new CoreException('Extension "pspell" is not available');
		}
	}
 /**
  * Initializes PSpell dictionary
  */
 private function init()
 {
     if (!$this->plink) {
         if (!extension_loaded('pspell')) {
             $this->error = "Pspell extension not available";
             return;
         }
         $this->plink = pspell_new($this->lang, null, null, RCUBE_CHARSET, PSPELL_FAST);
     }
     if (!$this->plink) {
         $this->error = "Unable to load Pspell engine for selected language";
     }
 }
Ejemplo n.º 20
0
 /**
  * Check for dependencies.
  *
  * @return void
  */
 public function onLoad()
 {
     if (!extension_loaded('pspell')) {
         $this->fail('pspell php extension is required');
     }
     if (!$this->getConfig('spellcheck.lang')) {
         $this->fail('Setting spellcheck.lang must be filled-in');
     }
     $this->plugins->getPlugin('Command');
     set_error_handler(array($this, 'loadDictionaryError'));
     $this->pspell = pspell_new($this->getConfig('spellcheck.lang'));
     restore_error_handler();
     $this->limit = $this->getConfig('spellcheck.limit', 5);
 }
Ejemplo n.º 21
0
 public static function check($text, $language)
 {
     self::$_pLink = pspell_new($language, "", "", "utf-8", PSPELL_FAST);
     if (!self::$_pLink) {
         throw new \Exception("Could not initialize pspell for language " . $language);
     }
     $words = self::_getWords($text);
     $checkspelling = self::_checkWords($words);
     if (!empty($checkspelling)) {
         return $checkspelling;
     } else {
         return array();
     }
 }
Ejemplo n.º 22
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";
    }
}
Ejemplo n.º 23
0
function bench_pspell($words)
{
    // TODO: check return values!!!
    echo "Bench Pspell: ";
    $tag = 'ru';
    $pspell_link = pspell_new($tag, "", "", "", PSPELL_FAST | PSPELL_RUN_TOGETHER);
    $not_found = 0;
    $b = microtime(true);
    foreach ($words as $word) {
        if (false === pspell_check($pspell_link, $word)) {
            pspell_suggest($pspell_link, $word);
            $not_found++;
        }
    }
    $e = microtime(true);
    printf("time = %0.2f sec, words per second = %0.2f, not found = %d\n", $e - $b, count($words) / ($e - $b), $not_found);
}
Ejemplo n.º 24
0
 public static function GetSpellSuggestionsWithPspell($strText, $strSpellLang)
 {
     if (!function_exists('pspell_new')) {
         return true;
     }
     if (file_exists(__DICTIONARY_PATH__ . '/' . $strSpellLang . '.dat')) {
         if (!defined('PSPELL_FAST')) {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
         if (!($pspell_config = pspell_config_create($strSpellLang, null, null, 'utf-8'))) {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
         if (!pspell_config_data_dir($pspell_config, __DICTIONARY_PATH__)) {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
         if (!pspell_config_dict_dir($pspell_config, __DICTIONARY_PATH__)) {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
         if (!($pspell_link = @pspell_new_config($pspell_config))) {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
     } else {
         if (file_exists('/usr/lib/aspell-0.60/' . $strSpellLang . '.dat')) {
             $strDictPath = '/usr/lib/aspell-0.60/';
             $pspell_link = pspell_new($strSpellLang, null, null, 'utf-8');
         } elseif (file_exists('/usr/lib64/aspell-0.60/' . $strSpellLang . '.dat')) {
             $strDictPath = '/usr/lib64/aspell-0.60/';
             $pspell_link = pspell_new($strSpellLang, null, null, 'utf-8');
         } else {
             return self::GetSpellSuggestionsWithHunspell($strText, $strSpellLang);
         }
     }
     $arrSuggestions = array();
     $arrCleanText = mb_split('\\s+', $strText);
     foreach ($arrCleanText as $strCleanText) {
         if (!pspell_check($pspell_link, trim($strCleanText))) {
             $suggestions = pspell_suggest($pspell_link, trim($strCleanText));
             if (in_array($strCleanText, $suggestions)) {
                 continue;
             }
             $arrSuggestions[$strCleanText] = array_slice($suggestions, 0, 3);
         }
     }
     return $arrSuggestions;
 }
Ejemplo n.º 25
0
 public function checkWords($adjust = 1, $length = 4, $percent = 0.2)
 {
     if ($this->length == 0) {
         return;
     }
     $dict = pspell_new('en', null, null, 'utf-8', PSPELL_FAST);
     preg_match_all('/[a-z]+/i', $this->password, $words);
     foreach ($words[0] as $word) {
         if (strlen($word) < $length) {
             continue;
         }
         if (strlen($word) / $this->length < $percent) {
             continue;
         }
         if (!pspell_check($dict, $word)) {
             continue;
         }
         $this->change($this->max * max(1.5 + strlen($word) / $this->length / 2 * $adjust, 1), "Found the word '%s'", array($word));
     }
 }
Ejemplo n.º 26
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;
    }
Ejemplo n.º 27
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;
 }
Ejemplo n.º 28
0
 /**
  * Check the current configuration for missing properties
  * and deprecated or obsolete settings
  *
  * @return array List with problems detected
  */
 function check_config()
 {
     $this->load_config();
     if (!$this->configured) {
         return null;
     }
     $out = $seen = array();
     // iterate over the current configuration
     foreach ($this->config as $prop => $value) {
         if ($replacement = $this->replaced_config[$prop]) {
             $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
             $seen[$replacement] = true;
         } else {
             if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
                 $out['obsolete'][] = array('prop' => $prop);
                 $seen[$prop] = true;
             }
         }
     }
     // the old default mime_magic reference is obsolete
     if ($this->config['mime_magic'] == '/usr/share/misc/magic') {
         $out['obsolete'][] = array('prop' => 'mime_magic', 'explain' => "Set value to null in order to use system default");
     }
     // check config dependencies and contradictions
     if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
         if (!extension_loaded('pspell')) {
             $out['dependencies'][] = array('prop' => 'spellcheck_engine', 'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
         } else {
             if (!empty($this->config['spellcheck_languages'])) {
                 foreach ($this->config['spellcheck_languages'] as $lang => $descr) {
                     if (!@pspell_new($lang)) {
                         $out['dependencies'][] = array('prop' => 'spellcheck_languages', 'explain' => "You are missing pspell support for language {$lang} ({$descr})");
                     }
                 }
             }
         }
     }
     if ($this->config['log_driver'] == 'syslog') {
         if (!function_exists('openlog')) {
             $out['dependencies'][] = array('prop' => 'log_driver', 'explain' => 'This requires the <tt>syslog</tt> extension which could not be loaded.');
         }
         if (empty($this->config['syslog_id'])) {
             $out['dependencies'][] = array('prop' => 'syslog_id', 'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
         }
     }
     // check ldap_public sources having global_search enabled
     if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
         foreach ($this->config['ldap_public'] as $ldap_public) {
             if ($ldap_public['global_search']) {
                 $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
                 break;
             }
         }
     }
     return $out;
 }
Ejemplo n.º 29
0
    /**
     * Main class of Spell Checker plugin for Typo3 CMS
     *
     * @return string content produced by the plugin
     */
    public function main()
    {
        $this->csConvObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
        // Setting start time
        $time_start = microtime(TRUE);
        $this->pspell_is_available = in_array('pspell', get_loaded_extensions());
        $this->AspellDirectory = trim($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['plugins']['SpellChecker']['AspellDirectory']) ?: '/usr/bin/aspell';
        // Setting command mode if requested and available
        $this->forceCommandMode = trim($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['plugins']['SpellChecker']['forceCommandMode']) ?: 0;
        if (!$this->pspell_is_available || $this->forceCommandMode) {
            $AspellVersionString = explode('Aspell', shell_exec($this->AspellDirectory . ' -v'));
            $AspellVersion = substr($AspellVersionString[1], 0, 4);
            if (doubleval($AspellVersion) < doubleval('0.5') && (!$this->pspell_is_available || $this->forceCommandMode)) {
                echo 'Configuration problem: Aspell version ' . $AspellVersion . ' too old. Spell checking cannot be performed in command mode.';
            }
            $this->defaultAspellEncoding = trim(shell_exec($this->AspellDirectory . ' config encoding'));
        }
        // Setting the list of dictionaries
        $dictionaryList = shell_exec($this->AspellDirectory . ' dump dicts');
        $dictionaryList = implode(',', GeneralUtility::trimExplode(LF, $dictionaryList, TRUE));
        $dictionaryArray = GeneralUtility::trimExplode(',', $dictionaryList, TRUE);
        $restrictToDictionaries = GeneralUtility::_POST('restrictToDictionaries');
        if ($restrictToDictionaries) {
            $dictionaryArray = array_intersect($dictionaryArray, GeneralUtility::trimExplode(',', $restrictToDictionaries, 1));
        }
        if (!count($dictionaryArray)) {
            $dictionaryArray[] = 'en';
        }
        $this->dictionary = GeneralUtility::_POST('dictionary');
        $defaultDictionary = $this->dictionary;
        if (!$defaultDictionary || !in_array($defaultDictionary, $dictionaryArray)) {
            $defaultDictionary = 'en';
        }
        uasort($dictionaryArray, 'strcoll');
        $dictionaryList = implode(',', $dictionaryArray);
        // Setting the dictionary
        if (empty($this->dictionary) || !in_array($this->dictionary, $dictionaryArray)) {
            $this->dictionary = 'en';
        }
        // Setting the pspell suggestion mode
        $this->pspellMode = GeneralUtility::_POST('pspell_mode') ? GeneralUtility::_POST('pspell_mode') : $this->pspellMode;
        // Now sanitize $this->pspellMode
        $this->pspellMode = GeneralUtility::inList('ultra,fast,normal,bad-spellers', $this->pspellMode) ? $this->pspellMode : 'normal';
        switch ($this->pspellMode) {
            case 'ultra':
            case 'fast':
                $pspellModeFlag = PSPELL_FAST;
                break;
            case 'bad-spellers':
                $pspellModeFlag = PSPELL_BAD_SPELLERS;
                break;
            case 'normal':
            default:
                $pspellModeFlag = PSPELL_NORMAL;
        }
        // Setting the charset
        if (GeneralUtility::_POST('pspell_charset')) {
            $this->charset = trim(GeneralUtility::_POST('pspell_charset'));
        }
        if (strtolower($this->charset) == 'iso-8859-1') {
            $this->parserCharset = strtolower($this->charset);
        }
        // In some configurations, Aspell uses 'iso8859-1' instead of 'iso-8859-1'
        $this->aspellEncoding = $this->parserCharset;
        if ($this->parserCharset == 'iso-8859-1' && strstr($this->defaultAspellEncoding, '8859-1')) {
            $this->aspellEncoding = $this->defaultAspellEncoding;
        }
        // However, we are going to work only in the parser charset
        if ($this->pspell_is_available && !$this->forceCommandMode) {
            $this->pspell_link = pspell_new($this->dictionary, '', '', $this->parserCharset, $pspellModeFlag);
        }
        // Setting the path to main dictionary
        $this->setMainDictionaryPath();
        // Setting the path to user personal dictionary, if any
        $this->setPersonalDictionaryPath();
        $this->fixPersonalDictionaryCharacterSet();
        $cmd = GeneralUtility::_POST('cmd');
        if ($cmd == 'learn') {
            // Only availble for BE_USERS, die silently if someone has gotten here by accident
            if (TYPO3_MODE !== 'BE' || !is_object($GLOBALS['BE_USER'])) {
                die('');
            }
            // Updating the personal word list
            $to_p_dict = GeneralUtility::_POST('to_p_dict');
            $to_p_dict = $to_p_dict ? $to_p_dict : array();
            $to_r_list = GeneralUtility::_POST('to_r_list');
            $to_r_list = $to_r_list ? $to_r_list : array();
            header('Content-Type: text/plain; charset=' . strtoupper($this->parserCharset));
            header('Pragma: no-cache');
            if ($to_p_dict || $to_r_list) {
                $tmpFileName = GeneralUtility::tempnam($this->filePrefix);
                $filehandle = fopen($tmpFileName, 'wb');
                if ($filehandle) {
                    // Get the character set of the main dictionary
                    // We need to convert the input into the character set of the main dictionary
                    $mainDictionaryCharacterSet = $this->getMainDictionaryCharacterSet();
                    // Write the personal words addition commands to the temporary file
                    foreach ($to_p_dict as $personal_word) {
                        $cmd = '&' . $this->csConvObj->conv($personal_word, $this->parserCharset, $mainDictionaryCharacterSet) . LF;
                        fwrite($filehandle, $cmd, strlen($cmd));
                    }
                    // Write the replacent pairs addition commands to the temporary file
                    foreach ($to_r_list as $replace_pair) {
                        $cmd = '$$ra ' . $this->csConvObj->conv($replace_pair[0], $this->parserCharset, $mainDictionaryCharacterSet) . ' , ' . $this->csConvObj->conv($replace_pair[1], $this->parserCharset, $mainDictionaryCharacterSet) . LF;
                        fwrite($filehandle, $cmd, strlen($cmd));
                    }
                    $cmd = '#' . LF;
                    $result = fwrite($filehandle, $cmd, strlen($cmd));
                    if ($result === FALSE) {
                        GeneralUtility::sysLog('SpellChecker tempfile write error: ' . $tmpFileName, $this->extKey, GeneralUtility::SYSLOG_SEVERITY_ERROR);
                    } else {
                        // Assemble the Aspell command
                        $aspellCommand = (TYPO3_OS === 'WIN' ? 'type ' : 'cat ') . escapeshellarg($tmpFileName) . ' | ' . $this->AspellDirectory . ' -a --mode=none' . ($this->personalDictionaryPath ? ' --home-dir=' . escapeshellarg($this->personalDictionaryPath) : '') . ' --lang=' . escapeshellarg($this->dictionary) . ' --encoding=' . escapeshellarg($mainDictionaryCharacterSet) . ' 2>&1';
                        $aspellResult = shell_exec($aspellCommand);
                        // Close and delete the temporary file
                        fclose($filehandle);
                        GeneralUtility::unlink_tempfile($tmpFileName);
                    }
                } else {
                    GeneralUtility::sysLog('SpellChecker tempfile open error: ' . $tmpFileName, $this->extKey, GeneralUtility::SYSLOG_SEVERITY_ERROR);
                }
            }
            flush();
            die;
        } else {
            // Check spelling content
            // Initialize output
            $this->result = '<?xml version="1.0" encoding="' . $this->parserCharset . '"?>
<!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="' . substr($this->dictionary, 0, 2) . '" lang="' . substr($this->dictionary, 0, 2) . '">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=' . $this->parserCharset . '" />
<link rel="stylesheet" type="text/css" media="all" href="' . (TYPO3_MODE == 'BE' ? '../' : '') . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey) . '/Resources/Public/Css/Skin/Plugins/spell-checker-iframe.css" />
<script type="text/javascript">
/*<![CDATA[*/
<!--
';
            // Getting the input content
            $content = GeneralUtility::_POST('content');
            // Parsing the input HTML
            $parser = xml_parser_create(strtoupper($this->parserCharset));
            xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
            xml_set_object($parser, $this);
            if (!xml_set_element_handler($parser, 'startHandler', 'endHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_set_character_data_handler($parser, 'collectDataHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_set_default_handler($parser, 'defaultHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_parse($parser, '<?xml version="1.0" encoding="' . $this->parserCharset . '"?><spellchecker> ' . preg_replace('/&nbsp;/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), ' ', $content) . ' </spellchecker>')) {
                echo 'Bad parsing';
            }
            if (xml_get_error_code($parser)) {
                throw new \UnexpectedException('Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)), 1294585788);
            }
            xml_parser_free($parser);
            if ($this->pspell_is_available && !$this->forceCommandMode) {
                pspell_clear_session($this->pspell_link);
            }
            $this->result .= 'var suggestedWords = {' . $this->suggestedWords . '};
var dictionaries = "' . $dictionaryList . '";
var selectedDictionary = "' . $this->dictionary . '";
';
            // Calculating parsing and spell checkting time
            $time = number_format(microtime(TRUE) - $time_start, 2, ',', ' ');
            // Insert spellcheck info
            $this->result .= 'var spellcheckInfo = { "Total words":"' . $this->wordCount . '","Misspelled words":"' . sizeof($this->misspelled) . '","Total suggestions":"' . $this->suggestionCount . '","Total words suggested":"' . $this->suggestedWordCount . '","Spelling checked in":"' . $time . '" };
// -->
/*]]>*/
</script>
</head>
';
            $this->result .= '<body onload="window.parent.RTEarea[\'' . GeneralUtility::_POST('editorId') . '\'].editor.getPlugin(\'SpellChecker\').spellCheckComplete();">';
            $this->result .= preg_replace('/' . preg_quote('<?xml') . '.*' . preg_quote('?>') . '[' . preg_quote(LF . CR . chr(32)) . ']*/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '', $this->text);
            $this->result .= '<div style="display: none;">' . $dictionaries . '</div>';
            // Closing
            $this->result .= '
</body></html>';
            // Outputting
            header('Content-Type: text/html; charset=' . strtoupper($this->parserCharset));
            echo $this->result;
        }
    }
Ejemplo n.º 30
-1
	/**
	 * Opens a link for pspell.
	 */
	function &_getPLink($lang) {
		// Check for native PSpell support
		if (!function_exists("pspell_new"))
			$this->throwError("PSpell support not found in PHP installation.");

		// Setup PSpell link
		$plink = pspell_new(
			$lang,
			$this->_config['PSpell.spelling'],
			$this->_config['PSpell.jargon'],
			empty($this->_config['PSpell.encoding']) ? 'utf-8' : $this->_config['PSpell.encoding'],
			$this->_config['PSpell.mode']
		);

		// Setup PSpell link
/*		if (!$plink) {
			$pspellConfig = pspell_config_create(
				$lang,
				$this->_config['PSpell.spelling'],
				$this->_config['PSpell.jargon'],
				$this->_config['PSpell.encoding']
			);

			$plink = pspell_new_config($pspell_config);
		}*/

		if (!$plink)
			$this->throwError("No PSpell link found opened.");

		return $plink;
	}