3 * sqspell_functions.php
4 * ----------------------
5 * All SquirrelSpell-wide functions are in this file.
7 * Copyright (c) 1999-2005 The SquirrelMail Project Team
8 * Licensed under the GNU GPL. For full terms see the file COPYING.
10 * @author Konstantin Riabitsev <icon@duke.edu>
13 * @subpackage squirrelspell
17 * This function is the GUI wrapper for the options page. SquirrelSpell
18 * uses it for creating all Options pages.
20 * @param string $title The title of the page to display
21 * @param string $scriptsrc This is used to link a file.js into the
22 * <script src="file.js"></script> format. This
23 * allows to separate javascript from the rest of the
24 * plugin and place it into the js/ directory.
25 * @param string $body The body of the message to display.
28 function sqspell_makePage($title, $scriptsrc, $body){
29 global $color, $SQSPELL_VERSION;
31 if (! sqgetGlobalVar('MOD', $MOD, SQ_GET
) ) {
32 $MOD = 'options_main';
35 displayPageHeader($color, 'None');
36 echo " <br />\n";
38 * Check if we need to link in a script.
41 echo "<script type=\"text/javascript\" src=\"js/$scriptsrc\"></script>\n";
43 echo html_tag( 'table', '', 'center', '', 'width="95%" border="0" cellpadding="2" cellspacing="0"' ) . "\n"
44 . html_tag( 'tr', "\n" .
45 html_tag( 'td', '<strong>' . $title .'</strong>', 'center', $color[9] )
47 . html_tag( 'tr', "\n" .
48 html_tag( 'td', '<hr />', 'left' )
50 . html_tag( 'tr', "\n" .
51 html_tag( 'td', $body, 'left' )
54 * Generate a nice "Return to Options" link, unless this is the
57 if ($MOD != "options_main"){
58 echo html_tag( 'tr', "\n" .
59 html_tag( 'td', '<hr />', 'left' )
61 . html_tag( 'tr', "\n" .
62 html_tag( 'td', '<a href="sqspell_options.php">'
63 . _("Back to "SpellChecker Options" page")
69 * Close the table and display the version.
71 echo html_tag( 'tr', "\n" .
72 html_tag( 'td', '<hr />', 'left' )
75 html_tag( 'td', 'SquirrelSpell ' . squirrelspell_version(), 'center', $color[9] )
77 echo '</body></html>';
81 * Function similar to the one above. This one is a general wrapper
82 * for the Squirrelspell pop-up window. It's called form nearly
83 * everywhere, except the check_me module, since that one is highly
86 * @param string $onload Used to indicate and pass the name of a js function
87 * to call in a <body onload="function()" for automatic
88 * onload script execution.
89 * @param string $title Title of the page.
90 * @param string $scriptsrc If defined, link this javascript source page into
91 * the document using <script src="file.js"> format.
92 * @param string $body The content to include.
95 function sqspell_makeWindow($onload, $title, $scriptsrc, $body){
96 global $color, $SQSPELL_VERSION;
98 displayHtmlHeader($title,
99 ($scriptsrc ?
"\n<script type=\"text/javascript\" src=\"js/$scriptsrc\"></script>\n" : ''));
101 echo "<body text=\"$color[8]\" bgcolor=\"$color[4]\" link=\"$color[7]\" "
102 . "vlink=\"$color[7]\" alink=\"$color[7]\"";
104 * Provide an onload="jsfunction()" if asked to.
107 echo " onload=\"$onload\"";
110 * Draw the rest of the page.
113 . html_tag( 'table', "\n" .
114 html_tag( 'tr', "\n" .
115 html_tag( 'td', '<strong>' . $title . '</strong>', 'center', $color[9] )
117 html_tag( 'tr', "\n" .
118 html_tag( 'td', '<hr />', 'left' )
120 html_tag( 'tr', "\n" .
121 html_tag( 'td', $body, 'left' )
123 html_tag( 'tr', "\n" .
124 html_tag( 'td', '<hr />', 'left' )
126 html_tag( 'tr', "\n" .
127 html_tag( 'td', 'SquirrelSpell ' . squirrelspell_version(), 'center', $color[9] )
129 '', '', 'width="100%" border="0" cellpadding="2"' )
130 . "</body>\n</html>\n";
134 * Encryption function used by plugin (old format)
136 * This function does the encryption and decryption of the user
137 * dictionary. It is only available when PHP is compiled with
138 * mcrypt support (--with-mcrypt). See doc/CRYPTO for more
141 * @param $mode A string with either of the two recognized values:
142 * "encrypt" or "decrypt".
143 * @param $ckey The key to use for processing (the user's password
145 * @param $input Content to decrypt or encrypt, according to $mode.
146 * @return encrypted/decrypted content, or "PANIC" if the
148 * @since 1.5.1 (sqspell 0.5)
151 function sqspell_crypto_old($mode, $ckey, $input){
153 * Double-check if we have the mcrypt_generic function. Bail out if
156 if (!function_exists('mcrypt_generic')) {
160 * Setup mcrypt routines.
162 $td = mcrypt_module_open(MCRYPT_Blowfish
, "", MCRYPT_MODE_ECB
, "");
163 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size ($td), MCRYPT_RAND
);
164 mcrypt_generic_init($td, $ckey, $iv);
166 * See what we have to do depending on $mode.
167 * 'encrypt' -- Encrypt the content.
168 * 'decrypt' -- Decrypt the content.
172 $crypto = mcrypt_generic($td, $input);
175 $crypto = mdecrypt_generic($td, $input);
177 * See if it decrypted successfully. If so, it should contain
178 * the string "# SquirrelSpell". If not, then bail out.
180 if (!strstr($crypto, "# SquirrelSpell")){
186 * Finish up the mcrypt routines and return the processed content.
188 if (function_exists('mcrypt_generic_deinit')) {
190 mcrypt_generic_deinit ($td);
191 mcrypt_module_close ($td);
193 // older deprecated function
194 mcrypt_generic_end ($td);
200 * Encryption function used by plugin
202 * This function does the encryption and decryption of the user
203 * dictionary. It is only available when PHP is compiled with
204 * mcrypt support (--with-mcrypt). See doc/CRYPTO for more
207 * @param $mode A string with either of the two recognized values:
208 * "encrypt" or "decrypt".
209 * @param $ckey The key to use for processing (the user's password
211 * @param $input Content to decrypt or encrypt, according to $mode.
212 * @return encrypted/decrypted content, or "PANIC" if the
215 function sqspell_crypto($mode, $ckey, $input){
217 * Double-check if we have the mcrypt_generic function. Bail out if
220 if (!function_exists('mcrypt_generic')) {
224 * Setup mcrypt routines.
226 $td = mcrypt_module_open(MCRYPT_Blowfish
, "", MCRYPT_MODE_ECB
, "");
227 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size ($td), MCRYPT_RAND
);
228 mcrypt_generic_init($td, $ckey, $iv);
230 * See what we have to do depending on $mode.
231 * 'encrypt' -- Encrypt the content.
232 * 'decrypt' -- Decrypt the content.
236 $crypto = mcrypt_generic($td, '{sqspell}'.$input);
239 $crypto = mdecrypt_generic($td, $input);
240 if (preg_match("/^\{sqspell\}(.*)/",$crypto,$match)){
241 $crypto = trim($match[1]);
248 * Finish up the mcrypt routines and return the processed content.
250 if (function_exists('mcrypt_generic_deinit')) {
252 mcrypt_generic_deinit ($td);
253 mcrypt_module_close ($td);
255 // older deprecated function
256 mcrypt_generic_end ($td);
262 * This function transparently upgrades the 0.2 dictionary format to the
263 * 0.3 format, since user-defined languages have been added in 0.3 and
264 * the new format keeps user dictionaries selection in the file.
266 * This function will be retired soon, as it's been a while since anyone
267 * has been using SquirrelSpell-0.2.
269 * @param $words_string Contents of the 0.2-style user dictionary.
270 * @return Contents of the 0.3-style user dictionary.
273 function sqspell_upgradeWordsFile($words_string){
274 global $SQSPELL_APP_DEFAULT, $SQSPELL_VERSION;
276 * Define just one dictionary for this user -- the default.
277 * If the user wants more, s/he can set them up in personal
278 * preferences. See doc/UPGRADING for more info.
281 substr_replace($words_string,
282 "# SquirrelSpell User Dictionary $SQSPELL_VERSION\n# "
283 . "Last Revision: " . date("Y-m-d")
284 . "\n# LANG: $SQSPELL_APP_DEFAULT\n# $SQSPELL_APP_DEFAULT",
285 0, strpos($words_string, "\n")) . "# End\n";
286 sqspell_writeWords($new_words_string);
287 return $new_words_string;
291 * gets list of available dictionaries from user's prefs.
292 * Function was modified in 1.5.1 (sqspell 0.5).
293 * Older function is suffixed with '_old'
294 * @return array list of dictionaries used by end user.
296 function sqspell_getSettings(){
297 global $data_dir, $username, $SQSPELL_APP_DEFAULT, $SQSPELL_APP;
301 $sLangs=getPref($data_dir,$username,'sqspell_langs','');
303 $ret[0]=$SQSPELL_APP_DEFAULT;
305 $aLangs = explode(',',$sLangs);
306 foreach ($aLangs as $lang) {
307 if (array_key_exists($lang,$SQSPELL_APP)) {
316 * Saves user's language preferences
317 * @param array $langs languages array (first key is default language)
318 * @since 1.5.1 (sqspell 0.5)
320 function sqspell_saveSettings($langs) {
321 global $data_dir, $username;
322 setPref($data_dir,$username,'sqspell_langs',implode(',',$langs));
326 * Get list of enabled languages.
328 * Right now it just returns an array with the dictionaries
329 * available to the user for spell-checking. It will probably
330 * do more in the future, as features are added.
332 * @param string $words The contents of the user's ".words" file.
333 * @return array a strings array with dictionaries available
334 * to this user, e.g. {"English", "Spanish"}, etc.
335 * @since 1.5.1 (sqspell 0.5)
338 function sqspell_getSettings_old($words){
339 global $SQSPELL_APP, $SQSPELL_APP_DEFAULT;
341 * Check if there is more than one dictionary configured in the
344 if (sizeof($SQSPELL_APP) > 1){
346 * Now load the user prefs. Check if $words was empty -- a bit of
347 * a dirty fall-back. TODO: make it so this is not required.
350 $words=sqspell_getWords_old();
354 * This user has a ".words" file.
355 * Find which dictionaries s/he wants to use and load them into
358 preg_match("/# LANG: (.*)/i", $words, $matches);
359 $langs=explode(", ", $matches[1]);
362 * User doesn't have a personal dictionary. Grab the default
365 $langs[0]=$SQSPELL_APP_DEFAULT;
369 * There is no need to read the ".words" file as there is only one
370 * dictionary defined system-wide.
372 $langs[0]=$SQSPELL_APP_DEFAULT;
378 * Get user dictionary for selected language
379 * Function was modified in 1.5.1 (sqspell 0.5).
380 * Older function is suffixed with '_old'
381 * @param string $lang language
382 * @param array words stored in selected language dictionary
384 function sqspell_getLang($lang) {
385 global $data_dir, $username,$SQSPELL_CRYPTO;
386 $sWords=getPref($data_dir,$username,'sqspell_dict_' . $lang,'');
387 if (preg_match("/^\{crypt\}(.*)/i",$sWords,$match)) {
389 * Dictionary is encrypted or mangled. Try to decrypt it.
390 * If fails, complain loudly.
392 * $old_key would be a value submitted by one of the modules with
393 * the user's old mailbox password. I admin, this is rather dirty,
396 if (sqgetGlobalVar('old_key', $old_key, SQ_POST
)) {
399 sqgetGlobalVar('key', $key, SQ_COOKIE
);
400 sqgetGlobalVar('onetimepad', $onetimepad, SQ_SESSION
);
402 * Get user's password (the key).
404 $clear_key = OneTimePadDecrypt($key, $onetimepad);
407 * Invoke the decryption routines.
409 $sWords=sqspell_crypto("decrypt", $clear_key, $match[1]);
411 * See if decryption failed.
413 if ($sWords=="PANIC"){
414 sqspell_handle_crypt_panic($lang);
415 // script execution stops here
418 * OK! Phew. Set the encryption flag to true so we can later on
419 * encrypt it again before saving to HDD.
421 $SQSPELL_CRYPTO=true;
425 * No encryption is/was used. Set $SQSPELL_CRYPTO to false,
426 * in case we have to save the dictionary later.
428 $SQSPELL_CRYPTO=false;
430 // rebuild word list and remove empty entries
432 foreach (explode(',',$sWords) as $word) {
433 if (trim($word) !='') {
434 $aWords[]=trim($word);
441 * Get user's dictionary (old format)
443 * This function returns only user-defined dictionary words that correspond
444 * to the requested language.
446 * @param $words The contents of the user's ".words" file.
447 * @param $lang Which language words to return, e.g. requesting
448 * "English" will return ONLY the words from user's
449 * English dictionary, disregarding any others.
450 * @return The list of words corresponding to the language
452 * @since 1.5.1 (sqspell 0.5)
455 function sqspell_getLang_old($words, $lang){
456 $start=strpos($words, "# $lang\n");
458 * strpos() will return -1 if no # $lang\n string was found.
459 * Use this to return a zero-length value and indicate that no
460 * words are present in the requested dictionary.
462 if (!$start) return '';
464 * The words list will end with a new directive, which will start
465 * with "#". Locate the next "#" and thus find out where the
468 $end=strpos($words, "#", $start+
1);
469 $lang_words = substr($words, $start, $end-$start);
474 * Saves user's dictionary (old format)
476 * This function operates the user dictionary. If the format is
477 * clear-text, then it just reads the file and returns it. However, if
478 * the file is encrypted (well, "garbled"), then it tries to decrypt
479 * it, checks whether the decryption was successful, troubleshoots if
480 * not, then returns the clear-text dictionary to the app.
482 * @return the contents of the user's ".words" file, decrypted if
484 * @since 1.5.1 (sqspell 0.5)
487 function sqspell_getWords_old(){
488 global $SQSPELL_WORDS_FILE, $SQSPELL_CRYPTO;
490 if (file_exists($SQSPELL_WORDS_FILE)){
494 $fp=fopen($SQSPELL_WORDS_FILE, 'r');
495 $words=fread($fp, filesize($SQSPELL_WORDS_FILE));
499 * Check if this is an encrypted file by looking for
500 * the string "# SquirrelSpell" in it (the crypto
501 * function does that).
503 if ($words && !strstr($words, "# SquirrelSpell")){
505 * This file is encrypted or mangled. Try to decrypt it.
506 * If fails, complain loudly.
508 * $old_key would be a value submitted by one of the modules with
509 * the user's old mailbox password. I admin, this is rather dirty,
512 sqgetGlobalVar('key', $key, SQ_COOKIE
);
513 sqgetGlobalVar('onetimepad', $onetimepad, SQ_SESSION
);
515 sqgetGlobalVar('old_key', $old_key, SQ_POST
);
517 if ($old_key != '') {
521 * Get user's password (the key).
523 $clear_key = OneTimePadDecrypt($key, $onetimepad);
526 * Invoke the decryption routines.
528 $words=sqspell_crypto_old("decrypt", $clear_key, $words);
530 * See if decryption failed.
532 if ($words=="PANIC"){
533 sqspell_handle_crypt_panic();
534 // script execution stops here.
537 * OK! Phew. Set the encryption flag to true so we can later on
538 * encrypt it again before saving to HDD.
540 $SQSPELL_CRYPTO=true;
544 * No encryption is/was used. Set $SQSPELL_CRYPTO to false,
545 * in case we have to save the dictionary later.
547 $SQSPELL_CRYPTO=false;
550 * Check if we need to upgrade the dictionary from version 0.2.x
551 * This is going away soon.
553 if (strstr($words, "Dictionary v0.2")){
554 $words=sqspell_upgradeWordsFile($words);
560 * Saves user's dictionary
561 * Function was replaced in 1.5.1 (sqspell 0.5).
562 * Older function is suffixed with '_old'
563 * @param array $words words that should be stored in dictionary
564 * @param string $lang language
566 function sqspell_writeWords($words,$lang){
567 global $SQSPELL_CRYPTO,$username,$data_dir;
569 $sWords = implode(',',$words);
570 if ($SQSPELL_CRYPTO){
572 * User wants to encrypt the file. So be it.
573 * Get the user's password to use as a key.
575 sqgetGlobalVar('key', $key, SQ_COOKIE
);
576 sqgetGlobalVar('onetimepad', $onetimepad, SQ_SESSION
);
578 $clear_key=OneTimePadDecrypt($key, $onetimepad);
580 * Try encrypting it. If fails, scream bloody hell.
582 $save_words = sqspell_crypto("encrypt", $clear_key, $sWords);
583 if ($save_words == 'PANIC'){
584 // FIXME: handle errors here
587 $save_words='{crypt}'.$save_words;
591 setPref($data_dir,$username,'sqspell_dict_'.$lang,$save_words);
595 * Writes user dictionary into the $username.words file, then changes mask
596 * to 0600. If encryption is needed -- does that, too.
598 * @param $words The contents of the ".words" file to write.
600 * @since 1.5.1 (sqspell 0.5)
603 function sqspell_writeWords_old($words){
604 global $SQSPELL_WORDS_FILE, $SQSPELL_CRYPTO;
606 * if $words is empty, create a template entry by calling the
607 * sqspell_makeDummy() function.
610 $words=sqspell_makeDummy();
612 if ($SQSPELL_CRYPTO){
614 * User wants to encrypt the file. So be it.
615 * Get the user's password to use as a key.
617 sqgetGlobalVar('key', $key, SQ_COOKIE
);
618 sqgetGlobalVar('onetimepad', $onetimepad, SQ_SESSION
);
620 $clear_key=OneTimePadDecrypt($key, $onetimepad);
622 * Try encrypting it. If fails, scream bloody hell.
624 $save_words = sqspell_crypto("encrypt", $clear_key, $words);
625 if ($save_words == 'PANIC'){
627 * AAAAAAAAH! I'm not handling this yet, since obviously
628 * the admin of the site forgot to compile the MCRYPT support in
629 * when upgrading an existing PHP installation.
630 * I will add a handler for this case later, when I can come up
631 * with some work-around... Right now, do nothing. Let the Admin's
634 /** save some hairs on admin's head and store error message in logs */
635 error_log('SquirrelSpell: php does not have mcrypt support');
638 $save_words = $words;
641 * Do the actual writing.
643 $fp=fopen($SQSPELL_WORDS_FILE, "w");
644 fwrite($fp, $save_words);
646 chmod($SQSPELL_WORDS_FILE, 0600);
650 * Deletes user's dictionary
651 * Function was modified in 1.5.1 (sqspell 0.5). Older function is suffixed
653 * @param string $lang dictionary
655 function sqspell_deleteWords($lang) {
656 global $data_dir, $username;
657 removePref($data_dir,$username,'sqspell_dict_'.$lang);
661 * Deletes user's dictionary when it is corrupted.
662 * @since 1.5.1 (sqspell 0.5)
665 function sqspell_deleteWords_old(){
667 * So I open the door to my enemies,
668 * and I ask can we wipe the slate clean,
669 * but they tell me to please go...
670 * uhm... Well, this just erases the user dictionary file.
672 global $SQSPELL_WORDS_FILE;
673 if (file_exists($SQSPELL_WORDS_FILE)){
674 unlink($SQSPELL_WORDS_FILE);
678 * Creates an empty user dictionary for the sake of saving prefs or
681 * @return The template to use when storing the user dictionary.
684 function sqspell_makeDummy(){
685 global $SQSPELL_VERSION, $SQSPELL_APP_DEFAULT;
686 $words = "# SquirrelSpell User Dictionary $SQSPELL_VERSION\n"
687 . "# Last Revision: " . date('Y-m-d')
688 . "\n# LANG: $SQSPELL_APP_DEFAULT\n# End\n";
693 * This function checks for security attacks. A $MOD variable is
694 * provided in the QUERY_STRING and includes one of the files from the
695 * modules directory ($MOD.mod). See if someone is trying to get out
696 * of the modules directory by providing dots, unicode strings, or
699 * @param string $rMOD the name of the module requested to include.
700 * @return void, since it bails out with an access error if needed.
702 function sqspell_ckMOD($rMOD){
703 if (strstr($rMOD, '.')
704 ||
strstr($rMOD, '/')
705 ||
strstr($rMOD, '%')
706 ||
strstr($rMOD, "\\")){
713 * Used to check internal version of SquirrelSpell dictionary
714 * @param integer $major main version number
715 * @param integer $minor second version number
716 * @return boolean true if stored dictionary version is $major.$minor or newer
717 * @since 1.5.1 (sqspell 0.5)
719 function sqspell_check_version($major,$minor) {
720 global $data_dir, $username;
721 // 0.4 version is internal version number that is used to indicate upgrade from
722 // separate files to generic SquirrelMail prefs storage.
723 $sqspell_version=getPref($data_dir,$username,'sqspell_version','0.4');
725 $aVersion=explode('.',$sqspell_version);
727 if ($aVersion[0] < $major ||
728 ( $aVersion[0] == $major && $aVersion[1] < $minor)) {
735 * Displays form that allows to enter different password for dictionary decryption.
736 * If language is not set, function provides form to handle older dictionary files.
737 * @param string $lang language
738 * @since 1.5.1 (sqspell 0.5)
740 function sqspell_handle_crypt_panic($lang=false) {
741 if (! sqgetGlobalVar('SCRIPT_NAME',$SCRIPT_NAME,SQ_SERVER
))
745 * AAAAAAAAAAAH!!!!! OK, ok, breathe!
746 * Let's hope the decryption failed because the user changed his
747 * password. Bring up the option to key in the old password
748 * or wipe the file and start over if everything else fails.
750 * The _("SquirrelSpell...) line has to be on one line, otherwise
751 * gettext will bork. ;(
753 $msg = html_tag( 'p', "\n" .
754 '<strong>' . _("ATTENTION:") . '</strong><br />'
755 . _("SquirrelSpell was unable to decrypt your personal dictionary. This is most likely due to the fact that you have changed your mailbox password. In order to proceed, you will have to supply your old password so that SquirrelSpell can decrypt your personal dictionary. It will be re-encrypted with your new password after this. If you haven't encrypted your dictionary, then it got mangled and is no longer valid. You will have to delete it and start anew. This is also true if you don't remember your old password -- without it, the encrypted data is no longer accessible.") ,
757 . (($lang) ?
html_tag('p',sprintf(_("Your %s dictionary is encrypted with password that differs from your current password."),
758 htmlspecialchars($lang)),'left') : '')
759 . '<blockquote>' . "\n"
760 . '<form method="post" onsubmit="return AYS()">' . "\n"
761 . '<input type="hidden" name="MOD" value="crypto_badkey" />' . "\n"
763 '<input type="hidden" name="dict_lang" value="'.htmlspecialchars($lang).'" />' :
764 '<input type="hidden" name="old_setup" value="yes" />')
765 . html_tag( 'p', "\n" .
766 '<input type="checkbox" name="delete_words" value="ON" />'
767 . _("Delete my dictionary and start a new one") . '<br />'
768 . _("Decrypt my dictionary with my old password:")
769 . '<input name="old_key" size="10" />' ,
771 . '</blockquote>' . "\n"
772 . html_tag( 'p', "\n"
773 . '<input type="submit" value="'
774 . _("Proceed") . ' >>" />' ,
778 * Add some string vars so they can be i18n'd.
780 $msg .= "<script type='text/javascript'><!--\n"
781 . "var ui_choice = \"" . _("You must make a choice") ."\";\n"
782 . "var ui_candel = \"" . _("You can either delete your dictionary or type in the old password. Not both.") . "\";\n"
783 . "var ui_willdel = \"" . _("This will delete your personal dictionary file. Proceed?") . "\";\n"
784 . "//--></script>\n";
786 * See if this happened in the pop-up window or when accessing
787 * the SpellChecker options page.
788 * This is a dirty solution, I agree.
789 * TODO: make this prettier.
791 if (strstr($SCRIPT_NAME, "sqspell_options")){
792 sqspell_makePage(_("Error Decrypting Dictionary"),
793 "decrypt_error.js", $msg);
795 sqspell_makeWindow(null, _("Error Decrypting Dictionary"),
796 "decrypt_error.js", $msg);
802 * SquirrelSpell version. Don't modify, since it identifies the format
803 * of the user dictionary files and messing with this can do ugly
805 * @global string $SQSPELL_VERSION
808 $SQSPELL_VERSION="v0.3.8";