PageRenderTime 145ms CodeModel.GetById 30ms app.highlight 13ms RepoModel.GetById 97ms app.codeStats 0ms

/public_html/lists/admin/readtestmail.php

https://github.com/samtuke/phplist
PHP | 339 lines | 256 code | 31 blank | 52 comment | 38 complexity | 2285cfae24cef9a7f57911b891a8d68b MD5 | raw file
  1<?php
  2require_once dirname(__FILE__) . '/accesscheck.php';
  3
  4########################################################################
  5# Reads mail from a test account that will recieve all sent mail. 
  6# Use developer_email to send all mail to one account.
  7# Use test_email settings to pop this box.
  8# This file shows the links from the first email foun d for a selected user.
  9# The links can be use to for instance confirm the user in an automated test.
 10#
 11# 2007 Bas Ovink - tincan ltd
 12########################################################################
 13
 14//CREATE TABLE `dev-phplist`.`phplist_testemail` (
 15//`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
 16//`date` datetime default NULL ,
 17//`header` text,
 18//`data` blob,
 19//`status` varchar( 255 ) default NULL ,
 20//`comment` text,
 21//PRIMARY KEY ( `id` ) ,
 22//KEY `dateindex` ( `date` )
 23//) ENGINE = MYISAM DEFAULT CHARSET = latin1 AUTO_INCREMENT =34;
 24
 25if (!$GLOBALS["commandline"]) {
 26  ob_end_flush();
 27  if (!MANUALLY_PROCESS_testS) {
 28    print $GLOBALS['I18N']->get("This page can only be called from the commandline");
 29    return;
 30  }
 31} else {
 32  ob_end_clean();
 33  print ClineSignature();
 34  ob_start();
 35}
 36
 37function prepareOutput() {
 38  global $outputdone;
 39  if (!$outputdone) {
 40    $outputdone= 1;
 41    return formStart('name="outputform" class="readtestmailOutput" ') . '<textarea name="output" rows=10 cols=70></textarea></form>';
 42  }
 43}
 44
 45$report= "";
 46## some general functions
 47function finish($flag, $message) {
 48  if ($flag == "error") {
 49    $subject= $GLOBALS['I18N']->get("test processing error");
 50  }
 51  elseif ($flag == "info") {
 52    $subject= $GLOBALS['I18N']->get("test Processing info");
 53  }
 54  if (!TEST && $message)
 55    sendReport($subject, $message);
 56
 57  # try..catch
 58  global $link;
 59  imap_close($link);
 60}
 61
 62function ProcessError($message) {
 63  output("$message");
 64  finish('error', $message);
 65  exit;
 66}
 67
 68function processTestEmails_shutdown() {
 69  global $report, $process_id;
 70  releaseLock($process_id);
 71  # $report .= "Connection status:".connection_status();
 72  finish('info', $report);
 73  if (!$GLOBALS["commandline"]) {
 74    include_once dirname(__FILE__) . '/footer.inc';
 75  }
 76}
 77
 78function output($message, $reset= 0) {
 79  $infostring= "[" . date("D j M Y H:i", time()) . "] [" . getenv("REMOTE_HOST") . "] [" . getenv("REMOTE_ADDR") . "]";
 80  #print "$infostring $message<br/>\n";
 81  $message= preg_replace("/\n/", '', $message);
 82  ## contribution from http://forums.phplist.com/viewtopic.php?p=14648
 83  ## in languages with accented characters replace the HTML back
 84  //Replace the "&rsquo;" which is not replaced by html_decode
 85  $message= preg_replace("/&rsquo;/", "'", $message);
 86  //Decode HTML chars
 87  #$message = html_entity_decode($message,ENT_QUOTES,$_SESSION['adminlanguage']['charset']);
 88  $message= html_entity_decode($message, ENT_QUOTES, 'UTF-8');
 89  if ($GLOBALS["commandline"]) {
 90    ob_end_clean();
 91    print strip_tags($message) . "\n";
 92    ob_start();
 93  } else {
 94    if ($reset)
 95      print '<script language="Javascript" type="text/javascript">
 96                                                                  //        if (document.forms[0].name == "outputform") {
 97                                                                            document.outputform.output.value = "";
 98                                                                            document.outputform.output.value += "\n";
 99                                                                  //        }
100                                                                        </script>' . "\n";
101
102    print '<script language="Javascript" type="text/javascript">
103                                            //      if (document.forms[0].name == "outputform") {
104                                                    document.outputform.output.value += "' . $message . '";
105                                                    document.outputform.output.value += "\n";
106                                            //      } else
107                                            //        document.writeln("' . $message . '");
108                                                </script>' . "\n";
109  }
110
111  flush();
112}
113
114//function processTestEmail($link, $mailIndex, $header) {
115//  global $tables;
116//  $headerinfo= imap_headerinfo($link, $mailIndex);
117//  $header= imap_fetchheader($link, $mailIndex);
118//
119//  $body= imap_body($link, $mailIndex);
120//  $msgid= 0;
121//  $user= 0;
122//  preg_match("/X-MessageId: (.*)/i", $header, $match);
123//  if (is_array($match) && isset ($match[1]))
124//    $msgid= trim($match[1]);
125//  if (!$msgid) {
126//    # older versions use X-Message
127//    preg_match("/X-Message: (.*)/i", $header, $match);
128//    if (is_array($match) && isset ($match[1]))
129//      $msgid= trim($match[1]);
130//  }
131//
132//  preg_match("/X-ListMember: (.*)/i", $header, $match);
133//  if (is_array($match) && isset ($match[1]))
134//    $user= trim($match[1]);
135//  if (!$user) {
136//    # older version use X-User
137//    preg_match("/X-User: (.*)/i", $header, $match);
138//    if (is_array($match) && isset ($match[1]))
139//      $user= trim($match[1]);
140//  }
141//  # some versions used the email to identify the users, some the userid and others the uniqid
142//  # use backward compatible way to find user
143//  if (preg_match("/.*@.*/i", $user, $match)) {
144//    $userid_req= Sql_Fetch_Row_Query("select id from {$tables["user"]} where email = \"$user\"");
145//    if (VERBOSE)
146//      output("UID" .
147//      $userid_req[0] . " MSGID" . $msgid);
148//    $userid= $userid_req[0];
149//  }
150//  elseif (preg_match("/^\d$/", $user)) {
151//    $userid= $user;
152//    if (VERBOSE)
153//      output("UID" . $userid . " MSGID" . $msgid);
154//  }
155//  elseif ($user) {
156//    $userid_req= Sql_Fetch_Row_Query("select id from {$tables["user"]} where uniqid = \"$user\"");
157//    if (VERBOSE)
158//      output("UID" . $userid_req[0] . " MSGID" . $msgid);
159//    $userid= $userid_req[0];
160//  } else {
161//    $userid= '';
162//  }
163//  //  Sql_Query(sprintf('insert into %s (date,header,data)
164//  //      values("%s","%s","%s")', 'phplist_testemail', date("Y-m-d H:i", @ strtotime($headerinfo->date)), addslashes($header), addslashes($body)));
165//  //  $testid= Sql_Insert_id();
166//  //  if ($userid) {
167//  //    Sql_Query(sprintf('update %s
168//  //          set status = "test system message",
169//  //          comment = "userid %s"
170//  //          where id = %d', 'phplist_testemail', $userid, $testid));
171//  //  } else {
172//  //    Sql_Query(sprintf('update %s
173//  //          set status = "unidentified test",
174//  //          comment = "not processed"
175//  //          where id = %d', 'phplist_testemail', $testid));
176//  //    return false;
177//  //  }
178//  dbg($userid, '$userid');
179//  return true;
180//}
181
182function openPop($server, $user, $password) {
183  $port= $GLOBALS["test_mailbox_port"];
184  if (!$port) {
185    $port= '110/pop3/notls';
186  }
187  set_time_limit(6000);
188
189  if (!TEST) {
190    $link= imap_open("{" . $server . ":" . $port . "}INBOX", $user, $password, CL_EXPUNGE);
191  } else {
192    $link= imap_open("{" . $server . ":" . $port . "}INBOX", $user, $password);
193  }
194
195  if (!$link) {
196    output($GLOBALS['I18N']->get("Cannot create POP3 connection to") . " $server: " . imap_last_error());
197    return null;
198  }
199  return $link;
200}
201
202function openMbox($file) {
203  set_time_limit(6000);
204
205  if (!TEST) {
206    $link= imap_open($file, "", "", CL_EXPUNGE);
207  } else {
208    $link= imap_open($file, "", "");
209  }
210  if (!$link) {
211    output($GLOBALS['I18N']->get("Cannot open mailbox file") . " " . imap_last_error());
212    return null;
213  }
214  return $link;
215}
216
217function findEmailForUser($link, $mailToFind, $max= 3000) {
218  global $test_mailbox_purge_unprocessed, $test_mailbox_purge;
219  output(sprintf('Looking for emails to %s', $mailToFind));
220
221  $num= imap_num_msg($link);
222  output($num . " " . $GLOBALS['I18N']->get("mails in mailbox") . "\n");
223  output($GLOBALS['I18N']->get("Please do not interrupt this process") . "\n");
224  if ($num > $max) {
225    print $GLOBALS['I18N']->get("Processing first") . " $max " . $GLOBALS['I18N']->get("tests") . "<br/>";
226    $num= $max;
227  }
228
229  $nberror= 0;
230  $found= false;
231  $mailIndex= 0;
232  while (!$found && $mailIndex++ <= $num) { //for ($x= 1; $x <= $num; $x++)
233    set_time_limit(60);
234    $header= imap_fetchheader($link, $mailIndex);
235    preg_match("/X-ListMember: (.*)/i", $header, $match);
236    
237    if (is_array($match) && isset ($match[1]) ) {
238      $match[1] = trim($match[1]);
239      $found= $mailToFind == $match[1];
240      if (!$found) {
241        printf('<a href="?page=readtestmail&amp;email=%s">Get (& delete) %s</a><br />', $match[1], $match[1]);
242      }
243    }
244    
245    if ($found) {
246      output('Message found');
247      if (!TEST && $test_mailbox_purge) {
248        output($GLOBALS['I18N']->get("Deleting message") . " $mailIndex");
249        imap_delete($link, $mailIndex);
250      }
251    } else {
252      if (!TEST && $test_mailbox_purge_unprocessed) {
253        output($GLOBALS['I18N']->get("Deleting message") . " $mailIndex");
254        imap_delete($link, $mailIndex);
255      }
256    }
257    flush();
258  }
259  flush();
260  output($GLOBALS['I18N']->get("Closing mailbox, and purging messages"));
261  if ($found) {
262    return $num;
263  } else {
264    return null;
265  }
266}
267
268#############################################
269# main
270function main() {
271};
272
273if (!function_exists('imap_open')) {
274  Error($GLOBALS['I18N']->get('IMAP is not included in your PHP installation, cannot continue') .
275  '<br/>' . $GLOBALS['I18N']->get('Check out') .
276  ' <a href="http://www.php.net/manual/en/ref.imap.php">http://www.php.net/manual/en/ref.imap.php</a>');
277  return;
278}
279
280//print '<script language="Javascript" src="js/progressbar.js" type="text/javascript"></script>';
281flush();
282$outputdone= 0;
283
284# lets not do this unless we do some locking first
285register_shutdown_function('processTestEmails_shutdown');
286$abort= ignore_user_abort(1);
287$process_id= getPageLock();
288
289if (!empty ($_REQUEST['email'])) {
290  $mailToFind= $_REQUEST['email'];
291  print prepareOutput();
292
293  switch ($test_protocol) {
294    case "pop" :
295      $link= openPop($test_mailbox_host, $test_mailbox_user, $test_mailbox_password);
296      break;
297    case "mbox" :
298      $link= openMbox($test_mailbox);
299      break;
300    default :
301      Error($GLOBALS['I18N']->get("test_protocol not supported"));
302      return;
303  }
304
305  if (isset ($link)) {
306    $mailIndex= findEmailForUser($link, $mailToFind);
307    if ( !is_null($mailIndex) ) {
308      $body= imap_body($link, $mailIndex);
309      $overview= imap_fetch_overview($link, $mailIndex);
310      printf('Subject: %s<br />', $overview[0]->subject);
311  
312      preg_match_all("/<a(.*)href=[\"\'](.*)[\"\']([^>]*)>/Umis", $body, $links);
313      foreach ($links[0] as $matchindex => $fullmatch) {
314        preg_match('/p=(\w+)/', $fullmatch, $linkPages);
315        printf('<a href="%s" id=%s>Link %s: %s</a><br />', $fullmatch, $matchindex++, $matchindex, $linkPages[1]);
316      }
317
318      preg_match_all('/http:\/\/\S+/', $body, $links);
319      foreach ($links[0] as $matchindex => $fullmatch) {
320        preg_match('/p=(\w+)/', $fullmatch, $linkPages);
321        printf('<a href="%s" id=%s>Link %s: %s</a><br />', $fullmatch, $matchindex++, $matchindex, $linkPages[1]);
322      }
323
324    }
325  }
326}
327
328{
329  print ('<form method="get">');
330  print ('  <input name="page" value="readtestmail" type="hidden" />');
331  print ('  <input class="submit" type="submit" name="action" value="Get email for user: " />');
332  printf('  <input type="text" name="email" value="%s" />', $_REQUEST['email']);
333  print ('</form>');
334}
335
336if (!$GLOBALS["commandline"]) {
337  print '<script language="Javascript" type="text/javascript"> finish(); </script>';
338}
339?>