tiki-mailin-code.php 22.5 KB
Newer Older
1
<?php
changi67's avatar
changi67 committed
2 3 4
/**
 * @package tikiwiki
 */
5
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
changi67's avatar
changi67 committed
6
// 
7 8
// 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.
changi67's avatar
changi67 committed
9 10
// $Id$

changi67's avatar
changi67 committed
11 12
require_once ('tiki-setup.php');
$access->check_script($_SERVER["SCRIPT_NAME"], basename(__FILE__));
13
include_once ('lib/mailin/mailinlib.php');
14
require_once ("lib/webmail/net_pop3.php");
15 16
include_once ("lib/mail/mimelib.php");
include_once ("lib/webmail/tikimaillib.php");
17
include_once ('lib/wiki/wikilib.php');
18 19 20 21 22 23

global $prefs;

$is_html = false;
$show_inlineImages = 'n';
$can_addAttachment = 'n';
24
$respond_email = 'y';
25

26 27 28 29 30
/**
 * @param $output
 * @param $out
 * @param $page
 * @param $user
31
 * @param $body
32
 */
33
function mailin_check_attachments(&$output, &$out, $page, $user)
34
{
35
	global $wikilib, $show_inlineImages, $can_addAttachment, $respond_email;
changi67's avatar
changi67 committed
36
	$cnt = 0;
37 38 39 40 41 42 43 44
	
	if ($can_addAttachment !== 'y') {
		return;
	}
	
	if (!isset($output["parts"])) {
		return;
	}
45 46
	
	for ($it = 0, $count_outputparts = count($output['parts']); $it < $count_outputparts; $it++) {
changi67's avatar
changi67 committed
47 48 49
		if (isset($output["parts"][$it]["d_parameters"]["filename"])) {
			$attachmentPart = $output["parts"][$it];
			$fileName = $attachmentPart["d_parameters"]["filename"];
50 51
			if (isset($attachmentPart["ctype_primary"])) $fileType = $attachmentPart["ctype_primary"] . "/" . $attachmentPart["ctype_secondary"];
			else $fileType = "";
changi67's avatar
changi67 committed
52
			$fileData = $attachmentPart["body"];
53 54
			$fileSize = strlen($fileData);
			$wikilib->wiki_attach_file($page, $fileName, $fileType, $fileSize, $fileData, "attached by mail", $user, "");
changi67's avatar
changi67 committed
55
			$cnt++;
56 57 58 59 60 61 62 63 64 65
			
			if($show_inlineImages === 'y') {
				$contentId = $attachmentPart['header']['content-id'];
				if (!empty($contentId)) {
					$contentId = str_replace("<", "", $contentId);
					$contentId = str_replace(">", "", $contentId);

					mailin_insert_inline_image($body, $contentId, $attId, $page);
				}
			}
changi67's avatar
changi67 committed
66 67 68 69
		}
	}
	$out.= $cnt;
	$out.= " attachment(s) added<br />";
70
}
71 72 73 74 75 76

/**
 * @param $output
 * @return string
 */
function mailin_get_body($output)
77
{
78 79 80 81
	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 = '';
changi67's avatar
changi67 committed
82
	return $body;
83
}
84 85 86 87 88 89 90 91 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
/**
 * @param $output
 * @return HTML string
 */
function mailin_get_html($output)
{
	if (isset($output['html'][0])) {
		$html = $output["html"][0];
	} elseif (isset($output['parts'][1]) && isset($output['parts'][1]["html"][0])) {
		$html = $output['parts'][1]["html"][0];
	} elseif (isset($output['parts'][0]) && isset($output['parts'][0]['parts'][1]) && isset($output['parts'][0]['parts'][1]["html"][0])) {
		$html = $output['parts'][0]['parts'][1]["html"][0];
	} elseif (isset($output['parts'][0]) && isset($output['parts'][0]['parts'][0]) && isset($output['parts'][0]['parts'][0]['parts'][1]) && isset($output['parts'][0]['parts'][0]['parts'][1]["html"][0])) {
		$html = $output['parts'][0]['parts'][0]['parts'][1]["html"][0];
	} else {
		$html = '';
	}
	return $html;
}

/**
 * This is function mailin_extract_inline_images
 * NOTE: Will force the use the HTML source as the page body
 * HTML is required in order to be able to identify the image in the email.
 *
 * @param string $pageName The name of the wiki page
 * @param mixed $output Array of email values
 * @param string $body The email body. Will be used as the wiki page body
 * @param string $out Log output
 * @param string $user The user; for logging purposes
 * @return nothing
 *
 */
function	mailin_extract_inline_images($pageName, $output, &$body, &$out, $user)
{
	global $wikilib, $is_html, $show_inlineImages, $can_addAttachment;
	
	if($show_inlineImages !== 'y') {
		return;
	}
	if ($can_addAttachment !== 'y') {
		return;
	}
	
	$cnt = 0;
	$errCnt = 0;
	if (!isset($output["parts"])) {
		return;
	}

	// Only for HTML email
	$html = mailin_get_html($output);
	if(empty($html)) {
		$out.= "inline attachments are only supported for email in html format<br />";
		return;
	}
	
	// Replace the text version, and use use the HTML as the page body
	
	// Locate the HTML
	$matches = array();
	preg_match("/<body[^>]*>(.*?)<\/body>/is", $html, $matches);
	$htmlBody = $matches[1];
	if (empty($htmlBody)) {
		// Assume the html is the body
		$htmlBody = $html;
	}
	
	// Get rid of "id" attributes, as they may cause a failure to load the image
	$htmlBody = str_ireplace('id=', 'xid=', $htmlBody);
	
	// Assign the HTML as the new body
	$body = $htmlBody;
	$is_html = true;

	// Locate the page with inline attachments	
160
	// Check deep level first, to avoid detecting extra, non-inlined attachments
161
	$activeParts = array();
162 163
	if (isset($output["parts"][0]["parts"][0]['parts'][1]["type"]) && $output["parts"][0]["parts"][0]['parts'][1]["type"] == 'text/html') {
		$activeParts = $output["parts"][0]["parts"];
164 165
	} elseif (isset($output["parts"][0]['parts'][1]["type"]) && $output["parts"][0]['parts'][1]["type"] == 'text/html') {
		$activeParts = $output["parts"][0]['parts'][1];
166 167 168
	} elseif (isset($output["parts"][1]) && isset($output["parts"][1]['ctype_parameters']['name'])) {
		$activeParts = $output["parts"];
	} 
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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	
	// Scroll the page attachments
	for ($it = 0, $count_outputparts = count($activeParts); $it < $count_outputparts; $it++) {
		if (isset($activeParts[$it]["ctype_parameters"]["name"])) {
			$attachmentPart = $activeParts[$it];
			$fileName = $attachmentPart["ctype_parameters"]["name"];
			if (isset($attachmentPart["type"])) {
				$fileType = $attachmentPart["type"];
			} else {
				$fileType = "";
			}
			
			// Only process images
			if(strpos($fileType,'image/',0) === false) {
				$errCnt++;
				continue;
			}
			
			// Process inline image
			$fileData = $attachmentPart['body'];
			$fileSize = function_exists('mb_strlen') ? mb_strlen($fileData, '8bit') : strlen($fileData);
			$attId = $wikilib->wiki_attach_file($pageName, $fileName, $fileType, $fileSize, $fileData, "inline image by mail", $user, "");
			$cnt++;
		
			$contentId = $attachmentPart['header']['content-id'];
			if (empty($contentId)) {
				$errCnt++;
				continue;
			}
			$contentId = str_replace("<", "", $contentId);
			$contentId = str_replace(">", "", $contentId);

			mailin_insert_inline_image($body, $contentId, $attId, $pageName);
		}
	}
	$out.= $cnt;
	$out.= " inline attachment(s) added. ".$errCnt." failed<br />";
}

function mailin_insert_inline_image(&$body, $contentId, $attId, $pageName)
{
	$search = array();
	$replace = array();
	$search[] = 'cid:'.$contentId;		// This string may differ depending on the senders email client, I guess. Tested using Outlook 2010 as the sender
	$replace[] = 'tiki-download_wiki_attachment.php?attId='.$attId.'&page='.urlencode($pageName);
	
	$newBody = str_replace($search, $replace, $body);
	if($newBody == $body) {
		$errCnt++;
		continue;
	}
	$body = $newBody;
}

223 224 225 226 227
/**
 * The tiki-mailin.php script is used to get / set wiki pages or articles
 * using a POP email account.
 */
global $debugger;
changi67's avatar
changi67 committed
228
if (defined($debugger)) $debugger->msg("tiki-mailin-code.php");
229 230
// Get a list of ACTIVE emails accounts configured for mailin procedures
$accs = $mailinlib->list_active_mailin_accounts(0, -1, 'account_desc', '');
231 232 233 234 235

if (empty($accs['data'])) {
	$content = '';
	return;
}
236
$content = '<br /><br />';
237 238 239

$userlib = TikiLib::lib('user');

240
// foreach account
241
foreach ($accs['data'] as $acc) {
242 243 244 245 246 247 248
	
	$show_inlineImages = $acc['show_inlineImages'];
	$can_addAttachment = $prefs['feature_wiki_attachments'];
	if($can_addAttachment === 'y') {
		$can_addAttachment = $acc['attachments'];
	}
	
249 250 251 252
	if (empty($acc['account'])) {
		continue;
	}
	
changi67's avatar
changi67 committed
253 254 255 256
	$content.= "<b>Processing account</b><br />";
	$content.= "Account :" . $acc['account'] . "<br />";
	$content.= "Type    :" . $acc['type'] . "<br />";
	$content.= "--------------------------<br />";
257

changi67's avatar
changi67 committed
258 259 260 261 262
	$pop3 = new Net_Pop3();
	$content.= "Connecting...";
	if ($pop3->connect($acc["pop"], $acc["port"])) {
		$content.= "OK.<br />";
		$content.= "Logging in...";
263 264
		
		// Login
changi67's avatar
changi67 committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
		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');
			}
284
		} else {
changi67's avatar
changi67 committed
285 286 287 288 289 290
			$content.= "Messages:" . $mailsum . "<br />";
			for ($i = 1; $i <= $mailsum; $i++) {
				$aux = $pop3->getParsedHeaders($i);
				if ($aux === FALSE) {
					$content.= "Headers not parsed.<br />";
				} else { // else $aux not FALSE
291 292 293
					if (!isset($aux["From"])) {
						$aux['From'] = $aux['Return-path'];
					}
changi67's avatar
changi67 committed
294 295 296
					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;
297
					$aux["realmsgid"] = preg_replace('/[<>]/', '', $aux["Message-ID"]);
changi67's avatar
changi67 committed
298
					$message = $pop3->getMsg($i);
299 300
					$mimelib = new mime();
					$output = $mimelib->decode($message);
301

302
					$content.= "<br />Reading a request.<br />From: " . $aux["From"] . "<br />Subject: " . $output['header']['subject'] . "<br />";
changi67's avatar
changi67 committed
303 304 305 306 307
					$content.= "sender email: " . $email_from . "<br />";
					$aux["sender"]["user"] = $userlib->get_user_by_email($email_from);
					$content.= "sender user: " . $aux["sender"]["user"] . "<br />";
					$cantUseMailIn = $acc["anonymous"] == 'n' && empty($aux["sender"]["user"]);
					if ($cantUseMailIn) {
308
						$content.= "Anonymous user access denied, sending auto-reply to email address:&nbsp;" . $aux["From"] . "<br />";
changi67's avatar
changi67 committed
309 310 311 312 313
						$mail = new TikiMail();
						$mail->setFrom($acc["account"]);
						$l = $prefs['language'];
						$mail->setSubject(tra('Tiki mail-in auto-reply', $l));
						$mail->setText(tra("Sorry, you can't use this feature.", $l));
314 315 316 317 318 319
						if ($acc['respond_email'] === 'y') {
							$res = $mail->send(array($email_from), 'mail');
							$content.= "Response sent<br />";
						} else {
							$content.= "Response by email is disabled<br />";
						}
changi67's avatar
changi67 committed
320
					} else {
321
						
322
						$processEmail = true;
323
						
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
						// Validate user's send permission
						if ($acc["anonymous"] == 'n') {
							
							if (!$userlib->user_has_permission($aux["sender"]["user"], 'tiki_p_send_mailin')) {
								$content.= "Access denied, sending auto-reply to email address:&nbsp;" . $aux["From"] . "<br />";
								$mail = new TikiMail();
								$mail->setFrom($acc["account"]);
								$l = $prefs['language'];
								$mail->setSubject(tra('Tiki mail-in auto-reply', $l));
								$mail->setText(tra("Sorry, you can't use this feature.", $l));
								if ($acc['respond_email'] === 'y') {
									$res = $mail->send(array($email_from), 'mail');
									$content.= "Response sent<br />";
								} else {
									$content.= "Response by email is disabled<br />";
changi67's avatar
changi67 committed
339
								}
340
								$processEmail = false;
changi67's avatar
changi67 committed
341
							}
342 343 344
						} 
						
						if ($processEmail) {
345
							
346 347 348 349 350
							if (empty($aux["sender"]["user"])) {
								$aux["sender"]["user"] = $email_from;
							}
							if (empty($aux["sender"]["name"])) {
								$aux["sender"]["name"] = $email_from;
351 352
							}
							
353
							if ($prefs['feature_articles'] && $acc['type'] == 'article-put') {
354

355 356
								$title = trim($output['header']['subject']);
								$topicId = isset($acc['article_topicId']) ? $acc['article_topicId'] : 0;
357
								$chkUser = $aux["sender"]["user"];
358 359
								if (!$wikilib->user_has_perm_on_object($chkUser, $topicId, 'topic', 'tiki_p_submit_article', 'tiki_p_edit_submission')) {
									$content.= $chkUser." cannot submit the article: ".$title."<br />";
360 361
									$processEmail = false;
								} if ($tiki_p_autoapprove_submission == 'y') {
362 363
									if (!$wikilib->user_has_perm_on_object($chkUser, $topicId, 'topic', 'tiki_p_autoapprove_submission)')) {
										$content.= $chkUser." cannot auto-approve the article: ".$title."<br />";
364 365
										$processEmail = false;
									}
366
								}
367 368 369 370 371 372

								if ($processEmail) {
									
									// This is used to CREATE articles
									$title = trim($output['header']['subject']);
									$msgbody = mailin_get_body($output);
373
									if ($msgbody && !empty($acc['discard_after'])) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
										$msgbody = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $msgbody);
									}
									$heading = $msgbody;
									$topicId = isset($acc['article_topicId']) ? $acc['article_topicId'] : 0;
									$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);
									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 />";
									}
412 413 414 415 416 417 418 419
								}
							} 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';
420
									}
421 422
									$method = $parts[0];
									$page = $parts[1];
changi67's avatar
changi67 committed
423
								} else {
424
									$page = trim($aux['Subject']);
changi67's avatar
changi67 committed
425
								}
426
								
427 428 429 430 431 432 433 434 435
								// Strip invalid characters from the page name 
								$wikilib = TikiLib::lib('wiki');
								if($wikilib->contains_badchars($page)) {
									$badChars = $wikilib->get_badchars();
									
									// Replace bad characters with a '_'
									for ($j = 0; $j < strlen($badChars); $j++) { 
										$char = $badChars[$j];
										$page = str_replace($char, "_", $page);
436
									}
437 438 439 440 441 442 443 444 445 446 447 448 449
								}
								
								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"]);
									if ($tikilib->page_exists($page)) {
										
										// Check permissions
										$chkUser = $aux["sender"]["user"];
										if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_view')) {
											$content.= $chkUser." cannot view the page: ".$page."<br />";
450
											$processEmail = false;
451 452
										}
										
453 454 455 456 457 458 459
										if ($processEmail) {
											$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));
										}
460 461 462 463
									} else {
										$l = $prefs['language'];
										$mail_data = $smarty->fetchLang($l, "mail/mailin_reply_subject.tpl");
										$mail->setSubject($mail_data . $page);
464
									}
465 466 467 468 469 470 471
									$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

arildb's avatar
arildb committed
472
									$chkUser = $aux["sender"]["user"];
473 474 475 476
									if ($tikilib->page_exists($page)) {
										// Check permissions for page
										if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
											$content.= $chkUser." cannot edit the page: ".$page."<br />";
477
											$processEmail = false;
478 479 480 481 482 483 484 485 486
										}
										if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
											$can_addAttachment = 'n';
											$show_inlineImages = 'n';
										}
									} else {
										// Check global permissions
										$userlib = TikiLib::lib('user');
										if (!$userlib->user_has_permission($chkUser, 'tiki_p_edit')) {
arildb's avatar
arildb committed
487
											$content.= $chkUser." cannot create the page: ".$page."<br />";
488
											$processEmail = false;
489 490 491 492 493
										}
										if (!$userlib->user_has_permission($chkUser, 'tiki_p_wiki_attach_files')) {
											$can_addAttachment = 'n';
											$show_inlineImages = 'n';
										}
494
									}
495
									
496 497 498 499 500 501 502 503 504
									if ($processEmail) {

										// Attempt to use HTML, if it exists
										$body = mailin_get_html($output);
										if (empty($body)) {
											$body = mailin_get_body($output);
										}
										if (!empty($acc['discard_after']) && $body) {
											$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
505
										}
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
										if (!empty($body)) {
											if ($prefs['feature_wiki_attachments'] === 'y') {
												mailin_extract_inline_images($page, $output, $body, $content, $aux["sender"]["user"]);
												mailin_check_attachments($output, $content, $page, $aux["sender"]["user"], $body);
											}
											if (!$tikilib->page_exists($page)) {
												$tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
												$content.= "Page: $page has been created<br />";
												
												// Assign category, if specified
												if ($prefs['feature_categories'] && isset($acc['categoryId'])) {
													try {
														$categoryId = intval($acc['categoryId']);
														if ($categoryId > 0) {
															// Validate the category before adding it
															$categlib = TikiLib::lib('categ');
															$categories = $categlib->get_category($categoryId);
															if ($categories !== false && !empty($categories)) {
																$categlib->categorizePage($page, $categoryId, $aux["sender"]["user"]);
																$content.= "Page: $page categorized. Id: ".$categoryId."<br />";
															} else {
																$content.= "Page: $page not categorized. Invalid categoryId: ".$categoryId."<br />";
															}
529
														}
530 531
													} catch (Exception $e) {
														$content.= "Failed to categorize page: $page  categoryId: ".$categoryId.". Error: ".$e->getMessage()."<br />";
532 533
													}
												}
534 535 536 537
												
											} else {
												$tikilib->update_page($page, $body, "Created from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
												$content.= "Page: $page has been updated";
538 539
											}
										}
changi67's avatar
changi67 committed
540
									}
541
								} elseif ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki-prepend' || ($acc['type'] == 'wiki' && $method == "APPEND") || ($acc['type'] == 'wiki' && $method == "PREPEND")) {
542

543
									// This is used to UPDATE wiki pages
544

545 546 547 548
									// Check permissions
									$chkUser = $aux["sender"]["user"];
									if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
										$content.= $chkUser." cannot edit the page: ".$page."<br />";
549
										$processEmail = false;
550 551 552 553 554
									}
									if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
										$can_addAttachment = 'n';
										$show_inlineImages = 'n';
									}
555

556
									if ($processEmail) {
557

558 559 560 561
										// Attempt to use HTML, if it exists
										$body = mailin_get_html($output);
										if (empty($body)) {
											$body = mailin_get_body($output);
562
										}
563 564 565 566 567 568 569 570 571 572 573 574

										if ($body && !empty($acc['discard_after'])) {
											$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
										}
										if (isset($body)) {
											if ($prefs['feature_wiki_attachments'] === 'y') {
												mailin_extract_inline_images($page, $output, $body, $content, $aux["sender"]["user"]);
												mailin_check_attachments($output, $content, $page, $aux["sender"]["user"], $body);
											}
											if (!$tikilib->page_exists($page)) {
												$tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"], '0.0.0.0', '');
												$content.= "Page: $page has been created<br />";
575
											} else {
576 577 578 579 580 581 582 583
												$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<br />";
584
											}
585 586 587 588 589 590 591 592 593 594 595 596 597 598
										}
									}
								} else {
									$mail = new TikiMail();
									$mail->setFrom($acc["account"]);
									$l = $prefs['language'];
									$mail_data = $smarty->fetchLang($l, "mail/mailin_help_subject.tpl");
									$mail->setSubject($mail_data);
									$smarty->assign('subject', $output['header']['subject']);
									$mail_data = $smarty->fetchLang($l, "mail/mailin_help.tpl");
									$mail->setText($mail_data);
									if ($acc['respond_email'] === 'y') {
										$res = $mail->send(array($email_from), 'mail');
										$content.= "Help response sent<br />";
changi67's avatar
changi67 committed
599
									} else {
600
										$content.= "Response by email is disabled<br />";
changi67's avatar
changi67 committed
601 602 603
									}
								}
							}
604
						}						
605
					}
changi67's avatar
changi67 committed
606
					// Remove the email from the pop3 server
607
					$pop3->deleteMsg($i);
608
					$content.= "Deleted message<br />";
609
				}
changi67's avatar
changi67 committed
610
				
611
			}
changi67's avatar
changi67 committed
612
			
613
		}
changi67's avatar
changi67 committed
614 615 616
		
	} else {
		$content.= "FAILED.<br />";
617
	}
changi67's avatar
changi67 committed
618 619
	$pop3->disconnect();
	
620
}