tiki-mailin-code.php 24.8 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$

11 12
use Tiki\MailIn;

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

global $prefs;

$is_html = false;
$show_inlineImages = 'n';
$can_addAttachment = 'n';
26
$respond_email = 'y';
27
$save_html = 'y';
28

29 30 31 32 33
/**
 * @param $output
 * @param $out
 * @param $page
 * @param $user
34
 * @param $body
35
 */
36
function mailin_check_attachments(&$output, &$out, $page, $user)
37
{
38
	global $wikilib, $show_inlineImages, $can_addAttachment, $respond_email;
changi67's avatar
changi67 committed
39
	$cnt = 0;
changi67's avatar
changi67 committed
40

41 42 43
	if ($can_addAttachment !== 'y') {
		return;
	}
changi67's avatar
changi67 committed
44

45 46 47
	if (!isset($output["parts"])) {
		return;
	}
changi67's avatar
changi67 committed
48

49
	for ($it = 0, $count_outputparts = count($output['parts']); $it < $count_outputparts; $it++) {
changi67's avatar
changi67 committed
50 51 52
		if (isset($output["parts"][$it]["d_parameters"]["filename"])) {
			$attachmentPart = $output["parts"][$it];
			$fileName = $attachmentPart["d_parameters"]["filename"];
53 54
			if (isset($attachmentPart["ctype_primary"])) $fileType = $attachmentPart["ctype_primary"] . "/" . $attachmentPart["ctype_secondary"];
			else $fileType = "";
changi67's avatar
changi67 committed
55
			$fileData = $attachmentPart["body"];
56 57
			$fileSize = strlen($fileData);
			$wikilib->wiki_attach_file($page, $fileName, $fileType, $fileSize, $fileData, "attached by mail", $user, "");
changi67's avatar
changi67 committed
58
			$cnt++;
changi67's avatar
changi67 committed
59

pkdille's avatar
pkdille committed
60
			if ($show_inlineImages === 'y') {
61 62 63 64 65 66 67 68
				$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
69 70 71 72
		}
	}
	$out.= $cnt;
	$out.= " attachment(s) added<br />";
73
}
74 75 76 77 78 79

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

changi67's avatar
changi67 committed
86
	return $body;
87
}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
/**
 * @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;
}
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
/**
 * @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,
			);
	}
changi67's avatar
changi67 committed
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154
	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,
		);
}

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

/**
 * 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
 *
 */
173
function mailin_extract_inline_images($pageName, $output, &$body, &$out, $user)
174 175
{
	global $wikilib, $is_html, $show_inlineImages, $can_addAttachment;
changi67's avatar
changi67 committed
176

pkdille's avatar
pkdille committed
177
	if ($show_inlineImages !== 'y') {
178 179 180 181 182
		return;
	}
	if ($can_addAttachment !== 'y') {
		return;
	}
changi67's avatar
changi67 committed
183

184 185 186 187 188 189 190 191
	$cnt = 0;
	$errCnt = 0;
	if (!isset($output["parts"])) {
		return;
	}

	// Only for HTML email
	$html = mailin_get_html($output);
pkdille's avatar
pkdille committed
192
	if (empty($html)) {
193 194 195
		$out.= "inline attachments are only supported for email in html format<br />";
		return;
	}
changi67's avatar
changi67 committed
196

197
	// Replace the text version, and use use the HTML as the page body
changi67's avatar
changi67 committed
198

199 200 201 202 203 204 205 206
	// 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;
	}
changi67's avatar
changi67 committed
207

208 209
	// Get rid of "id" attributes, as they may cause a failure to load the image
	$htmlBody = str_ireplace('id=', 'xid=', $htmlBody);
changi67's avatar
changi67 committed
210

211 212 213 214
	// Assign the HTML as the new body
	$body = $htmlBody;
	$is_html = true;

changi67's avatar
changi67 committed
215
	// Locate the page with inline attachments
216
	// Check deep level first, to avoid detecting extra, non-inlined attachments
217
	$activeParts = array();
218
	if (isset($output["parts"][0]["parts"][0]['parts'][1]["type"]) && isset($output["parts"][0]["parts"][0]["parts"][1]['ctype_parameters']['name'])) {
219
		$activeParts = $output["parts"][0]["parts"];
220
	} elseif (isset($output["parts"][0]['parts'][1]["type"]) && isset($output["parts"][0]["parts"][1]['ctype_parameters']['name'])) {
221
		$activeParts = $output["parts"][0]['parts'][1];
222 223
	} elseif (isset($output["parts"][1]) && isset($output["parts"][1]['ctype_parameters']['name'])) {
		$activeParts = $output["parts"];
changi67's avatar
changi67 committed
224 225
	}

226 227 228 229 230 231 232 233 234 235
	// 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 = "";
			}
changi67's avatar
changi67 committed
236

237
			// Only process images
pkdille's avatar
pkdille committed
238
			if (strpos($fileType, 'image/', 0) === false) {
239 240 241
				$errCnt++;
				continue;
			}
changi67's avatar
changi67 committed
242

243 244 245 246 247
			// 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++;
changi67's avatar
changi67 committed
248

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
			$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);
changi67's avatar
changi67 committed
270

271
	$newBody = str_replace($search, $replace, $body);
pkdille's avatar
pkdille committed
272
	if ($newBody == $body) {
273 274 275 276 277 278
		$errCnt++;
		continue;
	}
	$body = $newBody;
}

arildb's avatar
arildb committed
279 280 281
function mailin_preplog($msg)
{
	$logMessage = strip_tags($msg);
pkdille's avatar
pkdille committed
282
	$logMessage = str_replace('&nbsp;', ' ', $logMessage);
arildb's avatar
arildb committed
283 284 285 286
	return $logMessage;
}


287 288 289 290 291
/**
 * 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
292
if (defined($debugger)) $debugger->msg("tiki-mailin-code.php");
293 294
// Get a list of ACTIVE emails accounts configured for mailin procedures
$accs = $mailinlib->list_active_mailin_accounts(0, -1, 'account_desc', '');
295 296 297 298 299

if (empty($accs['data'])) {
	$content = '';
	return;
}
300
$content = '<br /><br />';
301 302 303

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

arildb's avatar
arildb committed
304 305 306 307 308
// Logger
$logUser = $aux["sender"]["user"];
$logslib = TikiLib::lib('logs');


309
// foreach account
310
foreach ($accs['data'] as $acc) {
311 312
	$show_inlineImages = $acc['show_inlineImages'];
	$can_addAttachment = $prefs['feature_wiki_attachments'];
pkdille's avatar
pkdille committed
313
	if ($can_addAttachment === 'y') {
314 315
		$can_addAttachment = $acc['attachments'];
	}
changi67's avatar
changi67 committed
316

317 318 319
	if (empty($acc['account'])) {
		continue;
	}
changi67's avatar
changi67 committed
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
	$account = MailIn\Account::fromDb($acc);
	$messages = $account->getMessages();

	foreach ($messages as $message) {
		$hasError = true;
		$email_from = $message->getFromAddress();
		$fromEmail = $message->getFromAddress();

		$sender_user = $message->getAssociatedUser();

		if (! $account->canReceive($message)) {
			$account->sendFailureResponse($message);
			continue; // Process next message
		}

		$processEmail = true;

		if (empty($sender_user)) {
			$sender_user = $email_from;
		}
		if (empty($aux["sender"]["name"])) {
			$aux["sender"]["name"] = $email_from;
		}

		$action = $account->getAction($message);

		if (! $action->isEnabled()) {
			// Action configured, but not enabled
			continue;
		}

		if ($account->isAnyoneAllowed() || $action->isAllowed($account, $message)) {
			$account->prepareMessage($message);
			$action->execute($account, $message);
		}

		continue; // FIXME : Remaining code still needs conversion

		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];
changi67's avatar
changi67 committed
368
		} else {
369 370 371 372 373 374 375 376 377 378 379 380 381
			$page = trim($aux['Subject']);
		}

		// 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 '_'
			$iStrlenBadChars = strlen($badChars);
			for ($j = 0; $j < $iStrlenBadChars; $j++) {
				$char = $badChars[$j];
				$page = str_replace($char, "_", $page);
changi67's avatar
changi67 committed
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 412 413 414 415 416

		if ($acc['type'] == 'wiki-get' || ($acc['type'] == 'wiki' && $method == "GET")) {
			//////////////
			//	wiki-get, wiki GET: Get a new wiki page. System emails page to user
			//////////////////////////////////////////////////////////////////////////////////
			// 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 = $sender_user;
				if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
					if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_view')) {
						$errorMsg = $chkUser." cannot view the page: ".$page."<br />";
						$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

						$content.= $errorMsg;
						$processEmail = false;
					}
				}
				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));
				}
			} else {
				$l = $prefs['language'];
				$mail_data = $smarty->fetchLang($l, "mail/mailin_reply_subject.tpl");
				$mail->setSubject($mail_data . $page);
changi67's avatar
changi67 committed
417
			}
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
			if ($processEmail) {
				$res = $mail->send(array($email_from), 'mail');
				$content.= "Response sent<br />";
				$hasError = false;
			}

		} elseif ($acc['type'] == 'wiki-put' || ($acc['type'] == 'wiki' && $method == "PUT")) {
			//////////////
			//	wiki-put, wiki PUT: Send a wiki page. User emails page to System
			//////////////////////////////////////////////////////////////////////////////////

			// This is used to Create/Update wiki pages
			$chkUser = $sender_user;

			// Attempt to use HTML, if it exists
			$body = mailin_get_html($output);
			if (empty($body)) {
				$body = mailin_get_body($output);
			}

			// Load user routing
			$route = array();
			if ($acc['routing'] === 'y') {
				$routes = $usermailinlib->locate_struct($chkUser, $aux['Subject'], $body);
				if (!empty($routes['data'])) {
					$content.= "User route from pattern: '".$routes['data'][0]['subj_pattern']."' / '".$routes['data'][0]['body_pattern']."'<br />";
					$route = $routes['data'][0];	// Only use the first route
				}
			}

			// Add namespace, if specified.
			// If no explicit namespace is specified, pages routed to structured may inherit, the structure namespace
			if ($prefs['namespace_enabled'] === 'y') {
				$nsName = trim($acc['namespace']);
				$ns = $prefs['namespace_separator'];
				if (!empty($nsName)) {
					// Use mail-in specified namespace
					if (!empty($ns)) {
						$page = $nsName.$ns.$page;
					}
				} elseif (!empty($route)) {
					// Inherit structure namespace
					$wikilib = TikiLib::lib('wiki');
					$nsName = $wikilib->get_namespace($route['structName']);
					if (!empty($nsName)) {
						if (!empty($ns)) {
							$page = $nsName.$ns.$page;
						}
466
					}
467 468 469 470 471 472 473 474 475 476
				}
			}


			// Check permissions
			if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
				if ($tikilib->page_exists($page)) {
					// Check permissions for page
					if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
						$errorMsg = $chkUser." cannot edit the page: ".$page."<br />";
arildb's avatar
arildb committed
477 478 479
						$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

						$content.= $errorMsg;
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
						$processEmail = false;
					}
					if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
						$can_addAttachment = 'n';
						$show_inlineImages = 'n';
					}
				} else {

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

					// Check the edit structure permissions on the target structure category, if defined for the routed structure
					$structCateg = array();
					if (!empty($route)) {
						if ($prefs['feature_categories'] === 'y') {

							$structName = $route['structName'];
							$categlib = TikiLib::lib('categ');
							$categParent = $categlib->get_object_categories('wiki page', $structName, -1, false);
							$catPermOK = false;
							foreach ($categParent as $c) {
								$categoryId = $c['categoryId'];
								if ($userlib->object_has_permission($chkUser, $categoryId, 'category', 'tiki_p_edit_structures')) {
									$catPermOK = true;
								}
								$structCateg[] = $categoryId;
							}
							if ($catPermOK == false) {
								$content.= $chkUser." cannot edit structure: ".$page."<br />";
								$processEmail = false;
							}
510
						} else {
511 512 513 514 515
							// Check global permissions
							if (!$userlib->user_has_permission($chkUser, 'tiki_p_edit_structures')) {
								$content.= $chkUser." cannot edit structure: ".$page."<br />";
								$processEmail = false;
							}
516
						}
517
					}
changi67's avatar
changi67 committed
518

519

520 521 522 523 524 525
					// Check category permission, if auto-assigning a category.
					// Otherwise checkglobal permissions
					if ($processEmail) {
						if ($prefs['feature_categories'] === 'y' && isset($acc['categoryId'])) {
							if (!$userlib->object_has_permission($chkUser, $acc['categoryId'], 'category', 'tiki_p_edit')) {
								$errorMsg = $chkUser." cannot create the page: ".$page."<br />";
arildb's avatar
arildb committed
526
								$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);
changi67's avatar
changi67 committed
527

arildb's avatar
arildb committed
528
								$content.= $errorMsg;
529
								$processEmail = false;
changi67's avatar
changi67 committed
530
							}
531 532 533 534 535 536 537
							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')) {
								$errorMsg = $chkUser." cannot create the page: ".$page."<br />";
arildb's avatar
arildb committed
538
								$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);
changi67's avatar
changi67 committed
539

arildb's avatar
arildb committed
540
								$content.= $errorMsg;
541
								$processEmail = false;
542
							}
543 544 545
							if (!$userlib->user_has_permission($chkUser, 'tiki_p_wiki_attach_files')) {
								$can_addAttachment = 'n';
								$show_inlineImages = 'n';
546
							}
547 548 549 550 551
						}
					}
				}
			}
			if ($processEmail) {
changi67's avatar
changi67 committed
552

553 554 555 556 557 558 559 560
				if (!empty($acc['discard_after']) && $body) {
					$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
				}
				if (!empty($body)) {
					if ($prefs['feature_wiki_attachments'] === 'y') {
						mailin_extract_inline_images($page, $output, $body, $content, $sender_user);
						mailin_check_attachments($output, $content, $page, $sender_user, $body);
					}
561

562 563
					$parsed_data = mailin_parse_body($body, $acc);
					$body = $parsed_data['body'];
changi67's avatar
changi67 committed
564

565
					if (!$tikilib->page_exists($page)) {
566

567 568 569
						// Check User structure routing
						if (!empty($route)) {
							// Structure routing is active. Create a structure node/page
changi67's avatar
changi67 committed
570

571 572 573 574 575 576
							// Use the page structure node, if specified, otherwise link to the rrot of the structure
							if ($route['page_id'] > 0) {
								$parent_id = $route['page_struct_refid'];	// page_ref_id
							} else {
								$parent_id = $route['page_ref_id'];
							}
577

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
							$structure_id = $route['structure_id'];
							$begin = true;

							$after_ref_id = null;
							$alias='';
							$options = array();

							$options['hide_toc'] = 'y';
							$options['creator'] = $sender_user;
							$options['creator_msg'] = tra('created from mail-in');
							$options['ip_source'] = '0.0.0.0';

							$structlib = TikiLib::lib('struct');
							$structlib->s_create_page($parent_id, $after_ref_id, $page, $alias, $structure_id, $options);
							$content.= "Page: $page has been added to structureId: ".$structure_id."<br />";

							$tikilib->update_page(
								$page,
								$body,
								"Updated from " . $acc["account"],
								$sender_user,
								$options['ip_source'],
								'', //desc
								0, //edit_minor
								'', //lang
								$parsed_data['is_html'], //is_html
								'', //hash
								null, //saveLastModif
								$parsed_data['wysiwyg']	//wysiwyg
							);
							$errorMsg = "Page: $page has been updated by email: " . $fromEmail . "<br />";
							$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

							$content.= $errorMsg;
							$hasError = false;
						} else {
614

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
							// Create a regular page
							$tikilib->create_page(
								$page,
								0,
								$body,
								$tikilib->now,
								"Created from " . $acc["account"],
								$sender_user,
								'0.0.0.0',
								'', //description
								'', //lang
								$parsed_data['is_html'], //is_html
								'', //hash
								$parsed_data['wysiwyg'] //wysiwyg
							);
							$errorMsg = "Page: $page has been created by email: " . $fromEmail . "<br />";
							$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

							$content.= $errorMsg;
							$hasError = false;
						}
636

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
						// Assign category, if specified.
						//	Include the routed structure categories, if defined
						if ($prefs['feature_categories'] === 'y') {

							$catList = array_merge($structCateg, array($acc['categoryId']));
							if (!empty($catList)) {
								try {
									foreach ($catList as $c) {
										$categoryId = intval($c);

										// Validate the category before adding it
										$categlib = TikiLib::lib('categ');
										$categories = $categlib->get_category($categoryId);
										if ($categories !== false && !empty($categories)) {
											$categlib->categorizePage($page, $categoryId, $sender_user);
											$content.= "Page: $page categorized. Id: ".$categoryId."<br />";
653
										} else {
654
											$content.= "Page: $page not categorized. Invalid categoryId: ".$categoryId."<br />";
655
										}
changi67's avatar
changi67 committed
656
									}
657 658
								} catch (Exception $e) {
									$content.= "Failed to categorize page: $page  categoryId: ".$categoryId.". Error: ".$e->getMessage()."<br />";
changi67's avatar
changi67 committed
659 660
								}
							}
changi67's avatar
changi67 committed
661
						}
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680

					} else {
						$tikilib->update_page(
							$page,
							$body,
							"Updated from " . $acc["account"],
							$sender_user,
							'0.0.0.0',
							'', //desc
							0, //edit_minor
							'', //lang
							$parsed_data['is_html'], //is_html
							'', //hash
							null, //saveLastModif
							$parsed_data['wysiwyg']	//wysiwyg
						);
						$errorMsg = "Page: $page has been updated by email: " . $fromEmail . "<br />";
						$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

arildb's avatar
arildb committed
681
						$content.= $errorMsg;
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
						$hasError = false;
					}
				}
			}
		} elseif ($acc['type'] == 'wiki-append' || $acc['type'] == 'wiki-prepend' || ($acc['type'] == 'wiki' && $method == "APPEND") || ($acc['type'] == 'wiki' && $method == "PREPEND")) {
			//////////////
			//	wiki-append, wiki-prepend, wiki APPEND, wiki PREPEND
			//////////////////////////////////////////////////////////////////////////////////

			// Check permissions
			$chkUser = $sender_user;
			if (($acc["anonymous"] == 'n') && (!$userlib->user_has_permission($chkUser, 'tiki_p_admin'))) {
				if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_edit')) {
					$errorMsg = $chkUser." cannot edit the page: ".$page."<br />";
					$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

					$content.= $errorMsg;
					$processEmail = false;
				}
				if (!$wikilib->user_has_perm_on_object($chkUser, $page, 'wiki page', 'tiki_p_wiki_attach_files')) {
					$can_addAttachment = 'n';
					$show_inlineImages = 'n';
				}
			}
			if ($processEmail) {

				// Attempt to use HTML, if it exists
				$body = mailin_get_html($output);
				if (empty($body)) {
					$body = mailin_get_body($output);
				}
changi67's avatar
changi67 committed
713

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
				if ($body && !empty($acc['discard_after'])) {
					$body = preg_replace("/" . $acc['discard_after'] . ".*$/s", "", $body);
				}
				$parsed_data = mailin_parse_body($body, $acc);
				$body = $parsed_data['body'];
				if (isset($body)) {
					if ($prefs['feature_wiki_attachments'] === 'y') {
						mailin_extract_inline_images($page, $output, $body, $content, $sender_user);
						mailin_check_attachments($output, $content, $page, $sender_user, $body);
					}
					if (!$tikilib->page_exists($page)) {
						$tikilib->create_page(
							$page,
							0,
							$body,
							$tikilib->now,
							"Created from " . $acc["account"],
							$sender_user,
							'0.0.0.0',
							'', //description
							'', //lang
							$parsed_data['is_html'], //is_html
							'', //hash
							$parsed_data['wysiwyg']	//wysiwyg
						);
						$errorMsg = "Page: $page has been created by email: " . $fromEmail . "<br />";
arildb's avatar
arildb committed
740
						$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

						$content.= $errorMsg;
						$hasError = false;
					} 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,
							"Created from " . $acc["account"],
							$sender_user,
							'0.0.0.0',
							'', //desc
							0, //edit_minor
							'', //lang
							$parsed_data['is_html'], //is_html
							'', //hash
							null, //saveLastModif
							$parsed_data['wysiwyg']	//wysiwyg
						);
						$errorMsg = "Page: $page has been updated by email: " . $fromEmail . "<br />";
						$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);

						$content.= $errorMsg;
						$hasError = false;
770
					}
771 772
				}
			}
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
		} else {
			//////////////
			//	Invalid mail-in type
			//////////////////////////////////////////////////////////////////////////////////
			$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 />";
			} else {
				$content.= "Response by email is disabled<br />";
			}
			$errorMsg = "Invalid mail-in type";
			$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);
793
		}
changi67's avatar
changi67 committed
794

795 796 797 798 799 800 801 802 803
		if (!$hasError || ($hasError && ($acc['leave_email'] !== 'y'))) {
			$message->delete();
			$errorMsg = "Deleted message on email server. From: ".$fromEmail." Subject: ".$aux['Subject']."<br />";
			$content.= $errorMsg;

			// Cleanup log message and write to log
			$logslib->add_log('mailin', mailin_preplog($errorMsg), $logUser);
		}
	}
804
}