<?php

	if (isset($_POST['cfms']))
	{
		$antiflood = DB :: $pdo -> querySingle("SELECT COUNT(*) FROM `{$table}` WHERE `id_user` = ? AND `time` > ?;", array($user['id'], time()-10));
		if (empty($antiflood)) {
		if (@$_POST['access'] == $user['access']){

		if ($imgc = @imagecreatefromstring(file_get_contents($_FILES['myFile']['tmp_name']))) {
		
		$name = system :: check($_FILES['myFile']['name']);

		$name = preg_replace('/(#|\?)/i', NULL, $name);
		$ras = strtolower(preg_replace('/^.*\./i', NULL, $name));
		$name = preg_replace('/\.[^\.]*$/i', NULL, $name); 
		$size = filesize($_FILES['myFile']['tmp_name']);
		$desc = $_POST['file_descr'];
		$img_x = imagesx($imgc);
		$img_y = imagesy($imgc);
		$PATH = system :: photosGetLink(false,$user['id']);
		system :: createDir(system :: $photosDir.$PATH);
		$lu = FILES_PATH.system :: $photosDir.$PATH;
		
		if ($_FILES['myFile']['size'] < 5000000) {	

		if ($ras!=NULL || $ras!=$name || preg_match("#^([A-z0-9\-\_\(\)\ ])+$#ui", $ras)){
		
		if ($img_y > 200 && $img_x > 200) {

			$key = rand(1000000, 10000000);

			$info = getimagesize($_FILES['myFile']['tmp_name']); 
			$width = $info[0];
			$height = $info[1];		
		
			$type = ".jpg";
			if(@imagejpeg($imgc, $_FILES['myFile']['tmp_name'])) {
			
			$image = new image;
			
			$timeu = time();

			$keyk = md5("photos://".$user['id']."/".$data['id']."/".$timeu."/".$key);
			
			// 1080
			if ($width > 1080 || $height > 1080) {
				$image->load($_FILES['myFile']['tmp_name']);	
				$image->preview($width,$height,1080);
				$image->save($lu.$keyk."_1080x".$type);	
			} else {
				$image->load($_FILES['myFile']['tmp_name']);		
				$image->save($lu.$keyk."_1080x".$type);	
			}	

			// 512
			if ($width > 512 || $height > 512) {
				$image->load($_FILES['myFile']['tmp_name']);	
				$image->preview($width,$height,512);
				$image->save($lu.$keyk."_512x".$type);	
			} else {
				$image->load($_FILES['myFile']['tmp_name']);		
				$image->save($lu.$keyk."_512x".$type);	
			}	

			// 256
			if ($width > 256 || $height > 256) {
				$image->load($_FILES['myFile']['tmp_name']);	
				$image->preview($width,$height,256);
				$image->save($lu.$keyk."_256x".$type);	
			} else {
				$image->load($_FILES['myFile']['tmp_name']);		
				$image->save($lu.$keyk."_256x".$type);	
			}	

			// Квадрат.
			$image->load($_FILES['myFile']['tmp_name']);	
			if($width != $height) {
				$image->preview2($width,$height,150);
				$image->crop(array(0,0,150,150));
			} else {
				$image->resize(150,150);
			}
			$image->save($lu.$keyk."_150x".$type);	

			// Фото 128x128
			if ($width > 128 || $height > 128) {
			$image->load($_FILES['myFile']['tmp_name']);	
			//$image->resize(128,128);	
			$image->preview($width,$height,128);	
			$image->save($lu.$keyk."_128x".$type);		
			} else {
			$image->load($_FILES['myFile']['tmp_name']);	
			$image->save($lu.$keyk."_128x".$type);		
			}	

			// Фото 64x64
			$image->load($_FILES['myFile']['tmp_name']);	
			if($width != $height) {
				$image->preview2($width,$height,64);	
				$image->crop(array(0,0,64,64));					
			} else {
				$image->resize(64,64);
			}
			$image->save($lu.$keyk."_64x".$type);	


			// default
			$image->load($_FILES['myFile']['tmp_name']);	
			$image->save($lu.$keyk.$type);
			$desc = mb_substr(system :: text($_POST['desc']), 0, 300,'UTF-8');
			DB :: $pdo -> query("INSERT INTO `{$table}` (`id_user`, `time`, `hash`, `id_album`, `size`, `width`, `height`,`desc`) VALUES (?,?,?,?,?,?,?,?);", array($user['id'], time(), $PATH.$keyk, $data['id'], $size, $width, $height, $desc));

			$id = DB :: $pdo -> lastInsertId();
			#------------NEW EVENTS------------#
			$EventsData = [
				'id_user' => $user['id'],
				'type' => 'photos',
				'id_type' => $user['id'],
				'data' => $id
			];
			Events::add($EventsData);
			#------------NEW EVENTS------------#
			DB :: $pdo -> query("UPDATE `users` SET `count_photos` = `count_photos`+1 WHERE `id` = ? LIMIT 1;", array($user['id']));
			DB :: $pdo -> query("UPDATE `{$table_a}` SET `count` = `count`+1, `last_photo` = ? WHERE `id` = ? LIMIT 1;", array($keyk, $data['id']));
			if($user['rait'] < '100'){DB::$pdo->query("UPDATE `users` SET `rait_us` ='".($user['rait_us'] + 0.02)."' WHERE `id` = '$user[id]' LIMIT 1");}




			if(AJAX) { die(json_encode(['link'=>$thisLink."{$user['id']}/view{$id}"])); }
			system::redirect("Фотография успешно добавлена.", $thisLink."{$user['id']}/view{$id}");
			exit();
			
			} else { $e = "Изображение имеет запрещенный формат."; }
		} else { $e = 'Слишком маленький размер фото, загружайте фото размером более чем 200х200.'; }
		} else { $e = 'Неверное расширение.'; }
		} else { $e = 'Выбранное вами фото имеет размер более 5 Мб.'; }
		} else { $e = 'Выбранный Вами формат изображения не поддерживается.'; }
		} else { $e = 'Вероятно вам подсунули эту ссылку.'; }
		} else { $e = 'Не так быстро'; }
		if(AJAX) { die(json_encode(['error'=>$e])); }
	}

	$back = system :: back("{$thisLink}{$data['id_user']}/album{$data['id']}", "Альбом");
	
	$title = "Фотографии - Добавление фотографии";
	$l = "Фотографии - Добавление фотографии";
	require (CORE.'head.php');

	system :: show($e);
	


	?>
	<div class="app-block">
	<form id="data-upload-form" method="post" enctype="multipart/form-data">
	<div class="list">
	<div id="data-upload-load">
	<label for="myFile"><div class="_center _gray">
		<?=language::text('textphoto', $language, 'photo');?>
	</div></label>
	<div>
	<input type="hidden" name="access" value="<?=$user['access']?>">
	<input name="myFile" type="file" id="myFile" accept="image/*">
	</div>
	</div>

	<div id="data-upload-file" style="display: none;">
			<div class="_font-s" style="margin-bottom: 10px;">
				<a prevent="1" href="#" class="_fl-r data-upload-cancel">Отменить</a>
				<span class="_bold _upper">Загрузка фотографии</span>
			</div>
			<div class="_m-top _oh">
			<div class="post-l">
				<div class="photos-upload-file-mini">
					
				</div>
			</div>
			<div class="post-c">
					<textarea placeholder="Введите описание к фотографии.." name="desc"></textarea>
			</div>
			</div>
			<div style="display: none;" class="photos-upload-file-progress"><div class="app-progress-bar"><span class="app-progress-bar">0%</span><div><span></span></div></div></div>

	</div>	
		<div style="margin-top: 15px;margin-bottom: 5px;" class="photos-upload-file-submit"><input type="submit" class="main-btn _w-100" name="cfms" value="Загрузить"></div>
		</div>
	</form>
	<?php

	echo $back;	
	echo "</div>";
	require (CORE.'foot.php');