diff --git a/connectors/php/filemanager.class.php b/connectors/php/filemanager.class.php index 5923196c..b936f199 100755 --- a/connectors/php/filemanager.class.php +++ b/connectors/php/filemanager.class.php @@ -1,3 +1,888 @@ +<<<<<<< HEAD + + * @author Simon Georget + * @copyright Authors + */ + +class Filemanager { + + protected $config = array(); + protected $language = array(); + protected $get = array(); + protected $post = array(); + protected $properties = array(); + protected $item = array(); + protected $languages = array(); + protected $root = ''; + protected $doc_root = ''; + protected $dynamic_fileroot = ''; + protected $logger = false; + protected $logfile = '/tmp/filemanager.log'; + protected $cachefolder = '_thumbs/'; + protected $thumbnail_width = 64; + protected $thumbnail_height = 64; + protected $separator = 'userfiles'; // @todo fix keep it or not? + + public function __construct($extraConfig = '') { + + $content = file_get_contents("../../scripts/filemanager.config.js"); + $config = json_decode($content, true); + + $this->config = $config; + + // override config options if needed + if(!empty($extraConfig)) { + $this->setup($extraConfig); + } + + $this->root = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR; + $this->properties = array( + 'Date Created'=>null, + 'Date Modified'=>null, + 'Height'=>null, + 'Width'=>null, + 'Size'=>null + ); + + // Log actions or not? + if ($this->config['options']['logger'] == true ) { + if(isset($this->config['options']['logfile'])) { + $this->logfile = $this->config['options']['logfile']; + } + $this->enableLog(); + } + + // if fileRoot is set manually, $this->doc_root takes fileRoot value + // for security check in isValidPath() method + // else it takes $_SERVER['DOCUMENT_ROOT'] default value + if ($this->config['options']['fileRoot'] !== false ) { + if($this->config['options']['serverRoot'] === true) { + // $this->doc_root = $_SERVER['DOCUMENT_ROOT']; + // global $sys; + if (substr_count($_SERVER['HTTP_HOST'], "ca-dev") > 0 OR $_SERVER['HTTP_HOST'] == 'localhost' OR substr_count($_SERVER['HTTP_HOST'], 'localhost.enguehard.info') > 0) { + $tab = explode('.', $_SERVER['SERVER_NAME']); + if ($_SERVER['HTTP_HOST'] == 'localhost') { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'../'; + } else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"].$tab[0].'/www'; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].$tab[0]; + } + $sys['env'] = 'dev'; + } else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'/../'; + $sys['env'] = 'prod'; + } + $this->doc_root = $sys['base_dir']; + $this->separator = basename($this->config['options']['fileRoot']); + } else { + $this->doc_root = $this->config['options']['fileRoot']; + $this->separator = basename($this->config['options']['fileRoot']); + } + } else { + $this->doc_root = $_SERVER['DOCUMENT_ROOT']; + } + + $this->__log(__METHOD__.' $this->doc_root value ' . $this->doc_root); + $this->__log(__METHOD__.' $this->separator value ' . $this->separator); + $this->__log(__METHOD__.' $this->config[\'options\'][\'fileRoot\'] value ' . $this->config['options']['fileRoot']); + + $this->setParams(); + $this->availableLanguages(); + $this->loadLanguageFile(); + } + + // $extraconfig should be formatted as json config array. + public function setup($extraconfig) { + + $this->config = array_merge_recursive($this->config, $extraconfig); + + } + + // allow Filemanager to be used with dynamic folders + public function setFileRoot($path) { + // global $sys + if (substr_count($_SERVER['HTTP_HOST'], "ca-dev") > 0 OR $_SERVER['HTTP_HOST'] == 'localhost' OR substr_count($_SERVER['HTTP_HOST'], 'localhost.enguehard.info') > 0) { + $tab = explode('.', $_SERVER['SERVER_NAME']); + if ($_SERVER['HTTP_HOST'] == 'localhost') { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'../'; + } else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"].$tab[0].'/www'; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].$tab[0]; + } + $sys['env'] = 'dev'; + } else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'/../'; + $sys['env'] = 'prod'; + } + + if($this->config['options']['serverRoot'] === true) { + // $this->doc_root = $_SERVER['DOCUMENT_ROOT']. $path; + $this->doc_root = $sys['base_dir'].$path; + } else { + $this->doc_root = $path; + } + + // necessary for retrieving path when set dynamically with $fm->setFileRoot() method + // $this->dynamic_fileroot = str_replace($_SERVER['DOCUMENT_ROOT'], '/', $this->doc_root); + $this->dynamic_fileroot = str_replace($sys['base_dir'], '', $this->doc_root); + $this->separator = basename($this->doc_root); + + $this->__log(__METHOD__.' $this->doc_root value overwritten : ' . $this->doc_root); + $this->__log(__METHOD__.' $this->dynamic_fileroot value ' . $this->dynamic_fileroot); + $this->__log(__METHOD__.' $this->separator value ' . $this->separator); + $this->__log(__METHOD__.' $this->config[\'options\'][\'fileRoot\'] value ' . $this->config['options']['fileRoot']); + } + + public function error($string,$textarea=false) { + $array = array( + 'Error'=>$string, + 'Code'=>'-1', + 'Properties'=>$this->properties + ); + + $this->__log( __METHOD__ . ' - error message : ' . $string); + + if($textarea) { + echo ''; + } else { + echo json_encode($array); + } + die(); + } + + public function lang($string) { + if(isset($this->language[$string]) && $this->language[$string]!='') { + return $this->language[$string]; + } else { + return 'Language string error on ' . $string; + } + } + + public function getvar($var) { + if(!isset($_GET[$var]) || $_GET[$var]=='') { + $this->error(sprintf($this->lang('INVALID_VAR'),$var)); + } else { + $this->get[$var] = $this->sanitize($_GET[$var]); + return true; + } + } + public function postvar($var) { + if(!isset($_POST[$var]) || $_POST[$var]=='') { + $this->error(sprintf($this->lang('INVALID_VAR'),$var)); + } else { + $this->post[$var] = $_POST[$var]; + return true; + } + } + + public function getinfo() { + $this->item = array(); + $this->item['properties'] = $this->properties; + $this->get_file_info('', false); + + // handle path when set dynamically with $fm->setFileRoot() method + if($this->dynamic_fileroot != '') { + $path = $this->dynamic_fileroot. $this->get['path']; + $path = preg_replace('~/+~', '/', $path); // remove multiple slashes + } else { + $path = $this->get['path']; + } + + + $array = array( + 'Path'=> $path, + 'Filename'=>$this->item['filename'], + 'File Type'=>$this->item['filetype'], + 'Preview'=>$this->item['preview'], + 'Properties'=>$this->item['properties'], + 'Error'=>"", + 'Code'=>0 + ); + return $array; + } + + public function getfolder() { + $array = array(); + $filesDir = array(); + + $current_path = $this->getFullPath(); + + + if(!$this->isValidPath($current_path)) { + $this->error("No way."); + } + + if(!is_dir($current_path)) { + $this->error(sprintf($this->lang('DIRECTORY_NOT_EXIST'),$this->get['path'])); + } + if(!$handle = opendir($current_path)) { + $this->error(sprintf($this->lang('UNABLE_TO_OPEN_DIRECTORY'),$this->get['path'])); + } else { + while (false !== ($file = readdir($handle))) { + if($file != "." && $file != "..") { + array_push($filesDir, $file); + } + } + closedir($handle); + + // By default + // Sorting files by name ('default' or 'NAME_DESC' cases from $this->config['options']['fileSorting'] + natcasesort($filesDir); + + foreach($filesDir as $file) { + + if(is_dir($current_path . $file)) { + if(!in_array($file, $this->config['exclude']['unallowed_dirs']) && !preg_match( $this->config['exclude']['unallowed_dirs_REGEXP'], $file)) { + $array[$this->get['path'] . $file .'/'] = array( + 'Path'=> $this->get['path'] . $file .'/', + 'Filename'=>$file, + 'File Type'=>'dir', + 'Preview'=> $this->config['icons']['path'] . $this->config['icons']['directory'], + 'Properties'=>array( + 'Date Created'=> date($this->config['options']['dateFormat'], filectime($this->getFullPath($this->get['path'] . $file .'/'))), + 'Date Modified'=> date($this->config['options']['dateFormat'], filemtime($this->getFullPath($this->get['path'] . $file .'/'))), + 'filemtime'=> filemtime($this->getFullPath($this->get['path'] . $file .'/')), + 'Height'=>null, + 'Width'=>null, + 'Size'=>null + ), + 'Error'=>"", + 'Code'=>0 + ); + } + } else if (!in_array($file, $this->config['exclude']['unallowed_files']) && !preg_match( $this->config['exclude']['unallowed_files_REGEXP'], $file)) { + $this->item = array(); + $this->item['properties'] = $this->properties; + $this->get_file_info($this->get['path'] . $file, true); + + if(!isset($this->params['type']) || (isset($this->params['type']) && strtolower($this->params['type'])=='images' && in_array(strtolower($this->item['filetype']),$this->config['images']['imagesExt']))) { + if($this->config['upload']['imagesOnly']== false || ($this->config['upload']['imagesOnly']== true && in_array(strtolower($this->item['filetype']),$this->config['images']['imagesExt']))) { + $array[$this->get['path'] . $file] = array( + 'Path'=>$this->get['path'] . $file, + 'Filename'=>$this->item['filename'], + 'File Type'=>$this->item['filetype'], + 'Preview'=>$this->item['preview'], + 'Properties'=>$this->item['properties'], + 'Error'=>"", + 'Code'=>0 + ); + } + } + } + } + } + + $array = $this->sortFiles($array); + + return $array; + } + + public function rename() { + + $suffix=''; + + + if(substr($this->get['old'],-1,1)=='/') { + $this->get['old'] = substr($this->get['old'],0,(strlen($this->get['old'])-1)); + $suffix='/'; + } + $tmp = explode('/',$this->get['old']); + $filename = $tmp[(sizeof($tmp)-1)]; + $path = str_replace('/' . $filename,'',$this->get['old']); + + $new_file = $this->getFullPath($path . '/' . $this->get['new']). $suffix; + $old_file = $this->getFullPath($this->get['old']) . $suffix; + + if(!$this->isValidPath($old_file)) { + $this->error("No way."); + } + + $this->__log(__METHOD__ . ' - renaming '. $old_file. ' to ' . $new_file); + + if(file_exists ($new_file)) { + if($suffix=='/' && is_dir($new_file)) { + $this->error(sprintf($this->lang('DIRECTORY_ALREADY_EXISTS'),$this->get['new'])); + } + if($suffix=='' && is_file($new_file)) { + $this->error(sprintf($this->lang('FILE_ALREADY_EXISTS'),$this->get['new'])); + } + } + + if(!rename($old_file,$new_file)) { + if(is_dir($old_file)) { + $this->error(sprintf($this->lang('ERROR_RENAMING_DIRECTORY'),$filename,$this->get['new'])); + } else { + $this->error(sprintf($this->lang('ERROR_RENAMING_FILE'),$filename,$this->get['new'])); + } + } + $array = array( + 'Error'=>"", + 'Code'=>0, + 'Old Path'=>$this->get['old'], + 'Old Name'=>$filename, + 'New Path'=>$path . '/' . $this->get['new'].$suffix, + 'New Name'=>$this->get['new'] + ); + return $array; + } + + public function delete() { + + $current_path = $this->getFullPath(); + + if(!$this->isValidPath($current_path)) { + $this->error("No way."); + } + + if(is_dir($current_path)) { + $this->unlinkRecursive($current_path); + $array = array( + 'Error'=>"", + 'Code'=>0, + 'Path'=>$this->formatPath($this->get['path']) + ); + + $this->__log(__METHOD__.' - deleting folder '.$current_path); + return $array; + + } else if(file_exists($current_path)) { + unlink($current_path); + $array = array( + 'Error'=>"", + 'Code'=>0, + 'Path'=>$this->formatPath($this->get['path']) + ); + + $this->__log(__METHOD__.' - deleting file '.$current_path); + return $array; + + } else { + $this->error(sprintf($this->lang('INVALID_DIRECTORY_OR_FILE'))); + } + } + + public function add() { + + $this->setParams(); + + if(!isset($_FILES['newfile']) || !is_uploaded_file($_FILES['newfile']['tmp_name'])) { + $this->error(sprintf($this->lang('INVALID_FILE_UPLOAD')),true); + } + // we determine max upload size if not set + if($this->config['upload']['fileSizeLimit'] == 'auto') { + $this->config['upload']['fileSizeLimit'] = $this->getMaxUploadFileSize(); + } + if($_FILES['newfile']['size'] > ($this->config['upload']['fileSizeLimit'] * 1024 * 1024)) { + $this->error(sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['size'] . 'Mb'),true); + } + if($this->config['upload']['imagesOnly'] || (isset($this->params['type']) && strtolower($this->params['type'])=='images')) { + if(!($size = @getimagesize($_FILES['newfile']['tmp_name']))){ + $this->error(sprintf($this->lang('UPLOAD_IMAGES_ONLY')),true); + } + if(!in_array($size[2], array(1, 2, 3, 7, 8))) { + $this->error(sprintf($this->lang('UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG')),true); + } + } + $_FILES['newfile']['name'] = $this->cleanString($_FILES['newfile']['name'],array('.','-')); + + $current_path = $this->getFullPath($this->post['currentpath']); + + if(!$this->isValidPath($current_path)) { + $this->error("No way."); + } + + if(!$this->config['upload']['overwrite']) { + $_FILES['newfile']['name'] = $this->checkFilename($current_path,$_FILES['newfile']['name']); + } + move_uploaded_file($_FILES['newfile']['tmp_name'], $current_path . $_FILES['newfile']['name']); + chmod($current_path . $_FILES['newfile']['name'], 0644); + + $response = array( + 'Path'=>$this->post['currentpath'], + 'Name'=>$_FILES['newfile']['name'], + 'Error'=>"", + 'Code'=>0 + ); + + $this->__log(__METHOD__.' - adding file '. $_FILES['newfile']['name'].' into '.$current_path); + + echo ''; + die(); + } + + public function addfolder() { + + $current_path = $this->getFullPath(); + + if(!$this->isValidPath($current_path)) { + $this->error("No way."); + } + if(is_dir($current_path . $this->get['name'])) { + $this->error(sprintf($this->lang('DIRECTORY_ALREADY_EXISTS'),$this->get['name'])); + + } + $newdir = $this->cleanString($this->get['name']); + if(!mkdir($current_path . $newdir,0755)) { + $this->error(sprintf($this->lang('UNABLE_TO_CREATE_DIRECTORY'),$newdir)); + } + $array = array( + 'Parent'=>$this->get['path'], + 'Name'=>$this->get['name'], + 'Error'=>"", + 'Code'=>0 + ); + $this->__log(__METHOD__ . ' - adding folder '. $current_path . $newdir); + + return $array; + } + + public function download() { + + $current_path = $this->getFullPath(); + + if(!$this->isValidPath($current_path)) { + $this->error("No way."); + } + + if(isset($this->get['path']) && file_exists($current_path)) { + header("Content-type: application/force-download"); + header('Content-Disposition: inline; filename="'.basename($current_path).'"'); + header("Content-Transfer-Encoding: Binary"); + header("Content-length: ".filesize($current_path)); + header('Content-Type: application/octet-stream'); + header('Content-Disposition: attachment; filename="'.basename($current_path).'"'); + readfile($current_path); + $this->__log(__METHOD__.' - downloading '.$current_path); + exit(); + } else { + $this->error(sprintf($this->lang('FILE_DOES_NOT_EXIST'), $current_path)); + } + } + + public function preview($thumbnail) { + + $current_path = $this->getFullPath(); + + if(isset($this->get['path']) && file_exists($current_path)) { + + // if $thumbnail is set to true we return the thumbnail + if($this->config['options']['generateThumbnails'] == true && $thumbnail == true) { + // get thumbnail (and create it if needed) + $returned_path = $this->get_thumbnail($current_path); + } else { + $returned_path = $current_path; + } + + header("Content-type: image/" .$ext = pathinfo($returned_path, PATHINFO_EXTENSION)); + header("Content-Transfer-Encoding: Binary"); + header("Content-length: ".filesize($returned_path)); + header('Content-Disposition: inline; filename="' . basename($returned_path) . '"'); + readfile($returned_path); + + exit(); + + } else { + $this->error(sprintf($this->lang('FILE_DOES_NOT_EXIST'),$current_path)); + } + } + + public function getMaxUploadFileSize() { + + $max_upload = (int) ini_get('upload_max_filesize'); + $max_post = (int) ini_get('post_max_size'); + $memory_limit = (int) ini_get('memory_limit'); + + $upload_mb = min($max_upload, $max_post, $memory_limit); + + $this->__log(__METHOD__ . ' - max upload file size is '. $upload_mb. 'Mb'); + + return $upload_mb; + } + + private function setParams() { + $tmp = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/'); + $tmp = explode('?',$tmp); + $params = array(); + if(isset($tmp[1]) && $tmp[1]!='') { + $params_tmp = explode('&',$tmp[1]); + if(is_array($params_tmp)) { + foreach($params_tmp as $value) { + $tmp = explode('=',$value); + if(isset($tmp[0]) && $tmp[0]!='' && isset($tmp[1]) && $tmp[1]!='') { + $params[$tmp[0]] = $tmp[1]; + } + } + } + } + $this->params = $params; + } + + + private function get_file_info($path='', $thumbnail = false) { + + // DO NOT rawurlencode() since $current_path it + // is used for displaying name file + if($path=='') { + $current_path = $this->get['path']; + } else { + $current_path = $path; + } + $tmp = explode('/',$current_path); + $this->item['filename'] = $tmp[(sizeof($tmp)-1)]; + + $tmp = explode('.',$this->item['filename']); + $this->item['filetype'] = $tmp[(sizeof($tmp)-1)]; + $this->item['filemtime'] = filemtime($this->getFullPath($current_path)); + $this->item['filectime'] = filectime($this->getFullPath($current_path)); + + $this->item['preview'] = $this->config['icons']['path'] . $this->config['icons']['default']; + + if(is_dir($current_path)) { + + $this->item['preview'] = $this->config['icons']['path'] . $this->config['icons']['directory']; + + } else if(in_array(strtolower($this->item['filetype']),$this->config['images']['imagesExt'])) { + + // svg should not be previewed as raster formats images + if($this->item['filetype'] == 'svg') { + $this->item['preview'] = $current_path; + } else { + $this->item['preview'] = 'connectors/php/filemanager.php?mode=preview&path='. rawurlencode($current_path); + if($thumbnail) $this->item['preview'] .= '&thumbnail=true'; + } + //if(isset($get['getsize']) && $get['getsize']=='true') { + $this->item['properties']['Size'] = filesize($this->getFullPath($current_path)); + if ($this->item['properties']['Size']) { + list($width, $height, $type, $attr) = getimagesize($this->getFullPath($current_path)); + } else { + $this->item['properties']['Size'] = 0; + list($width, $height) = array(0, 0); + } + $this->item['properties']['Height'] = $height; + $this->item['properties']['Width'] = $width; + $this->item['properties']['Size'] = filesize($this->getFullPath($current_path)); + //} + + } else if(file_exists($this->root . $this->config['icons']['path'] . strtolower($this->item['filetype']) . '.png')) { + + $this->item['preview'] = $this->config['icons']['path'] . strtolower($this->item['filetype']) . '.png'; + $this->item['properties']['Size'] = filesize($this->getFullPath($current_path)); + if (!$this->item['properties']['Size']) $this->item['properties']['Size'] = 0; + + } + + $this->item['properties']['Date Modified'] = date($this->config['options']['dateFormat'], $this->item['filemtime']); + $this->item['properties']['filemtime'] = filemtime($this->getFullPath($current_path)); + //$return['properties']['Date Created'] = $this->config['options']['dateFormat'], $return['filectime']); // PHP cannot get create timestamp +} + +private function getFullPath($path = '') { + + if($path == '') { + if(isset($this->get['path'])) $path = $this->get['path']; + } + + if($this->config['options']['fileRoot'] !== false) { + $full_path = $this->doc_root.rawurldecode(str_replace($this->doc_root, '', $path)); + if($this->dynamic_fileroot != '') { + $full_path = $this->doc_root.rawurldecode(str_replace($this->dynamic_fileroot, '', $path)); + } + } else { + $full_path = $this->doc_root . rawurldecode($path); + } + + $full_path = str_replace("//", "/", $full_path); + + return $full_path; +} + +/** + * format path regarding the initial configuration + * @param string $path + */ +private function formatPath($path) { + + if($this->dynamic_fileroot != '') { + + $a = explode($this->separator, $path); + return end($a); + + } else { + + return $path; + + } + +} + +private function sortFiles($array) { + + // handle 'NAME_ASC' + if($this->config['options']['fileSorting'] == 'NAME_ASC') { + $array = array_reverse($array); + } + + // handle 'TYPE_ASC' and 'TYPE_DESC' + if(strpos($this->config['options']['fileSorting'], 'TYPE_') !== false || $this->config['options']['fileSorting'] == 'default') { + + $a = array(); + $b = array(); + + foreach ($array as $key=>$item){ + if(strcmp($item["File Type"], "dir") == 0) { + $a[$key]=$item; + }else{ + $b[$key]=$item; + } + } + + if($this->config['options']['fileSorting'] == 'TYPE_ASC') { + $array = array_merge($a, $b); + } + + if($this->config['options']['fileSorting'] == 'TYPE_DESC' || $this->config['options']['fileSorting'] == 'default') { + $array = array_merge($b, $a); + } + } + + // handle 'MODIFIED_ASC' and 'MODIFIED_DESC' + if(strpos($this->config['options']['fileSorting'], 'MODIFIED_') !== false) { + + $modified_order_array = array(); // new array as a column to sort collector + + foreach ($array as $item) { + $modified_order_array[] = $item['Properties']['filemtime']; + } + + if($this->config['options']['fileSorting'] == 'MODIFIED_ASC') { + array_multisort($modified_order_array, SORT_ASC, $array); + } + if($this->config['options']['fileSorting'] == 'MODIFIED_DESC') { + array_multisort($modified_order_array, SORT_DESC, $array); + } + return $array; + + } + + return $array; + + +} + +private function isValidPath($path) { + + // @todo remove debug message + // $this->__log('compare : ' .$this->getFullPath(). '($this->getFullPath()) and ' . $path . '(path)'); + // $this->__log('strncmp() retruned value : ' .strncmp($path, $this->getFullPath(), strlen($this->getFullPath()))); + + return !strncmp($path, $this->getFullPath(), strlen($this->getFullPath())); + +} + +private function unlinkRecursive($dir,$deleteRootToo=true) { + if(!$dh = @opendir($dir)) { + return; + } + while (false !== ($obj = readdir($dh))) { + if($obj == '.' || $obj == '..') { + continue; + } + + if (!@unlink($dir . '/' . $obj)) { + $this->unlinkRecursive($dir.'/'.$obj, true); + } + } + + closedir($dh); + + if ($deleteRootToo) { + @rmdir($dir); + } + + return; +} + +private function cleanString($string, $allowed = array()) { + $allow = null; + + if (!empty($allowed)) { + foreach ($allowed as $value) { + $allow .= "\\$value"; + } + } + + $mapping = array( + 'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c', + 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', + 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', + 'Õ'=>'O', 'Ö'=>'O', 'Ő'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ű'=>'U', 'Ý'=>'Y', + 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', + 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', + 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ő'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'ű'=>'u', + 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r', ' '=>'_', "'"=>'_', '/'=>'' + ); + + if (is_array($string)) { + + $cleaned = array(); + + foreach ($string as $key => $clean) { + $clean = strtr($clean, $mapping); + + if($this->config['options']['chars_only_latin'] == true) { + $clean = preg_replace("/[^{$allow}_a-zA-Z0-9]/u", '', $clean); + // $clean = preg_replace("/[^{$allow}_a-zA-Z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}]/u", '', $clean); // allow only latin alphabet with cyrillic + } + $cleaned[$key] = preg_replace('/[_]+/', '_', $clean); // remove double underscore + } + } else { + $string = strtr($string, $mapping); + if($this->config['options']['chars_only_latin'] == true) { + $clean = preg_replace("/[^{$allow}_a-zA-Z0-9]/u", '', $string); + // $clean = preg_replace("/[^{$allow}_a-zA-Z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}]/u", '', $string); // allow only latin alphabet with cyrillic + } + $cleaned = preg_replace('/[_]+/', '_', $string); // remove double underscore + + } + return $cleaned; +} + +/** + * For debugging just call + * the direct URL http://localhost/Filemanager/connectors/php/filemanager.php?mode=preview&path=%2FFilemanager%2Fuserfiles%2FMy%20folder3%2Fblanches_neiges.jPg&thumbnail=true + * and echo vars below + * @param string $path + */ +private function get_thumbnail($path) { + + require_once('./inc/vendor/wideimage/lib/WideImage.php'); + + + // echo $path.'
'; + $a = explode($this->separator, $path); + + $path_parts = pathinfo($path); + + // $thumbnail_path = $path_parts['dirname'].'/'.$this->cachefolder; + $thumbnail_path = $a[0].$this->separator.'/'.$this->cachefolder.dirname(end($a)).'/'; + $thumbnail_name = $path_parts['filename'] . '_' . $this->thumbnail_width . 'x' . $this->thumbnail_height . 'px.' . $path_parts['extension']; + $thumbnail_fullpath = $thumbnail_path.$thumbnail_name; + + // echo $thumbnail_fullpath.'
'; + + // if thumbnail does not exist we generate it + if(!file_exists($thumbnail_fullpath)) { + + // create folder if it does not exist + if(!file_exists($thumbnail_path)) { + mkdir($thumbnail_path, 0755, true); + } + $image = WideImage::load($path); + $resized = $image->resize($this->thumbnail_width, $this->thumbnail_height, 'outside')->crop('center', 'center', $this->thumbnail_width, $this->thumbnail_height); + $resized->saveToFile($thumbnail_fullpath); + + $this->__log(__METHOD__ . ' - generating thumbnail : '. $thumbnail_fullpath); + + } + + return $thumbnail_fullpath; +} + +private function sanitize($var) { + $sanitized = strip_tags($var); + $sanitized = str_replace('http://', '', $sanitized); + $sanitized = str_replace('https://', '', $sanitized); + $sanitized = str_replace('../', '', $sanitized); + return $sanitized; +} + +private function checkFilename($path,$filename,$i='') { + if(!file_exists($path . $filename)) { + return $filename; + } else { + $_i = $i; + $tmp = explode(/*$this->config['upload']['suffix'] . */$i . '.',$filename); + if($i=='') { + $i=1; + } else { + $i++; + } + $filename = str_replace($_i . '.' . $tmp[(sizeof($tmp)-1)],$i . '.' . $tmp[(sizeof($tmp)-1)],$filename); + return $this->checkFilename($path,$filename,$i); + } +} + +private function loadLanguageFile() { + + // we load langCode var passed into URL if present and if exists + // else, we use default configuration var + $lang = $this->config['options']['culture']; + if(isset($this->params['langCode']) && in_array($this->params['langCode'], $this->languages)) $lang = $this->params['langCode']; + + if(file_exists($this->root. 'scripts/languages/'.$lang.'.js')) { + $stream =file_get_contents($this->root. 'scripts/languages/'.$lang.'.js'); + $this->language = json_decode($stream, true); + } else { + $stream =file_get_contents($this->root. 'scripts/languages/'.$lang.'.js'); + $this->language = json_decode($stream, true); + } +} + +private function availableLanguages() { + + if ($handle = opendir($this->root.'/scripts/languages/')) { + while (false !== ($file = readdir($handle))) { + if ($file != "." && $file != "..") { + array_push($this->languages, pathinfo($file, PATHINFO_FILENAME)); + } + } + closedir($handle); + } +} + +private function __log($msg) { + if($this->logger == true) { + $fp = fopen($this->logfile, "a"); + // $str = "[".date("d/m/Y h:i:s", mktime())."] ".$msg; + $str = "[".date("d/m/Y h:i:s")."] ".$msg; + fwrite($fp, $str.PHP_EOL); + fclose($fp); + } +} + +public function enableLog($logfile = '') { + + $this->logger = true; + + if($logfile != '') { + $this->logfile = $logfile; + } + + $this->__log(__METHOD__.' - Log enabled (in '.$this->logfile.' file)'); + +} + +public function disableLog() { + + $this->logger = false; + + $this->__log(__METHOD__.' - Log disabled'); +} +} +?> +======= +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 diff --git a/connectors/php/filemanager.php b/connectors/php/filemanager.php index fc3aa39f..9c2a44b2 100755 --- a/connectors/php/filemanager.php +++ b/connectors/php/filemanager.php @@ -1,3 +1,173 @@ +<<<<<<< HEAD + + * @author Simon Georget + * @copyright Authors + */ +session_start(); +require_once('./inc/filemanager.inc.php'); +require_once('filemanager.class.php'); + +/** + * Check if user is authorized + * + * @return boolean true is access granted, false if no access + */ +function auth() { + // You can insert your own code over here to check if the user is authorized. + // If you use a session variable, you've got to start the session first (session_start()) + return true; +} + + +// @todo Work on plugins registration +// if (isset($config['plugin']) && !empty($config['plugin'])) { +// $pluginPath = 'plugins' . DIRECTORY_SEPARATOR . $config['plugin'] . DIRECTORY_SEPARATOR; +// require_once($pluginPath . 'filemanager.' . $config['plugin'] . '.config.php'); +// require_once($pluginPath . 'filemanager.' . $config['plugin'] . '.class.php'); +// $className = 'Filemanager'.strtoupper($config['plugin']); +// $fm = new $className($config); +// } else { +// $fm = new Filemanager($config); +// } +if (substr_count($_SERVER['HTTP_HOST'], "ca-dev") > 0 OR $_SERVER['HTTP_HOST'] == 'localhost' OR substr_count($_SERVER['HTTP_HOST'], 'localhost.enguehard.info') > 0) { + $tab = explode('.', $_SERVER['SERVER_NAME']); + if ($_SERVER['HTTP_HOST'] == 'localhost') { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'../'; + } else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"].$tab[0].'/www'; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].$tab[0]; + } + $sys['env'] = 'dev'; +} else { + $sys['base_dir'] = $_SERVER["DOCUMENT_ROOT"]; + $sys['documentRoot'] = $_SERVER["DOCUMENT_ROOT"].'/../'; + $sys['env'] = 'prod'; +} + +if (isset($_SESSION['userfoldername'])) { + $folderPath = $sys['base_dir'].'/userfiles/image/'.$_SESSION['userfoldername'].'/'; +} else { + $folderPath = $sys['base_dir'].'/userfiles/image/'; +} + + +$fm = new Filemanager(); +$fm->setFileRoot($folderPath); +// $fm->enableLog('/tmp/filemanager.log'); + +$response = ''; + + +if(!auth()) { + $fm->error($fm->lang('AUTHORIZATION_REQUIRED')); +} + +if(!isset($_GET)) { + $fm->error($fm->lang('INVALID_ACTION')); +} else { + + if(isset($_GET['mode']) && $_GET['mode']!='') { + + switch($_GET['mode']) { + + default: + + $fm->error($fm->lang('MODE_ERROR')); + break; + + case 'getinfo': + + if($fm->getvar('path')) { + $response = $fm->getinfo(); + } + break; + + case 'getfolder': + + if($fm->getvar('path')) { + $response = $fm->getfolder(); + } + break; + + case 'rename': + + if($fm->getvar('old') && $fm->getvar('new')) { + $response = $fm->rename(); + } + break; + + case 'delete': + + if($fm->getvar('path')) { + $response = $fm->delete(); + } + break; + + case 'addfolder': + + if($fm->getvar('path') && $fm->getvar('name')) { + $response = $fm->addfolder(); + } + break; + + case 'download': + if($fm->getvar('path')) { + $fm->download(); + } + break; + + case 'preview': + if($fm->getvar('path')) { + if(isset($_GET['thumbnail'])) { + $thumbnail = true; + } else { + $thumbnail = false; + } + $fm->preview($thumbnail); + } + break; + + case 'maxuploadfilesize': + $fm->getMaxUploadFileSize(); + break; + } + + } else if(isset($_POST['mode']) && $_POST['mode']!='') { + + switch($_POST['mode']) { + + default: + + $fm->error($fm->lang('MODE_ERROR')); + break; + + case 'add': + + if($fm->postvar('currentpath')) { + $fm->add(); + } + break; + + } + + } +} + +echo json_encode($response); +die(); +======= >>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 ?> \ No newline at end of file diff --git a/scripts/filemanager.config.default.json b/scripts/filemanager.config.default.json index 06fe0965..1cab40c0 100644 --- a/scripts/filemanager.config.default.json +++ b/scripts/filemanager.config.default.json @@ -1,7 +1,7 @@ { - "_comment": "IMPORTANT : go to the wiki page to know about options configuration https://github.com/simogeo/Filemanager/wiki/Filemanager-configuration-file", + "_comment": "IMPORTANT : go to the wiki page to know about options configuration https://github.com/simogeo/Filemanager/wiki/Filemanager-configuration-file", "options": { - "culture": "en", + "culture": "fr", "lang": "php", "theme": "flat-dark", "defaultViewMode": "grid", @@ -21,6 +21,30 @@ "splitterWidth": 200, "splitterMinWidth": 200, "dateFormat": "d M Y H:i", +<<<<<<< HEAD:scripts/filemanager.config.js.default + "serverRoot": false, + "fileRoot": "/", + "relPath": "/", + "logger": false, + "logfile": "/tmp/filemanager.log", + "plugins": [] + }, + "security": { + "uploadPolicy": "ALLOW_ALL", + "uploadRestrictions": [ + "exe", + "bat", + "com", + "msi", + "bat", + "php", + "phps", + "phtml", + "php3", + "php4", + "cgi", + "pl" +======= "serverRoot": true, "fileRoot": false, "baseUrl": false, @@ -62,6 +86,7 @@ "wav", "zip", "rar" +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55:scripts/filemanager.config.default.json ] }, "upload": { diff --git a/scripts/filemanager.js b/scripts/filemanager.js index 2b25e838..87163892 100644 --- a/scripts/filemanager.js +++ b/scripts/filemanager.js @@ -10,12 +10,12 @@ */ (function($) { - + // function to retrieve GET params $.urlParam = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); if (results) - return results[1]; + return results[1]; else return 0; }; @@ -45,7 +45,7 @@ var loadConfigFile = function (type) { 'async': false, 'url': url, 'dataType': "json", - cache: false, + cache: false, 'success': function (data) { json = data; } @@ -61,6 +61,8 @@ var config = loadConfigFile(); if (config !== null) delete config.version; +<<<<<<< HEAD +======= // we merge default config and user config file var config = $.extend({}, configd, config); @@ -119,6 +121,7 @@ smartPath = function(url, path) { return rvalue; }; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 // Sets paths to connectors based on language selection. var fileConnector = config.options.fileConnector || 'connectors/' + config.options.lang + '/filemanager.' + config.options.lang; @@ -126,7 +129,7 @@ var fileConnector = config.options.fileConnector || 'connectors/' + config.optio // else apply default settings var capabilities = config.options.capabilities || new Array('select', 'download', 'rename', 'move', 'delete', 'replace'); -// Get localized messages from file +// Get localized messages from file // through culture var or from URL if($.urlParam('langCode') != 0) { if(file_exists ('scripts/languages/' + $.urlParam('langCode') + '.js')) { @@ -163,15 +166,23 @@ var setDimensions = function(){ if($.urlParam('CKEditorCleanUpFuncNum')) bheight +=60; +<<<<<<< HEAD + var newH = $(window).height() - $('#uploader').height() - bheight; + $('#splitter, #filetree, #fileinfo, .vsplitbar').height(newH); + + var newW = $('#splitter').width() - 6 - $('#filetree').width(); + $('#fileinfo').width(newW); +======= var newH = $(window).height() - $uploader.height() - $uploader.offset().top - bheight; $('#splitter, #filetree, #fileinfo, .vsplitbar').height(newH); var newW = $('#splitter').width() - $('div.vsplitbar').width() - $('#filetree').width(); $('#fileinfo').width(newW); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 }; // Display Min Path var displayPath = function(path, reduce) { - + reduce = (typeof reduce === "undefined") ? true : false; if(config.options.showFullPath == false) { @@ -211,7 +222,7 @@ function file_exists (url) { // + input by: Jani Hartikainen // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain. - // % note 1: Synchronous so may lock up browser, mainly here for study purposes. + // % note 1: Synchronous so may lock up browser, mainly here for study purposes. // * example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm'); // * returns 1: '123' var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); @@ -246,32 +257,50 @@ var preg_replace = function(array_pattern, array_pattern_replace, str) { var cleanString = function(str) { var cleaned = ""; +<<<<<<< HEAD + var p_search = new Array("Š", "š", "Đ", "đ", "Ž", "ž", "Č", "č", "Ć", "ć", "À", + "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", + "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ő", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", + "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", + "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ő", "ø", "ù", "ú", "û", "ý", + "ý", "þ", "ÿ", "Ŕ", "ŕ", " ", "'", "/" +======= var p_search = new Array("Š", "š", "Đ", "đ", "Ž", "ž", "Č", "č", "Ć", "ć", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ő", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ő", "ø", "ù", "ú", "û", "ü", "ý", "ý", "þ", "ÿ", "Ŕ", "ŕ", " ", "'", "/" +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 ); - var p_replace = new Array("S", "s", "Dj", "dj", "Z", "z", "C", "c", "C", "c", "A", - "A", "A", "A", "A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I", - "N", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "Y", "B", "Ss", + var p_replace = new Array("S", "s", "Dj", "dj", "Z", "z", "C", "c", "C", "c", "A", + "A", "A", "A", "A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I", + "N", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "Y", "B", "Ss", "a", "a", "a", "a", "a", "a", "a", "c", "e", "e", "e", "e", "i", "i", +<<<<<<< HEAD + "i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "y", + "y", "b", "y", "R", "r", "_", "_", "" +======= "i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "y", "y", "b", "y", "R", "r", "_", "_", "" +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 ); cleaned = preg_replace(p_search, p_replace, str); - + // allow only latin alphabet if(config.options.chars_only_latin) { cleaned = cleaned.replace(/[^_a-zA-Z0-9]/g, ""); } - + cleaned = cleaned.replace(/[_]+/g, "_"); +<<<<<<< HEAD + +======= // prevent bug https://github.com/simogeo/Filemanager/issues/474 if(cleaned == "") cleaned = "unsupportedCharsReplacement"; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 return cleaned; }; @@ -294,7 +323,7 @@ var formatBytes = function(bytes) { var d = parseFloat(1024); var c = 0; var u = [lg.bytes,lg.kb,lg.mb,lg.gb]; - + while(true){ if(n < d){ n = Math.round(n * 100) / 100; @@ -341,7 +370,7 @@ var isAuthorizedFile = function(filename) { if(config.security.uploadPolicy == 'ALLOW_ALL') { if($.inArray(ext, config.security.uploadRestrictions) == -1) return true; } - + return false; }; @@ -352,11 +381,11 @@ var basename = function(path, suffix) { if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) { b = b.substr(0, b.length-suffix.length); } - + return b; }; -// return filename extension +// return filename extension var getExtension = function(filename) { if(filename.split('.').length == 1) { return ""; @@ -409,6 +438,9 @@ var isAudioFile = function(filename) { } }; +<<<<<<< HEAD +// Return HTML video player +======= // Test if file is pdf file var isPdfFile = function(filename) { if($.inArray(getExtension(filename), config.pdfs.pdfsExt) != -1) { @@ -419,25 +451,36 @@ var isPdfFile = function(filename) { }; // Return HTML video player +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 var getVideoPlayer = function(data) { var code = ''; - + $("#fileinfo img").remove(); +<<<<<<< HEAD + $('#fileinfo #preview h1').before(code); + +======= $('#fileinfo #preview #main-title').before(code); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 }; -//Return HTML audio player +//Return HTML audio player var getAudioPlayer = function(data) { var code = ''; - + $("#fileinfo img").remove(); +<<<<<<< HEAD + $('#fileinfo #preview h1').before(code); + +======= $('#fileinfo #preview #main-title').before(code); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 }; //Return PDF Reader @@ -448,14 +491,20 @@ var getPdfReader = function(data) { $('#fileinfo #preview #main-title').before(code); }; -// Display icons on list view +// Display icons on list view // retrieving them from filetree // Called using SetInterval var display_icons = function(timer) { $('#fileinfo').find('td:first-child').each(function(){ +<<<<<<< HEAD + var path = $(this).attr('title'); + var treenode = $('#filetree').find('a[rel="' + path + '"]').parent(); + +======= var path = $(this).attr('data-path'); var treenode = $('#filetree').find('a[data-path="' + path + '"]').parent(); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 if (typeof treenode.css('background-image') !== "undefined") { $(this).css('background-image', treenode.css('background-image')); window.clearInterval(timer); @@ -464,8 +513,8 @@ var display_icons = function(timer) { }); }; -// Sets the folder status, upload, and new folder functions -// to the path specified. Called on initial page load and +// Sets the folder status, upload, and new folder functions +// to the path specified. Called on initial page load and // whenever a new directory is selected. var setUploader = function(path) { $('#currentpath').val(path); @@ -474,9 +523,9 @@ var setUploader = function(path) { $('#newfolder').unbind().click(function(){ var foldername = lg.default_foldername; var msg = lg.prompt_foldername + ' : '; - + var getFolderName = function(v, m){ - if(v != 1) return false; + if(v != 1) return false; var fname = m.children('#fname').val(); if(fname != ''){ @@ -491,17 +540,22 @@ var setUploader = function(path) { $('#filetree').find('a[data-path="' + result['Parent'] +'/"]').click().click(); } else { $.prompt(result['Error']); - } + } }); } else { $.prompt(lg.no_foldername); } }; - var btns = {}; - btns[lg.create_folder] = true; - btns[lg.cancel] = false; + var btns = {}; + btns[lg.create_folder] = true; + btns[lg.cancel] = false; $.prompt(msg, { callback: getFolderName, +<<<<<<< HEAD + buttons: btns + }); + }); +======= buttons: btns }); @@ -509,12 +563,18 @@ var setUploader = function(path) { }); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 }; // Binds specific actions to the toolbar in detail views. // Called when detail views are loaded. +<<<<<<< HEAD +var bindToolbar = function(data){ + +======= var bindToolbar = function(data) { +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 // this little bit is purely cosmetic $( "#fileinfo button" ).each(function( index ) { // check if span doesn't exist yet, when bindToolbar called from renameItem for example @@ -531,7 +591,7 @@ var bindToolbar = function(data) { $('#preview img').click(function () { selectItem(data); }).css("cursor", "pointer"); } } - + if (!has_capability(data, 'rename')) { $('#fileinfo').find('button#rename').hide(); } else { @@ -577,7 +637,7 @@ var bindToolbar = function(data) { }; //Create FileTree and bind elements -//called during initialization and also when adding a file +//called during initialization and also when adding a file //directly in root folder (via addNode) var createFileTree = function() { @@ -623,18 +683,31 @@ var createFileTree = function() { // Calls the SetUrl function for FCKEditor compatibility, // passes file path, dimensions, and alt text back to the -// opening window. Triggered by clicking the "Select" +// opening window. Triggered by clicking the "Select" // button in detail views or choosing the "Select" -// contextual menu option in list views. +// contextual menu option in list views. // NOTE: closes the window when finished. +<<<<<<< HEAD +var selectItem = function(data){ + if(config.options.relPath != false ) { + // REG var url = relPath + data['Path'].replace(fileRoot,""); + var url = relPath + data['Path']; +======= var selectItem = function(data) { if(config.options.baseUrl !== false ) { var url = smartPath(baseUrl, data['Path'].replace(fileRoot,"")); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 } else { var url = baseUrl + data['Path']; } +<<<<<<< HEAD + url = url.replace('//', '/'); +// alert(url + "\n"+data['Path']);return; + if(window.opener || window.tinyMCEPopup || $.urlParam('field_name')){ +======= if(window.opener || window.tinyMCEPopup || $.urlParam('field_name') || $.urlParam('CKEditorCleanUpFuncNum') || $.urlParam('CKEditor')) { +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 if(window.tinyMCEPopup){ // use TinyMCE > 3.0 integration method var win = tinyMCEPopup.getWindowArg("window"); @@ -654,15 +727,22 @@ var selectItem = function(data) { // tinymce 4 and colorbox if($.urlParam('field_name')){ parent.document.getElementById($.urlParam('field_name')).value = url; +<<<<<<< HEAD + + if(typeof top.tinyMCE !== "undefined") { + // parent.tinyMCE.activeEditor.windowManager.close(); it seems parent. does not work with IE9 /IE10 + top.tinyMCE.activeEditor.windowManager.close(); +======= if(typeof parent.tinyMCE !== "undefined") { parent.tinyMCE.activeEditor.windowManager.close(); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 } if(typeof parent.$.fn.colorbox !== "undefined") { parent.$.fn.colorbox.close(); } } - + else if($.urlParam('CKEditor')){ // use CKEditor 3.0 + integration method if (window.opener) { @@ -678,11 +758,11 @@ var selectItem = function(data) { if(data['Properties']['Width'] != ''){ var p = url; var w = data['Properties']['Width']; - var h = data['Properties']['Height']; + var h = data['Properties']['Height']; window.opener.SetUrl(p,w,h); } else { window.opener.SetUrl(url); - } + } } if (window.opener) { @@ -695,7 +775,7 @@ var selectItem = function(data) { // Renames the current item and returns the new name. // Called by clicking the "Rename" button in detail views -// or choosing the "Rename" contextual menu option in +// or choosing the "Rename" contextual menu option in // list views. var renameItem = function(data) { var finalName = ''; @@ -705,8 +785,18 @@ var renameItem = function(data) { var getNewName = function(v, m){ if(v != 1) return false; rname = m.children('#rname').val(); - + if(rname != ''){ +<<<<<<< HEAD + var givenName = nameFormat(rname); + var suffix = getExtension(data['Filename']); + if(suffix.length > 0) { + givenName = givenName + '.' + suffix; + } + var oldPath = data['Path']; + var connectString = fileConnector + '?mode=rename&old=' + data['Path'] + '&new=' + givenName; + +======= var givenName = rname; @@ -735,6 +825,7 @@ var renameItem = function(data) { var oldPath = data['Path']; var connectString = fileConnector + '?mode=rename&old=' + encodeURIComponent(data['Path']) + '&new=' + encodeURIComponent(givenName) + '&config=' + userconfig; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 $.ajax({ type: 'GET', url: connectString, @@ -744,16 +835,20 @@ var renameItem = function(data) { if(result['Code'] == 0){ var newPath = result['New Path']; var newName = result['New Name']; +<<<<<<< HEAD + +======= var oldPath = result['Old Path']; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 updateNode(oldPath, newPath, newName); - + var title = $("#preview h1").attr("title"); if (typeof title !="undefined" && title == oldPath) { $('#preview h1').text(newName); } - + if($('#fileinfo').data('view') == 'grid'){ $('#fileinfo img[data-path="' + oldPath + '"]').parent().next('p').text(newName); $('#fileinfo img[data-path="' + oldPath + '"]').attr('data-path', newPath); @@ -762,33 +857,33 @@ var renameItem = function(data) { $('#fileinfo td[data-path="' + oldPath + '"]').attr('data-path', newPath); } $("#preview h1").html(newName); - + // actualized data for binding data['Path']=newPath; data['Filename']=newName; - + // Bind toolbar functions. $('#fileinfo').find('button#rename, button#delete, button#download').unbind(); bindToolbar(data); - + if(config.options.showConfirmation) $.prompt(lg.successful_rename); } else { $.prompt(result['Error']); } - - finalName = result['New Name']; + + finalName = result['New Name']; } - }); + }); } }; - var btns = {}; - btns[lg.rename] = true; - btns[lg.cancel] = false; + var btns = {}; + btns[lg.rename] = true; + btns[lg.cancel] = false; $.prompt(msg, { callback: getNewName, - buttons: btns + buttons: btns }); - + return finalName; }; @@ -945,11 +1040,15 @@ var moveItem = function(data) { var deleteItem = function(data) { var isDeleted = false; var msg = lg.confirmation_delete; - + var doDelete = function(v, m){ if(v != 1) return false; +<<<<<<< HEAD + var connectString = fileConnector + '?mode=delete&path=' + encodeURIComponent(data['Path']), +======= var d = new Date(); // to prevent IE cache issues var connectString = fileConnector + '?mode=delete&path=' + encodeURIComponent(data['Path']) + '&time=' + d.getMilliseconds() + '&config=' + userconfig, +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 parent = data['Path'].split('/').reverse().slice(1).reverse().join('/') + '/'; $.ajax({ @@ -964,7 +1063,7 @@ var deleteItem = function(data) { rootpath = rootpath.substr(0, rootpath.lastIndexOf('/') + 1); $('#uploader h1').text(lg.current_folder + displayPath(rootpath)).attr("title", displayPath(rootpath, false)).attr('data-path', rootpath); isDeleted = true; - + if(config.options.showConfirmation) $.prompt(lg.successful_delete); // seems to be necessary when dealing w/ files located on s3 (need to look into a cleaner solution going forward) @@ -972,18 +1071,18 @@ var deleteItem = function(data) { } else { isDeleted = false; $.prompt(result['Error']); - } + } } - }); + }); }; - var btns = {}; - btns[lg.yes] = true; - btns[lg.no] = false; + var btns = {}; + btns[lg.yes] = true; + btns[lg.no] = false; $.prompt(msg, { callback: doDelete, - buttons: btns + buttons: btns }); - + return isDeleted; }; @@ -1087,8 +1186,13 @@ var addNode = function(path, name) { var ext = getExtension(name); var thisNode = $('#filetree').find('a[data-path="' + path + '"]'); var parentNode = thisNode.parent(); +<<<<<<< HEAD + var newNode = '
  • ' + name + '
  • '; + +======= var newNode = '
  • ' + name + '
  • '; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 // if is root folder // TODO optimize if(!parentNode.find('ul').size()) { @@ -1096,7 +1200,7 @@ var addNode = function(path, name) { parentNode.prepend(newNode); createFileTree(); - + } else { parentNode.find('ul').prepend(newNode); thisNode.click().click(); @@ -1123,13 +1227,13 @@ var updateNode = function(oldPath, newPath, newName){ } }; -// Removes the specified node. Called after a successful +// Removes the specified node. Called after a successful // delete operation. var removeNode = function(path) { $('#filetree') .find('a[data-path="' + path + '"]') .parent() - .fadeOut('slow', function(){ + .fadeOut('slow', function(){ $(this).remove(); }); // if the actual view is the deleted folder, we display parent folder @@ -1140,8 +1244,13 @@ var removeNode = function(path) { } // grid case if($('#fileinfo').data('view') == 'grid'){ +<<<<<<< HEAD + $('#contents img[alt="' + path + '"]').parent().parent() + .fadeOut('slow', function(){ +======= $('#contents img[data-path="' + path + '"]').parent().parent() .fadeOut('slow', function(){ +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 $(this).remove(); }); } @@ -1150,7 +1259,7 @@ var removeNode = function(path) { $('table#contents') .find('td[data-path="' + path + '"]') .parent() - .fadeOut('slow', function(){ + .fadeOut('slow', function(){ $(this).remove(); }); } @@ -1174,7 +1283,7 @@ var addFolder = function(parent, name) { getFolderInfo(parent + name + '/'); }).each(function() { $(this).contextMenu( - { menu: getContextMenuOptions($(this)) }, + { menu: getContextMenuOptions($(this)) }, function(action, el, pos){ var path = $(el).attr('data-path'); setMenus(action, path); @@ -1182,7 +1291,7 @@ var addFolder = function(parent, name) { } ); } - + if(config.options.showConfirmation) $.prompt(lg.successful_added_folder); }; @@ -1230,19 +1339,27 @@ var setMenus = function(action, path) { } else { var item = $('#fileinfo').find('td[data-path="' + data['Path'] + '"]').parent(); } - + switch(action){ case 'select': selectItem(data); break; +<<<<<<< HEAD + + case 'download': + window.location = fileConnector + '?mode=download&path=' + data['Path']; +======= case 'download': // todo implement javascript method to test if exstension is correct window.location = fileConnector + '?mode=download&path=' + data['Path'] + '&config=' + userconfig + '&time=' + d.getMilliseconds(); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 break; - + case 'rename': var newName = renameItem(data); break; +<<<<<<< HEAD +======= case 'replace': replaceItem(data); @@ -1251,6 +1368,7 @@ var setMenus = function(action, path) { case 'move': var newName = moveItem(data); break; +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 case 'delete': deleteItem(data); @@ -1290,6 +1408,9 @@ var getFileInfo = function(file) { } template += ''; +<<<<<<< HEAD + $('#fileinfo').html(template); +======= // test if scrollbar plugin is enabled if ($('#fileinfo .mCSB_container').length > 0) { $('#fileinfo .mCSB_container').html(template); @@ -1297,8 +1418,9 @@ var getFileInfo = function(file) { $('#fileinfo').html(template); } +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 $('#parentfolder').click(function() {getFolderInfo(currentpath);}); - + // Retrieve the data & populate the template. var d = new Date(); // to prevent IE cache issues $.getJSON(fileConnector + '?mode=getinfo&path=' + encodeURIComponent(file) + '&config=' + userconfig + '&time=' + d.getMilliseconds(), function(data){ @@ -1312,6 +1434,9 @@ var getFileInfo = function(file) { if(isAudioFile(data['Filename']) && config.audios.showAudioPlayer == true) { getAudioPlayer(data); } +<<<<<<< HEAD + +======= //Pdf if(isPdfFile(data['Filename']) && config.pdfs.showPdfReader == true) { getPdfReader(data); @@ -1339,21 +1464,22 @@ var getFileInfo = function(file) { }); } +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 var properties = ''; - + if(data['Properties']['Width'] && data['Properties']['Width'] != '') properties += '
    ' + lg.dimensions + '
    ' + data['Properties']['Width'] + 'x' + data['Properties']['Height'] + '
    '; if(data['Properties']['Date Created'] && data['Properties']['Date Created'] != '') properties += '
    ' + lg.created + '
    ' + data['Properties']['Date Created'] + '
    '; if(data['Properties']['Date Modified'] && data['Properties']['Date Modified'] != '') properties += '
    ' + lg.modified + '
    ' + data['Properties']['Date Modified'] + '
    '; if(data['Properties']['Size'] || parseInt(data['Properties']['Size'])==0) properties += '
    ' + lg.size + '
    ' + formatBytes(data['Properties']['Size']) + '
    '; $('#fileinfo').find('dl').html(properties); - + // Bind toolbar functions. bindToolbar(data); } else { $.prompt(data['Error']); } - }); + }); }; // Retrieves data for all items within the given folder and @@ -1382,21 +1508,25 @@ var getFolderInfo = function(path) { if ($.urlParam('type')) url += '&type=' + $.urlParam('type'); $.getJSON(url, function(data){ var result = ''; - + // Is there any error or user is unauthorized? if(data.Code=='-1') { handleError(data.Error); return; }; +<<<<<<< HEAD + +======= setDimensions(); //fix dimensions before all images load +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 if(data){ var counter = 0; var totalSize = 0; if($('#fileinfo').data('view') == 'grid'){ result += ''; } else { result += ''; result += ''; result += ''; - + for(key in data){ counter++; var path = data[key]['Path']; @@ -1448,31 +1583,34 @@ var getFolderInfo = function(path) { } else { result += ''; } - + if(props['Size'] && props['Size'] != ''){ result += ''; totalSize += props['Size']; } else { result += ''; } - + if(props['Date Modified'] && props['Date Modified'] != ''){ result += ''; } else { result += ''; } - - result += ''; + + result += ''; } - + result += ''; result += '
    ' + lg.name + '' + lg.dimensions + '' + lg.size + '' + lg.modified + '
    ' + formatBytes(props['Size']) + '' + props['Date Modified'] + '
    '; - } + } } else { result += '

    ' + lg.could_not_retrieve_folder + '

    '; } - + // Add the new markup to the DOM. +<<<<<<< HEAD + $('#fileinfo').html(result); +======= // test if scrollbar plugin is enabled if ($('#fileinfo .mCSB_container').length > 0) { $('#fileinfo .mCSB_container').html(result); @@ -1483,6 +1621,7 @@ var getFolderInfo = function(path) { // update #folder-info $('#items-counter').text(counter); $('#items-size').text(Math.round(totalSize / 1024 /1024 * 100) / 100); +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 // Bind click events to create detail views and add // contextual menu options. @@ -1505,12 +1644,17 @@ var getFolderInfo = function(path) { }); } else { $('#fileinfo tbody tr').click(function(){ +<<<<<<< HEAD + var path = $('td:first-child', this).attr('title'); + getDetailView(path); +======= var path = $('td:first-child', this).attr('data-path'); if(config.options.quickSelect && data[path]['File Type'] != 'dir' && $(this).hasClass('cap_select')) { selectItem(data[path]); } else { getDetailView(path); } +>>>>>>> c75b9144aaed3060951f996ae097f2ed68cb0d55 }).each(function() { $(this).contextMenu( { menu: getContextMenuOptions($(this)) }, @@ -1520,12 +1664,12 @@ var getFolderInfo = function(path) { } ); }); - + $('#fileinfo').find('table').tablesorter({ - textExtraction: function(node){ + textExtraction: function(node){ if($(node).find('abbr').size()){ return $(node).find('abbr').attr('title'); - } else { + } else { return node.innerHTML; } } @@ -1553,7 +1697,7 @@ var populateFileTree = function(path, callback) { handleError(data.Error); return; }; - + if(data) { result += "