pass objects to Log methods

This commit is contained in:
Spine
2023-12-11 04:08:30 +00:00
parent af8a5b4936
commit 5b4de30050
22 changed files with 103 additions and 74 deletions

View File

@@ -19,13 +19,13 @@ class Log extends Base {
/**
* Write a group entry
*/
public function group(int $groupId, int $userId, string $message): static {
public function group(TGroup $tgroup, ?User $user, string $message): static {
$qid = self::$db->get_query_id();
self::$db->prepared_query("
INSERT INTO group_log
(GroupID, UserID, Info, TorrentID, Hidden)
VALUES (?, ?, ?, 0, 0)
", $groupId, $userId, $message
", $tgroup->id(), $user?->id(), $message
);
self::$db->set_query_id($qid);
return $this;
@@ -34,13 +34,13 @@ class Log extends Base {
/**
* Write a torrent entry
*/
public function torrent(int $groupId, int $torrentId, ?int $userId, string $message): static {
public function torrent(Torrent $torrent, ?User $user, string $message): static {
$qid = self::$db->get_query_id();
self::$db->prepared_query("
INSERT INTO group_log
(GroupID, TorrentID, UserID, Info, Hidden)
VALUES (?, ?, ?, ?, 0)
", $groupId, $torrentId, $userId, $message
", $torrent->groupId(), $torrent->id(), $user?->id(), $message
);
self::$db->set_query_id($qid);
return $this;

View File

@@ -78,7 +78,7 @@ class TGroup extends \Gazelle\BaseManager {
$old->remove($user);
}
$logger->group($newId, $user->id(), "split from group $oldId")
$logger->group($new, $user, "split from group $oldId")
->general("Torrent {$torrent->id()} was split out from group $oldId to $newId by {$user->label()}");
$new->flush()->refresh();
@@ -243,7 +243,7 @@ class TGroup extends \Gazelle\BaseManager {
$oldLabel = $old->label();
$old->remove($user);
$log->general("Group $oldId deleted following merge to {$new->id()}.")
->group($new->id(), $user->id(), "Merged Group $oldLabel to {$new->label()}")
->group($new, $user, "Merged Group $oldLabel to {$new->label()}")
->merge($old, $new);
self::$db->commit();
@@ -418,7 +418,7 @@ class TGroup extends \Gazelle\BaseManager {
}
$new->refresh();
$logger->group($new->id(), $user->id(),
$logger->group($new, $user,
"category changed from {$old->categoryId()} to {$new->categoryId()}, merged from group {$old->id()}"
)
->general("Torrent {$torrent->id()} was changed to category {$new->categoryId()} by {$user->label()}");

View File

@@ -380,7 +380,7 @@ class Torrent extends \Gazelle\BaseManager {
if (!isset($refresh[$tgroupId])) {
$refresh[$tgroupId] = $torrent->group();
}
$log->torrent($tgroupId, $torrentId, $user->id(), "marked as freeleech type {$reason->label()}")
$log->torrent($torrent, $user, "marked as freeleech type {$reason->label()}")
->general($user->username() . " marked torrent $torrentId freeleech type {$reason->label()}");
}
foreach ($refresh as $tgroup) {

View File

@@ -491,22 +491,22 @@ class TGroup extends BaseObject {
);
}
public function addCoverArt(string $image, string $summary, int $userId, \Gazelle\Log $logger): int {
public function addCoverArt(string $image, string $summary, User $user, Log $logger): int {
self::$db->prepared_query("
INSERT IGNORE INTO cover_art
(GroupID, Image, Summary, UserID)
VALUES (?, ?, ?, ?)
", $this->id, $image, $summary, $userId
", $this->id, $image, $summary, $user->id()
);
$id = self::$db->inserted_id();
if ($id) {
$logger->group($this->id, $userId, "Additional cover \"$summary - $image\" added to group");
$logger->group($this, $user, "Additional cover \"$summary - $image\" added to group");
self::$cache->delete_value(sprintf(self::CACHE_COVERART_KEY, $this->id));
}
return $id;
}
public function removeCoverArt(int $coverId, int $userId, \Gazelle\Log $logger): int {
public function removeCoverArt(int $coverId, User $user, Log $logger): int {
[$image, $summary] = self::$db->row("
SELECT Image, Summary
FROM cover_art
@@ -522,7 +522,7 @@ class TGroup extends BaseObject {
);
$affected = self::$db->affected_rows();
if ($affected) {
$logger->group($this->id, $userId, "Additional cover \"$summary - $image\" removed from group");
$logger->group($this, $user, "Additional cover \"$summary - $image\" removed from group");
self::$cache->delete_value(sprintf(self::CACHE_COVERART_KEY, $this->id));
}
return $affected;
@@ -612,7 +612,7 @@ class TGroup extends BaseObject {
);
foreach ($add as $artistLabel) {
$logger->group($this->id, $user->id(), "Added artist $artistLabel")
$logger->group($this, $user, "Added artist $artistLabel")
->general("Artist $artistLabel was added to the group {$this->label()} by user {$user->label()}");
}
self::$cache->increment_value('stats_album_count', count($names));
@@ -1004,8 +1004,8 @@ class TGroup extends BaseObject {
$old->remove($user);
}
$logger->group($this->id, $user->id(), "merged group $oldId")
->general("Torrent " . $torrent->id() . " was edited by " . $user->label());
$logger->group($this, $user, "merged group $oldId")
->general("Torrent {$torrent->id()} was edited by {$user->label()}");
self::$db->commit();
$this->flush()->refresh();
@@ -1132,7 +1132,7 @@ class TGroup extends BaseObject {
$success = $this->setField('Name', $name)->modify();
if ($success) {
$this->refresh();
$logger->group($this->id, $user->id(), "renamed to \"$name\" from \"$oldName\"")
$logger->group($this, $user, "renamed to \"$name\" from \"$oldName\"")
->general("Torrent Group {$this->id} was renamed to \"$name\" from \"$oldName\" by {$user->username()}");
}
return $success;

View File

@@ -230,7 +230,7 @@ class Torrent extends TorrentAbstract {
WHERE ID = ?
", $this->id
);
$logger->torrent($this->groupId(), $this->id, $user->id(), "All logs removed from torrent");
$logger->torrent($this, $user, "All logs removed from torrent");
self::$db->commit();
$this->flush();
@@ -335,6 +335,7 @@ class Torrent extends TorrentAbstract {
*/
public function remove(?User $user, string $reason, int $trackerReason = -1): array {
$qid = self::$db->get_query_id();
self::$db->begin_transaction();
$this->info();
if ($this->id > MAX_PREV_TORRENT_ID) {
(new \Gazelle\User\Bonus($this->uploader()))->removePointsForUpload($this);
@@ -355,6 +356,7 @@ class Torrent extends TorrentAbstract {
$manager->relaxConstraints(true);
[$ok, $message] = $manager->softDelete(SQLDB, 'torrents_leech_stats', [['TorrentID', $this->id]], false);
if (!$ok) {
self::$db->rollback();
return [false, $message];
}
[$ok, $message] = $manager->softDelete(SQLDB, 'torrents', [['ID', $this->id]]);
@@ -430,20 +432,18 @@ class Torrent extends TorrentAbstract {
);
}
$userInfo = $user ? " by " . $user->username() : '';
(new Log)->general(
"Torrent {$this->id} ($name) [$edition] ($sizeMB $infohash) was deleted$userInfo for reason: $reason")
->torrent($this, $user, "deleted torrent ($sizeMB $infohash) for reason: $reason");
self::$db->commit();
array_push($deleteKeys, "zz_t_" . $this->id, sprintf(self::CACHE_KEY, $this->id), "torrent_group_" . $groupId);
self::$cache->delete_multi($deleteKeys);
self::$cache->decrement('stats_torrent_count');
$this->group()->refresh();
$this->flush();
$userInfo = $user ? " by " . $user->username() : '';
(new Log)->general(
"Torrent {$this->id} ($name) [$edition] ($sizeMB $infohash) was deleted$userInfo for reason: $reason")
->torrent(
$groupId, $this->id, $user?->id(),
"deleted torrent ($sizeMB $infohash) for reason: $reason"
);
self::$db->set_query_id($qid);
return [true, "torrent " . $this->id . " removed"];
}

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class LogCreated extends AbstractMigration {
public function up(): void {
$this->table('group_log')
->addColumn('created', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->save();
$this->table('log')
->addColumn('created', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->save();
$this->execute("UPDATE group_log SET created = Time");
$this->execute("UPDATE log SET created = Time");
}
public function down(): void {
$this->table('group_log')->removeColumn('created')->save();
$this->table('log')->removeColumn('created')->save();
}
}

View File

@@ -10,7 +10,7 @@ if (!$coverId || is_null($tgroup)) {
json_die('failure', 'bad parameters');
}
if ($tgroup->removeCoverArt($coverId, $Viewer->id(), new Gazelle\Log)) {
if ($tgroup->removeCoverArt($coverId, $Viewer, new Gazelle\Log)) {
json_print("success", ['id' => $coverId]);
} else {
json_die('failure', 'bad coverId');

View File

@@ -47,7 +47,7 @@ foreach ($Tags as $tagName) {
$tagMan->createTorrentTagVote($tagId, $tgroupId, $userId, 'up');
$added[] = $resolved;
(new Gazelle\Log)->group($tgroupId, $userId, "Tag \"$resolved\" added to group");
(new Gazelle\Log)->group($tgroup, $Viewer, "Tag \"$resolved\" added to group");
}
}

View File

@@ -20,7 +20,7 @@ if ($tgroup->removeTag($tag)) {
// Log the removal and if it was the last occurrence.
$logger = new Gazelle\Log;
$logger->group($tgroup->id(), $Viewer->id(), "Tag \"$tagName\" removed");
$logger->group($tgroup, $Viewer, "Tag \"$tagName\" removed");
if (!$tagMan->findById($tag->id())) {
$logger->general("Unused tag \"$tagName\" removed by user {$Viewer->label()}");
}

View File

@@ -182,8 +182,7 @@ if (isset($_POST['confirm'])) {
", $ArtistID
);
(new Gazelle\Log)->general(
"The artist $ArtistID ($ArtistName) was made into a non-redirecting alias of artist $NewArtistID ($NewArtistName) by user "
. $Viewer->id() . " (" . $Viewer->username() . ')'
"The artist $ArtistID ($ArtistName) was made into a non-redirecting alias of artist $NewArtistID ($NewArtistName) by user {$Viewer->label()}"
);
header("Location: artist.php?action=edit&artistid=$NewArtistID");
exit;

View File

@@ -28,7 +28,7 @@ foreach ($imageList as $n => $image) {
if ($banned) {
error("Please rehost images from $banned elsewhere.");
}
$tgroup->addCoverArt($image, trim($summaryList[$n]), $Viewer->id(), $logger);
$tgroup->addCoverArt($image, trim($summaryList[$n]), $Viewer, $logger);
}
header('Location: ' . redirectUrl($tgroup->location()));

View File

@@ -27,7 +27,7 @@ if ($tgroup->removeArtist($artist, $role, $Viewer, $logger)) {
}
$label = "$artistId ($artistName) [" . ARTIST_TYPE[$role] . "]";
$logger->group($tgroup->id(), $Viewer->id(), "removed artist $label")
$logger->group($tgroup, $Viewer, "removed artist $label")
->general("Artist $label removed from group " . $tgroup->label() . " by user " . $Viewer->label());
header('Location: ' . redirectUrl($tgroup->location()));

View File

@@ -12,7 +12,7 @@ if (is_null($torrent) || !$logId) {
}
(new Gazelle\File\RipLog)->remove([$torrent->id(), $logId]);
(new Gazelle\Log)->torrent($torrent->groupId(), $torrent->id(), $Viewer->id(), "Riplog ID $logId removed from torrent {$torrent->id()}");
(new Gazelle\Log)->torrent($torrent, $Viewer, "Riplog ID $logId removed from torrent {$torrent->id()}");
$torrent->clearLog($logId);
header('Location: ' . $torrent->location());

View File

@@ -93,7 +93,7 @@ if ($noCoverArt != $tgroup->hasNoCoverArt()) {
$logInfo[] = "No cover art exception " . ($noCoverArt ? 'added' : 'removed');
}
if ($logInfo) {
(new Gazelle\Log)->group($tgroup->id(), $Viewer->id(), implode(', ', $logInfo));
(new Gazelle\Log)->group($tgroup, $Viewer, implode(', ', $logInfo));
}
header('Location: ' . $tgroup->location());

View File

@@ -267,7 +267,7 @@ $db->commit();
$torrent->group()->refresh();
$changeLog = implode(', ', $change);
(new Gazelle\Log)->torrent($current['GroupID'], $TorrentID, $Viewer->id(), $changeLog)
(new Gazelle\Log)->torrent($torrent, $Viewer, $changeLog)
->general("Torrent $TorrentID ({$torrent->group()->name()}) in group {$current['GroupID']} was edited by "
. $Viewer->username() . " ($changeLog)");

View File

@@ -3,13 +3,13 @@
$tgroupId = (int)($_GET['id'] ?? 0);
if (!$tgroupId) {
// we may not have a torrent group because it has already been merged elsewhere
// so the best we can hope for is something that looks like an integer
// so the best we can hope for is something that looks like a positive integer
error(404);
}
$tgroup = (new Gazelle\Manager\TGroup)->findById($tgroupId);
echo $Twig->render('tgroup/group-log.twig', [
'group_id' => $tgroupId,
'title' => is_null($tgroup) ? "Group $tgroupId" : $tgroup->link(),
'log' => (new Gazelle\Manager\SiteLog(new Gazelle\Manager\User))->tgroupLogList($tgroupId),
'id' => $tgroupId,
'tgroup' => $tgroup,
'log' => (new Gazelle\Manager\SiteLog(new Gazelle\Manager\User))->tgroupLogList($tgroupId),
]);

View File

@@ -9,8 +9,8 @@ if (empty($_POST['importance']) || empty($_POST['artists']) || empty($_POST['gro
error(0);
}
$GroupID = (int)$_POST['groupid'];
if (!$GroupID) {
$tgroup = (new Gazelle\Manager\TGroup)->findById((int)($_POST['groupid'] ?? 0));
if (is_null($tgroup)) {
error(404);
}
$Artists = explode(',', $_POST['artists']);
@@ -29,10 +29,6 @@ foreach ($Artists as $Artist) {
if (count($CleanArtists) > 0) {
$db = Gazelle\DB::DB();
$GroupName = $db->scalar('
SELECT Name FROM torrents_group WHERE ID = ?
', $GroupID
);
$placeholders = placeholders($ArtistIDs);
$db->prepared_query("
SELECT ArtistID, Name
@@ -50,14 +46,12 @@ if (count($CleanArtists) > 0) {
WHERE GroupID = ?
AND ArtistID = ?
AND Importance = ?
", $GroupID, $ArtistID, $Importance
", $tgroup->id(), $ArtistID, $Importance
);
if ($db->affected_rows()) {
$change = "artist $ArtistID ({$ArtistNames[$ArtistID]['Name']}) removed as " . ARTIST_TYPE[$Importance];
$logger->group($GroupID, $Viewer->id(), $change)
->general("$change in group {$GroupID} ({$GroupName}) by user "
. $Viewer->id() . " (" . $Viewer->username() . ")"
);
$logger->group($tgroup, $Viewer, $change)
->general("$change in group {$tgroup->id()} ({$tgroup->name()}) by user {$Viewer->label()}");
$Cache->delete_value("artist_groups_$ArtistID");
}
}
@@ -87,7 +81,7 @@ if (count($CleanArtists) > 0) {
Importance = ?
WHERE GroupID = ?
AND ArtistID IN ($placeholders)
", $NewImportance, $GroupID, ...$ArtistIDs
", $NewImportance, $tgroup->id(), ...$ArtistIDs
);
$logger = new Gazelle\Log;
foreach ($CleanArtists as $Artist) {
@@ -98,10 +92,10 @@ if (count($CleanArtists) > 0) {
}
$change = "artist $ArtistID ({$ArtistNames[$ArtistID]['Name']}) changed role from "
. ARTIST_TYPE[$Importance] . " to " . ARTIST_TYPE[$NewImportance];
$logger->group($GroupID, $Viewer->id(), $change)
->general("$change in group {$GroupID} ({$GroupName}) by user " . $Viewer->label());
$logger->group($tgroup, $Viewer, $change)
->general("$change in group {$tgroup->id()} ({$tgroup->name()}) by user " . $Viewer->label());
}
}
(new \Gazelle\Manager\TGroup)->findById($GroupID)?->refresh();
header("Location: torrents.php?id=$GroupID");
$tgroup->refresh();
}
header("Location: {$tgroup->location()}");

View File

@@ -50,7 +50,7 @@ if ($tgroup->catalogueNumber() != $catNumber) {
}
if ($tgroup->dirty()) {
(new Gazelle\Log)->group($tgroup->id(), $Viewer->id(), ucfirst(implode(", ", $log)));
(new Gazelle\Log)->group($tgroup, $Viewer, ucfirst(implode(", ", $log)));
$tgroup->modify();
$tgroup->refresh();
}

View File

@@ -615,7 +615,7 @@ foreach ($upload['extra'] as $info) {
$size = number_format($extra->size() / (1024 * 1024), 2);
$upload['new'][] = $extra;
$torrentFiler->put($info['TorEnc'], $extra->id());
$log->torrent($GroupID, $extra->id(), $Viewer->id(), "uploaded ($size MiB)")
$log->torrent($extra, $Viewer, "uploaded ($size MiB)")
->general("Torrent {$extra->id()} ($logName) ($size MiB) was uploaded by " . $Viewer->username());
}
@@ -631,7 +631,7 @@ if ($logfileSummary?->total()) {
}
$size = number_format($TotalSize / (1024 * 1024), 2);
$log->torrent($GroupID, $TorrentID, $Viewer->id(), "uploaded ($size MiB)")
$log->torrent($torrent, $Viewer, "uploaded ($size MiB)")
->general("Torrent $TorrentID ($logName) ($size MiB) was uploaded by " . $Viewer->username());
if (!$torrentFiler->put($bencoder->getEncode(), $TorrentID)) {

View File

@@ -1,7 +1,7 @@
{{ header("History for Group " ~ tgroup_id) }}
{{ header("History for torrent group " ~ id) }}
<div class="thin">
<div class="header">
<h2>History for {{ tgroup.link|default("Group " ~ tgroup_id)|raw }}</h2>
<h2>{{ tgroup.link|default("Group " ~ tgroup_id)|raw }} Changelog</h2>
</div>
<table>
<tr class="colhead">

View File

@@ -57,7 +57,7 @@ class LogTest extends TestCase {
['log.jam']
);
$tgroupId = $this->tgroup->id();
$logger->group($tgroupId, $this->user->id(), self::PREFIX . "group first " . randomString());
$logger->group($this->tgroup, $this->user, self::PREFIX . "group first " . randomString());
$sitelog = new \Gazelle\Manager\SiteLog(new \Gazelle\Manager\User);
$this->assertCount(2, $sitelog->tgroupLogList($tgroupId), 'grouplog-intial');
@@ -77,14 +77,13 @@ class LogTest extends TestCase {
[[ARTIST_MAIN], ['phpunit log artist ' . randomString(6)]],
['log.jam']
);
$newId = $this->tgroupNew->id();
$logger->group($tgroupId, 0, self::PREFIX . "group extra " . randomString());
$logger->group($newId, 0, self::PREFIX . "group merge " . randomString());
$logger->group($this->tgroup, null, self::PREFIX . "group extra " . randomString());
$logger->group($this->tgroupNew, null, self::PREFIX . "group merge " . randomString());
$this->assertEquals(3, $logger->merge($this->tgroup, $this->tgroupNew), 'grouplog-merge-result');
$messageList = array_map(
fn($m) => $m['info'],
$sitelog->tgroupLogList($newId),
$sitelog->tgroupLogList($this->tgroupNew->id()),
);
$this->assertStringStartsWith(self::PREFIX . 'group merge ', $messageList[0], 'grouplog-merge-line-0');
@@ -96,15 +95,29 @@ class LogTest extends TestCase {
public function testTorrentlLog(): void {
$logger = new \Gazelle\Log;
$logger->torrent(-3, -30, -5, self::PREFIX . "torrent " . randomString());
$this->user = Helper::makeUser('sitelog.' . randomString(6), 'sitelog');
$this->tgroup = Helper::makeTGroupMusic(
$this->user,
'phpunit log ' . randomString(6),
[[ARTIST_MAIN], ['phpunit log artist ' . randomString(6)]],
['log.jam']
);
$torrent = Helper::makeTorrentMusic(
tgroup: $this->tgroup,
user: $this->user,
title: randomString(10),
);
$logger->torrent($torrent, $this->user, self::PREFIX . "torrent " . randomString());
$sitelog = new \Gazelle\Manager\SiteLog(new \Gazelle\Manager\User);
$this->assertCount(0, $sitelog->tgroupLogList(-1001), 'torrentlog-no-log');
$result = $sitelog->tgroupLogList(-3);
$this->assertCount(2, $sitelog->tgroupLogList($this->tgroup->id()), 'torrentlog-has-log');
$torrent->remove($this->user, 'phpunit log delete');
$result = $sitelog->tgroupLogList($this->tgroup->id());
$latest = current($result);
$this->assertEquals(1, $latest['deleted'], 'torrentlog-latest-is-deleted');
$this->assertEquals(-30, $latest['torrent_id'], 'torrentlog-latest-torrent-id');
$this->assertEquals(-5, $latest['user_id'], 'torrentlog-latest-user-id');
$this->assertEquals($torrent->id(), $latest['torrent_id'], 'torrentlog-latest-torrent-id');
$this->assertEquals($this->user->id(), $latest['user_id'], 'torrentlog-latest-user-id');
}
public function testRenderLog(): void {

View File

@@ -135,10 +135,10 @@ class TGroupTest extends TestCase {
}
public function testTGroupCoverArt(): void {
$coverId = $this->tgroup->addCoverArt('https://www.example.com/cover.jpg', 'cover art summary', 1, new Gazelle\Log);
$coverId = $this->tgroup->addCoverArt('https://www.example.com/cover.jpg', 'cover art summary', $this->userList['user'], new Gazelle\Log);
$this->assertGreaterThan(0, $coverId, 'tgroup-cover-art-add');
$this->assertEquals(1, $this->tgroup->removeCoverArt($coverId, 1, new Gazelle\Log), 'tgroup-cover-art-del-ok');
$this->assertEquals(0, $this->tgroup->removeCoverArt(9999999, 1, new Gazelle\Log), 'tgroup-cover-art-del-nok');
$this->assertEquals(1, $this->tgroup->removeCoverArt($coverId, $this->userList['user'], new Gazelle\Log), 'tgroup-cover-art-del-ok');
$this->assertEquals(0, $this->tgroup->removeCoverArt(9999999, $this->userList['user'], new Gazelle\Log), 'tgroup-cover-art-del-nok');
}
public function testTGroupRevision(): void {