<?php
class ControllerCommonFileManager extends Controller {

				private $dir_image = '';
				private $root_img_folder = '';
				private $http_img_folder = '';

				private $image_ext = array('gif', 'jpg', 'jpeg', 'png');
				private $image_mime = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif');

				private function initFoldersVariables() {
					$this->dir_image = realpath(DIR_IMAGE);
					$this->root_img_folder = realpath(DIR_IMAGE . 'catalog');
					$this->http_img_folder = HTTP_CATALOG . 'image/';
				}

				public function index() {
					$this->load->language('common/filemanager');

					$data['heading_title'] = $this->language->get('heading_title');

					$data['text_no_results'] = $this->language->get('text_no_results');
					$data['text_confirm'] = $this->language->get('text_confirm');

					$data['entry_search'] = $this->language->get('entry_search');
					$data['entry_folder'] = $this->language->get('entry_folder');

					$data['button_parent'] = $this->language->get('button_parent');
					$data['button_folder'] = $this->language->get('button_folder');

					$data['button_folder_refresh']   = $this->language->get('button_folder_refresh');
					$data['button_folder_delete']    = $this->language->get('button_folder_delete');

					$data['button_file_refresh']     = $this->language->get('button_file_refresh');
					$data['button_file_upload']      = $this->language->get('button_file_upload');
					$data['button_file_delete']      = $this->language->get('button_file_delete');

					$data['button_file_select']      = $this->language->get('button_file_select');
					$data['button_file_insert_img']  = $this->language->get('button_file_insert_img');
					$data['button_file_insert_link'] = $this->language->get('button_file_insert_link');
					$data['button_file_download']    = $this->language->get('button_file_download');
					$data['button_file_copy_url']    = $this->language->get('button_file_copy_url');

					// de onde veio a requisição para abrir o gerenciador de arquivos
					// - vazio = apenas gerenciador de arquivos (link direto)
					// - editor = editor de textos (summernote)
					// - image = botões para escolha de imagens
					if (isset($this->request->get['type'])) {
						$data['type'] = $this->request->get['type'];
					} else {
						$data['type'] = '';
					}

					// Return the target ID for the file manager to set the value
					if (isset($this->request->get['target'])) {
						$data['target'] = $this->request->get['target'];
					} else {
						$data['target'] = '';
					}

					// Return the thumbnail for the file manager to show a thumbnail
					if (isset($this->request->get['thumb'])) {
						$data['thumb'] = $this->request->get['thumb'];
					} else {
						$data['thumb'] = '';
					}

					$data['token'] = $this->session->data['token'];

					$data['folders'] = $this->get_folders();

					$data['is_ajax'] = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && mb_strtolower($_SERVER['HTTP_X_REQUESTED_WITH'], 'UTF-8') == 'xmlhttprequest';

					if (!$data['is_ajax']) {
						$this->document->setTitle($this->language->get('heading_title'));

						$data['breadcrumbs'] = array();

						$data['breadcrumbs'][] = array(
							'text' => $this->language->get('text_home'),
							'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
						);

						$data['breadcrumbs'][] = array(
							'text' => $this->language->get('heading_title'),
							'href' => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'], 'SSL')
						);

						$data['header'] = $this->load->controller('common/header');
						$data['column_left'] = $this->load->controller('common/column_left');
						$data['footer'] = $this->load->controller('common/footer');
					}

					$this->response->setOutput($this->load->view('common/filemanager_hdw.tpl', $data));
				}

				public function folders() {
					$this->response->addHeader('Content-Type: application/json');
					$this->response->setOutput( $this->get_folders() );
				}

				public function files() {
					$json = array();

					$directory = isset($this->request->request['directory']) ? trim($this->request->request['directory']) : '';
					$directory = $this->sanitizeAndExpandRelativePath($directory);

					if ($directory === false || !is_dir($directory)) {
						$json['error'] = true;
					}

					if (!$json) {
						$files = glob($directory . '/*');

						if ($files) {
							$this->load->model('tool/image');

							$this->initFoldersVariables();

							$allowed_ext = $this->getAllowedExt();

							foreach ($files as $file) {
								$file = realpath($file);

								if (!is_file($file)) {
									continue;
								}

								$pathinfo = pathinfo($file);

								$path = str_replace(DIRECTORY_SEPARATOR, '/', trim(str_replace($this->dir_image, '', $file), DIRECTORY_SEPARATOR));
								$href = $this->http_img_folder . $path;
								$name = $pathinfo['basename'];
								$size = $this->getFileSize($file);
								$extension = isset($pathinfo['extension']) ? mb_strtolower($pathinfo['extension'], 'UTF-8') : '';

								if (!in_array($extension, $allowed_ext)) {
									continue;
								}

								if (in_array($extension, $this->image_ext)) {
									$thumb = $this->model_tool_image->resize($path, 100, 100);

								} else {
									$thumb = "file_icons/{$extension}.png";

									if (!file_exists(DIR_IMAGE . $thumb)) {
										$thumb = 'file_icons/default.png';
									}

									$thumb = $this->model_tool_image->resize($thumb, 100, 100);
								}

								$json[] = array(
									'file'  => utf8_encode($path),
									'href'  => utf8_encode($href),
									'name'  => utf8_encode($name),
									'size'  => $size,
									'thumb' => utf8_encode($thumb)
								);
							}

							$sort = array();
							foreach ($json as $k => $v) {
								$sort[$k] = mb_strtolower($v['name'], 'UTF-8');
							}
							array_multisort($sort, SORT_ASC, SORT_STRING, $json);

						} else {
							$json['empty'] = true;
						}
					}

					$this->response->addHeader('Content-Type: application/json');
					$this->response->setOutput(json_encode($json));
				}

				public function download() {
					$error = false;

					$file = isset($this->request->request['file']) ? trim($this->request->request['file']) : '';
					$file = $this->sanitizeAndExpandRelativePath($file);

					if ($file === false || !is_file($file)) {
						$error = true;
					}

					if ($error) {
						$this->response->redirect($this->url->link('error/not_found', '', 'SSL'));
					}

					header('Content-Description: File Transfer');
					header('Content-Type: application/octet-stream');
					header('Content-Disposition: attachment; filename="'.basename($file).'"');
					header('Expires: 0');
					header('Cache-Control: must-revalidate');
					header('Pragma: public');
					header('Content-Length: ' . filesize($file));
					readfile($file);
				}

				public function upload() {
					$this->load->language('common/filemanager');

					$json = array();

					// Check user has permission
					if (!$this->user->hasPermission('modify', 'common/filemanager')) {
						$json['error'] = $this->language->get('error_permission');
					}

					$directory = isset($this->request->request['directory']) ? trim($this->request->request['directory']) : '';
					$directory = $this->sanitizeAndExpandRelativePath($directory);

					if ($directory === false || !is_dir($directory)) {
						$json['error'] = $this->language->get('error_directory');
					}

					if (!$json) {
						if (count($this->request->files['files'])) {
							$error = array();
							$success = array();

							$allowed_ext = $this->getAllowedExt();
							$allowed_mime = $this->getAllowedMime();

							foreach ($this->request->files['files']['name'] as $key => $value) {
								$file_name     = $this->request->files['files']['name'][$key];
								$file_tmp_name = $this->request->files['files']['tmp_name'][$key];
								$file_type     = $this->request->files['files']['type'][$key];
								$file_error    = $this->request->files['files']['error'][$key];
								$file_size     = $this->request->files['files']['size'][$key];

								if (!empty($file_name) && is_file($file_tmp_name)) {
									// Return any upload error
									if ($file_error != UPLOAD_ERR_OK) {
										$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_upload_' . $file_error);
										continue;
									}

									// Sanitize the filename
									$filename = html_entity_decode($file_name, ENT_QUOTES, 'UTF-8');

									$pathinfo = pathinfo($filename);
									$filename = $pathinfo['basename'];
									$extension = isset($pathinfo['extension']) ? mb_strtolower($pathinfo['extension'], 'UTF-8') : '';

									// Validate the filename length
									if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
										$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_filename');
										continue;
									}

									// Allowed file extension types
									if (!in_array($extension, $allowed_ext)) {
										$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_filetype');
										continue;
									}

									// Allowed file mime types
									if (!in_array($file_type, $allowed_mime)) {
										$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_filetype');
										continue;
									}

									// Check to see if any PHP files are trying to be uploaded
									$content = file_get_contents($file_tmp_name);

									if (preg_match('/\<\?php/i', $content)) {
										$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_filetype');
										continue;
									}

									if ($this->is_image($file_tmp_name)) {
										if ($file_size > 1024 * 1024 * 1) {
											$error[] = '<strong>'. $file_name .' ('. number_format($file_size / 1024 /1024, 2, ',', '.') .'MB):</strong><br>'. 'Para evitar problemas de performance e travamentos, não são permitidos arquivos de imagem maiores que 1MB e/ou com dimensões maiores que 2560 x 2560 pixels. Por favor, salve os arquivos com tamanho e dimensões permitidas e tente novamente.';
											continue;
										}

										$info = getimagesize($file_tmp_name);
										$width  = $info[0];
										$height = $info[1];

										if ($width > 2560 || $height > 2560) {
											$error[] = '<strong>'. $file_name .' ('.$width.' x '.$height.' pixels):</strong><br>'. 'Para evitar problemas de performance e travamentos, não são permitidos arquivos de imagem maiores que 1MB e/ou com dimensões maiores que 2560 x 2560 pixels. Por favor, salve os arquivos com tamanho e dimensões permitidas e tente novamente.';
											continue;
										}
									}
								} else {
									$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_upload');
									continue;
								}

								$filename = $this->getNewFilename($directory, $filename);

								if (@move_uploaded_file($file_tmp_name, $directory . '/' . $filename)) {
									$this->resize($directory . '/' . $filename);

									$success[] = $filename;
								} else {
									$error[] = '<strong>'. $file_name .':</strong><br>'. $this->language->get('error_upload');
								}

							} // foreach

							if ($error) {
								$total = count($error);
								$json['error'] = 'Ops... '. ($total > 1 ? "ocorreram {$total} erros" : 'ocorreu 1 erro') .' durante o envio!<br><br>- '. implode('<br><br>- ', $error);
							}

							if ($success) {
								$total = count($success);
								$json['success'] = $total .' '. ($total > 1 ? 'arquivos enviados' : 'arquivo enviado') .' com sucesso!<br><br>- '. implode('<br>- ', $success);
							}
						} else {
							$json['error'] = $this->language->get('error_upload');
						}
					}

					$this->response->addHeader('Content-Type: application/json');
					$this->response->setOutput(json_encode($json));
				}

				public function new_folder() {
					$this->load->language('common/filemanager');

					$json = array();

					// Check user has permission
					if (!$this->user->hasPermission('modify', 'common/filemanager')) {
						$json['error'] = $this->language->get('error_permission');
					}

					$directory = isset($this->request->request['directory']) ? trim($this->request->request['directory']) : '';
					$directory = $this->sanitizeAndExpandRelativePath($directory);

					if ($directory === false || !is_dir($directory)) {
						$json['error'] = $this->language->get('error_directory');
					}

					if (!$json) {
						// Sanitize the folder name
						$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));
						$folder = $this->sanitizeFilename($folder);

						// Validate the filename length
						if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
							$json['error'] = $this->language->get('error_folder');
						} else

						// Check if directory already exists or not
						if (is_dir($directory . DIRECTORY_SEPARATOR . $folder)) {
							$json['error'] = $this->language->get('error_exists');
						}
					}

					if (!$json) {
						mkdir($directory . DIRECTORY_SEPARATOR . $folder, 0777);

						$json['success'] = $this->language->get('text_directory');
					}

					$this->response->addHeader('Content-Type: application/json');
					$this->response->setOutput(json_encode($json));
				}

				public function delete_folder() {
					$this->load->language('common/filemanager');

					$json = array();

					// Check user has permission
					if (!$this->user->hasPermission('modify', 'common/filemanager')) {
						$json['error'] = $this->language->get('error_permission');
					}

					$directory = isset($this->request->request['directory']) ? trim($this->request->request['directory']) : '';
					$directory = $this->sanitizeAndExpandRelativePath($directory);

					if ($directory === false || !is_dir($directory)) {
						$json['error'] = $this->language->get('error_directory');
					}

					$this->initFoldersVariables();

					// não permite excluir a pasta raiz
					if ($directory == $this->root_img_folder) {
						$json['error'] = $this->language->get('error_delete');
					}

					if (!$json) {
						$files = array($directory);

						// Make path into an array
						$path = array($directory . '/*');

						// While the path array is still populated keep looping through
						while (count($path) != 0) {
							$next = array_shift($path);

							foreach (glob($next) as $file) {
								// If directory add to path array
								if (is_dir($file)) {
									$path[] = $file . '/*';
								}

								// Add the file to the files to be deleted array
								$files[] = $file;
							}
						}

						// Reverse sort the file array
						rsort($files);

						foreach ($files as $file) {
							// If file just delete
							if (is_file($file)) {
								unlink($file);

							// If directory use the remove directory function
							} elseif (is_dir($file)) {
								rmdir($file);
							}
						}

						$json['success'] = $this->language->get('text_delete');
					}

					$this->response->addHeader('Content-Type: application/json');
					$this->response->setOutput(json_encode($json));
				}

				private function get_folders() {
					$this->initFoldersVariables();

					$folders = array();
					$folders[] = $this->foldersToArray($this->root_img_folder);
					$folders = json_encode($folders);

					return $folders;
				}

				private function foldersToArray($source) {
					$source = realpath($source);
					$folders = scandir($source);

					if (!is_array($folders)) { return FALSE; }

					$path = trim(str_replace($this->dir_image, '', $source), DIRECTORY_SEPARATOR);
					$href = $this->http_img_folder . $path;
					$name = basename($source);

					$return = array();
					$return['id'] = md5($path);
					$return['path'] = $path;
					// $return['href'] = $href;
					$return['text'] = $name;

					$nodes = array();

					foreach ($folders as $folder) {
						// remove as pastas ./ e ../
						if ($folder == '.' || $folder == '..') { continue; }

						$realpath = realpath($source . DIRECTORY_SEPARATOR . $folder);

						if (is_dir($realpath)) {
							$tmp = $this->foldersToArray($realpath);

							if (is_array($tmp)) {
								$nodes[] = $tmp;
							}

						}
					}

					if (count($nodes) > 0) {
						$return['nodes'] = $nodes;
					}

					return $return;
				}

				private function getFileSize($file) {
					$suffix = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

					$size = filesize($file);

					$i = 0;
					while (($size / 1024) > 1) {
						$size = $size / 1024;
						$i++;
					}

					// return round(utf8_substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i];
					return round($size, 2) . $suffix[$i];
				}

				private function getAllowedExt() {
					$allowed_ext = mb_strtolower($this->config->get('config_file_ext_allowed'), 'UTF-8');
					$allowed_ext = preg_replace('/[ \r\n\t]+/', ',', $allowed_ext);
					$allowed_ext = explode(',', $allowed_ext);

					$allowed_ext = array_filter($allowed_ext);
					$allowed_ext = array_merge($allowed_ext, $this->image_ext);
					$allowed_ext = array_unique($allowed_ext);

					return $allowed_ext;
				}

				private function getAllowedMime() {
					$allowed_mime = mb_strtolower($this->config->get('config_file_mime_allowed'), 'UTF-8');
					$allowed_mime = preg_replace('/[ \r\n\t]+/', ',', $allowed_mime);
					$allowed_mime = explode(',', $allowed_mime);

					$allowed_mime = array_filter($allowed_mime);
					$allowed_mime = array_merge($allowed_mime, $this->image_mime);
					$allowed_mime = array_unique($allowed_mime);

					return $allowed_mime;
				}

				private function getNewFilename($directory, $filename) {
					$pathinfo = pathinfo($filename);
					$extension = isset($pathinfo['extension']) ? '.' . mb_strtolower($pathinfo['extension'], 'UTF-8') : '';
					$filename = mb_strtolower($pathinfo['filename'], 'UTF-8');

					$filename = $this->sanitizeFilename($filename);

					if ($filename == '') {
						$filename == 'sem-titulo';
					}

					if (utf8_strlen($filename) > 200) {
						$filename = substr($filename, 0, 200);
					}

					while (file_exists($directory . DIRECTORY_SEPARATOR . $filename . $extension)) {
						$filename = $this->increment_string($filename, '-');
					}

					$filename .= $extension;

					return $filename;
				}

				private function sanitizeAndExpandRelativePath($path) {
					if ($path == '') {
						$path = false;

					} else {
						// remove nomes de pastas não permitidos
						$path = preg_replace('/([\/\\\\]+[\/\\\\]?)+/', '/', $path);
						$path = trim(str_replace(array('../', '..\\', '..', './', '.\\'), '', $path), '\/');

						// remove a primeira pasta que deve obrigatoriamente ser 'catalog'
						$path = preg_replace('/^catalog[\/\\\\]?/i', '', $path);

						// busca o caminho real completo
						$path = realpath(DIR_IMAGE . 'catalog/' . $path);
					}

					return $path;
				}

				private function sanitizeFilename($filename) {
					$filename = $this->convert_accented_characters($filename);
					$filename = $this->url_title($filename, 'dash', TRUE);

					$filename = preg_replace('/[^a-z0-9_-]/', '',  $filename); //remove caracteres nao normais
					$filename = preg_replace('/_+/',		  '-', $filename); //substitui _ por -
					$filename = preg_replace('/-+/',		  '-', $filename); //substitui multiplos --- por apenas um -

					$filename = trim($filename, '-');
					$filename = trim($filename);

					return $filename;
				}

				private function convert_accented_characters($str) {
					$foreign_characters = array(
						'/ä|æ|ǽ/' => 'ae',
						'/ö|œ/' => 'oe',
						'/ü/' => 'ue',
						'/Ä/' => 'Ae',
						'/Ü/' => 'Ue',
						'/Ö/' => 'Oe',
						'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
						'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
						'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
						'/ç|ć|ĉ|ċ|č/' => 'c',
						'/Ð|Ď|Đ/' => 'D',
						'/ð|ď|đ/' => 'd',
						'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
						'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
						'/Ĝ|Ğ|Ġ|Ģ/' => 'G',
						'/ĝ|ğ|ġ|ģ/' => 'g',
						'/Ĥ|Ħ/' => 'H',
						'/ĥ|ħ/' => 'h',
						'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I',
						'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i',
						'/Ĵ/' => 'J',
						'/ĵ/' => 'j',
						'/Ķ/' => 'K',
						'/ķ/' => 'k',
						'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
						'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
						'/Ñ|Ń|Ņ|Ň/' => 'N',
						'/ñ|ń|ņ|ň|ŉ/' => 'n',
						'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
						'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
						'/Ŕ|Ŗ|Ř/' => 'R',
						'/ŕ|ŗ|ř/' => 'r',
						'/Ś|Ŝ|Ş|Š/' => 'S',
						'/ś|ŝ|ş|š|ſ/' => 's',
						'/Ţ|Ť|Ŧ/' => 'T',
						'/ţ|ť|ŧ/' => 't',
						'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
						'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
						'/Ý|Ÿ|Ŷ/' => 'Y',
						'/ý|ÿ|ŷ/' => 'y',
						'/Ŵ/' => 'W',
						'/ŵ/' => 'w',
						'/Ź|Ż|Ž/' => 'Z',
						'/ź|ż|ž/' => 'z',
						'/Æ|Ǽ/' => 'AE',
						'/ß/'=> 'ss',
						'/Ĳ/' => 'IJ',
						'/ĳ/' => 'ij',
						'/Œ/' => 'OE',
						'/ƒ/' => 'f',
						'/¹/' => '1',
						'/²/' => '2',
						'/³/' => '3'
					);

					return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str);
				}

				private function url_title($str, $separator = 'dash', $lowercase = TRUE)
				{
					if ($separator == 'dash')
					{
						$search		= '_';
						$replace	= '-';
					}
					else
					{
						$search		= '-';
						$replace	= '_';
					}

					$trans = array(
									'&\#\d+?;'				=> '',
									'&\S+?;'				=> '',
									'\s+'					=> $replace,
									'[^a-z0-9\-\._]'		=> '',
									$replace.'+'			=> $replace,
									$replace.'$'			=> $replace,
									'^'.$replace			=> $replace,
									'\.+$'					=> ''
								);

					$str = strip_tags($str);

					foreach ($trans as $key => $val)
					{
						$str = preg_replace("#".$key."#i", $val, $str);
					}

					if ($lowercase === TRUE)
					{
						$str = mb_strtolower($str, 'UTF-8');
					}

					return trim(stripslashes($str));
				}

				private function increment_string($str, $separator = '_', $first = 1)
				{
					preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);

					return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
				}

				private function is_image($file) {
					$pathinfo = pathinfo($file);
					$extension = isset($pathinfo['extension']) ? mb_strtolower($pathinfo['extension'], 'UTF-8') : '';

					if (in_array($extension, $this->image_ext)) {
						return true;
					}

					if (function_exists('finfo_open')) {
						$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
						$mimetype = mb_strtolower(finfo_file($finfo, $file), 'UTF-8');
						finfo_close($finfo);
					} elseif (function_exists('mime_content_type')) {
						$mimetype = mb_strtolower(@mime_content_type($file), 'UTF-8');
					} else {
						$mimetype = '';
					}

					if (in_array($mimetype, $this->image_mime)) {
						return true;
					}

					return false;
				}

				private function resize($file, $max_width = 2560, $max_height = 2560, $quality = 70) {
					if (!$this->is_image($file)) {
						return;
					}

					$info = getimagesize($file);
					$width  = $info[0];
					$height = $info[1];

					if ($width == 0 || $height == 0) {
						return;
					}

					$scale = min($max_width / $width, $max_height / $height);

					if ($scale >= 1) {
						return;
					}

					$new_width = (int)($width * $scale);
					$new_height = (int)($height * $scale);

					$image = new Image($file);
					$image->resize($new_width, $new_height);
					$image->save($file, $quality);
				}










			
	public function index_OLD() {
		$this->load->language('common/filemanager');

		if (isset($this->request->get['filter_name'])) {
			$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
		} else {
			$filter_name = null;
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['images'] = array();

		$this->load->model('tool/image');

		// Get directories
		$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);

		if (!$directories) {
			$directories = array();
		}

		// Get files
		$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);

		if (!$files) {
			$files = array();
		}

		// Merge directories and files
		$images = array_merge($directories, $files);

		// Get total number of files and directories
		$image_total = count($images);

		// Split the array based on current page number and max number of items per page of 10
		$images = array_splice($images, ($page - 1) * 16, 16);

		foreach ($images as $image) {
			$name = str_split(basename($image), 14);

			if (is_dir($image)) {
				$url = '';

				if (isset($this->request->get['target'])) {
					$url .= '&target=' . $this->request->get['target'];
				}

				if (isset($this->request->get['thumb'])) {
					$url .= '&thumb=' . $this->request->get['thumb'];
				}

				$data['images'][] = array(
					'thumb' => '',
					'name'  => implode(' ', $name),
					'type'  => 'directory',
					'path'  => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
					'href'  => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, 'SSL')
				);
			} elseif (is_file($image)) {
				// Find which protocol to use to pass the full image link back
				if ($this->request->server['HTTPS']) {
					$server = HTTPS_CATALOG;
				} else {
					$server = HTTP_CATALOG;
				}

				$data['images'][] = array(
					'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
					'name'  => implode(' ', $name),
					'type'  => 'image',
					'path'  => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
					'href'  => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
				);
			}
		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['entry_search'] = $this->language->get('entry_search');
		$data['entry_folder'] = $this->language->get('entry_folder');

		$data['button_parent'] = $this->language->get('button_parent');
		$data['button_refresh'] = $this->language->get('button_refresh');
		$data['button_upload'] = $this->language->get('button_upload');
		$data['button_folder'] = $this->language->get('button_folder');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_search'] = $this->language->get('button_search');

		$data['token'] = $this->session->data['token'];

		if (isset($this->request->get['directory'])) {
			$data['directory'] = urlencode($this->request->get['directory']);
		} else {
			$data['directory'] = '';
		}

		if (isset($this->request->get['filter_name'])) {
			$data['filter_name'] = $this->request->get['filter_name'];
		} else {
			$data['filter_name'] = '';
		}

		// Return the target ID for the file manager to set the value
		if (isset($this->request->get['target'])) {
			$data['target'] = $this->request->get['target'];
		} else {
			$data['target'] = '';
		}

		// Return the thumbnail for the file manager to show a thumbnail
		if (isset($this->request->get['thumb'])) {
			$data['thumb'] = $this->request->get['thumb'];
		} else {
			$data['thumb'] = '';
		}

		// Parent
		$url = '';

		if (isset($this->request->get['directory'])) {
			$pos = strrpos($this->request->get['directory'], '/');

			if ($pos) {
				$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
			}
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, 'SSL');

		// Refresh
		$url = '';

		if (isset($this->request->get['directory'])) {
			$url .= '&directory=' . urlencode($this->request->get['directory']);
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['directory'])) {
			$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['target'])) {
			$url .= '&target=' . $this->request->get['target'];
		}

		if (isset($this->request->get['thumb'])) {
			$url .= '&thumb=' . $this->request->get['thumb'];
		}

		$pagination = new Pagination();
		$pagination->total = $image_total;
		$pagination->page = $page;
		$pagination->limit = 16;
		$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$this->response->setOutput($this->load->view('common/filemanager.tpl', $data));
	}

	public function upload_OLD() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		// Check its a directory
		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
				// Sanitize the filename
				$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));

				// Validate the filename length
				if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
					$json['error'] = $this->language->get('error_filename');
				}

				// Allowed file extension types
				$allowed = array(
					'jpg',
					'jpeg',
					'gif',
					'png'
				);

				if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Allowed file mime types
				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/png',
					'image/x-png',
					'image/gif'
				);

				if (!in_array($this->request->files['file']['type'], $allowed)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Check to see if any PHP files are trying to be uploaded
				$content = file_get_contents($this->request->files['file']['tmp_name']);

				if (preg_match('/\<\?php/i', $content)) {
					$json['error'] = $this->language->get('error_filetype');
				}

				// Return any upload error
				if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
				}
			} else {
				$json['error'] = $this->language->get('error_upload');
			}
		}

		if (!$json) {
			move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);

			$json['success'] = $this->language->get('text_uploaded');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function folder() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Make sure we have the correct directory
		if (isset($this->request->get['directory'])) {
			$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
		} else {
			$directory = DIR_IMAGE . 'catalog';
		}

		// Check its a directory
		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			// Sanitize the folder name
			$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));

			// Validate the filename length
			if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
				$json['error'] = $this->language->get('error_folder');
			}

			// Check if directory already exists or not
			if (is_dir($directory . '/' . $folder)) {
				$json['error'] = $this->language->get('error_exists');
			}
		}

		if (!$json) {
			mkdir($directory . '/' . $folder, 0777);

			$json['success'] = $this->language->get('text_directory');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function delete() {
		$this->load->language('common/filemanager');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
			$json['error'] = $this->language->get('error_permission');
		}

		if (isset($this->request->post['path'])) {
			$paths = $this->request->post['path'];
		} else {
			$paths = array();
		}

		// Loop through each path to run validations
		foreach ($paths as $path) {
			$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');

			// Check path exsists
			if ($path == DIR_IMAGE . 'catalog') {
				$json['error'] = $this->language->get('error_delete');

				break;
			}
		}

		if (!$json) {
			// Loop through each path
			foreach ($paths as $path) {
				$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');

				// If path is just a file delete it
				if (is_file($path)) {
					unlink($path);

				// If path is a directory beging deleting each file and sub folder
				} elseif (is_dir($path)) {
					$files = array();

					// Make path into an array
					$path = array($path . '*');

					// While the path array is still populated keep looping through
					while (count($path) != 0) {
						$next = array_shift($path);

						foreach (glob($next) as $file) {
							// If directory add to path array
							if (is_dir($file)) {
								$path[] = $file . '/*';
							}

							// Add the file to the files to be deleted array
							$files[] = $file;
						}
					}

					// Reverse sort the file array
					rsort($files);

					foreach ($files as $file) {
						// If file just delete
						if (is_file($file)) {
							unlink($file);

						// If directory use the remove directory function
						} elseif (is_dir($file)) {
							rmdir($file);
						}
					}
				}
			}

			$json['success'] = $this->language->get('text_delete');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}