<commit_before><?php

$rootpath = './';
$page_access = 'guest';
$allow_guest_post = true;
require_once $rootpath . 'includes/inc_default.php';
require_once $rootpath . 'includes/inc_pagination.php';

$id = (isset($_GET['id'])) ? $_GET['id'] : false;
$del = (isset($_GET['del'])) ? $_GET['del'] : false;
$edit = (isset($_GET['edit'])) ? $_GET['edit'] : false;
$add = (isset($_GET['add'])) ? true : false;

$uid = (isset($_GET['uid'])) ? $_GET['uid'] : false;
$submit = (isset($_POST['zend'])) ? true : false;

$orderby = (isset($_GET['orderby'])) ? $_GET['orderby'] : 'm.cdate';
$asc = (isset($_GET['asc'])) ? $_GET['asc'] : 0;

$recent = (isset($_GET['recent'])) ? true : false;

$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 25;
$start = (isset($_GET['start'])) ? $_GET['start'] : 0;

$q = (isset($_GET['q'])) ? $_GET['q'] : '';
$cid = (isset($_GET['cid'])) ? $_GET['cid'] : '';

$ow = (isset($_GET['ow'])) ? $_GET['ow'] : 'all';
$valid = (isset($_GET['valid'])) ? $_GET['valid'] : 'all';
$ustatus = (isset($_GET['ustatus'])) ? $_GET['ustatus'] : 'active';
$fcode = (isset($_GET['fcode'])) ? $_GET['fcode'] : '';

$img = (isset($_GET['img'])) ? true : false;
$img_del = (isset($_GET['img_del'])) ? $_GET['img_del'] : false;

$images = (isset($_FILES['images'])) ? $_FILES['images'] : null;

$mail = (isset($_POST['mail'])) ? true : false;

$selected_msgs = (isset($_POST['sel']) && $_POST['sel'] != '') ? explode(',', $_POST['sel']) : [];

$extend_submit = (isset($_POST['extend_submit'])) ? true : false;
$extend = (isset($_POST['extend'])) ? $_POST['extend'] : false;
$access_submit = (isset($_POST['access_submit'])) ? true : false;

$access = $access_control->get_post_value();

if ($post && $s_guest && ($add || $edit || $del || $img || $img_del || $images
	|| $extend_submit || $access_submit || $extend || $access))
{
	$alert->error('Geen toegang als gast tot deze actie');
	cancel($id);
}

if (!$post)
{
	$extend = (isset($_GET['extend'])) ? $_GET['extend'] : false;
}

/*
 * bulk actions (set access or validity)
 */
if ($post & (($extend_submit && $extend) || ($access_submit && $access)) & ($s_admin || $s_user))
{
	if (!is_array($selected_msgs) || !count($selected_msgs))
	{
		$alert->error('Selecteer ten minste één vraag of aanbod voor deze actie.');
		cancel();
	}

	if (!count($selected_msgs))
	{
		$errors[] = 'Selecteer ten minste één vraag of aanbod voor deze actie.';
	}

	if ($error_token = get_error_form_token())
	{
		$errors[] = $error_token;
	}

	$validity_ary = [];

	$rows = $db->executeQuery('select id_user, id, content, validity from messages where id in (?)',
			[$selected_msgs], [\Doctrine\DBAL\Connection::PARAM_INT_ARRAY]);

	foreach ($rows as $row)
	{
		if (!$s_admin && $s_user && ($row['id_user'] != $s_id))
		{
			$errors[] = 'Je bent niet de eigenaar van vraag of aanbod ' . $row['content'] . ' ( ' . $row['id'] . ')';
			cancel();
		}

		$validity_ary[$row['id']] = $row['validity'];
	}

	if ($extend_submit && !count($errors))
	{
		foreach ($validity_ary as $id => $validity)
		{
			$validity = gmdate('Y-m-d H:i:s', strtotime($validity) + (86400 * $extend));

			$m = [
				'validity'		=> $validity,
				'mdate'			=> gmdate('Y-m-d H:i:s'),
				'exp_user_warn'	=> 'f',
			];

			if (!$db->update('messages', $m, ['id' => $id]))
			{
				$alert->error('Fout: ' . $row['content'] . ' is niet verlengd.');
				cancel();
			}
		}
		if (count($validity_ary) > 1)
		{
			$alert->success('De berichten zijn verlengd.');
		}
		else
		{
			$alert->success('Het bericht is verlengd.');
		}

		cancel();
	}

	if ($access_submit && !count($errors))
	{
		$access_error = $access_control->get_post_error();

		if ($access_error)
		{
			$errors[] = $access_error;
		}

		if (!count($errors))
		{
			$m = [
				'local' => ($access == '2') ? 'f' : 't',
				'mdate' => gmdate('Y-m-d H:i:s')
			];

			$db->beginTransaction();
			try
			{
				foreach ($validity_ary as $id => $validity)
				{
					$db->update('messages', $m, ['id' => $id]);
				}

				$db->commit();

				if (count($selected_msgs) > 1)
				{
					$alert->success('De berichten zijn aangepast.');
				}
				else
				{
					$alert->success('Het bericht is aangepast.');
				}

				cancel();
			}
			catch(Exception $e)
			{
				$db->rollback();
				throw $e;
				$alert->error('Fout bij het opslaan.');
				cancel();
			}
		}

		$alert->error($errors);
	}
}

/*
 * fetch message
 */
if ($id || $edit || $del)
{
	$id = ($id) ?: (($edit) ?: $del);

	$message = $db->fetchAssoc('SELECT m.*,
			c.id as cid,
			c.fullname as catname
		FROM messages m, categories c
		WHERE m.id = ?
			AND c.id = m.id_category', [$id]);

	if (!$message)
	{
		$alert->error('Bericht niet gevonden.');
		cancel();
	}

	$s_owner = (!$s_guest && $s_group_self && $s_id == $message['id_user'] && $message['id_user']) ? true : false;

	if ($message['local'] && $s_guest)
	{
		$alert->error('Je hebt geen toegang tot dit bericht.');
		cancel();
	}

	$ow_type = ($message['msg_type']) ? 'aanbod' : 'vraag';
	$ow_type_this = ($message['msg_type']) ? 'dit aanbod' : 'deze vraag';
	$ow_type_the = ($message['msg_type']) ? 'het aanbod' : 'de vraag';
	$ow_type_uc = ucfirst($ow_type);
	$ow_type_uc_the = ucfirst($ow_type_the);
}

/*
 * extend (link from notification mail)
 */

if ($id && $extend)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' te verlengen.');
		cancel($id);
	}

	$validity = gmdate('Y-m-d H:i:s', strtotime($message['validity']) + (86400 * $extend));

	$m = [
		'validity'		=> $validity,
		'mdate'			=> gmdate('Y-m-d H:i:s'),
		'exp_user_warn'	=> 'f',
	];

	if (!$db->update('messages', $m, ['id' => $id]))
	{
		$alert->error('Fout: ' . $ow_type_the . ' is niet verlengd.');
		cancel($id);
	}

	$alert->success($ow_type_uc_the . ' is verlengd.');
	cancel($id);
}

if ($post)
{
	$s3 = Aws\S3\S3Client::factory([
		'signature'	=> 'v4',
		'region'	=> 'eu-central-1',
		'version'	=> '2006-03-01',
	]);
}

/**
 * post images
 */
if ($post && $img && $images && !$s_guest)
{
	$ret_ary = [];

	if ($id)
	{
		if (!$s_owner && !$s_admin)
		{
			$ret_ary[] = ['error' => 'Je hebt onvoldoende rechten om een afbeelding op te laden voor dit vraag of aanbod bericht.'];
		}
	}
	else
	{
		$form_token = isset($_GET['form_token']) ? $_GET['form_token'] : false;

		if (!$form_token)
		{
			$ret_ary[] = ['error' => 'Geen vraag of aanbod id of form token gedefinieerd.'];
		}
		else if (!$redis->get('form_token_' . $form_token))
		{
			$ret_ary[] = ['error' => 'Formulier verlopen of ongeldig.'];
		}
	}

	if (count($ret_ary))
	{
		$images = [];
	}

	foreach($images['tmp_name'] as $index => $tmpfile)
	{
		$name = $images['name'][$index];
		$size = $images['size'][$index];
		$type = $images['type'][$index];

		if ($type != 'image/jpeg')
		{
			$ret_ary[] = [
				'name'	=> $name,
				'size'	=> $size,
				'error' => 'ongeldig bestandstype',
			];
			continue;
		}

		if ($size > (200 * 1024))
		{
			$ret_ary[] = [
				'name'	=> $name,
				'size'	=> $size,
				'error' => 'te groot bestand',
			];
			continue;
		}

		//

		$exif = exif_read_data($tmpfile);

		$orientation = $exif['COMPUTED']['Orientation'];

		$tmpfile2 = tempnam(sys_get_temp_dir(), 'img');

		$imagine = new Imagine\Imagick\Imagine();

		$image = $imagine->open($tmpfile);

		switch ($orientation)
		{
			case 3:
			case 4:
				$image->rotate(180);
				break;
			case 5:
			case 6:
				$image->rotate(-90);
				break;
			case 7:
			case 8:
				$image->rotate(90);
				break;
			default:
				break;
		}

		$orgsize = $image->getSize();

		$width = $orgsize->getWidth();
		$height = $orgsize->getHeight();

		$newsize = ($width > $height) ? $orgsize->widen(400) : $orgsize->heighten(400);

		$image->resize($newsize);

		$image->save($tmpfile2);

		// if no msg id available then we get the probable next id. If it doesn't match
		// when the msg is posted then the file will get renamed.

		if (!$id)
		{
			$id = $db->getColumn('select max(id) from messages');
			$id++;
		}

		try {
			$filename = $schema . '_m_' . $id . '_';
			$filename .= sha1($filename . microtime()) . '.jpg';

			$upload = $s3->upload($s3_img, $filename, fopen($tmpfile2, 'rb'), 'public-read', [
				'params'	=> [
					'CacheControl'	=> 'public, max-age=31536000',
					'ContentType'	=> 'image/jpeg',
				],
			]);

			$ret = ['filename' => $filename];

			// only insert into msgpictures table when the msg is already created.

			if ($form_token)
			{
				log_event('pict', 'Message-Picture ' . $filename . ' uploaded. Message not yet created.');

				$ret['msgid'] = $id;
			}
			else
			{
				$db->insert('msgpictures', [
					'msgid'			=> $id,
					'"PictureFile"'	=> $filename]);

				log_event('pict', 'Message-Picture ' . $filename . ' uploaded. Message: ' . $id);
			}

			//$img_id = $db->lastInsertId('msgpictures_id_seq');

			// $size = $s3->get_object_filesize($s3_img, $filename);

			unlink($tmpfile);

			$ret_ary[] = $ret;
		}
		catch(Exception $e)
		{
			echo $e->getMessage();
			log_event('pict', 'Upload fail : ' . $e->getMessage());
		}
	}

	header('Pragma: no-cache');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Content-Disposition: inline; filename="files.json"');
	header('X-Content-Type-Options: nosniff');
	header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');

	header('Vary: Accept');

	echo json_encode($ret_ary);
	exit;
}

if ($img_del == 'all' && $id && $post)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om afbeeldingen te verwijderen voor ' . $ow_type_this);
	}

	$imgs = $db->fetchAll('select * from msgpictures where msgid = ?', [$id]);

	foreach($imgs as $img)
	{
		$s3->deleteObject([
			'Bucket'	=> $s3_img,
			'Key'		=> $img['PictureFile'],
		]);
	}

	$db->delete('msgpictures', ['msgid' => $id]);

	$alert->success('De afbeeldingen voor ' . $ow_type_this . ' zijn verwijderd.');

	cancel($id);
}

/*
 * delete an image
 */
if ($img_del && $post && ctype_digit((string) $img_del))
{
	if (!($msg = $db->fetchAssoc('select m.id_user, p."PictureFile"
		from msgpictures p, messages m
		where p.msgid = m.id
			and p.id = ?', [$img_del])))
	{
		echo json_encode(['error' => 'Afbeelding niet gevonden.']);
		exit;
	}

	$s_owner = (!$s_guest && $s_group_self && $msg['id_user'] == $s_id && $msg['id_user']) ? true : false;

	if (!($s_owner || $s_admin))
	{
		echo json_encode(['error' => 'Onvoldoende rechten om deze afbeelding te verwijderen.']);
		exit;
	}

	$db->delete('msgpictures', ['id' => $img_del]);

	$s3->deleteObject([
		'Bucket'	=> $s3_img,
		'Key'		=> $msg['PictureFile'],
	]);

	echo json_encode(['success' => true]);
	exit;
}

/**
 * delete images form
 */
if ($img_del == 'all' && $id)
{
	if (!($s_admin || $s_owner))
	{
		$alert->error('Je kan geen afbeeldingen verwijderen voor ' . $ow_type_this);
		cancel($id);
	}

	$images = [];

	$st = $db->prepare('select id, "PictureFile" from msgpictures where msgid = ?');
	$st->bindValue(1, $id);
	$st->execute();

	while ($row = $st->fetch())
	{
		$images[$row['id']] = $row['PictureFile'];
	}

	if (!count($images))
	{
		$alert->error($ow_type_uc_the . ' heeft geen afbeeldingen.');
		cancel($id);
	}

	$str_this_ow = $ow_type . ' "' . aphp('messages', ['id' => $id], $message['content']) . '"';
	$h1 = 'Afbeeldingen verwijderen voor ' . $str_this_ow;
	$fa = 'newspaper-o';

	$include_ary[] = 'msg_img_del.js';

	include $rootpath . 'includes/inc_header.php';

	if ($s_admin)
	{
		echo 'Gebruiker: ' . link_user($message['id_user']);
	}

	echo '<div class="row">';

	foreach ($images as $img_id => $file)
	{
		$a_img = $s3_img_url . $file;

		echo '<div class="col-xs-6 col-md-3">';
		echo '<div class="thumbnail">';
		echo '<img src="' . $a_img . '" class="img-rounded">';

		echo '<div class="caption">';
        echo '<span class="btn btn-danger" data-img-del="' . $img_id . '" ';
        echo 'data-url="' . generate_url('messages', ['img_del' => $img_id]) . '" role="button">';
        echo '<i class="fa fa-times"></i> ';
        echo 'Verwijderen</span>';
		echo '</div>';
 		echo '</div>';
		echo '</div>';

	}

	echo '</div>';

	echo '<form method="post" class="form-horizontal">';

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<h3>Alle afbeeldingen verwijderen voor ' . $str_this_ow . '?</h3>';

	echo aphp('messages', ['id' => $id], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Alle verwijderen" name="zend" class="btn btn-danger">';

	echo '</form>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';

	exit;
}

/*
 * send email
 */
if ($mail && $post && $id)
{
	$content = $_POST['content'];
	$cc = $_POST['cc'];

	$user = readuser($message['id_user']);

	if (!$s_admin && !in_array($user['status'], [1, 2]))
	{
		$alert->error('Je hebt geen rechten om een bericht naar een niet-actieve gebruiker te sturen');
		cancel();
	}

	if ($s_master)
	{
		$alert->error('Het master account kan geen berichten versturen.');
		cancel();
	}

	if (!$s_schema)
	{
		$alert->error('Je hebt onvoldoende rechten om een bericht te versturen.');
		cancel();
	}

	$user_me = ($s_group_self) ? '' : readconfigfromdb('systemtag', $s_schema) . '.';
	$user_me .= link_user($session_user, $s_schema, false);
	$user_me .= ($s_group_self) ? '' : ' van interlets groep ' . readconfigfromdb('systemname', $s_schema);

	$my_contacts = $db->fetchAll('select c.value, tc.abbrev
		from ' . $s_schema . '.contact c, ' . $s_schema . '.type_contact tc
		where c.flag_public >= ?
			and c.id_user = ?
			and c.id_type_contact = tc.id', [$access_ary[$user['accountrole']], $s_id]);

	$subject = 'Reactie op je ' . $ow_type . ' ' . $message['content'];

	$text = 'Beste ' . $user['name'] . "\r\n\r\n";
	$text .= 'Gebruiker ' . $user_me . ' heeft een reactie op je ' . $ow_type . " verstuurd via de webtoepassing\r\n\r\n";
	$text .= '--------------------bericht--------------------' . "\r\n\r\n";
	$text .= $content . "\r\n\r\n";
	$text .= '-----------------------------------------------' . "\r\n\r\n";
	$text .= "Om te antwoorden kan je gewoon reply kiezen of de contactgegevens hieronder gebruiken\r\n\r\n";
	$text .= 'Contactgegevens van ' . $user_me . ":\r\n\r\n";

	foreach($my_contacts as $value)
	{
		$text .= '* ' . $value['abbrev'] . "\t" . $value['value'] ."\n";
	}

	if ($content)
	{
		if ($cc)
		{
			$msg = 'Dit is een kopie van het bericht dat je naar ' . $user['letscode'] . ' ';
			$msg .= $user['name'];
			$msg .= ($s_group_self) ? '' : ' van letsgroep ' . $systemname;
			$msg .= ' verzonden hebt. ';
			$msg .= "\r\n\r\n\r\n";

			mail_q(['to' => $s_schema . '.' . $s_id, 'subject' => $subject . ' (kopie)', 'text' => $msg . $text]);
		}

		$text .= "\r\n\r\nInloggen op de website: " . $base_url . "\r\n\r\n";

		mail_q(['to' => $user['id'], 'reply_to' => $s_schema . '.' . $s_id, 'subject' => $subject, 'text' => $text]);

		$alert->success('Mail verzonden.');
	}
	else
	{
		$alert->error('Fout: leeg bericht. Mail niet verzonden.');
	}
	cancel($id);
}

/*
 * delete message
 */
if ($del)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' te verwijderen.');
		cancel($del);
	}

	if($submit)
	{
		if ($error_token = get_error_form_token())
		{
			$alert->error($error_token);
		}

		$pictures = $db->fetchAll('SELECT * FROM msgpictures WHERE msgid = ?', [$del]);

		foreach($pictures as $value)
		{
			$s3->deleteObject([
				'Bucket' => $s3_img,
				'Key'    => $value['PictureFile'],
			]);
		}

		$db->delete('msgpictures', ['msgid' => $del]);

		if ($db->delete('messages', ['id' => $del]))
		{
			$column = 'stat_msgs_';
			$column .= ($message['msg_type']) ? 'offers' : 'wanted';

			$db->executeUpdate('update categories
				set ' . $column . ' = ' . $column . ' - 1
				where id = ?', [$message['id_category']]);

			$alert->success(ucfirst($ow_type_this) . ' is verwijderd.');
			cancel();
		}

		$alert->error(ucfirst($ow_type_this) . ' is niet verwijderd.');
	}

	$h1 = ucfirst($ow_type_this) . ' ';
	$h1 .= aphp('messages', ['id' => $del], $message['content']);
	$h1 .= ' verwijderen?';
	$fa = 'newspaper-o';

	include $rootpath . 'includes/inc_header.php';

	echo '<div class="panel panel-info printview">';

	echo '<div class="panel-heading">';

	echo '<dl>';

	echo '<dt>Wie</dt>';
	echo '<dd>';
	echo link_user($message['id_user']);
	echo '</dd>';

	echo '<dt>Categorie</dt>';
	echo '<dd>';
	echo htmlspecialchars($message['catname'], ENT_QUOTES);
	echo '</dd>';

	echo '<dt>Geldig tot</dt>';
	echo '<dd>';
	echo $message['validity'];
	echo '</dd>';

	echo '<dt>Zichtbaarheid</dt>';
	echo '<dd>';
	echo $access_control->get_label($message['local'] ? 'users' : 'interlets');
	echo '</dd>';

	echo '</dl>';

	echo '</div>';

	echo '<div class="panel-body">';
	echo htmlspecialchars($message['Description'], ENT_QUOTES);
	echo '</div>';

	echo '<div class="panel-heading">';
	echo '<h3>';
	echo '<span class="danger">';
	echo 'Ben je zeker dat ' . $ow_type_this;
	echo ' moet verwijderd worden?</span>';

	echo '</h3>';

	echo '<form method="post">';

	echo aphp('messages', ['id' => $del], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Verwijderen" name="zend" class="btn btn-danger">';
	generate_form_token();
	echo '</form></p>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';
	exit;
}

/*
 * edit - add
 */
if (($edit || $add))
{
	if (!($s_admin || $s_user) && $add)
	{
		$alert->error('Je hebt onvoldoende rechten om een vraag of aanbod toe te voegen.');
		cancel();
	}

	if (!($s_admin || $s_owner) && $edit)
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' aan te passen.');
		cancel($edit);
	}

	if ($submit)
	{
		$validity = $_POST['validity'];

		if (!ctype_digit((string) $validity))
		{
			$errors[] = 'De geldigheid in dagen moet een positief getal zijn.';
		}

		$vtime = time() + ((int) $validity * 86400);
		$vtime =  gmdate('Y-m-d H:i:s', $vtime);

		if ($s_admin)
		{
			list($user_letscode) = explode(' ', $_POST['user_letscode']);
			$user_letscode = trim($user_letscode);
			$user = $db->fetchAssoc('select *
				from users
				where letscode = ?
					and status in (1, 2)', [$user_letscode]);
			if (!$user)
			{
				$errors[] = 'Ongeldige letscode.' . $user_letscode;
			}
		}

		$msg = [
			'validity'		=> $_POST['validity'],
			'vtime'			=> $vtime,
			'content'		=> $_POST['content'],
			'"Description"'	=> $_POST['description'],
			'msg_type'		=> $_POST['msg_type'],
			'id_user'		=> ($s_admin) ? (int) $user['id'] : (($s_master) ? 0 : $s_id),
			'id_category'	=> $_POST['id_category'],
			'amount'		=> $_POST['amount'],
			'units'			=> $_POST['units'],
			'local'			=> ($access_control->get_post_value() == 2) ? 0 : 1,
		];

		$access_error = $access_control->get_post_error();

		if ($access_error)
		{
			$errors[] = $access_error;
		}

		if (!ctype_digit((string) $msg['amount']) && $msg['amount'] != '')
		{
			$errors[] = 'De (richt)prijs in ' . $currency . ' moet nul of een positief getal zijn.';
		}

		if (!$msg['id_category'])
		{
			$errors[] = 'Geieve een categorie te selecteren.';
		}
		else if(!$db->fetchColumn('select id from categories where id = ?', [$msg['id_category']]))
		{
			$errors[] = 'Categorie bestaat niet!';
		}

		if (!$msg['content'])
		{
			$errors[] = 'De titel ontbreekt.';
		}

		if(strlen($msg['content']) > 200)
		{
			$errors[] = 'De titel mag maximaal 200 tekens lang zijn.';
		}

		if(strlen($msg['"Description"']) > 2000)
		{
			$errors[] = 'De omschrijving mag maximaal 2000 tekens lang zijn.';
		}

		if(strlen($msg['units']) > 15)
		{
			$errors[] = '"Per (uur, stuk, ...)" mag maximaal 15 tekens lang zijn.';
		}

		if(!($db->fetchColumn('select id from users where id = ? and status <> 0', [$msg['id_user']])))
		{
			$errors[] = 'Gebruiker bestaat niet!';
		}

		if ($error_form = get_error_form_token())
		{
			$errors[] = $error_form;
		}

		if (count($errors))
		{
			$alert->error($errors);
		}
		else if ($add)
		{
			$msg['cdate'] = gmdate('Y-m-d H:i:s');
			$msg['validity'] = $msg['vtime'];

			unset($msg['vtime']);

			if (empty($msg['amount']))
			{
				unset($msg['amount']);
			}

			if ($db->insert('messages', $msg))
			{
				$id = $db->lastInsertId('messages_id_seq');

				$stat_column = 'stat_msgs_';
				$stat_column .= ($msg['msg_type']) ? 'offers' : 'wanted';

				$db->executeUpdate('update categories set ' . $stat_column . ' = ' . $stat_column . ' + 1 where id = ?', [$msg['id_category']]);

				$alert->success('Nieuw vraag of aanbod toegevoegd.');
				cancel($id);
			}
			else
			{
				$alert->error('Fout bij het opslaan van vraag of aanbod.');
			}
		}
		else if ($edit)
		{
			if(empty($msg['validity']))
			{
				unset($msg['validity']);
			}
			else
			{
				$msg['validity'] = $msg['vtime'];
			}
			$msg['mdate'] = gmdate('Y-m-d H:i:s');
/*
			$description = $msg['description'];
*/
			unset($msg['vtime']);

			if (empty($msg['amount']))
			{
				unset($msg['amount']);
			}

			$db->beginTransaction();

			try
			{
				$db->update('messages', $msg, ['id' => $edit]);

	//			$db->update('messages', ['"Description"' => $description, ['id' => $id]]);

				if ($msg['msg_type'] != $msg['msg_type'] || $msg['id_category'] != $msg['id_category'])
				{
					$column = 'stat_msgs_';
					$column .= ($msg['msg_type']) ? 'offers' : 'wanted';

					$db->executeUpdate('update categories
						set ' . $column . ' = ' . $column . ' - 1
						where id = ?', [$msg['id_category']]);

					$column = 'stat_msgs_';
					$column .= ($msg['msg_type']) ? 'offers' : 'wanted';

					$db->executeUpdate('update categories
						set ' . $column . ' = ' . $column . ' + 1
						where id = ?', [$msg['id_category']]);
				}
				$db->commit();
				$alert->success('Vraag/aanbod aangepast');
				cancel($edit);
			}
			catch(Exception $e)
			{
				$db->rollback();
				throw $e;
				exit;
			}
		}
		else
		{
			$alert->error('Fout: onbepaalde actie.');
			cancel();
		}

		$msg['description'] = $msg['"Description"'];
	}
	else if ($edit)
	{
		$msg =  $db->fetchAssoc('select m.*,
			m."Description" as description
			from messages m
			where m.id = ?', [$edit]);
		$msg['description'] = $msg['Description'];
		unset($msg['Description']);

		$rev = round((strtotime($msg['validity']) - time()) / (86400));
		$msg['validity'] = ($rev < 1) ? 0 : $rev;

		$user = readuser($msg['id_user']);

		$user_letscode = $user['letscode'] . ' ' . $user['name'];
	}
	else if ($add)
	{
		$msg = [
			'validity'		=> readconfigfromdb('msgs_days_default'),
			'content'		=> '',
			'description'	=> '',
			'msg_type'		=> '1',
			'id_user'		=> ($s_master) ? 0 : $s_id,
			'id_category'	=> '',
			'amount'		=> '',
			'units'			=> '',
			'local'			=> 0,
		];

		$uid = (isset($_GET['uid']) && $s_admin) ? $_GET['uid'] : (($s_master) ? 0 : $s_id);

		if ($s_master)
		{
			$user_letscode = '';
		}
		else
		{
			$user = readuser($uid);

			$user_letscode = $user['letscode'] . ' ' . $user['name'];
		}
	}

	$cat_list = ['' => ''];

	$rs = $db->prepare('SELECT id, fullname  FROM categories WHERE leafnote=1 order by fullname');

	$rs->execute();

	while ($row = $rs->fetch())
	{
		$cat_list[$row['id']] = $row['fullname'];
	}

	array_walk($msg, function(&$value, $key){ $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); });

	$top_buttons .= aphp('messages', ['view' => $view_messages], 'Lijst', 'btn btn-default', 'Alle vraag en aanbod', 'newspaper-o', true);

	if (!$s_master)
	{
		$top_buttons .= aphp('messages', ['uid' => $s_id, 'view' => $view_messages], 'Mijn vraag en aanbod', 'btn btn-default', 'Mijn vraag en aanbod', 'user', true);
	}

	if ($s_admin)
	{
		$include_ary[] = 'typeahead';
		$include_ary[] = 'typeahead.js';
		$include_ary[] = 'access_input_cache.js';
	}

	$h1 = ($add) ? 'Nieuw Vraag of Aanbod toevoegen' : 'Vraag of Aanbod aanpassen';
	$fa = 'newspaper-o';

	include $rootpath . 'includes/inc_header.php';

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<form method="post" class="form-horizontal">';

	if($s_admin)
	{
		echo '<div class="form-group">';
		echo '<label for="user_letscode" class="col-sm-2 control-label">';
		echo '<span class="label label-info">Admin</span> Gebruiker</label>';
		echo '<div class="col-sm-10">';
		echo '<input type="text" class="form-control" id="user_letscode" name="user_letscode" ';
		echo 'data-typeahead="' . get_typeahead('users_active') . '" ';
		echo 'value="' . $user_letscode . '" required>';
		echo '</div>';
		echo '</div>';
	}

	echo '<div class="form-group">';
	echo '<label for="msg_type" class="col-sm-2 control-label">Vraag/Aanbod</label>';
	echo '<div class="col-sm-10">';
	echo '<select name="msg_type" id="msg_type" class="form-control" required>';
	render_select_options(['1' => 'Aanbod', '0' => 'Vraag'], $msg['msg_type']);
	echo "</select>";
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="content" class="col-sm-2 control-label">Titel</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="content" name="content" ';
	echo 'value="' . $msg['content'] . '" maxlength="200" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="description" class="col-sm-2 control-label">Omschrijving</label>';
	echo '<div class="col-sm-10">';
	echo '<textarea name="description" class="form-control" id="description" rows="4" maxlength="2000">';
	echo $msg['description'];
	echo '</textarea>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="id_category" class="col-sm-2 control-label">Categorie</label>';
	echo '<div class="col-sm-10">';
	echo '<select name="id_category" id="id_category" class="form-control" required>';
	render_select_options($cat_list, $msg['id_category']);
	echo "</select>";
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="validity" class="col-sm-2 control-label">Geldigheid in dagen</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="validity" name="validity" min="1" ';
	echo 'value="' . $msg['validity'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="amount" class="col-sm-2 control-label">Aantal ' . $currency . '</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="amount" name="amount" min="0" ';
	echo 'value="' . $msg['amount'] . '">';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="units" class="col-sm-2 control-label">Per (uur, stuk, ...)</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="units" name="units" ';
	echo 'value="' . $msg['units'] . '">';
	echo '</div>';
	echo '</div>';

	$access_value = $edit ? ($msg['local'] ? 'users' : 'interlets') : false;

	echo $access_control->get_radio_buttons('messages', $access_value, 'admin');

	$btn = ($edit) ? 'primary' : 'success';

	echo aphp('messages', ['id' => $id], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Opslaan" name="zend" class="btn btn-' . $btn . '">';
	generate_form_token();

	echo '</form>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';
	exit;
}

/**
 * show a message
 */
if ($id)
{<commit_msg>ref #35 upload img button in edit/add msg form<commit_after><?php

$rootpath = './';
$page_access = 'guest';
$allow_guest_post = true;
require_once $rootpath . 'includes/inc_default.php';
require_once $rootpath . 'includes/inc_pagination.php';

$id = (isset($_GET['id'])) ? $_GET['id'] : false;
$del = (isset($_GET['del'])) ? $_GET['del'] : false;
$edit = (isset($_GET['edit'])) ? $_GET['edit'] : false;
$add = (isset($_GET['add'])) ? true : false;

$uid = (isset($_GET['uid'])) ? $_GET['uid'] : false;
$submit = (isset($_POST['zend'])) ? true : false;

$orderby = (isset($_GET['orderby'])) ? $_GET['orderby'] : 'm.cdate';
$asc = (isset($_GET['asc'])) ? $_GET['asc'] : 0;

$recent = (isset($_GET['recent'])) ? true : false;

$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 25;
$start = (isset($_GET['start'])) ? $_GET['start'] : 0;

$q = (isset($_GET['q'])) ? $_GET['q'] : '';
$cid = (isset($_GET['cid'])) ? $_GET['cid'] : '';

$ow = (isset($_GET['ow'])) ? $_GET['ow'] : 'all';
$valid = (isset($_GET['valid'])) ? $_GET['valid'] : 'all';
$ustatus = (isset($_GET['ustatus'])) ? $_GET['ustatus'] : 'active';
$fcode = (isset($_GET['fcode'])) ? $_GET['fcode'] : '';

$img = (isset($_GET['img'])) ? true : false;
$img_del = (isset($_GET['img_del'])) ? $_GET['img_del'] : false;

$images = (isset($_FILES['images'])) ? $_FILES['images'] : null;

$mail = (isset($_POST['mail'])) ? true : false;

$selected_msgs = (isset($_POST['sel']) && $_POST['sel'] != '') ? explode(',', $_POST['sel']) : [];

$extend_submit = (isset($_POST['extend_submit'])) ? true : false;
$extend = (isset($_POST['extend'])) ? $_POST['extend'] : false;
$access_submit = (isset($_POST['access_submit'])) ? true : false;

$access = $access_control->get_post_value();

if ($post && $s_guest && ($add || $edit || $del || $img || $img_del || $images
	|| $extend_submit || $access_submit || $extend || $access))
{
	$alert->error('Geen toegang als gast tot deze actie');
	cancel($id);
}

if (!$post)
{
	$extend = (isset($_GET['extend'])) ? $_GET['extend'] : false;
}

/*
 * bulk actions (set access or validity)
 */
if ($post & (($extend_submit && $extend) || ($access_submit && $access)) & ($s_admin || $s_user))
{
	if (!is_array($selected_msgs) || !count($selected_msgs))
	{
		$alert->error('Selecteer ten minste één vraag of aanbod voor deze actie.');
		cancel();
	}

	if (!count($selected_msgs))
	{
		$errors[] = 'Selecteer ten minste één vraag of aanbod voor deze actie.';
	}

	if ($error_token = get_error_form_token())
	{
		$errors[] = $error_token;
	}

	$validity_ary = [];

	$rows = $db->executeQuery('select id_user, id, content, validity from messages where id in (?)',
			[$selected_msgs], [\Doctrine\DBAL\Connection::PARAM_INT_ARRAY]);

	foreach ($rows as $row)
	{
		if (!$s_admin && $s_user && ($row['id_user'] != $s_id))
		{
			$errors[] = 'Je bent niet de eigenaar van vraag of aanbod ' . $row['content'] . ' ( ' . $row['id'] . ')';
			cancel();
		}

		$validity_ary[$row['id']] = $row['validity'];
	}

	if ($extend_submit && !count($errors))
	{
		foreach ($validity_ary as $id => $validity)
		{
			$validity = gmdate('Y-m-d H:i:s', strtotime($validity) + (86400 * $extend));

			$m = [
				'validity'		=> $validity,
				'mdate'			=> gmdate('Y-m-d H:i:s'),
				'exp_user_warn'	=> 'f',
			];

			if (!$db->update('messages', $m, ['id' => $id]))
			{
				$alert->error('Fout: ' . $row['content'] . ' is niet verlengd.');
				cancel();
			}
		}
		if (count($validity_ary) > 1)
		{
			$alert->success('De berichten zijn verlengd.');
		}
		else
		{
			$alert->success('Het bericht is verlengd.');
		}

		cancel();
	}

	if ($access_submit && !count($errors))
	{
		$access_error = $access_control->get_post_error();

		if ($access_error)
		{
			$errors[] = $access_error;
		}

		if (!count($errors))
		{
			$m = [
				'local' => ($access == '2') ? 'f' : 't',
				'mdate' => gmdate('Y-m-d H:i:s')
			];

			$db->beginTransaction();
			try
			{
				foreach ($validity_ary as $id => $validity)
				{
					$db->update('messages', $m, ['id' => $id]);
				}

				$db->commit();

				if (count($selected_msgs) > 1)
				{
					$alert->success('De berichten zijn aangepast.');
				}
				else
				{
					$alert->success('Het bericht is aangepast.');
				}

				cancel();
			}
			catch(Exception $e)
			{
				$db->rollback();
				throw $e;
				$alert->error('Fout bij het opslaan.');
				cancel();
			}
		}

		$alert->error($errors);
	}
}

/*
 * fetch message
 */
if ($id || $edit || $del)
{
	$id = ($id) ?: (($edit) ?: $del);

	$message = $db->fetchAssoc('SELECT m.*,
			c.id as cid,
			c.fullname as catname
		FROM messages m, categories c
		WHERE m.id = ?
			AND c.id = m.id_category', [$id]);

	if (!$message)
	{
		$alert->error('Bericht niet gevonden.');
		cancel();
	}

	$s_owner = (!$s_guest && $s_group_self && $s_id == $message['id_user'] && $message['id_user']) ? true : false;

	if ($message['local'] && $s_guest)
	{
		$alert->error('Je hebt geen toegang tot dit bericht.');
		cancel();
	}

	$ow_type = ($message['msg_type']) ? 'aanbod' : 'vraag';
	$ow_type_this = ($message['msg_type']) ? 'dit aanbod' : 'deze vraag';
	$ow_type_the = ($message['msg_type']) ? 'het aanbod' : 'de vraag';
	$ow_type_uc = ucfirst($ow_type);
	$ow_type_uc_the = ucfirst($ow_type_the);
}

/*
 * extend (link from notification mail)
 */

if ($id && $extend)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' te verlengen.');
		cancel($id);
	}

	$validity = gmdate('Y-m-d H:i:s', strtotime($message['validity']) + (86400 * $extend));

	$m = [
		'validity'		=> $validity,
		'mdate'			=> gmdate('Y-m-d H:i:s'),
		'exp_user_warn'	=> 'f',
	];

	if (!$db->update('messages', $m, ['id' => $id]))
	{
		$alert->error('Fout: ' . $ow_type_the . ' is niet verlengd.');
		cancel($id);
	}

	$alert->success($ow_type_uc_the . ' is verlengd.');
	cancel($id);
}

if ($post)
{
	$s3 = Aws\S3\S3Client::factory([
		'signature'	=> 'v4',
		'region'	=> 'eu-central-1',
		'version'	=> '2006-03-01',
	]);
}

/**
 * post images
 */
if ($post && $img && $images && !$s_guest)
{
	$ret_ary = [];

	if ($id)
	{
		if (!$s_owner && !$s_admin)
		{
			$ret_ary[] = ['error' => 'Je hebt onvoldoende rechten om een afbeelding op te laden voor dit vraag of aanbod bericht.'];
		}
	}
	else
	{
		$form_token = isset($_GET['form_token']) ? $_GET['form_token'] : false;

		if (!$form_token)
		{
			$ret_ary[] = ['error' => 'Geen vraag of aanbod id of form token gedefinieerd.'];
		}
		else if (!$redis->get('form_token_' . $form_token))
		{
			$ret_ary[] = ['error' => 'Formulier verlopen of ongeldig.'];
		}
	}

	if (count($ret_ary))
	{
		$images = [];
	}

	foreach($images['tmp_name'] as $index => $tmpfile)
	{
		$name = $images['name'][$index];
		$size = $images['size'][$index];
		$type = $images['type'][$index];

		if ($type != 'image/jpeg')
		{
			$ret_ary[] = [
				'name'	=> $name,
				'size'	=> $size,
				'error' => 'ongeldig bestandstype',
			];
			continue;
		}

		if ($size > (200 * 1024))
		{
			$ret_ary[] = [
				'name'	=> $name,
				'size'	=> $size,
				'error' => 'te groot bestand',
			];
			continue;
		}

		//

		$exif = exif_read_data($tmpfile);

		$orientation = $exif['COMPUTED']['Orientation'];

		$tmpfile2 = tempnam(sys_get_temp_dir(), 'img');

		$imagine = new Imagine\Imagick\Imagine();

		$image = $imagine->open($tmpfile);

		switch ($orientation)
		{
			case 3:
			case 4:
				$image->rotate(180);
				break;
			case 5:
			case 6:
				$image->rotate(-90);
				break;
			case 7:
			case 8:
				$image->rotate(90);
				break;
			default:
				break;
		}

		$orgsize = $image->getSize();

		$width = $orgsize->getWidth();
		$height = $orgsize->getHeight();

		$newsize = ($width > $height) ? $orgsize->widen(400) : $orgsize->heighten(400);

		$image->resize($newsize);

		$image->save($tmpfile2);

		// if no msg id available then we get the probable next id. If it doesn't match
		// when the msg is posted then the file will get renamed.

		if (!$id)
		{
			$id = $db->getColumn('select max(id) from messages');
			$id++;
		}

		try {
			$filename = $schema . '_m_' . $id . '_';
			$filename .= sha1($filename . microtime()) . '.jpg';

			$upload = $s3->upload($s3_img, $filename, fopen($tmpfile2, 'rb'), 'public-read', [
				'params'	=> [
					'CacheControl'	=> 'public, max-age=31536000',
					'ContentType'	=> 'image/jpeg',
				],
			]);

			$ret = ['filename' => $filename];

			// only insert into msgpictures table when the msg is already created.

			if ($form_token)
			{
				log_event('pict', 'Message-Picture ' . $filename . ' uploaded. Message not yet created.');

				$ret['msgid'] = $id;
			}
			else
			{
				$db->insert('msgpictures', [
					'msgid'			=> $id,
					'"PictureFile"'	=> $filename]);

				log_event('pict', 'Message-Picture ' . $filename . ' uploaded. Message: ' . $id);
			}

			//$img_id = $db->lastInsertId('msgpictures_id_seq');

			// $size = $s3->get_object_filesize($s3_img, $filename);

			unlink($tmpfile);

			$ret_ary[] = $ret;
		}
		catch(Exception $e)
		{
			echo $e->getMessage();
			log_event('pict', 'Upload fail : ' . $e->getMessage());
		}
	}

	header('Pragma: no-cache');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Content-Disposition: inline; filename="files.json"');
	header('X-Content-Type-Options: nosniff');
	header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');

	header('Vary: Accept');

	echo json_encode($ret_ary);
	exit;
}

if ($img_del == 'all' && $id && $post)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om afbeeldingen te verwijderen voor ' . $ow_type_this);
	}

	$imgs = $db->fetchAll('select * from msgpictures where msgid = ?', [$id]);

	foreach($imgs as $img)
	{
		$s3->deleteObject([
			'Bucket'	=> $s3_img,
			'Key'		=> $img['PictureFile'],
		]);
	}

	$db->delete('msgpictures', ['msgid' => $id]);

	$alert->success('De afbeeldingen voor ' . $ow_type_this . ' zijn verwijderd.');

	cancel($id);
}

/*
 * delete an image
 */
if ($img_del && $post && ctype_digit((string) $img_del))
{
	if (!($msg = $db->fetchAssoc('select m.id_user, p."PictureFile"
		from msgpictures p, messages m
		where p.msgid = m.id
			and p.id = ?', [$img_del])))
	{
		echo json_encode(['error' => 'Afbeelding niet gevonden.']);
		exit;
	}

	$s_owner = (!$s_guest && $s_group_self && $msg['id_user'] == $s_id && $msg['id_user']) ? true : false;

	if (!($s_owner || $s_admin))
	{
		echo json_encode(['error' => 'Onvoldoende rechten om deze afbeelding te verwijderen.']);
		exit;
	}

	$db->delete('msgpictures', ['id' => $img_del]);

	$s3->deleteObject([
		'Bucket'	=> $s3_img,
		'Key'		=> $msg['PictureFile'],
	]);

	echo json_encode(['success' => true]);
	exit;
}

/**
 * delete images form
 */
if ($img_del == 'all' && $id)
{
	if (!($s_admin || $s_owner))
	{
		$alert->error('Je kan geen afbeeldingen verwijderen voor ' . $ow_type_this);
		cancel($id);
	}

	$images = [];

	$st = $db->prepare('select id, "PictureFile" from msgpictures where msgid = ?');
	$st->bindValue(1, $id);
	$st->execute();

	while ($row = $st->fetch())
	{
		$images[$row['id']] = $row['PictureFile'];
	}

	if (!count($images))
	{
		$alert->error($ow_type_uc_the . ' heeft geen afbeeldingen.');
		cancel($id);
	}

	$str_this_ow = $ow_type . ' "' . aphp('messages', ['id' => $id], $message['content']) . '"';
	$h1 = 'Afbeeldingen verwijderen voor ' . $str_this_ow;
	$fa = 'newspaper-o';

	$include_ary[] = 'msg_img_del.js';

	include $rootpath . 'includes/inc_header.php';

	if ($s_admin)
	{
		echo 'Gebruiker: ' . link_user($message['id_user']);
	}

	echo '<div class="row">';

	foreach ($images as $img_id => $file)
	{
		$a_img = $s3_img_url . $file;

		echo '<div class="col-xs-6 col-md-3">';
		echo '<div class="thumbnail">';
		echo '<img src="' . $a_img . '" class="img-rounded">';

		echo '<div class="caption">';
        echo '<span class="btn btn-danger" data-img-del="' . $img_id . '" ';
        echo 'data-url="' . generate_url('messages', ['img_del' => $img_id]) . '" role="button">';
        echo '<i class="fa fa-times"></i> ';
        echo 'Verwijderen</span>';
		echo '</div>';
 		echo '</div>';
		echo '</div>';

	}

	echo '</div>';

	echo '<form method="post" class="form-horizontal">';

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<h3>Alle afbeeldingen verwijderen voor ' . $str_this_ow . '?</h3>';

	echo aphp('messages', ['id' => $id], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Alle verwijderen" name="zend" class="btn btn-danger">';

	echo '</form>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';

	exit;
}

/*
 * send email
 */
if ($mail && $post && $id)
{
	$content = $_POST['content'];
	$cc = $_POST['cc'];

	$user = readuser($message['id_user']);

	if (!$s_admin && !in_array($user['status'], [1, 2]))
	{
		$alert->error('Je hebt geen rechten om een bericht naar een niet-actieve gebruiker te sturen');
		cancel();
	}

	if ($s_master)
	{
		$alert->error('Het master account kan geen berichten versturen.');
		cancel();
	}

	if (!$s_schema)
	{
		$alert->error('Je hebt onvoldoende rechten om een bericht te versturen.');
		cancel();
	}

	$user_me = ($s_group_self) ? '' : readconfigfromdb('systemtag', $s_schema) . '.';
	$user_me .= link_user($session_user, $s_schema, false);
	$user_me .= ($s_group_self) ? '' : ' van interlets groep ' . readconfigfromdb('systemname', $s_schema);

	$my_contacts = $db->fetchAll('select c.value, tc.abbrev
		from ' . $s_schema . '.contact c, ' . $s_schema . '.type_contact tc
		where c.flag_public >= ?
			and c.id_user = ?
			and c.id_type_contact = tc.id', [$access_ary[$user['accountrole']], $s_id]);

	$subject = 'Reactie op je ' . $ow_type . ' ' . $message['content'];

	$text = 'Beste ' . $user['name'] . "\r\n\r\n";
	$text .= 'Gebruiker ' . $user_me . ' heeft een reactie op je ' . $ow_type . " verstuurd via de webtoepassing\r\n\r\n";
	$text .= '--------------------bericht--------------------' . "\r\n\r\n";
	$text .= $content . "\r\n\r\n";
	$text .= '-----------------------------------------------' . "\r\n\r\n";
	$text .= "Om te antwoorden kan je gewoon reply kiezen of de contactgegevens hieronder gebruiken\r\n\r\n";
	$text .= 'Contactgegevens van ' . $user_me . ":\r\n\r\n";

	foreach($my_contacts as $value)
	{
		$text .= '* ' . $value['abbrev'] . "\t" . $value['value'] ."\n";
	}

	if ($content)
	{
		if ($cc)
		{
			$msg = 'Dit is een kopie van het bericht dat je naar ' . $user['letscode'] . ' ';
			$msg .= $user['name'];
			$msg .= ($s_group_self) ? '' : ' van letsgroep ' . $systemname;
			$msg .= ' verzonden hebt. ';
			$msg .= "\r\n\r\n\r\n";

			mail_q(['to' => $s_schema . '.' . $s_id, 'subject' => $subject . ' (kopie)', 'text' => $msg . $text]);
		}

		$text .= "\r\n\r\nInloggen op de website: " . $base_url . "\r\n\r\n";

		mail_q(['to' => $user['id'], 'reply_to' => $s_schema . '.' . $s_id, 'subject' => $subject, 'text' => $text]);

		$alert->success('Mail verzonden.');
	}
	else
	{
		$alert->error('Fout: leeg bericht. Mail niet verzonden.');
	}
	cancel($id);
}

/*
 * delete message
 */
if ($del)
{
	if (!($s_owner || $s_admin))
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' te verwijderen.');
		cancel($del);
	}

	if($submit)
	{
		if ($error_token = get_error_form_token())
		{
			$alert->error($error_token);
		}

		$pictures = $db->fetchAll('SELECT * FROM msgpictures WHERE msgid = ?', [$del]);

		foreach($pictures as $value)
		{
			$s3->deleteObject([
				'Bucket' => $s3_img,
				'Key'    => $value['PictureFile'],
			]);
		}

		$db->delete('msgpictures', ['msgid' => $del]);

		if ($db->delete('messages', ['id' => $del]))
		{
			$column = 'stat_msgs_';
			$column .= ($message['msg_type']) ? 'offers' : 'wanted';

			$db->executeUpdate('update categories
				set ' . $column . ' = ' . $column . ' - 1
				where id = ?', [$message['id_category']]);

			$alert->success(ucfirst($ow_type_this) . ' is verwijderd.');
			cancel();
		}

		$alert->error(ucfirst($ow_type_this) . ' is niet verwijderd.');
	}

	$h1 = ucfirst($ow_type_this) . ' ';
	$h1 .= aphp('messages', ['id' => $del], $message['content']);
	$h1 .= ' verwijderen?';
	$fa = 'newspaper-o';

	include $rootpath . 'includes/inc_header.php';

	echo '<div class="panel panel-info printview">';

	echo '<div class="panel-heading">';

	echo '<dl>';

	echo '<dt>Wie</dt>';
	echo '<dd>';
	echo link_user($message['id_user']);
	echo '</dd>';

	echo '<dt>Categorie</dt>';
	echo '<dd>';
	echo htmlspecialchars($message['catname'], ENT_QUOTES);
	echo '</dd>';

	echo '<dt>Geldig tot</dt>';
	echo '<dd>';
	echo $message['validity'];
	echo '</dd>';

	echo '<dt>Zichtbaarheid</dt>';
	echo '<dd>';
	echo $access_control->get_label($message['local'] ? 'users' : 'interlets');
	echo '</dd>';

	echo '</dl>';

	echo '</div>';

	echo '<div class="panel-body">';
	echo htmlspecialchars($message['Description'], ENT_QUOTES);
	echo '</div>';

	echo '<div class="panel-heading">';
	echo '<h3>';
	echo '<span class="danger">';
	echo 'Ben je zeker dat ' . $ow_type_this;
	echo ' moet verwijderd worden?</span>';

	echo '</h3>';

	echo '<form method="post">';

	echo aphp('messages', ['id' => $del], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Verwijderen" name="zend" class="btn btn-danger">';
	generate_form_token();
	echo '</form></p>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';
	exit;
}

/*
 * edit - add
 */
if (($edit || $add))
{
	if (!($s_admin || $s_user) && $add)
	{
		$alert->error('Je hebt onvoldoende rechten om een vraag of aanbod toe te voegen.');
		cancel();
	}

	if (!($s_admin || $s_owner) && $edit)
	{
		$alert->error('Je hebt onvoldoende rechten om ' . $ow_type_this . ' aan te passen.');
		cancel($edit);
	}

	if ($submit)
	{
		$validity = $_POST['validity'];

		if (!ctype_digit((string) $validity))
		{
			$errors[] = 'De geldigheid in dagen moet een positief getal zijn.';
		}

		$vtime = time() + ((int) $validity * 86400);
		$vtime =  gmdate('Y-m-d H:i:s', $vtime);

		if ($s_admin)
		{
			list($user_letscode) = explode(' ', $_POST['user_letscode']);
			$user_letscode = trim($user_letscode);
			$user = $db->fetchAssoc('select *
				from users
				where letscode = ?
					and status in (1, 2)', [$user_letscode]);
			if (!$user)
			{
				$errors[] = 'Ongeldige letscode.' . $user_letscode;
			}
		}

		$msg = [
			'validity'		=> $_POST['validity'],
			'vtime'			=> $vtime,
			'content'		=> $_POST['content'],
			'"Description"'	=> $_POST['description'],
			'msg_type'		=> $_POST['msg_type'],
			'id_user'		=> ($s_admin) ? (int) $user['id'] : (($s_master) ? 0 : $s_id),
			'id_category'	=> $_POST['id_category'],
			'amount'		=> $_POST['amount'],
			'units'			=> $_POST['units'],
			'local'			=> ($access_control->get_post_value() == 2) ? 0 : 1,
		];

		$access_error = $access_control->get_post_error();

		if ($access_error)
		{
			$errors[] = $access_error;
		}

		if (!ctype_digit((string) $msg['amount']) && $msg['amount'] != '')
		{
			$errors[] = 'De (richt)prijs in ' . $currency . ' moet nul of een positief getal zijn.';
		}

		if (!$msg['id_category'])
		{
			$errors[] = 'Geieve een categorie te selecteren.';
		}
		else if(!$db->fetchColumn('select id from categories where id = ?', [$msg['id_category']]))
		{
			$errors[] = 'Categorie bestaat niet!';
		}

		if (!$msg['content'])
		{
			$errors[] = 'De titel ontbreekt.';
		}

		if(strlen($msg['content']) > 200)
		{
			$errors[] = 'De titel mag maximaal 200 tekens lang zijn.';
		}

		if(strlen($msg['"Description"']) > 2000)
		{
			$errors[] = 'De omschrijving mag maximaal 2000 tekens lang zijn.';
		}

		if(strlen($msg['units']) > 15)
		{
			$errors[] = '"Per (uur, stuk, ...)" mag maximaal 15 tekens lang zijn.';
		}

		if(!($db->fetchColumn('select id from users where id = ? and status <> 0', [$msg['id_user']])))
		{
			$errors[] = 'Gebruiker bestaat niet!';
		}

		if ($error_form = get_error_form_token())
		{
			$errors[] = $error_form;
		}

		if (count($errors))
		{
			$alert->error($errors);
		}
		else if ($add)
		{
			$msg['cdate'] = gmdate('Y-m-d H:i:s');
			$msg['validity'] = $msg['vtime'];

			unset($msg['vtime']);

			if (empty($msg['amount']))
			{
				unset($msg['amount']);
			}

			if ($db->insert('messages', $msg))
			{
				$id = $db->lastInsertId('messages_id_seq');

				$stat_column = 'stat_msgs_';
				$stat_column .= ($msg['msg_type']) ? 'offers' : 'wanted';

				$db->executeUpdate('update categories set ' . $stat_column . ' = ' . $stat_column . ' + 1 where id = ?', [$msg['id_category']]);

				$alert->success('Nieuw vraag of aanbod toegevoegd.');
				cancel($id);
			}
			else
			{
				$alert->error('Fout bij het opslaan van vraag of aanbod.');
			}
		}
		else if ($edit)
		{
			if(empty($msg['validity']))
			{
				unset($msg['validity']);
			}
			else
			{
				$msg['validity'] = $msg['vtime'];
			}
			$msg['mdate'] = gmdate('Y-m-d H:i:s');
/*
			$description = $msg['description'];
*/
			unset($msg['vtime']);

			if (empty($msg['amount']))
			{
				unset($msg['amount']);
			}

			$db->beginTransaction();

			try
			{
				$db->update('messages', $msg, ['id' => $edit]);

	//			$db->update('messages', ['"Description"' => $description, ['id' => $id]]);

				if ($msg['msg_type'] != $msg['msg_type'] || $msg['id_category'] != $msg['id_category'])
				{
					$column = 'stat_msgs_';
					$column .= ($msg['msg_type']) ? 'offers' : 'wanted';

					$db->executeUpdate('update categories
						set ' . $column . ' = ' . $column . ' - 1
						where id = ?', [$msg['id_category']]);

					$column = 'stat_msgs_';
					$column .= ($msg['msg_type']) ? 'offers' : 'wanted';

					$db->executeUpdate('update categories
						set ' . $column . ' = ' . $column . ' + 1
						where id = ?', [$msg['id_category']]);
				}
				$db->commit();
				$alert->success('Vraag/aanbod aangepast');
				cancel($edit);
			}
			catch(Exception $e)
			{
				$db->rollback();
				throw $e;
				exit;
			}
		}
		else
		{
			$alert->error('Fout: onbepaalde actie.');
			cancel();
		}

		$msg['description'] = $msg['"Description"'];
	}
	else if ($edit)
	{
		$msg =  $db->fetchAssoc('select m.*,
			m."Description" as description
			from messages m
			where m.id = ?', [$edit]);
		$msg['description'] = $msg['Description'];
		unset($msg['Description']);

		$rev = round((strtotime($msg['validity']) - time()) / (86400));
		$msg['validity'] = ($rev < 1) ? 0 : $rev;

		$user = readuser($msg['id_user']);

		$user_letscode = $user['letscode'] . ' ' . $user['name'];
	}
	else if ($add)
	{
		$msg = [
			'validity'		=> readconfigfromdb('msgs_days_default'),
			'content'		=> '',
			'description'	=> '',
			'msg_type'		=> '1',
			'id_user'		=> ($s_master) ? 0 : $s_id,
			'id_category'	=> '',
			'amount'		=> '',
			'units'			=> '',
			'local'			=> 0,
		];

		$uid = (isset($_GET['uid']) && $s_admin) ? $_GET['uid'] : (($s_master) ? 0 : $s_id);

		if ($s_master)
		{
			$user_letscode = '';
		}
		else
		{
			$user = readuser($uid);

			$user_letscode = $user['letscode'] . ' ' . $user['name'];
		}
	}

	$cat_list = ['' => ''];

	$rs = $db->prepare('SELECT id, fullname  FROM categories WHERE leafnote=1 order by fullname');

	$rs->execute();

	while ($row = $rs->fetch())
	{
		$cat_list[$row['id']] = $row['fullname'];
	}

	array_walk($msg, function(&$value, $key){ $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); });

	$top_buttons .= aphp('messages', ['view' => $view_messages], 'Lijst', 'btn btn-default', 'Alle vraag en aanbod', 'newspaper-o', true);

	if (!$s_master)
	{
		$top_buttons .= aphp('messages', ['uid' => $s_id, 'view' => $view_messages], 'Mijn vraag en aanbod', 'btn btn-default', 'Mijn vraag en aanbod', 'user', true);
	}

	if ($s_admin)
	{
		$include_ary[] = 'typeahead';
		$include_ary[] = 'typeahead.js';
	}

	$include_ary[] = 'fileupload';
	$include_ary[] = 'msg_edit.js';
	$include_ary[] = 'access_input_cache.js';	

	$h1 = ($add) ? 'Nieuw Vraag of Aanbod toevoegen' : 'Vraag of Aanbod aanpassen';
	$fa = 'newspaper-o';

	include $rootpath . 'includes/inc_header.php';

	echo '<div class="panel panel-info">';
	echo '<div class="panel-heading">';

	echo '<form method="post" class="form-horizontal">';

	if($s_admin)
	{
		echo '<div class="form-group">';
		echo '<label for="user_letscode" class="col-sm-2 control-label">';
		echo '<span class="label label-info">Admin</span> Gebruiker</label>';
		echo '<div class="col-sm-10">';
		echo '<input type="text" class="form-control" id="user_letscode" name="user_letscode" ';
		echo 'data-typeahead="' . get_typeahead('users_active') . '" ';
		echo 'value="' . $user_letscode . '" required>';
		echo '</div>';
		echo '</div>';
	}

	echo '<div class="form-group">';
	echo '<label for="msg_type" class="col-sm-2 control-label">Vraag/Aanbod</label>';
	echo '<div class="col-sm-10">';
	echo '<select name="msg_type" id="msg_type" class="form-control" required>';
	render_select_options(['1' => 'Aanbod', '0' => 'Vraag'], $msg['msg_type']);
	echo "</select>";
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="content" class="col-sm-2 control-label">Titel</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="content" name="content" ';
	echo 'value="' . $msg['content'] . '" maxlength="200" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="description" class="col-sm-2 control-label">Omschrijving</label>';
	echo '<div class="col-sm-10">';
	echo '<textarea name="description" class="form-control" id="description" rows="4" maxlength="2000">';
	echo $msg['description'];
	echo '</textarea>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="id_category" class="col-sm-2 control-label">Categorie</label>';
	echo '<div class="col-sm-10">';
	echo '<select name="id_category" id="id_category" class="form-control" required>';
	render_select_options($cat_list, $msg['id_category']);
	echo "</select>";
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="validity" class="col-sm-2 control-label">Geldigheid in dagen</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="validity" name="validity" min="1" ';
	echo 'value="' . $msg['validity'] . '" required>';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="amount" class="col-sm-2 control-label">Aantal ' . $currency . '</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="number" class="form-control" id="amount" name="amount" min="0" ';
	echo 'value="' . $msg['amount'] . '">';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="units" class="col-sm-2 control-label">Per (uur, stuk, ...)</label>';
	echo '<div class="col-sm-10">';
	echo '<input type="text" class="form-control" id="units" name="units" ';
	echo 'value="' . $msg['units'] . '">';
	echo '</div>';
	echo '</div>';

	echo '<div class="form-group">';
	echo '<label for="fileupload" class="col-sm-2 control-label">Afbeeldingen</label>';
	echo '<div class="col-sm-10">';

	echo '<span class="btn btn-default fileinput-button">';
	echo '<i class="fa fa-plus" id="img_plus"></i> Opladen';
	echo '<input id="fileupload" type="file" name="images[]" ';
	echo 'data-url="' . generate_url('messages', ['img' => 1, 'id' => $id]) . '" ';
	echo 'data-data-type="json" data-auto-upload="true" ';
	echo 'data-accept-file-types="/(\.|\/)(jpe?g)$/i" ';
	echo 'data-max-file-size="999000" ';
	echo 'multiple></span>&nbsp;';

	echo '<p><small>Afbeeldingen moeten in het jpg/jpeg formaat zijn. Je kan ook afbeeldingen hierheen ';
	echo 'verslepen.</small></p>';	
	echo '</div>';
	echo '</div>';

	$access_value = $edit ? ($msg['local'] ? 'users' : 'interlets') : false;

	echo $access_control->get_radio_buttons('messages', $access_value, 'admin');


	$btn = ($edit) ? 'primary' : 'success';

	echo aphp('messages', ['id' => $id], 'Annuleren', 'btn btn-default'). '&nbsp;';
	echo '<input type="submit" value="Opslaan" name="zend" class="btn btn-' . $btn . '">';
	generate_form_token();

	echo '</form>';

	echo '</div>';
	echo '</div>';

	include $rootpath . 'includes/inc_footer.php';
	exit;
}

/**
 * show a message
 */
if ($id)
{
{'fraction_non_alphanumeric': 0.23984543493889288, 'fraction_numerical': 0.0065420560747663555, 'mean_word_length': 3.6588796784727458, 'pattern_counts': {'":': 2, '<': 272, '<?xml version=': 0, '>': 660, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6146329', 'n_tokens_mistral': 23940, 'n_tokens_neox': 21597, 'n_words': 4416}