- 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
No known key found for this signature in database
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

@ -4,155 +4,170 @@
* Handle file uploads via XMLHttpRequest * Handle file uploads via XMLHttpRequest
*/ */
class qqUploadedFileXhr { 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"); {
$temp = tmpfile(); $input = fopen('php://input', 'r');
$realSize = stream_copy_to_stream($input, $temp); $temp = tmpfile();
fclose($input); $realSize = stream_copy_to_stream($input, $temp);
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() {
return $_GET['qqfile']; public function getName(): string
} {
function getSize() { return $_GET['qqfile'];
if (isset($_SERVER["CONTENT_LENGTH"])){ }
return (int)$_SERVER["CONTENT_LENGTH"];
} else { public function getSize(): int
throw new Exception('Getting content length is not supported.'); {
} if (isset($_SERVER['CONTENT_LENGTH'])) {
} return (int)$_SERVER['CONTENT_LENGTH'];
} else {
throw new Exception('Getting content length is not supported.');
}
}
} }
/** /**
* Handle file uploads via regular form post (uses the $_FILES array) * Handle file uploads via regular form post (uses the $_FILES array)
*/ */
class qqUploadedFileForm { 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)){ {
return false; if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
} return false;
return true; }
} return true;
function getName() { }
return $_FILES['qqfile']['name'];
} public function getName(): string
function getSize() { {
return $_FILES['qqfile']['size']; return $_FILES['qqfile']['name'];
} }
public function getSize(): int
{
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;
$this->checkServerSettings(); $this->checkServerSettings();
if (isset($_GET['qqfile'])) { if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr(); $this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) { } elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm(); $this->file = new qqUploadedFileForm();
} else { } else {
$this->file = false; $this->file = false;
} }
} }
private function checkServerSettings(){ private function checkServerSettings()
$postSize = $this->toBytes(ini_get('post_max_size')); {
$uploadSize = $this->toBytes(ini_get('upload_max_filesize')); $postSize = $this->toBytes(ini_get('post_max_size'));
$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); {
$last = strtolower($str[strlen($str)-1]); $val = trim($str);
switch($last) { $last = strtolower($str[strlen($str) - 1]);
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/** switch($last) {
* Returns array('success'=>true) or array('error'=>'error message') case 'g': $val *= 1024;
*/ case 'm': $val *= 1024;
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){ case 'k': $val *= 1024;
if (!is_writable($uploadDirectory)){ }
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file){ return $val;
return array('error' => 'No files were uploaded.'); }
}
$size = $this->file->getSize(); /**
* Returns array('success'=>true) or array('error'=>'error message')
*/
public function handleUpload(string $uploadDirectory, bool $replaceOldFile = false): array
{
if (!is_writable($uploadDirectory)) {
return ['error' => "Server error. Upload directory isn't writable."];
}
if ($size == 0) { if (!$this->file) {
return array('error' => 'File is empty'); return ['error' => 'No files were uploaded.'];
} }
if ($size > $this->sizeLimit) { $size = $this->file->getSize();
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName()); if ($size == 0) {
$filename = $pathinfo['filename']; return ['error' => 'File is empty'];
//$filename = md5(uniqid()); }
$ext = $pathinfo['extension'];
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){ if ($size > $this->sizeLimit) {
$these = implode(', ', $this->allowedExtensions); return ['error' => 'File is too large'];
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.'); }
}
if(!$replaceOldFile){ $pathinfo = pathinfo($this->file->getName());
/// don't overwrite previous files that were uploaded $filename = $pathinfo['filename'];
while (file_exists($uploadDirectory . $filename . '.' . $ext)) { //$filename = md5(uniqid());
$filename .= rand(10, 99); $ext = $pathinfo['extension'];
}
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){ if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
return array('success'=>true); $these = implode(', ', $this->allowedExtensions);
} else { return ['error' => 'File has an invalid extension, it should be one of '. $these . '.'];
return array('error'=> 'Could not save uploaded file.' . }
'The upload was cancelled, or server error encountered');
}
} if(!$replaceOldFile) {
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
return ['success' => true];
} else {
return ['error'=> 'Could not save uploaded file. 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;