<?
/**
* IMAP2WIKI
*
* Usage:
*
* Gets email from imap account and adds it to a dokuwiki page
* Typically used to give offline/email users possibility to comment on wiki contributions
* Subject of email indicates namespace and pagename that will be used to add comments to
*
* Tested with UTF-8 encoded subjects/content
*
* Todo : authentication mechanism
* Todo : error checking for nasty situations:
- subject is not valid wiki namespace
- imap server does not respond
- posting does not succeed
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Riny <riny [at] bk [dot] ru>
* @thanks Andreas Gohr, Harry Fuecks, Christopher Arndt, Christopher Smith and dokuwiki community
*/
// SETUP
$host ="10.100.50.177"; // servername where your dokuwiki is
$dokuwikipath ="/dokuwiki/doku.php"; //path to your dokuwiki
$discussionprefix = "discussion:"; //based on the discussion template of Esther Brunner
$imapuser ="name"; //username to log in
$imappass ="pass"; //password to log in
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
require_once DOKU_INC.'inc/init.php';
require_once DOKU_INC.'inc/common.php';
require_once DOKU_INC.'inc/mime_parser.php';
if(!defined('NL')) define('NL',"\n");
// FUNCTIONS
function _decodeHeader($input) {
// Original from RFC2047 routine from http://pear.php.net/manual/en/package.mail.mail-mime.php
// Remove white space between encoded-words
$input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
// For each encoded-word...
while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
$encoded = $matches[1];
$charset = $matches[2];
$encoding = $matches[3];
$text = $matches[4];
switch (strtolower($encoding)) {
case 'b':
$text = base64_decode($text);
break;
case 'q':
$text = str_replace('_', ' ', $text);
preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
foreach($matches[1] as $value)
$text = str_replace('='.$value, chr(hexdec($value)), $text);
break;
}
$input = str_replace($encoded, $text, $input);
}
return $input;
}
function PostToHost($host, $path, $referer, $data_to_send,$targeturl) {
$fp = fsockopen($host, 80);
printf("Wiki found...\n");
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data_to_send) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data_to_send);
printf("Submitted to $host<br />");
while(!feof($fp)) {
$res .= fgets($fp, 128);
}
printf("Posted to $host</br>");
fclose($fp);
return $res;
}
function GetRaw($host,$dokuwikipath,$wikiid){
// gets raw content (not authenticated)
$filetoget="http://".$host.$dokuwikipath."?do=export_raw&id=$wikiid";
return implode('',file($filetoget));
}
function m2p_handleMedia(&$body,$fname){
global $ID;
global $conf;
global $lang;
if(!$fname) return;
msg('Handling '.$fname);
$fid = cleanID(getNS($ID).':'.$fname);
list($iext,$imime) = mimetype($fid);
$fn = mediaFN($fid);
msg('Saving to '.$fid);
// get filetype regexp
require_once(DOKU_INC.'inc/media.php');
$types = array_keys(getMimeTypes());
$types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
$regex = join('|',$types);
if(!preg_match('/\.('.$regex.')$/i',$fn)){
msg($lang['uploadwrong'],-1);
return;
}
io_createNamespace($fid, 'media');
if(io_saveFile($fn,$body)){
chmod($fn, $conf['fmode']);
msg($lang['uploadsucc'],1);
if(function_exists('media_notify')){
media_notify($fid,$fn,$imime);
}
}
}
/**
* Convert the body charset and save the page
*/
function m2p_handlePage(&$body,$ctype){
global $ID;
static $run = false;
if($run){
msg('Second page body found - ignored');
return;
}
$run = true;
msg('Handling body');
if(preg_match('/charset=["\']?([^"\']+)["\';]?$/i',$ctype,$match)){
msg('Converting from charset '.$match[1]);
$body = iconv($match[1],'utf-8',$body);
}
$body = cleanText($body);
//strip signature:
$body = preg_replace('/\n?-- (.*)$/s','',$body);
msg('Body length: '.strlen($body).' bytes');
//save page
saveWikiText($ID,$body,'submitted by email');
}
/**
* Get a (maybe decoded) header from any of the given fields
*/
function m2p_getHeader(&$data,$headers){
if(!is_array($headers)) $headers = array($headers);
$value = '';
foreach($headers as $header){
if($data['DecodedHeaders'][$header][0][0]['Value']){
$value = iconv($data['DecodedHeaders'][$header][0][0]['Encoding'],
'utf-8', $data['DecodedHeaders'][$header][0][0]['Value']);
break;
}
if($data['Headers'][$header]){
$value = $data['Headers'][$header];
break;
}
}
return $value;
}
/**
* Send a report back and end the script
*
* If $message is set it is added to the report before sending it.
*/
function m2p_finish($message=''){
global $from;
global $ID;
global $MSG;
global $conf;
if($message) msg($message);
$subject = '['.$conf['title'].'] Your email submission';
$text = 'The following reports were created while processing your submission'.NL.NL;
foreach($MSG as $m){
$text .= $m['msg'].NL;
}
echo $text;
flush();
if(!$from){
die('no reply address');
}
mail_send($from, $subject, $text, $conf['mailfrom']);
//exit();
}
/////////////////////////////////////////////////////////////////////
// connect to imap server 82.62.3.23
$mailbox = imap_open("{imap.free.fr:143}",$imapuser,$imappass);
// check mailbox
$check = imap_check($mailbox);
// check nr of messages
$noofmsg=$check->Nmsgs;
if ($noofmsg==0){
echo "No messages to process";
}
// for every message in inbox
for ($index=1; $index<=$noofmsg; $index++){
$file="c:/test.eml";
if(is_file($file)) {
chown($file,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
//fclose($file);
unlink($file);
}
$res = imap_savebody($mailbox, "$file", $index);
// read the mail and parse it
$data = array();
$mail = new mime_parser_class();
$ok = $mail->Decode(array('File' => "$file"), $data);
if(!$ok) die('decoding failed');
$data = $data[0];
#print_r($data);
// set up the reporting address
$from = m2p_getHeader($data,array('reply-to:','from:'));
// check the subject for the page id
$ID = cleanID(m2p_getHeader($data,'subject:')."_".date(DATE_RFC822));
if(!$ID) m2p_finish('No ID given');
msg("Saving to $ID");
// check the parts
if(count($data['Parts']) == 0){
msg('Single-Part message');
if(substr($data['Headers']['content-type:'],0,10) != 'text/plain'){
m2p_finish('bad content type - we can only handle text/plain');
}
m2p_handlePage($data['Body'], $data['Headers']['content-type:']);
}else{
msg('Multi-Part message');
foreach($data['Parts'] as $part){
msg('Found: '.$part['Headers']['content-type:']);
if(substr($part['Headers']['content-type:'],0,10) == 'text/plain' &&
$part['Headers']['content-disposition:'] != 'attachment'){
m2p_handlePage($part['Body'],$data['headers']['content-type:']);
}else{
m2p_handleMedia($part['Body'],$part['FileName']);
}
}
}
m2p_finish();
imap_delete($mailbox, $index);
}
imap_expunge ($mailbox);
imap_close($mailbox);
?>