rewrite of sqimap_read_data_list() see this for more info:
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This implements all functions that do general imap functions.
10 *
11 * $Id$
12 */
13
14 require_once('../functions/page_header.php');
15
16 global $sqimap_session_id;
17 $sqimap_session_id = 1;
18
19 /* Sets an unique session id in order to avoid simultanous sessions crash. */
20 function sqimap_session_id($unique_id = false) {
21 global $data_dir, $username, $sqimap_session_id;
22 if (!$unique_id) {
23 return( sprintf("A%03d", $sqimap_session_id++) );
24 } else {
25 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
26 }
27 }
28
29 /*
30 * Both send a command and accept the result from the command.
31 * This is to allow proper session number handling.
32 */
33 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
34 $sid = sqimap_session_id($unique_id);
35 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
36 $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
37 return $read;
38 }
39
40 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
41 $sid = sqimap_session_id($unique_id);
42 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
43 $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
44 return $read;
45 }
46
47
48 /*
49 * custom fgets function. gets a line from IMAP
50 * no matter how big it may be
51 */
52
53 function sqimap_fgets($imap_stream) {
54 $read = '';
55 $buffer = 4096;
56 $results = '';
57 while (strpos($read, "\n") === false) {
58 if (!($read = fgets($imap_stream, $buffer))) {
59 break;
60 }
61 $results .= $read;
62 }
63 return $results;
64 }
65
66 /*
67 * Reads the output from the IMAP stream. If handle_errors is set to true,
68 * this will also handle all errors that are received. If it is not set,
69 * the errors will be sent back through $response and $message
70 */
71
72 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
73 global $color, $squirrelmail_language;
74 $read = '';
75 $pre_a = explode(' ',trim($pre));
76 $pre = $pre_a[0];
77 $resultlist = array();
78 $data = array();
79 $read = sqimap_fgets($imap_stream);
80 while (1) {
81 switch (true) {
82 case preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs):
83 case preg_match('/^\* (BYE \[ALERT\])(.*)$/', $read, $regs):
84 $response = $regs[1];
85 $message = trim($regs[2]);
86 break 2;
87 case preg_match("/^\* (OK \[PARSE\])(.*)$/", $read):
88 $read = sqimap_fgets($imap_stream);
89 break 1;
90 case preg_match('/^\* [0-9]+ FETCH.*/', $read):
91 $fetch_data = array();
92 $fetch_data[] = $read;
93 $read = sqimap_fgets($imap_stream);
94 while (!preg_match('/^\* [0-9]+ FETCH.*/', $read) &&
95 !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read)) {
96 $fetch_data[] = $read;
97 $read = sqimap_fgets($imap_stream);
98 }
99 $resultlist[] = $fetch_data;
100 break 1;
101 default:
102 $data[] = $read;
103 $read = sqimap_fgets($imap_stream);
104 break 1;
105 }
106 }
107 if (!empty($data)) {
108 $resultlist[] = $data;
109 }
110 elseif (empty($resultlist)) {
111 $resultlist[] = array();
112 }
113 if ($handle_errors == false) {
114 return( $resultlist );
115 }
116 elseif ($response == 'NO') {
117 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
118 if (strstr($message, 'command resulted in') === false) {
119 set_up_language($squirrelmail_language);
120 echo "<br><b><font color=$color[2]>\n" .
121 _("ERROR : Could not complete request.") .
122 "</b><br>\n" .
123 _("Query:") .
124 $query . '<br>' .
125 _("Reason Given: ") .
126 $message . "</font><br>\n";
127 exit;
128 }
129 }
130 elseif ($response == 'BAD') {
131 set_up_language($squirrelmail_language);
132 echo "<br><b><font color=$color[2]>\n" .
133 _("ERROR : Bad or malformed request.") .
134 "</b><br>\n" .
135 _("Query:") .
136 $query . '<br>' .
137 _("Server responded: ") .
138 $message . "</font><br>\n";
139 exit;
140 }
141 else {
142 return $resultlist;
143 }
144 }
145
146 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
147 $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
148 return $res[0];
149 }
150
151 /*
152 * Logs the user into the imap server. If $hide is set, no error messages
153 * will be displayed. This function returns the imap connection handle.
154 */
155 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
156 global $color, $squirrelmail_language, $HTTP_ACCEPT_LANGUAGE, $onetimepad;
157
158 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
159 if ( !$imap_stream ) {
160 return false;
161 }
162 $server_info = fgets ($imap_stream, 1024);
163
164 /* Decrypt the password */
165 $password = OneTimePadDecrypt($password, $onetimepad);
166
167 /* Do some error correction */
168 if (!$imap_stream) {
169 if (!$hide) {
170 set_up_language($squirrelmail_language, true);
171 printf (_("Error connecting to IMAP server: %s.")."<br>\r\n", $imap_server_address);
172 echo "$error_number : $error_string<br>\r\n";
173 }
174 exit;
175 }
176
177 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
178 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
179
180 /* If the connection was not successful, lets see why */
181 if ($response != 'OK') {
182 if (!$hide) {
183 if ($response != 'NO') {
184 /* "BAD" and anything else gets reported here. */
185 set_up_language($squirrelmail_language, true);
186 if ($response == 'BAD') {
187 printf (_("Bad request: %s")."<br>\r\n", $message);
188 } else {
189 printf (_("Unknown error: %s") . "<br>\n", $message);
190 }
191 echo '<br>' . _("Read data:") . "<br>\n";
192 if (is_array($read)) {
193 foreach ($read as $line) {
194 echo htmlspecialchars($line) . "<br>\n";
195 }
196 }
197 exit;
198 } else {
199 /*
200 * If the user does not log in with the correct
201 * username and password it is not possible to get the
202 * correct locale from the user's preferences.
203 * Therefore, apply the same hack as on the login
204 * screen.
205 *
206 * $squirrelmail_language is set by a cookie when
207 * the user selects language and logs out
208 */
209
210 set_up_language($squirrelmail_language, true);
211 include_once( '../functions/display_messages.php' );
212 logout_error( _("Unknown user or password incorrect.") );
213 session_destroy();
214 exit;
215 }
216 } else {
217 exit;
218 }
219 }
220 return $imap_stream;
221 }
222
223 /* Simply logs out the IMAP session */
224 function sqimap_logout ($imap_stream) {
225 /* Logout is not valid until the server returns 'BYE' */
226 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
227 }
228
229 function sqimap_capability($imap_stream, $capability='') {
230 global $sqimap_capabilities;
231 if (!is_array($sqimap_capabilities)) {
232 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
233
234 $c = explode(' ', $read[0]);
235 for ($i=2; $i < count($c); $i++) {
236 $cap_list = explode('=', $c[$i]);
237 if (isset($cap_list[1])) {
238 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
239 } else {
240 $sqimap_capabilities[$cap_list[0]] = TRUE;
241 }
242 }
243 }
244 if ($capability) {
245 if (isset($sqimap_capabilities[$capability])) {
246 return $sqimap_capabilities[$capability];
247 } else {
248 return false;
249 }
250 }
251 return $sqimap_capabilities;
252 }
253
254 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
255 function sqimap_get_delimiter ($imap_stream = false) {
256 global $sqimap_delimiter, $optional_delimiter;
257
258 /* Use configured delimiter if set */
259 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
260 return $optional_delimiter;
261 }
262
263 /* Do some caching here */
264 if (!$sqimap_delimiter) {
265 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
266 /*
267 * According to something that I can't find, this is supposed to work on all systems
268 * OS: This won't work in Courier IMAP.
269 * OS: According to rfc2342 response from NAMESPACE command is:
270 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
271 * OS: We want to lookup all personal NAMESPACES...
272 */
273 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
274 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
275 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
276 $pn = $data2[1];
277 }
278 $pna = explode(')(', $pn);
279 while (list($k, $v) = each($pna)) {
280 $lst = explode('"', $v);
281 if (isset($lst[3])) {
282 $pn[$lst[1]] = $lst[3];
283 } else {
284 $pn[$lst[1]] = '';
285 }
286 }
287 }
288 $sqimap_delimiter = $pn[0];
289 } else {
290 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
291 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
292 $quote_position = strpos ($read[0], '"');
293 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
294 }
295 }
296 return $sqimap_delimiter;
297 }
298
299
300 /* Gets the number of messages in the current mailbox. */
301 function sqimap_get_num_messages ($imap_stream, $mailbox) {
302 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", true, $result, $message);
303 for ($i = 0; $i < count($read_ary); $i++) {
304 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
305 return $regs[1];
306 }
307 }
308 return "BUG! Couldn't get number of messages in $mailbox!";
309 }
310
311
312 /* Returns a displayable email address.
313 * Luke Ehresman <lehresma@css.tayloru.edu>
314 * "Luke Ehresman" <lehresma@css.tayloru.edu>
315 * <lehresma@css.tayloru.edu>
316 * lehresma@css.tayloru.edu (Luke Ehresman)
317 * lehresma@css.tayloru.edu
318 * becomes: lehresma@css.tayloru.edu
319 */
320 function sqimap_find_email ($string) {
321 if (ereg("<([^>]+)>", $string, $regs)) {
322 $string = $regs[1];
323 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
324 $string = $regs[1];
325 }
326 return trim($string);
327 }
328
329
330 /*
331 * Takes the From: field and creates a displayable name.
332 * Luke Ehresman <lkehresman@yahoo.com>
333 * "Luke Ehresman" <lkehresman@yahoo.com>
334 * lkehresman@yahoo.com (Luke Ehresman)
335 * becomes: Luke Ehresman
336 * <lkehresman@yahoo.com>
337 * becomes: lkehresman@yahoo.com
338 */
339 function sqimap_find_displayable_name ($string) {
340 $string = trim($string);
341
342 if ( ereg('^(.+)<.*>', $string, $regs) ) {
343 $orig_string = $string;
344 $string = str_replace ('"', '', $regs[1] );
345 if (trim($string) == '') {
346 $string = sqimap_find_email($orig_string);
347 }
348 if( $string == '' || $string == ' ' ){
349 $string = '&nbsp';
350 }
351 }
352 elseif ( ereg('\((.*)\)', $string, $regs) ) {
353 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
354 if ( ereg('^(.+) \(', $string, $regs) ) {
355 $string = ereg_replace( ' \(\)$', '', $string );
356 } else {
357 $string = '&nbsp';
358 }
359 } else {
360 $string = $regs[1];
361 }
362 }
363 else {
364 $string = str_replace ('"', '', sqimap_find_email($string));
365 }
366
367 return trim($string);
368 }
369
370 /*
371 * Returns the number of unseen messages in this folder
372 */
373 function sqimap_unseen_messages ($imap_stream, $mailbox) {
374 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", true, $result, $message);
375 $i = 0;
376 while (isset($read_ary[$i])) {
377 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
378 break;
379 }
380 $i++;
381 }
382 return $regs[1];
383 }
384
385
386 /*
387 * Saves a message to a given folder -- used for saving sent messages
388 */
389 function sqimap_append ($imap_stream, $sent_folder, $length) {
390 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
391 $tmp = fgets ($imap_stream, 1024);
392 }
393
394 function sqimap_append_done ($imap_stream) {
395 fputs ($imap_stream, "\r\n");
396 $tmp = fgets ($imap_stream, 1024);
397 }
398
399 ?>