View file application/system/library/class.uploads.php

File size: 7.51Kb
<?PHP
	class Uploads {
		public $allowedMimeTypes = [
			/* Картинки */
			'image/jpeg',																			/* JPEG / JPG */
			'image/png',																			/* PNG */
			'image/gif',																			/* GIF */
			'image/webp',																			/* WEBP */
			
			/* Видео */
			'video/mp4',																			/* MP4 */
			'video/avi',																			/* AVI */
			'video/webm',																			/* WEBM */
			'video/mpeg',																			/* MPEG */
			
			/* Документы */
			'application/vnd.openxmlformats-officedocument.wordprocessingml.document',				/* Word */
			'application/msword',																	/* Word */
			'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',					/* Excel */
			'application/vnd.ms-excel',																/* Excel */
			'application/vnd.ms-powerpoint',														/* PPT */
			'application/vnd.openxmlformats-officedocument.presentationml.presentation',			/* PPTX */
			'application/atom+xml',																	/* XML */
			'application/xml',																		/* XML */
			'text/plain',																			/* TXT */
			'application/pdf',																		/* PDF */
			'application/java-archive',																/* JAR */
			
			/* Архивы */
			'application/zip',																		/* ZIP */
			'application/vnd.rar',																	/* RAR */
			'application/x-rar-compressed',															/* RAR */
			'application/octet-stream',																/* RAR */
			'application/x-7z-compressed',															/* 7z */
			'application/x-tar',																	/* TAR */
			'application/gzip'																		/* gZIP */
		];
		
		/*
			Загрузка документа на сервере
		*/
		public function Start(array $Files = [], $peerid = null) {
			try {
				/* Разрешенные форматы */
				$allowedMimeTypes = $this->allowedMimeTypes;
				
				$uploadMaxSize = ini_get('upload_max_filesize');
				$uploadMaxSizeBytes = return_bytes($uploadMaxSize);
				
				/* Выполняем загрузку на сервер  */
				foreach($Files['files']['name'] as $key => $name) {
					$uploadedFileType = mime_content_type($Files['files']['tmp_name'][$key]);
					
					if(!in_array($uploadedFileType, $allowedMimeTypes)) {
						throw new Exception(getLang('uploads_expansion'));
					}
					
					if($Files['files']['size'][$key] > $uploadMaxSizeBytes) {
						$endMessage = getLang('uploads_size');
					}
					
					$uploadDirectory = '/public/uploads/' . $_SESSION['id'] . '/';
					
					if(!is_dir($_SERVER['DOCUMENT_ROOT'] . $uploadDirectory)) {
						mkdir($_SERVER['DOCUMENT_ROOT'] . $uploadDirectory);
					}
					
					$fileExtension = pathinfo($Files['files']['name'][$key], PATHINFO_EXTENSION);
					$uniqueFileName = uniqid() . '_' . rand(1000, 99999) . '.' . $fileExtension;
					$fullPath = $uploadDirectory . $uniqueFileName;
					
					if(move_uploaded_file($Files['files']['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT'] . $fullPath)) {
						if(is_array($peerid)) {
							for($i = 0; $i < count($peerid); $i++) {
								$this->Add(
									$peerid[$i],
									$Files['files']['name'][$key],
									$Files['files']['type'][$key],
									$fullPath,
									$Files['files']['size'][$key]
								);
							}
						}
						else {
							$this->Add(
								$peerid,
								$Files['files']['name'][$key],
								$Files['files']['type'][$key],
								$fullPath,
								$Files['files']['size'][$key]
							);
						}
					}
				}
				
				if(isset($endMessage)) {
					return $endMessage;
				}
				
				return true;
			}
			catch(Exception $e) {
				throw new Exception($e->getMessage());
			}
		}
		
		/*
			Занесение сведений в базу
		*/
		public function Add($peerid, $name, $type, $path, $size) {
			try {
				$Messages = new Messages;
				
				$sth = pdo()->prepare('INSERT INTO `messages__files`(`userid`, `peerid`, `name`, `type`, `path`, `size`, `date`) VALUES (:userid, :peerid, :name, :type, :path, :size, :date)');
				$sth->execute([
					':userid' => $_SESSION['id'],
					':peerid' => $peerid,
					':name' => $name,
					':type' => $type,
					':path' => $path,
					':size' => formatFileSize($size),
					':date' => time()
				]);
				
				return $Messages->fileSend($peerid, pdo()->lastInsertId());
			}
			catch(Exception $e) {
				throw new Exception($e->getMessage());
			}
		}
		
		/*
			Получение визуального файла для сообщения
		*/
		public function getVisual($fileid, $peerid) {
			try {
				if($this->isValid($fileid, $peerid)) {
					$sth = pdo()->prepare('SELECT * FROM `messages__files` WHERE `id`=:id LIMIT 1');
					$sth->execute([':id' => $fileid]);
					
					if(!$sth->rowCount()) {
						return getLang('uploads_deleted');
					}
					
					$File = $sth->fetch(PDO::FETCH_OBJ);
					
					$imagesMimeTypes = [
						'image/jpeg',
						'image/png',
						'image/gif',
						'image/webp'
					];
					
					$videoMimeTypes = [
						'video/mp4',
						'video/avi'
					];
					
					$docMimeTypes = [
						'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
						'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
					];
					
					$tpl = new Template;
					
					if(in_array($File->type, $imagesMimeTypes)) {
						$temp = $tpl->Get('elements/clippaper/image');
					}
					elseif(in_array($File->type, $videoMimeTypes)) {
						$temp = $tpl->Get('elements/clippaper/video');
					}
					elseif(in_array($File->type, $docMimeTypes)) {
						$temp = $tpl->Get('elements/clippaper/docs');
					}
					else {
						$temp = $tpl->Get('elements/clippaper/other');
					}
					
					$tpl->AddCell('ClipPaper', $tpl->Set([
						'{id}' => $File->id,
						'{userid}' => $File->userid,
						'{name}' => $File->name,
						'{path}' => $File->path,
						'{type}' => $File->type,
						'{size}' => $File->size
					], $temp));
					
					return $tpl->Execute($tpl->GetCell('ClipPaper'));
				}
				else {
					return '';
				}
			}
			catch(Exception $e) {
				return $e->getMessage();
			}
		}
		
		/*
			Проверка валидности сообщения
		*/
		public function isValid($fileid, $peerid) {
			try {
				$sth = pdo()->prepare('SELECT * FROM `messages` WHERE `fileid`=:fileid LIMIT 1');
				$sth->execute([
					':fileid' => $fileid
				]);
				
				if($sth->rowCount()) {
					$Message = $sth->fetch(PDO::FETCH_OBJ);
					$ossl = new OSSL($_SERVER['SERVER_NAME'] . $peerid);
					$decrypt = $ossl->Decrypt($Message->cipher_text, $Message->tag, $Message->iv);
					
					if($decrypt) {
						return true;
					}
				}
				
				return false;
			}
			catch(Exception $e) {
				return false;
			}
		}
		
		/*
			Список разрешенного формата
		*/
		public function AcceptList() {
			$iLast = count($this->allowedMimeTypes) - 1;
			$lists = '';
			
			for($i = 0; $i < count($this->allowedMimeTypes); $i++) {
				if($i == $iLast) {
					$lists .= $this->allowedMimeTypes[$i];
				}
				else {
					$lists .= $this->allowedMimeTypes[$i] . ', ';
				}
			}
			
			return $lists;
		}
		
		/*
			Количество загруженных сообщений
		*/
		public function rowUserFiles($userid) {
			try {
				$sth = pdo()->prepare('SELECT * FROM `messages__files` WHERE `userid`=:userid');
				$sth->execute([
					':userid' => $userid
				]);
				
				return $sth->rowCount();
			}
			catch(Exception $e) {
				return 0;
			}
		}
	}