/** * Create new file and write into it from file pointer. * Return new file path or false on error. * * @param resource $fp file pointer * @param string $dir target dir path * @param string $name file name * @param array $stat file stat (required by some virtual fs) * * @return bool|string * * @author Dmitry (dio) Levashov **/ protected function _save($fp, $path, $name, $stat) { if ($name !== '') { $path .= '/' . $name; } list($parentId, $itemId, $parent) = $this->_gd_splitPath($path); if ($name === '') { $stat['iid'] = $itemId; } if (!$stat || empty($stat['iid'])) { $opts = ['q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name), 'fields' => self::FETCHFIELDS_LIST]; $srcFile = $this->_gd_query($opts); $srcFile = empty($srcFile) ? null : $srcFile[0]; } else { $srcFile = $this->_gd_getFile($path); } try { $mode = 'update'; $mime = isset($stat['mime']) ? $stat['mime'] : ''; $file = new Google_Service_Drive_DriveFile(); if ($srcFile) { $mime = $srcFile->getMimeType(); } else { $mode = 'insert'; $file->setName($name); $file->setParents([$parentId]); } if (!$mime) { $mime = self::mimetypeInternalDetect($name); } if ($mime === 'unknown') { $mime = 'application/octet-stream'; } $file->setMimeType($mime); $size = 0; if (isset($stat['size'])) { $size = $stat['size']; } else { $fstat = fstat($fp); if (!empty($fstat['size'])) { $size = $fstat['size']; } } // set chunk size (max: 100MB) $chunkSizeBytes = 100 * 1024 * 1024; if ($size > 0) { $memory = elFinder::getIniBytes('memory_limit'); if ($memory) { $chunkSizeBytes = min([$chunkSizeBytes, intval($memory / 4 / 256) * 256]); } } if ($size > $chunkSizeBytes) { $client = $this->client; // Call the API with the media upload, defer so it doesn't immediately return. $client->setDefer(true); if ($mode === 'insert') { $request = $this->service->files->create($file, ['fields' => self::FETCHFIELDS_GET]); } else { $request = $this->service->files->update($srcFile->getId(), $file, ['fields' => self::FETCHFIELDS_GET]); } // Create a media file upload to represent our upload process. $media = new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes); $media->setFileSize($size); // Upload the various chunks. $status will be false until the process is // complete. $status = false; while (!$status && !feof($fp)) { elFinder::extendTimeLimit(); // read until you get $chunkSizeBytes from TESTFILE // fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file // An example of a read buffered file is when reading from a URL $chunk = $this->_gd_readFileChunk($fp, $chunkSizeBytes); $status = $media->nextChunk($chunk); } // The final value of $status will be the data from the API for the object // that has been uploaded. if ($status !== false) { $obj = $status; } $client->setDefer(false); } else { $params = ['data' => stream_get_contents($fp), 'uploadType' => 'media', 'fields' => self::FETCHFIELDS_GET]; if ($mode === 'insert') { $obj = $this->service->files->create($file, $params); } else { $obj = $this->service->files->update($srcFile->getId(), $file, $params); } } if ($obj instanceof Google_Service_Drive_DriveFile) { return $this->_joinPath($parent, $obj->getId()); } else { return false; } } catch (Exception $e) { return $this->setError('GoogleDrive error: ' . $e->getMessage()); } }
/** * Create log record * * @param string $cmd command name * @param array $result command result * @param array $args command arguments from client * @param elFinder $elfinder elFinder instance * @return void|true * @author Dmitry (dio) Levashov **/ public function log($cmd, $result, $args, $elfinder) { $log = $cmd . ' [' . date('d.m H:s') . "]\n"; if (!empty($result['error'])) { $log .= "\tERROR: " . implode(' ', $result['error']) . "\n"; } if (!empty($result['warning'])) { $log .= "\tWARNING: " . implode(' ', $result['warning']) . "\n"; } if (!empty($result['removed'])) { foreach ($result['removed'] as $file) { // removed file contain additional field "realpath" $log .= "\tREMOVED: " . $file['realpath'] . "\n"; //preg_match('/[^\/]+$/', $file['realpath'], $file); //$log .= $file[0]; } } if (!empty($result['added'])) { foreach ($result['added'] as $file) { $log .= "\tADDED: " . $elfinder->realpath($file['hash']) . "\n"; } } if (!empty($result['changed'])) { foreach ($result['changed'] as $file) { $log .= "\tCHANGED: " . $elfinder->realpath($file['hash']) . "\n"; } } $this->write($log); }
/** * Execute elFinder command and output result * * @return void * @author Dmitry (dio) Levashov **/ public function run() { $isPost = $_SERVER["REQUEST_METHOD"] == 'POST'; $src = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET; $cmd = isset($src['cmd']) ? $src['cmd'] : ''; $args = array(); if (!function_exists('json_encode')) { $error = $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_JSON); $this->output(array('error' => '{"error":["' . implode('","', $error) . '"]}', 'raw' => true)); } if (!$this->elFinder->loaded()) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_VOL))); } // telepat_mode: on if (!$cmd && $isPost) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UPLOAD_COMMON, elFinder::ERROR_UPLOAD_FILES_SIZE), 'header' => 'Content-Type: text/html')); } // telepat_mode: off if (!$this->elFinder->commandExists($cmd)) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD))); } // collect required arguments to exec command foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) { $arg = $name == 'FILES' ? $_FILES : (isset($src[$name]) ? $src[$name] : ''); if (!is_array($arg)) { $arg = trim($arg); } if ($req && empty($arg)) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd))); } $args[$name] = $arg; } $args['debug'] = isset($src['debug']) ? !!$src['debug'] : false; $this->output($this->elFinder->exec($cmd, $args)); }
public function actionConnector() { $this->layout = false; Yii::import('elfinder.vendors.*'); require_once 'elFinder.class.php'; $opts = array('root' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR, 'URL' => Yii::app()->baseUrl . '/upload/', 'rootAlias' => 'Home'); $fm = new elFinder($opts); $fm->run(); }
public function connector() { $this->show->Title = 'Менеджер файлов'; include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'elFinder.class.php'; // $log = new elFinderLogger(); $opts = array('root' => DOC_ROOT . 'var/custom', 'URL' => BASE_PATH . 'var/custom/', 'rootAlias' => $this->show->Title); $fm = new elFinder($opts); $fm->run(); }
/** * Execute elFinder command and returns result * @param array $queryParameters GET query parameters. * @return array * @author Dmitry (dio) Levashov **/ public function execute($queryParameters) { $isPost = $_SERVER["REQUEST_METHOD"] == 'POST'; $src = $_SERVER["REQUEST_METHOD"] == 'POST' ? array_merge($_POST, $queryParameters) : $queryParameters; if ($isPost && !$src && ($rawPostData = @file_get_contents('php://input'))) { // for support IE XDomainRequest() $parts = explode('&', $rawPostData); foreach ($parts as $part) { list($key, $value) = array_pad(explode('=', $part), 2, ''); $src[$key] = rawurldecode($value); } $_POST = $src; $_REQUEST = array_merge_recursive($src, $_REQUEST); } $cmd = isset($src['cmd']) ? $src['cmd'] : ''; $args = array(); if (!function_exists('json_encode')) { $error = $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_JSON); return $this->output(array('error' => '{"error":["' . implode('","', $error) . '"]}', 'raw' => true)); } if (!$this->elFinder->loaded()) { return $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_VOL), 'debug' => $this->elFinder->mountErrors)); } // telepat_mode: on if (!$cmd && $isPost) { return $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UPLOAD, elFinder::ERROR_UPLOAD_TOTAL_SIZE), 'header' => 'Content-Type: text/html')); } // telepat_mode: off if (!$this->elFinder->commandExists($cmd)) { return $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD))); } // collect required arguments to exec command foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) { $arg = $name == 'FILES' ? $_FILES : (isset($src[$name]) ? $src[$name] : ''); if (!is_array($arg)) { $arg = trim($arg); } if ($req && (!isset($arg) || $arg === '')) { return $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd))); } $args[$name] = $arg; } $args['debug'] = isset($src['debug']) ? !!$src['debug'] : false; return $this->output($this->elFinder->exec($cmd, $this->input_filter($args))); }
protected function _checkName($n) { $Result = parent::_checkName($n); $Extension = pathinfo($Result, 4); $Name = pathinfo($Result, 8); $Result = Gdn_Format::Clean($Name) . '.' . Gdn_Format::Clean($Extension); $Result = trim($Result, '.'); return $Result; }
public function onUpLoadPreSave(&$path, &$name, $src, $elfinder, $volume) { $opts = $this->opts; $volOpts = $volume->getOptionsPlugin('Watermark'); if (is_array($volOpts)) { $opts = array_merge($this->opts, $volOpts); } if (!$opts['enable']) { return false; } $srcImgInfo = @getimagesize($src); if ($srcImgInfo === false) { return false; } // check Animation Gif if (elFinder::isAnimationGif($src)) { return false; } // check water mark image if (!file_exists($opts['source'])) { $opts['source'] = dirname(__FILE__) . "/" . $opts['source']; } if (is_readable($opts['source'])) { $watermarkImgInfo = @getimagesize($opts['source']); if (!$watermarkImgInfo) { return false; } } else { return false; } $watermark = $opts['source']; $marginLeft = $opts['marginRight']; $marginBottom = $opts['marginBottom']; $quality = $opts['quality']; $transparency = $opts['transparency']; // check target image type $imgTypes = array(IMAGETYPE_GIF => IMG_GIF, IMAGETYPE_JPEG => IMG_JPEG, IMAGETYPE_PNG => IMG_PNG, IMAGETYPE_WBMP => IMG_WBMP); if (!($opts['targetType'] & $imgTypes[$srcImgInfo[2]])) { return false; } // check target image size if ($opts['targetMinPixel'] > 0 && $opts['targetMinPixel'] > min($srcImgInfo[0], $srcImgInfo[1])) { return false; } $watermark_width = $watermarkImgInfo[0]; $watermark_height = $watermarkImgInfo[1]; $dest_x = $srcImgInfo[0] - $watermark_width - $marginLeft; $dest_y = $srcImgInfo[1] - $watermark_height - $marginBottom; if (class_exists('Imagick')) { return $this->watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo); } else { return $this->watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo); } }
protected function rm($args) { $result = parent::rm($args); foreach ($args['targets'] as $target) { // If the image has a corresponding Visual, remove it $path = $this->getPath($target); $v = Visual::get_by_path($path); if ($v) { $v->delete(); } } return $result; }
protected function configure() { parent::configure(); $this->tmpPath = ''; if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) { $this->tmpPath = $this->options['tmpPath']; } } if (!$this->tmpPath && ($tmp = elFinder::getStaticVar('commonTempPath'))) { $this->tmpPath = $tmp; } $this->mimeDetect = 'internal'; }
/** * Constructor * * @param array elFinder and roots configurations * @return void * @author nao-pon **/ public function __construct($opts) { parent::__construct($opts); $this->commands['perm'] = array('target' => true, 'perm' => true, 'umask' => false, 'gids' => false, 'filter' => false); }
/** * Long pooling sync checker * This function require server command `inotifywait` * If `inotifywait` need full path, Please add `define('ELFINER_INOTIFYWAIT_PATH', '/PATH_TO/inotifywait');` into connector.php * * @param string $path * @param int $standby * @param number $compare * @return number|bool */ public function localFileSystemInotify($path, $standby, $compare) { if (isset($this->sessionCache['localFileSystemInotify_disable'])) { return false; } $path = realpath($path); $mtime = filemtime($path); if ($mtime != $compare) { return $mtime; } $inotifywait = defined('ELFINER_INOTIFYWAIT_PATH') ? ELFINER_INOTIFYWAIT_PATH : 'inotifywait'; $path = escapeshellarg($path); $standby = max(1, intval($standby)); $cmd = $inotifywait . ' ' . $path . ' -t ' . $standby . ' -e moved_to,moved_from,move,close_write,delete,delete_self'; $this->procExec($cmd, $o, $r); if ($r === 0) { // changed clearstatcache(); $mtime = @filemtime($path); // error on busy? return $mtime ? $mtime : time(); } else { if ($r === 2) { // not changed (timeout) return $compare; } } // error // cache to $_SESSION $sessionStart = $this->sessionRestart(); if ($sessionStart) { $this->sessionCache['localFileSystemInotify_disable'] = true; elFinder::sessionWrite(); } return false; }
/** * Constructor * * @param array elFinder and roots configurations * @return void * @author Dmitry (dio) Levashov **/ public function __construct($opts) { if (session_id() == '') { session_start(); } $this->time = $this->utime(); $this->debug = isset($opts['debug']) && $opts['debug'] ? true : false; $this->timeout = isset($opts['timeout']) ? $opts['timeout'] : 0; $this->netVolumesSessionKey = !empty($opts['netVolumesSessionKey']) ? $opts['netVolumesSessionKey'] : 'elFinderNetVolumes'; $this->callbackWindowURL = isset($opts['callbackWindowURL']) ? $opts['callbackWindowURL'] : ''; self::$sessionCacheKey = !empty($opts['sessionCacheKey']) ? $opts['sessionCacheKey'] : 'elFinderCaches'; // check session cache $_optsMD5 = md5(json_encode($opts['roots'])); if (!isset($_SESSION[self::$sessionCacheKey]) || $_SESSION[self::$sessionCacheKey]['_optsMD5'] !== $_optsMD5) { $_SESSION[self::$sessionCacheKey] = array('_optsMD5' => $_optsMD5); } // setlocale and global locale regists to elFinder::locale self::$locale = !empty($opts['locale']) ? $opts['locale'] : 'en_US.UTF-8'; if (false === @setlocale(LC_ALL, self::$locale)) { self::$locale = setlocale(LC_ALL, ''); } // bind events listeners if (!empty($opts['bind']) && is_array($opts['bind'])) { $_req = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET; $_reqCmd = isset($_req['cmd']) ? $_req['cmd'] : ''; foreach ($opts['bind'] as $cmd => $handlers) { $doRegist = strpos($cmd, '*') !== false; if (!$doRegist) { $_getcmd = create_function('$cmd', 'list($ret) = explode(\'.\', $cmd);return trim($ret);'); $doRegist = $_reqCmd && in_array($_reqCmd, array_map($_getcmd, explode(' ', $cmd))); } if ($doRegist) { if (!is_array($handlers) || is_object($handlers[0])) { $handlers = array($handlers); } foreach ($handlers as $handler) { if ($handler) { if (is_string($handler) && strpos($handler, '.')) { list($_domain, $_name, $_method) = array_pad(explode('.', $handler), 3, ''); if (strcasecmp($_domain, 'plugin') === 0) { if ($plugin = $this->getPluginInstance($_name, isset($opts['plugin'][$_name]) ? $opts['plugin'][$_name] : array()) and method_exists($plugin, $_method)) { $this->bind($cmd, array($plugin, $_method)); } } } else { $this->bind($cmd, $handler); } } } } } } if (!isset($opts['roots']) || !is_array($opts['roots'])) { $opts['roots'] = array(); } // check for net volumes stored in session foreach ($this->getNetVolumes() as $root) { $opts['roots'][] = $root; } // "mount" volumes foreach ($opts['roots'] as $i => $o) { $class = 'elFinderVolume' . (isset($o['driver']) ? $o['driver'] : ''); if (class_exists($class)) { $volume = new $class(); try { if ($volume->mount($o)) { // unique volume id (ends on "_") - used as prefix to files hash $id = $volume->id(); $this->volumes[$id] = $volume; if (!$this->default && $volume->isReadable()) { $this->default = $this->volumes[$id]; } } else { $this->removeNetVolume($volume); $this->mountErrors[] = 'Driver "' . $class . '" : ' . implode(' ', $volume->error()); } } catch (Exception $e) { $this->removeNetVolume($volume); $this->mountErrors[] = 'Driver "' . $class . '" : ' . $e->getMessage(); } } else { $this->mountErrors[] = 'Driver "' . $class . '" does not exists'; } } // if at least one readable volume - ii desu >_< $this->loaded = !empty($this->default); }
/** * Output json * * @param array data to output * @return void * @author Dmitry (dio) Levashov **/ protected function output(array $data) { // clear output buffer while (@ob_get_level()) { @ob_end_clean(); } $header = isset($data['header']) ? $data['header'] : $this->header; unset($data['header']); if ($header) { if (is_array($header)) { foreach ($header as $h) { header($h); } } else { header($header); } } if (isset($data['pointer'])) { $toEnd = true; $fp = $data['pointer']; if (elFinder::isSeekableStream($fp)) { header('Accept-Ranges: bytes'); $psize = null; if (!empty($_SERVER['HTTP_RANGE'])) { $size = $data['info']['size']; $start = 0; $end = $size - 1; if (preg_match('/bytes=(\\d*)-(\\d*)(,?)/i', $_SERVER['HTTP_RANGE'], $matches)) { if (empty($matches[3])) { if (empty($matches[1]) && $matches[1] !== '0') { $start = $size - $matches[2]; } else { $start = intval($matches[1]); if (!empty($matches[2])) { $end = intval($matches[2]); if ($end >= $size) { $end = $size - 1; } $toEnd = $end == $size - 1; } } $psize = $end - $start + 1; header('HTTP/1.1 206 Partial Content'); header('Content-Length: ' . $psize); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size); fseek($fp, $start); } } } if (is_null($psize)) { rewind($fp); } } else { header('Accept-Ranges: none'); } // unlock session data for multiple access session_id() && session_write_close(); // client disconnect should abort ignore_user_abort(false); if ($toEnd) { fpassthru($fp); } else { $out = fopen('php://output', 'wb'); stream_copy_to_stream($fp, $out, $psize); fclose($out); } if (!empty($data['volume'])) { $data['volume']->close($data['pointer'], $data['info']['hash']); } exit; } else { if (!empty($data['raw']) && !empty($data['error'])) { exit($data['error']); } else { exit(json_encode($data)); } } }
/** * Configure after successfull mount. * * @return void * @author Dmitry (dio) Levashov **/ protected function configure() { parent::configure(); if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) { $this->tmp = $this->options['tmpPath']; } } if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) { $this->tmp = $tmp; } if (!$this->tmp && $this->tmbPath) { $this->tmp = $this->tmbPath; } if (!$this->tmp) { $this->disabled[] = 'mkfile'; $this->disabled[] = 'paste'; $this->disabled[] = 'duplicate'; $this->disabled[] = 'upload'; $this->disabled[] = 'edit'; $this->disabled[] = 'archive'; $this->disabled[] = 'extract'; } // echo $this->tmp; }
?> <?php echo $form->field($model, 'title')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'slug')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'image')->widget(InputFile::className(), ['language' => 'en', 'controller' => 'elfinder', 'path' => 'image', 'filter' => 'image', 'template' => '<div class="input-group">{input}<span class="input-group-btn">{button}</span></div>', 'options' => ['class' => 'form-control'], 'buttonOptions' => ['class' => 'btn btn-success'], 'multiple' => false]); ?> <?php echo $form->field($model, 'content')->widget(CKEditor::className(), ['editorOptions' => elFinder::ckeditorOptions(['elfinder'], ['preset' => 'standard', 'entities' => false])]); ?> <?php echo $form->field($model, 'meta_title')->textInput(); ?> <?php echo $form->field($model, 'meta_keywords')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'meta_description')->textInput(['maxlength' => true]); ?> <?php
/** * Clean cache * * @return void * @author Dmitry (dio) Levashov **/ protected function clearcache() { $this->cache = $this->dirsCache = array(); $this->sessionRestart(); unset($this->sessionCache['rootstat'][md5($this->root)]); elFinder::sessionWrite(); }
/** * Resize image * * @param string $hash image file * @param int $width new width * @param int $height new height * @param int $x X start poistion for crop * @param int $y Y start poistion for crop * @param string $mode action how to mainpulate image * @return array|false * @author Dmitry (dio) Levashov * @author Alexey Sukhotin * @author nao-pon * @author Troex Nevelin **/ public function resize($hash, $width, $height, $x, $y, $mode = 'resize', $bg = '', $degree = 0) { if ($this->commandDisabled('resize')) { return $this->setError(elFinder::ERROR_PERM_DENIED); } if (($file = $this->file($hash)) == false) { return $this->setError(elFinder::ERROR_FILE_NOT_FOUND); } if (!$file['write'] || !$file['read']) { return $this->setError(elFinder::ERROR_PERM_DENIED); } $path = $this->decode($hash); $work_path = $this->getWorkFile($this->encoding ? $this->convEncIn($path, true) : $path); if (!$work_path || !is_writable($work_path)) { if ($work_path && $path !== $work_path && is_file($work_path)) { @unlink($work_path); } return $this->setError(elFinder::ERROR_PERM_DENIED); } if ($this->imgLib != 'imagick') { if (elFinder::isAnimationGif($work_path)) { return $this->setError(elFinder::ERROR_UNSUPPORT_TYPE); } } switch ($mode) { case 'propresize': $result = $this->imgResize($work_path, $width, $height, true, true); break; case 'crop': $result = $this->imgCrop($work_path, $width, $height, $x, $y); break; case 'fitsquare': $result = $this->imgSquareFit($work_path, $width, $height, 'center', 'middle', $bg ? $bg : $this->options['tmbBgColor']); break; case 'rotate': $result = $this->imgRotate($work_path, $degree, $bg ? $bg : $this->options['tmbBgColor']); break; default: $result = $this->imgResize($work_path, $width, $height, false, true); break; } $ret = false; if ($result) { $stat = $this->stat($path); clearstatcache(); $fstat = stat($work_path); $stat['size'] = $fstat['size']; $stat['ts'] = $fstat['mtime']; if ($imgsize = @getimagesize($work_path)) { $stat['width'] = $imgsize[0]; $stat['height'] = $imgsize[1]; $stat['mime'] = $imgsize['mime']; } if ($path !== $work_path) { if ($fp = @fopen($work_path, 'rb')) { $ret = $this->saveCE($fp, $this->dirnameCE($path), $this->basenameCE($path), $stat); @fclose($fp); } } else { $ret = true; } if ($ret) { $this->rmTmb($file); $this->clearcache(); $ret = $this->stat($path); $ret['width'] = $stat['width']; $ret['height'] = $stat['height']; } } if ($path !== $work_path) { is_file($work_path) && @unlink($work_path); } return $ret; }
<?php error_reporting(0); // Set E_ALL for debuging if (function_exists('date_default_timezone_set')) { date_default_timezone_set('Europe/Moscow'); } include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'elFinder.class.php'; /** * Simple example how to use logger with elFinder **/ class elFinderLogger implements elFinderILogger { public function log($cmd, $ok, $context, $err = '', $errorData = array()) { if (false != ($fp = fopen('./log.txt', 'a'))) { if ($ok) { $str = "cmd: {$cmd}; OK; context: " . str_replace("\n", '', var_export($context, true)) . "; \n"; } else { $str = "cmd: {$cmd}; FAILED; context: " . str_replace("\n", '', var_export($context, true)) . "; error: {$err}; errorData: " . str_replace("\n", '', var_export($errorData, true)) . "\n"; } fwrite($fp, $str); fclose($fp); } } } $opts = array('root' => '../../files', 'URL' => 'http://localhost/mws/plugins/elfinder/files/', 'rootAlias' => 'Home'); $fm = new elFinder($opts); $fm->run();
/** * Save network volumes config. * * @param array $volumes volumes config * @return void * @author Dmitry (dio) Levashov */ protected function saveNetVolumes($volumes) { // try session restart @session_start(); $_SESSION[$this->netVolumesSessionKey] = elFinder::sessionDataEncode($volumes); elFinder::sessionWrite(); }
/** * Prepare FTP connection * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn * * @return bool * @author Dmitry (dio) Levashov * @author Cem (DiscoFever) **/ protected function init() { if (!class_exists('PDO', false)) { return $this->setError('PHP PDO class is require.'); } if (!$this->options['consumerKey'] || !$this->options['consumerSecret'] || !$this->options['accessToken'] || !$this->options['accessTokenSecret']) { return $this->setError('Required options undefined.'); } if (empty($this->options['metaCachePath']) && defined('ELFINDER_DROPBOX_META_CACHE_PATH')) { $this->options['metaCachePath'] = ELFINDER_DROPBOX_META_CACHE_PATH; } // make net mount key $this->netMountKey = md5(join('-', array('dropbox', $this->options['path']))); if (!$this->oauth) { if (defined('ELFINDER_DROPBOX_USE_CURL_PUT')) { $this->oauth = new Dropbox_OAuth_Curl($this->options['consumerKey'], $this->options['consumerSecret']); } else { if (class_exists('OAuth', false)) { $this->oauth = new Dropbox_OAuth_PHP($this->options['consumerKey'], $this->options['consumerSecret']); } else { if (!class_exists('HTTP_OAuth_Consumer')) { // We're going to try to load in manually include 'HTTP/OAuth/Consumer.php'; } if (class_exists('HTTP_OAuth_Consumer', false)) { $this->oauth = new Dropbox_OAuth_PEAR($this->options['consumerKey'], $this->options['consumerSecret']); } } } } if (!$this->oauth) { return $this->setError('OAuth extension not loaded.'); } // normalize root path $this->root = $this->options['path'] = $this->_normpath($this->options['path']); if (empty($this->options['alias'])) { $this->options['alias'] = $this->options['path'] === '/' ? 'Dropbox.com' : 'Dropbox' . $this->options['path']; } $this->rootName = $this->options['alias']; try { $this->oauth->setToken($this->options['accessToken'], $this->options['accessTokenSecret']); $this->dropbox = new Dropbox_API($this->oauth, $this->options['root']); } catch (Dropbox_Exception $e) { $this->session->remove('DropboxTokens'); return $this->setError('Dropbox error: ' . $e->getMessage()); } // user if (empty($this->options['dropboxUid'])) { try { $res = $this->dropbox->getAccountInfo(); $this->options['dropboxUid'] = $res['uid']; } catch (Dropbox_Exception $e) { $this->session->remove('DropboxTokens'); return $this->setError('Dropbox error: ' . $e->getMessage()); } } $this->dropboxUid = $this->options['dropboxUid']; $this->tmbPrefix = 'dropbox' . base_convert($this->dropboxUid, 10, 32); if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) { $this->tmp = $this->options['tmpPath']; } } if (!$this->tmp && is_writable($this->options['tmbPath'])) { $this->tmp = $this->options['tmbPath']; } if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) { $this->tmp = $tmp; } if (!empty($this->options['metaCachePath'])) { if ((is_dir($this->options['metaCachePath']) || mkdir($this->options['metaCachePath'])) && is_writable($this->options['metaCachePath'])) { $this->metaCache = $this->options['metaCachePath']; } } if (!$this->metaCache && $this->tmp) { $this->metaCache = $this->tmp; } if (!$this->metaCache) { return $this->setError('Cache dirctory (metaCachePath or tmp) is require.'); } // setup PDO if (!$this->options['PDO_DSN']) { $this->options['PDO_DSN'] = 'sqlite:' . $this->metaCache . DIRECTORY_SEPARATOR . '.elFinder_dropbox_db_' . md5($this->dropboxUid . $this->options['consumerSecret']); } // DataBase table name $this->DB_TableName = $this->options['PDO_DBName']; // DataBase check or make table try { $this->DB = new PDO($this->options['PDO_DSN'], $this->options['PDO_User'], $this->options['PDO_Pass'], $this->options['PDO_Options']); if (!$this->checkDB()) { return $this->setError('Can not make DB table'); } } catch (PDOException $e) { return $this->setError('PDO connection failed: ' . $e->getMessage()); } $res = $this->deltaCheck($this->isMyReload()); if ($res !== true) { if (is_string($res)) { return $this->setError($res); } else { return $this->setError('Could not check API "delta"'); } } if (is_null($this->options['syncChkAsTs'])) { $this->options['syncChkAsTs'] = true; } if ($this->options['syncChkAsTs']) { // 'tsPlSleep' minmum 5 sec $this->options['tsPlSleep'] = max(5, $this->options['tsPlSleep']); } else { // 'lsPlSleep' minmum 10 sec $this->options['lsPlSleep'] = max(10, $this->options['lsPlSleep']); } return true; }
/** * Return file info (used by client "places" ui) * * @param array $args command arguments * @return array * @author Dmitry Levashov **/ protected function info($args) { $files = array(); $sleep = 0; $compare = null; // long polling mode if ($args['compare'] && count($args['targets']) === 1) { $compare = intval($args['compare']); $hash = $args['targets'][0]; if ($volume = $this->volume($hash)) { $standby = (int) $volume->getOption('plStandby'); $_compare = false; if (($syncCheckFunc = $volume->getOption('syncCheckFunc')) && is_callable($syncCheckFunc)) { $_compare = call_user_func_array($syncCheckFunc, array($volume->realpath($hash), $standby, $compare, $volume, $this)); } if ($_compare !== false) { $compare = $_compare; } else { $sleep = max(1, (int) $volume->getOption('tsPlSleep')); $limit = max(1, $standby / $sleep) + 1; do { elFinder::extendTimeLimit(30 + $sleep); $volume->clearstatcache(); if (($info = $volume->file($hash)) != false) { if ($info['ts'] != $compare) { $compare = $info['ts']; break; } } else { $compare = 0; break; } if (--$limit) { sleep($sleep); } } while ($limit); } } } else { foreach ($args['targets'] as $hash) { if (($volume = $this->volume($hash)) != false && ($info = $volume->file($hash)) != false) { $info['path'] = $volume->path($hash); $files[] = $info; } } } $result = array('files' => $files); if (!is_null($compare)) { $result['compare'] = strval($compare); } return $result; }
/** * Set tmp path * * @return void * @author Dmitry (dio) Levashov **/ protected function configure() { parent::configure(); if ($tmp = $this->options['tmpPath']) { if (!file_exists($tmp)) { if (@mkdir($tmp)) { @chmod($tmp, $this->options['tmbPathMode']); } } $this->tmpPath = is_dir($tmp) && is_writable($tmp) ? $tmp : false; } if (!$this->tmpPath && ($tmp = elFinder::getStaticVar('commonTempPath'))) { $this->tmpPath = $tmp; } if (!$this->tmpPath && $this->tmbPath && $this->tmbPathWritable) { $this->tmpPath = $this->tmbPath; } $this->mimeDetect = 'internal'; }
public function __construct($opts) { parent::__construct($opts); $this->commands['desc'] = array('target' => TRUE, 'content' => FALSE); }
/** * Save network volumes config. * * @param array $volumes volumes config * @return void * @author Dmitry (dio) Levashov */ protected function saveNetVolumes($volumes) { $_SESSION[$this->netVolumesSessionKey] = elFinder::sessionDataEncode($volumes); }
public function run() { require_once dirname(__FILE__) . '/php/elFinder.class.php'; $fm = new \elFinder($this->settings); $fm->run(); }
/** * Configure after successfull mount. * * @return void * @author Dmitry (dio) Levashov **/ protected function configure() { $root = $this->stat($this->root); // chek thumbnails path if ($this->options['tmbPath']) { $this->options['tmbPath'] = strpos($this->options['tmbPath'], DIRECTORY_SEPARATOR) === false ? $this->_abspath($this->options['tmbPath']) : $this->_normpath($this->options['tmbPath']); } parent::configure(); // set $this->tmp by options['tmpPath'] $this->tmp = ''; if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) { $this->tmp = $this->options['tmpPath']; } } if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) { $this->tmp = $tmp; } // if no thumbnails url - try detect it if ($root['read'] && !$this->tmbURL && $this->URL) { if (strpos($this->tmbPath, $this->root) === 0) { $this->tmbURL = $this->URL . str_replace(DIRECTORY_SEPARATOR, '/', substr($this->tmbPath, strlen($this->root) + 1)); if (preg_match("|[^/?&=]\$|", $this->tmbURL)) { $this->tmbURL .= '/'; } } } // check quarantine dir $this->quarantine = ''; if (!empty($this->options['quarantine'])) { if (is_dir($this->options['quarantine'])) { if (is_writable($this->options['quarantine'])) { $this->quarantine = $this->options['quarantine']; } $this->options['quarantine'] = ''; } else { $this->quarantine = $this->_abspath($this->options['quarantine']); if (!is_dir($this->quarantine) && !$this->_mkdir($this->root, $this->options['quarantine']) || !is_writable($this->quarantine)) { $this->options['quarantine'] = $this->quarantine = ''; } } } if (!$this->quarantine) { if (!$this->tmp) { $this->archivers['extract'] = array(); $this->disabled[] = 'extract'; } else { $this->quarantine = $this->tmp; } } if ($this->options['quarantine']) { $this->attributes[] = array('pattern' => '~^' . preg_quote(DIRECTORY_SEPARATOR . $this->options['quarantine']) . '$~', 'read' => false, 'write' => false, 'locked' => true, 'hidden' => true); } }
/** * Create new file and write into it from file pointer. * Return new file path or false on error. * * @param resource $fp file pointer * @param string $dir target dir path * @param string $name file name * @param array $stat file stat (required by some virtual fs) * @return bool|string * @author Dmitry (dio) Levashov **/ protected function _save($fp, $dir, $name, $stat) { $this->clearcache(); $mime = $stat['mime']; $w = !empty($stat['width']) ? $stat['width'] : 0; $h = !empty($stat['height']) ? $stat['height'] : 0; $id = $this->_joinPath($dir, $name); elFinder::rewind($fp); $stat = fstat($fp); $size = $stat['size']; if ($tmpfile = tempnam($this->tmpPath, $this->id)) { if (($trgfp = fopen($tmpfile, 'wb')) == false) { unlink($tmpfile); } else { while (!feof($fp)) { fwrite($trgfp, fread($fp, 8192)); } fclose($trgfp); chmod($tmpfile, 0644); $sql = $id > 0 ? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES (' . $id . ', %d, \'%s\', LOAD_FILE(\'%s\'), %d, %d, \'%s\', %d, %d)' : 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \'%s\', LOAD_FILE(\'%s\'), %d, %d, \'%s\', %d, %d)'; $sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->loadFilePath($tmpfile), $size, time(), $mime, $w, $h); $res = $this->query($sql); unlink($tmpfile); if ($res) { return $id > 0 ? $id : $this->db->insert_id; } } } $content = ''; elFinder::rewind($fp); while (!feof($fp)) { $content .= fread($fp, 8192); } $sql = $id > 0 ? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES (' . $id . ', %d, \'%s\', \'%s\', %d, %d, \'%s\', %d, %d)' : 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \'%s\', \'%s\', %d, %d, \'%s\', %d, %d)'; $sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->db->real_escape_string($content), $size, time(), $mime, $w, $h); unset($content); if ($this->query($sql)) { return $id > 0 ? $id : $this->db->insert_id; } return false; }
/** * Output json * * @param array data to output * @return void * @author Dmitry (dio) Levashov **/ protected function output(array $data) { // clear output buffer while (ob_get_level() && ob_end_clean()) { } $header = isset($data['header']) ? $data['header'] : $this->header; unset($data['header']); if ($header) { if (is_array($header)) { foreach ($header as $h) { header($h); } } else { header($header); } } if (isset($data['pointer'])) { $toEnd = true; $fp = $data['pointer']; if (($this->reqMethod === 'GET' || $this->reqMethod === 'HEAD') && elFinder::isSeekableStream($fp) && array_search('Accept-Ranges: none', headers_list()) === false) { header('Accept-Ranges: bytes'); $psize = null; if (!empty($_SERVER['HTTP_RANGE'])) { $size = $data['info']['size']; $start = 0; $end = $size - 1; if (preg_match('/bytes=(\\d*)-(\\d*)(,?)/i', $_SERVER['HTTP_RANGE'], $matches)) { if (empty($matches[3])) { if (empty($matches[1]) && $matches[1] !== '0') { $start = $size - $matches[2]; } else { $start = intval($matches[1]); if (!empty($matches[2])) { $end = intval($matches[2]); if ($end >= $size) { $end = $size - 1; } $toEnd = $end == $size - 1; } } $psize = $end - $start + 1; header('HTTP/1.1 206 Partial Content'); header('Content-Length: ' . $psize); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size); fseek($fp, $start); } } } if (is_null($psize)) { elFinder::rewind($fp); } } else { header('Accept-Ranges: none'); if (isset($data['info']) && !$data['info']['size']) { if (function_exists('header_remove')) { header_remove('Content-Length'); } else { header('Content-Length:'); } } } // unlock session data for multiple access $this->elFinder->getSession()->close(); // client disconnect should abort ignore_user_abort(false); if ($reqMethod !== 'HEAD') { if ($toEnd) { fpassthru($fp); } else { $out = fopen('php://output', 'wb'); stream_copy_to_stream($fp, $out, $psize); fclose($out); } } if (!empty($data['volume'])) { $data['volume']->close($data['pointer'], $data['info']['hash']); } exit; } else { if (!empty($data['raw']) && !empty($data['error'])) { echo $data['error']; } else { if (isset($data['debug']) && isset($data['debug']['phpErrors'])) { $data['debug']['phpErrors'] = array_merge($data['debug']['phpErrors'], elFinder::$phpErrors); } echo json_encode($data); } flush(); exit(0); } }
/** * Return fileinfo * * @param string $path file cache * @return array * @author Dmitry (dio) Levashov **/ protected function stat($path) { if ($path === false || is_null($path)) { return false; } $is_root = $path == $this->root; if ($is_root) { $rootKey = md5($path); if (!isset($this->sessionCache['rootstat'])) { $this->sessionCache['rootstat'] = array(); } if (!$this->isMyReload()) { // need $path as key for netmount/netunmount if (isset($this->sessionCache['rootstat'][$rootKey])) { if ($ret = elFinder::sessionDataDecode($this->sessionCache['rootstat'][$rootKey], 'array')) { return $ret; } } } } $ret = isset($this->cache[$path]) ? $this->cache[$path] : $this->updateCache($path, $this->convEncOut($this->_stat($this->convEncIn($path)))); if ($is_root) { $this->sessionRestart(); $this->sessionCache['rootstat'][$rootKey] = elFinder::sessionDataEncode($ret); } return $ret; }