new plugin: klj_ftp

This commit is contained in:
Abdulrahman
2019-01-03 22:33:14 +03:00
parent 2300a979d0
commit 20c527e05c
7 changed files with 2190 additions and 0 deletions

156
plugins/kj_ftp/admin_kjftp.html Executable file
View File

@@ -0,0 +1,156 @@
<!-- Breadcrumbs -->
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="./">{lang.R_CPINDEX}</a></li>
<li class="breadcrumb-item">{olang.R_KJ_FTP_OPTIONS}</li>
</ol>
<a href="#" class="btn btn-primary pull-(lang.DIR==ltr?right:left)" data-toggle="modal" data-target="#account_add_new">
<i class="fa fa-plus-circle"></i> {olang.KJ_FTP_ADD_NEW_ACCOUNT}
</a>
<div class="clearfix"></div>
<div id="accordion" class="mt-3" role="tablist" aria-multiselectable="true">
<LOOP NAME="ftp_accounts">
<div class="card mb-3">
<div class="card-header" role="tab" id="heading{{id}}">
<h5 class="mb-0">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{id}}" aria-expanded="true" aria-controls="collapse{{id}}" style="text-decoration: none">
<IF LOOP="active">
<i class="fa fa-check text-success" title="{olang.KJ_FTP_OPT_ACTIVE}" data-toggle="tooltip"></i>
<ELSE>
<i class="fa fa-pause-circle text-gray-dark"></i>
</IF>
<small class="badge badge-pill badge-dark">{{name}}</small> {{host}}
</a>
</h5>
</div>
<div id="collapse{{id}}" class="collapse " role="tabpanel" aria-labelledby="heading{{id}}">
<div class="card-body">
<!-- edit form -->
<form method="post" action="{action}">
<input type="hidden" value="{{id}}" name="id">
<div class="form-group">
<label for="name">{olang.KJ_FTP_OPT_NAME}</label>
<input type="text" class="form-control" name="name" id="name" aria-describedby="nameHelp" placeholder="" value="{{name}}">
<small id="nameHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_NAME_HELP}</small>
</div>
<div class="form-group">
<label for="host">{olang.KJ_FTP_OPT_HOST}</label>
<input type="text" class="form-control" name="host" id="host" placeholder="" aria-describedby="hostHelp" value="{{host}}">
<small id="hostHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_HOST_HELP}</small>
</div>
<div class="form-group">
<label for="username">{olang.KJ_FTP_OPT_USERNAME}</label>
<input type="text" class="form-control" name="username" id="username" placeholder="" value="{{username}}">
</div>
<div class="form-group">
<label for="password">{olang.KJ_FTP_OPT_PASSWORD}</label>
<input type="text" class="form-control" name="password" id="password" placeholder="" value="">
</div>
<div class="form-group">
<label for="port">{olang.KJ_FTP_OPT_PORT}</label>
<input type="text" class="form-control" name="port" id="port" placeholder="" value="{{port}}">
</div>
<div class="form-group">
<label for="root">{olang.KJ_FTP_OPT_ROOT}</label>
<input type="text" class="form-control" name="root" id="root" placeholder="" value="{{root}}">
<small id="rootHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_ROOT_HELP}</small>
</div>
<div class="form-group">
<label for="link">{olang.KJ_FTP_OPT_LINK}</label>
<input type="text" class="form-control" name="link" id="link" placeholder="" value="{{link}}">
<small id="linkHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_LINK_HELP}</small>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="passive"<IF LOOP="passive"> checked="checked"</IF>>
Passive
</label>
<small id="passiveHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_PASSIVE_HELP}</small>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="active"<IF LOOP="active"> checked="checked"</IF>>
{olang.KJ_FTP_OPT_ACTIVE}
</label>
<small id="activeHelp" class="form-text text-muted">{olang.KJ_FTP_OPT_ACTIVE_HELP}</small>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="ssl"<IF LOOP="ssl"> checked="checked"</IF>>
SSL
</label>
</div>
<input type="submit" name="submit" class="btn btn-primary mt-2" value="{lang.UPDATE}">
<input type="hidden" name="type" value="edit">
{H_FORM_KEYS}
</form>
<!-- end edit form-->
</div>
</div>
</div>
</LOOP>
</div>
<!-- new account modal -->
<div id="account_add_new" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="addNewAccount" aria-hidden="true">
<form method="post" action="{action}" id="add_account_form">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addNewAccount">{olang.KJ_FTP_ADD_NEW_ACCOUNT}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-info">
{olang.KJ_FTP_ADD_NEW_ACCOUNT_EXP}
</div>
{H_FORM_KEYS}
</div>
<div class="modal-footer">
<input type="hidden" name="type" value="new">
<input type="submit" name="submit" class="btn btn-primary" value="{lang.YES}">
</div>
</div>
</div>
</form>
</div>
<!-- end new account modal -->

374
plugins/kj_ftp/ftp.php Normal file
View File

@@ -0,0 +1,374 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license http://www.kleeja.com/license
*
*/
/**
* @ignore
*/
if (!defined('IN_COMMON'))
{
exit();
}
/**
* Make changes with files using FTP
*/
class kleeja_ftp
{
/**
* TimeOut before disconnection
*/
public $timeout = 30;
/**
* Move to this folder after connection
*/
public $root = '';
/**
* If enabled, debug mode will be activated
*/
public $debug = false;
/**
* FTP current connection handler
*/
private $handler = null;
private $unique_name = '';
private $link = '';
/**
* Connect to FTP server
*
* @param string $host FTP server address
* @param string $user FTP server username
* @param string $password FTP server password
* @param int $port FTP server port
* @param string $rootPath
* @param bool $passive
* @return bool|kleeja_ftp
* @internal param string $path FTP server path
*/
public function open($host, $user, $password, $port = 21, $rootPath = '/', $passive = true, $ssl = false, $timeout = 90)
{
$this->timeout = $timeout;
$this->debug = defined('DEV_STAGE');
#connect to the server
if($ssl)
{
$this->handler = @ftp_ssl_connect($host, $port, $this->timeout);
}
else
{
$this->handler = @ftp_connect($host, $port, $this->timeout);
}
if (!$this->handler)
{
// if($this->debug)
// {
// echo 'can not connect<br>';
// var_dump($this->handler);
//
// }
return false;
}
#pasv mode
@ftp_pasv($this->handler, $passive);
#login to the server
if (!ftp_login($this->handler, $user, $password))
{
// if($this->debug)
// {
// echo 'can not login<br>';
// var_dump($this->handler);
// }
return false;
}
#move to the path
$rootPath = trim($rootPath);
if($rootPath == '/')
{
$rootPath = '';
}
if ($rootPath != '')
{
if (substr($rootPath, -1, 1) == '/')
{
$rootPath = substr($rootPath, 0, -1);
}
}
$this->root = $rootPath;
if($this->root != '')
{
$this->link = 'http://' . $host . '/' . ltrim($rootPath, '/');
if (!$this->file_exists($this->root))
{
$this->create_folder('');
}
}
return $this;
}
/**
* Go to the given folder
* @param string $dir
* @return bool
*/
public function go_to($dir = '')
{
if ($dir && $dir !== '/')
{
if (substr($dir, -1, 1) == '/')
{
$dir = substr($dir, 0, -1);
}
}
return @ftp_chdir($this->handler, $dir);
}
/**
* Close current FTP connection
*/
public function close()
{
if (!$this->handler)
{
return;
}
ftp_quit($this->handler);
}
/**
* Get the current folder that we are in now
* @return string
*/
public function current_folder()
{
return ftp_pwd($this->handler);
}
/**
* Change the file or folder permission
* @param string $file
* @param int $perm
* @return bool
*/
public function chmod($file, $perm = 0644)
{
if (function_exists('ftp_chmod'))
{
$action = @ftp_chmod($this->handler, $perm, $this->_fixpath($file));
}
else
{
$chmod_cmd = 'CHMOD ' . base_convert($perm, 10, 8) . ' ' . $this->_fixpath($file);
$action = ftp_site($this->handler, $chmod_cmd);
}
return $action;
}
/**
* is file exists
* @return bool
*/
public function file_exists($file)
{
return ftp_size($this->handler, $this->_fixpath($file)) > -1;
}
/**
* fix the given path to be compatible with the FTP
* @param string $path
* @return string
*/
private function _fixpath($path)
{
return ($this->root != '' ? $this->root . '/' : '') . $path;
}
/**
* Delete given file
* @param string $file
* @return bool
*/
public function delete($file)
{
return @ftp_delete($this->handler, $this->_fixpath($file));
}
/**
* Create a file and write the given content to it
* @param string $filePath
* @param $content
* @return bool
*/
public function write($filePath, $content)
{
$cached_file = PATH . 'cache/cached_ftp_' . uniqid(time());
#make it as a cached file
$h = @fopen($cached_file, 'wb');
fwrite($h, $content);
@fclose($h);
$r = @ftp_put($this->handler, $this->_fixpath($filePath), $cached_file, FTP_BINARY);
kleeja_unlink($cached_file, true);
return $r;
}
/**
* Upload a local file to the FTP server
* @param string $local_file
* @param string $server_file
* @return bool
*/
public function upload($local_file, $server_file, $deleteLocal = true)
{
#Initate the upload
#TODO if slow, use ftp_put
$ret = ftp_nb_put($this->handler, $this->_fixpath($server_file), $local_file, FTP_BINARY);
while ($ret == FTP_MOREDATA)
{
#still uploading
if($this->debug)
{
print ftell($this->handler)."\n";
}
$ret = ftp_nb_continue($this->handler);
}
if($deleteLocal)
{
kleeja_unlink($local_file);
}
#bad uploading
if ($ret != FTP_FINISHED)
{
return false;
}
return true;
}
/**
* Rename a file
* @param string $old_file
* @param string $new_file
* @return bool
*/
public function rename($old_file, $new_file)
{
return @ftp_rename($this->handler, $this->_fixpath($old_file), $this->_fixpath($new_file));
}
/**
* Create a folder
* @param string $dir
* @param int $perm
* @return bool
*/
public function create_folder($dir, $perm = 0755)
{
// if($this->debug)
// {
// var_dump($this->_fixpath($dir));
// }
if(ftp_mkdir($this->handler, $this->_fixpath($dir)) === false)
{
return false;
}
$this->chmod($this->_fixpath($dir), $perm);
return true;
}
/**
* Delete the given folder
* @param string $dir
* @return bool
*/
public function delete_folder($dir)
{
return @ftp_rmdir($this->handler, $this->_fixpath($dir));
}
/**
* @param string $unique_name
*/
public function setUniqueName($unique_name)
{
$this->unique_name = $unique_name;
}
/**
* @return string
*/
public function getUniqueName()
{
return $this->unique_name;
}
/**
* @param string $link
*/
public function setLink($link)
{
if(trim($link) == '')
{
return;
}
if (substr($link, -1, 1) == '/')
{
$link = substr($link, 0, -1);
}
$this->link = $link;
}
/**
* @return string
*/
public function getLink($path)
{
return $this->link . '/' . $path;
}
}

View File

@@ -0,0 +1,845 @@
<?php
#includes important functions
include_once PATH . '/includes/up_helpers/others.php';
include_once PATH . '/includes/up_helpers/thumbs.php';
include_once PATH . '/includes/up_helpers/watermark.php';
include_once PATH . '/includes/up_helpers/remote_uploading.php';
class ftpUploader implements KleejaUploader
{
protected $messages = array();
protected $allowed_file_extensions = array();
protected $upload_fields_limit = 0;
protected $total_uploaded_files = 0;
/**
* set the allowed extensions of uploaded files
* @param array $allowed_file_extensions an array of allowed extensions, and sizes ['gif'=>122, 'png'=>2421 ..]
* @return void
*/
function setAllowedFileExtensions($allowed_file_extensions)
{
$this->allowed_file_extensions = $allowed_file_extensions;
}
/**
* get the allowed extensions of uploaded files
* @return array
*/
function getAllowedFileExtensions()
{
return $this->allowed_file_extensions;
}
/**
* set the allowed limit of the uploaded files
* @param int $limit
* @return void
*/
function setUploadFieldsLimit($limit)
{
$this->upload_fields_limit = $limit;
}
/**
* get the allowed limit of the uploaded files
* @return int
*/
function getUploadFieldsLimit()
{
return $this->upload_fields_limit;
}
/**
* add an information message to output it to the user
* @param string $message
* @return void
*/
function addInfoMessage($message)
{
array_push($this->messages, array($message, 'info'));
}
/**
* add an error message to output it to the user
* @param string $message
* @return void
*/
function addErrorMessage($message)
{
array_push($this->messages, array($message, 'error'));
}
/**
* get all the messages
* @return array
*/
function getMessages()
{
return $this->messages;
}
/**
* save the file information to the database
* @param array $fileInfo
* @return void
*/
function saveToDatabase($fileInfo)
{
global $SQL, $dbprefix, $config;
// $fileInfo =
// [
// 'saveToFolder'
// 'originalFileName'
// 'generatedFileName'
// 'fileSize'
// 'currentUserId'
// 'fileExtension
// 'ftpName'
// ];
// + to be added in this method and goes to generateOutputBox
// [
// 'DeleteCode'
// 'insertId'
// [
#sometime cant see file after uploading.. but ..
getKleejaFtpInstance()->chmod($fileInfo['saveToFolder'] . '/' . $fileInfo['generatedFileName'], 0644);
$fileInfo['DeleteCode'] = sha1($fileInfo['generatedFileName'] . uniqid());
$queryValues = array
(
'name' => $fileInfo['generatedFileName'],
'real_filename' => $fileInfo['originalFileName'],
'size' => intval($fileInfo['fileSize']),
'time' => time(),
'folder'=> 'ftp://' . $fileInfo['ftpName'] . ':' .$fileInfo['saveToFolder'],
'type' => $fileInfo['fileExtension'],
'user' => $fileInfo['currentUserId'],
'code_del' => $fileInfo['DeleteCode'],
'user_ip' => get_ip(),
'id_form' => $config['id_form'],
);
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_saveToDatabase_qr', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# insertion query
$insert_query = array(
'INSERT' => '`' . implode('` , `' , array_keys($queryValues)) . '`',
'INTO' => "{$dbprefix}files",
'VALUES' => "'" . implode("', '", array_map(array($SQL, 'escape'), array_values($queryValues))) . "'"
);
# do the query
$SQL->build($insert_query);
# inset id so it can be used in url like in do.php?id={id_for_url}
$fileInfo['insertId'] = $SQL->insert_id();
# update Kleeja stats
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => ($is_img ? "imgs=imgs+1" : "files=files+1") . ",sizes=sizes+" . intval($fileInfo['fileSize']) . ""
);
$SQL->build($update_query);
$this->generateOutputBox($fileInfo);
}
/**
* generate a box of the result and add it to addInfoMessage
* @param array $fileInfo
* @return void
*/
function generateOutputBox($fileInfo)
{
global $config, $lang;
// $fileInfo =
// [
// 'saveToFolder'
// 'originalFileName'
// 'generatedFileName'
// 'fileSize'
// 'currentUserId'
// 'fileExtension
// 'DeleteCode'
// 'insertId'
// [
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
# information of file, used for generating a url boxes
$file_info = array(
'::ID::' => $fileInfo['insertId'],
'::NAME::' => $fileInfo['generatedFileName'],
'::DIR::' => $fileInfo['saveToFolder'],
'::FNAME::' => $fileInfo['originalFileName'],
);
# show del code link box
$extra_del = '';
if ($config['del_url_file'])
{
$extra_del = get_up_tpl_box('del_file_code',
array(
'b_title' => $lang['URL_F_DEL'],
'b_code_link' => kleeja_get_link('del', array('::CODE::'=>$fileInfo['DeleteCode']))
)
);
}
//show imgs
if($is_img)
{
$img_html_result = '';
$img_html_result .= get_up_tpl_box('image_thumb',
array(
'b_title' => $lang['URL_F_THMB'],
'b_url_link'=> kleeja_get_link('image', $file_info),
'b_img_link'=> kleeja_get_link('thumb', $file_info)
)
);
#then show, image box
$img_html_result .= get_up_tpl_box('image',
array(
'b_title' => $lang['URL_F_IMG'],
'b_bbc_title'=> $lang['URL_F_BBC'],
'b_url_link'=> kleeja_get_link('image', $file_info),
)
);
#add del link box to the result if there is any
$img_html_result .= $extra_del;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_generateOutputBox_image_result', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#show success message
$this->addInfoMessage(
'<div class="up-box-title">'. $lang['IMG_DOWNLAODED'] . ': ' .
htmlspecialchars($fileInfo['originalFileName']) . '</div>' . "\n" .
$img_html_result
);
}
else
{
#then show other files
$else_html_result = get_up_tpl_box('file',
array(
'b_title' => $lang['URL_F_FILE'],
'b_bbc_title'=> $lang['URL_F_BBC'],
'b_url_link'=> kleeja_get_link('file', $file_info),
)
);
#add del link box to the result if there is any
$else_html_result .= $extra_del;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_generateOutputBox_file_result', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#show success message
$this->addInfoMessage(
'<div class="up-box-title">'. $lang['FILE_DOWNLAODED']. ': '
. htmlspecialchars($fileInfo['originalFileName']) . '</div>' . "\n" .
$else_html_result
);
}
$this->total_uploaded_files++;
}
/**
* here happens the magic, call this on upload submit
* @param int $uploadType upload from files input or links
* @todo watermark
* @return void
*/
function upload($uploadType)
{
global $usrcp, $config, $lang;
# when $uploadType = 1, then we upload from _file input
# if $uploadType = 2, then we uploading from url which is disabled by default and is buggy
#upload to this folder
$current_uploading_folder = $config['foldername'];
#current user id
$current_user_id = $usrcp->name() ? $usrcp->id() : '-1';
#is captcha is on?
$captcha_enabled = intval($config['safe_code']);
$return_now = false;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_upload_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# check folder our real folder
if(!getKleejaFtpInstance()->file_exists($current_uploading_folder))
{
if(!$this->make_folder($current_uploading_folder))
{
$this->addErrorMessage($lang['CANT_DIR_CRT']);
}
}
if($return_now)
{
return;
}
#no uploading yet, or just go to index.php, so we have make a new session
if(!$uploadType)
{
unset($_SESSION['FIILES_NOT_DUPLI'], $_SESSION['FIILES_NOT_DUPLI_LINKS']);
}
# is captcha on, and there is uploading going on
if($captcha_enabled && $uploadType)
{
#captcha is wrong
if(!kleeja_check_captcha())
{
$this->addErrorMessage($lang['WRONG_VERTY_CODE']);
return;
}
}
# to prevent flooding, user must wait, waiting-time is grapped from Kleeja settings, admin is exceptional
if(! user_can('enter_acp') && user_is_flooding($current_user_id))
{
$this->addErrorMessage(sprintf($lang['YOU_HAVE_TO_WAIT'],
$current_user_id == '-1' ? $config['guestsectoupload'] : $config['usersectoupload']));
return;
}
#detect flooding
if ($uploadType == 1 && isset($_SESSION['FIILES_NOT_DUPLI']))
{
if(!empty($_SESSION['FIILES_NOT_DUPLI']) && $_SESSION['FIILES_NOT_DUPLI'] == sha1(serialize(array_column($_FILES, 'name'))))
{
unset($_SESSION['FIILES_NOT_DUPLI']);
redirect('./');
return;
}
}
if ($uploadType == 2 && isset($_SESSION['FIILES_NOT_DUPLI_LINKS']))
{
if($_SESSION['FIILES_NOT_DUPLI_LINKS'] == sha1(serialize($_POST)))
{
unset($_SESSION['FIILES_NOT_DUPLI_LINKS']);
redirect('./');
return;
}
}
# flooding code, making sure every ok session is cleared
if ($uploadType == 1 && sizeof($_FILES) > 0)
{
$_SESSION['FIILES_NOT_DUPLI'] = sha1(serialize(array_column($_FILES, 'name')));
}
elseif($uploadType == 2)
{
$_SESSION['FIILES_NOT_DUPLI_LINKS'] = sha1(serialize($_POST));
}
#now close session to let user open any other page in Kleeja
session_write_close();
# do upload
switch($uploadType)
{
#uploading from a _files input
default:
case 1:
if(!empty($_FILES['file']['tmp_name']))
{
$_FILES['file'][0] = $_FILES['file'];
}
# loop the uploaded files
for($i=0; $i<=$this->getUploadFieldsLimit(); $i++)
{
//no file!
if(empty($_FILES['file_' . $i . '_']['tmp_name']) && empty($_FILES['file'][$i]['tmp_name']))
{
continue;
}
$this->uploadTypeFile($i, $current_uploading_folder, $current_user_id);
}
break;
#uploading from a url text-input
case 2:
#if not enabled, quit it
if($config['www_url'] != 1)
{
break;
}
#loop text inputs
for($i=0; $i<=$this->getUploadFieldsLimit(); $i++)
{
$this->uploadTypeUrl($i, $current_uploading_folder, $current_user_id);
}
break;
}
# well, no file uploaded, ask user to choose a file before submit
if($this->total_uploaded_files == 0 && sizeof($this->messages) == 0)
{
$this->addErrorMessage($lang['CHOSE_F']);
}
}
/**
* upload a file from $_FILES
* @param integer $fieldNumber as in file[i]
* @param $current_uploading_folder
* @param $current_user_id
*/
function uploadTypeFile($fieldNumber, $current_uploading_folder, $current_user_id)
{
global $config, $lang;
$fileInfo = array(
'saveToFolder',
'originalFileName',
'generatedFileName',
'fileSize',
'currentUserId',
'fileExtension'
);
$fileInfo['saveToFolder'] = $current_uploading_folder;
$fileInfo['currentUserId'] = $current_user_id;
if(!isset($_FILES['file_' . $fieldNumber . '_']) && isset($_FILES['file'][$fieldNumber]))
{
$_FILES['file_' . $fieldNumber . '_'] = $_FILES['file'][$fieldNumber];
}
# file name
$fileInfo['originalFileName'] = isset($_FILES['file_' . $fieldNumber . '_']['name'])
? htmlspecialchars(str_replace(array(';',','), '', $_FILES['file_' . $fieldNumber . '_']['name']))
: '';
if(empty($fileInfo['originalFileName']))
{
return;
}
# get the extension of file
$fileInfo['fileExtension'] = strtolower(array_pop(explode('.', $fileInfo['originalFileName'])));
# them the size
$fileInfo['fileSize'] = !empty($_FILES['file_' . $fieldNumber . '_']['size'])
? intval($_FILES['file_' . $fieldNumber . '_']['size'])
: 0;
# get the other filename, changed depend on kleeja settings
$fileInfo['generatedFileName'] = change_filename_decoding($fileInfo['originalFileName'], $fieldNumber, $fileInfo['fileExtension']);
# filename templates {rand:..}, {date:..}
$fileInfo['generatedFileName'] = change_filename_templates(trim($config['prefixname']) . $fileInfo['generatedFileName']);
# file exists before? change it a little
if(getKleejaFtpInstance()->file_exists($current_uploading_folder . '/' . $fileInfo['generatedFileName']))
{
$fileInfo['generatedFileName'] = change_filename_decoding(
$fileInfo['generatedFileName'],
$fieldNumber, $fileInfo['fileExtension'],
'exists'
);
}
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_uploadTypeFile_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# now, let process it
if(!in_array(strtolower($fileInfo['fileExtension']), array_keys($this->getAllowedFileExtensions())))
{
# guest
if($current_user_id == '-1')
{
$this->addErrorMessage(
sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension'])
. '<br> <a href="' . ($config['mod_writer'] ? "register.html" : "ucp.php?go=register") .
'" title="' . htmlspecialchars($lang['REGISTER']) . '">' . $lang['REGISTER'] . '</a>'
);
}
# a member
else
{
$this->addErrorMessage(sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']));
}
}
# bad chars in the filename
elseif(preg_match ("#[\\\/\:\*\?\<\>\|\"]#", $fileInfo['generatedFileName']))
{
$this->addErrorMessage(sprintf($lang['WRONG_F_NAME'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check file extension for bad stuff
elseif(ext_check_safe($_FILES['file_' . $fieldNumber . '_']['name']) == false)
{
$this->addErrorMessage(sprintf($lang['WRONG_F_NAME'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check the mime-type for the file
elseif(check_mime_type($_FILES['file_' . $fieldNumber . '_']['type'], $fileInfo['fileExtension'], $_FILES['file_' . $fieldNumber . '_']['tmp_name']) == false)
{
$this->addErrorMessage(sprintf($lang['NOT_SAFE_FILE'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check file size
elseif($this->getAllowedFileExtensions()[$fileInfo['fileExtension']] > 0
&& $fileInfo['fileSize'] >= $this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
{
$this->addErrorMessage(sprintf(
$lang['SIZE_F_BIG'],
htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name']),
readable_size($this->getAllowedFileExtensions()[$fileInfo['fileExtension']]))
);
}
# no errors, so upload it
else
{
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_uploadTypeFile_2nd', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#cache it locally for now
$localFile = PATH . 'cache/' . uniqid(time()) . '.' . $fileInfo['fileExtension'];
# now, upload the file
$file = move_uploaded_file($_FILES['file_' . $fieldNumber . '_']['tmp_name'], $localFile);
if ($file)
{
//watermark + thumbnail
if($is_img)
{
$this->generateThumbnail(
$localFile,
$fileInfo['fileExtension'],
$current_uploading_folder . '/thumbs/' . $fileInfo['generatedFileName']
);
}
if($config['write_imgs'] != 0)
{
$this->generateWatermark($localFile, $fileInfo['fileExtension']);
}
getKleejaFtpInstance()->upload($localFile, $current_uploading_folder . "/" . $fileInfo['generatedFileName']);
$fileInfo['ftpName'] = getKleejaFtpInstance()->getUniqueName();
$this->saveToDatabase($fileInfo);
}
else
{
$this->addErrorMessage(sprintf($lang['CANT_UPLAOD'], $fileInfo['originalFileName']));
}
}
}
/**
* upload a file from a URL
* @param $fieldNumber
* @param $current_uploading_folder
* @param $current_user_id
*/
function uploadTypeUrl($fieldNumber, $current_uploading_folder, $current_user_id)
{
global $config, $lang;
$fileInfo = array(
'saveToFolder',
'originalFileName',
'generatedFileName',
'fileSize',
'currentUserId',
'fileExtension'
);
$fileInfo['saveToFolder'] = $current_uploading_folder;
$fileInfo['currentUserId'] = $current_user_id;
if(p('file_' . $fieldNumber . '_') == '' || p('file_' . $fieldNumber . '_') == $lang['PAST_URL_HERE'])
{
return;
}
# get file name
$fileInfo['originalFileName'] = basename(p('file_' . $fieldNumber . '_'));
# file extension, type
$fileExtensions = array_map('strtolower', explode(".", $fileInfo['originalFileName']));
if(sizeof($fileExtensions) > 1 && in_array($fileExtensions[sizeof($fileExtensions)-1], array('html', 'php', 'html')))
{
$fileInfo['fileExtension'] = strtolower($fileExtensions[sizeof($fileExtensions)-2]);
}
else if(sizeof($fileExtensions) > 0)
{
$fileInfo['fileExtension'] = strtolower($fileExtensions[sizeof($fileExtensions)-1]);
}
else
{
$fileInfo['fileExtension'] = ''; //what to do?
}
# change to another filename depend on kleeja settings
$fileInfo['generatedFileName'] = change_filename_decoding($fileInfo['originalFileName'], $fieldNumber, $fileInfo['fileExtension']);
$fileInfo['generatedFileName'] = change_filename_templates(trim($config['prefixname']) . $fileInfo['generatedFileName']);
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_uploadTypeUrl_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#forbbiden type ? quit it
if(!in_array(strtolower($fileInfo['fileExtension']), array_keys($this->getAllowedFileExtensions())))
{
if($current_user_id == '-1')
{
$this->addErrorMessage(
sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']) .
'<br> <a href="' . ($config['mod_writer'] ? "register.html" : "ucp.php?go=register") . '">' .
$lang['REGISTER'] . '</a>'
);
}
# a member
else
{
$this->addErrorMessage(sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']));
}
}
# file exists before ? quit it
elseif(getKleejaFtpInstance()->file_exists($current_uploading_folder . '/' . $fileInfo['generatedFileName']))
{
$fileInfo['generatedFileName'] = change_filename_decoding(
$fileInfo['generatedFileName'],
$fieldNumber, $fileInfo['fileExtension'],
'exists'
);
}
# no errors, ok, lets upload now
else
{
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
is_array($plugin_run_result = Plugins::getInstance()->run('ftpUploader_uploadTypeUrl_2nd', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#no prefix ? http or even ftp, then add one
if(!in_array(strtolower(substr(p('file_' . $fieldNumber . '_'), 0, 4)), array('http', 'ftp:')))
{
$_POST['file_' . $fieldNumber . '_'] = 'http://' . p('file_' . $fieldNumber . '_');
}
#get size, if big quit it
$fileInfo['fileSize'] = get_remote_file_size(p('file_' . $fieldNumber . '_'));
if($this->getAllowedFileExtensions()[$fileInfo['fileExtension']] > 0 && $fileInfo['fileSize'] >= $this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
{
$this->addErrorMessage(sprintf(
$lang['SIZE_F_BIG'],
p('file_' . $fieldNumber . '_'),
readable_size($this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
));
}
else
{
#cache it locally for now
$localFile = PATH . 'cache/' . uniqid(time()) . '.' . $fileInfo['fileExtension'];
#get remote data, if no data quit it
$data = fetch_remote_file(
p('file_' . $fieldNumber . '_'),
$localFile,
15,
false,
2,
true
);
if($data === false)
{
$this->addErrorMessage($lang['URL_CANT_GET']);
}
else
{
//watermark + thumbnail
if($is_img)
{
$this->generateThumbnail(
$localFile,
$fileInfo['fileExtension'],
$current_uploading_folder . '/thumbs/' . $fileInfo['generatedFileName']
);
if($config['write_imgs'] != 0)
{
$this->generateWatermark($localFile, $fileInfo['fileExtension']);
}
}
getKleejaFtpInstance()->upload($localFile, $current_uploading_folder . "/" . $fileInfo['generatedFileName']);
$fileInfo['ftpName'] = getKleejaFtpInstance()->getUniqueName();
$this->saveToDatabase($fileInfo);
}
}
}
}
function generateThumbnail($source_path, $ext, $saveToThisFtpPath)
{
global $config;
// var_dump($source_path);
# get default thumb dimensions
$thmb_dim_w = $thmb_dim_h = 150;
if(strpos($config['thmb_dims'], '*') !== false)
{
list($thmb_dim_w, $thmb_dim_h) = array_map('trim', explode('*', $config['thmb_dims']));
}
$localThumbFile = $source_path.'.thumb.'.$ext;
# generate a thumbnail
helper_thumb($source_path, $ext, $localThumbFile, $thmb_dim_w, $thmb_dim_h);
if(file_exists($localThumbFile))
{
getKleejaFtpInstance()->upload($localThumbFile, $saveToThisFtpPath);
}
}
function generateWatermark($localFile, $ext)
{
helper_watermark(
$localFile,
$ext
);
}
function make_folder($folder)
{
#try to make a new upload folder
$folders = explode('/', $folder);
$path = '';
foreach ($folders as $sub_folder)
{
getKleejaFtpInstance()->create_folder($path . $sub_folder);
getKleejaFtpInstance()->create_folder($path . $sub_folder . '/thumbs');
$this->generate_htaccess($path . $sub_folder);
$indexHtml = '<a href="http://kleeja.com"><p>KLEEJA ..</p></a>';
getKleejaFtpInstance()->write($path . $sub_folder . "/index.html", $indexHtml);
getKleejaFtpInstance()->write($path . $sub_folder . "/thumbs/index.html", $indexHtml);
$path .= $sub_folder . '/';
}
return true;
}
function generate_htaccess($folder)
{
#data for the htaccess
$htaccess_data = "<Files ~ \"^.*\.(php|php*|cgi|pl|phtml|shtml|sql|asp|aspx)\">\nOrder allow,deny\nDeny from all\n</Files>\n<IfModule mod_php4.c>\nphp_flag engine off\n</IfModule>\n<IfModule mod_php5.c>\nphp_flag engine off\n</IfModule>\nRemoveType .php .php* .phtml .pl .cgi .asp .aspx .sql";
getKleejaFtpInstance()->write($folder . "/.htaccess", $htaccess_data);
getKleejaFtpInstance()->write($folder . "/thumbs/.htaccess", $htaccess_data);
}
}

BIN
plugins/kj_ftp/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

55
plugins/kj_ftp/index.html Executable file
View File

@@ -0,0 +1,55 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box"><h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"><span style="font-size: 140%">Powered by <a target="_blank"
href="http://www.kleeja.com">Kleeja</a></span>
</div>
</body>
</html>

573
plugins/kj_ftp/init.php Normal file
View File

@@ -0,0 +1,573 @@
<?php
# kleeja plugin
# kj_ftp
# version: 1.0
# developer: kleeja team
# prevent illegal run
if (!defined('IN_PLUGINS_SYSTEM')) {
exit();
}
# 1- create_folder, generate htaccess: done
# 2- kleeja_unlink: done
# plugin basic information
$kleeja_plugin['kj_ftp']['information'] = array(
# the casucal name of this plugin, anything can a human being understands
'plugin_title' => array(
'en' => 'Kleeja Multi-FTP Uploading',
'ar' => 'تحميل FTP متعدد'
),
# who is developing this plugin?
'plugin_developer' => 'kleeja.com',
# this plugin version
'plugin_version' => '1.1',
# explain what is this plugin, why should i use it?
'plugin_description' => array(
'en' => 'Add Multi-FTP support to Kleeja',
'ar' => 'إضافة دعم التحميل لعدة FTP في كليجا'
),
# min version of kleeja that's required to run this plugin
'plugin_kleeja_version_min' => '2.0',
# max version of kleeja that support this plugin, use 0 for unlimited
'plugin_kleeja_version_max' => '3.0',
# should this plugin run before others?, 0 is normal, and higher number has high priority
'plugin_priority' => 0
);
//after installation message, you can remove it, it's not required
$kleeja_plugin['kj_ftp']['first_run']['ar'] = "
شكراً لاستخدامك إضافة الـFTP المتعدد لكليجا، قم بمراسلتنا بالأخطاء عند ظهورها على البريد: <br>
info@kleeja.com
";
$kleeja_plugin['kj_ftp']['first_run']['en'] = "
Thank you for using our plugin, if you encounter any bugs and errors, contact us: <br>
info@kleeja.com
";
# plugin installation function
$kleeja_plugin['kj_ftp']['install'] = function ($plg_id) {
global $dbprefix, $SQL;
//create table
$sql = "CREATE TABLE IF NOT EXISTS `{$dbprefix}kj_ftp_info` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`host` varchar(199) COLLATE utf8_bin DEFAULT NULL,
`username` varchar(199) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(199) COLLATE utf8_bin DEFAULT NULL,
`port` int(4) DEFAULT '21',
`root` varchar(199) COLLATE utf8_bin DEFAULT '',
`passive` tinyint(1) DEFAULT '1',
`ssl` tinyint(1) DEFAULT '1',
`timeout` int(4) DEFAULT '60',
`link` varchar(199) COLLATE utf8_bin DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '0',
`group` int(4) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;";
$SQL->query($sql);
//new language variables
add_olang(array(
'R_KJ_FTP_OPTIONS' => 'تحميل الـFTP المتعدد',
#
'KJ_FTP_OPT_NAME' => 'الإسم الثابت',
'KJ_FTP_OPT_NAME_HELP' => 'كليجا تستخدم الإسم الثابت لحفظ وجلب الملفات، عند تغيير الإسم الثابت لن نستطيع جلب الملفات! عدل الإسم في حالة واحدة فقط، وهي لربط ملفات سابقة بحساب قديم تم حذفه.',
'KJ_FTP_OPT_HOST' => 'الخادم',
'KJ_FTP_OPT_HOST_HELP' => ' مثل: kleeja.com أو سب دومين sub.kleeja.com أو آي بي 188.54.12.11',
'KJ_FTP_OPT_USERNAME' => 'اسم المستخدم',
'KJ_FTP_OPT_PASSWORD' => 'كلمة المرور (مخفية، أكتب جديدة فقط لو أردت التغيير)',
'KJ_FTP_OPT_PORT' => 'منفذ',
'KJ_FTP_OPT_ROOT' => 'المسار الجذر',
'KJ_FTP_OPT_ROOT_HELP' => 'المسار الذي ستقوم كليجا بإنشاء مجلد uploads داخله، غالباً دعه فارغ',
'KJ_FTP_OPT_PASSIVE_HELP' => 'وضع FTP الآمن, قد يكون أبطئ',
'KJ_FTP_OPT_ACTIVE' => 'مُفعل',
'KJ_FTP_OPT_ACTIVE_HELP' => 'الحساب غير المفعل لن يستلم تحميلات جديدة ولكن سيتم جلب الملفات التي تم تحميلها مسبقاً منه.',
'KJ_FTP_OPT_LINK' => 'الرابط الفعلي',
'KJ_FTP_OPT_LINK_HELP' => 'مثل: http://kleeja.com أو https://www.example.com/ftp1، لو ترك فارغاً سيتم إستخدام إنتاج رابط من الخادم ومجلد الروت.',
'KJ_FTP_ADD_NEW_ACCOUNT' => 'أضف حساب FTP جديد',
'KJ_FTP_ADD_NEW_ACCOUNT_EXP' => ' هل أنت متأكد من إضافة حساب FTP جديد؟<br><small>يمكنك إضافة بيانات الحساب بعد الإضافة وتعديل الحساب.</small>',
'KJ_FTP_ACCOUNT_ADDED' => 'تم إضافة الحساب بنجاح',
'KJ_FTP_ACCOUNT_UPDATED' => 'تم تحديث الحساب بنجاح',
'KJ_FTP_ACCOUNT_NAME_CONFLICT' => 'الأسم الثابت موجود في حساب آخر! لايمكنك إستخدام اسم ثابت واحد في حسابين',
#
'KJ_FTP_NO_ACTIVE_ACCOUNTS_NOTE' => 'لآنه لايوجد أي حساب FTP تم تفعيله للتحميل، فإن كليجا ستستخدم نظام التحميل الإفتراضي المحلي. لجعل كليجا تقوم بالتحميل بإستخدام الإضافة، <a href="./?cp=kj_ftp_options">قم بتفعيل حساب FTP للتحميل</a> الآن!',
),
'ar',
$plg_id);
add_olang(array(
'R_KJ_FTP_OPTIONS' => 'KJ - Multi-FTP Uploading',
#
'KJ_FTP_OPT_NAME' => 'Unique Name',
'KJ_FTP_OPT_NAME_HELP' => 'Kleeja uses this name to identify that a file is related to this FTP account. Changing it will ruin the old files connection. Only edit this if you want to recover a connection of an old FTP account that has been deleted.',
'KJ_FTP_OPT_HOST' => 'Host',
'KJ_FTP_OPT_HOST_HELP' => ' Like: kleeja.com or a subdomain: sub.kleeja.com or an IP: 188.54.12.11',
'KJ_FTP_OPT_USERNAME' => 'Username',
'KJ_FTP_OPT_PASSWORD' => 'Password (hidden, type a new password only you want to change it)',
'KJ_FTP_OPT_PORT' => 'Port',
'KJ_FTP_OPT_ROOT' => 'Root Path',
'KJ_FTP_OPT_ROOT_HELP' => 'The path where Kleeja will create "uploads" folder in. Usually keeping it empty is fine.',
'KJ_FTP_OPT_PASSIVE_HELP' => 'Secure Passive FTP mode, slower.',
'KJ_FTP_OPT_ACTIVE' => 'Active',
'KJ_FTP_OPT_ACTIVE_HELP' => 'Inactive account will not receive new uploads to it, but will continue serving previous upload from it.',
'KJ_FTP_OPT_LINK' => 'Direct Link',
'KJ_FTP_OPT_LINK_HELP' => 'Link: http://kleeja.com or https://www.example.com/ftp1; If left empty, we will try to generate a link from the ftp host and given root folder.',
'KJ_FTP_ADD_NEW_ACCOUNT' => 'Add New FTP Account',
'KJ_FTP_ADD_NEW_ACCOUNT_EXP' => 'Are you sure of adding a new FTP account? <br><small>You can edit the account information after adding it.</small>',
'KJ_FTP_ACCOUNT_ADDED' => 'The FTP account has been added successfully!',
'KJ_FTP_ACCOUNT_UPDATED' => 'The FTP account has been updated successfully!',
'KJ_FTP_ACCOUNT_NAME_CONFLICT' => 'The unique name is existed before, you can not have two accounts with same unique name!',
#
'KJ_FTP_NO_ACTIVE_ACCOUNTS_NOTE' => 'Because you did not activate any FTP account, Kleeja will fallback to the default local uploading method. To make Kleeja Use FTP uploading method, <a href="./?cp=kj_ftp_options">activate an FTP account</a> now!',
),
'en',
$plg_id);
};
//plugin update function, called if plugin is already installed but version is different than current
$kleeja_plugin['kj_ftp']['update'] = function ($old_version, $new_version) {
// if(version_compare($old_version, '0.5', '<')){
// //... update to 0.5
// }
//
// if(version_compare($old_version, '0.6', '<')){
// //... update to 0.6
// }
//you could use update_config, update_olang
};
# plugin uninstalling, function to be called at uninstalling
$kleeja_plugin['kj_ftp']['uninstall'] = function ($plg_id) {
//delete options
// delete_config(array(
// 'kj_ftp_home_meta_description',
// 'kj_ftp_home_meta_keywords'
// ));
delete_olang(null, null, $plg_id);
};
# plugin functions
$kleeja_plugin['kj_ftp']['functions'] = array(
//add to admin menu
'begin_admin_page' => function ($args)
{
$adm_extensions = $args['adm_extensions'];
$ext_icons = $args['ext_icons'];
$adm_extensions[] = 'kj_ftp_options';
$ext_icons['kj_ftp_options'] = 'cloud-upload';
return compact('adm_extensions', 'ext_icons');
},
'not_exists_kj_ftp_options' => function()
{
$include_alternative = dirname(__FILE__) . '/kj_ftp_options.php';
return compact('include_alternative');
},
'begin_index_page' => function()
{
if(defined('DISABLE_KLJ_FTP')){
return;
}
$uploadingMethodClass = dirname(__FILE__) . '/ftpUploader.php';
return compact('uploadingMethodClass');
},
'kleeja_get_link_func2' => function($args)
{
if(defined('DISABLE_KLJ_FTP')){
return;
}
global $config;
if(($args['pid'] == 'image' || $args['pid'] == 'thumb') && $config['id_form_img'] == 'direct'){
$realFolder = str_replace(array_keys($args['extra']), array_values($args['extra']), $args['links'][$args['pid']]);
$uniqueName = '';
if(strpos($realFolder, 'ftp://') !== false)
{
$afterFTP = explode('ftp://', $realFolder, 2);
$folder = explode(':', $afterFTP[1], 2);
$uniqueName = $folder[0];
$realFolder = $folder[1];
}
if(empty($uniqueName)){
$return_link = getKleejaFtpInstance()->getLink('') . $realFolder;
}else {
$return_link = getKleejaFtpLink($uniqueName, $realFolder);
}
return compact('return_link');
}
},
'down_go_page' => function($args)
{
if(defined('DISABLE_KLJ_FTP')){
return;
}
if(strpos($args['f'], 'ftp://') !== false)
{
define('MAKE_DOPHP_301_HEADER', true);
$afterFTP = explode('ftp://', $args['f'], 2);
$filename = $args['n'];
$folder = explode(':', $afterFTP[1], 2);
$uniqueName = $folder[0];
$realFolder = ig('thmb') || ig('thmbf') ? $folder[1] . '/thumbs' : $folder[1];
$path_file = getKleejaFtpLink($uniqueName, $realFolder, $filename);
return compact('path_file');
}
},
'kleeja_unlink_func' => function($args)
{
if(defined('DISABLE_KLJ_FTP')){
return;
}
if(strpos($args['filePath'], 'ftp://') !== false)
{
$afterFTP = explode('ftp://', $args['filePath'], 2);
$path = explode(':', $afterFTP[1], 2);
$uniqueName = $path[0];
$filePath = $path[1];
$ftpAccount = getKleejaFtpAccount($uniqueName);
getKleejaFtpAccountInstance($ftpAccount)->delete($filePath);
// getKleejaFtpAccountInstance($ftpAccount)->close();
$return = true;
return compact('return');
}
},
'end_common' => function()
{
global $dbprefix, $SQL;
if(!
$SQL->num_rows(
$SQL->query("SELECT active FROM {$dbprefix}kj_ftp_info WHERE active=1")
)
){
define('DISABLE_KLJ_FTP', true);
}
},
'stats_start_admin' => function($args)
{
$ADM_NOTIFICATIONS = $args['ADM_NOTIFICATIONS'];
if(defined('DISABLE_KLJ_FTP')) {
global $lang, $olang;
$ADM_NOTIFICATIONS['kljFtpNoActive'] = array(
'id' => 'kljFtpNoActive',
'msg_type'=> 'info',
'title'=> $lang['NOTE'] . ' (' . $olang['R_KJ_FTP_OPTIONS'] . ')',
'msg'=> $olang['KJ_FTP_NO_ACTIVE_ACCOUNTS_NOTE']
);
}else{
unset($ADM_NOTIFICATIONS['htaccess_u'], $ADM_NOTIFICATIONS['htaccess_t'], $ADM_NOTIFICATIONS['no_thumbs']);
}
return compact('ADM_NOTIFICATIONS');
},
//support video plugin
'plugin:video_player:do_display' => function($args){
$folder = $args['file_info']['folder'];
$filename = $args['file_info']['name'];
if(strpos($folder, 'ftp://') !== false)
{
$afterFTP = explode('ftp://', $folder, 2);
$path = explode(':', $afterFTP[1], 2);
$uniqueName = $path[0];
$realFolder = $path[1];
$video_path = getKleejaFtpLink($uniqueName, $realFolder, $filename);
return compact('video_path');
}
},
//support pdf plugin
'plugin:pdf_viewer:do_display' => function($args){
$folder = $args['file_info']['folder'];
$filename = $args['file_info']['name'];
if(strpos($folder, 'ftp://') !== false)
{
$afterFTP = explode('ftp://', $folder, 2);
$path = explode(':', $afterFTP[1], 2);
$uniqueName = $path[0];
$realFolder = $path[1];
$pdf_path = getKleejaFtpLink($uniqueName, $realFolder, $filename);
return compact('pdf_path');
}
}
);
if(!function_exists('getKleejaFtpInstance'))
{
/**
* @return kleeja_ftp|null
*/
function getKleejaFtpInstance()
{
if (!class_exists('kleeja_ftp'))
{
require_once dirname(__FILE__) . '/ftp.php';
}
/** @var kleeja_ftp $kljFtp */
static $kljFtp = null;
if (is_null($kljFtp))
{
global $dbprefix, $SQL, $cache;
##### ------ > cached random, solve inadequate mySQL RAND.
if (!($ftp_accounts = $cache->get('klj_ftp::ftp_names')))
{
$query = array(
'SELECT' => 'k.name',
'FROM' => "`{$dbprefix}kj_ftp_info` k",
'WHERE' => 'k.active = 1'
);
$result = $SQL->build($query);
$ftp_accounts = array();
while($row=$SQL->fetch_array($result))
{
array_push($ftp_accounts, $row['name']);
}
$SQL->freeresult($result);
$cache->save('klj_ftp::ftp_names', $ftp_accounts);
}
if (sizeof($ftp_accounts) == 0) {
kleeja_show_error(102, 'NO FTP ACCOUNT FOUND!', __FILE__, __LINE__);
return null;
}
####
//random
shuffle($ftp_accounts);
shuffle($ftp_accounts);
shuffle($ftp_accounts);
$ftp_account = getKleejaFtpAccount($ftp_accounts[0]);
$kljFtp = new kleeja_ftp();
$connect = $kljFtp->open(
$ftp_account['host'],
$ftp_account['username'],
$ftp_account['password'],
$ftp_account['port'],
$ftp_account['root'],
$ftp_account['passive'] == 1,
$ftp_account['ssl'] == 1,
$ftp_account['timeout']
);
if(!$connect){
kleeja_show_error(102, 'FTP ACCOUNT CAN NOT CONNECT (' . $ftp_account['name'] . ')!', __FILE__, __LINE__);
}
$kljFtp->setUniqueName($ftp_account['name']);
$kljFtp->setLink($ftp_account['link']);
register_shutdown_function(function() { getKleejaFtpInstance()->close(); } );
}
return $kljFtp;
}
}
if(!function_exists('getKleejaFtpAccountInstance'))
{
/**
* @return kleeja_ftp|null
*/
function getKleejaFtpAccountInstance($ftp_account)
{
if (!class_exists('kleeja_ftp'))
{
require_once dirname(__FILE__) . '/ftp.php';
}
/** @var kleeja_ftp $kljFtp */
static $kljFtp = null;
//
if ($kljFtp === null || $kljFtp->getUniqueName() !== $ftp_account['name'])
{
$kljFtp = new kleeja_ftp();
$connect = $kljFtp->open(
$ftp_account['host'],
$ftp_account['username'],
$ftp_account['password'],
$ftp_account['port'],
$ftp_account['root'],
$ftp_account['passive'] == 1,
$ftp_account['ssl'] == 1,
$ftp_account['timeout']
);
if(!$connect){
kleeja_show_error(102, 'FTP ACCOUNT CAN NOT CONNECT (' . $ftp_account['name'] . ')!', __FILE__, __LINE__);
}
$kljFtp->setUniqueName($ftp_account['name']);
$kljFtp->setLink($ftp_account['link']);
register_shutdown_function(function() use($kljFtp) { $kljFtp->close(); } );
}
return $kljFtp;
}
}
if(!function_exists('getKleejaFtpAccount'))
{
function getKleejaFtpAccount($uniqueName)
{
global $dbprefix, $SQL;
$query = array(
'SELECT' => 'k.*',
'FROM' => "`{$dbprefix}kj_ftp_info` k",
'WHERE' => "k.name = '" . $SQL->escape($uniqueName) . "'",
'LIMIT' => '1'
);
$result = $SQL->build($query);
if($SQL->num_rows($result))
{
return $SQL->fetch_array($result);
}
return false;
}
}
if(!function_exists('getKleejaFtpLink'))
{
function getKleejaFtpLink($uniqueName, $folder, $filename = '')
{
$ftp_account = getKleejaFtpAccount($uniqueName);
if($ftp_account == false)
{
return '...' . $uniqueName . '...';
}
$link = !empty($ftp_account['link']) ? trim($ftp_account['link']) : '';
$host = trim($ftp_account['host']);
$rootPath = trim($ftp_account['root']);
if($link != '')
{
return ltrim($link, '/') . '/' . $folder . ($filename !== '' ? '/' . $filename : '');
}
if ($rootPath != '')
{
if (substr($rootPath, -1, 1) == '/')
{
$rootPath = substr($rootPath, 0, -1);
}
}
return $host . '/' . $rootPath . '/' . $folder . ($filename !== '' ? '/' . $filename : '');
}
}

View File

@@ -0,0 +1,187 @@
<?php
// not for directly open
if (!defined('IN_ADMIN'))
{
exit;
}
if (intval($userinfo['founder']) !== 1) {
kleeja_admin_err($lang['HV_NOT_PRVLG_ACCESS'], ADMIN_PATH.'?cp='.basename(__FILE__, '.php'));
exit;
}
#current case
$current_case = g('case');
#current template
$stylee = 'admin_kjftp';
#template folder path
$styleePath = dirname(__FILE__);
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php');
$H_FORM_KEYS = kleeja_add_form_key('adm_kj_ftp');
if(ip('submit'))
{
$current_case = p('type') == 'new' ? 'new' : 'edit';
if(!kleeja_check_form_key('adm_kj_ftp', 3600))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
$ERRORS = false;
switch ($current_case)
{
/**
* show a list of current ftp accounts
*/
default:
case 'list':
#TODO show a error if no active account exists
//There is no active FTP account! activate an account or disable this plugin to use standard local files uploading system.
$query = array(
'SELECT' => 'k.*',
'FROM' => "`{$dbprefix}kj_ftp_info` k",
'ORDER BY' => 'k.id ASC'
);
$result = $SQL->build($query);
$result_number = $SQL->num_rows($result);
$ftp_accounts = array();
if($result_number > 0)
{
while($row=$SQL->fetch_array($result))
{
unset($row['password']);
$ftp_accounts[] = $row;
}
}
$SQL->free();
break;
/**
* no need!
*/
case 'delete':
break;
/**
* add new ftp account
*/
case 'new':
//is this enough ?
$unique_name = uniqid();
$insert_query = array(
'INSERT' => 'name, host',
'INTO' => "{$dbprefix}kj_ftp_info",
'VALUES' => "'$unique_name', 'example.com'"
);
if ($SQL->build($insert_query)) {
$last_user_id = $SQL->insert_id();
kleeja_admin_info($olang['KJ_FTP_ACCOUNT_ADDED'], true, '', true, $action, 3);
}
break;
case 'edit':
#save, show info
$data = array(
'name' => p('name'),
'host' => p('host'),
'username' => p('username'),
'password' => p('password'),
'link' => p('link'),
'port' => p('port', 'int'),
'root' => p('root'),
'passive' => ip('passive') ? 1 : 0,
'active' => ip('active') ? 1 : 0,
'ssl' => ip('ssl') ? 1 : 0,
);
if($data['port'] == 0){
$data['port'] = 21;
}
if(strpos($data['host'], 'ftp://') !== false){
$data['host'] = str_replace('ftp://', '', $data['host']);
}
if(strpos($data['host'], 'http://') !== false){
$data['host'] = str_replace('http://', '', $data['host']);
}
if(strpos($data['host'], 'https://') !== false){
$data['host'] = str_replace('https://', '', $data['host']);
}
if ($data['password'] === '') {
unset($data['password']);
}
if(
$SQL->num_rows(
$SQL->query("SELECT * FROM {$dbprefix}kj_ftp_info WHERE id<>" . p('id') . " AND name='" . $SQL->escape($data['name']) . "'")
)
)
{
kleeja_admin_err($olang['KJ_FTP_ACCOUNT_NAME_CONFLICT'], true, '', true, $action);
}
$updateSet = '';
foreach ($data as $n=>$v){
$updateSet .= ($updateSet == '' ? '' : ', '). "`$n`='" . $SQL->escape($v) . "'";
}
$update_query = array(
'UPDATE' => "{$dbprefix}kj_ftp_info",
'SET' => $updateSet,
'WHERE' => "id=". p('id')
);
$SQL->build($update_query);
$cache->clean('klj_ftp::ftp_names');
kleeja_admin_info($olang['KJ_FTP_ACCOUNT_UPDATED'], true, '', true, $action, 2);
break;
}