[php] change code style to PSR-2 of all of php files

This commit is contained in:
nao-pon
2019-01-01 21:18:39 +09:00
parent abc52cc9ce
commit 15cc46ea27
29 changed files with 19080 additions and 18403 deletions
+45 -44
View File
@@ -2,53 +2,54 @@
define('ELFINDER_PHP_ROOT_PATH', dirname(__FILE__));
function elFinderAutoloader($name) {
$map = array(
'elFinder' => 'elFinder.class.php',
'elFinderConnector' => 'elFinderConnector.class.php',
'elFinderEditor' => 'editors/editor.php',
'elFinderLibGdBmp' => 'libs/GdBmp.php',
'elFinderPlugin' => 'elFinderPlugin.php',
'elFinderPluginAutoResize' => 'plugins/AutoResize/plugin.php',
'elFinderPluginAutoRotate' => 'plugins/AutoRotate/plugin.php',
'elFinderPluginNormalizer' => 'plugins/Normalizer/plugin.php',
'elFinderPluginSanitizer' => 'plugins/Sanitizer/plugin.php',
'elFinderPluginWatermark' => 'plugins/Watermark/plugin.php',
'elFinderSession' => 'elFinderSession.php',
'elFinderSessionInterface' => 'elFinderSessionInterface.php',
'elFinderVolumeDriver' => 'elFinderVolumeDriver.class.php',
'elFinderVolumeDropbox2' => 'elFinderVolumeDropbox2.class.php',
'elFinderVolumeFTP' => 'elFinderVolumeFTP.class.php',
'elFinderVolumeFlysystemGoogleDriveCache' => 'elFinderFlysystemGoogleDriveNetmount.php',
'elFinderVolumeFlysystemGoogleDriveNetmount' => 'elFinderFlysystemGoogleDriveNetmount.php',
'elFinderVolumeGoogleDrive' => 'elFinderVolumeGoogleDrive.class.php',
'elFinderVolumeGroup' => 'elFinderVolumeGroup.class.php',
'elFinderVolumeLocalFileSystem' => 'elFinderVolumeLocalFileSystem.class.php',
'elFinderVolumeMySQL' => 'elFinderVolumeMySQL.class.php',
'elFinderVolumeTrash' => 'elFinderVolumeTrash.class.php',
);
if (isset($map[$name])) {
return include_once(ELFINDER_PHP_ROOT_PATH . '/' . $map[$name]);
}
$prefix = substr($name, 0, 14);
if (substr($prefix, 0, 8) === 'elFinder') {
if ($prefix === 'elFinderVolume') {
$file = ELFINDER_PHP_ROOT_PATH . '/' . $name . '.class.php';
return (is_file($file) && include_once($file));
} else if ($prefix === 'elFinderPlugin') {
$file = ELFINDER_PHP_ROOT_PATH . '/plugins/' . substr($name, 14) . '/plugin.php';
return (is_file($file) && include_once($file));
} else if ($prefix === 'elFinderEditor') {
$file = ELFINDER_PHP_ROOT_PATH . '/editors/' . substr($name, 14) . '/editor.php';
return (is_file($file) && include_once($file));
}
}
return false;
function elFinderAutoloader($name)
{
$map = array(
'elFinder' => 'elFinder.class.php',
'elFinderConnector' => 'elFinderConnector.class.php',
'elFinderEditor' => 'editors/editor.php',
'elFinderLibGdBmp' => 'libs/GdBmp.php',
'elFinderPlugin' => 'elFinderPlugin.php',
'elFinderPluginAutoResize' => 'plugins/AutoResize/plugin.php',
'elFinderPluginAutoRotate' => 'plugins/AutoRotate/plugin.php',
'elFinderPluginNormalizer' => 'plugins/Normalizer/plugin.php',
'elFinderPluginSanitizer' => 'plugins/Sanitizer/plugin.php',
'elFinderPluginWatermark' => 'plugins/Watermark/plugin.php',
'elFinderSession' => 'elFinderSession.php',
'elFinderSessionInterface' => 'elFinderSessionInterface.php',
'elFinderVolumeDriver' => 'elFinderVolumeDriver.class.php',
'elFinderVolumeDropbox2' => 'elFinderVolumeDropbox2.class.php',
'elFinderVolumeFTP' => 'elFinderVolumeFTP.class.php',
'elFinderVolumeFlysystemGoogleDriveCache' => 'elFinderFlysystemGoogleDriveNetmount.php',
'elFinderVolumeFlysystemGoogleDriveNetmount' => 'elFinderFlysystemGoogleDriveNetmount.php',
'elFinderVolumeGoogleDrive' => 'elFinderVolumeGoogleDrive.class.php',
'elFinderVolumeGroup' => 'elFinderVolumeGroup.class.php',
'elFinderVolumeLocalFileSystem' => 'elFinderVolumeLocalFileSystem.class.php',
'elFinderVolumeMySQL' => 'elFinderVolumeMySQL.class.php',
'elFinderVolumeTrash' => 'elFinderVolumeTrash.class.php',
);
if (isset($map[$name])) {
return include_once(ELFINDER_PHP_ROOT_PATH . '/' . $map[$name]);
}
$prefix = substr($name, 0, 14);
if (substr($prefix, 0, 8) === 'elFinder') {
if ($prefix === 'elFinderVolume') {
$file = ELFINDER_PHP_ROOT_PATH . '/' . $name . '.class.php';
return (is_file($file) && include_once($file));
} else if ($prefix === 'elFinderPlugin') {
$file = ELFINDER_PHP_ROOT_PATH . '/plugins/' . substr($name, 14) . '/plugin.php';
return (is_file($file) && include_once($file));
} else if ($prefix === 'elFinderEditor') {
$file = ELFINDER_PHP_ROOT_PATH . '/editors/' . substr($name, 14) . '/editor.php';
return (is_file($file) && include_once($file));
}
}
return false;
}
if (version_compare(PHP_VERSION, '5.3', '<')) {
spl_autoload_register('elFinderAutoloader');
spl_autoload_register('elFinderAutoloader');
} else {
spl_autoload_register('elFinderAutoloader', true, true);
spl_autoload_register('elFinderAutoloader', true, true);
}
+21 -21
View File
@@ -7,36 +7,36 @@ echo 'белая собака';
echo strToLower('белая собака');
$orig = 'ёЁйЙØÅŻ';
echo $orig.'<br>';
echo $orig . '<br>';
$path = '../../../files/tmp/';
if (!touch($path.$orig)) {
exit('unable to create file');
if (!touch($path . $orig)) {
exit('unable to create file');
}
$orig = str_replace('"', '', json_encode($orig));
echo "original: ".$orig.'<br>';
echo "original: " . $orig . '<br>';
$origParts = explode('\\', $orig);
array_shift($origParts);
// й ё Й Ё Ø Å
$patterns = array("\u0438\u0306", "\u0435\u0308", "\u0418\u0306", "\u0415\u0308", "\u00d8A", "\u030a");
$replace = array("\u0439", "\u0451", "\u0419", "\u0401", "\u00d8", "\u00c5");
$replace = array("\u0439", "\u0451", "\u0419", "\u0401", "\u00d8", "\u00c5");
foreach(scandir($path) as $f) {
if ($f != '.' && $f != '..' && substr($f, 0, 1) != '.') {
// echo mb_detect_encoding($f);
$name = str_replace('"', '', json_encode($f));
echo "before replace: $name<br>";
// $name = str_replace($patterns, $replace, $name);
// echo "after replace: $name<br>";
break;
}
foreach (scandir($path) as $f) {
if ($f != '.' && $f != '..' && substr($f, 0, 1) != '.') {
// echo mb_detect_encoding($f);
$name = str_replace('"', '', json_encode($f));
echo "before replace: $name<br>";
// $name = str_replace($patterns, $replace, $name);
// echo "after replace: $name<br>";
break;
}
}
@@ -47,10 +47,10 @@ array_shift($parts);
$diff = array_diff($parts, $origParts);
if (count($diff)) {
echo "Following symbols not found in original";
echo '<pre>';
print_r($diff);
echo '</pre>';
echo "Following symbols not found in original";
echo '<pre>';
print_r($diff);
echo '</pre>';
} else {
echo "OK";
echo "OK";
}
+4 -4
View File
@@ -28,7 +28,7 @@ class elFinderEditorOnlineConvert extends elFinderEditor
$string_method = '';
$options = array();
// Currently these converts are make error with API call. I don't know why.
$nonApi = array('android','blackberry','dpg','ipad','iphone','ipod','nintendo-3ds','nintendo-ds','ps3','psp','wii','xbox');
$nonApi = array('android', 'blackberry', 'dpg', 'ipad', 'iphone', 'ipod', 'nintendo-3ds', 'nintendo-ds', 'ps3', 'psp', 'wii', 'xbox');
if (in_array($convert, $nonApi)) {
return array('apires' => array());
}
@@ -88,17 +88,17 @@ class elFinderEditorOnlineConvert extends elFinderEditor
if ($ch) {
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$error = curl_error($ch);
$error = curl_error($ch);
curl_close($ch);
if (! empty($error)) {
if (!empty($error)) {
$res = array('error' => $error);
} else {
$data = json_decode($response, true);
if (isset($data['status']) && isset($data['status']['code']) && $data['status']['code'] === 'completed') {
$session = $this->elfinder->getSession();
$urlContentSaveIds = $session->get('urlContentSaveIds', array());
$urlContentSaveIds['OnlineConvert-'.$data['id']] = true;
$urlContentSaveIds['OnlineConvert-' . $data['id']] = true;
$session->set('urlContentSaveIds', $urlContentSaveIds);
}
$res = array('apires' => $data);
+3 -3
View File
@@ -5,8 +5,8 @@ class elFinderEditorZipArchive extends elFinderEditor
public function enabled()
{
return (!defined('ELFINDER_DISABLE_ZIPEDITOR') || !ELFINDER_DISABLE_ZIPEDITOR) &&
class_exists('Barryvdh\elFinderFlysystemDriver\Driver') &&
class_exists('League\Flysystem\Filesystem') &&
class_exists('League\Flysystem\ZipArchive\ZipArchiveAdapter');
class_exists('Barryvdh\elFinderFlysystemDriver\Driver') &&
class_exists('League\Flysystem\Filesystem') &&
class_exists('League\Flysystem\ZipArchive\ZipArchiveAdapter');
}
}
+4 -4
View File
@@ -50,7 +50,7 @@ class elFinderEditorZohoOffice extends elFinderEditor
$cookie = $this->elfinder->getFetchCookieFile();
$save = false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, elFinder::getConnectorUrl().'?cmd=editor&name=ZohoOffice&method=chk&args[target]='.rawurlencode($hash).$cdata);
curl_setopt($ch, CURLOPT_URL, elFinder::getConnectorUrl() . '?cmd=editor&name=ZohoOffice&method=chk&args[target]=' . rawurlencode($hash) . $cdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($cookie) {
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
@@ -77,7 +77,7 @@ class elFinderEditorZohoOffice extends elFinderEditor
$cfile->setPostFilename($file['name']);
$cfile->setMimeType($file['mime']);
} else {
$cfile = '@'.$srcFile;
$cfile = '@' . $srcFile;
}
}
}
@@ -101,7 +101,7 @@ class elFinderEditorZohoOffice extends elFinderEditor
'lang' => $lang
);
if ($save) {
$data['saveurl'] = elFinder::getConnectorUrl().'?cmd=editor&name=ZohoOffice&method=save'.$cdata;
$data['saveurl'] = elFinder::getConnectorUrl() . '?cmd=editor&name=ZohoOffice&method=save' . $cdata;
}
if ($cfile) {
$data['content'] = $cfile;
@@ -146,7 +146,7 @@ class elFinderEditorZohoOffice extends elFinderEditor
public function save()
{
if (isset($_POST) && ! empty($_POST['id'])) {
if (isset($_POST) && !empty($_POST['id'])) {
$hash = $_POST['id'];
if ($volume = $this->elfinder->getVolume($hash)) {
$content = file_get_contents($_FILES['content']['tmp_name']);
+4 -3
View File
@@ -1,4 +1,5 @@
<?php
/**
* Abstract class of editor plugins.
*
@@ -66,13 +67,13 @@ class elFinderEditor
/**
* Return $this->args value of the key
*
* @param string $key target key
* @param string $empty empty value
* @param string $key target key
* @param string $empty empty value
*
* @return mixed
*/
public function argValue($key, $empty = '')
{
return isset($this->args[$key])? $this->args[$key] : $empty;
return isset($this->args[$key]) ? $this->args[$key] : $empty;
}
}
+4722 -4555
View File
File diff suppressed because it is too large Load Diff
+358 -345
View File
@@ -5,351 +5,364 @@
*
* @author Dmitry (dio) Levashov
**/
class elFinderConnector {
/**
* elFinder instance
*
* @var elFinder
**/
protected $elFinder;
/**
* Options
*
* @var array
**/
protected $options = array();
/**
* Must be use output($data) $data['header']
*
* @var string
* @deprecated
**/
protected $header = '';
class elFinderConnector
{
/**
* elFinder instance
*
* @var elFinder
**/
protected $elFinder;
/**
* HTTP request method
*
* @var string
*/
protected $reqMethod = '';
/**
* Content type of output JSON
*
* @var string
*/
protected static $contentType = 'Content-Type: application/json; charset=utf-8';
/**
* Constructor
*
* @param $elFinder
* @param bool $debug
* @author Dmitry (dio) Levashov
*/
public function __construct($elFinder, $debug=false) {
$this->elFinder = $elFinder;
$this->reqMethod = strtoupper($_SERVER["REQUEST_METHOD"]);
if ($debug) {
self::$contentType = 'Content-Type: text/plain; charset=utf-8';
}
}
/**
* Execute elFinder command and output result
*
* @return void
* @throws Exception
* @author Dmitry (dio) Levashov
*/
public function run() {
$isPost = $this->reqMethod === 'POST';
$src = $isPost ? array_merge($_GET, $_POST) : $_GET;
$maxInputVars = (! $src || isset($src['targets']))? ini_get('max_input_vars') : null;
if ((! $src || $maxInputVars) && $rawPostData = file_get_contents('php://input')) {
// for max_input_vars and supports IE XDomainRequest()
$parts = explode('&', $rawPostData);
if (! $src || $maxInputVars < count($parts)) {
$src = array();
foreach($parts as $part) {
list($key, $value) = array_pad(explode('=', $part), 2, '');
$key = rawurldecode($key);
if (preg_match('/^(.+?)\[([^\[\]]*)\]$/', $key, $m)) {
$key = $m[1];
$idx = $m[2];
if (!isset($src[$key])) {
$src[$key] = array();
}
if ($idx) {
$src[$key][$idx] = rawurldecode($value);
} else {
$src[$key][] = rawurldecode($value);
}
} else {
$src[$key] = rawurldecode($value);
}
}
$_POST = $this->input_filter($src);
$_REQUEST = $this->input_filter(array_merge_recursive($src, $_REQUEST));
}
}
if (isset($src['targets']) && $this->elFinder->maxTargets && count($src['targets']) > $this->elFinder->maxTargets) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_MAX_TARGTES)));
}
$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), 'debug' => $this->elFinder->mountErrors));
}
// telepat_mode: on
if (!$cmd && $isPost) {
$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)) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD)));
}
// collect required arguments to exec command
$hasFiles = false;
foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) {
if ($name === 'FILES') {
if (isset($_FILES)) {
$hasFiles = true;
} elseif ($req) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
} else {
$arg = isset($src[$name])? $src[$name] : '';
if (!is_array($arg) && $req !== '') {
$arg = trim($arg);
}
if ($req && $arg === '') {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
$args[$name] = $arg;
}
}
$args['debug'] = isset($src['debug']) ? !!$src['debug'] : false;
$args = $this->input_filter($args);
if ($hasFiles) {
$args['FILES'] = $_FILES;
}
try {
$this->output($this->elFinder->exec($cmd, $args));
} catch (elFinderAbortException $e) {
// connection aborted
// unlock session data for multiple access
$this->elFinder->getSession()->close();
// HTTP response code
header('HTTP/1.0 204 No Content');
// clear output buffer
while(ob_get_level() && ob_end_clean()){}
exit();
}
}
/**
* Output json
*
* @param array data to output
* @return void
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
protected function output(array $data) {
// unlock session data for multiple access
$this->elFinder->getSession()->close();
// client disconnect should abort
ignore_user_abort(false);
if ($this->header) {
self::sendHeader($this->header);
}
if (isset($data['pointer'])) {
// set time limit to 0
elFinder::extendTimeLimit(0);
// send optional header
if (!empty($data['header'])) {
self::sendHeader($data['header']);
}
// clear output buffer
while(ob_get_level() && ob_end_clean()){}
$toEnd = true;
$fp = $data['pointer'];
$sendData = !($this->reqMethod === 'HEAD' || !empty($data['info']['xsendfile']));
$psize = null;
if (($this->reqMethod === 'GET' || !$sendData)
&& elFinder::isSeekableStream($fp)
&& (array_search('Accept-Ranges: none', headers_list()) === false)) {
header('Accept-Ranges: bytes');
if (!empty($_SERVER['HTTP_RANGE'])) {
$size = $data['info']['size'];
$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);
// Apache mod_xsendfile dose not support range request
if (isset($data['info']['xsendfile']) && strtolower($data['info']['xsendfile']) === 'x-sendfile') {
if (function_exists('header_remove')) {
header_remove($data['info']['xsendfile']);
} else {
header($data['info']['xsendfile'] . ':');
}
unset($data['info']['xsendfile']);
if ($this->reqMethod !== 'HEAD') {
$sendData = true;
}
}
$sendData && fseek($fp, $start);
}
}
}
if ($sendData && 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:');
}
}
}
/**
* Options
*
* @var array
**/
protected $options = array();
if ($sendData) {
if ($toEnd) {
// PHP < 5.6 has a bug of fpassthru
// see https://bugs.php.net/bug.php?id=66736
if (version_compare(PHP_VERSION, '5.6', '<')) {
file_put_contents('php://output', $fp);
} else {
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 {
self::outputJson($data);
exit(0);
}
}
/**
* Remove null & stripslashes applies on "magic_quotes_gpc"
*
* @param mixed $args
* @return mixed
* @author Naoki Sawada
*/
protected function input_filter($args) {
static $magic_quotes_gpc = NULL;
if ($magic_quotes_gpc === NULL)
$magic_quotes_gpc = (version_compare(PHP_VERSION, '5.4', '<') && get_magic_quotes_gpc());
if (is_array($args)) {
return array_map(array(& $this, 'input_filter'), $args);
}
$res = str_replace("\0", '', $args);
$magic_quotes_gpc && ($res = stripslashes($res));
return $res;
}
/**
* Send HTTP header
*
* @param string|array $header optional header
*/
protected static function sendHeader($header = null) {
if ($header) {
if (is_array($header)) {
foreach ($header as $h) {
header($h);
}
} else {
header($header);
}
}
}
/**
* Output JSON
*
* @param array $data
*/
public static function outputJson($data) {
// send header
$header = isset($data['header']) ? $data['header'] : self::$contentType;
self::sendHeader($header);
unset($data['header']);
if (!empty($data['raw']) && isset($data['error'])) {
$out = $data['error'];
} else {
if (isset($data['debug']) && isset($data['debug']['phpErrors'])) {
$data['debug']['phpErrors'] = array_merge($data['debug']['phpErrors'], elFinder::$phpErrors);
}
$out = json_encode($data);
}
// clear output buffer
while(ob_get_level() && ob_end_clean()){}
header('Content-Length: ' . strlen($out));
echo $out;
flush();
}
/**
* Must be use output($data) $data['header']
*
* @var string
* @deprecated
**/
protected $header = '';
/**
* HTTP request method
*
* @var string
*/
protected $reqMethod = '';
/**
* Content type of output JSON
*
* @var string
*/
protected static $contentType = 'Content-Type: application/json; charset=utf-8';
/**
* Constructor
*
* @param $elFinder
* @param bool $debug
*
* @author Dmitry (dio) Levashov
*/
public function __construct($elFinder, $debug = false)
{
$this->elFinder = $elFinder;
$this->reqMethod = strtoupper($_SERVER["REQUEST_METHOD"]);
if ($debug) {
self::$contentType = 'Content-Type: text/plain; charset=utf-8';
}
}
/**
* Execute elFinder command and output result
*
* @return void
* @throws Exception
* @author Dmitry (dio) Levashov
*/
public function run()
{
$isPost = $this->reqMethod === 'POST';
$src = $isPost ? array_merge($_GET, $_POST) : $_GET;
$maxInputVars = (!$src || isset($src['targets'])) ? ini_get('max_input_vars') : null;
if ((!$src || $maxInputVars) && $rawPostData = file_get_contents('php://input')) {
// for max_input_vars and supports IE XDomainRequest()
$parts = explode('&', $rawPostData);
if (!$src || $maxInputVars < count($parts)) {
$src = array();
foreach ($parts as $part) {
list($key, $value) = array_pad(explode('=', $part), 2, '');
$key = rawurldecode($key);
if (preg_match('/^(.+?)\[([^\[\]]*)\]$/', $key, $m)) {
$key = $m[1];
$idx = $m[2];
if (!isset($src[$key])) {
$src[$key] = array();
}
if ($idx) {
$src[$key][$idx] = rawurldecode($value);
} else {
$src[$key][] = rawurldecode($value);
}
} else {
$src[$key] = rawurldecode($value);
}
}
$_POST = $this->input_filter($src);
$_REQUEST = $this->input_filter(array_merge_recursive($src, $_REQUEST));
}
}
if (isset($src['targets']) && $this->elFinder->maxTargets && count($src['targets']) > $this->elFinder->maxTargets) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_MAX_TARGTES)));
}
$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), 'debug' => $this->elFinder->mountErrors));
}
// telepat_mode: on
if (!$cmd && $isPost) {
$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)) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD)));
}
// collect required arguments to exec command
$hasFiles = false;
foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) {
if ($name === 'FILES') {
if (isset($_FILES)) {
$hasFiles = true;
} elseif ($req) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
} else {
$arg = isset($src[$name]) ? $src[$name] : '';
if (!is_array($arg) && $req !== '') {
$arg = trim($arg);
}
if ($req && $arg === '') {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
$args[$name] = $arg;
}
}
$args['debug'] = isset($src['debug']) ? !!$src['debug'] : false;
$args = $this->input_filter($args);
if ($hasFiles) {
$args['FILES'] = $_FILES;
}
try {
$this->output($this->elFinder->exec($cmd, $args));
} catch (elFinderAbortException $e) {
// connection aborted
// unlock session data for multiple access
$this->elFinder->getSession()->close();
// HTTP response code
header('HTTP/1.0 204 No Content');
// clear output buffer
while (ob_get_level() && ob_end_clean()) {
}
exit();
}
}
/**
* Output json
*
* @param array data to output
*
* @return void
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
protected function output(array $data)
{
// unlock session data for multiple access
$this->elFinder->getSession()->close();
// client disconnect should abort
ignore_user_abort(false);
if ($this->header) {
self::sendHeader($this->header);
}
if (isset($data['pointer'])) {
// set time limit to 0
elFinder::extendTimeLimit(0);
// send optional header
if (!empty($data['header'])) {
self::sendHeader($data['header']);
}
// clear output buffer
while (ob_get_level() && ob_end_clean()) {
}
$toEnd = true;
$fp = $data['pointer'];
$sendData = !($this->reqMethod === 'HEAD' || !empty($data['info']['xsendfile']));
$psize = null;
if (($this->reqMethod === 'GET' || !$sendData)
&& elFinder::isSeekableStream($fp)
&& (array_search('Accept-Ranges: none', headers_list()) === false)) {
header('Accept-Ranges: bytes');
if (!empty($_SERVER['HTTP_RANGE'])) {
$size = $data['info']['size'];
$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);
// Apache mod_xsendfile dose not support range request
if (isset($data['info']['xsendfile']) && strtolower($data['info']['xsendfile']) === 'x-sendfile') {
if (function_exists('header_remove')) {
header_remove($data['info']['xsendfile']);
} else {
header($data['info']['xsendfile'] . ':');
}
unset($data['info']['xsendfile']);
if ($this->reqMethod !== 'HEAD') {
$sendData = true;
}
}
$sendData && fseek($fp, $start);
}
}
}
if ($sendData && 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:');
}
}
}
if ($sendData) {
if ($toEnd) {
// PHP < 5.6 has a bug of fpassthru
// see https://bugs.php.net/bug.php?id=66736
if (version_compare(PHP_VERSION, '5.6', '<')) {
file_put_contents('php://output', $fp);
} else {
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 {
self::outputJson($data);
exit(0);
}
}
/**
* Remove null & stripslashes applies on "magic_quotes_gpc"
*
* @param mixed $args
*
* @return mixed
* @author Naoki Sawada
*/
protected function input_filter($args)
{
static $magic_quotes_gpc = NULL;
if ($magic_quotes_gpc === NULL)
$magic_quotes_gpc = (version_compare(PHP_VERSION, '5.4', '<') && get_magic_quotes_gpc());
if (is_array($args)) {
return array_map(array(& $this, 'input_filter'), $args);
}
$res = str_replace("\0", '', $args);
$magic_quotes_gpc && ($res = stripslashes($res));
return $res;
}
/**
* Send HTTP header
*
* @param string|array $header optional header
*/
protected static function sendHeader($header = null)
{
if ($header) {
if (is_array($header)) {
foreach ($header as $h) {
header($h);
}
} else {
header($header);
}
}
}
/**
* Output JSON
*
* @param array $data
*/
public static function outputJson($data)
{
// send header
$header = isset($data['header']) ? $data['header'] : self::$contentType;
self::sendHeader($header);
unset($data['header']);
if (!empty($data['raw']) && isset($data['error'])) {
$out = $data['error'];
} else {
if (isset($data['debug']) && isset($data['debug']['phpErrors'])) {
$data['debug']['phpErrors'] = array_merge($data['debug']['phpErrors'], elFinder::$phpErrors);
}
$out = json_encode($data);
}
// clear output buffer
while (ob_get_level() && ob_end_clean()) {
}
header('Content-Length: ' . strlen($out));
echo $out;
flush();
}
}// END class
+46 -42
View File
@@ -11,7 +11,7 @@ use Hypweb\elFinderFlysystemDriverExt\Driver as ExtDriver;
elFinder::$netDrivers['googledrive'] = 'FlysystemGoogleDriveNetmount';
if (! class_exists('elFinderVolumeFlysystemGoogleDriveCache', false)) {
if (!class_exists('elFinderVolumeFlysystemGoogleDriveCache', false)) {
class elFinderVolumeFlysystemGoogleDriveCache extends ACache
{
use Hasdir;
@@ -25,14 +25,14 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
public function __construct()
{
parent::__construct();
$opts = array(
'acceptedName' => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
'rootCssClass' => 'elfinder-navbar-root-googledrive',
'gdAlias' => '%s@GDrive',
'gdCacheDir' => __DIR__ . '/.tmp',
'gdCachePrefix' => 'gd-',
'gdCacheExpire' => 600
'gdAlias' => '%s@GDrive',
'gdCacheDir' => __DIR__ . '/.tmp',
'gdCachePrefix' => 'gd-',
'gdCacheExpire' => 600
);
$this->options = array_merge($this->options, $opts);
@@ -64,6 +64,7 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
* Call from elFinder::netmout() before volume->mount()
*
* @param $options
*
* @return Array
* @author Naoki Sawada
*/
@@ -75,11 +76,11 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
if (empty($options['client_secret']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTSECRET')) {
$options['client_secret'] = ELFINDER_GOOGLEDRIVE_CLIENTSECRET;
}
if (! isset($options['pass'])) {
if (!isset($options['pass'])) {
$options['pass'] = '';
}
try {
$client = new \Google_Client();
$client->setClientId($options['client_id']);
@@ -93,8 +94,8 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
}
$options = array_merge($this->session->get('GoogleDriveAuthParams', []), $options);
if (! isset($options['access_token'])) {
if (!isset($options['access_token'])) {
$options['access_token'] = $this->session->get('GoogleDriveTokens', []);
$this->session->remove('GoogleDriveTokens');
}
@@ -129,22 +130,22 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
if (empty($options['url'])) {
$options['url'] = elFinder::getConnectorUrl();
}
$callback = $options['url']
. '?cmd=netmount&protocol=googledrive&host=1';
$callback = $options['url']
. '?cmd=netmount&protocol=googledrive&host=1';
$client->setRedirectUri($callback);
if (! $aToken && empty($_GET['code'])) {
$client->setScopes([ Google_Service_Drive::DRIVE ]);
if (! empty($options['offline'])) {
if (!$aToken && empty($_GET['code'])) {
$client->setScopes([Google_Service_Drive::DRIVE]);
if (!empty($options['offline'])) {
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
}
$url = $client->createAuthUrl();
$html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
$html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
</script>';
if (empty($options['pass']) && $options['host'] !== '1') {
$options['pass'] = 'return';
@@ -153,13 +154,13 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
} else {
$out = array(
'node' => $options['id'],
'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "'.str_replace($html, '"', '\\"').'", "error" : "'.elFinder::ERROR_ACCESS_DENIED.'"}',
'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "' . str_replace($html, '"', '\\"') . '", "error" : "' . elFinder::ERROR_ACCESS_DENIED . '"}',
'bind' => 'netmount'
);
return array('exit' => 'callback', 'out' => $out);
}
} else {
if (! empty($_GET['code'])) {
if (!empty($_GET['code'])) {
$aToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$options['access_token'] = $aToken;
$this->session->set('GoogleDriveTokens', $aToken)->set('GoogleDriveAuthParams', $options);
@@ -171,7 +172,7 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
return array('exit' => 'callback', 'out' => $out);
}
$folders = [];
foreach($service->files->listFiles([
foreach ($service->files->listFiles([
'pageSize' => 1000,
'q' => 'trashed = false and mimeType = "application/vnd.google-apps.folder"'
]) as $f) {
@@ -180,11 +181,11 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
natcasesort($folders);
$folders = ['root' => $rootObj->getName()] + $folders;
$folders = json_encode($folders);
$json = '{"protocol": "googledrive", "mode": "done", "folders": '.$folders.'}';
$json = '{"protocol": "googledrive", "mode": "done", "folders": ' . $folders . '}';
$options['pass'] = 'return';
$html = 'Google.com';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
</script>';
$this->session->set('GoogleDriveAuthParams', $options);
return array('exit' => true, 'body' => $html);
@@ -193,20 +194,20 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
} catch (Exception $e) {
$this->session->remove('GoogleDriveAuthParams')->remove('GoogleDriveTokens');
if (empty($options['pass'])) {
return array('exit' => true, 'body' => '{msg:'.elFinder::ERROR_ACCESS_DENIED.'}'.' '.$e->getMessage());
return array('exit' => true, 'body' => '{msg:' . elFinder::ERROR_ACCESS_DENIED . '}' . ' ' . $e->getMessage());
} else {
return array('exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]);
}
}
if (! $aToken) {
if (!$aToken) {
return array('exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE);
}
if ($options['path'] === '/') {
$options['path'] = 'root';
}
try {
$file = $service->files->get($options['path']);
$options['alias'] = sprintf($this->options['gdAlias'], $file->getName());
@@ -221,7 +222,7 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
return array('exit' => true, 'error' => $e->getMessage());
}
foreach(['host', 'user', 'pass', 'id', 'offline'] as $key) {
foreach (['host', 'user', 'pass', 'id', 'offline'] as $key) {
unset($options[$key]);
}
@@ -234,17 +235,18 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
*
* @param $netVolumes
* @param $key
*
* @return bool
* @internal param array $options
*/
public function netunmount($netVolumes, $key)
{
$cache = $this->options['gdCacheDir'] . DIRECTORY_SEPARATOR . $this->options['gdCachePrefix'].$this->netMountKey;
$cache = $this->options['gdCacheDir'] . DIRECTORY_SEPARATOR . $this->options['gdCachePrefix'] . $this->netMountKey;
if (file_exists($cache) && is_writeable($cache)) {
unlink($cache);
}
if ($tmbs = glob($this->tmbPath . DIRECTORY_SEPARATOR . $this->netMountKey . '*')) {
foreach($tmbs as $file) {
foreach ($tmbs as $file) {
unlink($file);
}
}
@@ -257,6 +259,7 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
* false - otherwise
*
* @param array $opts
*
* @return bool
* @author Naoki Sawada
*/
@@ -264,7 +267,7 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
{
$creds = null;
if (isset($opts['access_token'])) {
$this->netMountKey = md5(join('-', array('googledrive', $opts['path'], (isset($opts['access_token']['refresh_token'])? $opts['access_token']['refresh_token'] : $opts['access_token']['access_token']))));
$this->netMountKey = md5(join('-', array('googledrive', $opts['path'], (isset($opts['access_token']['refresh_token']) ? $opts['access_token']['refresh_token'] : $opts['access_token']['access_token']))));
}
$client = new \Google_Client();
@@ -289,13 +292,13 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
if (!isset($opts['path']) || $opts['path'] === '') {
$opts['path'] = 'root';
}
$googleDrive = new GoogleDriveAdapter($service, $opts['path'], [ 'useHasDir' => true ]);
$googleDrive = new GoogleDriveAdapter($service, $opts['path'], ['useHasDir' => true]);
$opts['fscache'] = null;
if ($this->options['gdCacheDir'] && is_writeable($this->options['gdCacheDir'])) {
if ($this->options['gdCacheExpire']) {
$opts['fscache'] = new elFinderVolumeFlysystemGoogleDriveCache(new Local($this->options['gdCacheDir']), $this->options['gdCachePrefix'].$this->netMountKey, $this->options['gdCacheExpire']);
$opts['fscache'] = new elFinderVolumeFlysystemGoogleDriveCache(new Local($this->options['gdCacheDir']), $this->options['gdCachePrefix'] . $this->netMountKey, $this->options['gdCacheExpire']);
}
}
if ($opts['fscache']) {
@@ -308,10 +311,10 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
$opts['filesystem'] = $filesystem;
$opts['separator'] = '/';
$opts['checkSubfolders'] = true;
if (! isset($opts['alias'])) {
if (!isset($opts['alias'])) {
$opts['alias'] = 'GoogleDrive';
}
if ($res = parent::mount($opts)) {
// update access_token of session data
if ($creds) {
@@ -327,8 +330,9 @@ class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
/**
* @inheritdoc
*/
protected function tmbname($stat) {
return $this->netMountKey.substr(substr($stat['hash'], strlen($this->id)), -38).$stat['ts'].'.png';
}
protected function tmbname($stat)
{
return $this->netMountKey . substr(substr($stat['hash'], strlen($this->id)), -38) . $stat['ts'] . '.png';
}
}
+104 -98
View File
@@ -1,107 +1,113 @@
<?php
/**
* elFinder Plugin Abstract
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPlugin {
/**
* This plugin's options
*
* @var array
*/
protected $opts = array();
/**
* Get current volume's options
*
* @param object $volume
* @return array options
*/
protected function getCurrentOpts($volume) {
$name = substr(get_class($this), 14); // remove "elFinderPlugin"
$opts = $this->opts;
if (is_object($volume)) {
$volOpts = $volume->getOptionsPlugin($name);
if (is_array($volOpts)) {
$opts = array_merge($opts, $volOpts);
}
}
return $opts;
}
/**
* Is enabled with options
*
* @param array $opts
* @param elFinder $elfinder
* @return boolean
*/
protected function iaEnabled($opts, $elfinder = null) {
if (! $opts['enable']) {
return false;
}
// check post var 'contentSaveId' to disable this plugin
if ($elfinder && !empty($opts['disableWithContentSaveId'])) {
$session = $elfinder->getSession();
$urlContentSaveIds = $session->get('urlContentSaveIds', array());
if (!empty(elFinder::$currentArgs['contentSaveId']) && ($contentSaveId = elFinder::$currentArgs['contentSaveId'])) {
if (!empty($urlContentSaveIds[$contentSaveId])) {
$elfinder->removeUrlContentSaveId($contentSaveId);
return false;
}
}
}
class elFinderPlugin
{
if (isset($opts['onDropWith']) && !is_null($opts['onDropWith'])) {
// plugin disabled by default, enabled only if given key is pressed
if (isset($_REQUEST['dropWith']) && $_REQUEST['dropWith']) {
$onDropWith = $opts['onDropWith'];
$action = (int)$_REQUEST['dropWith'];
if (!is_array($onDropWith)) {
$onDropWith = array($onDropWith);
}
foreach($onDropWith as $key) {
$key = (int)$key;
if (($action & $key) === $key) {
return true;
}
}
}
return false;
}
if (isset($opts['offDropWith']) && ! is_null($opts['offDropWith']) && isset($_REQUEST['dropWith'])) {
// plugin enabled by default, disabled only if given key is pressed
$offDropWith = $opts['offDropWith'];
$action = (int)$_REQUEST['dropWith'];
if (! is_array($offDropWith)) {
$offDropWith = array($offDropWith);
}
$res = true;
foreach($offDropWith as $key) {
$key = (int)$key;
if ($key === 0) {
if ($action === 0) {
$res = false;
break;
}
} else {
if (($action & $key) === $key) {
$res = false;
break;
}
}
}
if (! $res) {
return false;
}
}
return true;
}
/**
* This plugin's options
*
* @var array
*/
protected $opts = array();
/**
* Get current volume's options
*
* @param object $volume
*
* @return array options
*/
protected function getCurrentOpts($volume)
{
$name = substr(get_class($this), 14); // remove "elFinderPlugin"
$opts = $this->opts;
if (is_object($volume)) {
$volOpts = $volume->getOptionsPlugin($name);
if (is_array($volOpts)) {
$opts = array_merge($opts, $volOpts);
}
}
return $opts;
}
/**
* Is enabled with options
*
* @param array $opts
* @param elFinder $elfinder
*
* @return boolean
*/
protected function iaEnabled($opts, $elfinder = null)
{
if (!$opts['enable']) {
return false;
}
// check post var 'contentSaveId' to disable this plugin
if ($elfinder && !empty($opts['disableWithContentSaveId'])) {
$session = $elfinder->getSession();
$urlContentSaveIds = $session->get('urlContentSaveIds', array());
if (!empty(elFinder::$currentArgs['contentSaveId']) && ($contentSaveId = elFinder::$currentArgs['contentSaveId'])) {
if (!empty($urlContentSaveIds[$contentSaveId])) {
$elfinder->removeUrlContentSaveId($contentSaveId);
return false;
}
}
}
if (isset($opts['onDropWith']) && !is_null($opts['onDropWith'])) {
// plugin disabled by default, enabled only if given key is pressed
if (isset($_REQUEST['dropWith']) && $_REQUEST['dropWith']) {
$onDropWith = $opts['onDropWith'];
$action = (int)$_REQUEST['dropWith'];
if (!is_array($onDropWith)) {
$onDropWith = array($onDropWith);
}
foreach ($onDropWith as $key) {
$key = (int)$key;
if (($action & $key) === $key) {
return true;
}
}
}
return false;
}
if (isset($opts['offDropWith']) && !is_null($opts['offDropWith']) && isset($_REQUEST['dropWith'])) {
// plugin enabled by default, disabled only if given key is pressed
$offDropWith = $opts['offDropWith'];
$action = (int)$_REQUEST['dropWith'];
if (!is_array($offDropWith)) {
$offDropWith = array($offDropWith);
}
$res = true;
foreach ($offDropWith as $key) {
$key = (int)$key;
if ($key === 0) {
if ($action === 0) {
$res = false;
break;
}
} else {
if (($action & $key) === $key) {
$res = false;
break;
}
}
}
if (!$res) {
return false;
}
}
return true;
}
}
+215 -213
View File
@@ -5,241 +5,243 @@
* Session Wrapper Class.
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
**/
class elFinderSession implements elFinderSessionInterface
{
protected $started = false;
protected $started = false;
protected $cookiePay = false;
protected $keys = array();
protected $base64encode = false;
protected $opts = array(
'base64encode' => false,
'keys' => array(
'default' => 'elFinderCaches',
'netvolume' => 'elFinderNetVolumes'
)
);
public function __construct($opts)
{
$this->opts = array_merge($this->opts, $opts);
$this->base64encode = !empty($this->opts['base64encode']);
$this->keys = $this->opts['keys'];
return $this;
}
protected $cookiePay = false;
protected $keys = array();
protected $base64encode = false;
protected $opts = array(
'base64encode' => false,
'keys' => array(
'default' => 'elFinderCaches',
'netvolume' => 'elFinderNetVolumes'
)
);
public function __construct($opts)
{
$this->opts = array_merge($this->opts, $opts);
$this->base64encode = !empty($this->opts['base64encode']);
$this->keys = $this->opts['keys'];
return $this;
}
/**
* {@inheritdoc}
*/
public function start()
{
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
} else {
set_error_handler(array($this, 'session_start_error'), E_NOTICE);
session_start();
restore_error_handler();
}
$this->started = session_id()? true : false;
return $this;
}
public function start()
{
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
} else {
set_error_handler(array($this, 'session_start_error'), E_NOTICE);
session_start();
restore_error_handler();
}
$this->started = session_id() ? true : false;
return $this;
}
/**
* {@inheritdoc}
*/
public function close()
{
if ($this->started) {
if (!$this->cookiePay) {
$cParm = session_get_cookie_params();
ini_set('session.use_cookies', 0);
setcookie(session_name(), session_id(), 0, $cParm['path'], $cParm['domain'], $cParm['secure'], $cParm['httponly']);
$this->cookiePay = true;
}
session_write_close();
}
$this->started = false;
return $this;
}
public function close()
{
if ($this->started) {
if (!$this->cookiePay) {
$cParm = session_get_cookie_params();
ini_set('session.use_cookies', 0);
setcookie(session_name(), session_id(), 0, $cParm['path'], $cParm['domain'], $cParm['secure'], $cParm['httponly']);
$this->cookiePay = true;
}
session_write_close();
}
$this->started = false;
return $this;
}
/**
* {@inheritdoc}
*/
public function get($key, $empty = null)
{
$closed = false;
if (! $this->started) {
$closed = true;
$this->start();
}
$data = null;
if ($this->started) {
$session =& $this->getSessionRef($key);
$data = $session;
if ($data && $this->base64encode) {
$data = $this->decodeData($data);
}
}
$checkFn = null;
if (! is_null($empty)) {
if (is_string($empty)) {
$checkFn = 'is_string';
} elseif (is_array($empty)) {
$checkFn = 'is_array';
} elseif (is_object($empty)) {
$checkFn = 'is_object';
} elseif (is_float($empty)) {
$checkFn = 'is_float';
} elseif (is_int($empty)) {
$checkFn = 'is_int';
}
}
if (is_null($data) || ($checkFn && ! $checkFn($data))) {
$session = $data = $empty;
}
if ($closed) {
$this->close();
}
public function get($key, $empty = null)
{
$closed = false;
if (!$this->started) {
$closed = true;
$this->start();
}
$data = null;
if ($this->started) {
$session =& $this->getSessionRef($key);
$data = $session;
if ($data && $this->base64encode) {
$data = $this->decodeData($data);
}
}
$checkFn = null;
if (!is_null($empty)) {
if (is_string($empty)) {
$checkFn = 'is_string';
} elseif (is_array($empty)) {
$checkFn = 'is_array';
} elseif (is_object($empty)) {
$checkFn = 'is_object';
} elseif (is_float($empty)) {
$checkFn = 'is_float';
} elseif (is_int($empty)) {
$checkFn = 'is_int';
}
}
if (is_null($data) || ($checkFn && !$checkFn($data))) {
$session = $data = $empty;
}
if ($closed) {
$this->close();
}
return $data;
}
return $data;
}
/**
* {@inheritdoc}
*/
public function set($key, $data)
{
$closed = false;
if (! $this->started) {
$closed = true;
$this->start();
}
$session =& $this->getSessionRef($key);
if ($this->base64encode) {
$data = $this->encodeData($data);
}
$session = $data;
if ($closed) {
$this->close();
}
return $this;
}
public function set($key, $data)
{
$closed = false;
if (!$this->started) {
$closed = true;
$this->start();
}
$session =& $this->getSessionRef($key);
if ($this->base64encode) {
$data = $this->encodeData($data);
}
$session = $data;
if ($closed) {
$this->close();
}
return $this;
}
/**
* {@inheritdoc}
*/
public function remove($key)
{
$closed = false;
if (! $this->started) {
$closed = true;
$this->start();
}
public function remove($key)
{
$closed = false;
if (!$this->started) {
$closed = true;
$this->start();
}
list($cat, $name) = array_pad(explode('.', $key, 2), 2, null);
if (is_null($name)) {
if (! isset($this->keys[$cat])) {
$name = $cat;
$cat = 'default';
}
}
if (isset($this->keys[$cat])) {
$cat = $this->keys[$cat];
} else {
$name = $cat . '.' . $name;
$cat = $this->keys['default'];
}
if (is_null($name)) {
unset($_SESSION[$cat]);
} else {
if (isset($_SESSION[$cat]) && is_array($_SESSION[$cat])) {
unset($_SESSION[$cat][$name]);
}
}
list($cat, $name) = array_pad(explode('.', $key, 2), 2, null);
if (is_null($name)) {
if (!isset($this->keys[$cat])) {
$name = $cat;
$cat = 'default';
}
}
if (isset($this->keys[$cat])) {
$cat = $this->keys[$cat];
} else {
$name = $cat . '.' . $name;
$cat = $this->keys['default'];
}
if (is_null($name)) {
unset($_SESSION[$cat]);
} else {
if (isset($_SESSION[$cat]) && is_array($_SESSION[$cat])) {
unset($_SESSION[$cat][$name]);
}
}
if ($closed) {
$this->close();
}
return $this;
}
protected function & getSessionRef($key)
{
$session = null;
if ($this->started) {
list($cat, $name) = array_pad(explode('.', $key, 2), 2, null);
if (is_null($name)) {
if (! isset($this->keys[$cat])) {
$name = $cat;
$cat = 'default';
}
}
if (isset($this->keys[$cat])) {
$cat = $this->keys[$cat];
} else {
$name = $cat . '.' . $name;
$cat = $this->keys['default'];
}
if (is_null($name)) {
if (! isset($_SESSION[$cat])) {
$_SESSION[$cat] = null;
}
$session =& $_SESSION[$cat];
} else {
if (! isset($_SESSION[$cat]) || ! is_array($_SESSION[$cat])) {
$_SESSION[$cat] = array();
}
if (! isset($_SESSION[$cat][$name])) {
$_SESSION[$cat][$name] = null;
}
$session =& $_SESSION[$cat][$name];
}
}
return $session;
}
protected function encodeData($data)
{
if ($this->base64encode) {
$data = base64_encode(serialize($data));
}
return $data;
}
protected function decodeData($data)
{
if ($this->base64encode) {
if (is_string($data)) {
if (($data = base64_decode($data)) !== false) {
$data = unserialize($data);
} else {
$data = null;
}
} else {
$data = null;
}
}
return $data;
}
if ($closed) {
$this->close();
}
protected function session_start_error($errno , $errstr) {}
return $this;
}
protected function & getSessionRef($key)
{
$session = null;
if ($this->started) {
list($cat, $name) = array_pad(explode('.', $key, 2), 2, null);
if (is_null($name)) {
if (!isset($this->keys[$cat])) {
$name = $cat;
$cat = 'default';
}
}
if (isset($this->keys[$cat])) {
$cat = $this->keys[$cat];
} else {
$name = $cat . '.' . $name;
$cat = $this->keys['default'];
}
if (is_null($name)) {
if (!isset($_SESSION[$cat])) {
$_SESSION[$cat] = null;
}
$session =& $_SESSION[$cat];
} else {
if (!isset($_SESSION[$cat]) || !is_array($_SESSION[$cat])) {
$_SESSION[$cat] = array();
}
if (!isset($_SESSION[$cat][$name])) {
$_SESSION[$cat][$name] = null;
}
$session =& $_SESSION[$cat][$name];
}
}
return $session;
}
protected function encodeData($data)
{
if ($this->base64encode) {
$data = base64_encode(serialize($data));
}
return $data;
}
protected function decodeData($data)
{
if ($this->base64encode) {
if (is_string($data)) {
if (($data = base64_decode($data)) !== false) {
$data = unserialize($data);
} else {
$data = null;
}
} else {
$data = null;
}
}
return $data;
}
protected function session_start_error($errno, $errstr)
{
}
}
+45 -47
View File
@@ -5,55 +5,53 @@
* Session Wrapper Interface.
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
**/
interface elFinderSessionInterface
{
/**
* Session start
*
* @return self
**/
public function start();
/**
* Session write & close
*
* @return self
**/
public function close();
/**
* Get session data
*
* This method must be equipped with an automatic start / close.
*
* @param string $key Target key
* @param mixed $empty Return value of if session target key does not exist
*
* @return mixed
**/
public function get($key, $empty = '');
/**
* Set session data
*
* This method must be equipped with an automatic start / close.
*
* @param string $key Target key
* @param mixed $data Value
*
* @return self
**/
public function set($key, $data);
/**
* Get session data
*
* @param string $key Target key
*
* @return self
**/
public function remove($key);
/**
* Session start
*
* @return self
**/
public function start();
/**
* Session write & close
*
* @return self
**/
public function close();
/**
* Get session data
* This method must be equipped with an automatic start / close.
*
* @param string $key Target key
* @param mixed $empty Return value of if session target key does not exist
*
* @return mixed
**/
public function get($key, $empty = '');
/**
* Set session data
* This method must be equipped with an automatic start / close.
*
* @param string $key Target key
* @param mixed $data Value
*
* @return self
**/
public function set($key, $data);
/**
* Get session data
*
* @param string $key Target key
*
* @return self
**/
public function remove($key);
}
+124 -159
View File
@@ -129,7 +129,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$paths = explode('/', trim($path, '/'));
$id = array_pop($paths);
if ($paths) {
$parent = '/'.implode('/', $paths);
$parent = '/' . implode('/', $paths);
$pid = array_pop($paths);
} else {
$pid = '0';
@@ -144,9 +144,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Obtains a new access token from OAuth. This token is valid for one hour.
*
* @param string $clientSecret The Box client secret
* @param string $code The code returned by Box after
* @param string $code The code returned by Box after
* successful log in
* @param string $redirectUri Must be the same as the redirect URI passed
* @param string $redirectUri Must be the same as the redirect URI passed
* to LoginUrl
*
* @return bool|object
@@ -189,11 +189,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
CURLOPT_URL => $url,
));
$decoded = $this->_bd_curlExec($curl, true, array('Content-Length: '.strlen($fields)));
$decoded = $this->_bd_curlExec($curl, true, array('Content-Length: ' . strlen($fields)));
return (object) array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
return (object)array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
}
@@ -227,16 +227,16 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$curl = curl_init();
curl_setopt_array($curl, array(
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true, // i am sending post data
CURLOPT_POSTFIELDS => 'client_id='.urlencode($this->options['client_id'])
.'&client_secret='.urlencode($this->options['client_secret'])
.'&grant_type=refresh_token'
.'&refresh_token='.urlencode($token->data->refresh_token),
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true, // i am sending post data
CURLOPT_POSTFIELDS => 'client_id=' . urlencode($this->options['client_id'])
. '&client_secret=' . urlencode($this->options['client_secret'])
. '&grant_type=refresh_token'
. '&refresh_token=' . urlencode($token->data->refresh_token),
CURLOPT_URL => $url,
));
CURLOPT_URL => $url,
));
$decoded = $this->_bd_curlExec($curl);
@@ -244,10 +244,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
}
$token = (object) array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
$token = (object)array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
$this->session->set('BoxTokens', $token);
$this->options['accessToken'] = json_encode($token);
@@ -285,8 +285,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
/**
* Creates a base cURL object which is compatible with the Box.com API.
*
* @param $url
* @param $url
* @param bool $contents
*
* @return boolean|array
* @throws Exception
*/
@@ -309,9 +310,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if (!$single && $total > ($offset + $cnt)) {
$offset = $offset + $cnt;
if (strpos($url, 'offset=') === false) {
$url .= '&offset='.$offset;
$url .= '&offset=' . $offset;
} else {
$url = preg_replace('/^(.+?offset=)\d+(.*)$/', '${1}'.$offset.'$2', $url);
$url = preg_replace('/^(.+?offset=)\d+(.*)$/', '${1}' . $offset . '$2', $url);
}
$more = $this->_bd_fetch($url);
if (is_array($more)) {
@@ -338,13 +339,12 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param array $headers
*
* @throws \Exception
*
* @return mixed
*/
protected function _bd_curlExec($curl, $decodeOrParent = true, $headers = array())
{
$headers = array_merge(array(
'Authorization: Bearer '.$this->token->data->access_token,
'Authorization: Bearer ' . $this->token->data->access_token,
), $headers);
$result = elFinder::curlExec($curl, array(), $headers);
@@ -358,7 +358,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if (!empty($decoded->error_code)) {
$errmsg = $decoded->error_code;
if (!empty($decoded->message)) {
$errmsg .= ': '.$decoded->message;
$errmsg .= ': ' . $decoded->message;
}
throw new \Exception($errmsg);
}
@@ -388,9 +388,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
/**
* Drive query and fetchAll.
*
* @param $itemId
* @param $itemId
* @param bool $fetch_self
* @param bool $recursive
*
* @return bool|object
* @throws Exception
*/
@@ -403,12 +404,12 @@ class elFinderVolumeBox extends elFinderVolumeDriver
}
if ($fetch_self) {
$path = '/folders/'.$itemId.'?fields='.self::FETCHFIELDS;
$path = '/folders/' . $itemId . '?fields=' . self::FETCHFIELDS;
} else {
$path = '/folders/'.$itemId.'/items?limit=1000&fields='.self::FETCHFIELDS;
$path = '/folders/' . $itemId . '/items?limit=1000&fields=' . self::FETCHFIELDS;
}
$url = self::API_URL.$path;
$url = self::API_URL . $path;
if ($recursive) {
foreach ($this->_bd_fetch($url) as $file) {
@@ -422,8 +423,8 @@ class elFinderVolumeBox extends elFinderVolumeDriver
} else {
$result = $this->_bd_fetch($url);
if ($fetch_self && !$result) {
$path = '/files/'.$itemId.'?fields='.self::FETCHFIELDS;
$url = self::API_URL.$path;
$path = '/files/' . $itemId . '?fields=' . self::FETCHFIELDS;
$url = self::API_URL . $path;
$result = $this->_bd_fetch($url);
}
}
@@ -461,7 +462,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param object $raw line from ftp_rawlist() output
*
* @return array
*
* @author Dmitry Levashov
**/
protected function _bd_parseRaw($raw)
@@ -479,7 +479,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$stat['size'] = 0;
$stat['dirs'] = -1;
} else {
$stat['size'] = (int) $raw->size;
$stat['size'] = (int)$raw->size;
if (!empty($raw->shared_link->url) && $raw->shared_link->access == 'open') {
if ($url = $this->getSharedWebContentLink($raw)) {
$stat['url'] = $url;
@@ -505,7 +505,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
list(, $itemId) = $this->_bd_splitPath($path);
try {
$url = self::API_URL.'/files/'.$itemId.'/thumbnail.png?min_height=' . $this->tmbSize . '&min_width=' . $this->tmbSize;
$url = self::API_URL . '/files/' . $itemId . '/thumbnail.png?min_height=' . $this->tmbSize . '&min_width=' . $this->tmbSize;
$contents = $this->_bd_fetch($url, true);
return $contents;
@@ -527,20 +527,20 @@ class elFinderVolumeBox extends elFinderVolumeDriver
list(, $itemId) = $this->_bd_splitPath($path);
if ($type == 'folders') {
$url = self::API_URL.'/'.$type.'/'.$itemId.'?recursive=true';
$url = self::API_URL . '/' . $type . '/' . $itemId . '?recursive=true';
} else {
$url = self::API_URL.'/'.$type.'/'.$itemId;
$url = self::API_URL . '/' . $type . '/' . $itemId;
}
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'DELETE',
));
//unlink or delete File or Folder in the Parent
$this->_bd_curlExec($curl);
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
return true;
@@ -555,7 +555,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Call from elFinder::netmout() before volume->mount().
*
* @return array
*
* @author Naoki Sawada
* @author Raja Sharma updating for Box
**/
@@ -590,28 +589,28 @@ class elFinderVolumeBox extends elFinderVolumeDriver
try {
// Obtain the token using the code received by the Box.com API
$this->session->set('BoxTokens',
$this->_bd_obtainAccessToken($options['client_id'], $options['client_secret'], $_GET['code']));
$this->_bd_obtainAccessToken($options['client_id'], $options['client_secret'], $_GET['code']));
$out = array(
'node' => $options['id'],
'json' => '{"protocol": "box", "mode": "done", "reset": 1}',
'bind' => 'netmount',
'node' => $options['id'],
'json' => '{"protocol": "box", "mode": "done", "reset": 1}',
'bind' => 'netmount',
);
return array('exit' => 'callback', 'out' => $out);
} catch (Exception $e) {
$out = array(
'node' => $options['id'],
'json' => json_encode(array('error' => $e->getMessage())),
'node' => $options['id'],
'json' => json_encode(array('error' => $e->getMessage())),
);
return array('exit' => 'callback', 'out' => $out);
}
} elseif (!empty($_GET['error'])) {
$out = array(
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
);
return array('exit' => 'callback', 'out' => $out);
@@ -646,28 +645,28 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
foreach ($this->ARGS as $k => $v) {
if (!in_array($k, $innerKeys)) {
$cdata .= '&'.$k.'='.rawurlencode($v);
$cdata .= '&' . $k . '=' . rawurlencode($v);
}
}
if (empty($options['url'])) {
$options['url'] = elFinder::getConnectorUrl();
}
$callback = $options['url']
.'?cmd=netmount&protocol=box&host=box.com&user=init&pass=return&node='.$options['id'].$cdata;
. '?cmd=netmount&protocol=box&host=box.com&user=init&pass=return&node=' . $options['id'] . $cdata;
try {
$this->session->set('BoxTokens', (object) array('token' => null));
$this->session->set('BoxTokens', (object)array('token' => null));
$url = self::AUTH_URL.'?'.http_build_query(array('response_type' => 'code', 'client_id' => $options['client_id'], 'redirect_uri' => elFinder::getConnectorUrl().'?cmd=netmount&protocol=box&host=1'));
$url = self::AUTH_URL . '?' . http_build_query(array('response_type' => 'code', 'client_id' => $options['client_id'], 'redirect_uri' => elFinder::getConnectorUrl() . '?cmd=netmount&protocol=box&host=1'));
$url .= '&oauth_callback='.rawurlencode($callback);
$url .= '&oauth_callback=' . rawurlencode($callback);
} catch (Exception $e) {
return array('exit' => true, 'body' => '{msg:errAccess}');
}
$html = '<input id="elf-volumedriver-box-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
$html = '<input id="elf-volumedriver-box-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "box", mode: "makebtn"});
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "box", mode: "makebtn"});
</script>';
return array('exit' => true, 'body' => $html);
@@ -677,7 +676,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($result) {
foreach ($result as $res) {
if ($res->type == 'folder') {
$folders[$res->id.' '] = $res->name;
$folders[$res->id . ' '] = $res->name;
}
}
natcasesort($folders);
@@ -690,11 +689,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$folders = ['root' => 'My Box'] + $folders;
$folders = json_encode($folders);
$expires = empty($this->token->data->refresh_token) ? (int) $this->token->expires : 0;
$json = '{"protocol": "box", "mode": "done", "folders": '.$folders.', "expires": '.$expires.'}';
$expires = empty($this->token->data->refresh_token) ? (int)$this->token->expires : 0;
$json = '{"protocol": "box", "mode": "done", "folders": ' . $folders . ', "expires": ' . $expires . '}';
$html = 'Box.com';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
</script>';
return array('exit' => true, 'body' => $html);
@@ -724,11 +723,12 @@ class elFinderVolumeBox extends elFinderVolumeDriver
*
* @param $netVolumes
* @param $key
*
* @return bool
*/
public function netunmount($netVolumes, $key)
{
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->tmbPrefix.'*.png')) {
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/') . DIRECTORY_SEPARATOR . $this->tmbPrefix . '*.png')) {
foreach ($tmbs as $file) {
unlink($file);
}
@@ -745,10 +745,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
public function debug()
{
$res = parent::debug();
if (! empty($this->options['accessToken'])) {
if (!empty($this->options['accessToken'])) {
$res['accessToken'] = $this->options['accessToken'];
}
return $res;
}
@@ -761,7 +761,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn.
*
* @return bool
*
* @throws Exception
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
@@ -802,12 +801,12 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if (empty($this->options['alias'])) {
list(, $itemId) = $this->_bd_splitPath($this->options['path']);
$this->options['alias'] = ($this->options['path'] === '/') ? $this->options['root'] :
$this->_bd_query($itemId, $fetch_self = true)->name.'@Box.com';
$this->_bd_query($itemId, $fetch_self = true)->name . '@Box.com';
}
$this->rootName = $this->options['alias'];
$this->tmbPrefix = 'box'.base_convert($this->netMountKey, 10, 32);
$this->tmbPrefix = 'box' . base_convert($this->netMountKey, 10, 32);
if (!empty($this->options['tmpPath'])) {
if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) {
@@ -835,7 +834,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Configure after successfull mount.
*
* @author Dmitry (dio) Levashov
*
* @throws elFinderAbortException
*/
protected function configure()
@@ -880,16 +878,14 @@ class elFinderVolumeBox extends elFinderVolumeDriver
// > Note: If an item is added to Box then it becomes accessible through the search endpoint after ten minutes.
/***
$url = self::API_URL.'/search?limit=1&offset=0&content_types=name&ancestor_folder_ids='.rawurlencode($pid)
.'&query='.rawurlencode('"'.$name.'"')
.'fields='.self::FETCHFIELDS;
$raw = $this->_bd_fetch($url);
if (is_array($raw) && count($raw)) {
return $this->_bd_parseRaw($raw);
}
***/
* $url = self::API_URL.'/search?limit=1&offset=0&content_types=name&ancestor_folder_ids='.rawurlencode($pid)
* .'&query='.rawurlencode('"'.$name.'"')
* .'fields='.self::FETCHFIELDS;
* $raw = $this->_bd_fetch($url);
* if (is_array($raw) && count($raw)) {
* return $this->_bd_parseRaw($raw);
* }
***/
$phash = $this->encode($parent);
@@ -960,7 +956,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name new file name (optionaly)
*
* @return string|false
*
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
**/
@@ -977,11 +972,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
/**
* Remove file/ recursive remove dir.
*
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param string $path file path
* @param bool $force try to remove even if file locked
*
* @return bool
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
@@ -1020,9 +1014,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Create thumnbnail and return it's URL on success.
*
* @param string $path file path
* @param $stat
* @return string|false
* @param $stat
*
* @return string|false
* @throws ImagickException
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
@@ -1035,7 +1029,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
}
$name = $this->tmbname($stat);
$tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
$tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
// copy image into tmbPath so some drivers does not store files on local fs
if (!$data = $this->_bd_getThumbnail($path)) {
@@ -1095,12 +1089,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param array $stat file stat
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function tmbname($stat)
{
return $this->tmbPrefix.$stat['rev'].$stat['ts'].'.png';
return $this->tmbPrefix . $stat['rev'] . $stat['ts'] . '.png';
}
/**
@@ -1109,7 +1102,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param object $raw data
*
* @return string
*
* @author Naoki Sawada
**/
protected function getSharedWebContentLink($raw)
@@ -1119,19 +1111,19 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($raw->shared_link->url && ($fType == 'image' || $fType == 'video' || $fType == 'audio')) {
if ($fExtension == 'jpg' && $fType == 'image') {
$url = 'https://app.box.com/representation/file_version_'.$raw->file_version->id.'/image_2048_'.$fExtension.'/1.'.$fExtension.'?shared_name='.basename($raw->shared_link->url);
$url = 'https://app.box.com/representation/file_version_' . $raw->file_version->id . '/image_2048_' . $fExtension . '/1.' . $fExtension . '?shared_name=' . basename($raw->shared_link->url);
return $url;
} elseif ($fExtension !== 'jpg' && $fType == 'image') {
$url = 'https://app.box.com/representation/file_version_'.$raw->file_version->id.'/image_2048/1.'.$fExtension.'?shared_name='.basename($raw->shared_link->url);
$url = 'https://app.box.com/representation/file_version_' . $raw->file_version->id . '/image_2048/1.' . $fExtension . '?shared_name=' . basename($raw->shared_link->url);
return $url;
} elseif ($fType == 'video') {
$url = 'https://app.box.com/representation/file_version_'.$raw->file_version->id.'/video_480.'.$fExtension.'?shared_name='.basename($raw->shared_link->url);
$url = 'https://app.box.com/representation/file_version_' . $raw->file_version->id . '/video_480.' . $fExtension . '?shared_name=' . basename($raw->shared_link->url);
return $url;
} elseif ($fType == 'audio') {
$url = 'https://app.box.com/index.php?rm=preview_stream&amp&file_version_'.$raw->file_version->id.'/audio/mpeg:'.$raw->name.'&shared_name='.basename($raw->shared_link->url);
$url = 'https://app.box.com/index.php?rm=preview_stream&amp&file_version_' . $raw->file_version->id . '/audio/mpeg:' . $raw->name . '&shared_name=' . basename($raw->shared_link->url);
return $url;
}
@@ -1145,17 +1137,16 @@ class elFinderVolumeBox extends elFinderVolumeDriver
/**
* Return content URL.
*
* @param string $hash file hash
* @param array $options options
* @param string $hash file hash
* @param array $options options
*
* @return string
*
* @throws Exception
* @author Naoki Sawada
*/
public function getContentUrl($hash, $options = array())
{
if (! empty($options['onetime']) && $this->options['onetimeUrl']) {
if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
return parent::getContentUrl($hash, $options);
}
if (!empty($options['temporary'])) {
@@ -1171,7 +1162,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
list(, $itemId) = $this->_bd_splitPath($path);
$params['shared_link']['access'] = 'open'; //open|company|collaborators
$url = self::API_URL.'/files/'.$itemId;
$url = self::API_URL . '/files/' . $itemId;
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
@@ -1179,9 +1170,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
CURLOPT_POSTFIELDS => json_encode($params),
));
$res = $this->_bd_curlExec($curl, true, array(
// The data is sent as JSON as per Box documentation.
'Content-Type: application/json',
));
// The data is sent as JSON as per Box documentation.
'Content-Type: application/json',
));
if ($url = $this->getSharedWebContentLink($res)) {
return $url;
@@ -1199,7 +1190,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _dirname($path)
@@ -1215,7 +1205,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _basename($path)
@@ -1232,7 +1221,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _joinPath($dir, $name)
@@ -1241,7 +1229,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$dir = '';
}
return $this->_normpath($dir.'/'.$name);
return $this->_normpath($dir . '/' . $name);
}
/**
@@ -1250,7 +1238,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path path
*
* @return string
*
* @author Troex Nevelin
**/
protected function _normpath($path)
@@ -1258,7 +1245,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if (DIRECTORY_SEPARATOR !== '/') {
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
}
$path = '/'.ltrim($path, '/');
$path = '/' . ltrim($path, '/');
return $path;
}
@@ -1269,7 +1256,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _relpath($path)
@@ -1283,7 +1269,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _abspath($path)
@@ -1297,12 +1282,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _path($path)
{
return $this->rootName.$this->_normpath(substr($path, strlen($this->root)));
return $this->rootName . $this->_normpath(substr($path, strlen($this->root)));
}
/**
@@ -1312,12 +1296,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $parent parent path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _inpath($path, $parent)
{
return $path == $parent || strpos($path, $parent.'/') === 0;
return $path == $parent || strpos($path, $parent . '/') === 0;
}
/***************** file stat ********************/
@@ -1333,13 +1316,11 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* - (bool) hidden is object hidden. optionally
* - (string) alias for symlinks - link target path relative to root path. optionally
* - (string) target for symlinks - link target path. optionally.
*
* If file does not exists - returns empty array or false.
*
* @param string $path file path
*
* @return array|false
*
* @throws Exception
* @author Dmitry (dio) Levashov
*/
@@ -1358,7 +1339,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @throws Exception
* @author Dmitry (dio) Levashov
*/
@@ -1366,9 +1346,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
{
list(, $itemId) = $this->_bd_splitPath($path);
$path = '/folders/'.$itemId.'/items?limit=1&offset=0&fields='.self::FETCHFIELDS;
$path = '/folders/' . $itemId . '/items?limit=1&offset=0&fields=' . self::FETCHFIELDS;
$url = self::API_URL.$path;
$url = self::API_URL . $path;
if ($res = $this->_bd_fetch($url)) {
if ($res[0]->type == 'folder') {
@@ -1387,7 +1367,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $mime file mime type
*
* @return string
*
* @throws ImagickException
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
@@ -1403,10 +1382,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($size = @getimagesize($work)) {
$cache['width'] = $size[0];
$cache['height'] = $size[1];
$ret = array('dim' => $size[0].'x'.$size[1]);
$ret = array('dim' => $size[0] . 'x' . $size[1]);
$srcfp = fopen($work, 'rb');
if ($subImgLink = $this->getSubstituteImgLink(elFinder::$currentArgs['target'], $size, $srcfp)) {
$ret['url'] = $subImgLink;
$ret['url'] = $subImgLink;
}
}
}
@@ -1423,7 +1402,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path dir path
*
* @return array
*
* @throws Exception
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
@@ -1440,8 +1418,8 @@ class elFinderVolumeBox extends elFinderVolumeDriver
*
* @param string $path file path
* @param string $mode
* @return resource|false
*
* @return resource|false
* @author Dmitry (dio) Levashov
*/
protected function _fopen($path, $mode = 'rb')
@@ -1449,8 +1427,8 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($mode === 'rb' || $mode === 'r') {
list(, $itemId) = $this->_bd_splitPath($path);
$data = array(
'target' => self::API_URL.'/files/'.$itemId.'/content',
'headers' => array('Authorization: Bearer '.$this->token->data->access_token),
'target' => self::API_URL . '/files/' . $itemId . '/content',
'headers' => array('Authorization: Bearer ' . $this->token->data->access_token),
);
return elFinder::getStreamByUrl($data);
@@ -1463,10 +1441,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* Close opened file.
*
* @param resource $fp file pointer
* @param string $path
*
* @param string $path
* @return void
*
* @author Dmitry (dio) Levashov
*/
protected function _fclose($fp, $path = '')
@@ -1486,7 +1463,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name new directory name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkdir($path, $name)
@@ -1495,7 +1471,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
list(, $parentId) = $this->_bd_splitPath($path);
$params = array('name' => $name, 'parent' => array('id' => $parentId));
$url = self::API_URL.'/folders';
$url = self::API_URL . '/folders';
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
@@ -1508,7 +1484,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
return $this->_joinPath($path, $folder->id);
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
}
@@ -1519,7 +1495,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name new file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkfile($path, $name)
@@ -1534,7 +1509,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path symlink path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _symlink($target, $path, $name)
@@ -1550,7 +1524,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name new file name
*
* @return string|false
*
* @author Dmitry (dio) Levashov
**/
protected function _copy($source, $targetDir, $name)
@@ -1563,10 +1536,10 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$srcItem = $this->_bd_getRawItem($source);
$properties = array('name' => $name, 'parent' => array('id' => $parentId));
$data = (object) $properties;
$data = (object)$properties;
$type = ($srcItem->type === 'folder') ? 'folders' : 'files';
$url = self::API_URL.'/'.$type.'/'.$srcId.'/copy';
$url = self::API_URL . '/' . $type . '/' . $srcId . '/copy';
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
@@ -1587,7 +1560,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
return false;
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
}
@@ -1600,7 +1573,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $name file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _move($source, $targetDir, $name)
@@ -1617,8 +1589,8 @@ class elFinderVolumeBox extends elFinderVolumeDriver
$properties = array('name' => $name, 'parent' => array('id' => $parentId));
$type = ($srcItem->type === 'folder') ? 'folders' : 'files';
$url = self::API_URL.'/'.$type.'/'.$itemId;
$data = (object) $properties;
$url = self::API_URL . '/' . $type . '/' . $itemId;
$data = (object)$properties;
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
@@ -1627,9 +1599,9 @@ class elFinderVolumeBox extends elFinderVolumeDriver
));
$result = $this->_bd_curlExec($curl, $targetDir, array(
// The data is sent as JSON as per Box documentation.
'Content-Type: application/json',
));
// The data is sent as JSON as per Box documentation.
'Content-Type: application/json',
));
if ($result && isset($result->id)) {
return $this->_joinPath($targetDir, $result->id);
@@ -1637,7 +1609,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
return false;
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
}
@@ -1647,7 +1619,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _unlink($path)
@@ -1661,7 +1632,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _rmdir($path)
@@ -1679,7 +1649,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param array $stat file stat (required by some virtual fs)
*
* @return bool|string
*
* @author Dmitry (dio) Levashov
**/
protected function _save($fp, $path, $name, $stat)
@@ -1715,30 +1684,30 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($itemId === '') {
//upload or create new file in destination target
$properties = array('name' => $name, 'parent' => array('id' => $parentId));
$url = self::UPLOAD_URL.'/files/content';
$url = self::UPLOAD_URL . '/files/content';
} else {
//update existing file in destination target
$properties = array('name' => $name);
$url = self::UPLOAD_URL.'/files/'.$itemId.'/content';
$url = self::UPLOAD_URL . '/files/' . $itemId . '/content';
}
if (class_exists('CURLFile')) {
$cfile = new CURLFile($tmpFilePath);
} else {
$cfile = '@'.$tmpFilePath;
$cfile = '@' . $tmpFilePath;
}
$params = array('attributes' => json_encode($properties), 'file' => $cfile);
$curl = $this->_bd_prepareCurl(array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
));
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
));
$file = $this->_bd_curlExec($curl, $parent);
return $this->_joinPath($parent, $file->entries[0]->id);
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
}
@@ -1748,18 +1717,17 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $path file path
*
* @return string|false
*
* @author Dmitry (dio) Levashov
**/
protected function _getContents($path)
{
try {
list(, $itemId) = $this->_bd_splitPath($path);
$url = self::API_URL.'/files/'.$itemId.'/content';
$url = self::API_URL . '/files/' . $itemId . '/content';
$contents = $this->_bd_fetch($url, true);
} catch (Exception $e) {
return $this->setError('Box error: '.$e->getMessage());
return $this->setError('Box error: ' . $e->getMessage());
}
return $contents;
@@ -1772,7 +1740,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param string $content new file content
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _filePutContents($path, $content)
@@ -1781,7 +1748,7 @@ class elFinderVolumeBox extends elFinderVolumeDriver
if ($local = $this->getTempFile($path)) {
if (file_put_contents($local, $content, LOCK_EX) !== false
&& ($fp = fopen($local, 'rb'))) {
&& ($fp = fopen($local, 'rb'))) {
clearstatcache();
$res = $this->_save($fp, $path, '', array());
fclose($fp);
@@ -1818,7 +1785,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return true
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
@@ -1836,7 +1802,6 @@ class elFinderVolumeBox extends elFinderVolumeDriver
* @param array $arc archiver options
*
* @return string|bool
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
File diff suppressed because it is too large Load Diff
+54 -92
View File
@@ -1,11 +1,11 @@
<?php
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\DropboxFile;
use Kunnu\Dropbox\Models\FolderMetadata;
use Kunnu\Dropbox\Models\FileMetadata;
use Kunnu\Dropbox\Exceptions\DropboxClientException;
use Kunnu\Dropbox\Models\FileMetadata;
use Kunnu\Dropbox\Models\FolderMetadata;
/**
* Simple elFinder driver for Dropbox
@@ -104,7 +104,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$dirname = '/';
$basename = $path;
} else {
$dirname = '/'.substr($path, 0, $pos);
$dirname = '/' . substr($path, 0, $pos);
$basename = substr($path, $pos + 1);
}
}
@@ -144,7 +144,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param object $raw line from ftp_rawlist() output
*
* @return array
*
* @author Naoki Sawada
**/
protected function _db_parseRaw($raw)
@@ -185,7 +184,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$stat['ts'] = 0;
$stat['dirs'] = -1;
} else {
$stat['size'] = isset($data['size']) ? (int) $data['size'] : 0;
$stat['size'] = isset($data['size']) ? (int)$data['size'] : 0;
if (isset($data['server_modified'])) {
$stat['ts'] = strtotime($data['server_modified']);
} elseif (isset($data['client_modified'])) {
@@ -226,7 +225,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
*/
protected function _db_joinName($dir, $displayName)
{
return rtrim($dir, '/').'/'.$displayName;
return rtrim($dir, '/') . '/' . $displayName;
}
/**
@@ -242,17 +241,17 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
public static function getTokenFromOauth1($app_key, $app_secret, $oauth1_token, $oauth1_secret)
{
$data = [
'oauth1_token' => $oauth1_token,
'oauth1_token_secret' => $oauth1_secret,
'oauth1_token' => $oauth1_token,
'oauth1_token_secret' => $oauth1_secret,
];
$auth = base64_encode($app_key.':'.$app_secret);
$auth = base64_encode($app_key . ':' . $app_secret);
$ch = curl_init('https://api.dropboxapi.com/2/auth/token/from_oauth1');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Basic '.$auth,
'Authorization: Basic ' . $auth,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
@@ -272,7 +271,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Call from elFinder::netmout() before volume->mount().
*
* @return array
*
* @author Naoki Sawada
**/
public function netmountPrepare($options)
@@ -334,14 +332,14 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
}
$callback = $options['url']
.'?cmd=netmount&protocol=dropbox2&host=1';
. '?cmd=netmount&protocol=dropbox2&host=1';
if (!$aToken && empty($_GET['code'])) {
$url = $authHelper->getAuthUrl($callback);
$html = '<input id="elf-volumedriver-dropbox2-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
$html = '<input id="elf-volumedriver-dropbox2-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "dropbox2", mode: "makebtn"});
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "dropbox2", mode: "makebtn"});
</script>';
if (empty($options['pass']) && $options['host'] !== '1') {
$options['pass'] = 'return';
@@ -351,7 +349,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
} else {
$out = [
'node' => $options['id'],
'json' => '{"protocol": "dropbox2", "mode": "makebtn", "body" : "'.str_replace($html, '"', '\\"').'", "error" : "'.elFinder::ERROR_ACCESS_DENIED.'"}',
'json' => '{"protocol": "dropbox2", "mode": "makebtn", "body" : "' . str_replace($html, '"', '\\"') . '", "error" : "' . elFinder::ERROR_ACCESS_DENIED . '"}',
'bind' => 'netmount',
];
@@ -391,11 +389,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$folders = ['/' => '/'] + $folders;
$folders = json_encode($folders);
$json = '{"protocol": "dropbox2", "mode": "done", "folders": '.$folders.'}';
$json = '{"protocol": "dropbox2", "mode": "done", "folders": ' . $folders . '}';
$options['pass'] = 'return';
$html = 'Dropbox.com';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
</script>';
$this->session->set('Dropbox2AuthParams', $options);
@@ -405,7 +403,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
} catch (DropboxClientException $e) {
$this->session->remove('Dropbox2AuthParams')->remove('Dropbox2Tokens');
if (empty($options['pass'])) {
return ['exit' => true, 'body' => '{msg:'.elFinder::ERROR_ACCESS_DENIED.'}'.' '.$e->getMessage()];
return ['exit' => true, 'body' => '{msg:' . elFinder::ERROR_ACCESS_DENIED . '}' . ' ' . $e->getMessage()];
} else {
return ['exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]];
}
@@ -448,7 +446,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
*/
public function netunmount($netVolumes, $key)
{
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->driverId.'_'.$this->options['tokens']['uid'].'*.png')) {
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/') . DIRECTORY_SEPARATOR . $this->driverId . '_' . $this->options['tokens']['uid'] . '*.png')) {
foreach ($tmbs as $file) {
unlink($file);
}
@@ -466,7 +464,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Connect to remote server and check if credentials are correct, if so, store the connection id in $this->service.
*
* @return bool
*
* @author Naoki Sawada
**/
protected function init()
@@ -495,7 +492,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
try {
// make net mount key for network mount
$aToken = $this->options['access_token'];
$this->netMountKey = md5($aToken.'-'.$this->options['path']);
$this->netMountKey = md5($aToken . '-' . $this->options['path']);
$errors = [];
if (!$this->service) {
@@ -503,7 +500,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$this->service = new Dropbox($app);
}
} catch (DropboxClientException $e) {
$errors[] = 'Dropbox error: '.$e->getMessage();
$errors[] = 'Dropbox error: ' . $e->getMessage();
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
@@ -553,7 +550,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Configure after successfull mount.
*
* @author Naoki Sawada
*
* @throws elFinderAbortException
*/
protected function configure()
@@ -585,10 +581,9 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Cache dir contents.
*
* @param string $path dir path
*
* @return
*
* @author Naoki Sawada
*
*/
protected function cacheDir($path)
{
@@ -624,11 +619,10 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Recursive files search.
*
* @param string $path dir path
* @param string $q search string
* @param array $mimes
* @param string $q search string
* @param array $mimes
*
* @return array
*
* @throws elFinderAbortException
* @author Naoki Sawada
*/
@@ -671,12 +665,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Copy file/recursive copy dir only in current volume.
* Return new file path or false.
*
* @param string $src source path
* @param string $dst destination dir path
* @param string $src source path
* @param string $dst destination dir path
* @param string $name new file name (optionaly)
*
* @return string|false
*
* @throws elFinderAbortException
* @author Naoki Sawada
*/
@@ -704,11 +697,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
/**
* Remove file/ recursive remove dir.
*
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param bool $recursive
* @return bool
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param bool $recursive
*
* @return bool
* @throws elFinderAbortException
* @author Naoki Sawada
*/
@@ -746,11 +739,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* Create thumnbnail and return it's URL on success.
*
* @param string $path file path
* @param $stat
* @param $stat
*
* @return string|false
* @throws ImagickException
* @throws elFinderAbortException
*
* @author Naoki Sawada
*/
protected function createTmb($path, $stat)
@@ -760,7 +753,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
}
$name = $this->tmbname($stat);
$tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
$tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
// copy image into tmbPath so some drivers does not store files on local fs
if (!$data = $this->_db_getThumbnail($path)) {
@@ -819,17 +812,16 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $stat file stat
*
* @return string
*
* @author Naoki Sawada
**/
protected function tmbname($stat)
{
$name = $this->driverId.'_';
$name = $this->driverId . '_';
if (isset($this->options['tokens']) && is_array($this->options['tokens'])) {
$name .= $this->options['tokens']['uid'];
}
return $name.md5($stat['iid']).$stat['ts'].'.png';
return $name . md5($stat['iid']) . $stat['ts'] . '.png';
}
/**
@@ -840,12 +832,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $options options array
*
* @return bool|string
*
* @author Naoki Sawada
*/
public function getContentUrl($hash, $options = [])
{
if (! empty($options['onetime']) && $this->options['onetimeUrl']) {
if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
return parent::getContentUrl($hash, $options);
}
if (!empty($options['temporary'])) {
@@ -864,8 +855,8 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
if ($res && !empty($res['links'])) {
foreach ($res['links'] as $link) {
if (isset($link['link_permissions'])
&& isset($link['link_permissions']['requested_visibility'])
&& $link['link_permissions']['requested_visibility']['.tag'] === $this->options['publishPermission']['requested_visibility']) {
&& isset($link['link_permissions']['requested_visibility'])
&& $link['link_permissions']['requested_visibility']['.tag'] === $this->options['publishPermission']['requested_visibility']) {
$url = $link['url'];
break;
}
@@ -884,7 +875,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
return $url;
}
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
}
@@ -915,7 +906,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Naoki Sawada
**/
protected function _dirname($path)
@@ -931,7 +921,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Naoki Sawada
**/
protected function _basename($path)
@@ -948,12 +937,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $name
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _joinPath($dir, $name)
{
return rtrim($dir, '/').'/'.strtolower($name);
return rtrim($dir, '/') . '/' . strtolower($name);
}
/**
@@ -962,12 +950,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path path
*
* @return string
*
* @author Naoki Sawada
**/
protected function _normpath($path)
{
return '/'.ltrim($path, '/');
return '/' . ltrim($path, '/');
}
/**
@@ -976,7 +963,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _relpath($path)
@@ -994,7 +980,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Naoki Sawada
**/
protected function _abspath($path)
@@ -1012,7 +997,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Naoki Sawada
**/
protected function _path($path)
@@ -1029,12 +1013,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $parent parent path
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _inpath($path, $parent)
{
return $path == $parent || strpos($path, $parent.'/') === 0;
return $path == $parent || strpos($path, $parent . '/') === 0;
}
/***************** file stat ********************/
@@ -1050,13 +1033,11 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* - (bool) hidden is object hidden. optionally
* - (string) alias for symlinks - link target path relative to root path. optionally
* - (string) target for symlinks - link target path. optionally.
*
* If file does not exists - returns empty array or false.
*
* @param string $path file path
*
* @return array|false
*
* @author Dmitry (dio) Levashov
**/
protected function _stat($path)
@@ -1074,7 +1055,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _subdirs($path)
@@ -1093,7 +1073,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
}
}
} catch (DropboxClientException $e) {
$this->setError('Dropbox error: '.$e->getMessage());
$this->setError('Dropbox error: ' . $e->getMessage());
}
return $hasdir;
@@ -1109,7 +1089,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @return string
* @throws ImagickException
* @throws elFinderAbortException
*
* @author Naoki Sawada
*/
protected function _dimensions($path, $mime)
@@ -1124,10 +1103,10 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
file_put_contents($tmp, $data);
$size = getimagesize($tmp);
if ($size) {
$ret = array('dim' => $size[0].'x'.$size[1]);
$ret = array('dim' => $size[0] . 'x' . $size[1]);
$srcfp = fopen($tmp, 'rb');
if ($subImgLink = $this->getSubstituteImgLink(elFinder::$currentArgs['target'], $size, $srcfp)) {
$ret['url'] = $subImgLink;
$ret['url'] = $subImgLink;
}
}
}
@@ -1143,7 +1122,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path dir path
*
* @return array
*
* @author Naoki Sawada
**/
protected function _scandir($path)
@@ -1160,7 +1138,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param bool $write open file for writing
*
* @return resource|false
*
* @author Naoki Sawada
**/
protected function _fopen($path, $mode = 'rb')
@@ -1170,9 +1147,9 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$access_token = $this->service->getAccessToken();
if ($access_token) {
$data = array(
'target' => $link->getLink(),
'headers' => array('Authorization: Bearer '.$access_token),
);
'target' => $link->getLink(),
'headers' => array('Authorization: Bearer ' . $access_token),
);
return elFinder::getStreamByUrl($data);
}
@@ -1188,7 +1165,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param resource $fp file pointer
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _fclose($fp, $path = '')
@@ -1205,7 +1181,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $name new directory name
*
* @return string|bool
*
* @author Naoki Sawada
**/
protected function _mkdir($path, $name)
@@ -1213,7 +1188,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
try {
return $this->service->createFolder($this->_db_joinName($path, $name))->getPathLower();
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
}
@@ -1224,7 +1199,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $name new file name
*
* @return string|bool
*
* @author Naoki Sawada
**/
protected function _mkfile($path, $name)
@@ -1239,7 +1213,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path symlink path
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _symlink($target, $path, $name)
@@ -1255,7 +1228,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $name new file name
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _copy($source, $targetDir, $name)
@@ -1263,7 +1235,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
try {
$this->service->copy($source, $this->_db_joinName($targetDir, $name))->getPathLower();
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
return true;
@@ -1278,7 +1250,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $name file name
*
* @return string|bool
*
* @author Naoki Sawada
**/
protected function _move($source, $targetDir, $name)
@@ -1286,7 +1257,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
try {
return $this->service->move($source, $this->_db_joinName($targetDir, $name))->getPathLower();
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
}
@@ -1296,7 +1267,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _unlink($path)
@@ -1306,7 +1276,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
return true;
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
return true;
@@ -1318,7 +1288,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _rmdir($path)
@@ -1336,7 +1305,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $stat file stat (required by some virtual fs)
*
* @return bool|string
*
* @author Naoki Sawada
**/
protected function _save($fp, $path, $name, $stat)
@@ -1361,7 +1329,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
return $this->service->upload($dropboxFile, $fullpath, ['mode' => 'overwrite'])->getPathLower();
} catch (DropboxClientException $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
}
@@ -1371,7 +1339,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file path
*
* @return string|false
*
* @author Naoki Sawada
**/
protected function _getContents($path)
@@ -1382,7 +1349,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
$file = $this->service->download($path);
$contents = $file->getContents();
} catch (Exception $e) {
return $this->setError('Dropbox error: '.$e->getMessage());
return $this->setError('Dropbox error: ' . $e->getMessage());
}
return $contents;
@@ -1395,7 +1362,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $content new file content
*
* @return bool
*
* @author Naoki Sawada
**/
protected function _filePutContents($path, $content)
@@ -1404,7 +1370,7 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
if ($local = $this->getTempFile($path)) {
if (file_put_contents($local, $content, LOCK_EX) !== false
&& ($fp = fopen($local, 'rb'))) {
&& ($fp = fopen($local, 'rb'))) {
clearstatcache();
$name = '';
$stat = $this->stat($path);
@@ -1448,7 +1414,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return true
*
* @author Dmitry (dio) Levashov
* @author Alexey Sukhotin
**/
@@ -1464,7 +1429,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param string $path file/dir path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _findSymlinks($path)
@@ -1479,7 +1443,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return true
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
@@ -1497,7 +1460,6 @@ class elFinderVolumeDropbox2 extends elFinderVolumeDriver
* @param array $arc archiver options
*
* @return string|bool
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
File diff suppressed because it is too large Load Diff
+89 -124
View File
@@ -91,7 +91,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
/**
* Current token expires
*
*
* @var integer
**/
private $expires;
@@ -160,7 +160,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$paths = explode('/', $path);
$id = array_pop($paths);
if ($paths) {
$parent = '/'.implode('/', $paths);
$parent = '/' . implode('/', $paths);
$pid = array_pop($paths);
} else {
$rootid = ($this->root === '/') ? 'root' : trim($this->root, '/');
@@ -188,9 +188,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$result = [];
$pageToken = null;
$parameters = [
'fields' => self::FETCHFIELDS_LIST,
'pageSize' => 1000,
'spaces' => 'drive',
'fields' => self::FETCHFIELDS_LIST,
'pageSize' => 1000,
'spaces' => 'drive',
];
if (is_array($opts)) {
@@ -244,7 +244,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param array $raw line from ftp_rawlist() output
*
* @return array
*
* @author Dmitry Levashov
**/
protected function _gd_parseRaw($raw)
@@ -262,7 +261,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$stat['size'] = 0;
} else {
$stat['mime'] = $raw['mimeType'] == 'image/bmp' ? 'image/x-ms-bmp' : $raw['mimeType'];
$stat['size'] = (int) $raw['size'];
$stat['size'] = (int)$raw['size'];
if ($size = $raw->getImageMediaMetadata()) {
$stat['width'] = $size['width'];
$stat['height'] = $size['height'];
@@ -273,7 +272,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
if ($this->options['useGoogleTmb']) {
if (isset($raw['thumbnailLink'])) {
if ($published) {
$stat['tmb'] = 'drive.google.com/thumbnail?authuser=0&sz=s'.$this->options['tmbSize'].'&id='.$raw['id'];
$stat['tmb'] = 'drive.google.com/thumbnail?authuser=0&sz=s' . $this->options['tmbSize'] . '&id=' . $raw['id'];
} else {
$stat['tmb'] = substr($raw['thumbnailLink'], 8); // remove "https://"
}
@@ -317,7 +316,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
protected function _gd_getDirectoryData($usecache = true)
{
if ($usecache) {
$cache = $this->session->get($this->id.$this->netMountKey, []);
$cache = $this->session->get($this->id . $this->netMountKey, []);
if ($cache) {
$this->parents = $cache['parents'];
$this->names = $cache['names'];
@@ -337,8 +336,8 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$data = [];
$opts = [
'fields' => 'files(id, name, parents)',
'q' => sprintf('trashed=false and mimeType="%s"', self::DIRMIME),
'fields' => 'files(id, name, parents)',
'q' => sprintf('trashed=false and mimeType="%s"', self::DIRMIME),
];
$res = $this->_gd_query($opts);
foreach ($res as $raw) {
@@ -359,10 +358,10 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$data['root'] = $data[$root];
}
$this->directories = $data;
$this->session->set($this->id.$this->netMountKey, [
'parents' => $this->parents,
'names' => $this->names,
'directories' => $this->directories,
$this->session->set($this->id . $this->netMountKey, [
'parents' => $this->parents,
'names' => $this->names,
'directories' => $this->directories,
]);
}
@@ -394,6 +393,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Get ID based path from item ID.
*
* @param string $id
*
* @return array
*/
protected function _gd_getMountPaths($id)
@@ -404,7 +404,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
list($pid) = explode('/', $id, 2);
$path = $id;
if ('/'.$pid === $this->root) {
if ('/' . $pid === $this->root) {
$root = true;
} elseif (!isset($this->parents[$pid])) {
$root = true;
@@ -412,12 +412,12 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
$res = [];
if ($root) {
if ($this->root === '/' || strpos('/'.$path, $this->root) === 0) {
$res = [(strpos($path, '/') === false) ? '/' : ('/'.$path)];
if ($this->root === '/' || strpos('/' . $path, $this->root) === 0) {
$res = [(strpos($path, '/') === false) ? '/' : ('/' . $path)];
}
} else {
foreach ($this->parents[$pid] as $p) {
$_p = $p.'/'.$path;
$_p = $p . '/' . $path;
$res = array_merge($res, $this->_gd_getMountPaths($_p));
}
}
@@ -480,7 +480,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
protected function _gd_getDownloadUrl($file)
{
if (strpos($file->mimeType, 'application/vnd.google-apps.') !== 0) {
return 'https://www.googleapis.com/drive/v3/files/'.$file->getId().'?alt=media';
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '?alt=media';
} else {
$mimeMap = $this->options['appsExportMap'];
if (isset($mimeMap[$file->getMimeType()])) {
@@ -490,7 +490,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
$mime = rawurlencode($mime);
return 'https://www.googleapis.com/drive/v3/files/'.$file->getId().'/export?mimeType='.$mime;
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '/export?mimeType=' . $mime;
}
return false;
@@ -500,6 +500,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Get thumbnail from GoogleDrive.com.
*
* @param string $path
*
* @return string | boolean
*/
protected function _gd_getThumbnail($path)
@@ -508,7 +509,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
try {
$contents = $this->service->files->get($itemId, [
'alt' => 'media',
'alt' => 'media',
]);
$contents = $contents->getBody()->detach();
rewind($contents);
@@ -611,7 +612,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Call from elFinder::netmout() before volume->mount().
*
* @return array
*
* @author Naoki Sawada
* @author Raja Sharma updating for GoogleDrive
**/
@@ -682,7 +682,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
$callback = $options['url']
.'?cmd=netmount&protocol=googledrive&host=1';
. '?cmd=netmount&protocol=googledrive&host=1';
$client->setRedirectUri($callback);
if (!$aToken && empty($_GET['code'])) {
@@ -693,9 +693,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
$url = $client->createAuthUrl();
$html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
$html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
</script>';
if (empty($options['pass']) && $options['host'] !== '1') {
$options['pass'] = 'return';
@@ -705,7 +705,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
} else {
$out = [
'node' => $options['id'],
'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "'.str_replace($html, '"', '\\"').'", "error" : "'.elFinder::ERROR_ACCESS_DENIED.'"}',
'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "' . str_replace($html, '"', '\\"') . '", "error" : "' . elFinder::ERROR_ACCESS_DENIED . '"}',
'bind' => 'netmount',
];
@@ -744,11 +744,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$folders = ['root' => $rootObj->getName()] + $folders;
$folders = json_encode($folders);
$expires = empty($aToken['refresh_token']) ? $aToken['created'] + $aToken['expires_in'] - 30 : 0;
$json = '{"protocol": "googledrive", "mode": "done", "folders": '.$folders.', "expires": '.$expires.'}';
$json = '{"protocol": "googledrive", "mode": "done", "folders": ' . $folders . ', "expires": ' . $expires . '}';
$options['pass'] = 'return';
$html = 'Google.com';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
</script>';
$this->session->set('GoogleDriveAuthParams', $options);
@@ -758,7 +758,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
} catch (Exception $e) {
$this->session->remove('GoogleDriveAuthParams')->remove('GoogleDriveTokens');
if (empty($options['pass'])) {
return ['exit' => true, 'body' => '{msg:'.elFinder::ERROR_ACCESS_DENIED.'}'.' '.$e->getMessage()];
return ['exit' => true, 'body' => '{msg:' . elFinder::ERROR_ACCESS_DENIED . '}' . ' ' . $e->getMessage()];
} else {
return ['exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]];
}
@@ -799,18 +799,19 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
*
* @param $netVolumes
* @param $key
*
* @return bool
*/
public function netunmount($netVolumes, $key)
{
if (!$this->options['useGoogleTmb']) {
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->netMountKey.'*.png')) {
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/') . DIRECTORY_SEPARATOR . $this->netMountKey . '*.png')) {
foreach ($tmbs as $file) {
unlink($file);
}
}
}
$this->session->remove($this->id.$this->netMountKey);
$this->session->remove($this->id . $this->netMountKey);
return true;
}
@@ -828,9 +829,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
{
list($parentId, $name) = $this->_gd_splitPath($path);
$opts = [
'q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name),
'fields' => self::FETCHFIELDS_LIST,
];
'q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name),
'fields' => self::FETCHFIELDS_LIST,
];
$srcFile = $this->_gd_query($opts);
return empty($srcFile) ? false : $this->_gd_parseRaw($srcFile[0]);
@@ -845,7 +846,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* 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)
**/
@@ -889,7 +889,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$tmp = $this->getTempPath();
}
if ($tmp) {
$aTokenFile = $tmp.DIRECTORY_SEPARATOR.md5($this->options['client_id'].$this->options['refresh_token']).'.gtoken';
$aTokenFile = $tmp . DIRECTORY_SEPARATOR . md5($this->options['client_id'] . $this->options['refresh_token']) . '.gtoken';
if (is_file($aTokenFile)) {
$this->options['access_token'] = json_decode(file_get_contents($aTokenFile), true);
}
@@ -948,7 +948,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$this->service = new \Google_Service_Drive($client);
}
$this->netMountKey = md5($aToken.'-'.$this->options['path']);
$this->netMountKey = md5($aToken . '-' . $this->options['path']);
} catch (InvalidArgumentException $e) {
$errors[] = $e->getMessage();
} catch (Google_Service_Exception $e) {
@@ -956,7 +956,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
if (!$this->service) {
$this->session->remove($this->id.$this->netMountKey);
$this->session->remove($this->id . $this->netMountKey);
if ($aTokenFile) {
unlink($aTokenFile);
}
@@ -1044,9 +1044,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return array
*
* @author Dmitry Levashov
*
*/
protected function cacheDir($path)
{
@@ -1062,17 +1060,17 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$res = $this->_gd_query($opts);
$mountPath = $this->_normpath($path.'/');
$mountPath = $this->_normpath($path . '/');
if ($res) {
foreach ($res as $raw) {
if ($stat = $this->_gd_parseRaw($raw)) {
$stat = $this->updateCache($mountPath.$raw->id, $stat);
if (empty($stat['hidden']) && $path !== $mountPath.$raw->id) {
$stat = $this->updateCache($mountPath . $raw->id, $stat);
if (empty($stat['hidden']) && $path !== $mountPath . $raw->id) {
if (!$hasDir && $stat['mime'] === 'directory') {
$hasDir = true;
}
$this->dirsCache[$path][] = $mountPath.$raw->id;
$this->dirsCache[$path][] = $mountPath . $raw->id;
}
}
}
@@ -1089,11 +1087,10 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Recursive files search.
*
* @param string $path dir path
* @param string $q search string
* @param array $mimes
* @param string $q search string
* @param array $mimes
*
* @return array
*
* @throws elFinderAbortException
* @author Naoki Sawada
*/
@@ -1106,26 +1103,26 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
list(, $itemId) = $this->_gd_splitPath($path);
$path = $this->_normpath($path.'/');
$path = $this->_normpath($path . '/');
$result = [];
$query = '';
if ($itemId !== 'root') {
$dirs = array_merge([$itemId], $this->_gd_getDirectories($itemId));
$query = '(\''.implode('\' in parents or \'', $dirs).'\' in parents)';
$query = '(\'' . implode('\' in parents or \'', $dirs) . '\' in parents)';
}
$tmp = [];
if (!$mimes) {
foreach (explode(' ', $q) as $_v) {
$tmp[] = 'fullText contains \''.str_replace('\'', '\\\'', $_v).'\'';
$tmp[] = 'fullText contains \'' . str_replace('\'', '\\\'', $_v) . '\'';
}
$query .= ($query ? ' and ' : '').implode(' and ', $tmp);
$query .= ($query ? ' and ' : '') . implode(' and ', $tmp);
} else {
foreach ($mimes as $_v) {
$tmp[] = 'mimeType contains \''.str_replace('\'', '\\\'', $_v).'\'';
$tmp[] = 'mimeType contains \'' . str_replace('\'', '\\\'', $_v) . '\'';
}
$query .= ($query ? ' and ' : '').'('.implode(' or ', $tmp).')';
$query .= ($query ? ' and ' : '') . '(' . implode(' or ', $tmp) . ')';
}
$opts = [
@@ -1145,14 +1142,14 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
foreach ($parents as $parent) {
$paths = $this->_gd_getMountPaths($parent);
foreach ($paths as $path) {
$path = ($path === '') ? '/' : (rtrim($path, '/').'/');
if (!isset($this->cache[$path.$raw->id])) {
$stat = $this->updateCache($path.$raw->id, $stat);
$path = ($path === '') ? '/' : (rtrim($path, '/') . '/');
if (!isset($this->cache[$path . $raw->id])) {
$stat = $this->updateCache($path . $raw->id, $stat);
} else {
$stat = $this->cache[$path.$raw->id];
$stat = $this->cache[$path . $raw->id];
}
if (empty($stat['hidden'])) {
$stat['path'] = $this->_path($path).$stat['name'];
$stat['path'] = $this->_path($path) . $stat['name'];
$result[] = $stat;
}
}
@@ -1173,7 +1170,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name new file name (optionaly)
*
* @return string|false
*
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
**/
@@ -1193,7 +1189,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$res = $this->_gd_query($opts);
foreach ($res as $raw) {
$raw['mimeType'] == self::DIRMIME ? $this->copy($src.'/'.$raw['id'], $path, $raw['name']) : $this->_copy($src.'/'.$raw['id'], $path, $raw['name']);
$raw['mimeType'] == self::DIRMIME ? $this->copy($src . '/' . $raw['id'], $path, $raw['name']) : $this->_copy($src . '/' . $raw['id'], $path, $raw['name']);
}
$ret = $this->_joinPath($dst, $itemId);
@@ -1215,12 +1211,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
/**
* Remove file/ recursive remove dir.
*
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param bool $recursive
*
* @param bool $recursive
* @return bool
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
@@ -1259,9 +1254,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Create thumnbnail and return it's URL on success.
*
* @param string $path file path
* @param $stat
* @return string|false
* @param $stat
*
* @return string|false
* @throws ImagickException
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
@@ -1274,7 +1269,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
$name = $this->tmbname($stat);
$tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
$tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
// copy image into tmbPath so some drivers does not store files on local fs
if (!$data = $this->_gd_getThumbnail($path)) {
@@ -1330,12 +1325,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param array $stat file stat
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function tmbname($stat)
{
return $this->netMountKey.$stat['iid'].$stat['ts'].'.png';
return $this->netMountKey . $stat['iid'] . $stat['ts'] . '.png';
}
/**
@@ -1346,12 +1340,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param array $options options array
*
* @return bool|string
*
* @author Naoki Sawada
*/
public function getContentUrl($hash, $options = [])
{
if (! empty($options['onetime']) && $this->options['onetimeUrl']) {
if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
return parent::getContentUrl($hash, $options);
}
if (!empty($options['temporary'])) {
@@ -1397,7 +1390,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _dirname($path)
@@ -1413,7 +1405,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _basename($path)
@@ -1430,12 +1421,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _joinPath($dir, $name)
{
return $this->_normpath($dir.'/'.$name);
return $this->_normpath($dir . '/' . $name);
}
/**
@@ -1444,7 +1434,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path path
*
* @return string
*
* @author Troex Nevelin
**/
protected function _normpath($path)
@@ -1452,7 +1441,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
if (DIRECTORY_SEPARATOR !== '/') {
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
}
$path = '/'.ltrim($path, '/');
$path = '/' . ltrim($path, '/');
return $path;
}
@@ -1463,7 +1452,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _relpath($path)
@@ -1477,7 +1465,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _abspath($path)
@@ -1491,7 +1478,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _path($path)
@@ -1506,7 +1492,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$names[] = isset($this->names[$_p]) ? $this->names[$_p] : $_p;
}
return $this->rootName.implode('/', $names);
return $this->rootName . implode('/', $names);
}
/**
@@ -1516,12 +1502,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $parent parent path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _inpath($path, $parent)
{
return $path == $parent || strpos($path, $parent.'/') === 0;
return $path == $parent || strpos($path, $parent . '/') === 0;
}
/***************** file stat ********************/
@@ -1537,13 +1522,11 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* - (bool) hidden is object hidden. optionally
* - (string) alias for symlinks - link target path relative to root path. optionally
* - (string) target for symlinks - link target path. optionally.
*
* If file does not exists - returns empty array or false.
*
* @param string $path file path
*
* @return array|false
*
* @author Dmitry (dio) Levashov
**/
protected function _stat($path)
@@ -1565,7 +1548,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _subdirs($path)
@@ -1586,7 +1568,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $mime file mime type
*
* @return string
*
* @throws ImagickException
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
@@ -1600,7 +1581,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
if ($file = $this->_gd_getFile($path)) {
if (isset($file['imageMediaMetadata'])) {
$ret = array('dim' => $file['imageMediaMetadata']['width'].'x'.$file['imageMediaMetadata']['height']);
$ret = array('dim' => $file['imageMediaMetadata']['width'] . 'x' . $file['imageMediaMetadata']['height']);
if (func_num_args() > 2) {
$args = func_get_arg(2);
} else {
@@ -1613,7 +1594,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
if (min(($tmbSize / $srcSize[0]), ($tmbSize / $srcSize[1])) < 1) {
if ($this->_gd_isPublished($file)) {
$tmbSize = strval($tmbSize);
$ret['url'] = 'https://drive.google.com/thumbnail?authuser=0&sz=s'.$tmbSize.'&id='.$file['id'];
$ret['url'] = 'https://drive.google.com/thumbnail?authuser=0&sz=s' . $tmbSize . '&id=' . $file['id'];
} elseif ($subImgLink = $this->getSubstituteImgLink(elFinder::$currentArgs['target'], $srcSize)) {
$ret['url'] = $subImgLink;
}
@@ -1634,7 +1615,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return array
*
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
**/
@@ -1652,7 +1632,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param bool $write open file for writing
*
* @return resource|false
*
* @author Dmitry (dio) Levashov
**/
protected function _fopen($path, $mode = 'rb')
@@ -1675,8 +1654,8 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
}
if ($access_token) {
$data = array(
'target' => $dlurl,
'headers' => array('Authorization: Bearer '.$access_token),
'target' => $dlurl,
'headers' => array('Authorization: Bearer ' . $access_token),
);
return elFinder::getStreamByUrl($data);
@@ -1694,7 +1673,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param resource $fp file pointer
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _fclose($fp, $path = '')
@@ -1714,7 +1692,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name new directory name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkdir($path, $name)
@@ -1741,7 +1718,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
return false;
}
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
}
@@ -1752,7 +1729,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name new file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkfile($path, $name)
@@ -1767,7 +1743,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path symlink path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _symlink($target, $path, $name)
@@ -1783,7 +1758,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name new file name
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _copy($source, $targetDir, $name)
@@ -1805,7 +1779,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
return $itemId;
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
return true;
@@ -1820,13 +1794,12 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $name file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _move($source, $targetDir, $name)
{
list($removeParents, $itemId) = $this->_gd_splitPath($source);
$target = $this->_normpath($targetDir.'/'.$itemId);
$target = $this->_normpath($targetDir . '/' . $itemId);
try {
//moving and renaming a file or directory
$files = new \Google_Service_Drive_DriveFile();
@@ -1842,7 +1815,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$this->_gd_getDirectoryData(false);
}
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
return $target;
@@ -1854,7 +1827,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _unlink($path)
@@ -1867,7 +1839,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$opts = ['removeParents' => $pid];
$this->service->files->update($itemId, $files, $opts);
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
return true;
@@ -1879,7 +1851,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _rmdir($path)
@@ -1894,19 +1865,18 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Create new file and write into it from file pointer.
* Return new file path or false on error.
*
* @param resource $fp file pointer
* @param $path
* @param string $name file name
* @param array $stat file stat (required by some virtual fs)
* @param resource $fp file pointer
* @param $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;
$path .= '/' . $name;
}
list($parentId, $itemId, $parent) = $this->_gd_splitPath($path);
if ($name === '') {
@@ -2019,7 +1989,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
return false;
}
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
}
@@ -2029,7 +1999,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string|false
*
* @author Dmitry (dio) Levashov
**/
protected function _getContents($path)
@@ -2042,9 +2011,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
$contents = $this->service->files->get($itemId, [
'alt' => 'media',
]);
$contents = (string) $contents->getBody();
$contents = (string)$contents->getBody();
} catch (Exception $e) {
return $this->setError('GoogleDrive error: '.$e->getMessage());
return $this->setError('GoogleDrive error: ' . $e->getMessage());
}
return $contents;
@@ -2057,7 +2026,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param string $content new file content
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _filePutContents($path, $content)
@@ -2066,7 +2034,7 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
if ($local = $this->getTempFile($path)) {
if (file_put_contents($local, $content, LOCK_EX) !== false
&& ($fp = fopen($local, 'rb'))) {
&& ($fp = fopen($local, 'rb'))) {
clearstatcache();
$res = $this->_save($fp, $path, '', []);
fclose($fp);
@@ -2100,10 +2068,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Unpack archive.
*
* @param string $path archive path
* @param array $arc archiver command and arguments (same as in $this->archivers)
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return void
*
* @author Dmitry (dio) Levashov
* @author Alexey Sukhotin
*/
@@ -2117,10 +2084,9 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* Extract files from archive.
*
* @param string $path archive path
* @param array $arc archiver command and arguments (same as in $this->archivers)
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return void
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
*/
@@ -2138,7 +2104,6 @@ class elFinderVolumeGoogleDrive extends elFinderVolumeDriver
* @param array $arc archiver options
*
* @return string|bool
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
+294 -262
View File
@@ -5,279 +5,311 @@
*
* @author Naoki Sawada
**/
class elFinderVolumeGroup extends elFinderVolumeDriver {
/**
* Driver id
* Must be started from letter and contains [a-z0-9]
* Used as part of volume id
*
* @var string
**/
protected $driverId = 'g';
/**
* Constructor
* Extend options with required fields
*/
public function __construct() {
$this->options['type'] = 'group';
$this->options['path'] = '/';
$this->options['dirUrlOwn'] = true;
$this->options['syncMinMs'] = 0;
$this->options['tmbPath'] = '';
$this->options['disabled'] = array(
'archive',
'copy',
'cut',
'duplicate',
'edit',
'empty',
'extract',
'getfile',
'mkdir',
'mkfile',
'paste',
'resize',
'rm',
'upload'
);
}
/*********************************************************************/
/* FS API */
/*********************************************************************/
class elFinderVolumeGroup extends elFinderVolumeDriver
{
/*********************** paths/urls *************************/
/**
* @inheritdoc
**/
protected function _dirname($path) {
return '/';
}
/**
* Driver id
* Must be started from letter and contains [a-z0-9]
* Used as part of volume id
*
* @var string
**/
protected $driverId = 'g';
/**
* {@inheritDoc}
**/
protected function _basename($path) {
return '';
}
/**
* {@inheritDoc}
**/
protected function _joinPath($dir, $name) {
return '/' . $name;
}
/**
* {@inheritDoc}
**/
protected function _normpath($path) {
return '/';
}
/**
* {@inheritDoc}
**/
protected function _relpath($path) {
return '/';
}
/**
* {@inheritDoc}
**/
protected function _abspath($path) {
return '/';
}
/**
* {@inheritDoc}
**/
protected function _path($path) {
return '/';
}
/**
* {@inheritDoc}
**/
protected function _inpath($path, $parent) {
return false;
}
/***************** file stat ********************/
/**
* Constructor
* Extend options with required fields
*/
public function __construct()
{
$this->options['type'] = 'group';
$this->options['path'] = '/';
$this->options['dirUrlOwn'] = true;
$this->options['syncMinMs'] = 0;
$this->options['tmbPath'] = '';
$this->options['disabled'] = array(
'archive',
'copy',
'cut',
'duplicate',
'edit',
'empty',
'extract',
'getfile',
'mkdir',
'mkfile',
'paste',
'resize',
'rm',
'upload'
);
}
/**
* {@inheritDoc}
**/
protected function _stat($path) {
if ($path === '/') {
return array(
'size' => 0,
'ts' => 0,
'mime' => 'directory',
'read' => true,
'write' => false,
'locked' => true,
'hidden' => false,
'dirs' => 0
);
}
return false;
}
/**
* {@inheritDoc}
**/
protected function _subdirs($path) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _dimensions($path, $mime) {
return false;
}
/******************** file/dir content *********************/
/**
* {@inheritDoc}
**/
protected function readlink($path) {
return null;
}
/**
* {@inheritDoc}
**/
protected function _scandir($path) {
return array();
}
/*********************************************************************/
/* FS API */
/*********************************************************************/
/**
* {@inheritDoc}
**/
protected function _fopen($path, $mode='rb') {
return false;
}
/*********************** paths/urls *************************/
/**
* {@inheritDoc}
**/
protected function _fclose($fp, $path='') {
return true;
}
/******************** file/dir manipulations *************************/
/**
* {@inheritDoc}
**/
protected function _mkdir($path, $name) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _mkfile($path, $name) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _symlink($source, $targetDir, $name) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _copy($source, $targetDir, $name) {
return false;
}
/**
* @inheritdoc
**/
protected function _dirname($path)
{
return '/';
}
/**
* {@inheritDoc}
**/
protected function _move($source, $targetDir, $name) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _unlink($path) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _basename($path)
{
return '';
}
/**
* {@inheritDoc}
**/
protected function _rmdir($path) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _save($fp, $dir, $name, $stat) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _getContents($path) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _filePutContents($path, $content) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _joinPath($dir, $name)
{
return '/' . $name;
}
/**
* {@inheritDoc}
**/
protected function _checkArchivers() {
return;
}
/**
* {@inheritDoc}
**/
protected function _normpath($path)
{
return '/';
}
/**
* {@inheritDoc}
**/
protected function _chmod($path, $mode) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _relpath($path)
{
return '/';
}
/**
* {@inheritDoc}
**/
protected function _findSymlinks($path) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _abspath($path)
{
return '/';
}
/**
* {@inheritDoc}
**/
protected function _extract($path, $arc) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _archive($dir, $files, $name, $arc) {
return false;
}
/**
* {@inheritDoc}
**/
protected function _path($path)
{
return '/';
}
/**
* {@inheritDoc}
**/
protected function _inpath($path, $parent)
{
return false;
}
/***************** file stat ********************/
/**
* {@inheritDoc}
**/
protected function _stat($path)
{
if ($path === '/') {
return array(
'size' => 0,
'ts' => 0,
'mime' => 'directory',
'read' => true,
'write' => false,
'locked' => true,
'hidden' => false,
'dirs' => 0
);
}
return false;
}
/**
* {@inheritDoc}
**/
protected function _subdirs($path)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _dimensions($path, $mime)
{
return false;
}
/******************** file/dir content *********************/
/**
* {@inheritDoc}
**/
protected function readlink($path)
{
return null;
}
/**
* {@inheritDoc}
**/
protected function _scandir($path)
{
return array();
}
/**
* {@inheritDoc}
**/
protected function _fopen($path, $mode = 'rb')
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _fclose($fp, $path = '')
{
return true;
}
/******************** file/dir manipulations *************************/
/**
* {@inheritDoc}
**/
protected function _mkdir($path, $name)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _mkfile($path, $name)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _symlink($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _copy($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _move($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _unlink($path)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _rmdir($path)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _save($fp, $dir, $name, $stat)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _getContents($path)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _filePutContents($path, $content)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _checkArchivers()
{
return;
}
/**
* {@inheritDoc}
**/
protected function _chmod($path, $mode)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _findSymlinks($path)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _extract($path, $arc)
{
return false;
}
/**
* {@inheritDoc}
**/
protected function _archive($dir, $files, $name, $arc)
{
return false;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+157 -189
View File
@@ -78,7 +78,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
/**
* Current token expires
*
*
* @var integer
**/
private $expires;
@@ -118,10 +118,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
/**
* Obtains a new access token from OAuth. This token is valid for one hour.
*
* @param $client_id
* @param $client_secret
* @param string $code The code returned by OneDrive after
* @param $client_id
* @param $client_secret
* @param string $code The code returned by OneDrive after
* successful log in
*
* @return object|string
* @throws Exception Thrown if the redirect URI of this Client instance's
* state is not set
@@ -141,26 +142,26 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$curl = curl_init();
$fields = http_build_query(
array(
'client_id' => $client_id,
'redirect_uri' => elFinder::getConnectorUrl(),
'client_secret' => $client_secret,
'code' => $code,
'grant_type' => 'authorization_code',
)
);
array(
'client_id' => $client_id,
'redirect_uri' => elFinder::getConnectorUrl(),
'client_secret' => $client_secret,
'code' => $code,
'grant_type' => 'authorization_code',
)
);
curl_setopt_array($curl, array(
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_HTTPHEADER => array(
'Content-Length: '.strlen($fields),
),
CURLOPT_HTTPHEADER => array(
'Content-Length: ' . strlen($fields),
),
CURLOPT_URL => $url,
CURLOPT_URL => $url,
));
$result = curl_exec($curl);
@@ -168,7 +169,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if (false === $result) {
if (curl_errno($curl)) {
throw new \Exception('curl_setopt_array() failed: '
.curl_error($curl));
. curl_error($curl));
} else {
throw new \Exception('curl_setopt_array(): empty response');
}
@@ -181,9 +182,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
throw new \Exception('json_decode() failed');
}
return (object) array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
return (object)array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
}
@@ -217,22 +218,22 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$curl = curl_init();
curl_setopt_array($curl, array(
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true, // i am sending post data
CURLOPT_POSTFIELDS => 'client_id='.urlencode($this->options['client_id'])
.'&client_secret='.urlencode($this->options['client_secret'])
.'&grant_type=refresh_token'
.'&refresh_token='.urlencode($token->data->refresh_token),
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true, // i am sending post data
CURLOPT_POSTFIELDS => 'client_id=' . urlencode($this->options['client_id'])
. '&client_secret=' . urlencode($this->options['client_secret'])
. '&grant_type=refresh_token'
. '&refresh_token=' . urlencode($token->data->refresh_token),
CURLOPT_URL => $url,
));
CURLOPT_URL => $url,
));
$result = curl_exec($curl);
if (!$result) {
if (curl_errno($curl)) {
throw new \Exception('curl_setopt_array() failed: '.curl_error($curl));
throw new \Exception('curl_setopt_array() failed: ' . curl_error($curl));
} else {
throw new \Exception('curl_setopt_array(): empty response');
}
@@ -249,10 +250,10 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
}
$token = (object) array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
$token = (object)array(
'expires' => time() + $decoded->expires_in - 30,
'data' => $decoded,
);
$this->session->set('OneDriveTokens', $token);
$this->options['accessToken'] = json_encode($token);
@@ -284,7 +285,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$paths = explode('/', trim($path, '/'));
$id = array_pop($paths);
if ($paths) {
$parent = '/'.implode('/', $paths);
$parent = '/' . implode('/', $paths);
$pid = array_pop($paths);
} else {
$pid = 'root';
@@ -305,12 +306,12 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$curl = curl_init($url);
$defaultOptions = array(
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer '.$this->token->data->access_token,
),
// General options.
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer ' . $this->token->data->access_token,
),
);
curl_setopt_array($curl, $defaultOptions);
@@ -322,8 +323,8 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Creates a base cURL object which is compatible with the OneDrive API.
*
* @param string $path The path of the API call (eg. me/skydrive)
* @param bool $contents
*
* @param bool $contents
* @return resource A compatible cURL object
* @throws elFinderAbortException
*/
@@ -340,7 +341,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if (isset($result->value)) {
$res = $result->value;
unset($result->value);
$result = (array) $result;
$result = (array)$result;
if (!empty($result['@odata.nextLink'])) {
$nextRes = $this->_od_createCurl($result['@odata.nextLink'], false);
if (is_array($nextRes)) {
@@ -358,10 +359,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
/**
* Drive query and fetchAll.
*
* @param $itemId
* @param bool $fetch_self
* @param bool $recursive
* @param $itemId
* @param bool $fetch_self
* @param bool $recursive
* @param array $options
*
* @return object|array
* @throws elFinderAbortException
*/
@@ -376,14 +378,14 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if ($fetch_self == true) {
$path = $itemId;
} else {
$path = $itemId.'/children';
$path = $itemId . '/children';
}
if (isset($options['query'])) {
$path .= '?'.http_build_query($options['query']);
$path .= '?' . http_build_query($options['query']);
}
$url = self::API_URL.$path;
$url = self::API_URL . $path;
$res = $this->_od_createCurl($url);
if (!$fetch_self && $recursive && is_array($res)) {
@@ -406,7 +408,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param object $raw line from ftp_rawlist() output
*
* @return array
*
* @author Dmitry Levashov
**/
protected function _od_parseRaw($raw)
@@ -433,7 +434,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if (isset($raw->file->mimeType)) {
$stat['mime'] = $raw->file->mimeType;
}
$stat['size'] = (int) $raw->size;
$stat['size'] = (int)$raw->size;
if (!$this->disabledGetUrl) {
$stat['url'] = '1';
}
@@ -476,6 +477,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Get thumbnail from OneDrive.com.
*
* @param string $path
*
* @return string | boolean
*/
protected function _od_getThumbnail($path)
@@ -483,7 +485,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
list(, $itemId) = $this->_od_splitPath($path);
try {
$url = self::API_URL.$itemId.'/thumbnails/0/medium/content';
$url = self::API_URL . $itemId . '/thumbnails/0/medium/content';
return $this->_od_createCurl($url, $contents = true);
} catch (Exception $e) {
@@ -513,9 +515,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
// create upload session
if ($itemId) {
$url = self::API_URL.$itemId.'/createUploadSession';
$url = self::API_URL . $itemId . '/createUploadSession';
} else {
$url = self::API_URL.$parentId.':/'.rawurlencode($name).':/createUploadSession';
$url = self::API_URL . $parentId . ':/' . rawurlencode($name) . ':/createUploadSession';
}
$curl = $this->_od_prepareCurl($url);
curl_setopt_array($curl, array(
@@ -530,7 +532,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
throw new Exception($sess->error->message);
}
$next = strlen($send);
$range = '0-'.($next - 1).'/'.$size;
$range = '0-' . ($next - 1) . '/' . $size;
} else {
throw new Exception('API response can not be obtained.');
}
@@ -550,8 +552,8 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
CURLOPT_RETURNTRANSFER => true,
CURLOPT_INFILE => $putFp,
CURLOPT_HTTPHEADER => array(
'Content-Length: '.strlen($send),
'Content-Range: bytes '.$range,
'Content-Length: ' . strlen($send),
'Content-Range: bytes ' . $range,
),
);
curl_setopt_array($curl, $options);
@@ -573,7 +575,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
throw new Exception('Data can not be acquired from the source.');
}
$next += strlen($send);
$range = $_next.'-'.($next - 1).'/'.$size;
$range = $_next . '-' . ($next - 1) . '/' . $size;
$retry = 0;
} else {
if (++$retry > 3) {
@@ -593,7 +595,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
throw new Exception('An error occurred in the uploadSession API call.');
}
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
}
@@ -642,7 +644,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Call from elFinder::netmout() before volume->mount().
*
* @return array
*
* @author Naoki Sawada
* @author Raja Sharma updating for OneDrive
**/
@@ -677,27 +678,27 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
try {
// Obtain the token using the code received by the OneDrive API
$this->session->set('OneDriveTokens',
$this->_od_obtainAccessToken($options['client_id'], $options['client_secret'], $_GET['code']));
$this->_od_obtainAccessToken($options['client_id'], $options['client_secret'], $_GET['code']));
$out = array(
'node' => $options['id'],
'json' => '{"protocol": "onedrive", "mode": "done", "reset": 1}',
'bind' => 'netmount',
'node' => $options['id'],
'json' => '{"protocol": "onedrive", "mode": "done", "reset": 1}',
'bind' => 'netmount',
);
return array('exit' => 'callback', 'out' => $out);
} catch (Exception $e) {
$out = array(
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED.' '.$e->getMessage())),
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED . ' ' . $e->getMessage())),
);
return array('exit' => 'callback', 'out' => $out);
}
} elseif (!empty($_GET['error'])) {
$out = array(
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
'node' => $options['id'],
'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
);
return array('exit' => 'callback', 'out' => $out);
@@ -737,17 +738,17 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
foreach ($this->ARGS as $k => $v) {
if (!in_array($k, $innerKeys)) {
$cdata .= '&'.$k.'='.rawurlencode($v);
$cdata .= '&' . $k . '=' . rawurlencode($v);
}
}
if (empty($options['url'])) {
$options['url'] = elFinder::getConnectorUrl();
}
$callback = $options['url']
.'?cmd=netmount&protocol=onedrive&host=onedrive.com&user=init&pass=return&node='.$options['id'].$cdata;
. '?cmd=netmount&protocol=onedrive&host=onedrive.com&user=init&pass=return&node=' . $options['id'] . $cdata;
try {
$this->session->set('OneDriveTokens', (object) array('token' => null));
$this->session->set('OneDriveTokens', (object)array('token' => null));
$offline = '';
// Gets a log in URL with sufficient privileges from the OneDrive API
@@ -755,21 +756,21 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$offline = ' offline_access';
}
$redirect_uri = $options['url'].'/netmount/onedrive/1';
$redirect_uri = $options['url'] . '/netmount/onedrive/1';
$url = self::AUTH_URL
.'?client_id='.urlencode($options['client_id'])
.'&scope='.urlencode('files.readwrite.all'.$offline)
.'&response_type=code'
.'&redirect_uri='.urlencode($redirect_uri);
. '?client_id=' . urlencode($options['client_id'])
. '&scope=' . urlencode('files.readwrite.all' . $offline)
. '&response_type=code'
. '&redirect_uri=' . urlencode($redirect_uri);
$url .= '&oauth_callback='.rawurlencode($callback);
$url .= '&oauth_callback=' . rawurlencode($callback);
} catch (Exception $e) {
return array('exit' => true, 'body' => '{msg:errAccess}');
}
$html = '<input id="elf-volumedriver-onedrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
$html = '<input id="elf-volumedriver-onedrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "onedrive", mode: "makebtn"});
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "onedrive", mode: "makebtn"});
</script>';
return array('exit' => true, 'body' => $html);
@@ -790,11 +791,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$folders = ['root' => 'My OneDrive'] + $folders;
$folders = json_encode($folders);
$expires = empty($this->token->data->refresh_token) ? (int) $this->token->expires : 0;
$json = '{"protocol": "onedrive", "mode": "done", "folders": '.$folders.', "expires": '.$expires.'}';
$expires = empty($this->token->data->refresh_token) ? (int)$this->token->expires : 0;
$json = '{"protocol": "onedrive", "mode": "done", "folders": ' . $folders . ', "expires": ' . $expires . '}';
$html = 'OneDrive.com';
$html .= '<script>
$("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
$("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
</script>';
return array('exit' => true, 'body' => $html);
@@ -828,7 +829,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
*/
public function netunmount($netVolumes, $key)
{
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->tmbPrefix.'*.png')) {
if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/') . DIRECTORY_SEPARATOR . $this->tmbPrefix . '*.png')) {
foreach ($tmbs as $file) {
unlink($file);
}
@@ -861,7 +862,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn.
*
* @return bool
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
@@ -882,7 +882,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
return $this->setError($e->getMessage());
}
$this->expires = empty($this->token->data->refresh_token) ? (int) $this->token->expires : 0;
$this->expires = empty($this->token->data->refresh_token) ? (int)$this->token->expires : 0;
if (empty($options['netkey'])) {
// make net mount key
@@ -903,12 +903,12 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if (empty($this->options['alias'])) {
$this->options['alias'] = ($this->options['path'] === '/') ? $this->options['root'] :
$this->_od_query(basename($this->options['path']), $fetch_self = true)->name.'@OneDrive';
$this->_od_query(basename($this->options['path']), $fetch_self = true)->name . '@OneDrive';
}
$this->rootName = $this->options['alias'];
$this->tmbPrefix = 'onedrive'.base_convert($this->netMountKey, 10, 32);
$this->tmbPrefix = 'onedrive' . base_convert($this->netMountKey, 10, 32);
if (!empty($this->options['tmpPath'])) {
if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) {
@@ -976,8 +976,8 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
{
list($pid, $name) = $this->_od_splitPath($path);
$raw = $this->_od_query($pid.'/children/'.rawurlencode($name), true);
return $raw? $this->_od_parseRaw($raw) : false;
$raw = $this->_od_query($pid . '/children/' . rawurlencode($name), true);
return $raw ? $this->_od_parseRaw($raw) : false;
}
/**
@@ -1024,12 +1024,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Copy file/recursive copy dir only in current volume.
* Return new file path or false.
*
* @param string $src source path
* @param string $dst destination dir path
* @param string $src source path
* @param string $dst destination dir path
* @param string $name new file name (optionaly)
*
* @return string|false
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
@@ -1056,11 +1055,10 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
/**
* Remove file/ recursive remove dir.
*
* @param string $path file path
* @param bool $force try to remove even if file locked
* @param string $path file path
* @param bool $force try to remove even if file locked
*
* @return bool
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Naoki Sawada
@@ -1099,9 +1097,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Create thumnbnail and return it's URL on success.
*
* @param string $path file path
* @param $stat
* @return string|false
* @param $stat
*
* @return string|false
* @throws ImagickException
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
@@ -1135,7 +1133,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
}
$name = $this->tmbname($stat);
$tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
$tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
// copy image into tmbPath so some drivers does not store files on local fs
if (!$data = $this->_od_getThumbnail($path)) {
@@ -1191,12 +1189,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param array $stat file stat
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function tmbname($stat)
{
return $this->tmbPrefix.$stat['rev'].$stat['ts'].'.png';
return $this->tmbPrefix . $stat['rev'] . $stat['ts'] . '.png';
}
/**
@@ -1206,12 +1203,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param array $options options
*
* @return string
*
* @author Naoki Sawada
**/
public function getContentUrl($hash, $options = array())
{
if (! empty($options['onetime']) && $this->options['onetimeUrl']) {
if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
return parent::getContentUrl($hash, $options);
}
if (!empty($options['temporary'])) {
@@ -1227,8 +1223,8 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
list(, $itemId) = $this->_od_splitPath($path);
try {
$url = self::API_URL.$itemId.'/createLink';
$data = (object) array(
$url = self::API_URL . $itemId . '/createLink';
$data = (object)array(
'type' => 'embed',
'scope' => 'anonymous',
);
@@ -1244,7 +1240,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$result = json_decode($result);
if (isset($result->link)) {
list(, $res) = explode('?', $result->link->webUrl);
$res = 'https://onedrive.live.com/download.aspx?'.$res;
$res = 'https://onedrive.live.com/download.aspx?' . $res;
}
}
} catch (Exception $e) {
@@ -1263,7 +1259,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _dirname($path)
@@ -1279,7 +1274,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _basename($path)
@@ -1296,7 +1290,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $name
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _joinPath($dir, $name)
@@ -1305,7 +1298,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$dir = '';
}
return $this->_normpath($dir.'/'.$name);
return $this->_normpath($dir . '/' . $name);
}
/**
@@ -1314,7 +1307,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path path
*
* @return string
*
* @author Troex Nevelin
**/
protected function _normpath($path)
@@ -1322,7 +1314,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if (DIRECTORY_SEPARATOR !== '/') {
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
}
$path = '/'.ltrim($path, '/');
$path = '/' . ltrim($path, '/');
return $path;
}
@@ -1333,7 +1325,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _relpath($path)
@@ -1347,7 +1338,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _abspath($path)
@@ -1361,12 +1351,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string
*
* @author Dmitry (dio) Levashov
**/
protected function _path($path)
{
return $this->rootName.$this->_normpath(substr($path, strlen($this->root)));
return $this->rootName . $this->_normpath(substr($path, strlen($this->root)));
}
/**
@@ -1376,12 +1365,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $parent parent path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _inpath($path, $parent)
{
return $path == $parent || strpos($path, $parent.'/') === 0;
return $path == $parent || strpos($path, $parent . '/') === 0;
}
/***************** file stat ********************/
@@ -1397,13 +1385,11 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* - (bool) hidden is object hidden. optionally
* - (string) alias for symlinks - link target path relative to root path. optionally
* - (string) target for symlinks - link target path. optionally.
*
* If file does not exists - returns empty array or false.
*
* @param string $path file path
*
* @return array|false
*
* @author Dmitry (dio) Levashov
**/
protected function _stat($path)
@@ -1425,7 +1411,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
@@ -1433,7 +1418,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
{
list(, $itemId) = $this->_od_splitPath($path);
return (bool) $this->_od_query($itemId, false, false, array(
return (bool)$this->_od_query($itemId, false, false, array(
'query' => array(
'top' => 1,
'select' => 'id',
@@ -1450,7 +1435,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $mime file mime type
*
* @return string
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
*/
@@ -1478,19 +1462,19 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
),
);
if ($tmbSize) {
$tmb = 'c'.$tmbSize.'x'.$tmbSize;
$options['query']['expand'] = 'thumbnails(select='.$tmb.')';
$tmb = 'c' . $tmbSize . 'x' . $tmbSize;
$options['query']['expand'] = 'thumbnails(select=' . $tmb . ')';
}
$raw = $this->_od_query($itemId, true, false, $options);
if ($raw && $img = $raw->image) {
if (isset($img->width) && isset($img->height)) {
$ret = array('dim' => $img->width.'x'.$img->height);
$ret = array('dim' => $img->width . 'x' . $img->height);
if ($tmbSize) {
$srcSize = explode('x', $ret['dim']);
if (min(($tmbSize / $srcSize[0]), ($tmbSize / $srcSize[1])) < 1) {
if (!empty($raw->thumbnails)) {
$tmbArr = (array) $raw->thumbnails[0];
$tmbArr = (array)$raw->thumbnails[0];
if (!empty($tmbArr[$tmb]->url)) {
$ret['url'] = $tmbArr[$tmb]->url;
}
@@ -1507,7 +1491,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if ($size = @getimagesize($work)) {
$cache['width'] = $size[0];
$cache['height'] = $size[1];
$ret = $size[0].'x'.$size[1];
$ret = $size[0] . 'x' . $size[1];
}
}
is_file($work) && @unlink($work);
@@ -1523,7 +1507,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return array
*
* @throws elFinderAbortException
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
@@ -1542,7 +1525,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param bool $write open file for writing
*
* @return resource|false
*
* @author Dmitry (dio) Levashov
**/
protected function _fopen($path, $mode = 'rb')
@@ -1550,8 +1532,8 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if ($mode === 'rb' || $mode === 'r') {
list(, $itemId) = $this->_od_splitPath($path);
$data = array(
'target' => self::API_URL.$itemId.'/content',
'headers' => array('Authorization: Bearer '.$this->token->data->access_token),
'target' => self::API_URL . $itemId . '/content',
'headers' => array('Authorization: Bearer ' . $this->token->data->access_token),
);
return elFinder::getStreamByUrl($data);
@@ -1566,7 +1548,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param resource $fp file pointer
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _fclose($fp, $path = '')
@@ -1586,7 +1567,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $name new directory name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkdir($path, $name)
@@ -1596,13 +1576,13 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
try {
$properties = array(
'name' => (string) $name,
'folder' => (object) array(),
'name' => (string)$name,
'folder' => (object)array(),
);
$data = (object) $properties;
$data = (object)$properties;
$url = self::API_URL.$parentId.'/children';
$url = self::API_URL . $parentId . '/children';
$curl = $this->_od_prepareCurl($url);
@@ -1618,7 +1598,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
return $this->_joinPath($path, $folder->id);
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
}
@@ -1629,7 +1609,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $name new file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
**/
protected function _mkfile($path, $name)
@@ -1644,7 +1623,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path symlink path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _symlink($target, $path, $name)
@@ -1660,7 +1638,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $name new file name
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _copy($source, $targetDir, $name)
@@ -1672,24 +1649,24 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
list(, $parentId) = $this->_od_splitPath($targetDir);
list(, $itemId) = $this->_od_splitPath($source);
$url = self::API_URL.$itemId.'/copy';
$url = self::API_URL . $itemId . '/copy';
$properties = array(
'name' => (string) $name,
'name' => (string)$name,
);
if ($parentId === 'root') {
$properties['parentReference'] = (object) array('path' => '/drive/root:');
$properties['parentReference'] = (object)array('path' => '/drive/root:');
} else {
$properties['parentReference'] = (object) array('id' => (string) $parentId);
$properties['parentReference'] = (object)array('id' => (string)$parentId);
}
$data = (object) $properties;
$data = (object)$properties;
$curl = $this->_od_prepareCurl($url);
curl_setopt_array($curl, array(
CURLOPT_POST => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer '.$this->token->data->access_token,
'Content-Type: application/json',
'Authorization: Bearer ' . $this->token->data->access_token,
'Prefer: respond-async',
),
CURLOPT_POSTFIELDS => json_encode($data),
@@ -1716,7 +1693,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
break;
}
} elseif (isset($res->error)) {
return $this->setError('OneDrive error: '.$res->error->message);
return $this->setError('OneDrive error: ' . $res->error->message);
}
}
}
@@ -1731,7 +1708,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
return false;
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
return true;
@@ -1742,11 +1719,10 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Return new file path or false.
*
* @param string $source source file path
* @param $targetDir
* @param string $name file name
* @param $targetDir
* @param string $name file name
*
* @return string|bool
*
* @author Dmitry (dio) Levashov
*/
protected function _move($source, $targetDir, $name)
@@ -1756,31 +1732,31 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
list($sourceParentId, $itemId, $srcParent) = $this->_od_splitPath($source);
$properties = array(
'name' => (string) $name,
);
'name' => (string)$name,
);
if ($targetParentId !== $sourceParentId) {
$properties['parentReference'] = (object) array('id' => (string) $targetParentId);
$properties['parentReference'] = (object)array('id' => (string)$targetParentId);
}
$url = self::API_URL.$itemId;
$data = (object) $properties;
$url = self::API_URL . $itemId;
$data = (object)$properties;
$curl = $this->_od_prepareCurl($url);
curl_setopt_array($curl, array(
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => json_encode($data),
));
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => json_encode($data),
));
$result = json_decode(curl_exec($curl));
curl_close($curl);
if ($result && isset($result->id)) {
return $targetDir.'/'.$result->id;
return $targetDir . '/' . $result->id;
} else {
return false;
}
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
return false;
@@ -1792,7 +1768,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _unlink($path)
@@ -1801,7 +1776,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
try {
list(, $itemId) = $this->_od_splitPath($path);
$url = self::API_URL.$itemId;
$url = self::API_URL . $itemId;
$curl = $this->_od_prepareCurl($url);
curl_setopt_array($curl, array(
@@ -1812,7 +1787,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
$result = curl_exec($curl);
curl_close($curl);
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
return true;
@@ -1824,7 +1799,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path dir path
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _rmdir($path)
@@ -1836,13 +1810,12 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Create new file and write into it from file pointer.
* Return new file path or false on error.
*
* @param resource $fp file pointer
* @param $path
* @param string $name file name
* @param array $stat file stat (required by some virtual fs)
* @param resource $fp file pointer
* @param $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)
@@ -1880,9 +1853,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
try {
//Create or Update a file
if ($itemId === '') {
$url = self::API_URL.$parentId.':/'.rawurlencode($name).':/content';
$url = self::API_URL . $parentId . ':/' . rawurlencode($name) . ':/content';
} else {
$url = self::API_URL.$itemId.'/content';
$url = self::API_URL . $itemId . '/content';
}
$curl = $this->_od_prepareCurl();
@@ -1904,7 +1877,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
return $this->_joinPath($parent, $file->id);
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
}
@@ -1914,7 +1887,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $path file path
*
* @return string|false
*
* @author Dmitry (dio) Levashov
**/
protected function _getContents($path)
@@ -1923,10 +1895,10 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
try {
list(, $itemId) = $this->_od_splitPath($path);
$url = self::API_URL.$itemId.'/content';
$url = self::API_URL . $itemId . '/content';
$contents = $this->_od_createCurl($url, $contents = true);
} catch (Exception $e) {
return $this->setError('OneDrive error: '.$e->getMessage());
return $this->setError('OneDrive error: ' . $e->getMessage());
}
return $contents;
@@ -1939,7 +1911,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param string $content new file content
*
* @return bool
*
* @author Dmitry (dio) Levashov
**/
protected function _filePutContents($path, $content)
@@ -1948,7 +1919,7 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
if ($local = $this->getTempFile($path)) {
if (file_put_contents($local, $content, LOCK_EX) !== false
&& ($fp = fopen($local, 'rb'))) {
&& ($fp = fopen($local, 'rb'))) {
clearstatcache();
$res = $this->_save($fp, $path, '', array());
fclose($fp);
@@ -1982,10 +1953,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Unpack archive.
*
* @param string $path archive path
* @param array $arc archiver command and arguments (same as in $this->archivers)
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return void
*
* @author Dmitry (dio) Levashov
* @author Alexey Sukhotin
*/
@@ -1999,10 +1969,9 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* Extract files from archive.
*
* @param string $path archive path
* @param array $arc archiver command and arguments (same as in $this->archivers)
* @param array $arc archiver command and arguments (same as in $this->archivers)
*
* @return void
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
*/
@@ -2020,7 +1989,6 @@ class elFinderVolumeOneDrive extends elFinderVolumeDriver
* @param array $arc archiver options
*
* @return string|bool
*
* @author Dmitry (dio) Levashov,
* @author Alexey Sukhotin
**/
+1
View File
@@ -1,4 +1,5 @@
<?php
/**
* elFinder driver for trash bin at local filesystem.
*
+1
View File
@@ -1,4 +1,5 @@
<?php
/**
* elFinder driver for trash bin at MySQL Database
*
+360 -352
View File
@@ -1,10 +1,8 @@
<?php
/**
* Copyright (c) 2011, oov. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
@@ -13,7 +11,6 @@
* - Neither the name of the oov nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
@@ -24,20 +21,16 @@
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* bmp ファイルを GD で使えるように
*
* 使用例:
* //ファイルから読み込む場合はGDでPNGなどを読み込むのと同じような方法で可
* $image = imagecreatefrombmp("test.bmp");
* imagedestroy($image);
*
* //文字列から読み込む場合は以下の方法で可
* $image = GdBmp::loadFromString(file_get_contents("test.bmp"));
* //自動判定されるので破損ファイルでなければこれでも上手くいく
* //$image = imagecreatefrombmp(file_get_contents("test.bmp"));
* imagedestroy($image);
*
* //その他任意のストリームからの読み込みも可能
* $stream = fopen("http://127.0.0.1/test.bmp");
* $image = GdBmp::loadFromStream($stream);
@@ -45,7 +38,6 @@
* //$image = imagecreatefrombmp($stream);
* fclose($stream);
* imagedestroy($image);
*
* 対応フォーマット
* 1bit
* 4bit
@@ -58,390 +50,406 @@
* BITMAPINFOHEADER の biCompression が BI_PNG / BI_JPEG の画像
* すべての形式でトップダウン/ボトムアップの両方をサポート
* 特殊なビットフィールドでもビットフィールドデータが正常なら読み込み可能
*
* 以下のものは非対応
* BITMAPV4HEADER と BITMAPV5HEADER に含まれる色空間に関する様々な機能
*
* @param $filename_or_stream_or_binary
*
* @return bool|resource
*/
if (! function_exists('imagecreatefrombmp')) {
function imagecreatefrombmp($filename_or_stream_or_binary){
return elFinderLibGdBmp::load($filename_or_stream_or_binary);
}
if (!function_exists('imagecreatefrombmp')) {
function imagecreatefrombmp($filename_or_stream_or_binary)
{
return elFinderLibGdBmp::load($filename_or_stream_or_binary);
}
}
class elFinderLibGdBmp{
public static function load($filename_or_stream_or_binary){
if (is_resource($filename_or_stream_or_binary)){
return self::loadFromStream($filename_or_stream_or_binary);
} else if (is_string($filename_or_stream_or_binary) && strlen($filename_or_stream_or_binary) >= 26){
$bfh = unpack("vtype/Vsize", $filename_or_stream_or_binary);
if ($bfh["type"] == 0x4d42 && ($bfh["size"] == 0 || $bfh["size"] == strlen($filename_or_stream_or_binary))){
return self::loadFromString($filename_or_stream_or_binary);
}
}
return self::loadFromFile($filename_or_stream_or_binary);
}
public static function loadFromFile($filename){
$fp = fopen($filename, "rb");
if ($fp === false){
return false;
}
class elFinderLibGdBmp
{
public static function load($filename_or_stream_or_binary)
{
if (is_resource($filename_or_stream_or_binary)) {
return self::loadFromStream($filename_or_stream_or_binary);
} else if (is_string($filename_or_stream_or_binary) && strlen($filename_or_stream_or_binary) >= 26) {
$bfh = unpack("vtype/Vsize", $filename_or_stream_or_binary);
if ($bfh["type"] == 0x4d42 && ($bfh["size"] == 0 || $bfh["size"] == strlen($filename_or_stream_or_binary))) {
return self::loadFromString($filename_or_stream_or_binary);
}
}
return self::loadFromFile($filename_or_stream_or_binary);
}
$bmp = self::loadFromStream($fp);
public static function loadFromFile($filename)
{
$fp = fopen($filename, "rb");
if ($fp === false) {
return false;
}
fclose($fp);
return $bmp;
}
$bmp = self::loadFromStream($fp);
public static function loadFromString($str){
//data scheme より古いバージョンから対応しているようなので php://memory を使う
$fp = fopen("php://memory", "r+b");
if ($fp === false){
return false;
}
fclose($fp);
return $bmp;
}
if (fwrite($fp, $str) != strlen($str)){
fclose($fp);
return false;
}
public static function loadFromString($str)
{
//data scheme より古いバージョンから対応しているようなので php://memory を使う
$fp = fopen("php://memory", "r+b");
if ($fp === false) {
return false;
}
if (fseek($fp, 0) === -1){
fclose($fp);
return false;
}
if (fwrite($fp, $str) != strlen($str)) {
fclose($fp);
return false;
}
$bmp = self::loadFromStream($fp);
if (fseek($fp, 0) === -1) {
fclose($fp);
return false;
}
fclose($fp);
return $bmp;
}
$bmp = self::loadFromStream($fp);
public static function loadFromStream($stream){
$buf = fread($stream, 14); //2+4+2+2+4
if ($buf === false){
return false;
}
fclose($fp);
return $bmp;
}
//シグネチャチェック
if ($buf[0] != 'B' || $buf[1] != 'M'){
return false;
}
public static function loadFromStream($stream)
{
$buf = fread($stream, 14); //2+4+2+2+4
if ($buf === false) {
return false;
}
$bitmap_file_header = unpack(
//BITMAPFILEHEADER構造体
"vtype/".
"Vsize/".
"vreserved1/".
"vreserved2/".
"Voffbits", $buf
);
//シグネチャチェック
if ($buf[0] != 'B' || $buf[1] != 'M') {
return false;
}
return self::loadFromStreamAndFileHeader($stream, $bitmap_file_header);
}
$bitmap_file_header = unpack(
//BITMAPFILEHEADER構造体
"vtype/" .
"Vsize/" .
"vreserved1/" .
"vreserved2/" .
"Voffbits", $buf
);
public static function loadFromStreamAndFileHeader($stream, array $bitmap_file_header){
if ($bitmap_file_header["type"] != 0x4d42){
return false;
}
return self::loadFromStreamAndFileHeader($stream, $bitmap_file_header);
}
//情報ヘッダサイズを元に形式を区別して読み込み
$buf = fread($stream, 4);
if ($buf === false){
return false;
}
list(,$header_size) = unpack("V", $buf);
public static function loadFromStreamAndFileHeader($stream, array $bitmap_file_header)
{
if ($bitmap_file_header["type"] != 0x4d42) {
return false;
}
//情報ヘッダサイズを元に形式を区別して読み込み
$buf = fread($stream, 4);
if ($buf === false) {
return false;
}
list(, $header_size) = unpack("V", $buf);
if ($header_size == 12){
$buf = fread($stream, $header_size - 4);
if ($buf === false){
return false;
}
if ($header_size == 12) {
$buf = fread($stream, $header_size - 4);
if ($buf === false) {
return false;
}
extract(unpack(
//BITMAPCOREHEADER構造体 - OS/2 Bitmap
"vwidth/".
"vheight/".
"vplanes/".
"vbit_count", $buf
));
//飛んでこない分は 0 で初期化しておく
$clr_used = $clr_important = $alpha_mask = $compression = 0;
extract(unpack(
//BITMAPCOREHEADER構造体 - OS/2 Bitmap
"vwidth/" .
"vheight/" .
"vplanes/" .
"vbit_count", $buf
));
//飛んでこない分は 0 で初期化しておく
$clr_used = $clr_important = $alpha_mask = $compression = 0;
//マスク類は初期化されないのでここで割り当てておく
$red_mask = 0x00ff0000;
$green_mask = 0x0000ff00;
$blue_mask = 0x000000ff;
} else if (124 < $header_size || $header_size < 40) {
//未知の形式
return false;
} else {
//この時点で36バイト読めることまではわかっている
$buf = fread($stream, 36); //既に読んだ部分は除外しつつBITMAPINFOHEADERのサイズだけ読む
if ($buf === false){
return false;
}
//マスク類は初期化されないのでここで割り当てておく
$red_mask = 0x00ff0000;
$green_mask = 0x0000ff00;
$blue_mask = 0x000000ff;
} else if (124 < $header_size || $header_size < 40) {
//未知の形式
return false;
} else {
//この時点で36バイト読めることまではわかっている
$buf = fread($stream, 36); //既に読んだ部分は除外しつつBITMAPINFOHEADERのサイズだけ読む
if ($buf === false) {
return false;
}
//BITMAPINFOHEADER構造体 - Windows Bitmap
extract(unpack(
"Vwidth/".
"Vheight/".
"vplanes/".
"vbit_count/".
"Vcompression/".
"Vsize_image/".
"Vx_pels_per_meter/".
"Vy_pels_per_meter/".
"Vclr_used/".
"Vclr_important", $buf
));
//負の整数を受け取る可能性があるものは自前で変換する
if ($width & 0x80000000){ $width = -(~$width & 0xffffffff) - 1; }
if ($height & 0x80000000){ $height = -(~$height & 0xffffffff) - 1; }
if ($x_pels_per_meter & 0x80000000){ $x_pels_per_meter = -(~$x_pels_per_meter & 0xffffffff) - 1; }
if ($y_pels_per_meter & 0x80000000){ $y_pels_per_meter = -(~$y_pels_per_meter & 0xffffffff) - 1; }
//BITMAPINFOHEADER構造体 - Windows Bitmap
extract(unpack(
"Vwidth/" .
"Vheight/" .
"vplanes/" .
"vbit_count/" .
"Vcompression/" .
"Vsize_image/" .
"Vx_pels_per_meter/" .
"Vy_pels_per_meter/" .
"Vclr_used/" .
"Vclr_important", $buf
));
//負の整数を受け取る可能性があるものは自前で変換する
if ($width & 0x80000000) {
$width = -(~$width & 0xffffffff) - 1;
}
if ($height & 0x80000000) {
$height = -(~$height & 0xffffffff) - 1;
}
if ($x_pels_per_meter & 0x80000000) {
$x_pels_per_meter = -(~$x_pels_per_meter & 0xffffffff) - 1;
}
if ($y_pels_per_meter & 0x80000000) {
$y_pels_per_meter = -(~$y_pels_per_meter & 0xffffffff) - 1;
}
//ファイルによっては BITMAPINFOHEADER のサイズがおかしい(書き込み間違い?)ケースがある
//自分でファイルサイズを元に逆算することで回避できることもあるので再計算できそうなら正当性を調べる
//シークできないストリームの場合全体のファイルサイズは取得できないので、$bitmap_file_headerにサイズ申告がなければやらない
if ($bitmap_file_header["size"] != 0){
$colorsize = $bit_count == 1 || $bit_count == 4 || $bit_count == 8 ? ($clr_used ? $clr_used : pow(2, $bit_count))<<2 : 0;
$bodysize = $size_image ? $size_image : ((($width * $bit_count + 31) >> 3) & ~3) * abs($height);
$calcsize = $bitmap_file_header["size"] - $bodysize - $colorsize - 14;
//ファイルによっては BITMAPINFOHEADER のサイズがおかしい(書き込み間違い?)ケースがある
//自分でファイルサイズを元に逆算することで回避できることもあるので再計算できそうなら正当性を調べる
//シークできないストリームの場合全体のファイルサイズは取得できないので、$bitmap_file_headerにサイズ申告がなければやらない
if ($bitmap_file_header["size"] != 0) {
$colorsize = $bit_count == 1 || $bit_count == 4 || $bit_count == 8 ? ($clr_used ? $clr_used : pow(2, $bit_count)) << 2 : 0;
$bodysize = $size_image ? $size_image : ((($width * $bit_count + 31) >> 3) & ~3) * abs($height);
$calcsize = $bitmap_file_header["size"] - $bodysize - $colorsize - 14;
//本来であれば一致するはずなのに合わない時は、値がおかしくなさそうなら(BITMAPV5HEADERの範囲内なら)計算して求めた値を採用する
if ($header_size < $calcsize && 40 <= $header_size && $header_size <= 124){
$header_size = $calcsize;
}
}
//本来であれば一致するはずなのに合わない時は、値がおかしくなさそうなら(BITMAPV5HEADERの範囲内なら)計算して求めた値を採用する
if ($header_size < $calcsize && 40 <= $header_size && $header_size <= 124) {
$header_size = $calcsize;
}
}
//BITMAPV4HEADER や BITMAPV5HEADER の場合まだ読むべきデータが残っている可能性がある
if ($header_size - 40 > 0){
$buf = fread($stream, $header_size - 40);
if ($buf === false){
return false;
}
//BITMAPV4HEADER や BITMAPV5HEADER の場合まだ読むべきデータが残っている可能性がある
if ($header_size - 40 > 0) {
$buf = fread($stream, $header_size - 40);
if ($buf === false) {
return false;
}
extract(unpack(
//BITMAPV4HEADER構造体(Windows95以降)
//BITMAPV5HEADER構造体(Windows98/2000以降)
"Vred_mask/".
"Vgreen_mask/".
"Vblue_mask/".
"Valpha_mask", $buf . str_repeat("\x00", 120)
));
} else {
$alpha_mask = $red_mask = $green_mask = $blue_mask = 0;
}
extract(unpack(
//BITMAPV4HEADER構造体(Windows95以降)
//BITMAPV5HEADER構造体(Windows98/2000以降)
"Vred_mask/" .
"Vgreen_mask/" .
"Vblue_mask/" .
"Valpha_mask", $buf . str_repeat("\x00", 120)
));
} else {
$alpha_mask = $red_mask = $green_mask = $blue_mask = 0;
}
//パレットがないがカラーマスクもない時
if (
($bit_count == 16 || $bit_count == 24 || $bit_count == 32)&&
$compression == 0 &&
$red_mask == 0 && $green_mask == 0 && $blue_mask == 0
){
//もしカラーマスクを所持していない場合は
//規定のカラーマスクを適用する
switch($bit_count){
case 16:
$red_mask = 0x7c00;
$green_mask = 0x03e0;
$blue_mask = 0x001f;
break;
case 24:
case 32:
$red_mask = 0x00ff0000;
$green_mask = 0x0000ff00;
$blue_mask = 0x000000ff;
break;
}
}
}
//パレットがないがカラーマスクもない時
if (
($bit_count == 16 || $bit_count == 24 || $bit_count == 32) &&
$compression == 0 &&
$red_mask == 0 && $green_mask == 0 && $blue_mask == 0
) {
//もしカラーマスクを所持していない場合は
//規定のカラーマスクを適用する
switch ($bit_count) {
case 16:
$red_mask = 0x7c00;
$green_mask = 0x03e0;
$blue_mask = 0x001f;
break;
case 24:
case 32:
$red_mask = 0x00ff0000;
$green_mask = 0x0000ff00;
$blue_mask = 0x000000ff;
break;
}
}
}
if (
($width == 0)||
($height == 0)||
($planes != 1)||
(($alpha_mask & $red_mask ) != 0)||
(($alpha_mask & $green_mask) != 0)||
(($alpha_mask & $blue_mask ) != 0)||
(($red_mask & $green_mask) != 0)||
(($red_mask & $blue_mask ) != 0)||
(($green_mask & $blue_mask ) != 0)
){
//不正な画像
return false;
}
if (
($width == 0) ||
($height == 0) ||
($planes != 1) ||
(($alpha_mask & $red_mask) != 0) ||
(($alpha_mask & $green_mask) != 0) ||
(($alpha_mask & $blue_mask) != 0) ||
(($red_mask & $green_mask) != 0) ||
(($red_mask & $blue_mask) != 0) ||
(($green_mask & $blue_mask) != 0)
) {
//不正な画像
return false;
}
//BI_JPEG と BI_PNG の場合は jpeg/png がそのまま入ってるだけなのでそのまま取り出してデコードする
if ($compression == 4 || $compression == 5){
$buf = stream_get_contents($stream, $size_image);
if ($buf === false){
return false;
}
return imagecreatefromstring($buf);
}
//BI_JPEG と BI_PNG の場合は jpeg/png がそのまま入ってるだけなのでそのまま取り出してデコードする
if ($compression == 4 || $compression == 5) {
$buf = stream_get_contents($stream, $size_image);
if ($buf === false) {
return false;
}
return imagecreatefromstring($buf);
}
//画像本体の読み出し
//1行のバイト数
$line_bytes = (($width * $bit_count + 31) >> 3) & ~3;
//全体の行数
$lines = abs($height);
//y軸進行量(ボトムアップかトップダウンか)
$y = $height > 0 ? $lines-1 : 0;
$line_step = $height > 0 ? -1 : 1;
//画像本体の読み出し
//1行のバイト数
$line_bytes = (($width * $bit_count + 31) >> 3) & ~3;
//全体の行数
$lines = abs($height);
//y軸進行量(ボトムアップかトップダウンか)
$y = $height > 0 ? $lines - 1 : 0;
$line_step = $height > 0 ? -1 : 1;
//256色以下の画像か?
if ($bit_count == 1 || $bit_count == 4 || $bit_count == 8){
$img = imagecreate($width, $lines);
//256色以下の画像か?
if ($bit_count == 1 || $bit_count == 4 || $bit_count == 8) {
$img = imagecreate($width, $lines);
//画像データの前にパレットデータがあるのでパレットを作成する
$palette_size = $header_size == 12 ? 3 : 4; //OS/2形式の場合は x に相当する箇所のデータは最初から確保されていない
$colors = $clr_used ? $clr_used : pow(2, $bit_count); //色数
$palette = array();
for($i = 0; $i < $colors; ++$i){
$buf = fread($stream, $palette_size);
if ($buf === false){
imagedestroy($img);
return false;
}
extract(unpack("Cb/Cg/Cr/Cx", $buf . "\x00"));
$palette[] = imagecolorallocate($img, $r, $g, $b);
}
//画像データの前にパレットデータがあるのでパレットを作成する
$palette_size = $header_size == 12 ? 3 : 4; //OS/2形式の場合は x に相当する箇所のデータは最初から確保されていない
$colors = $clr_used ? $clr_used : pow(2, $bit_count); //色数
$palette = array();
for ($i = 0; $i < $colors; ++$i) {
$buf = fread($stream, $palette_size);
if ($buf === false) {
imagedestroy($img);
return false;
}
extract(unpack("Cb/Cg/Cr/Cx", $buf . "\x00"));
$palette[] = imagecolorallocate($img, $r, $g, $b);
}
$shift_base = 8 - $bit_count;
$mask = ((1 << $bit_count) - 1) << $shift_base;
$shift_base = 8 - $bit_count;
$mask = ((1 << $bit_count) - 1) << $shift_base;
//圧縮されている場合とされていない場合でデコード処理が大きく変わる
if ($compression == 1 || $compression == 2){
$x = 0;
$qrt_mod2 = $bit_count >> 2 & 1;
for(;;){
//もし描写先が範囲外になっている場合デコード処理がおかしくなっているので抜ける
//変なデータが渡されたとしても最悪なケースで255回程度の無駄なので目を瞑る
if ($x < -1 || $x > $width || $y < -1 || $y > $height){
imagedestroy($img);
return false;
}
$buf = fread($stream, 1);
if ($buf === false){
imagedestroy($img);
return false;
}
switch($buf){
case "\x00":
$buf = fread($stream, 1);
if ($buf === false){
imagedestroy($img);
return false;
}
switch($buf){
case "\x00": //EOL
$y += $line_step;
$x = 0;
break;
case "\x01": //EOB
$y = 0;
$x = 0;
break 3;
case "\x02": //MOV
$buf = fread($stream, 2);
if ($buf === false){
imagedestroy($img);
return false;
}
list(,$xx, $yy) = unpack("C2", $buf);
$x += $xx;
$y += $yy * $line_step;
break;
default: //ABS
list(,$pixels) = unpack("C", $buf);
$bytes = ($pixels >> $qrt_mod2) + ($pixels & $qrt_mod2);
$buf = fread($stream, ($bytes + 1) & ~1);
if ($buf === false){
imagedestroy($img);
return false;
}
for ($i = 0, $pos = 0; $i < $pixels; ++$i, ++$x, $pos += $bit_count){
list(,$c) = unpack("C", $buf[$pos >> 3]);
$b = $pos & 0x07;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
break;
}
break;
default:
$buf2 = fread($stream, 1);
if ($buf2 === false){
imagedestroy($img);
return false;
}
list(,$size, $c) = unpack("C2", $buf . $buf2);
for($i = 0, $pos = 0; $i < $size; ++$i, ++$x, $pos += $bit_count){
$b = $pos & 0x07;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
break;
}
}
} else {
for ($line = 0; $line < $lines; ++$line, $y += $line_step){
$buf = fread($stream, $line_bytes);
if ($buf === false){
imagedestroy($img);
return false;
}
//圧縮されている場合とされていない場合でデコード処理が大きく変わる
if ($compression == 1 || $compression == 2) {
$x = 0;
$qrt_mod2 = $bit_count >> 2 & 1;
for (; ;) {
//もし描写先が範囲外になっている場合デコード処理がおかしくなっているので抜ける
//変なデータが渡されたとしても最悪なケースで255回程度の無駄なので目を瞑る
if ($x < -1 || $x > $width || $y < -1 || $y > $height) {
imagedestroy($img);
return false;
}
$buf = fread($stream, 1);
if ($buf === false) {
imagedestroy($img);
return false;
}
switch ($buf) {
case "\x00":
$buf = fread($stream, 1);
if ($buf === false) {
imagedestroy($img);
return false;
}
switch ($buf) {
case "\x00": //EOL
$y += $line_step;
$x = 0;
break;
case "\x01": //EOB
$y = 0;
$x = 0;
break 3;
case "\x02": //MOV
$buf = fread($stream, 2);
if ($buf === false) {
imagedestroy($img);
return false;
}
list(, $xx, $yy) = unpack("C2", $buf);
$x += $xx;
$y += $yy * $line_step;
break;
default: //ABS
list(, $pixels) = unpack("C", $buf);
$bytes = ($pixels >> $qrt_mod2) + ($pixels & $qrt_mod2);
$buf = fread($stream, ($bytes + 1) & ~1);
if ($buf === false) {
imagedestroy($img);
return false;
}
for ($i = 0, $pos = 0; $i < $pixels; ++$i, ++$x, $pos += $bit_count) {
list(, $c) = unpack("C", $buf[$pos >> 3]);
$b = $pos & 0x07;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
break;
}
break;
default:
$buf2 = fread($stream, 1);
if ($buf2 === false) {
imagedestroy($img);
return false;
}
list(, $size, $c) = unpack("C2", $buf . $buf2);
for ($i = 0, $pos = 0; $i < $size; ++$i, ++$x, $pos += $bit_count) {
$b = $pos & 0x07;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
break;
}
}
} else {
for ($line = 0; $line < $lines; ++$line, $y += $line_step) {
$buf = fread($stream, $line_bytes);
if ($buf === false) {
imagedestroy($img);
return false;
}
$pos = 0;
for ($x = 0; $x < $width; ++$x, $pos += $bit_count){
list(,$c) = unpack("C", $buf[$pos >> 3]);
$b = $pos & 0x7;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
}
}
} else {
$img = imagecreatetruecolor($width, $lines);
imagealphablending($img, false);
if ($alpha_mask)
{
//αデータがあるので透過情報も保存できるように
imagesavealpha($img, true);
}
$pos = 0;
for ($x = 0; $x < $width; ++$x, $pos += $bit_count) {
list(, $c) = unpack("C", $buf[$pos >> 3]);
$b = $pos & 0x7;
imagesetpixel($img, $x, $y, $palette[($c & ($mask >> $b)) >> ($shift_base - $b)]);
}
}
}
} else {
$img = imagecreatetruecolor($width, $lines);
imagealphablending($img, false);
if ($alpha_mask) {
//αデータがあるので透過情報も保存できるように
imagesavealpha($img, true);
}
//x軸進行量
$pixel_step = $bit_count >> 3;
$alpha_max = $alpha_mask ? 0x7f : 0x00;
$alpha_mask_r = $alpha_mask ? 1/$alpha_mask : 1;
$red_mask_r = $red_mask ? 1/$red_mask : 1;
$green_mask_r = $green_mask ? 1/$green_mask : 1;
$blue_mask_r = $blue_mask ? 1/$blue_mask : 1;
//x軸進行量
$pixel_step = $bit_count >> 3;
$alpha_max = $alpha_mask ? 0x7f : 0x00;
$alpha_mask_r = $alpha_mask ? 1 / $alpha_mask : 1;
$red_mask_r = $red_mask ? 1 / $red_mask : 1;
$green_mask_r = $green_mask ? 1 / $green_mask : 1;
$blue_mask_r = $blue_mask ? 1 / $blue_mask : 1;
for ($line = 0; $line < $lines; ++$line, $y += $line_step){
$buf = fread($stream, $line_bytes);
if ($buf === false){
imagedestroy($img);
return false;
}
for ($line = 0; $line < $lines; ++$line, $y += $line_step) {
$buf = fread($stream, $line_bytes);
if ($buf === false) {
imagedestroy($img);
return false;
}
$pos = 0;
for ($x = 0; $x < $width; ++$x, $pos += $pixel_step){
list(,$c) = unpack("V", substr($buf, $pos, $pixel_step). "\x00\x00");
$a_masked = $c & $alpha_mask;
$r_masked = $c & $red_mask;
$g_masked = $c & $green_mask;
$b_masked = $c & $blue_mask;
$a = $alpha_max - ((($a_masked<<7) - $a_masked) * $alpha_mask_r);
$r = (($r_masked<<8) - $r_masked) * $red_mask_r;
$g = (($g_masked<<8) - $g_masked) * $green_mask_r;
$b = (($b_masked<<8) - $b_masked) * $blue_mask_r;
imagesetpixel($img, $x, $y, ($a<<24)|($r<<16)|($g<<8)|$b);
}
}
imagealphablending($img, true); //デフォルト値に戻しておく
}
return $img;
}
$pos = 0;
for ($x = 0; $x < $width; ++$x, $pos += $pixel_step) {
list(, $c) = unpack("V", substr($buf, $pos, $pixel_step) . "\x00\x00");
$a_masked = $c & $alpha_mask;
$r_masked = $c & $red_mask;
$g_masked = $c & $green_mask;
$b_masked = $c & $blue_mask;
$a = $alpha_max - ((($a_masked << 7) - $a_masked) * $alpha_mask_r);
$r = (($r_masked << 8) - $r_masked) * $red_mask_r;
$g = (($g_masked << 8) - $g_masked) * $green_mask_r;
$b = (($b_masked << 8) - $b_masked) * $blue_mask_r;
imagesetpixel($img, $x, $y, ($a << 24) | ($r << 16) | ($g << 8) | $b);
}
}
imagealphablending($img, true); //デフォルト値に戻しておく
}
return $img;
}
}
+130 -127
View File
@@ -1,141 +1,144 @@
<?php
/**
* elFinder Plugin AutoResize
*
* Auto resize on file upload.
*
* ex. binding, configure on connector options
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.AutoResize.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'AutoResize' => array(
* 'enable' => true, // For control by volume driver
* 'maxWidth' => 1024, // Path to Water mark image
* 'maxHeight' => 1024, // Margin right pixel
* 'quality' => 95, // JPEG image save quality
* 'preserveExif' => false, // Preserve EXIF data (Imagick only)
* 'forceEffect' => false, // For change quality or make progressive JPEG of small images
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'AutoResize' => array(
* 'enable' => true, // For control by volume driver
* 'maxWidth' => 1024, // Path to Water mark image
* 'maxHeight' => 1024, // Margin right pixel
* 'quality' => 95, // JPEG image save quality
* 'preserveExif' => false, // Preserve EXIF data (Imagick only)
* 'forceEffect' => false, // For change quality or make progressive JPEG of small images
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.AutoResize.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'AutoResize' => array(
* 'enable' => true, // For control by volume driver
* 'maxWidth' => 1024, // Path to Water mark image
* 'maxHeight' => 1024, // Margin right pixel
* 'quality' => 95, // JPEG image save quality
* 'preserveExif' => false, // Preserve EXIF data (Imagick only)
* 'forceEffect' => false, // For change quality or make progressive JPEG of small images
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'AutoResize' => array(
* 'enable' => true, // For control by volume driver
* 'maxWidth' => 1024, // Path to Water mark image
* 'maxHeight' => 1024, // Margin right pixel
* 'quality' => 95, // JPEG image save quality
* 'preserveExif' => false, // Preserve EXIF data (Imagick only)
* 'forceEffect' => false, // For change quality or make progressive JPEG of small images
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPluginAutoResize extends elFinderPlugin {
class elFinderPluginAutoResize extends elFinderPlugin
{
public function __construct($opts) {
$defaults = array(
'enable' => true, // For control by volume driver
'maxWidth' => 1024, // Path to Water mark image
'maxHeight' => 1024, // Margin right pixel
'quality' => 95, // JPEG image save quality
'preserveExif' => false, // Preserve EXIF data (Imagick only)
'forceEffect' => false, // For change quality or make progressive JPEG of small images
'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
public function __construct($opts)
{
$defaults = array(
'enable' => true, // For control by volume driver
'maxWidth' => 1024, // Path to Water mark image
'maxHeight' => 1024, // Margin right pixel
'quality' => 95, // JPEG image save quality
'preserveExif' => false, // Preserve EXIF data (Imagick only)
'forceEffect' => false, // For change quality or make progressive JPEG of small images
'targetType' => IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP, // Target image formats ( bit-field )
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
$this->opts = array_merge($defaults, $opts);
$this->opts = array_merge($defaults, $opts);
}
}
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $this->iaEnabled($opts, $elfinder)) {
return false;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
// check target image type
$imgTypes = array(
IMAGETYPE_GIF => IMG_GIF,
IMAGETYPE_JPEG => IMG_JPEG,
IMAGETYPE_PNG => IMG_PNG,
IMAGETYPE_BMP => IMG_WBMP,
IMAGETYPE_WBMP => IMG_WBMP
);
if (! isset($imgTypes[$imageType]) || ! ($opts['targetType'] & $imgTypes[$imageType])) {
return false;
}
if (! $srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
if ($opts['forceEffect'] || $srcImgInfo[0] > $opts['maxWidth'] || $srcImgInfo[1] > $opts['maxHeight']) {
return $this->resize($volume, $src, $srcImgInfo, $opts['maxWidth'], $opts['maxHeight'], $opts['quality'], $opts['preserveExif']);
}
return false;
}
private function resize($volume, $src, $srcImgInfo, $maxWidth, $maxHeight, $jpgQuality, $preserveExif) {
$zoom = min(($maxWidth/$srcImgInfo[0]),($maxHeight/$srcImgInfo[1]));
$width = round($srcImgInfo[0] * $zoom);
$height = round($srcImgInfo[1] * $zoom);
$unenlarge = true;
$checkAnimated = true;
return $volume->imageUtil('resize', $src, compact('width', 'height', 'jpgQuality', 'preserveExif', 'unenlarge', 'checkAnimated'));
}
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$this->iaEnabled($opts, $elfinder)) {
return false;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
// check target image type
$imgTypes = array(
IMAGETYPE_GIF => IMG_GIF,
IMAGETYPE_JPEG => IMG_JPEG,
IMAGETYPE_PNG => IMG_PNG,
IMAGETYPE_BMP => IMG_WBMP,
IMAGETYPE_WBMP => IMG_WBMP
);
if (!isset($imgTypes[$imageType]) || !($opts['targetType'] & $imgTypes[$imageType])) {
return false;
}
if (!$srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
if ($opts['forceEffect'] || $srcImgInfo[0] > $opts['maxWidth'] || $srcImgInfo[1] > $opts['maxHeight']) {
return $this->resize($volume, $src, $srcImgInfo, $opts['maxWidth'], $opts['maxHeight'], $opts['quality'], $opts['preserveExif']);
}
return false;
}
private function resize($volume, $src, $srcImgInfo, $maxWidth, $maxHeight, $jpgQuality, $preserveExif)
{
$zoom = min(($maxWidth / $srcImgInfo[0]), ($maxHeight / $srcImgInfo[1]));
$width = round($srcImgInfo[0] * $zoom);
$height = round($srcImgInfo[1] * $zoom);
$unenlarge = true;
$checkAnimated = true;
return $volume->imageUtil('resize', $src, compact('width', 'height', 'jpgQuality', 'preserveExif', 'unenlarge', 'checkAnimated'));
}
}
+121 -118
View File
@@ -1,132 +1,135 @@
<?php
/**
* elFinder Plugin AutoRotate
*
* Auto rotation on file upload of JPEG file by EXIF Orientation.
*
* ex. binding, configure on connector options
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.AutoRotate.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'AutoRotate' => array(
* 'enable' => true, // For control by volume driver
* 'quality' => 95, // JPEG image save quality
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'AutoRotate' => array(
* 'enable' => true, // For control by volume driver
* 'quality' => 95, // JPEG image save quality
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.AutoRotate.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'AutoRotate' => array(
* 'enable' => true, // For control by volume driver
* 'quality' => 95, // JPEG image save quality
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'AutoRotate' => array(
* 'enable' => true, // For control by volume driver
* 'quality' => 95, // JPEG image save quality
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPluginAutoRotate extends elFinderPlugin {
class elFinderPluginAutoRotate extends elFinderPlugin
{
public function __construct($opts) {
$defaults = array(
'enable' => true, // For control by volume driver
'quality' => 95, // JPEG image save quality
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
public function __construct($opts)
{
$defaults = array(
'enable' => true, // For control by volume driver
'quality' => 95, // JPEG image save quality
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
$this->opts = array_merge($defaults, $opts);
$this->opts = array_merge($defaults, $opts);
}
}
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $this->iaEnabled($opts, $elfinder)) {
return false;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
// check target image type
if ($imageType !== IMAGETYPE_JPEG) {
return false;
}
if (! $srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
return $this->rotate($volume, $src, $srcImgInfo, $opts['quality']);
}
private function rotate($volume, $src, $srcImgInfo, $quality) {
if (! function_exists('exif_read_data')) {
return false;
}
$degree = 0;
$exif = exif_read_data($src);
if($exif && !empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$degree = 270;
break;
case 3:
$degree = 180;
break;
case 6:
$degree = 90;
break;
}
}
$opts = array(
'degree' => $degree,
'jpgQuality' => $quality,
'checkAnimated' => true
);
return $volume->imageUtil('rotate', $src, $opts);
}
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$this->iaEnabled($opts, $elfinder)) {
return false;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
// check target image type
if ($imageType !== IMAGETYPE_JPEG) {
return false;
}
if (!$srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
return $this->rotate($volume, $src, $srcImgInfo, $opts['quality']);
}
private function rotate($volume, $src, $srcImgInfo, $quality)
{
if (!function_exists('exif_read_data')) {
return false;
}
$degree = 0;
$exif = exif_read_data($src);
if ($exif && !empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 8:
$degree = 270;
break;
case 3:
$degree = 180;
break;
case 6:
$degree = 90;
break;
}
}
$opts = array(
'degree' => $degree,
'jpgQuality' => $quality,
'checkAnimated' => true
);
return $volume->imageUtil('rotate', $src, $opts);
}
}
+184 -181
View File
@@ -1,197 +1,200 @@
<?php
/**
* elFinder Plugin Normalizer
*
* UTF-8 Normalizer of file-name and file-path etc.
* nfc(NFC): Canonical Decomposition followed by Canonical Composition
* nfkc(NFKC): Compatibility Decomposition followed by Canonical
*
* This plugin require Class "Normalizer" (PHP 5 >= 5.3.0, PECL intl >= 1.0.0)
* or PEAR package "I18N_UnicodeNormalizer"
*
* ex. binding, configure on connector options
* $opts = array(
* 'bind' => array(
* 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(
* 'Plugin.Normalizer.cmdPreprocess'
* ),
* 'upload.presave' => array(
* 'Plugin.Normalizer.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Normalizer' => array(
* 'enable' => true,
* 'nfc' => true,
* 'nfkc' => true,
* 'umlauts' => false,
* 'lowercase' => false,
* 'convmap' => array()
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Normalizer' => array(
* 'enable' => true,
* 'nfc' => true,
* 'nfkc' => true,
* 'umlauts' => false,
* 'lowercase' => false,
* 'convmap' => array()
* )
* )
* )
* )
* );
* $opts = array(
* 'bind' => array(
* 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(
* 'Plugin.Normalizer.cmdPreprocess'
* ),
* 'upload.presave' => array(
* 'Plugin.Normalizer.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Normalizer' => array(
* 'enable' => true,
* 'nfc' => true,
* 'nfkc' => true,
* 'umlauts' => false,
* 'lowercase' => false,
* 'convmap' => array()
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Normalizer' => array(
* 'enable' => true,
* 'nfc' => true,
* 'nfkc' => true,
* 'umlauts' => false,
* 'lowercase' => false,
* 'convmap' => array()
* )
* )
* )
* )
* );
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPluginNormalizer extends elFinderPlugin
{
private $replaced = array();
private $keyMap = array(
'ls' => 'intersect',
'upload' => 'renames',
'mkdir' => array('name', 'dirs')
);
public function __construct($opts) {
$defaults = array(
'enable' => true, // For control by volume driver
'nfc' => true, // Canonical Decomposition followed by Canonical Composition
'nfkc' => true, // Compatibility Decomposition followed by Canonical
'umlauts' => false, // Convert umlauts with their closest 7 bit ascii equivalent
'lowercase' => false, // Make chars lowercase
'convmap' => array()// Convert map ('FROM' => 'TO') array
);
$this->opts = array_merge($defaults, $opts);
}
public function cmdPreprocess($cmd, &$args, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $opts['enable']) {
return false;
}
$this->replaced[$cmd] = array();
$key = (isset($this->keyMap[$cmd]))? $this->keyMap[$cmd] : 'name';
if (is_array($key)) {
$keys = $key;
} else {
$keys = array($key);
}
foreach($keys as $key) {
if (isset($args[$key])) {
if (is_array($args[$key])) {
foreach($args[$key] as $i => $name) {
if ($cmd === 'mkdir' && $key === 'dirs') {
// $name need '/' as prefix see #2607
$name = '/' . ltrim($name, '/');
$_names = explode('/', $name);
$_res = array();
foreach($_names as $_name) {
$_res[] = $this->normalize($_name, $opts);
}
$this->replaced[$cmd][$name] = $args[$key][$i] = join('/', $_res);
} else {
$this->replaced[$cmd][$name] = $args[$key][$i] = $this->normalize($name, $opts);
}
}
} else if ($args[$key] !== '') {
$name = $args[$key];
$this->replaced[$cmd][$name] = $args[$key] = $this->normalize($name, $opts);
}
}
}
if ($cmd === 'ls' || $cmd === 'mkdir') {
if (! empty($this->replaced[$cmd])) {
// un-regist for legacy settings
$elfinder->unbind($cmd, array($this, 'cmdPostprocess'));
$elfinder->bind($cmd, array($this, 'cmdPostprocess'));
}
}
return true;
}
public function cmdPostprocess($cmd, &$result, $args, $elfinder, $volume) {
if ($cmd === 'ls') {
if (! empty($result['list']) && ! empty($this->replaced['ls'])) {
foreach($result['list'] as $hash => $name) {
if ($keys = array_keys($this->replaced['ls'], $name)) {
if (count($keys) === 1) {
$result['list'][$hash] = $keys[0];
} else {
$result['list'][$hash] = $keys;
}
}
}
}
} else if ($cmd === 'mkdir') {
if (! empty($result['hashes']) && ! empty($this->replaced['mkdir'])) {
foreach($result['hashes'] as $name => $hash) {
if ($keys = array_keys($this->replaced['mkdir'], $name)) {
$result['hashes'][$keys[0]] = $hash;
}
}
}
}
}
// NOTE: $thash is directory hash so it unneed to process at here
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $opts['enable']) {
return false;
}
$name = $this->normalize($name, $opts);
return true;
}
protected function normalize($str, $opts) {
if ($opts['nfc'] || $opts['nfkc']) {
if (class_exists('Normalizer', false)) {
if ($opts['nfc'] && ! Normalizer::isNormalized($str, Normalizer::FORM_C))
$str = Normalizer::normalize($str, Normalizer::FORM_C);
if ($opts['nfkc'] && ! Normalizer::isNormalized($str, Normalizer::FORM_KC))
$str = Normalizer::normalize($str, Normalizer::FORM_KC);
} else {
if (! class_exists('I18N_UnicodeNormalizer', false)) {
include_once 'I18N/UnicodeNormalizer.php';
}
if (class_exists('I18N_UnicodeNormalizer', false)) {
$normalizer = new I18N_UnicodeNormalizer();
if ($opts['nfc'])
$str = $normalizer->normalize($str, 'NFC');
if ($opts['nfkc'])
$str = $normalizer->normalize($str, 'NFKC');
}
}
}
if ($opts['umlauts']) {
if (strpos($str = htmlentities($str, ENT_QUOTES, 'UTF-8'), '&') !== false) {
$str = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $str), ENT_QUOTES, 'utf-8');
}
}
if ($opts['convmap'] && is_array($opts['convmap'])) {
$str = strtr($str, $opts['convmap']);
}
if ($opts['lowercase']) {
if (function_exists('mb_strtolower')) {
$str = mb_strtolower($str, 'UTF-8');
} else {
$str = strtolower($str);
}
}
return $str;
}
private $replaced = array();
private $keyMap = array(
'ls' => 'intersect',
'upload' => 'renames',
'mkdir' => array('name', 'dirs')
);
public function __construct($opts)
{
$defaults = array(
'enable' => true, // For control by volume driver
'nfc' => true, // Canonical Decomposition followed by Canonical Composition
'nfkc' => true, // Compatibility Decomposition followed by Canonical
'umlauts' => false, // Convert umlauts with their closest 7 bit ascii equivalent
'lowercase' => false, // Make chars lowercase
'convmap' => array()// Convert map ('FROM' => 'TO') array
);
$this->opts = array_merge($defaults, $opts);
}
public function cmdPreprocess($cmd, &$args, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$opts['enable']) {
return false;
}
$this->replaced[$cmd] = array();
$key = (isset($this->keyMap[$cmd])) ? $this->keyMap[$cmd] : 'name';
if (is_array($key)) {
$keys = $key;
} else {
$keys = array($key);
}
foreach ($keys as $key) {
if (isset($args[$key])) {
if (is_array($args[$key])) {
foreach ($args[$key] as $i => $name) {
if ($cmd === 'mkdir' && $key === 'dirs') {
// $name need '/' as prefix see #2607
$name = '/' . ltrim($name, '/');
$_names = explode('/', $name);
$_res = array();
foreach ($_names as $_name) {
$_res[] = $this->normalize($_name, $opts);
}
$this->replaced[$cmd][$name] = $args[$key][$i] = join('/', $_res);
} else {
$this->replaced[$cmd][$name] = $args[$key][$i] = $this->normalize($name, $opts);
}
}
} else if ($args[$key] !== '') {
$name = $args[$key];
$this->replaced[$cmd][$name] = $args[$key] = $this->normalize($name, $opts);
}
}
}
if ($cmd === 'ls' || $cmd === 'mkdir') {
if (!empty($this->replaced[$cmd])) {
// un-regist for legacy settings
$elfinder->unbind($cmd, array($this, 'cmdPostprocess'));
$elfinder->bind($cmd, array($this, 'cmdPostprocess'));
}
}
return true;
}
public function cmdPostprocess($cmd, &$result, $args, $elfinder, $volume)
{
if ($cmd === 'ls') {
if (!empty($result['list']) && !empty($this->replaced['ls'])) {
foreach ($result['list'] as $hash => $name) {
if ($keys = array_keys($this->replaced['ls'], $name)) {
if (count($keys) === 1) {
$result['list'][$hash] = $keys[0];
} else {
$result['list'][$hash] = $keys;
}
}
}
}
} else if ($cmd === 'mkdir') {
if (!empty($result['hashes']) && !empty($this->replaced['mkdir'])) {
foreach ($result['hashes'] as $name => $hash) {
if ($keys = array_keys($this->replaced['mkdir'], $name)) {
$result['hashes'][$keys[0]] = $hash;
}
}
}
}
}
// NOTE: $thash is directory hash so it unneed to process at here
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$opts['enable']) {
return false;
}
$name = $this->normalize($name, $opts);
return true;
}
protected function normalize($str, $opts)
{
if ($opts['nfc'] || $opts['nfkc']) {
if (class_exists('Normalizer', false)) {
if ($opts['nfc'] && !Normalizer::isNormalized($str, Normalizer::FORM_C))
$str = Normalizer::normalize($str, Normalizer::FORM_C);
if ($opts['nfkc'] && !Normalizer::isNormalized($str, Normalizer::FORM_KC))
$str = Normalizer::normalize($str, Normalizer::FORM_KC);
} else {
if (!class_exists('I18N_UnicodeNormalizer', false)) {
include_once 'I18N/UnicodeNormalizer.php';
}
if (class_exists('I18N_UnicodeNormalizer', false)) {
$normalizer = new I18N_UnicodeNormalizer();
if ($opts['nfc'])
$str = $normalizer->normalize($str, 'NFC');
if ($opts['nfkc'])
$str = $normalizer->normalize($str, 'NFKC');
}
}
}
if ($opts['umlauts']) {
if (strpos($str = htmlentities($str, ENT_QUOTES, 'UTF-8'), '&') !== false) {
$str = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $str), ENT_QUOTES, 'utf-8');
}
}
if ($opts['convmap'] && is_array($opts['convmap'])) {
$str = strtr($str, $opts['convmap']);
}
if ($opts['lowercase']) {
if (function_exists('mb_strtolower')) {
$str = mb_strtolower($str, 'UTF-8');
} else {
$str = strtolower($str);
}
}
return $str;
}
}
+144 -140
View File
@@ -1,153 +1,157 @@
<?php
/**
* elFinder Plugin Sanitizer
*
* Sanitizer of file-name and file-path etc.
*
* ex. binding, configure on connector options
* $opts = array(
* 'bind' => array(
* 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(
* 'Plugin.Sanitizer.cmdPreprocess'
* ),
* 'upload.presave' => array(
* 'Plugin.Sanitizer.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Sanitizer' => array(
* 'enable' => true,
* 'targets' => array('\\','/',':','*','?','"','<','>','|'), // target chars
* 'replace' => '_', // replace to this
* 'callBack' => null // Or @callable sanitize function
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Sanitizer' => array(
* 'enable' => true,
* 'targets' => array('\\','/',':','*','?','"','<','>','|'), // target chars
* 'replace' => '_', // replace to this
* 'callBack' => null // Or @callable sanitize function
* )
* )
* )
* )
* );
* $opts = array(
* 'bind' => array(
* 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(
* 'Plugin.Sanitizer.cmdPreprocess'
* ),
* 'upload.presave' => array(
* 'Plugin.Sanitizer.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Sanitizer' => array(
* 'enable' => true,
* 'targets' => array('\\','/',':','*','?','"','<','>','|'), // target chars
* 'replace' => '_', // replace to this
* 'callBack' => null // Or @callable sanitize function
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Sanitizer' => array(
* 'enable' => true,
* 'targets' => array('\\','/',':','*','?','"','<','>','|'), // target chars
* 'replace' => '_', // replace to this
* 'callBack' => null // Or @callable sanitize function
* )
* )
* )
* )
* );
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPluginSanitizer extends elFinderPlugin
{
private $replaced = array();
private $keyMap = array(
'ls' => 'intersect',
'upload' => 'renames',
'mkdir' => array('name', 'dirs')
);
private $replaced = array();
private $keyMap = array(
'ls' => 'intersect',
'upload' => 'renames',
'mkdir' => array('name', 'dirs')
);
public function __construct($opts) {
$defaults = array(
'enable' => true, // For control by volume driver
'targets' => array('\\','/',':','*','?','"','<','>','|'), // target chars
'replace' => '_', // replace to this
'callBack' => null // Or callable sanitize function
);
$this->opts = array_merge($defaults, $opts);
}
public function cmdPreprocess($cmd, &$args, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $opts['enable']) {
return false;
}
$this->replaced[$cmd] = array();
$key = (isset($this->keyMap[$cmd]))? $this->keyMap[$cmd] : 'name';
if (is_array($key)) {
$keys = $key;
} else {
$keys = array($key);
}
foreach($keys as $key) {
if (isset($args[$key])) {
if (is_array($args[$key])) {
foreach($args[$key] as $i => $name) {
if ($cmd === 'mkdir' && $key === 'dirs') {
// $name need '/' as prefix see #2607
$name = '/' . ltrim($name, '/');
$_names = explode('/', $name);
$_res = array();
foreach($_names as $_name) {
$_res[] = $this->sanitizeFileName($_name, $opts);
}
$this->replaced[$cmd][$name] = $args[$key][$i] = join('/', $_res);
} else {
$this->replaced[$cmd][$name] = $args[$key][$i] = $this->sanitizeFileName($name, $opts);
}
}
} else if ($args[$key] !== '') {
$name = $args[$key];
$this->replaced[$cmd][$name] = $args[$key] = $this->sanitizeFileName($name, $opts);
}
}
}
if ($cmd === 'ls' || $cmd === 'mkdir') {
if (! empty($this->replaced[$cmd])) {
// un-regist for legacy settings
$elfinder->unbind($cmd, array($this, 'cmdPostprocess'));
$elfinder->bind($cmd, array($this, 'cmdPostprocess'));
}
}
return true;
}
public function cmdPostprocess($cmd, &$result, $args, $elfinder, $volume) {
if ($cmd === 'ls') {
if (! empty($result['list']) && ! empty($this->replaced['ls'])) {
foreach($result['list'] as $hash => $name) {
if ($keys = array_keys($this->replaced['ls'], $name)) {
if (count($keys) === 1) {
$result['list'][$hash] = $keys[0];
} else {
$result['list'][$hash] = $keys;
}
}
}
}
} else if ($cmd === 'mkdir') {
if (! empty($result['hashes']) && ! empty($this->replaced['mkdir'])) {
foreach($result['hashes'] as $name => $hash) {
if ($keys = array_keys($this->replaced['mkdir'], $name)) {
$result['hashes'][$keys[0]] = $hash;
}
}
}
}
}
// NOTE: $thash is directory hash so it unneed to process at here
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $opts['enable']) {
return false;
}
$name = $this->sanitizeFileName($name, $opts);
return true;
}
protected function sanitizeFileName($filename, $opts) {
if(!empty($opts['callBack']) && is_callable($opts['callBack'])) {
return call_user_func_array($opts['callBack'], array($filename, $opts));
}
return str_replace($opts['targets'], $opts['replace'], $filename);
}
public function __construct($opts)
{
$defaults = array(
'enable' => true, // For control by volume driver
'targets' => array('\\', '/', ':', '*', '?', '"', '<', '>', '|'), // target chars
'replace' => '_', // replace to this
'callBack' => null // Or callable sanitize function
);
$this->opts = array_merge($defaults, $opts);
}
public function cmdPreprocess($cmd, &$args, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$opts['enable']) {
return false;
}
$this->replaced[$cmd] = array();
$key = (isset($this->keyMap[$cmd])) ? $this->keyMap[$cmd] : 'name';
if (is_array($key)) {
$keys = $key;
} else {
$keys = array($key);
}
foreach ($keys as $key) {
if (isset($args[$key])) {
if (is_array($args[$key])) {
foreach ($args[$key] as $i => $name) {
if ($cmd === 'mkdir' && $key === 'dirs') {
// $name need '/' as prefix see #2607
$name = '/' . ltrim($name, '/');
$_names = explode('/', $name);
$_res = array();
foreach ($_names as $_name) {
$_res[] = $this->sanitizeFileName($_name, $opts);
}
$this->replaced[$cmd][$name] = $args[$key][$i] = join('/', $_res);
} else {
$this->replaced[$cmd][$name] = $args[$key][$i] = $this->sanitizeFileName($name, $opts);
}
}
} else if ($args[$key] !== '') {
$name = $args[$key];
$this->replaced[$cmd][$name] = $args[$key] = $this->sanitizeFileName($name, $opts);
}
}
}
if ($cmd === 'ls' || $cmd === 'mkdir') {
if (!empty($this->replaced[$cmd])) {
// un-regist for legacy settings
$elfinder->unbind($cmd, array($this, 'cmdPostprocess'));
$elfinder->bind($cmd, array($this, 'cmdPostprocess'));
}
}
return true;
}
public function cmdPostprocess($cmd, &$result, $args, $elfinder, $volume)
{
if ($cmd === 'ls') {
if (!empty($result['list']) && !empty($this->replaced['ls'])) {
foreach ($result['list'] as $hash => $name) {
if ($keys = array_keys($this->replaced['ls'], $name)) {
if (count($keys) === 1) {
$result['list'][$hash] = $keys[0];
} else {
$result['list'][$hash] = $keys;
}
}
}
}
} else if ($cmd === 'mkdir') {
if (!empty($result['hashes']) && !empty($this->replaced['mkdir'])) {
foreach ($result['hashes'] as $name => $hash) {
if ($keys = array_keys($this->replaced['mkdir'], $name)) {
$result['hashes'][$keys[0]] = $hash;
}
}
}
}
}
// NOTE: $thash is directory hash so it unneed to process at here
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
if (!$opts['enable']) {
return false;
}
$name = $this->sanitizeFileName($name, $opts);
return true;
}
protected function sanitizeFileName($filename, $opts)
{
if (!empty($opts['callBack']) && is_callable($opts['callBack'])) {
return call_user_func_array($opts['callBack'], array($filename, $opts));
}
return str_replace($opts['targets'], $opts['replace'], $filename);
}
}
+399 -395
View File
@@ -1,420 +1,424 @@
<?php
/**
* elFinder Plugin Watermark
*
* Print watermark on file upload.
*
* ex. binding, configure on connector options
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.Watermark.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Watermark' => array(
* 'enable' => true, // For control by volume driver
* 'source' => 'logo.png', // Path to Water mark image
* 'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
* 'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
* 'marginX' => 5, // Margin horizontal pixel
* 'marginY' => 5, // Margin vertical pixel
* 'quality' => 95, // JPEG image save quality
* 'transparency' => 70, // Water mark image transparency ( other than PNG )
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'targetMinPixel' => 200, // Target image minimum pixel size
* 'interlace' => IMG_GIF|IMG_JPG, // Set interlacebit image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Watermark' => array(
* 'enable' => true, // For control by volume driver
* 'source' => 'logo.png', // Path to Water mark image
* 'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
* 'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
* 'marginX' => 5, // Margin horizontal pixel
* 'marginY' => 5, // Margin vertical pixel
* 'quality' => 95, // JPEG image save quality
* 'transparency' => 70, // Water mark image transparency ( other than PNG )
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'targetMinPixel' => 200, // Target image minimum pixel size
* 'interlace' => IMG_GIF|IMG_JPG, // Set interlacebit image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
* $opts = array(
* 'bind' => array(
* 'upload.presave' => array(
* 'Plugin.Watermark.onUpLoadPreSave'
* )
* ),
* // global configure (optional)
* 'plugin' => array(
* 'Watermark' => array(
* 'enable' => true, // For control by volume driver
* 'source' => 'logo.png', // Path to Water mark image
* 'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
* 'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
* 'marginX' => 5, // Margin horizontal pixel
* 'marginY' => 5, // Margin vertical pixel
* 'quality' => 95, // JPEG image save quality
* 'transparency' => 70, // Water mark image transparency ( other than PNG )
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'targetMinPixel' => 200, // Target image minimum pixel size
* 'interlace' => IMG_GIF|IMG_JPG, // Set interlacebit image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* ),
* // each volume configure (optional)
* 'roots' => array(
* array(
* 'driver' => 'LocalFileSystem',
* 'path' => '/path/to/files/',
* 'URL' => 'http://localhost/to/files/'
* 'plugin' => array(
* 'Watermark' => array(
* 'enable' => true, // For control by volume driver
* 'source' => 'logo.png', // Path to Water mark image
* 'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
* 'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
* 'marginX' => 5, // Margin horizontal pixel
* 'marginY' => 5, // Margin vertical pixel
* 'quality' => 95, // JPEG image save quality
* 'transparency' => 70, // Water mark image transparency ( other than PNG )
* 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
* 'targetMinPixel' => 200, // Target image minimum pixel size
* 'interlace' => IMG_GIF|IMG_JPG, // Set interlacebit image formats ( bit-field )
* 'offDropWith' => null, // Enabled by default. To disable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* 'onDropWith' => null // Disabled by default. To enable it if it is dropped with pressing the meta key
* // Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
* // In case of using any key, specify it as an array
* )
* )
* )
* )
* );
*
* @package elfinder
* @author Naoki Sawada
* @author Naoki Sawada
* @license New BSD
*/
class elFinderPluginWatermark extends elFinderPlugin {
class elFinderPluginWatermark extends elFinderPlugin
{
private $watermarkImgInfo = null;
private $watermarkImgInfo = null;
public function __construct($opts) {
$defaults = array(
'enable' => true, // For control by volume driver
'source' => 'logo.png', // Path to Water mark image
'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
'marginX' => 5, // Margin horizontal pixel
'marginY' => 5, // Margin vertical pixel
'quality' => 95, // JPEG image save quality
'transparency' => 70, // Water mark image transparency ( other than PNG )
'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
'targetMinPixel' => 200, // Target image minimum pixel size
'interlace' => IMG_GIF|IMG_JPG, // Set interlacebit image formats ( bit-field )
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'marginRight' => 0, // Deprecated - marginX should be used
'marginBottom' => 0, // Deprecated - marginY should be used
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
public function __construct($opts)
{
$defaults = array(
'enable' => true, // For control by volume driver
'source' => 'logo.png', // Path to Water mark image
'ratio' => 0.2, // Ratio to original image (ratio > 0 and ratio <= 1)
'position' => 'RB', // Position L(eft)/C(enter)/R(ight) and T(op)/M(edium)/B(ottom)
'marginX' => 5, // Margin horizontal pixel
'marginY' => 5, // Margin vertical pixel
'quality' => 95, // JPEG image save quality
'transparency' => 70, // Water mark image transparency ( other than PNG )
'targetType' => IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP, // Target image formats ( bit-field )
'targetMinPixel' => 200, // Target image minimum pixel size
'interlace' => IMG_GIF | IMG_JPG, // Set interlacebit image formats ( bit-field )
'offDropWith' => null, // To disable it if it is dropped with pressing the meta key
// Alt: 8, Ctrl: 4, Meta: 2, Shift: 1 - sum of each value
// In case of using any key, specify it as an array
'marginRight' => 0, // Deprecated - marginX should be used
'marginBottom' => 0, // Deprecated - marginY should be used
'disableWithContentSaveId' => true // Disable on URL upload with post data "contentSaveId"
);
$this->opts = array_merge($defaults, $opts);
$this->opts = array_merge($defaults, $opts);
}
}
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume) {
$opts = $this->getCurrentOpts($volume);
if (! $this->iaEnabled($opts, $elfinder)) {
return false;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
// check target image type
$imgTypes = array(
IMAGETYPE_GIF => IMG_GIF,
IMAGETYPE_JPEG => IMG_JPEG,
IMAGETYPE_PNG => IMG_PNG,
IMAGETYPE_BMP => IMG_WBMP,
IMAGETYPE_WBMP => IMG_WBMP
);
if (! isset($imgTypes[$imageType]) || ! ($opts['targetType'] & $imgTypes[$imageType])) {
return false;
}
// check Animation Gif
if ($imageType === IMAGETYPE_GIF && elFinder::isAnimationGif($src)) {
return false;
}
// check Animation Png
if ($imageType === IMAGETYPE_PNG && elFinder::isAnimationPng($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;
}
if (! $srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
$watermark = $opts['source'];
$quality = $opts['quality'];
$transparency = $opts['transparency'];
public function onUpLoadPreSave(&$thash, &$name, $src, $elfinder, $volume)
{
$opts = $this->getCurrentOpts($volume);
// 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];
if (!$this->iaEnabled($opts, $elfinder)) {
return false;
}
// Specified as a ratio to the image size
if ($opts['ratio'] && $opts['ratio'] > 0 && $opts['ratio'] <= 1) {
$maxW = $srcImgInfo[0] * $opts['ratio'] - ($opts['marginX'] * 2);
$maxH = $srcImgInfo[1] * $opts['ratio'] - ($opts['marginY'] * 2);
$dx = $dy = 0;
if (($maxW >= $watermarkImgInfo[0] && $maxH >= $watermarkImgInfo[0]) || ($maxW <= $watermarkImgInfo[0] && $maxH <= $watermarkImgInfo[0])) {
$dx = abs($srcImgInfo[0] - $watermarkImgInfo[0]);
$dy = abs($srcImgInfo[1] - $watermarkImgInfo[1]);
} else if ($maxW < $watermarkImgInfo[0]) {
$dx = -1;
} else {
$dy = -1;
}
if ($dx < $dy) {
$ww = $maxW;
$wh = $watermarkImgInfo[1] * ($ww / $watermarkImgInfo[0]);
} else {
$wh = $maxH;
$ww = $watermarkImgInfo[0] * ($wh / $watermarkImgInfo[1]);
}
$watermarkImgInfo[0] = $ww;
$watermarkImgInfo[1] = $wh;
} else {
$opts['ratio'] = null;
}
$imageType = null;
$srcImgInfo = null;
if (extension_loaded('fileinfo') && function_exists('mime_content_type')) {
$mime = mime_content_type($src);
if (substr($mime, 0, 5) !== 'image') {
return false;
}
}
if (extension_loaded('exif') && function_exists('exif_imagetype')) {
$imageType = exif_imagetype($src);
} else {
$srcImgInfo = getimagesize($src);
if ($srcImgInfo === false) {
return false;
}
$imageType = $srcImgInfo[2];
}
$opts['position'] = strtoupper($opts['position']);
// Set vertical position
if (strpos($opts['position'], 'T') !== false) {
// Top
$dest_x = $opts['marginX'];
} else if (strpos($opts['position'], 'M') !== false) {
// Middle
$dest_x = ($srcImgInfo[0] - $watermarkImgInfo[0]) / 2;
} else {
// Bottom
$dest_x = $srcImgInfo[0] - $watermarkImgInfo[0] - max($opts['marginBottom'], $opts['marginX']);
}
// check target image type
$imgTypes = array(
IMAGETYPE_GIF => IMG_GIF,
IMAGETYPE_JPEG => IMG_JPEG,
IMAGETYPE_PNG => IMG_PNG,
IMAGETYPE_BMP => IMG_WBMP,
IMAGETYPE_WBMP => IMG_WBMP
);
if (!isset($imgTypes[$imageType]) || !($opts['targetType'] & $imgTypes[$imageType])) {
return false;
}
// Set horizontal position
if (strpos($opts['position'], 'L') !== false) {
// Left
$dest_y = $opts['marginY'];
} else if (strpos($opts['position'], 'C') !== false) {
// Middle
$dest_y = ($srcImgInfo[1] - $watermarkImgInfo[1]) / 2;
} else {
// Right
$dest_y = $srcImgInfo[1] - $watermarkImgInfo[1] - max($opts['marginRight'], $opts['marginY']);
}
// check Animation Gif
if ($imageType === IMAGETYPE_GIF && elFinder::isAnimationGif($src)) {
return false;
}
// check Animation Png
if ($imageType === IMAGETYPE_PNG && elFinder::isAnimationPng($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;
}
// check interlace
$opts['interlace'] = ($opts['interlace'] & $imgTypes[$imageType]);
if (class_exists('Imagick', false)) {
return $this->watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $opts);
} else {
elFinder::expandMemoryForGD(array($watermarkImgInfo, $srcImgInfo));
return $this->watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo, $opts);
}
}
private function watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $opts) {
try {
// Open the original image
$img = new Imagick($src);
// Open the watermark
$watermark = new Imagick($watermark);
// zoom
if ($opts['ratio']) {
$watermark->scaleImage($watermarkImgInfo[0], $watermarkImgInfo[1]);
}
if (!$srcImgInfo) {
$srcImgInfo = getimagesize($src);
}
// Set transparency
if (strtoupper($watermark->getImageFormat()) !== 'PNG') {
$watermark->setImageOpacity($transparency/100);
}
// Overlay the watermark on the original image
$img->compositeImage($watermark, imagick::COMPOSITE_OVER, $dest_x, $dest_y);
// Set quality
if (strtoupper($img->getImageFormat()) === 'JPEG') {
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setCompressionQuality($quality);
}
// set interlace
$opts['interlace'] && $img->setInterlaceScheme(Imagick::INTERLACE_PLANE);
$result = $img->writeImage($src);
$img->clear();
$img->destroy();
$watermark->clear();
$watermark->destroy();
return $result ? true : false;
} catch (Exception $e) {
$ermsg = $e->getMessage();
$ermsg && trigger_error($ermsg);
return false;
}
}
private function watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo, $opts) {
$watermark_width = $watermarkImgInfo[0];
$watermark_height = $watermarkImgInfo[1];
$watermark = $opts['source'];
$quality = $opts['quality'];
$transparency = $opts['transparency'];
$ermsg = '';
switch ($watermarkImgInfo['mime']) {
case 'image/gif':
if (imagetypes() & IMG_GIF) {
$oWatermarkImg = imagecreatefromgif($watermark);
} else {
$ermsg = 'GIF images are not supported as watermark image';
}
break;
case 'image/jpeg':
if (imagetypes() & IMG_JPG) {
$oWatermarkImg = imagecreatefromjpeg($watermark) ;
} else {
$ermsg = 'JPEG images are not supported as watermark image';
}
break;
case 'image/png':
if (imagetypes() & IMG_PNG) {
$oWatermarkImg = imagecreatefrompng($watermark) ;
} else {
$ermsg = 'PNG images are not supported as watermark image';
}
break;
case 'image/wbmp':
if (imagetypes() & IMG_WBMP) {
$oWatermarkImg = imagecreatefromwbmp($watermark);
} else {
$ermsg = 'WBMP images are not supported as watermark image';
}
break;
default:
$oWatermarkImg = false;
$ermsg = $watermarkImgInfo['mime'].' images are not supported as watermark image';
break;
}
// check target image size
if ($opts['targetMinPixel'] > 0 && $opts['targetMinPixel'] > min($srcImgInfo[0], $srcImgInfo[1])) {
return false;
}
if (! $ermsg) {
// zoom
if ($opts['ratio']) {
$tmpImg = imagecreatetruecolor($watermarkImgInfo[0], $watermarkImgInfo[1]);
imagealphablending($tmpImg, false);
imagesavealpha($tmpImg, true);
imagecopyresampled($tmpImg, $oWatermarkImg, 0, 0, 0, 0, $watermarkImgInfo[0], $watermarkImgInfo[1], imagesx($oWatermarkImg), imagesy($oWatermarkImg));
imageDestroy($oWatermarkImg);
$oWatermarkImg = $tmpImg;
$tmpImg = null;
}
$watermark_width = $watermarkImgInfo[0];
$watermark_height = $watermarkImgInfo[1];
switch ($srcImgInfo['mime']) {
case 'image/gif':
if (imagetypes() & IMG_GIF) {
$oSrcImg = imagecreatefromgif($src);
} else {
$ermsg = 'GIF images are not supported as source image';
}
break;
case 'image/jpeg':
if (imagetypes() & IMG_JPG) {
$oSrcImg = imagecreatefromjpeg($src) ;
} else {
$ermsg = 'JPEG images are not supported as source image';
}
break;
case 'image/png':
if (imagetypes() & IMG_PNG) {
$oSrcImg = imagecreatefrompng($src) ;
} else {
$ermsg = 'PNG images are not supported as source image';
}
break;
case 'image/wbmp':
if (imagetypes() & IMG_WBMP) {
$oSrcImg = imagecreatefromwbmp($src);
} else {
$ermsg = 'WBMP images are not supported as source image';
}
break;
default:
$oSrcImg = false;
$ermsg = $srcImgInfo['mime'].' images are not supported as source image';
break;
}
}
if ($ermsg || false === $oSrcImg || false === $oWatermarkImg) {
$ermsg && trigger_error($ermsg);
return false;
}
if ($srcImgInfo['mime'] === 'image/png') {
if (function_exists('imagecolorallocatealpha')) {
$bg = imagecolorallocatealpha($oSrcImg, 255, 255, 255, 127);
imagefill($oSrcImg, 0, 0 , $bg);
}
}
if ($watermarkImgInfo['mime'] === 'image/png') {
imagecopy($oSrcImg, $oWatermarkImg, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
} else {
imagecopymerge($oSrcImg, $oWatermarkImg, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $transparency);
}
// set interlace
$opts['interlace'] && imageinterlace($oSrcImg, true);
switch ($srcImgInfo['mime']) {
case 'image/gif':
imagegif($oSrcImg, $src);
break;
case 'image/jpeg':
imagejpeg($oSrcImg, $src, $quality);
break;
case 'image/png':
if (function_exists('imagesavealpha') && function_exists('imagealphablending')) {
imagealphablending($oSrcImg, false);
imagesavealpha($oSrcImg, true);
}
imagepng($oSrcImg, $src);
break;
case 'image/wbmp':
imagewbmp($oSrcImg, $src);
break;
}
// Specified as a ratio to the image size
if ($opts['ratio'] && $opts['ratio'] > 0 && $opts['ratio'] <= 1) {
$maxW = $srcImgInfo[0] * $opts['ratio'] - ($opts['marginX'] * 2);
$maxH = $srcImgInfo[1] * $opts['ratio'] - ($opts['marginY'] * 2);
$dx = $dy = 0;
if (($maxW >= $watermarkImgInfo[0] && $maxH >= $watermarkImgInfo[0]) || ($maxW <= $watermarkImgInfo[0] && $maxH <= $watermarkImgInfo[0])) {
$dx = abs($srcImgInfo[0] - $watermarkImgInfo[0]);
$dy = abs($srcImgInfo[1] - $watermarkImgInfo[1]);
} else if ($maxW < $watermarkImgInfo[0]) {
$dx = -1;
} else {
$dy = -1;
}
if ($dx < $dy) {
$ww = $maxW;
$wh = $watermarkImgInfo[1] * ($ww / $watermarkImgInfo[0]);
} else {
$wh = $maxH;
$ww = $watermarkImgInfo[0] * ($wh / $watermarkImgInfo[1]);
}
$watermarkImgInfo[0] = $ww;
$watermarkImgInfo[1] = $wh;
} else {
$opts['ratio'] = null;
}
imageDestroy($oSrcImg);
imageDestroy($oWatermarkImg);
return true;
}
$opts['position'] = strtoupper($opts['position']);
// Set vertical position
if (strpos($opts['position'], 'T') !== false) {
// Top
$dest_x = $opts['marginX'];
} else if (strpos($opts['position'], 'M') !== false) {
// Middle
$dest_x = ($srcImgInfo[0] - $watermarkImgInfo[0]) / 2;
} else {
// Bottom
$dest_x = $srcImgInfo[0] - $watermarkImgInfo[0] - max($opts['marginBottom'], $opts['marginX']);
}
// Set horizontal position
if (strpos($opts['position'], 'L') !== false) {
// Left
$dest_y = $opts['marginY'];
} else if (strpos($opts['position'], 'C') !== false) {
// Middle
$dest_y = ($srcImgInfo[1] - $watermarkImgInfo[1]) / 2;
} else {
// Right
$dest_y = $srcImgInfo[1] - $watermarkImgInfo[1] - max($opts['marginRight'], $opts['marginY']);
}
// check interlace
$opts['interlace'] = ($opts['interlace'] & $imgTypes[$imageType]);
if (class_exists('Imagick', false)) {
return $this->watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $opts);
} else {
elFinder::expandMemoryForGD(array($watermarkImgInfo, $srcImgInfo));
return $this->watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo, $opts);
}
}
private function watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $opts)
{
try {
// Open the original image
$img = new Imagick($src);
// Open the watermark
$watermark = new Imagick($watermark);
// zoom
if ($opts['ratio']) {
$watermark->scaleImage($watermarkImgInfo[0], $watermarkImgInfo[1]);
}
// Set transparency
if (strtoupper($watermark->getImageFormat()) !== 'PNG') {
$watermark->setImageOpacity($transparency / 100);
}
// Overlay the watermark on the original image
$img->compositeImage($watermark, imagick::COMPOSITE_OVER, $dest_x, $dest_y);
// Set quality
if (strtoupper($img->getImageFormat()) === 'JPEG') {
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setCompressionQuality($quality);
}
// set interlace
$opts['interlace'] && $img->setInterlaceScheme(Imagick::INTERLACE_PLANE);
$result = $img->writeImage($src);
$img->clear();
$img->destroy();
$watermark->clear();
$watermark->destroy();
return $result ? true : false;
} catch (Exception $e) {
$ermsg = $e->getMessage();
$ermsg && trigger_error($ermsg);
return false;
}
}
private function watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo, $opts)
{
$watermark_width = $watermarkImgInfo[0];
$watermark_height = $watermarkImgInfo[1];
$ermsg = '';
switch ($watermarkImgInfo['mime']) {
case 'image/gif':
if (imagetypes() & IMG_GIF) {
$oWatermarkImg = imagecreatefromgif($watermark);
} else {
$ermsg = 'GIF images are not supported as watermark image';
}
break;
case 'image/jpeg':
if (imagetypes() & IMG_JPG) {
$oWatermarkImg = imagecreatefromjpeg($watermark);
} else {
$ermsg = 'JPEG images are not supported as watermark image';
}
break;
case 'image/png':
if (imagetypes() & IMG_PNG) {
$oWatermarkImg = imagecreatefrompng($watermark);
} else {
$ermsg = 'PNG images are not supported as watermark image';
}
break;
case 'image/wbmp':
if (imagetypes() & IMG_WBMP) {
$oWatermarkImg = imagecreatefromwbmp($watermark);
} else {
$ermsg = 'WBMP images are not supported as watermark image';
}
break;
default:
$oWatermarkImg = false;
$ermsg = $watermarkImgInfo['mime'] . ' images are not supported as watermark image';
break;
}
if (!$ermsg) {
// zoom
if ($opts['ratio']) {
$tmpImg = imagecreatetruecolor($watermarkImgInfo[0], $watermarkImgInfo[1]);
imagealphablending($tmpImg, false);
imagesavealpha($tmpImg, true);
imagecopyresampled($tmpImg, $oWatermarkImg, 0, 0, 0, 0, $watermarkImgInfo[0], $watermarkImgInfo[1], imagesx($oWatermarkImg), imagesy($oWatermarkImg));
imageDestroy($oWatermarkImg);
$oWatermarkImg = $tmpImg;
$tmpImg = null;
}
switch ($srcImgInfo['mime']) {
case 'image/gif':
if (imagetypes() & IMG_GIF) {
$oSrcImg = imagecreatefromgif($src);
} else {
$ermsg = 'GIF images are not supported as source image';
}
break;
case 'image/jpeg':
if (imagetypes() & IMG_JPG) {
$oSrcImg = imagecreatefromjpeg($src);
} else {
$ermsg = 'JPEG images are not supported as source image';
}
break;
case 'image/png':
if (imagetypes() & IMG_PNG) {
$oSrcImg = imagecreatefrompng($src);
} else {
$ermsg = 'PNG images are not supported as source image';
}
break;
case 'image/wbmp':
if (imagetypes() & IMG_WBMP) {
$oSrcImg = imagecreatefromwbmp($src);
} else {
$ermsg = 'WBMP images are not supported as source image';
}
break;
default:
$oSrcImg = false;
$ermsg = $srcImgInfo['mime'] . ' images are not supported as source image';
break;
}
}
if ($ermsg || false === $oSrcImg || false === $oWatermarkImg) {
$ermsg && trigger_error($ermsg);
return false;
}
if ($srcImgInfo['mime'] === 'image/png') {
if (function_exists('imagecolorallocatealpha')) {
$bg = imagecolorallocatealpha($oSrcImg, 255, 255, 255, 127);
imagefill($oSrcImg, 0, 0, $bg);
}
}
if ($watermarkImgInfo['mime'] === 'image/png') {
imagecopy($oSrcImg, $oWatermarkImg, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
} else {
imagecopymerge($oSrcImg, $oWatermarkImg, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $transparency);
}
// set interlace
$opts['interlace'] && imageinterlace($oSrcImg, true);
switch ($srcImgInfo['mime']) {
case 'image/gif':
imagegif($oSrcImg, $src);
break;
case 'image/jpeg':
imagejpeg($oSrcImg, $src, $quality);
break;
case 'image/png':
if (function_exists('imagesavealpha') && function_exists('imagealphablending')) {
imagealphablending($oSrcImg, false);
imagesavealpha($oSrcImg, true);
}
imagepng($oSrcImg, $src);
break;
case 'image/wbmp':
imagewbmp($oSrcImg, $src);
break;
}
imageDestroy($oSrcImg);
imageDestroy($oWatermarkImg);
return true;
}
}