tiki-mailin-code.php 27.1 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
$save_html = 'y';
26

27 28 29 30 31
/**
 * @param $output
 * @param $out
 * @param $page
 * @param $user
32
 * @param $body
33
 */
34
function mailin_check_attachments(&$output, &$out, $page, $user)
35
{
36
	global $wikilib, $show_inlineImages, $can_addAttachment, $respond_email;
changi67's avatar
changi67 committed
37
	$cnt = 0;
38 39 40 41 42 43 44 45
	
	if ($can_addAttachment !== 'y') {
		return;
	}
	
	if (!isset($output["parts"])) {
		return;
	}
46 47
	
	for ($it = 0, $count_outputparts = count($output['parts']); $it < $count_outputparts; $it++) {
changi67's avatar
changi67 committed
48 49 50
		if (isset($output["parts"][$it]["d_parameters"]["filename"])) {
			$attachmentPart = $output["parts"][$it];
			$fileName = $attachmentPart["d_parameters"]["filename"];
51 52
			if (isset($attachmentPart["ctype_primary"])) $fileType = $attachmentPart["ctype_primary"] . "/" . $attachmentPart["ctype_secondary"];
			else $fileType = "";
changi67's avatar
changi67 committed
53
			$fileData = $attachmentPart["body"];
54 55
			$fileSize = strlen($fileData);
			$wikilib->wiki_attach_file($page, $fileName, $fileType, $fileSize, $fileData, "attached by mail", $user, "");
changi67's avatar
changi67 committed
56
			$cnt++;
57 58 59 60 61 62 63 64 65 66
			
			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
67 68 69 70
		}
	}
	$out.= $cnt;
	$out.= " attachment(s) added<br />";
71
}
72 73 74 75 76 77

/**
 * @param $output
 * @return string
 */
function mailin_get_body($output)
78
{
79 80 81 82
	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 = '';
83

changi67's avatar
changi67 committed
84
	return $body;
85
}
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
/**
 * @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;
}
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
/**
 * @param $body
 * @return parsed content
 */
function mailin_parse_body($body, $acc)
{
	global $prefs;

	$is_html = false;
	$wysiwyg = NULL;
	if (mailin_containsStringHTML($body)) {
		$is_html = true;
		$wysiwyg = 'y';
	}

	if ($is_html && $acc['save_html'] === 'y') {
		// Keep HTML setting. Always save as HTML
		return array(
			'body'=>$body,
			'is_html'=>$is_html,
			'wysiwyg'=>$wysiwyg,
			);
	}
	if ($prefs['feature_wysiwyg'] === 'y' && $prefs['wysiwyg_default'] === 'y' && $prefs['wysiwyg_htmltowiki'] !== 'y' ) {
		// WYSIWYG HTML editor is active
		$is_html = true;
		$wysiwyg = 'y';
		return array(
			'body'=>$body,
			'is_html'=>$is_html,
			'wysiwyg'=>$wysiwyg,
			);
	}
	
	if ($is_html) {
		include_once "lib/wiki/editlib.php";
		$editlib = new EditLib;
		$body = $editlib->parseToWiki($body);
		$is_html = false;
		$wysiwyg = NULL;
	}
	return array(
		'body'=>$body,
		'is_html'=>$is_html,
		'wysiwyg'=>$wysiwyg,
		);
}

function mailin_containsStringHTML($str) 
{
	return preg_match ('/<[^>]*>/', $str) == 1;	
}
157 158 159 160 161 162 163 164 165 166 167 168 169 170

/**
 * 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
 *
 */
171
function mailin_extract_inline_images($pageName, $output, &$body, &$out, $user)
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
{
	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	
214
	// Check deep level first, to avoid detecting extra, non-inlined attachments
215
	$activeParts = array();
216
	if (isset($output["parts"][0]["parts"][0]['parts'][1]["type"]) && isset($output["parts"][0]["parts"][0]["parts"][1]['ctype_parameters']['name'])) {
217
		$activeParts = $output["parts"][0]["parts"];
218
	} elseif (isset($output["parts"][0]['parts'][1]["type"]) && isset($output["parts"][0]["parts"][1]['ctype_parameters']['name'])) {
219
		$activeParts = $output["parts"][0]['parts'][1];
220 221 222
	} elseif (isset($output["parts"][1]) && isset($output["parts"][1]['ctype_parameters']['name'])) {
		$activeParts = $output["parts"];
	} 
223 224 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
	
	// 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;
}

277 278 279 280 281
/**
 * 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
282
if (defined($debugger)) $debugger->msg("tiki-mailin-code.php");
283 284
// Get a list of ACTIVE emails accounts configured for mailin procedures
$accs = $mailinlib->list_active_mailin_accounts(0, -1, 'account_desc', '');
285 286 287 288 289

if (empty($accs['data'])) {
	$content = '';
	return;
}
290
$content = '<br /><br />';
291 292 293

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

294
// foreach account
295
foreach ($accs['data'] as $acc) {
296 297 298 299 300 301 302
	
	$show_inlineImages = $acc['show_inlineImages'];
	$can_addAttachment = $prefs['feature_wiki_attachments'];
	if($can_addAttachment === 'y') {
		$can_addAttachment = $acc['attachments'];
	}
	
303 304 305 306
	if (empty($acc['account'])) {
		continue;
	}
	
changi67's avatar
changi67 committed
307 308 309 310
	$content.= "<b>Processing account</b><br />";
	$content.= "Account :" . $acc['account'] . "<br />";
	$content.= "Type    :" . $acc['type'] . "<br />";
	$content.= "--------------------------<br />";
311

changi67's avatar
changi67 committed
312 313 314 315 316
	$pop3 = new Net_Pop3();
	$content.= "Connecting...";
	if ($pop3->connect($acc["pop"], $acc["port"])) {
		$content.= "OK.<br />";
		$content.= "Logging in...";
317 318
		
		// Login
changi67's avatar
changi67 committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
		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');
			}
338
		} else {
changi67's avatar
changi67 committed
339 340 341 342 343 344
			$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
345 346 347
					if (!isset($aux["From"])) {
						$aux['From'] = $aux['Return-path'];
					}
changi67's avatar
changi67 committed
348 349 350
					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;
351
					$aux["realmsgid"] = preg_replace('/[<>]/', '', $aux["Message-ID"]);
changi67's avatar
changi67 committed
352
					$message = $pop3->getMsg($i);
353 354
					$mimelib = new mime();
					$output = $mimelib->decode($message);
355

356
					$content.= "<br />Reading a request.<br />From: " . $aux["From"] . "<br />Subject: " . $output['header']['subject'] . "<br />";
changi67's avatar
changi67 committed
357 358 359 360 361
					$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) {
362
						$content.= "Anonymous user access denied, sending auto-reply to email address:&nbsp;" . $aux["From"] . "<br />";
changi67's avatar
changi67 committed
363 364 365 366 367
						$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));
368 369 370 371 372 373
						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
374
					} else {
375
						
376
						$processEmail = true;
377
						
378
						// Validate user's send permission
379 380
						$chkUser = $aux["sender"]["user"];
						if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
381

382
							if (!$userlib->user_has_permission($chkUser, 'tiki_p_send_mailin')) {
383 384 385 386 387 388 389 390 391 392 393
								$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
394
								}
395
								$processEmail = false;
changi67's avatar
changi67 committed
396
							}
397
						} 
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
						if (($acc["admin"] === 'n') && ($userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
								$content.= "Admin access is blocked, 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 />";
								}
								$processEmail = false;
						}
413 414
						
						if ($processEmail) {
415
							
416 417 418 419 420
							if (empty($aux["sender"]["user"])) {
								$aux["sender"]["user"] = $email_from;
							}
							if (empty($aux["sender"]["name"])) {
								$aux["sender"]["name"] = $email_from;
421 422
							}
							
423
							if ($prefs['feature_articles'] && $acc['type'] == 'article-put') {
424

425 426
								$title = trim($output['header']['subject']);
								$topicId = isset($acc['article_topicId']) ? $acc['article_topicId'] : 0;
427
								$chkUser = $aux["sender"]["user"];
428
								if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
429 430
									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 />";
431
										$processEmail = false;
432 433 434 435 436
									} if ($tiki_p_autoapprove_submission == 'y') {
										if (!$wikilib->user_has_perm_on_object($chkUser, $topicId, 'topic', 'tiki_p_autoapprove_submission)')) {
											$content.= $chkUser." cannot auto-approve the article: ".$title."<br />";
											$processEmail = false;
										}
437
									}
438
								}
439 440 441 442 443
								if ($processEmail) {
									
									// This is used to CREATE articles
									$title = trim($output['header']['subject']);
									$msgbody = mailin_get_body($output);
444
									if ($msgbody && !empty($acc['discard_after'])) {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
										$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 />";
									}
483 484 485 486 487 488 489 490
								}
							} 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';
491
									}
492 493
									$method = $parts[0];
									$page = $parts[1];
changi67's avatar
changi67 committed
494
								} else {
495
									$page = trim($aux['Subject']);
changi67's avatar
changi67 committed
496
								}
497
								
498 499 500 501 502 503 504 505 506
								// 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);
507
									}
508 509 510 511 512 513 514 515 516 517 518
								}
								
								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"];
519
										if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
520 521 522 523
											if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_view')) {
												$content.= $chkUser." cannot view the page: ".$page."<br />";
												$processEmail = false;
											}
524
										}
525 526 527 528 529 530 531
										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));
										}
532 533 534 535
									} else {
										$l = $prefs['language'];
										$mail_data = $smarty->fetchLang($l, "mail/mailin_reply_subject.tpl");
										$mail->setSubject($mail_data . $page);
536
									}
537 538 539 540 541 542 543
									$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

544
									// Check permissions
arildb's avatar
arildb committed
545
									$chkUser = $aux["sender"]["user"];
546
									if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
547
										if ($tikilib->page_exists($page)) {
548
											// Check permissions for page
549 550
											if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
												$content.= $chkUser." cannot edit the page: ".$page."<br />";
551 552
												$processEmail = false;
											}
553
											if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
554 555 556 557
												$can_addAttachment = 'n';
												$show_inlineImages = 'n';
											}
										} else {
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
											// Check category permission, if auto-assigning a category.
											// Otherwise checkglobal permissions
											$userlib = TikiLib::lib('user');
											if ($prefs['feature_categories'] && isset($acc['categoryId'])) {
												if (!$userlib->object_has_permission($chkUser, $acc['categoryId'], 'category', 'tiki_p_edit')) {
													$content.= $chkUser." cannot create the page: ".$page."<br />";
													$processEmail = false;
												}
												if (!$userlib->object_has_permission($chkUser, $acc['categoryId'], 'category', 'tiki_p_wiki_attach_files')) {
													$can_addAttachment = 'n';
													$show_inlineImages = 'n';
												}
											} else {
												if (!$userlib->user_has_permission($chkUser, 'tiki_p_edit')) {
													$content.= $chkUser." cannot create the page: ".$page."<br />";
													$processEmail = false;
												}
												if (!$userlib->user_has_permission($chkUser, 'tiki_p_wiki_attach_files')) {
													$can_addAttachment = 'n';
													$show_inlineImages = 'n';
												}
579
											}
580
										}
581
									}
582 583 584 585 586 587 588
									if ($processEmail) {

										// Attempt to use HTML, if it exists
										$body = mailin_get_html($output);
										if (empty($body)) {
											$body = mailin_get_body($output);
										}
589 590 591 592 593 594 595 596 597 598 599
										
										// Add namespace, if specified
										if ($prefs['namespace_enabled'] === 'y') {
											$nsName = trim($acc['namespace']);
											if (!empty($nsName)) {
												$ns = $prefs['namespace_separator'];
												if (!empty($ns)) {
													$page = $nsName.$ns.$page;
												}
											}
										}
600

601 602
										if (!empty($acc['discard_after']) && $body) {
											$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
603
										}
604 605 606 607 608
										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);
											}
609 610 611 612

											$parsed_data = mailin_parse_body($body, $acc);
											$body = $parsed_data['body'];

613
											if (!$tikilib->page_exists($page)) {
614 615 616 617 618 619 620 621 622

												$tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"],
																	'0.0.0.0',
																	'',						//description
																	'',						//lang
																	$parsed_data['is_html'],	//is_html
																	'',						//hash
																	$parsed_data['wysiwyg']	//wysiwyg
												);
623
												$content.= "Page: $page has been created<br />";
624

625 626 627 628 629 630 631 632 633 634 635 636 637 638
												// 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 />";
															}
639
														}
640 641
													} catch (Exception $e) {
														$content.= "Failed to categorize page: $page  categoryId: ".$categoryId.". Error: ".$e->getMessage()."<br />";
642 643
													}
												}
644 645
												
											} else {
646 647 648 649 650 651 652 653 654 655 656
												$tikilib->update_page($page, $body, "Created from " . $acc["account"],
																		$aux["sender"]["user"],
																		'0.0.0.0',
																		'',	//desc
																		0, 	//edit_minor
																		'',	//lang
																		$parsed_data['is_html'],	//is_html
																		'',	//hash
																		null,	//saveLastModif
																		$parsed_data['wysiwyg']	//wysiwyg
												);
657
												$content.= "Page: $page has been updated<br />";
658 659
											}
										}
changi67's avatar
changi67 committed
660
									}
661
								} elseif ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki-prepend' || ($acc['type'] == 'wiki' && $method == "APPEND") || ($acc['type'] == 'wiki' && $method == "PREPEND")) {
662

663
									// This is used to UPDATE wiki pages
664

665 666
									// Check permissions
									$chkUser = $aux["sender"]["user"];
667
									if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
668 669 670 671 672 673 674 675
										if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
											$content.= $chkUser." cannot edit the page: ".$page."<br />";
											$processEmail = false;
										}
										if(!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
											$can_addAttachment = 'n';
											$show_inlineImages = 'n';
										}
676
									}
677
									if ($processEmail) {
678

679 680 681 682
										// Attempt to use HTML, if it exists
										$body = mailin_get_html($output);
										if (empty($body)) {
											$body = mailin_get_body($output);
683
										}
684 685 686 687

										if ($body && !empty($acc['discard_after'])) {
											$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
										}
688 689
										$parsed_data = mailin_parse_body($body, $acc);
										$body = $parsed_data['body'];
690 691 692 693 694 695
										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)) {
696 697 698 699 700 701 702 703
												$tikilib->create_page($page, 0, $body, $tikilib->now, "Created from " . $acc["account"], $aux["sender"]["user"],
																	 '0.0.0.0',
																	 '',						//description
																	 '',						//lang
																	 $parsed_data['is_html'],	//is_html
																	 '',						//hash
																	 $parsed_data['wysiwyg']	//wysiwyg
												);
704
												$content.= "Page: $page has been created<br />";
705
											} else {
706 707 708 709 710 711
												$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'];
												}
712 713 714 715 716 717 718 719 720 721 722
												$tikilib->update_page($page, $body, "Created from " . $acc["account"],
																	$aux["sender"]["user"],
																	'0.0.0.0',
																	'',	//desc
																	0, 	//edit_minor
																	'',	//lang
																	$parsed_data['is_html'],	//is_html
																	'',	//hash
																	null,	//saveLastModif
																	$parsed_data['wysiwyg']	//wysiwyg
												);
723
												$content.= "Page: $page has been updated<br />";
724
											}
725 726 727 728 729 730 731 732 733 734 735 736 737 738
										}
									}
								} 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
739
									} else {
740
										$content.= "Response by email is disabled<br />";
changi67's avatar
changi67 committed
741 742 743
									}
								}
							}
744
						}						
745
					}
changi67's avatar
changi67 committed
746
					// Remove the email from the pop3 server
747
					$pop3->deleteMsg($i);
748
					$content.= "Deleted message<br />";
749
				}
changi67's avatar
changi67 committed
750
				
751
			}
changi67's avatar
changi67 committed
752
			
753
		}
changi67's avatar
changi67 committed
754 755 756
		
	} else {
		$content.= "FAILED.<br />";
757
	}
changi67's avatar
changi67 committed
758 759
	$pop3->disconnect();
	
760
}