tiki-mailin-code.php 14.3 KB
Newer Older
1 2
<?php

3
// Copyright (c) 2002-2007, Luis Argerich, Garland Foster, Eduardo Polidor, et. al.
4 5 6
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.

7
/**
8 9 10
 * 2008-11-17 Scot E. Wilcoxon
 *   Reformat so everything is similarly indented.  There were too many deindentations.
 *
11
 * 2008-11-12 Scot E. Wilcoxon
12 13 14
 *   Added port to connect.
 *   Test and report progress.
 *   Replaced some tab characters with spaces.
15 16
 */

17
//this script may only be included - so its better to die if called directly.
michael_davey's avatar
michael_davey committed
18 19 20
//smarty is not there - we need setup
require_once('tiki-setup.php');  
$access->check_script($_SERVER["SCRIPT_NAME"],basename(__FILE__));
21

22 23
include_once ('lib/mailin/mailinlib.php');

24 25
// require_once ("lib/webmail/pop3.php");
require_once ("lib/webmail/net_pop3.php");
26 27
include_once ("lib/webmail/class.rc4crypt.php");

28 29
include_once ("lib/mail/mimelib.php");
include_once ("lib/webmail/tikimaillib.php");
30
include_once ('lib/wiki/wikilib.php');
31

32
function mailin_check_attachments(&$output, &$out, $page, $user) {
33 34 35
  global  $wikilib;
  $cnt = 0;
  if (!isset($output["parts"]))
36
  return;
37 38 39 40 41 42
  for ($it = 0; $it < count($output["parts"]); $it++)
  {
    if (isset($output["parts"][$it]["d_parameters"]["filename"]))
    {
      $attachmentPart = $output["parts"][$it];
      $fileName = $attachmentPart["d_parameters"]["filename"];
43 44 45 46
  if (isset($attachmentPart["ctype_primary"]))
    $fileType = $attachmentPart["ctype_primary"] ."/". $attachmentPart["ctype_secondary"];
  else
        $fileType="";
47 48 49 50 51 52 53
      $fileData = $attachmentPart["body"];
      $fileSize = strlen($fileData);
      $wikilib->wiki_attach_file($page, $fileName, $fileType, $fileSize, $fileData, "attached by mail", $user, "");
      $cnt++;
    }
  }
  $out .= $cnt;
54
  $out .= " attachment(s) added<br />";
55
}
56

57
function mailin_get_body($output) {
58 59 60 61 62 63 64 65 66
  if (isset($output['text'][0]))
    $body = $output["text"][0];
  elseif (isset($output['parts'][0]) && isset($output['parts'][0]["text"][0]))
    $body = $output['parts'][0]["text"][0];
  elseif (isset($output['parts'][0]) && isset($output['parts'][0]['parts'][0]) && isset($output['parts'][0]['parts'][0]["text"][0]))
    $body = $output['parts'][0]['parts'][0]["text"][0];
  else
    $body = '';
  return $body;
67 68

}
69 70 71 72 73 74 75 76

/**
 * The tiki-mailin.php script is used to get / set wiki pages or articles
 * using a POP email account.
 */

global $debugger;
if(defined($debugger)) $debugger->msg("tiki-mailin-code.php");
77 78 79 80

// Get a list of ACTIVE emails accounts configured for mailin procedures
$accs = $mailinlib->list_active_mailin_accounts(0, -1, 'account_desc', '');

81 82
//print ('<a href="tiki-admin_mailin.php">Admin</a><br /><br />');
$content = '<br /><br />';
83 84 85

// foreach account
foreach ($accs['data'] as $acc) {
86 87 88 89
  $content .= "<b>Processing account</b><br />";
  $content .= "Account :" . $acc['account'] . "<br />";
  $content .= "Type    :" . $acc['type'] . "<br />";
  $content .= "--------------------------<br />";
90 91
  //$pop3 = new POP3($acc["pop"], $acc["username"], $acc["pass"]);
  //$pop3->Open();
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  $pop3 = new Net_Pop3();
  $content .= "Connecting...";
  if( $pop3->connect($acc["pop"],$acc["port"]) ) {
    $content .= "OK.<br />";
    $content .= "Logging in...";
    if( $status=($pop3->login($acc["username"], $acc["pass"], "USER")) !== FALSE ) {
      $content .= "OK (" . $status . ").<br />";
      if(defined($debugger)) $debugger->msg("Logged in, status " . $status);
    } else {
      $content .= "FAILED.<br />";
      if(defined($debugger)) {
        $debugger->msg("Login failed, status " . $status);
        $debugger->msg("dump of pop3:");
        $debugger->var_dump('$pop3');
      }
    }
    $mailsum = $pop3->numMsg();
    if( $mailsum === FALSE ) {
      $content .= "No messages.<br />";
      if(defined($debugger)) {
        $debugger->msg("No messages.");
        $debugger->msg("dump of pop3:");
        $debugger->var_dump('$pop3');
      }
    } else { // else $mailsum not FALSE
      $content .= "Messages:" . $mailsum . "<br />";
118

119
      for ($i = 1; $i <= $mailsum; $i++) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133
        $aux = $pop3->getParsedHeaders($i);
        if( $aux === FALSE ) {
          $content .= "Headers not parsed.<br />";
        } else { // else $aux not FALSE
          // var_dump($aux);
          if (!isset($aux["From"])) $aux['From'] = $aux['Return-path'];
          preg_match('/<?([-!#$%&\'*+\.\/0-9=?A-Z^_`a-z{|}~][email protected][-!#$%&\'*+\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\.\/0-9=?A-Z^_`a-z{|}~]+)>?/',$aux["From"],$mail);
          $email_from = $mail[1];
             
          $aux["msgid"] = $i;
          $aux["realmsgid"] = ereg_replace("[<>]","",$aux["Message-ID"]);
          $message = $pop3->getMsg($i);
          $output = mime::decode($message);
        //mailin_parse_output($output, $parts, 0);
134

135
          $content .= "Reading a request.<br />From: " . $aux["From"] . "<br />Subject: " . $output['header']['subject'] . "<br />";
136

137 138 139
          $content .= "sender email: " . $email_from . "<br />";
          $aux["sender"]["user"] = $userlib->get_user_by_email($email_from);
          $content .= "sender user: " .  $aux["sender"]["user"] . "<br />";
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
          $cantUseMailIn = $acc["anonymous"]=='n' && empty($aux["sender"]["user"]);
          if($cantUseMailIn) {
            $content .= "Anonymous user acces denied, sending auto-reply to email address:&nbsp;" .  $aux["From"] . "<br />";
            $mail = new TikiMail();
            $mail->setFrom($acc["account"]);
            $c = $prefs['default_mail_charset'];
            $mail->setHeadCharset($c);
            $mail->setTextCharset($c);
            $l = $prefs['language'];
            $mail->setSubject(tra('Tiki mail-in auto-reply', $l));
            $mail->setSMTPParams($acc["smtp"], $acc["smtpPort"], '', $acc["useAuth"], $acc["username"], $acc["pass"]);
            $mail->setText(tra("Sorry, you can't use this feature.", $l));
            $res = $mail->send(array($email_from), 'mail');
            $content .= "Response sent<br />";
          } else {
            if (empty($aux["sender"]["user"]))
              $aux["sender"]["user"] = $email_from;
        
            if (empty($aux["sender"]["name"]))
              $aux["sender"]["name"] = $email_from;
        
            if ($acc['type'] == 'article-put') {
              // This is used to CREATE articles
              $title = trim($output['header']['subject']);
              
              $msgbody = mailin_get_body($output);
              if ($msgbody && isset($acc['discard_after'])) {
                   $msgbody = preg_replace("/".$acc['discard_after'].".*$/s", "", $msgbody);
              }
              
              $heading = $msgbody;
              $topicId = $acc['article_topicId'];
              $userm = $aux['sender']['user'];
              $authorName = $userm;
              $body = '';
              $publishDate = $tikilib->now;
              $cur_time = explode(',', $tikilib->date_format('%Y,%m,%d,%H,%M,%S', $publishDate));
                $expireDate = $tikilib->make_time($cur_time[3], $cur_time[4], $cur_time[5], $cur_time[1], $cur_time[2], $cur_time[0]+1);
              $subId = 0;
              $type = $acc['article_type'];
              $useImage = 'n';
              $image_x = '';
              $image_y = '';
              $imgname = '';
              $imgsize = '';
              $imgtype = '';
              $imgdata = '';
              $topline = '';
              $subtitle = '';
              $linkto = '';
              $image_caption = '';
              $lang = '';
              $rating = 7;
              $isfloat = 'n';
            
              global $artlib;
              if (!is_object($artlib)) {
                include_once('lib/articles/artlib.php');
              }
              $subid = $artlib->replace_submission($title, $authorName, $topicId, $useImage, $imgname, $imgsize, $imgtype, $imgdata, $heading, 
                    $body, $publishDate, $expireDate, $userm, $subId, $image_x, $image_y, $type, 
                    $topline, $subtitle, $linkto, $image_caption, $lang, $rating, $isfloat);
203

204 205 206 207 208 209 210
              global $tiki_p_autoapprove_submission;
              if ($tiki_p_autoapprove_submission == 'y') {
                $artlib->approve_submission($subid);
                $content .= "Article: $title has been submitted<br />";
              } else {
                $content .= "Article: $title has been created<br />";
              }
211

212 213 214 215 216 217 218 219 220 221 222 223 224
            } else { //else if ($acc['type'] == 'article-put')
              if ($acc['type'] == 'wiki') {
                $p_page = trim($aux['Subject']);
                $parts = explode(':', $p_page);
                if (!isset($parts[1])) {
                  $parts[1] = $parts[0];
                  $parts[0] = 'GET';
                }
                $method = $parts[0];
                $page = $parts[1];
              } else {
                $page = trim($aux['Subject']);
              }
225

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
              if ($acc['type'] == 'wiki-get' || ($acc['type'] == 'wiki' && $method == "GET")) {
                // A wiki-get account sends a copy of the page to the sender
                // and also sends the source of the page
                $mail = new TikiMail();
                $mail->setFrom($acc["account"]);
                $c = $prefs['default_mail_charset'];
                $mail->setHeadCharset($c);
                $mail->setHtmlCharset($c); 
                $mail->setTextCharset($c);
                $mail->setSMTPParams($acc["smtp"], $acc["smtpPort"], '', $acc["useAuth"], $acc["username"], $acc["pass"]);
                
                if ($tikilib->page_exists($page)) {
                  $mail->setSubject($page);
                  $info = $tikilib->get_page_info($page);
                  $data = $tikilib->parse_data($info["data"]);
                  $mail->addAttachment($info['data'], 'source.txt', 'plain/txt');
                  $mail->setHTML($data, strip_tags($data));
                } else {
                  $l = $prefs['language'];
                  $mail_data = $smarty->fetchLang($l, "mail/mailin_reply_subject.tpl");
                  $mail->setSubject($mail_data.$page);
                }
                $res = $mail->send(array($email_from), 'mail');
                $content .= "Response sent<br />";
              } //end if ($acc['type'] == 'wiki-get' || ($acc['type'] == 'wiki' && $method == "GET"))
        
              elseif ($acc['type'] == 'wiki-put' || ($acc['type'] == 'wiki' && $method == "PUT")) {
                // This is used to UPDATE wiki pages
            
                $body = mailin_get_body($output);
          
                if (isset($acc['discard_after']) && $body) {
                   $body = preg_replace("/".$acc['discard_after'].".*$/s", "", $body);
                }
                if (!empty($body)) {
                  if (!$tikilib->page_exists($page)) {
                    $content .= "Page: $page has been created<br />";
                
                    $tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
                  } else {
                    $tikilib->update_page($page, $body, "Created from " . $acc["account"], $aux["sender"]["user"],
                      '0.0.0.0', '');
                
                    $content .= "Page: $page has been updated";
                  }
                }
                mailin_check_attachments($output, $content, $page, $aux["sender"]["user"]);
              }
              elseif ($acc['type'] == 'wiki-put' || ($acc['type'] == 'wiki' && $method == "PUT")) { }
        
              elseif ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki-prepend' || ($acc['type'] == 'wiki' && $method == "APPEND") || ($acc['type'] == 'wiki' && $method == "PREPEND")) {
                // This is used to UPDATE wiki pages
          
                $body = mailin_get_body($output);
                if ($body && isset($acc['discard_after'])) {
                    $body = preg_replace("/".$acc['discard_after'].".*$/s", "", $body);
                }
          
                if (isset($body)) {
                  if (!$tikilib->page_exists($page)) {
                    $content .= "Page: $page has been created<br />";
                
                    $tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
                  } else {
                    $info = $tikilib->get_page_info($page);
                    if ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki' && $method == "APPEND")
                    $body = $info['data'] . $body;
                    else
                    $body = $body . $info['data'];
                    $tikilib->update_page($page, $body,
                      "Updated from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
                    $content .= "Page: $page has been updated";
                  }
                }
                mailin_check_attachments($output, $content, $page, $aux["sender"]["user"]);
              } //end elseif ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki-prepend' || ($acc['type'] == 'wiki' && $method == "APPEND") || ($acc['type'] == 'wiki' && $method == "PREPEND")) 
302

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
              else {
                $mail = new TikiMail();
              
                $mail->setFrom($acc["account"]);
                $c = $prefs['default_mail_charset'];
                $mail->setHeadCharset($c);
                $mail->setTextCharset($c);
                $l = $prefs['language'];
                $mail_data = $smarty->fetchLang($l, "mail/mailin_help_subject.tpl");
                $mail->setSubject($mail_data);
                $mail->setSMTPParams($acc["smtp"], $acc["smtpPort"], '', $acc["useAuth"], $acc["username"], $acc["pass"]);
                $smarty->assign('subject', $output['header']['subject']);
                $mail_data = $smarty->fetchLang($l, "mail/mailin_help.tpl");
                $mail->setText($mail_data);
                $res = $mail->send(array($email_from), 'mail');
              }
            }//end if ($acc['type'] == 'article-put')
          }//end if($cantUseMailIn)
          // Remove the email from the pop3 server
          $pop3->deleteMsg($i);
        } // else $aux not FALSE
324 325 326 327
      }//end for ($i = 1; $i <= $mailsum; $i++)
    } // else $mailsum not FALSE
  } else {
    $content .= "FAILED.<br />";
328
  } // end else if( $pop3->connect($acc["pop"],$acc["port"]) )
329

330
  $pop3->disconnect();
331
//echo $content;
332
}//end foreach ($accs['data'] as $acc) {