Is it possible that when I upload a file with KCFinder, that he also puts that data (filename & path) in a MYSQL database?
I've already searched in the core files of CKFinder, where I can put the query when the file is succesfully uploaded, but I'm not sure where I can put the query if it is SUCCESFULLY uploaded..
I've found a function in 2 files which could be relevant, but I don't know if this is the right function and where I have to put in the query...
browser.php
- Code: Select all
<?php protected function moveUploadFile($file, $dir) {
$message = $this->checkUploadedFile($file);
if ($message !== true) {
if (isset($file['tmp_name']))
@unlink($file['tmp_name']);
return "{$file['name']}: $message";
}
$filename = $this->normalizeFilename($file['name']);
$target = "$dir/" . file::getInexistantFilename($filename, $dir);
if (!@move_uploaded_file($file['tmp_name'], $target) &&
!@rename($file['tmp_name'], $target) &&
!@copy($file['tmp_name'], $target)
) {
@unlink($file['tmp_name']);
return "{$file['name']}: " . $this->label("Cannot move uploaded file to target folder.");
} elseif (function_exists('chmod'))
chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
return "/" . basename($target);
}
?>
Uploader.php
- Code: Select all
<?php
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) @unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($this->get['dir']) &&
(false !== ($gdir = $this->checkInputDir($this->get['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
@mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!@move_uploaded_file($file['tmp_name'], $target) &&
!@rename($file['tmp_name'], $target) &&
!@copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
@chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}
if (strlen($message) &&
isset($this->file['tmp_name']) &&
file_exists($this->file['tmp_name'])
)
@unlink($this->file['tmp_name']);
if (strlen($message) && method_exists($this, 'errorMsg'))
$this->errorMsg($message);
$this->callBack($url, $message);
}
?>
And I also need to update the query when the file is renamed and when a file is deleted from KCFinder, I also need it deleted from the database.
Full browser.php (I've deleted some functions which were totally not relevant)
- Code: Select all
<?php
class browser extends uploader {
protected $action;
protected $thumbsDir;
protected $thumbsTypeDir;
public function __construct() {
parent::__construct();
if (isset($this->post['dir'])) {
$dir = $this->checkInputDir($this->post['dir'], true, false);
if ($dir === false) unset($this->post['dir']);
$this->post['dir'] = $dir;
}
if (isset($this->get['dir'])) {
$dir = $this->checkInputDir($this->get['dir'], true, false);
if ($dir === false) unset($this->get['dir']);
$this->get['dir'] = $dir;
}
$thumbsDir = $this->config['uploadDir'] . "/" . $this->config['thumbsDir'];
if ((
!is_dir($thumbsDir) &&
!@mkdir($thumbsDir, $this->config['dirPerms'])
) ||
!is_readable($thumbsDir) ||
!dir::isWritable($thumbsDir) ||
(
!is_dir("$thumbsDir/{$this->type}") &&
!@mkdir("$thumbsDir/{$this->type}", $this->config['dirPerms'])
)
)
$this->errorMsg("Cannot access or create thumbnails folder.");
$this->thumbsDir = $thumbsDir;
$this->thumbsTypeDir = "$thumbsDir/{$this->type}";
// Remove temporary zip downloads if exists
$files = dir::content($this->config['uploadDir'], array(
'types' => "file",
'pattern' => '/^.*\.zip$/i'
));
if (is_array($files) && count($files)) {
$time = time();
foreach ($files as $file)
if (is_file($file) && ($time - filemtime($file) > 3600))
unlink($file);
}
if (isset($this->get['theme']) &&
($this->get['theme'] == basename($this->get['theme'])) &&
is_dir("themes/{$this->get['theme']}")
)
$this->config['theme'] = $this->get['theme'];
}
public function action() {
$act = isset($this->get['act']) ? $this->get['act'] : "browser";
if (!method_exists($this, "act_$act"))
$act = "browser";
$this->action = $act;
$method = "act_$act";
if ($this->config['disabled']) {
$message = $this->label("You don't have permissions to browse server.");
if (in_array($act, array("browser", "upload")) ||
(substr($act, 0, 8) == "download")
)
$this->backMsg($message);
else {
header("Content-Type: text/plain; charset={$this->charset}");
die(json_encode(array('error' => $message)));
}
}
if (!isset($this->session['dir']))
$this->session['dir'] = $this->type;
else {
$type = $this->getTypeFromPath($this->session['dir']);
$dir = $this->config['uploadDir'] . "/" . $this->session['dir'];
if (($type != $this->type) || !is_dir($dir) || !is_readable($dir))
$this->session['dir'] = $this->type;
}
$this->session['dir'] = path::normalize($this->session['dir']);
if ($act == "browser") {
header("X-UA-Compatible: chrome=1");
header("Content-Type: text/html; charset={$this->charset}");
} elseif (
(substr($act, 0, 8) != "download") &&
!in_array($act, array("thumb", "upload"))
)
header("Content-Type: text/plain; charset={$this->charset}");
$return = $this->$method();
echo ($return === true)
? '{}'
: $return;
}
protected function act_browser() {
if (isset($this->get['dir']) &&
is_dir("{$this->typeDir}/{$this->get['dir']}") &&
is_readable("{$this->typeDir}/{$this->get['dir']}")
)
$this->session['dir'] = path::normalize("{$this->type}/{$this->get['dir']}");
return $this->output();
}
protected function act_init() {
$tree = $this->getDirInfo($this->typeDir);
$tree['dirs'] = $this->getTree($this->session['dir']);
if (!is_array($tree['dirs']) || !count($tree['dirs']))
unset($tree['dirs']);
$files = $this->getFiles($this->session['dir']);
$dirWritable = dir::isWritable("{$this->config['uploadDir']}/{$this->session['dir']}");
$data = array(
'tree' => &$tree,
'files' => &$files,
'dirWritable' => $dirWritable
);
return json_encode($data);
}
protected function act_thumb() {
$this->getDir($this->get['dir'], true);
if (!isset($this->get['file']) || !isset($this->get['dir']))
$this->sendDefaultThumb();
$file = $this->get['file'];
if (basename($file) != $file)
$this->sendDefaultThumb();
$file = "{$this->thumbsDir}/{$this->type}/{$this->get['dir']}/$file";
if (!is_file($file) || !is_readable($file)) {
$file = "{$this->config['uploadDir']}/{$this->type}/{$this->get['dir']}/" . basename($file);
if (!is_file($file) || !is_readable($file))
$this->sendDefaultThumb($file);
$image = new gd($file);
if ($image->init_error)
$this->sendDefaultThumb($file);
$browsable = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (in_array($image->type, $browsable) &&
($image->get_width() <= $this->config['thumbWidth']) &&
($image->get_height() <= $this->config['thumbHeight'])
) {
$type =
($image->type == IMAGETYPE_GIF) ? "gif" : (
($image->type == IMAGETYPE_PNG) ? "png" : "jpeg");
$type = "image/$type";
httpCache::file($file, $type);
} else
$this->sendDefaultThumb($file);
}
httpCache::file($file, "image/jpeg");
}
protected function act_upload() {
if (!$this->config['access']['files']['upload'] ||
!isset($this->post['dir'])
)
$this->errorMsg("Unknown error.");
$dir = $this->postDir();
if (!dir::isWritable($dir))
$this->errorMsg("Cannot access or write to upload folder.");
if (is_array($this->file['name'])) {
$return = array();
foreach ($this->file['name'] as $i => $name) {
$return[] = $this->moveUploadFile(array(
'name' => $name,
'tmp_name' => $this->file['tmp_name'][$i],
'error' => $this->file['error'][$i]
), $dir);
}
return implode("\n", $return);
} else
return $this->moveUploadFile($this->file, $dir);
}
protected function act_rename() {
$dir = $this->postDir();
if (!$this->config['access']['files']['rename'] ||
!isset($this->post['dir']) ||
!isset($this->post['file']) ||
!isset($this->post['newName']) ||
(false === ($file = "$dir/{$this->post['file']}")) ||
!file_exists($file) || !is_readable($file) || !file::isWritable($file)
)
$this->errorMsg("Unknown error.");
if (isset($this->config['denyExtensionRename']) &&
$this->config['denyExtensionRename'] &&
(file::getExtension($this->post['file'], true) !==
file::getExtension($this->post['newName'], true)
)
)
$this->errorMsg("You cannot rename the extension of files!");
$newName = $this->normalizeFilename(trim($this->post['newName']));
if (!strlen($newName))
$this->errorMsg("Please enter new file name.");
if (preg_match('/[\/\\\\]/s', $newName))
$this->errorMsg("Unallowable characters in file name.");
if (substr($newName, 0, 1) == ".")
$this->errorMsg("File name shouldn't begins with '.'");
$newName = "$dir/$newName";
if (file_exists($newName))
$this->errorMsg("A file or folder with that name already exists.");
$ext = file::getExtension($newName);
if (!$this->validateExtension($ext, $this->type))
$this->errorMsg("Denied file extension.");
if (!@rename($file, $newName))
$this->errorMsg("Unknown error.");
$thumbDir = "{$this->thumbsTypeDir}/{$this->post['dir']}";
$thumbFile = "$thumbDir/{$this->post['file']}";
if (file_exists($thumbFile))
@rename($thumbFile, "$thumbDir/" . basename($newName));
return true;
}
protected function act_delete() {
$dir = $this->postDir();
if (!$this->config['access']['files']['delete'] ||
!isset($this->post['dir']) ||
!isset($this->post['file']) ||
(false === ($file = "$dir/{$this->post['file']}")) ||
!file_exists($file) || !is_readable($file) || !file::isWritable($file) ||
!@unlink($file)
)
$this->errorMsg("Unknown error.");
$thumb = "{$this->thumbsTypeDir}/{$this->post['dir']}/{$this->post['file']}";
if (file_exists($thumb)) @unlink($thumb);
return true;
}
protected function act_cp_cbd() {
$dir = $this->postDir();
if (!$this->config['access']['files']['copy'] ||
!isset($this->post['dir']) ||
!is_dir($dir) || !is_readable($dir) || !dir::isWritable($dir) ||
!isset($this->post['files']) || !is_array($this->post['files']) ||
!count($this->post['files'])
)
$this->errorMsg("Unknown error.");
$error = array();
foreach($this->post['files'] as $file) {
$file = path::normalize($file);
if (substr($file, 0, 1) == ".") continue;
$type = explode("/", $file);
$type = $type[0];
if ($type != $this->type) continue;
$path = "{$this->config['uploadDir']}/$file";
$base = basename($file);
$replace = array('file' => $base);
$ext = file::getExtension($base);
if (!file_exists($path))
$error[] = $this->label("The file '{file}' does not exist.", $replace);
elseif (substr($base, 0, 1) == ".")
$error[] = "$base: " . $this->label("File name shouldn't begins with '.'");
elseif (!$this->validateExtension($ext, $type))
$error[] = "$base: " . $this->label("Denied file extension.");
elseif (file_exists("$dir/$base"))
$error[] = "$base: " . $this->label("A file or folder with that name already exists.");
elseif (!is_readable($path) || !is_file($path))
$error[] = $this->label("Cannot read '{file}'.", $replace);
elseif (!@copy($path, "$dir/$base"))
$error[] = $this->label("Cannot copy '{file}'.", $replace);
else {
if (function_exists("chmod"))
@chmod("$dir/$base", $this->config['filePerms']);
$fromThumb = "{$this->thumbsDir}/$file";
if (is_file($fromThumb) && is_readable($fromThumb)) {
$toThumb = "{$this->thumbsTypeDir}/{$this->post['dir']}";
if (!is_dir($toThumb))
@mkdir($toThumb, $this->config['dirPerms'], true);
$toThumb .= "/$base";
@copy($fromThumb, $toThumb);
}
}
}
if (count($error))
return json_encode(array('error' => $error));
return true;
}
protected function act_mv_cbd() {
$dir = $this->postDir();
if (!$this->config['access']['files']['move'] ||
!isset($this->post['dir']) ||
!is_dir($dir) || !is_readable($dir) || !dir::isWritable($dir) ||
!isset($this->post['files']) || !is_array($this->post['files']) ||
!count($this->post['files'])
)
$this->errorMsg("Unknown error.");
$error = array();
foreach($this->post['files'] as $file) {
$file = path::normalize($file);
if (substr($file, 0, 1) == ".") continue;
$type = explode("/", $file);
$type = $type[0];
if ($type != $this->type) continue;
$path = "{$this->config['uploadDir']}/$file";
$base = basename($file);
$replace = array('file' => $base);
$ext = file::getExtension($base);
if (!file_exists($path))
$error[] = $this->label("The file '{file}' does not exist.", $replace);
elseif (substr($base, 0, 1) == ".")
$error[] = "$base: " . $this->label("File name shouldn't begins with '.'");
elseif (!$this->validateExtension($ext, $type))
$error[] = "$base: " . $this->label("Denied file extension.");
elseif (file_exists("$dir/$base"))
$error[] = "$base: " . $this->label("A file or folder with that name already exists.");
elseif (!is_readable($path) || !is_file($path))
$error[] = $this->label("Cannot read '{file}'.", $replace);
elseif (!file::isWritable($path) || !@rename($path, "$dir/$base"))
$error[] = $this->label("Cannot move '{file}'.", $replace);
else {
if (function_exists("chmod"))
@chmod("$dir/$base", $this->config['filePerms']);
$fromThumb = "{$this->thumbsDir}/$file";
if (is_file($fromThumb) && is_readable($fromThumb)) {
$toThumb = "{$this->thumbsTypeDir}/{$this->post['dir']}";
if (!is_dir($toThumb))
@mkdir($toThumb, $this->config['dirPerms'], true);
$toThumb .= "/$base";
@rename($fromThumb, $toThumb);
}
}
}
if (count($error))
return json_encode(array('error' => $error));
return true;
}
protected function act_rm_cbd() {
if (!$this->config['access']['files']['delete'] ||
!isset($this->post['files']) ||
!is_array($this->post['files']) ||
!count($this->post['files'])
)
$this->errorMsg("Unknown error.");
$error = array();
foreach($this->post['files'] as $file) {
$file = path::normalize($file);
if (substr($file, 0, 1) == ".") continue;
$type = explode("/", $file);
$type = $type[0];
if ($type != $this->type) continue;
$path = "{$this->config['uploadDir']}/$file";
$base = basename($file);
$replace = array('file' => $base);
if (!is_file($path))
$error[] = $this->label("The file '{file}' does not exist.", $replace);
elseif (!@unlink($path))
$error[] = $this->label("Cannot delete '{file}'.", $replace);
else {
$thumb = "{$this->thumbsDir}/$file";
if (is_file($thumb)) @unlink($thumb);
}
}
if (count($error))
return json_encode(array('error' => $error));
return true;
}
protected function moveUploadFile($file, $dir) {
$message = $this->checkUploadedFile($file);
if ($message !== true) {
if (isset($file['tmp_name']))
@unlink($file['tmp_name']);
return "{$file['name']}: $message";
}
$filename = $this->normalizeFilename($file['name']);
$target = "$dir/" . file::getInexistantFilename($filename, $dir);
if (!@move_uploaded_file($file['tmp_name'], $target) &&
!@rename($file['tmp_name'], $target) &&
!@copy($file['tmp_name'], $target)
) {
@unlink($file['tmp_name']);
return "{$file['name']}: " . $this->label("Cannot move uploaded file to target folder.");
} elseif (function_exists('chmod'))
chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
echo('<script type="text/javascript">alert("'.$filename.' , '.$dir.'/'.$filename.'")</script>');
return "/" . basename($target);
}
protected function sendDefaultThumb($file=null) {
if ($file !== null) {
$ext = file::getExtension($file);
$thumb = "themes/{$this->config['theme']}/img/files/big/$ext.png";
}
if (!isset($thumb) || !file_exists($thumb))
$thumb = "themes/{$this->config['theme']}/img/files/big/..png";
header("Content-Type: image/png");
readfile($thumb);
die;
}
protected function getFiles($dir) {
$thumbDir = "{$this->config['uploadDir']}/{$this->config['thumbsDir']}/$dir";
$dir = "{$this->config['uploadDir']}/$dir";
$return = array();
$files = dir::content($dir, array('types' => "file"));
if ($files === false)
return $return;
foreach ($files as $file) {
$size = @getimagesize($file);
if (is_array($size) && count($size)) {
$thumb_file = "$thumbDir/" . basename($file);
if (!is_file($thumb_file))
$this->makeThumb($file, false);
$smallThumb =
($size[0] <= $this->config['thumbWidth']) &&
($size[1] <= $this->config['thumbHeight']) &&
in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_PNG, IMAGETYPE_JPEG));
} else
$smallThumb = false;
$stat = stat($file);
if ($stat === false) continue;
$name = basename($file);
$ext = file::getExtension($file);
$bigIcon = file_exists("themes/{$this->config['theme']}/img/files/big/$ext.png");
$smallIcon = file_exists("themes/{$this->config['theme']}/img/files/small/$ext.png");
$thumb = file_exists("$thumbDir/$name");
$return[] = array(
'name' => stripcslashes($name),
'size' => $stat['size'],
'mtime' => $stat['mtime'],
'date' => @strftime($this->dateTimeSmall, $stat['mtime']),
'readable' => is_readable($file),
'writable' => file::isWritable($file),
'bigIcon' => $bigIcon,
'smallIcon' => $smallIcon,
'thumb' => $thumb,
'smallThumb' => $smallThumb
);
}
return $return;
}
protected function getTree($dir, $index=0) {
$path = explode("/", $dir);
$pdir = "";
for ($i = 0; ($i <= $index && $i < count($path)); $i++)
$pdir .= "/{$path[$i]}";
if (strlen($pdir))
$pdir = substr($pdir, 1);
$fdir = "{$this->config['uploadDir']}/$pdir";
$dirs = $this->getDirs($fdir);
if (is_array($dirs) && count($dirs) && ($index <= count($path) - 1)) {
foreach ($dirs as $i => $cdir) {
if ($cdir['hasDirs'] &&
(
($index == count($path) - 1) ||
($cdir['name'] == $path[$index + 1])
)
) {
$dirs[$i]['dirs'] = $this->getTree($dir, $index + 1);
if (!is_array($dirs[$i]['dirs']) || !count($dirs[$i]['dirs'])) {
unset($dirs[$i]['dirs']);
continue;
}
}
}
} else
return false;
return $dirs;
}
protected function output($data=null, $template=null) {
if (!is_array($data)) $data = array();
if ($template === null)
$template = $this->action;
if (file_exists("tpl/tpl_$template.php")) {
ob_start();
$eval = "unset(\$data);unset(\$template);unset(\$eval);";
$_ = $data;
foreach (array_keys($data) as $key)
if (preg_match('/^[a-z\d_]+$/i', $key))
$eval .= "\$$key=\$_['$key'];";
$eval .= "unset(\$_);require \"tpl/tpl_$template.php\";";
eval($eval);
return ob_get_clean();
}
return "";
}
protected function errorMsg($message, array $data=null) {
if (in_array($this->action, array("thumb", "upload", "download", "downloadDir")))
die($this->label($message, $data));
if (($this->action === null) || ($this->action == "browser"))
$this->backMsg($message, $data);
else {
$message = $this->label($message, $data);
die(json_encode(array('error' => $message)));
}
}
}
?>
Full uploader.php (I've deleted some functions which were totally not relevant)
- Code: Select all
<?php
class uploader {
/** Release version */
const VERSION = "2.51";
/** Config session-overrided settings
* @var array */
protected $config = array();
/** Opener applocation properties
* $opener['name'] Got from $_GET['opener'];
* $opener['CKEditor']['funcNum'] CKEditor function number (got from $_GET)
* $opener['TinyMCE'] Boolean
* @var array */
protected $opener = array();
/** Got from $_GET['type'] or first one $config['types'] array key, if inexistant
* @var string */
protected $type;
/** Helper property. Local filesystem path to the Type Directory
* Equivalent: $config['uploadDir'] . "/" . $type
* @var string */
protected $typeDir;
/** Helper property. Web URL to the Type Directory
* Equivalent: $config['uploadURL'] . "/" . $type
* @var string */
protected $typeURL;
/** Linked to $config['types']
* @var array */
protected $types = array();
/** Settings which can override default settings if exists as keys in $config['types'][$type] array
* @var array */
protected $typeSettings = array('disabled', 'theme', 'dirPerms', 'filePerms', 'denyZipDownload', 'maxImageWidth', 'maxImageHeight', 'thumbWidth', 'thumbHeight', 'jpegQuality', 'access', 'filenameChangeChars', 'dirnameChangeChars', 'denyExtensionRename', 'deniedExts');
/** Got from language file
* @var string */
protected $charset;
/** The language got from $_GET['lng'] or $_GET['lang'] or... Please see next property
* @var string */
protected $lang = 'en';
/** Possible language $_GET keys
* @var array */
protected $langInputNames = array('lang', 'langCode', 'lng', 'language', 'lang_code');
/** Uploaded file(s) info. Linked to first $_FILES element
* @var array */
protected $file;
/** Next three properties are got from the current language file
* @var string */
protected $dateTimeFull; // Currently not used
protected $dateTimeMid; // Currently not used
protected $dateTimeSmall;
/** Contain Specified language labels
* @var array */
protected $labels = array();
/** Contain unprocessed $_GET array. Please use this instead of $_GET
* @var array */
protected $get;
/** Contain unprocessed $_POST array. Please use this instead of $_POST
* @var array */
protected $post;
/** Contain unprocessed $_COOKIE array. Please use this instead of $_COOKIE
* @var array */
protected $cookie;
/** Session array. Please use this property instead of $_SESSION
* @var array */
protected $session;
/** CMS integration attribute (got from $_GET['cms'])
* @var string */
protected $cms = "";
/** Magic method which allows read-only access to protected or private class properties
* @param string $property
* @return mixed */
public function __get($property) {
return property_exists($this, $property) ? $this->$property : null;
}
public function __construct() {
// DISABLE MAGIC QUOTES
if (function_exists('set_magic_quotes_runtime'))
@set_magic_quotes_runtime(false);
// INPUT INIT
$input = new input();
$this->get = &$input->get;
$this->post = &$input->post;
$this->cookie = &$input->cookie;
// SET CMS INTEGRATION ATTRIBUTE
if (isset($this->get['cms']) &&
in_array($this->get['cms'], array("drupal"))
)
$this->cms = $this->get['cms'];
// LINKING UPLOADED FILE
if (count($_FILES))
$this->file = &$_FILES[key($_FILES)];
// LOAD DEFAULT CONFIGURATION
require "config.php";
// SETTING UP SESSION
if (isset($_CONFIG['_sessionLifetime']))
ini_set('session.gc_maxlifetime', $_CONFIG['_sessionLifetime'] * 60);
if (isset($_CONFIG['_sessionDir']))
ini_set('session.save_path', $_CONFIG['_sessionDir']);
if (isset($_CONFIG['_sessionDomain']))
ini_set('session.cookie_domain', $_CONFIG['_sessionDomain']);
switch ($this->cms) {
case "drupal": break;
default: session_start(); break;
}
// RELOAD DEFAULT CONFIGURATION
require "config.php";
$this->config = $_CONFIG;
// LOAD SESSION CONFIGURATION IF EXISTS
if (isset($_CONFIG['_sessionVar']) &&
is_array($_CONFIG['_sessionVar'])
) {
foreach ($_CONFIG['_sessionVar'] as $key => $val)
if ((substr($key, 0, 1) != "_") && isset($_CONFIG[$key]))
$this->config[$key] = $val;
if (!isset($this->config['_sessionVar']['self']))
$this->config['_sessionVar']['self'] = array();
$this->session = &$this->config['_sessionVar']['self'];
} else
$this->session = &$_SESSION;
// GET TYPE DIRECTORY
$this->types = &$this->config['types'];
$firstType = array_keys($this->types);
$firstType = $firstType[0];
$this->type = (
isset($this->get['type']) &&
isset($this->types[$this->get['type']])
)
? $this->get['type'] : $firstType;
// LOAD TYPE DIRECTORY SPECIFIC CONFIGURATION IF EXISTS
if (is_array($this->types[$this->type])) {
foreach ($this->types[$this->type] as $key => $val)
if (in_array($key, $this->typeSettings))
$this->config[$key] = $val;
$this->types[$this->type] = isset($this->types[$this->type]['type'])
? $this->types[$this->type]['type'] : "";
}
// COOKIES INIT
$ip = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
$ip = '/^' . implode('\.', array($ip, $ip, $ip, $ip)) . '$/';
if (preg_match($ip, $_SERVER['HTTP_HOST']) ||
preg_match('/^[^\.]+$/', $_SERVER['HTTP_HOST'])
)
$this->config['cookieDomain'] = "";
elseif (!strlen($this->config['cookieDomain']))
$this->config['cookieDomain'] = $_SERVER['HTTP_HOST'];
if (!strlen($this->config['cookiePath']))
$this->config['cookiePath'] = "/";
// UPLOAD FOLDER INIT
// FULL URL
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)\/?$/',
$this->config['uploadURL'], $patt)
) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$path = path::normalize($path);
$this->config['uploadURL'] = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/$path";
$this->config['uploadDir'] = strlen($this->config['uploadDir'])
? path::normalize($this->config['uploadDir'])
: path::url2fullPath("/$path");
$this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
$this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
// SITE ROOT
} elseif ($this->config['uploadURL'] == "/") {
$this->config['uploadDir'] = strlen($this->config['uploadDir'])
? path::normalize($this->config['uploadDir'])
: path::normalize($_SERVER['DOCUMENT_ROOT']);
$this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
$this->typeURL = "/{$this->type}";
// ABSOLUTE & RELATIVE
} else {
$this->config['uploadURL'] = (substr($this->config['uploadURL'], 0, 1) === "/")
? path::normalize($this->config['uploadURL'])
: path::rel2abs_url($this->config['uploadURL']);
$this->config['uploadDir'] = strlen($this->config['uploadDir'])
? path::normalize($this->config['uploadDir'])
: path::url2fullPath($this->config['uploadURL']);
$this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
$this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
}
if (!is_dir($this->config['uploadDir']))
@mkdir($this->config['uploadDir'], $this->config['dirPerms']);
// HOST APPLICATIONS INIT
if (isset($this->get['CKEditorFuncNum']))
$this->opener['CKEditor']['funcNum'] = $this->get['CKEditorFuncNum'];
if (isset($this->get['opener']) &&
(strtolower($this->get['opener']) == "tinymce") &&
isset($this->config['_tinyMCEPath']) &&
strlen($this->config['_tinyMCEPath'])
)
$this->opener['TinyMCE'] = true;
// LOCALIZATION
foreach ($this->langInputNames as $key)
if (isset($this->get[$key]) &&
preg_match('/^[a-z][a-z\._\-]*$/i', $this->get[$key]) &&
file_exists("lang/" . strtolower($this->get[$key]) . ".php")
) {
$this->lang = $this->get[$key];
break;
}
$this->localize($this->lang);
// CHECK & MAKE DEFAULT .htaccess
if (isset($this->config['_check4htaccess']) &&
$this->config['_check4htaccess']
) {
$htaccess = "{$this->config['uploadDir']}/.htaccess";
if (!file_exists($htaccess)) {
if (!@file_put_contents($htaccess, $this->get_htaccess()))
$this->backMsg("Cannot write to upload folder. {$this->config['uploadDir']}");
} else {
if (false === ($data = @file_get_contents($htaccess)))
$this->backMsg("Cannot read .htaccess");
if (($data != $this->get_htaccess()) && !@file_put_contents($htaccess, $data))
$this->backMsg("Incorrect .htaccess file. Cannot rewrite it!");
}
}
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) @unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($this->get['dir']) &&
(false !== ($gdir = $this->checkInputDir($this->get['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
@mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!@move_uploaded_file($file['tmp_name'], $target) &&
!@rename($file['tmp_name'], $target) &&
!@copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
@chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}
if (strlen($message) &&
isset($this->file['tmp_name']) &&
file_exists($this->file['tmp_name'])
)
@unlink($this->file['tmp_name']);
if (strlen($message) && method_exists($this, 'errorMsg'))
$this->errorMsg($message);
$this->callBack($url, $message);
}
protected function normalizeFilename($filename) {
if (isset($this->config['filenameChangeChars']) &&
is_array($this->config['filenameChangeChars'])
)
$filename = strtr($filename, $this->config['filenameChangeChars']);
return $filename;
}
protected function checkUploadedFile(array $aFile=null) {
$config = &$this->config;
$file = ($aFile === null) ? $this->file : $aFile;
if (!is_array($file) || !isset($file['name']))
return $this->label("Unknown error");
if (is_array($file['name'])) {
foreach ($file['name'] as $i => $name) {
$return = $this->checkUploadedFile(array(
'name' => $name,
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i]
));
if ($return !== true)
return "$name: $return";
}
return true;
}
$extension = file::getExtension($file['name']);
$typePatt = strtolower(text::clearWhitespaces($this->types[$this->type]));
// CHECK FOR UPLOAD ERRORS
if ($file['error'])
return
($file['error'] == UPLOAD_ERR_INI_SIZE) ?
$this->label("The uploaded file exceeds {size} bytes.",
array('size' => ini_get('upload_max_filesize'))) : (
($file['error'] == UPLOAD_ERR_FORM_SIZE) ?
$this->label("The uploaded file exceeds {size} bytes.",
array('size' => $this->get['MAX_FILE_SIZE'])) : (
($file['error'] == UPLOAD_ERR_PARTIAL) ?
$this->label("The uploaded file was only partially uploaded.") : (
($file['error'] == UPLOAD_ERR_NO_FILE) ?
$this->label("No file was uploaded.") : (
($file['error'] == UPLOAD_ERR_NO_TMP_DIR) ?
$this->label("Missing a temporary folder.") : (
($file['error'] == UPLOAD_ERR_CANT_WRITE) ?
$this->label("Failed to write file.") :
$this->label("Unknown error.")
)))));
// HIDDEN FILENAMES CHECK
elseif (substr($file['name'], 0, 1) == ".")
return $this->label("File name shouldn't begins with '.'");
// EXTENSION CHECK
elseif (!$this->validateExtension($extension, $this->type))
return $this->label("Denied file extension.");
protected function makeThumb($file, $overwrite=true) {
$gd = new gd($file);
// Drop files which are not GD handled images
if ($gd->init_error)
return true;
$thumb = substr($file, strlen($this->config['uploadDir']));
$thumb = $this->config['uploadDir'] . "/" . $this->config['thumbsDir'] . "/" . $thumb;
$thumb = path::normalize($thumb);
$thumbDir = dirname($thumb);
if (!is_dir($thumbDir) && !@mkdir($thumbDir, $this->config['dirPerms'], true))
return false;
if (!$overwrite && is_file($thumb))
return true;
// Images with smaller resolutions than thumbnails
if (($gd->get_width() <= $this->config['thumbWidth']) &&
($gd->get_height() <= $this->config['thumbHeight'])
) {
$browsable = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
// Drop only browsable types
if (in_array($gd->type, $browsable))
return true;
// Resize image
} elseif (!$gd->resize_fit($this->config['thumbWidth'], $this->config['thumbHeight']))
return false;
// Save thumbnail
return $gd->imagejpeg($thumb, $this->config['jpegQuality']);
}
protected function localize($langCode) {
require "lang/{$langCode}.php";
setlocale(LC_ALL, $lang['_locale']);
$this->charset = $lang['_charset'];
$this->dateTimeFull = $lang['_dateTimeFull'];
$this->dateTimeMid = $lang['_dateTimeMid'];
$this->dateTimeSmall = $lang['_dateTimeSmall'];
unset($lang['_locale']);
unset($lang['_charset']);
unset($lang['_dateTimeFull']);
unset($lang['_dateTimeMid']);
unset($lang['_dateTimeSmall']);
$this->labels = $lang;
}
protected function label($string, array $data=null) {
$return = isset($this->labels[$string]) ? $this->labels[$string] : $string;
if (is_array($data))
foreach ($data as $key => $val)
$return = str_replace("{{$key}}", $val, $return);
return $return;
}
protected function backMsg($message, array $data=null) {
$message = $this->label($message, $data);
if (isset($this->file['tmp_name']) && file_exists($this->file['tmp_name']))
@unlink($this->file['tmp_name']);
$this->callBack("", $message);
die;
}
protected function callBack($url, $message="") {
$message = text::jsValue($message);
$CKfuncNum = isset($this->opener['CKEditor']['funcNum'])
? $this->opener['CKEditor']['funcNum'] : 0;
if (!$CKfuncNum) $CKfuncNum = 0;
header("Content-Type: text/html; charset={$this->charset}");
?><html>
<body>
<script type='text/javascript'>
var kc_CKEditor = (window.parent && window.parent.CKEDITOR)
? window.parent.CKEDITOR.tools.callFunction
: ((window.opener && window.opener.CKEDITOR)
? window.opener.CKEDITOR.tools.callFunction
: false);
var kc_FCKeditor = (window.opener && window.opener.OnUploadCompleted)
? window.opener.OnUploadCompleted
: ((window.parent && window.parent.OnUploadCompleted)
? window.parent.OnUploadCompleted
: false);
var kc_Custom = (window.parent && window.parent.KCFinder)
? window.parent.KCFinder.callBack
: ((window.opener && window.opener.KCFinder)
? window.opener.KCFinder.callBack
: false);
if (kc_CKEditor)
kc_CKEditor(<?php echo $CKfuncNum ?>, '<?php echo $url ?>', '<?php echo $message ?>');
if (kc_FCKeditor)
kc_FCKeditor(<?php echo strlen($message) ? 1 : 0 ?>, '<?php echo $url ?>', '', '<?php echo $message ?>');
if (kc_Custom) {
if (<?php echo strlen($message) ?>) alert('<?php echo $message ?>');
kc_Custom('<?php echo $url ?>');
}
if (!kc_CKEditor && !kc_FCKeditor && !kc_Custom)
alert("<?php echo $message ?>");
</script>
</body>
</html><?php
}
protected function get_htaccess() {
return "<IfModule mod_php4.c>
php_value engine off
</IfModule>
<IfModule mod_php5.c>
php_value engine off
</IfModule>
";
}
}
?>
Thanks!

