This commit is contained in:
Shish 2023-01-11 11:15:26 +00:00
parent 91b354f6f8
commit 5a64e8729b
49 changed files with 99 additions and 112 deletions

View file

@ -60,8 +60,8 @@
"ext-memcache": "memcache caching", "ext-memcache": "memcache caching",
"ext-memcached": "memcached caching", "ext-memcached": "memcached caching",
"ext-apc": "apc caching", "ext-apc": "apc caching",
"ext-apcu": "apc caching",
"ext-redis": "redis caching", "ext-redis": "redis caching",
"ext-dom": "some extensions",
"ext-curl": "some extensions", "ext-curl": "some extensions",
"ext-ctype": "some extensions", "ext-ctype": "some extensions",
"ext-json": "some extensions", "ext-json": "some extensions",

View file

@ -138,8 +138,8 @@ class BaseThemelet
$next_html = $at_end ? "Next" : $this->gen_page_link($base_url, $query, $next, "Next"); $next_html = $at_end ? "Next" : $this->gen_page_link($base_url, $query, $next, "Next");
$last_html = $at_end ? "Last" : $this->gen_page_link($base_url, $query, $total_pages, "Last"); $last_html = $at_end ? "Last" : $this->gen_page_link($base_url, $query, $total_pages, "Last");
$start = $current_page-5 > 1 ? $current_page-5 : 1; $start = max($current_page - 5, 1);
$end = $start+10 < $total_pages ? $start+10 : $total_pages; $end = min($start + 10, $total_pages);
$pages = []; $pages = [];
foreach (range($start, $end) as $i) { foreach (range($start, $end) as $i) {

View file

@ -27,15 +27,15 @@ class NoCache implements CacheEngine
class MemcachedCache implements CacheEngine class MemcachedCache implements CacheEngine
{ {
public ?Memcached $memcache=null; public ?\Memcached $memcache=null;
public function __construct(string $args) public function __construct(string $args)
{ {
$hp = explode(":", $args); $hp = explode(":", $args);
$this->memcache = new Memcached(); $this->memcache = new \Memcached();
#$this->memcache->setOption(Memcached::OPT_COMPRESSION, False); #$this->memcache->setOption(\Memcached::OPT_COMPRESSION, False);
#$this->memcache->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_PHP); #$this->memcache->setOption(\Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_PHP);
#$this->memcache->setOption(Memcached::OPT_PREFIX_KEY, phpversion()); #$this->memcache->setOption(\Memcached::OPT_PREFIX_KEY, phpversion());
$this->memcache->addServer($hp[0], (int)$hp[1]); $this->memcache->addServer($hp[0], (int)$hp[1]);
} }
@ -46,9 +46,9 @@ class MemcachedCache implements CacheEngine
$val = $this->memcache->get($key); $val = $this->memcache->get($key);
$res = $this->memcache->getResultCode(); $res = $this->memcache->getResultCode();
if ($res == Memcached::RES_SUCCESS) { if ($res == \Memcached::RES_SUCCESS) {
return $val; return $val;
} elseif ($res == Memcached::RES_NOTFOUND) { } elseif ($res == \Memcached::RES_NOTFOUND) {
return false; return false;
} else { } else {
error_log("Memcached error during get($key): $res"); error_log("Memcached error during get($key): $res");
@ -62,7 +62,7 @@ class MemcachedCache implements CacheEngine
$this->memcache->set($key, $val, $time); $this->memcache->set($key, $val, $time);
$res = $this->memcache->getResultCode(); $res = $this->memcache->getResultCode();
if ($res != Memcached::RES_SUCCESS) { if ($res != \Memcached::RES_SUCCESS) {
error_log("Memcached error during set($key): $res"); error_log("Memcached error during set($key): $res");
} }
} }
@ -73,7 +73,7 @@ class MemcachedCache implements CacheEngine
$this->memcache->delete($key); $this->memcache->delete($key);
$res = $this->memcache->getResultCode(); $res = $this->memcache->getResultCode();
if ($res != Memcached::RES_SUCCESS && $res != Memcached::RES_NOTFOUND) { if ($res != \Memcached::RES_SUCCESS && $res != \Memcached::RES_NOTFOUND) {
error_log("Memcached error during delete($key): $res"); error_log("Memcached error during delete($key): $res");
} }
} }
@ -104,15 +104,15 @@ class APCCache implements CacheEngine
class RedisCache implements CacheEngine class RedisCache implements CacheEngine
{ {
private Redis $redis; private \Redis $redis;
public function __construct(string $args) public function __construct(string $args)
{ {
$this->redis = new Redis(); $this->redis = new \Redis();
$hp = explode(":", $args); $hp = explode(":", $args);
$this->redis->pconnect($hp[0], (int)$hp[1]); $this->redis->pconnect($hp[0], (int)$hp[1]);
$this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); $this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
$this->redis->setOption(Redis::OPT_PREFIX, 'shm:'); $this->redis->setOption(\Redis::OPT_PREFIX, 'shm:');
} }
public function get(string $key) public function get(string $key)

View file

@ -27,7 +27,7 @@ function captcha_get_html(): string
<script type=\"text/javascript\" src=\"https://www.google.com/recaptcha/api.js\"></script>"; <script type=\"text/javascript\" src=\"https://www.google.com/recaptcha/api.js\"></script>";
} else { } else {
session_start(); session_start();
$captcha = Securimage::getCaptchaHtml(['securimage_path' => './vendor/dapphp/securimage/']); $captcha = \Securimage::getCaptchaHtml(['securimage_path' => './vendor/dapphp/securimage/']);
} }
} }
return $captcha; return $captcha;
@ -53,7 +53,7 @@ function captcha_check(): bool
} }
} else { } else {
session_start(); session_start();
$securimg = new Securimage(); $securimg = new \Securimage();
if ($securimg->check($_POST['captcha_code']) === false) { if ($securimg->check($_POST['captcha_code']) === false) {
log_info("core", "Captcha failed (Securimage)"); log_info("core", "Captcha failed (Securimage)");
return false; return false;

View file

@ -16,7 +16,7 @@ class CommandBuilder
public function __construct(String $executable) public function __construct(String $executable)
{ {
if (empty($executable)) { if (empty($executable)) {
throw new InvalidArgumentException("executable cannot be empty"); throw new \InvalidArgumentException("executable cannot be empty");
} }
$this->executable = $executable; $this->executable = $executable;

View file

@ -151,12 +151,17 @@ class Database
if (is_null($this->db)) { if (is_null($this->db)) {
$this->connect_db(); $this->connect_db();
} }
return $this->db->execute( $ret = $this->db->execute(
"-- " . str_replace("%2F", "/", urlencode($_GET['q'] ?? '')). "\n" . "-- " . str_replace("%2F", "/", urlencode($_GET['q'] ?? '')). "\n" .
$query, $query,
$args $args
); );
} catch (PDOException $pdoe) { if($ret === false) {
throw new SCoreException("Query failed", $query);
}
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $ret;
} catch (\PDOException $pdoe) {
throw new SCoreException($pdoe->getMessage(), $query); throw new SCoreException($pdoe->getMessage(), $query);
} }
} }

View file

@ -746,7 +746,7 @@ class Image
VALUES(:iid, :tid) VALUES(:iid, :tid)
", ["iid"=>$this->id, "tid"=>$id]); ", ["iid"=>$this->id, "tid"=>$id]);
array_push($written_tags, $id); $written_tags[] = $id;
} }
$database->execute( $database->execute(
" "

View file

@ -34,7 +34,7 @@ function install()
// Pull in necessary files // Pull in necessary files
require_once "vendor/autoload.php"; require_once "vendor/autoload.php";
global $_tracer; global $_tracer;
$_tracer = new EventTracer(); $_tracer = new \EventTracer();
require_once "core/exceptions.php"; require_once "core/exceptions.php";
require_once "core/cacheengine.php"; require_once "core/cacheengine.php";
@ -102,7 +102,7 @@ function ask_questions()
"; ";
} }
$drivers = PDO::getAvailableDrivers(); $drivers = \PDO::getAvailableDrivers();
if ( if (
!in_array(DatabaseDriverID::MYSQL->value, $drivers) && !in_array(DatabaseDriverID::MYSQL->value, $drivers) &&
!in_array(DatabaseDriverID::PGSQL->value, $drivers) && !in_array(DatabaseDriverID::PGSQL->value, $drivers) &&
@ -292,7 +292,7 @@ function create_tables(Database $db)
if ($db->is_transaction_open()) { if ($db->is_transaction_open()) {
$db->commit(); $db->commit();
} }
} catch (PDOException $e) { } catch (\PDOException $e) {
throw new InstallerException( throw new InstallerException(
"PDO Error:", "PDO Error:",
"<p>An error occurred while trying to create the database tables necessary for Shimmie.</p> "<p>An error occurred while trying to create the database tables necessary for Shimmie.</p>

View file

@ -9,6 +9,9 @@ namespace Shimmie2;
* be included right at the very start of index.php and tests/bootstrap.php * be included right at the very start of index.php and tests/bootstrap.php
*/ */
use JetBrains\PhpStorm\NoReturn;
#[NoReturn]
function die_nicely($title, $body, $code=0) function die_nicely($title, $body, $code=0)
{ {
print("<!DOCTYPE html> print("<!DOCTYPE html>
@ -48,7 +51,7 @@ set_error_handler(function ($errNo, $errStr) {
// Should we turn ALL notices into errors? PHP allows a lot of // Should we turn ALL notices into errors? PHP allows a lot of
// terrible things to happen by default... // terrible things to happen by default...
if (str_starts_with($errStr, 'Use of undefined constant ')) { if (str_starts_with($errStr, 'Use of undefined constant ')) {
throw new Exception("PHP Error#$errNo: $errStr"); throw new \Exception("PHP Error#$errNo: $errStr");
} else { } else {
return false; return false;
} }

View file

@ -560,10 +560,6 @@ function get_debug_info(): string
* Request initialisation stuff * * Request initialisation stuff *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/** @privatesection
* @noinspection PhpIncludeInspection
*/
function require_all(array $files): void function require_all(array $files): void
{ {
foreach ($files as $filename) { foreach ($files as $filename) {

View file

@ -220,7 +220,7 @@ class AutoTagger extends Extension
$existing_tags = Tag::explode($existing_tags); $existing_tags = Tag::explode($existing_tags);
foreach ($additional_tags as $t) { foreach ($additional_tags as $t) {
if (!in_array(strtolower($t), $existing_tags)) { if (!in_array(strtolower($t), $existing_tags)) {
array_push($existing_tags, strtolower($t)); $existing_tags[] = strtolower($t);
} }
} }

View file

@ -297,7 +297,7 @@ class BulkActions extends Extension
try { try {
send_event(new SourceSetEvent($image, $source)); send_event(new SourceSetEvent($image, $source));
$total++; $total++;
} catch (Exception $e) { } catch (\Exception $e) {
$page->flash("Error while setting source for {$image->id}: " . $e->getMessage()); $page->flash("Error while setting source for {$image->id}: " . $e->getMessage());
} }
} }

View file

@ -112,7 +112,7 @@ class BulkAddCSV extends Extension
try { try {
$this->add_image($fullpath, $pathinfo["basename"], $tags, $source, $rating, $thumbfile); $this->add_image($fullpath, $pathinfo["basename"], $tags, $source, $rating, $thumbfile);
$list .= "ok\n"; $list .= "ok\n";
} catch (Exception $ex) { } catch (\Exception $ex) {
$list .= "failed:<br>". $ex->getMessage(); $list .= "failed:<br>". $ex->getMessage();
} }
} else { } else {

View file

@ -49,11 +49,11 @@ class BulkDownload extends Extension
($event->action == BulkDownload::DOWNLOAD_ACTION_NAME)) { ($event->action == BulkDownload::DOWNLOAD_ACTION_NAME)) {
$download_filename = $user->name . '-' . date('YmdHis') . '.zip'; $download_filename = $user->name . '-' . date('YmdHis') . '.zip';
$zip_filename = tempnam(sys_get_temp_dir(), "shimmie_bulk_download"); $zip_filename = tempnam(sys_get_temp_dir(), "shimmie_bulk_download");
$zip = new ZipArchive(); $zip = new \ZipArchive();
$size_total = 0; $size_total = 0;
$max_size = $config->get_int(BulkDownloadConfig::SIZE_LIMIT); $max_size = $config->get_int(BulkDownloadConfig::SIZE_LIMIT);
if ($zip->open($zip_filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === true) { if ($zip->open($zip_filename, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE) === true) {
foreach ($event->items as $image) { foreach ($event->items as $image) {
$img_loc = warehouse_path(Image::IMAGE_DIR, $image->hash, false); $img_loc = warehouse_path(Image::IMAGE_DIR, $image->hash, false);
$size_total += filesize($img_loc); $size_total += filesize($img_loc);

View file

@ -17,7 +17,7 @@ class BulkImportExport extends DataHandlerExtension
if ($this->supported_mime($event->mime) && if ($this->supported_mime($event->mime) &&
$user->can(Permissions::BULK_IMPORT)) { $user->can(Permissions::BULK_IMPORT)) {
$zip = new ZipArchive(); $zip = new \ZipArchive();
if ($zip->open($event->tmpname) === true) { if ($zip->open($event->tmpname) === true) {
$json_data = $this->get_export_data($zip); $json_data = $this->get_export_data($zip);
@ -71,11 +71,11 @@ class BulkImportExport extends DataHandlerExtension
$database->commit(); $database->commit();
$total++; $total++;
} catch (Exception $ex) { } catch (\Exception $ex) {
$failed++; $failed++;
try { try {
$database->rollBack(); $database->rollBack();
} catch (Exception $ex2) { } catch (\Exception $ex2) {
log_error(BulkImportExportInfo::KEY, "Could not roll back transaction: " . $ex2->getMessage(), "Could not import " . $item->hash . ": " . $ex->getMessage()); log_error(BulkImportExportInfo::KEY, "Could not roll back transaction: " . $ex2->getMessage(), "Could not import " . $item->hash . ": " . $ex->getMessage());
} }
log_error(BulkImportExportInfo::KEY, "Could not import " . $item->hash . ": " . $ex->getMessage(), "Could not import " . $item->hash . ": " . $ex->getMessage()); log_error(BulkImportExportInfo::KEY, "Could not import " . $item->hash . ": " . $ex->getMessage(), "Could not import " . $item->hash . ": " . $ex->getMessage());
@ -118,11 +118,11 @@ class BulkImportExport extends DataHandlerExtension
($event->action == self::EXPORT_ACTION_NAME)) { ($event->action == self::EXPORT_ACTION_NAME)) {
$download_filename = $user->name . '-' . date('YmdHis') . '.zip'; $download_filename = $user->name . '-' . date('YmdHis') . '.zip';
$zip_filename = tempnam(sys_get_temp_dir(), "shimmie_bulk_export"); $zip_filename = tempnam(sys_get_temp_dir(), "shimmie_bulk_export");
$zip = new ZipArchive(); $zip = new \ZipArchive();
$json_data = []; $json_data = [];
if ($zip->open($zip_filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === true) { if ($zip->open($zip_filename, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE) === true) {
foreach ($event->items as $image) { foreach ($event->items as $image) {
$img_loc = warehouse_path(Image::IMAGE_DIR, $image->hash, false); $img_loc = warehouse_path(Image::IMAGE_DIR, $image->hash, false);
@ -134,7 +134,7 @@ class BulkImportExport extends DataHandlerExtension
$data["filename"] = $image->filename; $data["filename"] = $image->filename;
$data["source"] = $image->source; $data["source"] = $image->source;
array_push($json_data, $data); $json_data[] = $data;
$zip->addFile($img_loc, $image->hash); $zip->addFile($img_loc, $image->hash);
} }
@ -167,7 +167,7 @@ class BulkImportExport extends DataHandlerExtension
return false; return false;
} }
private function get_export_data(ZipArchive $zip): ?array private function get_export_data(\ZipArchive $zip): ?array
{ {
$info = $zip->getStream(self::EXPORT_INFO_FILE_NAME); $info = $zip->getStream(self::EXPORT_INFO_FILE_NAME);
if ($info !== false) { if ($info !== false) {

View file

@ -552,7 +552,7 @@ class CommentList extends Extension
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'none', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'none',
]; ];
$akismet = new Akismet( $akismet = new \Akismet(
$_SERVER['SERVER_NAME'], $_SERVER['SERVER_NAME'],
$config->get_string('comment_wordpress_key'), $config->get_string('comment_wordpress_key'),
$comment $comment

View file

@ -113,7 +113,7 @@ class ET extends Extension
'branch' => $commitBranch, 'branch' => $commitBranch,
'origin' => $commitOrigin, 'origin' => $commitOrigin,
]; ];
} catch (Exception $e) { } catch (\Exception $e) {
} }
} }

View file

@ -49,7 +49,7 @@ class CBZFileHandler extends DataHandlerExtension
{ {
$out = "data/comic-cover-FIXME.jpg"; // TODO: random $out = "data/comic-cover-FIXME.jpg"; // TODO: random
$za = new ZipArchive(); $za = new \ZipArchive();
$za->open($archive); $za->open($archive);
$names = []; $names = [];
for ($i=0; $i<$za->numFiles;$i++) { for ($i=0; $i<$za->numFiles;$i++) {

View file

@ -53,7 +53,7 @@ class PixelFileHandler extends DataHandlerExtension
log_warning("handle_pixel", "Insufficient memory while creating thumbnail: ".$e->getMessage()); log_warning("handle_pixel", "Insufficient memory while creating thumbnail: ".$e->getMessage());
imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black); imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black);
return true; return true;
} catch (Exception $e) { } catch (\Exception $e) {
log_error("handle_pixel", "Error while creating thumbnail: ".$e->getMessage()); log_error("handle_pixel", "Error while creating thumbnail: ".$e->getMessage());
return false; return false;
} }

View file

@ -96,7 +96,7 @@ class MiniSVGParser
xml_parser_free($xml_parser); xml_parser_free($xml_parser);
} }
public function startElement($parser, $name, $attrs) public function startElement($parser, $name, $attrs): void
{ {
if ($name == "SVG" && $this->xml_depth == 0) { if ($name == "SVG" && $this->xml_depth == 0) {
$this->width = int_escape($attrs["WIDTH"]); $this->width = int_escape($attrs["WIDTH"]);
@ -105,7 +105,7 @@ class MiniSVGParser
$this->xml_depth++; $this->xml_depth++;
} }
public function endElement($parser, $name) public function endElement($parser, $name): void
{ {
$this->xml_depth--; $this->xml_depth--;
} }

View file

@ -35,7 +35,7 @@ class ImageBanTest extends ShimmiePHPUnitTestCase
// Can't repost // Can't repost
try { try {
$this->post_image("tests/pbx_screenshot.jpg", "pbx"); $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->assertTrue(false); $this->fail();
} catch (UploadException $e) { } catch (UploadException $e) {
$this->assertTrue(true); $this->assertTrue(true);
} }

View file

@ -14,7 +14,7 @@ class LinkImageTest extends ShimmiePHPUnitTestCase
$matches = []; $matches = [];
preg_match("#value='https?://.*/(post/view/[0-9]+)'#", $this->page_to_text(), $matches); preg_match("#value='https?://.*/(post/view/[0-9]+)'#", $this->page_to_text(), $matches);
$this->assertTrue(count($matches) > 0); $this->assertNotEmpty($matches);
$page = $this->get_page($matches[1]); $page = $this->get_page($matches[1]);
$this->assertEquals("Post $image_id: pie", $page->title); $this->assertEquals("Post $image_id: pie", $page->title);
} }

View file

@ -68,7 +68,7 @@ class LiveFeed extends Extension
} }
fwrite($fp, "$data\n"); fwrite($fp, "$data\n");
fclose($fp); fclose($fp);
} catch (Exception $e) { } catch (\Exception $e) {
/* logging errors shouldn't break everything */ /* logging errors shouldn't break everything */
} }
} }

View file

@ -50,7 +50,7 @@ class ActorColumn extends Column
public function get_sql_filter(): string public function get_sql_filter(): string
{ {
$driver = $this->table->db->getAttribute(PDO::ATTR_DRIVER_NAME); $driver = $this->table->db->getAttribute(\PDO::ATTR_DRIVER_NAME);
switch ($driver) { switch ($driver) {
case "pgsql": case "pgsql":
return "((LOWER(username) = LOWER(:{$this->name}_0)) OR (address && cast(:{$this->name}_1 as inet)))"; return "((LOWER(username) = LOWER(:{$this->name}_0)) OR (address && cast(:{$this->name}_1 as inet)))";

View file

@ -28,7 +28,7 @@ class LogLogstash extends Extension
]; ];
$this->send_data($data); $this->send_data($data);
} catch (Exception $e) { } catch (\Exception $e) {
// we can't log that logging is broken // we can't log that logging is broken
} }
} }
@ -52,7 +52,7 @@ class LogLogstash extends Extension
} }
fwrite($fp, json_encode($data)); fwrite($fp, json_encode($data));
fclose($fp); fclose($fp);
} catch (Exception $e) { } catch (\Exception $e) {
// we can't log that logging is broken // we can't log that logging is broken
} }
} }

View file

@ -44,7 +44,7 @@ class LogNet extends Extension
} }
fwrite($fp, "$data\n"); fwrite($fp, "$data\n");
fclose($fp); fclose($fp);
} catch (Exception $e) { } catch (\Exception $e) {
/* logging errors shouldn't break everything */ /* logging errors shouldn't break everything */
} }
} }

View file

@ -28,7 +28,7 @@ class NotATagTest extends ShimmiePHPUnitTestCase
// Modified Bad as user - redirect // Modified Bad as user - redirect
try { try {
send_event(new TagSetEvent($image, ["three", "face"])); send_event(new TagSetEvent($image, ["three", "face"]));
$this->assertTrue(false, "Should've had an exception"); $this->fail("Should've had an exception");
} catch (TagSetException $e) { } catch (TagSetException $e) {
$this->assertTrue(true); $this->assertTrue(true);
} }

View file

@ -147,7 +147,7 @@ class NumericScore extends Extension
$dte = [$totaldate, $year, "\\y\\e\\a\\r\=Y", "year"]; $dte = [$totaldate, $year, "\\y\\e\\a\\r\=Y", "year"];
} else { } else {
// this should never happen due to the fact that the page event is already matched against earlier. // this should never happen due to the fact that the page event is already matched against earlier.
throw new UnexpectedValueException("Error: Invalid page event."); throw new \UnexpectedValueException("Error: Invalid page event.");
} }
$sql .= " AND NOT numeric_score=0 ORDER BY numeric_score DESC LIMIT :limit OFFSET 0"; $sql .= " AND NOT numeric_score=0 ORDER BY numeric_score DESC LIMIT :limit OFFSET 0";

View file

@ -521,7 +521,7 @@ class OuroborosAPI extends Extension
$response = json_encode($response); $response = json_encode($response);
} elseif ($this->type == 'xml') { } elseif ($this->type == 'xml') {
// Seriously, XML sucks... // Seriously, XML sucks...
$xml = new XMLWriter(); $xml = new \XMLWriter();
$xml->openMemory(); $xml->openMemory();
$xml->startDocument('1.0', 'utf-8'); $xml->startDocument('1.0', 'utf-8');
$xml->startElement('response'); $xml->startElement('response');
@ -546,7 +546,7 @@ class OuroborosAPI extends Extension
if ($this->type == 'json') { if ($this->type == 'json') {
$response = json_encode($data); $response = json_encode($data);
} elseif ($this->type == 'xml') { } elseif ($this->type == 'xml') {
$xml = new XMLWriter(); $xml = new \XMLWriter();
$xml->openMemory(); $xml->openMemory();
$xml->startDocument('1.0', 'utf-8'); $xml->startDocument('1.0', 'utf-8');
if (array_key_exists(0, $data)) { if (array_key_exists(0, $data)) {
@ -572,7 +572,7 @@ class OuroborosAPI extends Extension
$page->set_data($response); $page->set_data($response);
} }
private function createItemXML(XMLWriter $xml, string $type, $item) private function createItemXML(\XMLWriter $xml, string $type, $item)
{ {
$xml->startElement($type); $xml->startElement($type);
foreach ($item as $key => $val) { foreach ($item as $key => $val) {

View file

@ -347,7 +347,7 @@ class Pools extends Extension
$image_order = $image_order + 1; $image_order = $image_order + 1;
} }
$database->commit(); $database->commit();
} catch (Exception $e) { } catch (\Exception $e) {
$database->rollback(); $database->rollback();
} }
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
@ -581,7 +581,7 @@ class Pools extends Extension
if ($this->have_permission($user, $pool)) { if ($this->have_permission($user, $pool)) {
send_event( send_event(
new PoolAddPostsEvent($pool_id, iterator_map_to_array("_image_to_id", $event->items)) new PoolAddPostsEvent($pool_id, iterator_map_to_array("Shimmie2\_image_to_id", $event->items))
); );
} }
break; break;
@ -592,7 +592,7 @@ class Pools extends Extension
$new_pool_title = $_POST['bulk_pool_new']; $new_pool_title = $_POST['bulk_pool_new'];
$pce = new PoolCreationEvent($new_pool_title); $pce = new PoolCreationEvent($new_pool_title);
send_event($pce); send_event($pce);
send_event(new PoolAddPostsEvent($pce->new_id, iterator_map_to_array("_image_to_id", $event->items))); send_event(new PoolAddPostsEvent($pce->new_id, iterator_map_to_array("Shimmie2\_image_to_id", $event->items)));
break; break;
} }
} }

View file

@ -81,7 +81,7 @@ class PostTitles extends Extension
} }
public function onBulkImport(BulkImportEvent $event) public function onBulkImport(BulkImportEvent $event)
{ {
if (property_exists($event->fields, "title") && $event->fields->title!=null) { if (array_key_exists("title", $event->fields) && $event->fields->title!=null) {
$this->set_title($event->image->id, $event->fields->title); $this->set_title($event->image->id, $event->fields->title);
} }
} }

View file

@ -45,7 +45,7 @@ class RandomList extends Extension
if (!$random_image) { if (!$random_image) {
continue; continue;
} }
array_push($random_images, $random_image); $random_images[] = $random_image;
} }
$this->theme->set_page($search_terms); $this->theme->set_page($search_terms);

View file

@ -28,18 +28,7 @@ class ImageRating
} }
} }
function clear_ratings() function add_rating(ImageRating $rating): void
{
global $_shm_ratings;
$keys = array_keys($_shm_ratings);
foreach ($keys as $key) {
if ($key != "?") {
unset($_shm_ratings[$key]);
}
}
}
function add_rating(ImageRating $rating)
{ {
global $_shm_ratings; global $_shm_ratings;
if ($rating->code == "?" && array_key_exists("?", $_shm_ratings)) { if ($rating->code == "?" && array_key_exists("?", $_shm_ratings)) {
@ -97,7 +86,7 @@ class Ratings extends Extension
$codes = implode("", array_keys($_shm_ratings)); $codes = implode("", array_keys($_shm_ratings));
$search_terms = []; $search_terms = [];
foreach ($_shm_ratings as $key => $rating) { foreach ($_shm_ratings as $key => $rating) {
array_push($search_terms, $rating->search_term); $search_terms[] = $rating->search_term;
} }
$this->search_regexp = "/^rating[=|:](?:(\*|[" . $codes . "]+)|(" . $this->search_regexp = "/^rating[=|:](?:(\*|[" . $codes . "]+)|(" .
implode("|", $search_terms) . "|".implode("|", self::UNRATED_KEYWORDS)."))$/D"; implode("|", $search_terms) . "|".implode("|", self::UNRATED_KEYWORDS)."))$/D";
@ -193,7 +182,7 @@ class Ratings extends Extension
} }
public function onBulkImport(BulkImportEvent $event) public function onBulkImport(BulkImportEvent $event)
{ {
if (property_exists($event->fields, "rating") if (array_key_exists("rating", $event->fields)
&& $event->fields->rating != null && $event->fields->rating != null
&& Ratings::rating_is_valid($event->fields->rating)) { && Ratings::rating_is_valid($event->fields->rating)) {
$this->set_rating($event->image->id, $event->fields->rating, ""); $this->set_rating($event->image->id, $event->fields->rating, "");

View file

@ -44,7 +44,7 @@ class RegenThumbTheme extends Themelet
$mimes = []; $mimes = [];
$results = $database->get_all("SELECT mime, count(*) count FROM images group by mime"); $results = $database->get_all("SELECT mime, count(*) count FROM images group by mime");
foreach ($results as $result) { foreach ($results as $result) {
array_push($mimes, "<option value='".$result["mime"]."'>".$result["mime"]." (".$result["count"].")</option>"); $mimes[] = "<option value='" . $result["mime"] . "'>" . $result["mime"] . " (" . $result["count"] . ")</option>";
} }
$html = " $html = "

View file

@ -35,7 +35,7 @@ class ResolutionLimitTest extends ShimmiePHPUnitTestCase
$this->log_in_as_user(); $this->log_in_as_user();
try { try {
$this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot"); $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot");
$this->assertTrue(false, "Invalid-size image was allowed"); $this->fail("Invalid-size image was allowed");
} catch (UploadException $e) { } catch (UploadException $e) {
$this->assertEquals("Post too small", $e->getMessage()); $this->assertEquals("Post too small", $e->getMessage());
} }
@ -52,7 +52,7 @@ class ResolutionLimitTest extends ShimmiePHPUnitTestCase
try { try {
$this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot"); $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot");
$this->assertTrue(false, "Invalid-size image was allowed"); $this->fail("Invalid-size image was allowed");
} catch (UploadException $e) { } catch (UploadException $e) {
$this->assertEquals("Post too large", $e->getMessage()); $this->assertEquals("Post too large", $e->getMessage());
} }
@ -69,7 +69,7 @@ class ResolutionLimitTest extends ShimmiePHPUnitTestCase
try { try {
$this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot"); $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot");
$this->assertTrue(false, "Invalid-size image was allowed"); $this->fail("Invalid-size image was allowed");
} catch (UploadException $e) { } catch (UploadException $e) {
$this->assertEquals("Post needs to be in one of these ratios: 16:9", $e->getMessage()); $this->assertEquals("Post needs to be in one of these ratios: 16:9", $e->getMessage());
} }

View file

@ -108,7 +108,7 @@ class Rule34 extends Extension
$database->set_timeout(DATABASE_TIMEOUT+15000); // deleting users can take a while $database->set_timeout(DATABASE_TIMEOUT+15000); // deleting users can take a while
if (function_exists("sd_notify_watchdog")) { if (function_exists("sd_notify_watchdog")) {
sd_notify_watchdog(); \sd_notify_watchdog();
} }
if ($event->page_matches("rule34/comic_admin")) { if ($event->page_matches("rule34/comic_admin")) {

View file

@ -6,11 +6,6 @@ namespace Shimmie2;
_d("STATSD_HOST", null); _d("STATSD_HOST", null);
function dstat($name, $val)
{
StatsDInterface::$stats["shimmie.$name"] = $val;
}
class StatsDInterface extends Extension class StatsDInterface extends Extension
{ {
public static array $stats = []; public static array $stats = [];
@ -115,7 +110,7 @@ class StatsDInterface extends Extension
fwrite($fp, "$stat:$value"); fwrite($fp, "$stat:$value");
} }
fclose($fp); fclose($fp);
} catch (Exception $e) { } catch (\Exception $e) {
// ignore any failures. // ignore any failures.
} }
} }

View file

@ -156,7 +156,7 @@ class TagCategories extends Extension
return $h_tag_no_underscores; return $h_tag_no_underscores;
} }
public function page_update() public function page_update(): bool
{ {
global $user, $database; global $user, $database;

View file

@ -70,7 +70,7 @@ class TagSetEvent extends Event
if ((!str_contains($tag, ':')) && (!str_contains($tag, '='))) { if ((!str_contains($tag, ':')) && (!str_contains($tag, '='))) {
//Tag doesn't contain : or =, meaning it can't possibly be a metatag. //Tag doesn't contain : or =, meaning it can't possibly be a metatag.
//This should help speed wise, as it avoids running every single tag through a bunch of preg_match instead. //This should help speed wise, as it avoids running every single tag through a bunch of preg_match instead.
array_push($this->tags, $tag); $this->tags[] = $tag;
continue; continue;
} }
@ -79,9 +79,9 @@ class TagSetEvent extends Event
//seperate tags from metatags //seperate tags from metatags
if (!$ttpe->metatag) { if (!$ttpe->metatag) {
array_push($this->tags, $tag); $this->tags[] = $tag;
} else { } else {
array_push($this->metatags, $tag); $this->metatags[] = $tag;
} }
} }
} }
@ -287,7 +287,7 @@ class TagEdit extends Extension
{ {
$tags = $event->image->get_tag_list(); $tags = $event->image->get_tag_list();
$tags = str_replace("/", "", $tags); $tags = str_replace("/", "", $tags);
$tags = preg_replace("/^\.+/", "", $tags); $tags = ltrim($tags, ".");
$event->replace('$tags', $tags); $event->replace('$tags', $tags);
} }

View file

@ -30,7 +30,7 @@ class TagEditTest extends ShimmiePHPUnitTestCase
try { try {
send_event(new TagSetEvent($image, [])); send_event(new TagSetEvent($image, []));
$this->assertTrue(false); $this->fail();
} catch (SCoreException $e) { } catch (SCoreException $e) {
$this->assertEquals("Tried to set zero tags", $e->error); $this->assertEquals("Tried to set zero tags", $e->error);
} }

View file

@ -106,7 +106,7 @@ class TagEditCloud extends Extension
SELECT tag, FLOOR(LN(LN(count - :tag_min1 + 1)+1)*150)/200 AS scaled, count SELECT tag, FLOOR(LN(LN(count - :tag_min1 + 1)+1)*150)/200 AS scaled, count
FROM tags FROM tags
WHERE count >= :tag_min2 WHERE count >= :tag_min2
ORDER BY SUM(count) OVER (PARTITION BY SUBSTRING_INDEX(tag, ':', 1)) DESC, CASE ORDER BY SUM(count) OVER (PARTITION BY SUBSTRING_INDEX(tag, ':', 1)) DESC, CASE
WHEN tag LIKE '%:%' THEN 1 WHEN tag LIKE '%:%' THEN 1
ELSE 2 ELSE 2
END, tag END, tag
@ -159,7 +159,7 @@ class TagEditCloud extends Extension
$size = sprintf("%.2f", max($row['scaled'], 0.5)); $size = sprintf("%.2f", max($row['scaled'], 0.5));
$js = html_escape('tageditcloud_toggle_tag(this,'.json_encode($full_tag).')'); //Ugly, but it works $js = html_escape('tageditcloud_toggle_tag(this,'.json_encode($full_tag).')'); //Ugly, but it works
if (array_search($row['tag'], $image->get_tag_array()) !== false) { if (in_array($row['tag'], $image->get_tag_array())) {
if ($used_first) { if ($used_first) {
if ($last_used_cat !== $current_cat && $last_used_cat !== null) { if ($last_used_cat !== $current_cat && $last_used_cat !== null) {
$precloud .= "</span><span class='tag-category'>\n"; $precloud .= "</span><span class='tag-category'>\n";

View file

@ -97,7 +97,7 @@ class TaggerXML extends Extension
return $this->list_to_xml($tags, "image", (string)$image_id); return $this->list_to_xml($tags, "image", (string)$image_id);
} }
private function list_to_xml(PDOStatement $tags, string $type, string $query, ?array$misc=null): string private function list_to_xml(\FFSPHP\PDOStatement $tags, string $type, string $query, ?array$misc=null): string
{ {
$r = $tags->_numOfRows; $r = $tags->_numOfRows;
@ -115,7 +115,7 @@ class TaggerXML extends Extension
return $result."</list>"; return $result."</list>";
} }
private function tag_to_xml(PDORow $tag): string private function tag_to_xml(\PDORow $tag): string
{ {
return return
"<tag ". "<tag ".

View file

@ -182,7 +182,7 @@ class TranscodeImage extends Extension
$new_image = $this->transcode_image($event->tmpname, $mime, $target_mime); $new_image = $this->transcode_image($event->tmpname, $mime, $target_mime);
$event->set_mime($target_mime); $event->set_mime($target_mime);
$event->set_tmpname($new_image); $event->set_tmpname($new_image);
} catch (Exception $e) { } catch (\Exception $e) {
log_error("transcode", "Error while performing upload transcode: ".$e->getMessage()); log_error("transcode", "Error while performing upload transcode: ".$e->getMessage());
// We don't want to interfere with the upload process, // We don't want to interfere with the upload process,
// so if something goes wrong the untranscoded image jsut continues // so if something goes wrong the untranscoded image jsut continues
@ -295,11 +295,11 @@ class TranscodeImage extends Extension
$database->commit(); $database->commit();
$total++; $total++;
$size_difference += ($before_size - $new_image->filesize); $size_difference += ($before_size - $new_image->filesize);
} catch (Exception $e) { } catch (\Exception $e) {
log_error("transcode", "Error while bulk transcode on item {$image->id} to $mime: ".$e->getMessage()); log_error("transcode", "Error while bulk transcode on item {$image->id} to $mime: ".$e->getMessage());
try { try {
$database->rollback(); $database->rollback();
} catch (Exception $e) { } catch (\Exception $e) {
// is this safe? o.o // is this safe? o.o
} }
} }

View file

@ -166,11 +166,11 @@ class TranscodeVideo extends Extension
if ($output_image!=$image) { if ($output_image!=$image) {
$total++; $total++;
} }
} catch (Exception $e) { } catch (\Exception $e) {
log_error("transcode_video", "Error while bulk transcode on item {$image->id} to $format: ".$e->getMessage()); log_error("transcode_video", "Error while bulk transcode on item {$image->id} to $format: ".$e->getMessage());
try { try {
$database->rollback(); $database->rollback();
} catch (Exception $e) { } catch (\Exception $e) {
// is this safe? o.o // is this safe? o.o
} }
} }

View file

@ -95,7 +95,7 @@ class Update extends Extension
/** TODO: Backup all folders (except /data, /images, /thumbs) before attempting this? /** TODO: Backup all folders (except /data, /images, /thumbs) before attempting this?
Either that or point to https://github.com/shish/shimmie2/blob/master/README.txt -> Upgrade from 2.3.X **/ Either that or point to https://github.com/shish/shimmie2/blob/master/README.txt -> Upgrade from 2.3.X **/
$zip = new ZipArchive(); $zip = new \ZipArchive();
if ($zip->open("./data/update_$commitSHA.zip") === true) { if ($zip->open("./data/update_$commitSHA.zip") === true) {
for ($i = 1; $i < $zip->numFiles; $i++) { for ($i = 1; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i); $filename = $zip->getNameIndex($i);

View file

@ -107,7 +107,7 @@ class UploadTest extends ShimmiePHPUnitTestCase
file_put_contents("data/huge.jpg", file_get_contents("tests/pbx_screenshot.jpg") . str_repeat("U", 1024*1024*3)); file_put_contents("data/huge.jpg", file_get_contents("tests/pbx_screenshot.jpg") . str_repeat("U", 1024*1024*3));
try { try {
$this->post_image("data/huge.jpg", "test"); $this->post_image("data/huge.jpg", "test");
$this->assertTrue(false, "Uploading huge.jpg didn't fail..."); $this->fail("Uploading huge.jpg didn't fail...");
} catch (UploadException $e) { } catch (UploadException $e) {
$this->assertEquals("File too large (3.0MB > 1.0MB)", $e->error); $this->assertEquals("File too large (3.0MB > 1.0MB)", $e->error);
} }

View file

@ -376,7 +376,7 @@ class Wiki extends Extension
return new WikiPage($row); return new WikiPage($row);
} }
public static function format_tag_wiki_page(WikiPage $page) public static function format_tag_wiki_page(WikiPage $page): string
{ {
global $database, $config; global $database, $config;
@ -434,7 +434,7 @@ class Wiki extends Extension
", ["title"=>$a_tag]); ", ["title"=>$a_tag]);
$tag_html = $tag_list_t->return_tag($a_row, $tag_category_dict ?? []); $tag_html = $tag_list_t->return_tag($a_row, $tag_category_dict ?? []);
array_push($f_auto_tags, $tag_html[1]); $f_auto_tags[] = $tag_html[1];
} }
$template = str_replace("{autotags}", implode(", ", $f_auto_tags), $template); $template = str_replace("{autotags}", implode(", ", $f_auto_tags), $template);

View file

@ -191,8 +191,7 @@ abstract class ShimmiePHPUnitTestCase extends TestCase
} elseif ($page->mode == PageMode::DATA) { } elseif ($page->mode == PageMode::DATA) {
return $page->data; return $page->data;
} else { } else {
$this->assertTrue(false, "Page mode is not PAGE or DATA"); $this->fail("Page mode is not PAGE or DATA");
return "";
} }
} }

View file

@ -198,7 +198,7 @@ EOD;
$b = $block->body; $b = $block->body;
$i = $block->id; $i = $block->id;
$dom = new DomDocument(); $dom = new \DomDocument();
$dom->loadHTML($b); $dom->loadHTML($b);
// $output = []; // $output = [];
$html = "<section id='$i'>\n<nav class='mdl-navigation'>\n"; $html = "<section id='$i'>\n<nav class='mdl-navigation'>\n";