Source for file imap_general.php

Documentation is available at imap_general.php

  1. <?php
  2.  
  3. /**
  4.  * imap_general.php
  5.  *
  6.  * This implements all functions that do general IMAP functions.
  7.  *
  8.  * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  9.  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10.  * @version $Id: imap_general.php,v 1.140.2.37 2006/10/04 19:35:42 stekkel Exp $
  11.  * @package squirrelmail
  12.  * @subpackage imap
  13.  */
  14.  
  15. /** Includes.. */
  16. require_once(SM_PATH 'functions/page_header.php');
  17. require_once(SM_PATH 'functions/auth.php');
  18.  
  19.  
  20. /**
  21.  * Generates a new session ID by incrementing the last one used;
  22.  * this ensures that each command has a unique ID.
  23.  * @param bool unique_id
  24.  * @return string IMAP session id of the form 'A000'.
  25.  */
  26. function sqimap_session_id($unique_id FALSE{
  27.     static $sqimap_session_id 1;
  28.  
  29.     if (!$unique_id{
  30.         returnsprintf("A%03d"$sqimap_session_id++) );
  31.     else {
  32.         returnsprintf("A%03d"$sqimap_session_id++' UID' );
  33.     }
  34. }
  35.  
  36. /**
  37.  * Both send a command and accept the result from the command.
  38.  * This is to allow proper session number handling.
  39.  */
  40. function sqimap_run_command_list ($imap_stream$query$handle_errors&$response&$message$unique_id false{
  41.     if ($imap_stream{
  42.         $sid sqimap_session_id($unique_id);
  43.         fputs ($imap_stream$sid ' ' $query "\r\n");
  44.         $read sqimap_read_data_list ($imap_stream$sid$handle_errors$response$message$query );
  45.         return $read;
  46.     else {
  47.         global $squirrelmail_language$color;
  48.         set_up_language($squirrelmail_language);
  49.         require_once(SM_PATH 'functions/display_messages.php');
  50.         $string "<b><font color=\"$color[2]\">\n.
  51.                 _("ERROR: No available IMAP stream.".
  52.                 "</b></font>\n";
  53.         error_box($string,$color);
  54.         return false;
  55.     }
  56. }
  57.  
  58. function sqimap_run_command ($imap_stream$query$handle_errors&$response,
  59.                             &$message$unique_id false,$filter=false,
  60.                              $outputstream=false,$no_return=false{
  61.     if ($imap_stream{
  62.         $sid sqimap_session_id($unique_id);
  63.         fputs ($imap_stream$sid ' ' $query "\r\n");
  64.         $read sqimap_read_data ($imap_stream$sid$handle_errors$response,
  65.                                   $message$query,$filter,$outputstream,$no_return);
  66.         return $read;
  67.     else {
  68.         global $squirrelmail_language$color;
  69.         set_up_language($squirrelmail_language);
  70.         require_once(SM_PATH 'functions/display_messages.php');
  71.         $string "<b><font color=\"$color[2]\">\n.
  72.                 _("ERROR: No available IMAP stream.".
  73.                 "</b></font>\n";
  74.         error_box($string,$color);
  75.         return false;
  76.     }
  77. }
  78.  
  79.  
  80. /**
  81.  * Custom fgets function: gets a line from the IMAP server,
  82.  * no matter how big it may be.
  83.  * @param stream imap_stream the stream to read from
  84.  * @return string a line
  85.  */
  86. function sqimap_fgets($imap_stream{
  87.     $read '';
  88.     $buffer 4096;
  89.     $results '';
  90.     $offset 0;
  91.     while (strpos($results"\r\n"$offset=== false{
  92.         if (!($read fgets($imap_stream$buffer))) {
  93.         /* this happens in case of an error */
  94.         /* reset $results because it's useless */
  95.         $results false;
  96.             break;
  97.         }
  98.         if $results != '' {
  99.             $offset strlen($results1;
  100.         }
  101.         $results .= $read;
  102.     }
  103.     return $results;
  104. }
  105.  
  106. function sqimap_fread($imap_stream,$iSize,$filter=false,
  107.                       $outputstream=false$no_return=false{
  108.     if (!$filter || !$outputstream{
  109.         $iBufferSize $iSize;
  110.     else {
  111.         // see php bug 24033. They changed fread behaviour %$^&$%
  112.         $iBufferSize 7800// multiple of 78 in case of base64 decoding.
  113.     }
  114.     if ($iSize $iBufferSize{
  115.         $iBufferSize $iSize;
  116.     }
  117.  
  118.     $iRetrieved 0;
  119.     $results '';
  120.     $sRead $sReadRem '';
  121.     // NB: fread can also stop at end of a packet on sockets.
  122.     while ($iRetrieved $iSize{
  123.         $sRead fread($imap_stream,$iBufferSize);
  124.         $iLength strlen($sRead);
  125.         $iRetrieved += $iLength ;
  126.         $iRemaining $iSize $iRetrieved;
  127.         if ($iRemaining $iBufferSize{
  128.             $iBufferSize $iRemaining;
  129.         }
  130.         if ($sRead == ''{
  131.             $results false;
  132.             break;
  133.         }
  134.         if ($sReadRem != ''{
  135.             $sRead $sReadRem $sRead;
  136.             $sReadRem '';
  137.         }
  138.  
  139.         if ($filter && $sRead != ''{
  140.            // in case the filter is base64 decoding we return a remainder
  141.            $sReadRem $filter($sRead);
  142.         }
  143.         if ($outputstream && $sRead != ''{
  144.            if (is_resource($outputstream)) {
  145.                fwrite($outputstream,$sRead);
  146.            else if ($outputstream == 'php://stdout'{
  147.                echo $sRead;
  148.            }
  149.         }
  150.         if ($no_return{
  151.             $sRead '';
  152.         else {
  153.             $results .= $sRead;
  154.         }
  155.     }
  156.     return $results;
  157. }
  158.  
  159. /**
  160.  * Reads the output from the IMAP stream.  If handle_errors is set to true,
  161.  * this will also handle all errors that are received.  If it is not set,
  162.  * the errors will be sent back through $response and $message.
  163.  */
  164. function sqimap_read_data_list ($imap_stream$tag_uid$handle_errors,
  165.           &$response&$message$query '',
  166.            $filter false$outputstream false$no_return false{
  167.     global $color$squirrelmail_language;
  168.     $read '';
  169.     $tag_uid_a explode(' ',trim($tag_uid));
  170.     $tag $tag_uid_a[0];
  171.     $resultlist array();
  172.     $data array();
  173.     $read sqimap_fgets($imap_stream);
  174.     $i 0;
  175.     while ($read{
  176.         $char $read{0};
  177.         switch ($char)
  178.         {
  179.           case '+':
  180.           default:
  181.             $read sqimap_fgets($imap_stream);
  182.             break;
  183.  
  184.           case $tag{0}:
  185.           {
  186.             /* get the command */
  187.             $arg '';
  188.             $i strlen($tag)+1;
  189.             $s substr($read,$i);
  190.             if (($j strpos($s,' ')) || ($j strpos($s,"\n"))) {
  191.                 $arg substr($s,0,$j);
  192.             }
  193.             $found_tag substr($read,0,$i-1);
  194.             if ($arg && $found_tag==$tag{
  195.                 switch ($arg)
  196.                 {
  197.                   case 'OK':
  198.                   case 'BAD':
  199.                   case 'NO':
  200.                   case 'BYE':
  201.                   case 'PREAUTH':
  202.                     $response $arg;
  203.                     $message trim(substr($read,$i+strlen($arg)));
  204.                     break 3/* switch switch while */
  205.                   default:
  206.                     /* this shouldn't happen */
  207.                     $response $arg;
  208.                     $message trim(substr($read,$i+strlen($arg)));
  209.                     break 3/* switch switch while */
  210.                 }
  211.             elseif($found_tag !== $tag{
  212.                 /* reset data array because we do not need this reponse */
  213.                 $data array();
  214.                 $read sqimap_fgets($imap_stream);
  215.                 break;
  216.             }
  217.           // end case $tag{0}
  218.  
  219.           case '*':
  220.           {
  221.             if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
  222.                 /* check for literal */
  223.                 $s substr($read,-3);
  224.                 $fetch_data array();
  225.                 do /* outer loop, continue until next untagged fetch
  226.                         or tagged reponse */
  227.                     do /* innerloop for fetching literals. with this loop
  228.                             we prohibid that literal responses appear in the
  229.                             outer loop so we can trust the untagged and
  230.                             tagged info provided by $read */
  231.                         if ($s === "}\r\n"{
  232.                             $j strrpos($read,'{');
  233.                             $iLit substr($read,$j+1,-3);
  234.                             $fetch_data[$read;
  235.                             $sLiteral sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
  236.                             if ($sLiteral === false/* error */
  237.                                 break 4/* while while switch while */
  238.                             }
  239.                             /* backwards compattibility */
  240.                             $aLiteral explode("\n"$sLiteral);
  241.                             /* release not neaded data */
  242.                             unset($sLiteral);
  243.                             foreach ($aLiteral as $line{
  244.                                 $fetch_data[$line ."\n";
  245.                             }
  246.                             /* release not neaded data */
  247.                             unset($aLiteral);
  248.                             /* next fgets belongs to this fetch because
  249.                                we just got the exact literalsize and there
  250.                                must follow data to complete the response */
  251.                             $read sqimap_fgets($imap_stream);
  252.                             if ($read === false/* error */
  253.                                 break 4/* while while switch while */
  254.                             }
  255.                             $fetch_data[$read;
  256.                         else {
  257.                             $fetch_data[$read;
  258.                         }
  259.                         /* retrieve next line and check in the while
  260.                            statements if it belongs to this fetch response */
  261.                         $read sqimap_fgets($imap_stream);
  262.                         if ($read === false/* error */
  263.                             break 4/* while while switch while */
  264.                         }
  265.                         /* check for next untagged reponse and break */
  266.                         if ($read{0== '*'break 2;
  267.                         $s substr($read,-3);
  268.                     while ($s === "}\r\n");
  269.                     $s substr($read,-3);
  270.                 while ($read{0!== '*' &&
  271.                          substr($read,0,strlen($tag)) !== $tag);
  272.                 $resultlist[$fetch_data;
  273.                 /* release not neaded data */
  274.                 unset ($fetch_data);
  275.             else {
  276.                 $s substr($read,-3);
  277.                 do {
  278.                     if ($s === "}\r\n"{
  279.                         $j strrpos($read,'{');
  280.                         $iLit substr($read,$j+1,-3);
  281.                         // check for numeric value to avoid that untagged responses like:
  282.                         // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
  283.                         // will trigger literal fetching  ({SET:debug=51} !== int )
  284.                         if (is_numeric($iLit)) {
  285.                             $data[$read;
  286.                             $sLiteral fread($imap_stream,$iLit);
  287.                             if ($sLiteral === false/* error */
  288.                                 $read false;
  289.                                 break 3/* while switch while */
  290.                             }
  291.                             $data[$sLiteral;
  292.                             $data[sqimap_fgets($imap_stream);
  293.                         else {
  294.                             $data[$read;
  295.                         }
  296.                     else {
  297.                          $data[$read;
  298.                     }
  299.                     $read sqimap_fgets($imap_stream);
  300.                     if ($read === false{
  301.                         break 3/* while switch while */
  302.                     else if ($read{0== '*'{
  303.                         break;
  304.                     }
  305.                     $s substr($read,-3);
  306.                 while ($s === "}\r\n");
  307.                 break 1;
  308.             }
  309.             break;
  310.           // end case '*'
  311.         }   // end switch
  312.     // end while
  313.  
  314.     /* error processing in case $read is false */
  315.     if ($read === false{
  316.         unset($data);
  317.         set_up_language($squirrelmail_language);
  318.         require_once(SM_PATH 'functions/display_messages.php');
  319.         $string "<b><font color=\"$color[2]\">\n.
  320.                   _("ERROR: Connection dropped by IMAP server.".
  321.                   "</b><br />\n";
  322.         $cmd explode(' ',$query);
  323.         $cmd strtolower($cmd[0]);
  324.         if ($query != '' &&  $cmd != 'login'{
  325.             $string .= ("Query:"' 'htmlspecialchars($query)
  326.             . '<br />' "</font><br />\n";
  327.         }
  328.         error_box($string,$color);
  329.         exit;
  330.     }
  331.  
  332.     /* Set $resultlist array */
  333.     if (!empty($data)) {
  334.         $resultlist[$data;
  335.     }
  336.     elseif (empty($resultlist)) {
  337.         $resultlist[array();
  338.     }
  339.  
  340.     /* Return result or handle errors */
  341.     if ($handle_errors == false{
  342.         return$resultlist );
  343.     }
  344.     switch ($response{
  345.     case 'OK':
  346.         return $resultlist;
  347.         break;
  348.     case 'NO':
  349.         /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  350.         if (strstr($message'command resulted in'=== false{
  351.             set_up_language($squirrelmail_language);
  352.             require_once(SM_PATH 'functions/display_messages.php');
  353.             $string "<b><font color=\"$color[2]\">\n.
  354.                 _("ERROR: Could not complete request.".
  355.                 "</b><br />\n" .
  356.                 _("Query:"' ' .
  357.                 htmlspecialchars($query'<br />' .
  358.                 _("Reason Given:"' ' .
  359.                 htmlspecialchars($message"</font><br />\n";
  360.             error_box($string,$color);
  361.             echo '</body></html>';
  362.             exit;
  363.         }
  364.         break;
  365.     case 'BAD':
  366.         set_up_language($squirrelmail_language);
  367.         require_once(SM_PATH 'functions/display_messages.php');
  368.         $string "<b><font color=\"$color[2]\">\n.
  369.             _("ERROR: Bad or malformed request.".
  370.             "</b><br />\n" .
  371.             _("Query:"' '.
  372.             htmlspecialchars($query'<br />' .
  373.             _("Server responded:"' ' .
  374.             htmlspecialchars($message"</font><br />\n";
  375.         error_box($string,$color);
  376.         echo '</body></html>';
  377.         exit;
  378.     case 'BYE':
  379.         set_up_language($squirrelmail_language);
  380.         require_once(SM_PATH 'functions/display_messages.php');
  381.         $string "<b><font color=\"$color[2]\">\n.
  382.             _("ERROR: IMAP server closed the connection.".
  383.             "</b><br />\n" .
  384.             _("Query:"' '.
  385.             htmlspecialchars($query'<br />' .
  386.             _("Server responded:"' ' .
  387.             htmlspecialchars($message"</font><br />\n";
  388.         error_box($string,$color);
  389.         echo '</body></html>';
  390.         exit;
  391.     default:
  392.         set_up_language($squirrelmail_language);
  393.         require_once(SM_PATH 'functions/display_messages.php');
  394.         $string "<b><font color=\"$color[2]\">\n.
  395.             _("ERROR: Unknown IMAP response.".
  396.             "</b><br />\n" .
  397.             _("Query:"' '.
  398.             htmlspecialchars($query'<br />' .
  399.             _("Server responded:"' ' .
  400.             htmlspecialchars($message"</font><br />\n";
  401.         error_box($string,$color);
  402.        /* the error is displayed but because we don't know the reponse we
  403.           return the result anyway */
  404.        return $resultlist;
  405.        break;
  406.     }
  407. }
  408.  
  409. function sqimap_read_data ($imap_stream$tag_uid$handle_errors,
  410.                            &$response&$message$query '',
  411.                            $filter=false,$outputstream=false,$no_return=false{
  412.  
  413.     $res sqimap_read_data_list($imap_stream$tag_uid$handle_errors,
  414.               $response$message$query,$filter,$outputstream,$no_return);
  415.     /* sqimap_read_data should be called for one response
  416.        but since it just calls sqimap_read_data_list which
  417.        handles multiple responses we need to check for that
  418.        and merge the $res array IF they are seperated and
  419.        IF it was a FETCH response. */
  420.  
  421. //    if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
  422. //        && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
  423. //        $result = array();
  424. //        foreach($res as $index=>$value) {
  425. //            $result = array_merge($result, $res["$index"]);
  426. //        }
  427. //    }
  428.  
  429.     return $res[0];
  430. }
  431.  
  432. /**
  433.  * Logs the user into the IMAP server.  If $hide is set, no error messages
  434.  * will be displayed.  This function returns the IMAP connection handle.
  435.  */
  436. function sqimap_login ($username$password$imap_server_address$imap_port$hide{
  437.     global $color$squirrelmail_language$onetimepad$use_imap_tls$imap_auth_mech;
  438.  
  439.     if (!isset($onetimepad|| empty($onetimepad)) {
  440.         sqgetglobalvar('onetimepad' $onetimepad SQ_SESSION );
  441.     }
  442.     $imap_server_address sqimap_get_user_server($imap_server_address$username);
  443.         $host=$imap_server_address;
  444.  
  445.         if (($use_imap_tls == trueand (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  446.           /* Use TLS by prefixing "tls://" to the hostname */
  447.           $imap_server_address 'tls://' $imap_server_address;
  448.         }
  449.  
  450.     $imap_stream @fsockopen($imap_server_address$imap_port$error_number$error_string15);
  451.  
  452.     /* Do some error correction */
  453.     if (!$imap_stream{
  454.         if (!$hide{
  455.             set_up_language($squirrelmail_languagetrue);
  456.             require_once(SM_PATH 'functions/display_messages.php');
  457.             logout_errorsprintf(_("Error connecting to IMAP server: %s.")$imap_server_address).
  458.                 "<br />\r\n$error_number : $error_string<br />\r\n",
  459.         sprintf(_("Error connecting to IMAP server: %s.")$imap_server_address) );
  460.         }
  461.         exit;
  462.     }
  463.  
  464.     $server_info fgets ($imap_stream1024);
  465.  
  466.     /* Decrypt the password */
  467.     $password OneTimePadDecrypt($password$onetimepad);
  468.  
  469.     if (($imap_auth_mech == 'cram-md5'OR ($imap_auth_mech == 'digest-md5')) {
  470.         // We're using some sort of authentication OTHER than plain or login
  471.         $tag=sqimap_session_id(false);
  472.         if ($imap_auth_mech == 'digest-md5'{
  473.             $query $tag " AUTHENTICATE DIGEST-MD5\r\n";
  474.         elseif ($imap_auth_mech == 'cram-md5'{
  475.             $query $tag " AUTHENTICATE CRAM-MD5\r\n";
  476.         }
  477.         fputs($imap_stream,$query);
  478.         $answer=sqimap_fgets($imap_stream);
  479.         // Trim the "+ " off the front
  480.         $response=explode(" ",$answer,3);
  481.         if ($response[0== '+'{
  482.             // Got a challenge back
  483.             $challenge=$response[1];
  484.             if ($imap_auth_mech == 'digest-md5'{
  485.                 $reply digest_md5_response($username,$password,$challenge,'imap',$host);
  486.             elseif ($imap_auth_mech == 'cram-md5'{
  487.                 $reply cram_md5_response($username,$password,$challenge);
  488.             }
  489.             fputs($imap_stream,$reply);
  490.             $read=sqimap_fgets($imap_stream);
  491.             if ($imap_auth_mech == 'digest-md5'{
  492.                 // DIGEST-MD5 has an extra step..
  493.                 if (substr($read,0,1== '+'// OK so far..
  494.                     fputs($imap_stream,"\r\n");
  495.                     $read=sqimap_fgets($imap_stream);
  496.                 }
  497.             }
  498.             $results=explode(" ",$read,3);
  499.             $response=$results[1];
  500.             $message=$results[2];
  501.         else {
  502.             // Fake the response, so the error trap at the bottom will work
  503.             $response="BAD";
  504.             $message='IMAP server does not appear to support the authentication method selected.';
  505.             $message .= '  Please contact your system administrator.';
  506.         }
  507.     elseif ($imap_auth_mech == 'login'{
  508.         // this is a workaround to alert users of LOGINDISABLED, which is done "right" in
  509.         // devel but requires functions not available in stable. RFC requires us to
  510.         // not send LOGIN when LOGINDISABLED is advertised.
  511.         if(stristr($server_info'LOGINDISABLED')) {
  512.             $response 'BAD';
  513.             $message _("The IMAP server is reporting that plain text logins are disabled.").' '.
  514.                 _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.").' ';
  515.             if (!$use_imap_tls{
  516.                 $message .= _("Also, the use of TLS may allow SquirrelMail to login.").' ';
  517.             }
  518.             $message .= _("Please contact your system administrator and report this error.");
  519.         else {
  520.             // Original IMAP login code
  521.             $query 'LOGIN';
  522.             if(sq_is8bit($username)) {
  523.                 $query .= ' {' strlen($username"}\r\n$username";
  524.             else {
  525.                 $query .= ' "' quoteimap($username'"';
  526.             }
  527.             if(sq_is8bit($password)) {
  528.                 $query .= ' {' strlen($password"}\r\n$password";
  529.             else {
  530.                 $query .= ' "' quoteimap($password'"';
  531.             }
  532.             $read sqimap_run_command ($imap_stream$queryfalse$response$message);
  533.         }
  534.     elseif ($imap_auth_mech == 'plain'{
  535.         /* Replace this with SASL PLAIN if it ever gets implemented */
  536.         $response="BAD";
  537.         $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
  538.     else {
  539.         $response="BAD";
  540.         $message="Internal SquirrelMail error - unknown IMAP authentication method chosen.  Please contact the developers.";
  541.     }
  542.  
  543.     /* If the connection was not successful, lets see why */
  544.     if ($response != 'OK'{
  545.         if (!$hide{
  546.             if ($response != 'NO'{
  547.                 /* "BAD" and anything else gets reported here. */
  548.                 $message htmlspecialchars($message);
  549.                 set_up_language($squirrelmail_languagetrue);
  550.                 require_once(SM_PATH 'functions/display_messages.php');
  551.                 if ($response == 'BAD'{
  552.                     $string sprintf (_("Bad request: %s")."<br />\r\n"$message);
  553.                 else {
  554.                     $string sprintf (_("Unknown error: %s""<br />\n"$message);
  555.                 }
  556.                 if (isset($read&& is_array($read)) {
  557.                     $string .= '<br />' _("Read data:""<br />\n";
  558.                     foreach ($read as $line{
  559.                         $string .= htmlspecialchars($line"<br />\n";
  560.                     }
  561.                 }
  562.                 error_box($string,$color);
  563.                 exit;
  564.             else {
  565.                 /*
  566.                  * If the user does not log in with the correct
  567.                  * username and password it is not possible to get the
  568.                  * correct locale from the user's preferences.
  569.                  * Therefore, apply the same hack as on the login
  570.                  * screen.
  571.                  *
  572.                  * $squirrelmail_language is set by a cookie when
  573.                  * the user selects language and logs out
  574.                  */
  575.  
  576.                 set_up_language($squirrelmail_languagetrue);
  577.                 include_once(SM_PATH 'functions/display_messages.php' );
  578.                 sqsession_destroy();
  579.                 /* terminate the session nicely */
  580.                 sqimap_logout($imap_stream);
  581.                 logout_error_("Unknown user or password incorrect.") );
  582.                 exit;
  583.             }
  584.         else {
  585.             exit;
  586.         }
  587.     }
  588.     return $imap_stream;
  589. }
  590.  
  591. /**
  592.  * Simply logs out the IMAP session
  593.  * @param stream imap_stream the IMAP connection to log out.
  594.  * @return void 
  595.  */
  596. function sqimap_logout ($imap_stream{
  597.     /* Logout is not valid until the server returns 'BYE'
  598.      * If we don't have an imap_stream we're already logged out */
  599.     if(isset($imap_stream&& $imap_stream)
  600.         sqimap_run_command($imap_stream'LOGOUT'false$response$message);
  601. }
  602.  
  603. /**
  604.  * Retreive the CAPABILITY string from the IMAP server.
  605.  * If capability is set, returns only that specific capability,
  606.  * else returns array of all capabilities.
  607.  */
  608. function sqimap_capability($imap_stream$capability=''{
  609.     global $sqimap_capabilities;
  610.     if (!is_array($sqimap_capabilities)) {
  611.         $read sqimap_run_command($imap_stream'CAPABILITY'true$a$b);
  612.  
  613.         $c explode(' '$read[0]);
  614.         for ($i=2$i count($c)$i++{
  615.             $cap_list explode('='$c[$i]);
  616.             if (isset($cap_list[1])) {
  617.                 // FIX ME. capabilities can occure multiple times.
  618.                 // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
  619.                 $sqimap_capabilities[$cap_list[0]] $cap_list[1];
  620.             else {
  621.                 $sqimap_capabilities[$cap_list[0]] TRUE;
  622.             }
  623.         }
  624.     }
  625.     if ($capability{
  626.         if (isset($sqimap_capabilities[$capability])) {
  627.                 return $sqimap_capabilities[$capability];
  628.         else {
  629.                 return false;
  630.         }
  631.     }
  632.     return $sqimap_capabilities;
  633. }
  634.  
  635. /**
  636.  * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
  637.  */
  638. function sqimap_get_delimiter ($imap_stream false{
  639.     global $sqimap_delimiter$optional_delimiter;
  640.  
  641.     /* Use configured delimiter if set */
  642.     if((!empty($optional_delimiter)) && $optional_delimiter != 'detect'{
  643.         return $optional_delimiter;
  644.     }
  645.  
  646.     /* Do some caching here */
  647.     if (!$sqimap_delimiter{
  648.         if (sqimap_capability($imap_stream'NAMESPACE')) {
  649.             /*
  650.              * According to something that I can't find, this is supposed to work on all systems
  651.              * OS: This won't work in Courier IMAP.
  652.              * OS: According to rfc2342 response from NAMESPACE command is:
  653.              * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  654.              * OS: We want to lookup all personal NAMESPACES...
  655.              */
  656.             $read sqimap_run_command($imap_stream'NAMESPACE'true$a$b);
  657.             if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)'$read[0]$data)) {
  658.                 if (eregi('^\\( *\\((.*)\\) *\\)'$data[1]$data2)) {
  659.                     $pn $data2[1];
  660.                 }
  661.                 $pna explode(')('$pn);
  662.                 while (list($k$veach($pna)) {
  663.                     $lst explode('"'$v);
  664.                     if (isset($lst[3])) {
  665.                         $pn[$lst[1]] $lst[3];
  666.                     else {
  667.                         $pn[$lst[1]] '';
  668.                     }
  669.                 }
  670.             }
  671.             $sqimap_delimiter $pn[0];
  672.         else {
  673.             fputs ($imap_stream". LIST \"INBOX\" \"\"\r\n");
  674.             $read sqimap_read_data($imap_stream'.'true$a$b);
  675.             $quote_position strpos ($read[0]'"');
  676.             $sqimap_delimiter substr ($read[0]$quote_position+11);
  677.         }
  678.     }
  679.     return $sqimap_delimiter;
  680. }
  681.  
  682.  
  683. /**
  684.  * Gets the number of messages in the current mailbox.
  685.  */
  686. function sqimap_get_num_messages ($imap_stream$mailbox{
  687.     $read_ary sqimap_run_command ($imap_stream"EXAMINE \"$mailbox\""false$result$message);
  688.     for ($i 0$i count($read_ary)$i++{
  689.         if (ereg("[^ ]+ +([^ ]+) +EXISTS"$read_ary[$i]$regs)) {
  690.             return $regs[1];
  691.         }
  692.     }
  693.     return false//"BUG! Couldn't get number of messages in $mailbox!";
  694. }
  695.  
  696. function parseAddress($address$max=0{
  697.     $aTokens array();
  698.     $aAddress array();
  699.     $iCnt strlen($address);
  700.     $aSpecials array('(' ,'<' ,',' ,';' ,':');
  701.     $aReplace =  array(' (',' <',' ,',' ;',' :');
  702.     $address str_replace($aSpecials,$aReplace,$address);
  703.     $i 0;
  704.     while ($i $iCnt{
  705.         $cChar $address{$i};
  706.         switch($cChar)
  707.         {
  708.         case '<':
  709.             $iEnd strpos($address,'>',$i+1);
  710.             if (!$iEnd{
  711.                $sToken substr($address,$i);
  712.                $i $iCnt;
  713.             else {
  714.                $sToken substr($address,$i,$iEnd $i +1);
  715.                $i $iEnd;
  716.             }
  717.             $sToken str_replace($aReplace$aSpecials,$sToken);
  718.             $aTokens[$sToken;
  719.             break;
  720.         case '"':
  721.             $iEnd strpos($address,$cChar,$i+1);
  722.             if ($iEnd{
  723.                 // skip escaped quotes
  724.                 $prev_char $address{$iEnd-1};
  725.                 while ($prev_char === '\\' && substr($address,$iEnd-2,2!== '\\\\'{
  726.                     $iEnd strpos($address,$cChar,$iEnd+1);
  727.                     if ($iEnd{
  728.                         $prev_char $address{$iEnd-1};
  729.                     else {
  730.                         $prev_char false;
  731.                     }
  732.                 }
  733.             }
  734.             if (!$iEnd{
  735.                 $sToken substr($address,$i);
  736.                 $i $iCnt;
  737.             else {
  738.                 // also remove the surrounding quotes
  739.                 $sToken substr($address,$i+1,$iEnd $i -1);
  740.                 $i $iEnd;
  741.             }
  742.             $sToken str_replace($aReplace$aSpecials,$sToken);
  743.             if ($sToken$aTokens[$sToken;
  744.             break;
  745.         case '(':
  746.             $iEnd strrpos($address,')');
  747.             if (!$iEnd || $iEnd $i{
  748.                 $sToken substr($address,$i);
  749.                 $i $iCnt;
  750.             else {
  751.                 $sToken substr($address,$i,$iEnd $i 1);
  752.                 $i $iEnd;
  753.             }
  754.             $sToken str_replace($aReplace$aSpecials,$sToken);
  755.             $aTokens[$sToken;
  756.             break;
  757.         case ',':
  758.         case ';':
  759.         case ';':
  760.         case ' ':
  761.             $aTokens[$cChar;
  762.             break;
  763.         default:
  764.             $iEnd strpos($address,' ',$i+1);
  765.             if ($iEnd{
  766.                 $sToken trim(substr($address,$i,$iEnd $i));
  767.                 $i $iEnd-1;
  768.             else {
  769.                 $sToken trim(substr($address,$i));
  770.                 $i $iCnt;
  771.             }
  772.             if ($sToken$aTokens[$sToken;
  773.         }
  774.         ++$i;
  775.     }
  776.     $sPersonal $sEmail $sComment $sGroup '';
  777.     $aStack $aComment array();
  778.     foreach ($aTokens as $sToken{
  779.         if ($max && $max == count($aAddress)) {
  780.             return $aAddress;
  781.         }
  782.         $cChar $sToken{0};
  783.         switch ($cChar)
  784.         {
  785.           case '=':
  786.           case '"':
  787.           case ' ':
  788.             $aStack[$sToken;
  789.             break;
  790.           case '(':
  791.             $aComment[substr($sToken,1,-1);
  792.             break;
  793.           case ';':
  794.             if ($sGroup{
  795.                 $sEmail trim(implode(' ',$aStack));
  796.                 $aAddress[array($sGroup,$sEmail);
  797.                 $aStack $aComment array();
  798.                 $sGroup '';
  799.                 break;
  800.             }
  801.           case ',':
  802.             if (!$sEmail{
  803.                 while (count($aStack&& !$sEmail{
  804.                     $sEmail trim(array_pop($aStack));
  805.                 }
  806.             }
  807.             if (count($aStack)) {
  808.                 $sPersonal trim(implode('',$aStack));
  809.             else {
  810.                 $sPersonal '';
  811.             }
  812.             if (!$sPersonal && count($aComment)) {
  813.                 $sComment implode(' ',$aComment);
  814.                 $sPersonal .= $sComment;
  815.             }
  816.             $aAddress[array($sEmail,$sPersonal);
  817.             $sPersonal $sComment $sEmail '';
  818.             $aStack $aComment array();
  819.             break;
  820.           case ':':
  821.             $sGroup implode(' ',$aStack)break;
  822.             $aStack array();
  823.             break;
  824.           case '<':
  825.             $sEmail trim(substr($sToken,1,-1));
  826.             break;
  827.           case '>':
  828.             /* skip */
  829.             break;
  830.           default$aStack[$sTokenbreak;
  831.         }
  832.     }
  833.     /* now do the action again for the last address */
  834.     if (!$sEmail{
  835.         while (count($aStack&& !$sEmail{
  836.             $sEmail trim(array_pop($aStack));
  837.         }
  838.     }
  839.     if (count($aStack)) {
  840.         $sPersonal trim(implode('',$aStack));
  841.     else {
  842.         $sPersonal '';
  843.     }
  844.     if (!$sPersonal && count($aComment)) {
  845.         $sComment implode(' ',$aComment);
  846.         $sPersonal .= $sComment;
  847.     }
  848.     $aAddress[array($sEmail,$sPersonal);
  849.     return $aAddress;
  850. }
  851.  
  852.  
  853. /**
  854.  * Returns the number of unseen messages in this folder.
  855.  */
  856. function sqimap_unseen_messages ($imap_stream$mailbox{
  857.     $read_ary sqimap_run_command ($imap_stream"STATUS \"$mailbox\" (UNSEEN)"false$result$message);
  858.     $i 0;
  859.     $regs array(falsefalse);
  860.     while (isset($read_ary[$i])) {
  861.         if (ereg("UNSEEN ([0-9]+)"$read_ary[$i]$regs)) {
  862.             break;
  863.         }
  864.         $i++;
  865.     }
  866.     return $regs[1];
  867. }
  868.  
  869. /**
  870.  * Returns the number of unseen/total messages in this folder
  871.  */
  872. function sqimap_status_messages ($imap_stream$mailbox{
  873.     $read_ary sqimap_run_command ($imap_stream"STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)"false$result$message);
  874.     $i 0;
  875.     $messages $unseen $recent false;
  876.     $regs array(false,false);
  877.     while (isset($read_ary[$i])) {
  878.         if (preg_match('/UNSEEN\s+([0-9]+)/i'$read_ary[$i]$regs)) {
  879.             $unseen $regs[1];
  880.         }
  881.         if (preg_match('/MESSAGES\s+([0-9]+)/i'$read_ary[$i]$regs)) {
  882.             $messages $regs[1];
  883.         }
  884.         if (preg_match('/RECENT\s+([0-9]+)/i'$read_ary[$i]$regs)) {
  885.             $recent $regs[1];
  886.         }
  887.         $i++;
  888.     }
  889.     return array('MESSAGES' => $messages'UNSEEN'=>$unseen'RECENT' => $recent);
  890. }
  891.  
  892.  
  893. /**
  894.  * Saves a message to a given folder -- used for saving sent messages
  895.  */
  896. function sqimap_append ($imap_stream$sent_folder$length{
  897.     fputs ($imap_streamsqimap_session_id(" APPEND \"$sent_folder\" (\\Seen{".$length."}\r\n");
  898.     $tmp fgets ($imap_stream1024);
  899.     sqimap_append_checkresponse($tmp$sent_folder);
  900. }
  901.  
  902. function sqimap_append_done ($imap_stream$folder=''{
  903.     fputs ($imap_stream"\r\n");
  904.     $tmp fgets ($imap_stream1024);
  905.     sqimap_append_checkresponse($tmp$folder);
  906. }
  907.  
  908. function sqimap_append_checkresponse($response$folder{
  909.  
  910.     if (preg_match("/(.*)(BAD|NO)(.*)$/"$response$regs)) {
  911.         global $squirrelmail_language$color;
  912.         set_up_language($squirrelmail_language);
  913.         require_once(SM_PATH 'functions/display_messages.php');
  914.  
  915.         $reason $regs[3];
  916.         if ($regs[2== 'NO'{
  917.            $string "<b><font color=\"$color[2]\">\n.
  918.                   _("ERROR: Could not append message to"." $folder..
  919.                   "</b><br />\n" .
  920.                   _("Server responded:"' ' .
  921.                   $reason "<br />\n";
  922.            if (preg_match("/(.*)(quota)(.*)$/i"$reason$regs)) {
  923.               $string .= _("Solution:"' ' .
  924.             _("Remove unneccessary messages from your folders. Start with your Trash folder.")
  925.               ."<br />\n";
  926.            }
  927.            $string .= "</font>\n";
  928.            error_box($string,$color);
  929.         else {
  930.            $string "<b><font color=\"$color[2]\">\n.
  931.                   _("ERROR: Bad or malformed request.".
  932.                   "</b><br />\n" .
  933.                   _("Server responded:"' ' .
  934.                   $reason "</font><br />\n";
  935.            error_box($string,$color);
  936.            exit;
  937.         }
  938.     }
  939. }
  940.  
  941. function sqimap_get_user_server ($imap_server$username{
  942.    if (substr($imap_server04!= "map:"{
  943.        return $imap_server;
  944.    }
  945.    $function substr($imap_server4);
  946.    return $function($username);
  947. }
  948.  
  949. /**
  950.  * This is an example that gets IMAP servers from yellowpages (NIS).
  951.  * you can simple put map:map_yp_alias in your $imap_server_address
  952.  * in config.php use your own function instead map_yp_alias to map your
  953.  * LDAP whatever way to find the users IMAP server.
  954.  */
  955. function map_yp_alias($username{
  956.    $yp = `ypmatch $username aliases`;
  957.    return chop(substr($ypstrlen($username)+1));
  958. }
  959.  
  960. ?>

Documentation generated on Sat, 07 Oct 2006 16:31:39 +0300 by phpDocumentor 1.3.0RC6