- changed more double-quotes to single
- cleaned up js_upload/file-uploader/server/php.php a lot
- added some type-hints
This commit is contained in:
Roland Häder 2022-06-23 06:04:05 +02:00
parent 28cdecea93
commit 3bda8dfa32
Signed by: roland
GPG key ID: C82EDE5DDFA0BA77
3 changed files with 172 additions and 157 deletions

View file

@ -64,7 +64,7 @@ function advancedcontentfilter_install(App $a)
Hook::add('dbstructure_definition' , __FILE__, 'advancedcontentfilter_dbstructure_definition'); Hook::add('dbstructure_definition' , __FILE__, 'advancedcontentfilter_dbstructure_definition');
DBStructure::performUpdate(); DBStructure::performUpdate();
Logger::notice("installed advancedcontentfilter"); Logger::notice('installed advancedcontentfilter');
} }
/* /*
@ -73,20 +73,20 @@ function advancedcontentfilter_install(App $a)
function advancedcontentfilter_dbstructure_definition(App $a, &$database) function advancedcontentfilter_dbstructure_definition(App $a, &$database)
{ {
$database["advancedcontentfilter_rules"] = [ $database['advancedcontentfilter_rules'] = [
"comment" => "Advancedcontentfilter addon rules", 'comment' => 'Advancedcontentfilter addon rules',
"fields" => [ 'fields' => [
"id" => ["type" => "int unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1", "comment" => "Auto incremented rule id"], 'id' => ['type' => 'int unsigned', 'not null' => '1', 'extra' => 'auto_increment', 'primary' => '1', 'comment' => 'Auto incremented rule id'],
"uid" => ["type" => "int unsigned", "not null" => "1", "comment" => "Owner user id"], 'uid' => ['type' => 'int unsigned', 'not null' => '1', 'comment' => 'Owner user id'],
"name" => ["type" => "varchar(255)", "not null" => "1", "comment" => "Rule name"], 'name' => ['type' => 'varchar(255)', 'not null' => '1', 'comment' => 'Rule name'],
"expression" => ["type" => "mediumtext" , "not null" => "1", "comment" => "Expression text"], 'expression' => ['type' => 'mediumtext' , 'not null' => '1', 'comment' => 'Expression text'],
"serialized" => ["type" => "mediumtext" , "not null" => "1", "comment" => "Serialized parsed expression"], 'serialized' => ['type' => 'mediumtext' , 'not null' => '1', 'comment' => 'Serialized parsed expression'],
"active" => ["type" => "boolean" , "not null" => "1", "default" => "1", "comment" => "Whether the rule is active or not"], 'active' => ['type' => 'boolean' , 'not null' => '1', 'default' => '1', 'comment' => 'Whether the rule is active or not'],
"created" => ["type" => "datetime" , "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => "Creation date"], 'created' => ['type' => 'datetime' , 'not null' => '1', 'default' => DBA::NULL_DATETIME, 'comment' => 'Creation date'],
], ],
"indexes" => [ 'indexes' => [
"PRIMARY" => ["id"], 'PRIMARY' => ['id'],
"uid_active" => ["uid", "active"], 'uid_active' => ['uid', 'active'],
] ]
]; ];
} }

View file

@ -82,17 +82,17 @@ function blackout_redirect ($a, $b) {
function blackout_addon_admin(&$a, &$o) { function blackout_addon_admin(&$a, &$o) {
$mystart = DI::config()->get('blackout','begindate'); $mystart = DI::config()->get('blackout','begindate');
if (! is_string($mystart)) { $mystart = "YYYY-MM-DD hh:mm"; } if (! is_string($mystart)) { $mystart = 'YYYY-MM-DD hh:mm'; }
$myend = DI::config()->get('blackout','enddate'); $myend = DI::config()->get('blackout','enddate');
if (! is_string($myend)) { $myend = "YYYY-MM-DD hh:mm"; } if (! is_string($myend)) { $myend = 'YYYY-MM-DD hh:mm'; }
$myurl = DI::config()->get('blackout','url'); $myurl = DI::config()->get('blackout','url');
if (! is_string($myurl)) { $myurl = "https://www.example.com"; } if (! is_string($myurl)) { $myurl = 'https://www.example.com'; }
$t = Renderer::getMarkupTemplate( "admin.tpl", "addon/blackout/" ); $t = Renderer::getMarkupTemplate( 'admin.tpl', 'addon/blackout/' );
$date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart); $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart);
$date2 = DateTime::createFromFormat('Y-m-d G:i', $myend); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend);
// a note for the admin // a note for the admin
$adminnote = ""; $adminnote = '';
if ($date2 < $date1) { if ($date2 < $date1) {
$adminnote = DI::l10n()->t("The end-date is prior to the start-date of the blackout, you should fix this."); $adminnote = DI::l10n()->t("The end-date is prior to the start-date of the blackout, you should fix this.");
} else { } else {
@ -100,9 +100,9 @@ function blackout_addon_admin(&$a, &$o) {
} }
$o = Renderer::replaceMacros($t, [ $o = Renderer::replaceMacros($t, [
'$submit' => DI::l10n()->t('Save Settings'), '$submit' => DI::l10n()->t('Save Settings'),
'$rurl' => ["rurl", DI::l10n()->t("Redirect URL"), $myurl, DI::l10n()->t("All your visitors from the web will be redirected to this URL."), "", "", "url"], '$rurl' => ['rurl', DI::l10n()->t("Redirect URL"), $myurl, DI::l10n()->t("All your visitors from the web will be redirected to this URL."), '', '', 'url'],
'$startdate' => ["startdate", DI::l10n()->t("Begin of the Blackout"), $mystart, DI::l10n()->t("Format is <tt>YYYY-MM-DD hh:mm</tt>; <em>YYYY</em> year, <em>MM</em> month, <em>DD</em> day, <em>hh</em> hour and <em>mm</em> minute.")], '$startdate' => ['startdate', DI::l10n()->t("Begin of the Blackout"), $mystart, DI::l10n()->t("Format is <tt>YYYY-MM-DD hh:mm</tt>; <em>YYYY</em> year, <em>MM</em> month, <em>DD</em> day, <em>hh</em> hour and <em>mm</em> minute.")],
'$enddate' => ["enddate", DI::l10n()->t("End of the Blackout"), $myend, ""], '$enddate' => ['enddate', DI::l10n()->t("End of the Blackout"), $myend, ''],
'$adminnote' => $adminnote, '$adminnote' => $adminnote,
'$aboutredirect' => DI::l10n()->t("<strong>Note</strong>: The redirect will be active from the moment you press the submit button. Users currently logged in will <strong>not</strong> be thrown out but can't login again after logging out while the blackout is still in place."), '$aboutredirect' => DI::l10n()->t("<strong>Note</strong>: The redirect will be active from the moment you press the submit button. Users currently logged in will <strong>not</strong> be thrown out but can't login again after logging out while the blackout is still in place."),
]); ]);

View file

@ -8,29 +8,34 @@ class qqUploadedFileXhr {
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save(string $path): bool
$input = fopen("php://input", "r"); {
$input = fopen('php://input', 'r');
$temp = tmpfile(); $temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp); $realSize = stream_copy_to_stream($input, $temp);
fclose($input); fclose($input);
if ($realSize != $this->getSize()){ if ($realSize != $this->getSize()) {
return false; return false;
} }
$target = fopen($path, "w"); $target = fopen($path, 'w');
fseek($temp, 0, SEEK_SET); fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target); stream_copy_to_stream($temp, $target);
fclose($target); fclose($target);
return true; return true;
} }
function getName() {
public function getName(): string
{
return $_GET['qqfile']; return $_GET['qqfile'];
} }
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])){ public function getSize(): int
return (int)$_SERVER["CONTENT_LENGTH"]; {
if (isset($_SERVER['CONTENT_LENGTH'])) {
return (int)$_SERVER['CONTENT_LENGTH'];
} else { } else {
throw new Exception('Getting content length is not supported.'); throw new Exception('Getting content length is not supported.');
} }
@ -45,27 +50,33 @@ class qqUploadedFileForm {
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save(string $path): bool
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){ {
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
return false; return false;
} }
return true; return true;
} }
function getName() {
public function getName(): string
{
return $_FILES['qqfile']['name']; return $_FILES['qqfile']['name'];
} }
function getSize() {
public function getSize(): int
{
return $_FILES['qqfile']['size']; return $_FILES['qqfile']['size'];
} }
} }
class qqFileUploader { class qqFileUploader {
private $allowedExtensions = array(); private $allowedExtensions = [];
private $sizeLimit = 10485760; private $sizeLimit = 10485760;
private $file; private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){ public function __construct(array $allowedExtensions = [], $sizeLimit = 10485760)
$allowedExtensions = array_map("strtolower", $allowedExtensions); {
$allowedExtensions = array_map('strtolower', $allowedExtensions);
$this->allowedExtensions = $allowedExtensions; $this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit; $this->sizeLimit = $sizeLimit;
@ -81,47 +92,52 @@ class qqFileUploader {
} }
} }
private function checkServerSettings(){ private function checkServerSettings()
{
$postSize = $this->toBytes(ini_get('post_max_size')); $postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize')); $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){ if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M'; $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size'}"); die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
} }
} }
private function toBytes($str){ private function toBytes(string $str): int
{
$val = trim($str); $val = trim($str);
$last = strtolower($str[strlen($str)-1]); $last = strtolower($str[strlen($str) - 1]);
switch($last) { switch($last) {
case 'g': $val *= 1024; case 'g': $val *= 1024;
case 'm': $val *= 1024; case 'm': $val *= 1024;
case 'k': $val *= 1024; case 'k': $val *= 1024;
} }
return $val; return $val;
} }
/** /**
* Returns array('success'=>true) or array('error'=>'error message') * Returns array('success'=>true) or array('error'=>'error message')
*/ */
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){ public function handleUpload(string $uploadDirectory, bool $replaceOldFile = false): array
if (!is_writable($uploadDirectory)){ {
return array('error' => "Server error. Upload directory isn't writable."); if (!is_writable($uploadDirectory)) {
return ['error' => "Server error. Upload directory isn't writable."];
} }
if (!$this->file){ if (!$this->file) {
return array('error' => 'No files were uploaded.'); return ['error' => 'No files were uploaded.'];
} }
$size = $this->file->getSize(); $size = $this->file->getSize();
if ($size == 0) { if ($size == 0) {
return array('error' => 'File is empty'); return ['error' => 'File is empty'];
} }
if ($size > $this->sizeLimit) { if ($size > $this->sizeLimit) {
return array('error' => 'File is too large'); return ['error' => 'File is too large'];
} }
$pathinfo = pathinfo($this->file->getName()); $pathinfo = pathinfo($this->file->getName());
@ -129,30 +145,29 @@ class qqFileUploader {
//$filename = md5(uniqid()); //$filename = md5(uniqid());
$ext = $pathinfo['extension']; $ext = $pathinfo['extension'];
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){ if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
$these = implode(', ', $this->allowedExtensions); $these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.'); return ['error' => 'File has an invalid extension, it should be one of '. $these . '.'];
} }
if(!$replaceOldFile){ if(!$replaceOldFile) {
/// don't overwrite previous files that were uploaded /// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) { while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99); $filename .= rand(10, 99);
} }
} }
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){ if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
return array('success'=>true); return ['success' => true];
} else { } else {
return array('error'=> 'Could not save uploaded file.' . return ['error'=> 'Could not save uploaded file. The upload was cancelled, or server error encountered'];
'The upload was cancelled, or server error encountered');
} }
} }
} }
// list of valid extensions, ex. array("jpeg", "xml", "bmp") // list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array(); $allowedExtensions = [];
// max file size in bytes // max file size in bytes
$sizeLimit = 10 * 1024 * 1024; $sizeLimit = 10 * 1024 * 1024;