From 3e3fdfb804b3faea02df1c0a40ed2cba3b5f3663 Mon Sep 17 00:00:00 2001 From: Git Date: Wed, 28 Aug 2013 23:08:41 +0000 Subject: [PATCH] Empty commit --- cheaters.php | 2 - classes/alias.class.php | 38 +- classes/artists.class.php | 54 +- classes/artists_similar.class.php | 15 +- classes/bitcoinrpc.class.php | 32 + classes/bookmarks.class.php | 15 +- classes/cache.class.php | 31 +- classes/calendar.class.php | 139 ++ classes/calendarview.class.php | 109 ++ classes/collages.class.php | 68 +- classes/comments.class.php | 395 ++++++ classes/commentsview.class.php | 94 ++ classes/config.template | 10 + classes/debug.class.php | 26 +- classes/donations.class.php | 836 ++++++++++++ classes/donationsbitcoin.class.php | 186 +++ classes/donationsview.class.php | 212 +++ classes/format.class.php | 78 +- classes/forums.class.php | 339 ++++- classes/g.class.php | 2 +- classes/inbox.class.php | 3 +- classes/invite_tree.class.php | 20 +- classes/irc.class.php | 21 +- classes/lastfm.class.php | 76 +- classes/mass_user_bookmarks_editor.class.php | 12 +- classes/mass_user_torrents_editor.class.php | 52 +- .../mass_user_torrents_table_view.class.php | 34 +- classes/misc.class.php | 126 +- classes/mysql.class.php | 6 +- classes/notificationsmanager.class.php | 659 +++++++++ classes/notificationsmanagerview.class.php | 151 +++ classes/paranoia.class.php | 4 +- classes/permissions.class.php | 65 +- classes/permissions_form.php | 1 - classes/requests.class.php | 96 +- classes/script_start.php | 31 +- classes/search.class.php | 15 +- classes/sitehistory.class.php | 94 +- classes/sitehistoryview.class.php | 18 +- classes/subscriptions.class.php | 334 +++++ classes/text.class.php | 13 +- classes/time.class.php | 38 +- classes/tools.class.php | 111 +- classes/torrent_form.class.php | 38 +- classes/torrents.class.php | 282 ++-- classes/torrentsdl.class.php | 20 +- classes/tracker.class.php | 5 +- classes/userrank.class.php | 29 +- classes/users.class.php | 208 +-- classes/view.class.php | 10 +- classes/votes.class.php | 89 +- classes/wiki.class.php | 7 +- design/privatefooter.php | 8 +- design/privateheader.php | 438 ++---- design/publicheader.php | 6 +- design/views/generic/reply/quickreply.php | 42 +- docs/CHANGES.txt | 21 + gazelle.sql | 776 +++++++---- sections/ajax/clear_user_notification.php | 39 + sections/ajax/forum/thread.php | 11 +- sections/ajax/get_user_notifications.php | 9 + sections/ajax/index.php | 6 + sections/ajax/info.php | 22 +- sections/ajax/request.php | 47 +- sections/ajax/subscriptions.php | 16 +- sections/ajax/tcomments.php | 60 +- sections/ajax/user.php | 13 +- sections/ajax/userhistory/post_history.php | 33 +- sections/api/index.php | 14 +- sections/artist/artist.php | 255 +--- sections/artist/delete.php | 4 +- sections/artist/edit.php | 8 +- sections/artist/index.php | 184 --- sections/artist/rename.php | 2 + sections/artist/take_warn.php | 79 -- sections/artist/warn.php | 70 - sections/better/files.php | 2 +- sections/better/folders.php | 4 +- sections/better/single.php | 2 +- sections/better/snatch.php | 2 +- sections/better/tags.php | 4 +- sections/better/transcode.php | 2 +- sections/better/transcode_beta.php | 2 +- sections/better/upload.php | 2 +- sections/bookmarks/torrents.php | 30 +- sections/collages/add_comment.php | 37 - sections/collages/all_comments.php | 91 +- sections/collages/artist_collage.php | 30 +- sections/collages/browse.php | 6 +- sections/collages/delete_comment.php | 48 - sections/collages/edit.php | 2 +- sections/collages/get_post.php | 30 - sections/collages/index.php | 12 - sections/collages/manage.php | 5 +- sections/collages/manage_artists.php | 5 +- sections/collages/take_delete.php | 16 +- sections/collages/takeedit_comment.php | 64 - sections/collages/torrent_collage.php | 64 +- sections/comments/artistcomments.php | 62 - sections/comments/collagecomments.php | 100 -- sections/comments/comments.php | 276 ++++ sections/comments/get.php | 15 + sections/comments/index.php | 87 +- sections/comments/jump.php | 11 + sections/comments/post.php | 52 - sections/comments/requestcomments.php | 101 -- sections/comments/take_delete.php | 14 + sections/comments/take_edit.php | 14 + sections/comments/take_post.php | 25 + sections/comments/take_warn.php | 49 + sections/comments/torrentcomments.php | 91 -- sections/comments/warn.php | 67 + sections/donate/donate.php | 106 +- sections/feeds/index.php | 18 +- sections/forums/ajax_get_edit.php | 4 +- sections/forums/delete.php | 7 +- sections/forums/forum.php | 42 +- sections/forums/get_post.php | 2 +- sections/forums/index.php | 22 +- sections/forums/main.php | 81 +- sections/forums/mod_thread.php | 37 +- sections/forums/newthread.php | 6 +- sections/forums/search.php | 48 +- sections/forums/subscribe.php | 14 - sections/forums/take_new_thread.php | 26 +- sections/forums/take_reply.php | 26 +- sections/forums/take_warn.php | 2 +- sections/forums/takeedit.php | 4 +- sections/forums/thread.php | 75 +- sections/friends/friends.php | 4 +- sections/inbox/conversation.php | 9 +- sections/inbox/inbox.php | 4 +- sections/index/feat_album.php | 2 +- sections/index/private.php | 2 +- sections/log/index.php | 9 +- sections/login/index.php | 17 +- sections/login/login.php | 18 +- sections/register/index.php | 2 + sections/reports/ajax_resolve_report.php | 4 +- sections/reports/array.php | 31 +- sections/reports/compose.php | 66 +- sections/reports/report.php | 24 +- sections/reports/reports.php | 81 +- sections/reports/stats.php | 15 +- sections/reports/takereport.php | 68 +- sections/reports/takeresolve.php | 4 +- sections/reportsv2/ajax_new_report.php | 18 +- sections/reportsv2/header.php | 14 +- sections/reportsv2/reports.php | 6 +- sections/reportsv2/static.php | 22 +- sections/reportsv2/views.php | 12 +- sections/requests/index.php | 188 --- sections/requests/request.php | 113 +- sections/requests/requests.php | 2 +- sections/requests/take_warn.php | 97 -- sections/requests/takedelete.php | 2 + sections/requests/takevote.php | 6 + sections/requests/warn.php | 74 -- sections/rules/ratio.php | 2 +- sections/schedule/index.php | 21 +- sections/sitehistory/index.php | 12 +- sections/sitehistory/take_edit.php | 4 +- sections/staffpm/common_responses.php | 16 +- sections/staffpm/makedonor.php | 86 +- sections/staffpm/staff_inbox.php | 56 +- sections/staffpm/unresolve.php | 7 +- sections/staffpm/user_inbox.php | 4 +- sections/staffpm/viewconv.php | 26 +- sections/tools/data/bitcoin_balance.php | 13 +- sections/tools/data/donation_log.php | 115 +- sections/tools/data/donor_rewards.php | 111 ++ sections/tools/data/service_stats.php | 10 +- sections/tools/index.php | 19 +- .../managers/ajax_get_calendar_event.php | 120 ++ .../managers/ajax_take_calendar_event.php | 16 + sections/tools/managers/bans.php | 4 +- sections/tools/managers/calendar.php | 29 + sections/tools/managers/change_log.php | 2 +- .../tools/managers/global_notification.php | 64 + .../managers/take_global_notification.php | 13 + sections/tools/misc/create_user.php | 7 +- sections/tools/services/get_cc.php | 2 +- sections/tools/services/get_host.php | 28 +- sections/tools/tools.php | 7 +- sections/top10/donors.php | 98 ++ sections/top10/history.php | 14 +- sections/top10/index.php | 3 + sections/top10/tags.php | 9 +- sections/top10/torrents.php | 61 +- sections/top10/users.php | 19 +- sections/top10/votes.php | 66 +- sections/torrents/browse.php | 85 +- sections/torrents/browse2.php | 69 +- sections/torrents/delete.php | 18 +- sections/torrents/details.php | 301 ++--- sections/torrents/downloadlist.php | 17 +- sections/torrents/edit.php | 2 - sections/torrents/editgroupid.php | 7 +- sections/torrents/functions.php | 22 +- sections/torrents/grouplog.php | 2 +- sections/torrents/index.php | 189 --- sections/torrents/masspm.php | 2 - sections/torrents/merge.php | 30 +- sections/torrents/notify.php | 14 +- sections/torrents/peerlist.php | 10 +- sections/torrents/snatchlist.php | 18 +- sections/torrents/take_warn.php | 79 -- sections/torrents/takechangecategory.php | 8 +- sections/torrents/takeedit.php | 5 +- sections/torrents/user.php | 18 +- sections/torrents/vote.php | 2 +- sections/torrents/warn.php | 70 - sections/user/advancedsearch.php | 193 +-- sections/user/community_stats.php | 33 +- sections/user/connchecker.php | 30 +- sections/user/donor_stats.php | 18 + sections/user/edit.php | 722 ++++++---- sections/user/index.php | 7 +- sections/user/linkedfunctions.php | 4 +- sections/user/subscribe.php | 13 - sections/user/takeedit.php | 106 +- sections/user/takemoderate.php | 9 +- sections/user/user.php | 292 ++-- sections/userhistory/catchup.php | 22 +- sections/userhistory/comments_subscribe.php | 9 + sections/userhistory/email_history.php | 4 +- sections/userhistory/index.php | 3 + sections/userhistory/post_history.php | 59 +- sections/userhistory/quote_notifications.php | 143 +- sections/userhistory/subscribed_collages.php | 36 +- sections/userhistory/subscriptions.php | 273 ++-- sections/userhistory/thread_subscribe.php | 43 +- sections/wiki/article.php | 6 +- static/common/symbols/donor_2.png | Bin 0 -> 328 bytes static/common/symbols/donor_3.png | Bin 0 -> 319 bytes static/common/symbols/donor_4.png | Bin 0 -> 321 bytes static/common/symbols/donor_5.png | Bin 0 -> 309 bytes static/common/symbols/donor_6.png | Bin 0 -> 311 bytes static/functions/browse.js | 20 +- static/functions/calendar.js | 39 + static/functions/comments.js | 146 +- static/functions/cssgallery.js | 8 +- static/functions/donor_titles.js | 36 + static/functions/form_validate.js | 5 + static/functions/mosaic.js | 10 + static/functions/noty/layouts/bottom.js | 34 + static/functions/noty/layouts/bottomCenter.js | 41 + static/functions/noty/layouts/bottomLeft.js | 43 + static/functions/noty/layouts/bottomRight.js | 43 + static/functions/noty/layouts/center.js | 56 + static/functions/noty/layouts/centerLeft.js | 61 + static/functions/noty/layouts/centerRight.js | 61 + static/functions/noty/layouts/inline.js | 31 + static/functions/noty/layouts/top.js | 34 + static/functions/noty/layouts/topCenter.js | 41 + static/functions/noty/layouts/topLeft.js | 43 + static/functions/noty/layouts/topRight.js | 43 + static/functions/noty/noty.js | 550 ++++++++ static/functions/noty/themes/default.js | 159 +++ static/functions/script_start.js | 28 +- static/functions/send_rippy.js | 40 + static/functions/sort.js | 8 +- static/functions/subscriptions.js | 11 + static/functions/tooltipster.js | 1 + static/functions/tooltipster_settings.js | 31 + static/functions/user_notifications.js | 124 ++ static/functions/user_settings.js | 62 + static/styles/anorex/style.css | 9 + static/styles/calendar/style.css | 58 + static/styles/dark_ambient/style.css | 12 +- static/styles/donor/style.css | 0 static/styles/global.css | 84 +- static/styles/layer_cake/style.css | 70 +- static/styles/layer_cake/style2.css | 753 ----------- static/styles/minimal/style.css | 4 +- static/styles/mono/style.css | 33 +- static/styles/postmod/style.css | 20 +- static/styles/proton/style.css | 7 +- static/styles/store/images/bg-black.png | Bin 0 -> 1074 bytes static/styles/store/images/bg-grid.png | Bin 0 -> 9942 bytes static/styles/store/images/hover-magnify.png | Bin 0 -> 2830 bytes static/styles/store/images/progress.gif | Bin 0 -> 2608 bytes static/styles/store/style.css | 92 ++ static/styles/tooltipster/custom.css | 28 + static/styles/tooltipster/reset.css | 44 + static/styles/tooltipster/style.css | 290 ++++ .../tooltipster/themes/tooltipster-light.css | 12 + .../tooltipster/themes/tooltipster-noir.css | 12 + .../tooltipster/themes/tooltipster-punk.css | 12 + .../tooltipster/themes/tooltipster-shadow.css | 12 + static/styles/white.cd/old_minified.css | 39 - static/styles/white.cd/style.css | 1173 +++++++++-------- 292 files changed, 11507 insertions(+), 7493 deletions(-) delete mode 100644 cheaters.php create mode 100644 classes/bitcoinrpc.class.php create mode 100644 classes/calendar.class.php create mode 100644 classes/calendarview.class.php create mode 100644 classes/comments.class.php create mode 100644 classes/commentsview.class.php create mode 100644 classes/donations.class.php create mode 100644 classes/donationsbitcoin.class.php create mode 100644 classes/donationsview.class.php create mode 100644 classes/notificationsmanager.class.php create mode 100644 classes/notificationsmanagerview.class.php create mode 100644 classes/subscriptions.class.php create mode 100644 sections/ajax/clear_user_notification.php create mode 100644 sections/ajax/get_user_notifications.php delete mode 100644 sections/artist/take_warn.php delete mode 100644 sections/artist/warn.php delete mode 100644 sections/collages/add_comment.php delete mode 100644 sections/collages/delete_comment.php delete mode 100644 sections/collages/get_post.php delete mode 100644 sections/collages/takeedit_comment.php delete mode 100644 sections/comments/artistcomments.php delete mode 100644 sections/comments/collagecomments.php create mode 100644 sections/comments/comments.php create mode 100644 sections/comments/get.php create mode 100644 sections/comments/jump.php delete mode 100644 sections/comments/post.php delete mode 100644 sections/comments/requestcomments.php create mode 100644 sections/comments/take_delete.php create mode 100644 sections/comments/take_edit.php create mode 100644 sections/comments/take_post.php create mode 100644 sections/comments/take_warn.php delete mode 100644 sections/comments/torrentcomments.php create mode 100644 sections/comments/warn.php delete mode 100644 sections/forums/subscribe.php delete mode 100644 sections/requests/take_warn.php delete mode 100644 sections/requests/warn.php create mode 100644 sections/tools/data/donor_rewards.php create mode 100644 sections/tools/managers/ajax_get_calendar_event.php create mode 100644 sections/tools/managers/ajax_take_calendar_event.php create mode 100644 sections/tools/managers/calendar.php create mode 100644 sections/tools/managers/global_notification.php create mode 100644 sections/tools/managers/take_global_notification.php create mode 100644 sections/top10/donors.php delete mode 100644 sections/torrents/take_warn.php delete mode 100644 sections/torrents/warn.php create mode 100644 sections/user/donor_stats.php delete mode 100644 sections/user/subscribe.php create mode 100644 sections/userhistory/comments_subscribe.php create mode 100644 static/common/symbols/donor_2.png create mode 100644 static/common/symbols/donor_3.png create mode 100644 static/common/symbols/donor_4.png create mode 100644 static/common/symbols/donor_5.png create mode 100644 static/common/symbols/donor_6.png create mode 100644 static/functions/calendar.js create mode 100644 static/functions/donor_titles.js create mode 100644 static/functions/mosaic.js create mode 100644 static/functions/noty/layouts/bottom.js create mode 100644 static/functions/noty/layouts/bottomCenter.js create mode 100644 static/functions/noty/layouts/bottomLeft.js create mode 100644 static/functions/noty/layouts/bottomRight.js create mode 100644 static/functions/noty/layouts/center.js create mode 100644 static/functions/noty/layouts/centerLeft.js create mode 100644 static/functions/noty/layouts/centerRight.js create mode 100644 static/functions/noty/layouts/inline.js create mode 100644 static/functions/noty/layouts/top.js create mode 100644 static/functions/noty/layouts/topCenter.js create mode 100644 static/functions/noty/layouts/topLeft.js create mode 100644 static/functions/noty/layouts/topRight.js create mode 100644 static/functions/noty/noty.js create mode 100644 static/functions/noty/themes/default.js create mode 100644 static/functions/send_rippy.js create mode 100644 static/functions/tooltipster.js create mode 100644 static/functions/tooltipster_settings.js create mode 100644 static/functions/user_notifications.js create mode 100644 static/functions/user_settings.js create mode 100644 static/styles/calendar/style.css create mode 100644 static/styles/donor/style.css delete mode 100644 static/styles/layer_cake/style2.css create mode 100644 static/styles/store/images/bg-black.png create mode 100644 static/styles/store/images/bg-grid.png create mode 100644 static/styles/store/images/hover-magnify.png create mode 100644 static/styles/store/images/progress.gif create mode 100644 static/styles/store/style.css create mode 100644 static/styles/tooltipster/custom.css create mode 100644 static/styles/tooltipster/reset.css create mode 100644 static/styles/tooltipster/style.css create mode 100644 static/styles/tooltipster/themes/tooltipster-light.css create mode 100644 static/styles/tooltipster/themes/tooltipster-noir.css create mode 100644 static/styles/tooltipster/themes/tooltipster-punk.css create mode 100644 static/styles/tooltipster/themes/tooltipster-shadow.css delete mode 100644 static/styles/white.cd/old_minified.css diff --git a/cheaters.php b/cheaters.php deleted file mode 100644 index 172ee44a..00000000 --- a/cheaters.php +++ /dev/null @@ -1,2 +0,0 @@ -query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT Alias, ArticleID FROM wiki_aliases"); - $Aliases = $DB->to_array('Alias'); - $Cache->cache_value('wiki_aliases', $Aliases, 3600 * 24 * 14); // 2 weeks + $Aliases = G::$DB->to_array('Alias'); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('wiki_aliases', $Aliases, 3600 * 24 * 14); // 2 weeks } function to_id($Alias) { - global $Cache, $DB; - $Aliases = $Cache->get_value('wiki_aliases'); + $Aliases = G::$Cache->get_value('wiki_aliases'); if (!$Aliases) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT Alias, ArticleID FROM wiki_aliases"); - $Aliases = $DB->to_array('Alias'); - $Cache->cache_value('wiki_aliases', $Aliases, 3600 * 24 * 14); // 2 weeks + $Aliases = G::$DB->to_array('Alias'); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('wiki_aliases', $Aliases, 3600 * 24 * 14); // 2 weeks } return $Aliases[$this->convert($Alias)]['ArticleID']; } @@ -32,21 +34,20 @@ function flush() { } function to_id($Alias) { - global $DB; $Alias = $this->convert($Alias); - $DB->query(" + G::$DB->query(" SELECT ArticleID FROM wiki_aliases WHERE Alias LIKE '$Alias'"); - list($ArticleID) = $DB->next_record(); + list($ArticleID) = G::$DB->next_record(); return $ArticleID; } */ function article($ArticleID, $Error = true) { - global $Cache, $DB; - $Contents = $Cache->get_value('wiki_article_'.$ArticleID); + $Contents = G::$Cache->get_value('wiki_article_'.$ArticleID); if (!$Contents) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT w.Revision, w.Title, @@ -63,11 +64,12 @@ function article($ArticleID, $Error = true) { LEFT JOIN users_main AS u ON u.ID=w.Author WHERE w.ID='$ArticleID' GROUP BY w.ID"); - if (!$DB->has_results() && $Error) { + if (!G::$DB->has_results() && $Error) { error(404); } - $Contents = $DB->to_array(); - $Cache->cache_value('wiki_article_'.$ArticleID, $Contents, 3600 * 24 * 14); // 2 weeks + $Contents = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('wiki_article_'.$ArticleID, $Contents, 3600 * 24 * 14); // 2 weeks } return $Contents; } diff --git a/classes/artists.class.php b/classes/artists.class.php index b88ac4fc..503b8a73 100644 --- a/classes/artists.class.php +++ b/classes/artists.class.php @@ -18,14 +18,13 @@ class Artists { * 6 => DJ */ public static function get_artists($GroupIDs) { - global $Cache, $DB; $Results = array(); $DBs = array(); foreach ($GroupIDs as $GroupID) { if (!is_number($GroupID)) { continue; } - $Artists = $Cache->get_value('groups_artists_'.$GroupID); + $Artists = G::$Cache->get_value('groups_artists_'.$GroupID); if (is_array($Artists)) { $Results[$GroupID] = $Artists; } else { @@ -37,7 +36,8 @@ public static function get_artists($GroupIDs) { if (empty($IDs)) { $IDs = "null"; } - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT ta.GroupID, ta.ArtistID, aa.Name, @@ -49,16 +49,17 @@ public static function get_artists($GroupIDs) { ORDER BY ta.GroupID ASC, ta.Importance ASC, aa.Name ASC;"); - while (list($GroupID, $ArtistID, $ArtistName, $ArtistImportance, $AliasID) = $DB->next_record(MYSQLI_BOTH, false)) { + while (list($GroupID, $ArtistID, $ArtistName, $ArtistImportance, $AliasID) = G::$DB->next_record(MYSQLI_BOTH, false)) { $Results[$GroupID][$ArtistImportance][] = array('id' => $ArtistID, 'name' => $ArtistName, 'aliasid' => $AliasID); $New[$GroupID][$ArtistImportance][] = array('id' => $ArtistID, 'name' => $ArtistName, 'aliasid' => $AliasID); } + G::$DB->set_query_id($QueryID); foreach ($DBs as $GroupID) { if (isset($New[$GroupID])) { - $Cache->cache_value('groups_artists_'.$GroupID, $New[$GroupID]); + G::$Cache->cache_value('groups_artists_'.$GroupID, $New[$GroupID]); } else { - $Cache->cache_value('groups_artists_'.$GroupID, array()); + G::$Cache->cache_value('groups_artists_'.$GroupID, array()); } } $Missing = array_diff($GroupIDs, array_keys($Results)); @@ -216,50 +217,53 @@ public static function display_artist($Artist, $MakeLink = true, $Escape = true) * @param int $ArtistID */ public static function delete_artist($ArtistID) { - global $DB, $LoggedUser, $Cache; - - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT Name FROM artists_group WHERE ArtistID = ".$ArtistID); - list($Name) = $DB->next_record(MYSQLI_NUM, false); + list($Name) = G::$DB->next_record(MYSQLI_NUM, false); // Delete requests - $DB->query(" + G::$DB->query(" SELECT RequestID FROM requests_artists WHERE ArtistID = $ArtistID AND ArtistID != 0"); - $Requests = $DB->to_array(); + $Requests = G::$DB->to_array(); foreach ($Requests AS $Request) { list($RequestID) = $Request; - $DB->query('DELETE FROM requests WHERE ID='.$RequestID); - $DB->query('DELETE FROM requests_votes WHERE RequestID='.$RequestID); - $DB->query('DELETE FROM requests_tags WHERE RequestID='.$RequestID); - $DB->query('DELETE FROM requests_artists WHERE RequestID='.$RequestID); + G::$DB->query('DELETE FROM requests WHERE ID='.$RequestID); + G::$DB->query('DELETE FROM requests_votes WHERE RequestID='.$RequestID); + G::$DB->query('DELETE FROM requests_tags WHERE RequestID='.$RequestID); + G::$DB->query('DELETE FROM requests_artists WHERE RequestID='.$RequestID); } // Delete artist - $DB->query('DELETE FROM artists_group WHERE ArtistID='.$ArtistID); - $DB->query('DELETE FROM artists_alias WHERE ArtistID='.$ArtistID); - $Cache->decrement('stats_artist_count'); + G::$DB->query('DELETE FROM artists_group WHERE ArtistID='.$ArtistID); + G::$DB->query('DELETE FROM artists_alias WHERE ArtistID='.$ArtistID); + G::$Cache->decrement('stats_artist_count'); // Delete wiki revisions - $DB->query('DELETE FROM wiki_artists WHERE PageID='.$ArtistID); + G::$DB->query('DELETE FROM wiki_artists WHERE PageID='.$ArtistID); // Delete tags - $DB->query('DELETE FROM artists_tags WHERE ArtistID='.$ArtistID); + G::$DB->query('DELETE FROM artists_tags WHERE ArtistID='.$ArtistID); - $Cache->delete_value('artist_'.$ArtistID); - $Cache->delete_value('artist_groups_'.$ArtistID); + // Delete artist comments, subscriptions and quote notifications + Comments::delete_page('artist', $ArtistID); + + G::$Cache->delete_value('artist_'.$ArtistID); + G::$Cache->delete_value('artist_groups_'.$ArtistID); // Record in log - if (!empty($LoggedUser['Username'])) { - $Username = $LoggedUser['Username']; + if (!empty(G::$LoggedUser['Username'])) { + $Username = G::$LoggedUser['Username']; } else { $Username = 'System'; } Misc::write_log("Artist $ArtistID ($Name) was deleted by $Username"); + G::$DB->set_query_id($QueryID); } diff --git a/classes/artists_similar.class.php b/classes/artists_similar.class.php index e555cefd..efb301a7 100644 --- a/classes/artists_similar.class.php +++ b/classes/artists_similar.class.php @@ -39,17 +39,18 @@ function load_data($Data) { } function set_up() { + $QueryID = G::$DB->get_query_id(); + $this->x = ceil(WIDTH / 2); $this->y = ceil(HEIGHT / 2); $this->xValues[$this->x] = $this->ID; $this->yValues[$this->y] = $this->ID; - global $DB; // Get artists that are directly similar to the artist $ArtistIDs = array(); - $DB->query(" + G::$DB->query(" SELECT s2.ArtistID, ag.Name, @@ -62,12 +63,12 @@ function set_up() { ORDER BY ass.Score DESC LIMIT 14"); - if (!$DB->has_results()) { + if (!G::$DB->has_results()) { return; } // Build into array. Each artist is its own object in $this->Artists - while (list($ArtistID, $Name, $Score) = $DB->next_record(MYSQLI_NUM, false)) { + while (list($ArtistID, $Name, $Score) = G::$DB->next_record(MYSQLI_NUM, false)) { if ($Score < 0) { continue; } @@ -78,7 +79,7 @@ function set_up() { } // Get similarities between artists on the map - $DB->query(" + G::$DB->query(" SELECT s1.ArtistID, s2.ArtistID @@ -90,7 +91,7 @@ function set_up() { AND s2.ArtistID IN('.implode(',', $ArtistIDs).')'); // Build into array - while (list($Artist1ID, $Artist2ID) = $DB->next_record()) { + while (list($Artist1ID, $Artist2ID) = G::$DB->next_record()) { $this->Artists[$Artist1ID]->Similar[$Artist2ID] = array('ID'=>$Artist2ID); } @@ -107,6 +108,8 @@ function set_up() { } } reset($this->Artists); + + G::$DB->set_query_id($QueryID); } function set_positions() { diff --git a/classes/bitcoinrpc.class.php b/classes/bitcoinrpc.class.php new file mode 100644 index 00000000..8951fe46 --- /dev/null +++ b/classes/bitcoinrpc.class.php @@ -0,0 +1,32 @@ + $Method, + 'params' => $Args, + 'id' => $MessageID) + ); + + $Request = array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/json', + 'content' => $Params + ) + ); + + if (!$Response = file_get_contents(BITCOIN_RPC_URL, false, stream_context_create($Request))) { + return false; + } + $Response = json_decode($Response); + if ($Response->id != $MessageID || !empty($Response->error) || empty($Response->result)) { + return false; + } + return $Response->result; + } +} diff --git a/classes/bookmarks.class.php b/classes/bookmarks.class.php index 00790b27..f94a5a30 100644 --- a/classes/bookmarks.class.php +++ b/classes/bookmarks.class.php @@ -69,7 +69,7 @@ public static function has_bookmarked($Type, $ID) { /** * Fetch all bookmarks of a certain type for a user. - * If UserID is false than defaults to $LoggedUser['ID'] + * If UserID is false than defaults to G::$LoggedUser['ID'] * * @param string $Type * type of bookmarks to fetch @@ -78,19 +78,20 @@ public static function has_bookmarked($Type, $ID) { * @return array the bookmarks */ public static function all_bookmarks($Type, $UserID = false) { - global $DB, $Cache, $LoggedUser; if ($UserID === false) { - $UserID = $LoggedUser['ID']; + $UserID = G::$LoggedUser['ID']; } $CacheKey = 'bookmarks_' . $Type . '_' . $UserID; - if (($Bookmarks = $Cache->get_value($CacheKey)) === false) { + if (($Bookmarks = G::$Cache->get_value($CacheKey)) === false) { list ($Table, $Col) = self::bookmark_schema($Type); - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT $Col FROM $Table WHERE UserID = '$UserID'"); - $Bookmarks = $DB->collect($Col); - $Cache->cache_value($CacheKey, $Bookmarks, 0); + $Bookmarks = G::$DB->collect($Col); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value($CacheKey, $Bookmarks, 0); } return $Bookmarks; } diff --git a/classes/cache.class.php b/classes/cache.class.php index 41414aaa..37cb13a0 100644 --- a/classes/cache.class.php +++ b/classes/cache.class.php @@ -40,15 +40,18 @@ class CACHE extends Memcache { protected $InTransaction = false; public $Time = 0; private $PersistentKeys = array( - 'stats_*', - 'percentiles_*', - 'top10tor_*', + 'ajax_requests_*', 'query_lock_*', + 'stats_*', + 'top10tor_*', 'top10votes_*', -// 'similar_albums_*', 'users_snatched_*', - 'ajax_requests_*' + + // Cache-based features + 'global_notification', + 'notifications_one_reads_*', ); + private $ClearedKeys = array(); public $CanClear = false; public $InternalCache = true; @@ -110,21 +113,27 @@ public function get_value($Key, $NoCache = false) { // Because of this, not user cache data will require a secondary pageload following the clearcache to update if (count($this->CacheHits) > 0) { foreach (array_keys($this->CacheHits) as $HitKey) { - if (!Misc::in_array_partial($HitKey, $this->PersistentKeys)) { + if (!isset($this->ClearedKeys[$HitKey]) && !Misc::in_array_partial($HitKey, $this->PersistentKeys)) { $this->delete($HitKey); unset($this->CacheHits[$HitKey]); + $this->ClearedKeys[$HitKey] = true; } } } + if (!isset($this->ClearedKeys[$Key])) { + $this->delete($Key); + $this->ClearedKeys[$Key] = true; + $this->Time += (microtime(true) - $StartTime) * 1000; + return false; + } + } elseif (!isset($this->ClearedKeys[$Key]) && $_GET['clearcache'] == $Key) { $this->delete($Key); + $this->ClearedKeys[$Key] = true; $this->Time += (microtime(true) - $StartTime) * 1000; return false; - } elseif ($_GET['clearcache'] == $Key) { - $this->delete($Key); - $this->Time += (microtime(true) - $StartTime) * 1000; - return false; - } elseif (in_array($_GET['clearcache'], $this->CacheHits)) { + } elseif (!isset($this->ClearedKeys[$_GET['clearcache']]) && in_array($_GET['clearcache'], $this->CacheHits)) { unset($this->CacheHits[$_GET['clearcache']]); + $this->ClearedKeys[$_GET['clearcache']] = true; $this->delete($_GET['clearcache']); } } diff --git a/classes/calendar.class.php b/classes/calendar.class.php new file mode 100644 index 00000000..d79605d9 --- /dev/null +++ b/classes/calendar.class.php @@ -0,0 +1,139 @@ + "IRC Meeting", "IRC Brainstorm", "Poll Deadline", "Feature Release", "Blog Post", "Announcement", "Featured Album", "Product Release", "Staff Picks", "Forum Brainstorm", "Forum Discussion", "Promotion"); + public static $Importances = array(1 => "Critical", "Important", "Average", "Meh"); + public static $Colors = array( + "Critical" => "red", + "Important" => "yellow", + "Average" => "green", + "Meh" => "blue"); + + public static $Teams = array( + 0 => "Everyone", + 1 => "Staff" + + ); + + public static function can_view() { + return check_perms('users_mod') + + ; + } + + private static function get_teams_query() { + $Teams = array(0); + $IsMod = check_perms("users_mod"); + if ($IsMod) { + $Teams[] = 1; + } + + return "Team IN (" . implode(",", $Teams) . ") "; + } + + public static function get_events($Month, $Year) { + if (empty($Month) || empty($Year)) { + $Date = getdate(); + $Month = $Date['mon']; + $Year = $Date['year']; + } + $Month = (int) $Month; + $Year = (int) $Year; + + $TeamsSQL = self::get_teams_query(); + + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + ID, Team, Title, Category, Importance, DAY(StartDate) AS StartDay, DAY(EndDate) AS EndDay + FROM calendar + WHERE + MONTH(StartDate) = '$Month' + AND + YEAR(StartDate) = '$Year' + AND + $TeamsSQL"); + $Events = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); + return $Events; + } + + public static function get_event($ID) { + $ID = (int) $ID; + if (empty($ID)) { + error("Invalid ID"); + } + $TeamsSQL = self::get_teams_query(); + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + ID, Team, Title, Body, Category, Importance, AddedBy, StartDate, EndDate + FROM calendar + WHERE + ID = '$ID' + AND + $TeamsSQL"); + $Event = G::$DB->next_record(MYSQLI_ASSOC); + G::$DB->set_query_id($QueryID); + return $Event; + } + + public static function create_event($Title, $Body, $Category, $Importance, $Team, $UserID, $StartDate, $EndDate = null) { + if (empty($Title) || empty($Body) || !is_number($Category) || !is_number($Importance) || !is_number($Team) || empty($StartDate)) { + error("Error adding event"); + } + $Title = db_string($Title); + $Body = db_string($Body); + $Category = (int) $Category; + $Importance = (int) $Importance; + $UserID = (int) $UserID; + $Team = (int) $Team; + $StartDate = db_string($StartDate); + $EndDate = db_string($EndDate); + + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + INSERT INTO calendar + (Title, Body, Category, Importance, Team, StartDate, EndDate, AddedBy) + VALUES + ('$Title', '$Body', '$Category', '$Importance', '$Team' '$StartDate', '$EndDate', '$UserID')"); + G::$DB->set_query_id($QueryID); + } + + public static function update_event($ID, $Title, $Body, $Category, $Importance, $Team, $StartDate, $EndDate = null) { + if (!is_number($ID) || empty($Title) || empty($Body) || !is_number($Category) || !is_number($Importance) || !is_number($Team) || empty($StartDate)) { + error("Error updating event"); + } + $ID = (int) $ID; + $Title = db_string($Title); + $Body = db_string($Body); + $Category = (int) $Category; + $Importance = (int) $Importance; + $Team = (int) $Team; + $StartDate = db_string($StartDate); + $EndDate = db_string($EndDate); + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + UPDATE calendar + SET + Title = '$Title', + Body = '$Body', + Category = '$Category', + Importance = '$Importance', + Team = '$Team', + StartDate = '$StartDate', + EndDate = '$EndDate' + WHERE + ID = '$ID'"); + G::$DB->set_query_id($QueryID); + } + + public static function remove_event($ID) { + $ID = (int) $ID; + if (!empty($ID)) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("DELETE FROM calendar WHERE ID = '$ID'"); + G::$DB->set_query_id($QueryID); + } + } + +} diff --git a/classes/calendarview.class.php b/classes/calendarview.class.php new file mode 100644 index 00000000..c6c2fdad --- /dev/null +++ b/classes/calendarview.class.php @@ -0,0 +1,109 @@ + +

+ < + + > +

+ + += $Day)) { + $Results[] = $Event; + } + } + return $Results; + } + + + private static function render_events_day($Day, $Events) { + $Events = self::get_events_on($Day, $Events); + foreach ($Events as $Event) { + $Color = Calendar::$Colors[Calendar::$Importances[$Event['Importance']]]; + $Category = Calendar::$Categories[$Event['Category']]; + $Tooltip = $Event['Title'] . " - " . Calendar::$Categories[$Event['Category']] . " - " . Calendar::$Importances[$Event['Importance']]; +?> +

+ + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+
+ +
+
+get_value('collage_comments_'.$CollageID); - if ($NumComments === false) { - $DB->query(" - SELECT COUNT(ID) - FROM collages_comments - WHERE CollageID = '$CollageID'"); - list($NumComments) = $DB->next_record(); - $Cache->cache_value('collage_comments_'.$CollageID, $NumComments, 0); - } - return $NumComments; - } - - public static function get_comment_catalogue($CollageID, $CatalogueID) { - global $DB, $Cache; - $Catalogue = $Cache->get_value('collage_comments_'.$CollageID.'_catalogue_'.$CatalogueID); - if ($Catalogue === false) { - $CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - $DB->query(" - SELECT - ID, - UserID, - Time, - Body - FROM collages_comments - WHERE CollageID = '$CollageID' - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false, MYSQLI_ASSOC); - $Cache->cache_value('collage_comments_'.$CollageID.'_catalogue_'.$CatalogueID, $Catalogue, 0); - } - return $Catalogue; - } - public static function increase_subscriptions($CollageID) { - global $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" UPDATE collages SET Subscribers = Subscribers + 1 WHERE ID = '$CollageID'"); - + G::$DB->set_query_id($QueryID); } public static function decrease_subscriptions($CollageID) { - global $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" UPDATE collages SET Subscribers = IF(Subscribers < 1, 0, Subscribers - 1) WHERE ID = '$CollageID'"); + G::$DB->set_query_id($QueryID); } public static function create_personal_collage() { - global $DB, $LoggedUser; - - $DB->query(" + G::$DB->query(" SELECT COUNT(ID) FROM collages - WHERE UserID = '$LoggedUser[ID]' + WHERE UserID = '" . G::$LoggedUser['ID'] . "' AND CategoryID = '0' AND Deleted = '0'"); - list($CollageCount) = $DB->next_record(); + list($CollageCount) = G::$DB->next_record(); - if ($CollageCount >= $LoggedUser['Permissions']['MaxCollages']) { - list($CollageID) = $DB->next_record(); + if ($CollageCount >= G::$LoggedUser['Permissions']['MaxCollages']) { + // TODO: fix this, the query was for COUNT(ID), so I highly doubt that this works... - Y + list($CollageID) = G::$DB->next_record(); header('Location: collage.php?id='.$CollageID); die(); } - $NameStr = ($CollageCount > 0) ? ' no. ' . ($CollageCount + 1) : ''; - $DB->query(" + $NameStr = db_string(G::$LoggedUser['Username'] . "'s personal collage" . ($CollageCount > 0 ? ' no. ' . ($CollageCount + 1) : '')); + $Description = db_string('Personal collage for ' . G::$LoggedUser['Username'] . '. The first 5 albums will appear on his or her [url=https://' . SSL_SITE_URL . '/user.php?id= ' . G::$LoggedUser['ID'] . ']profile[/url].'); + G::$DB->query(" INSERT INTO collages (Name, Description, CategoryID, UserID) VALUES - ('$LoggedUser[Username]\'s personal collage$NameStr', 'Personal collage for $LoggedUser[Username]. The first 5 albums will appear on his or her [url=https:\/\/".SSL_SITE_URL."\/user.php?id=$LoggedUser[ID]]profile[\/url].', '0', $LoggedUser[ID])"); - $CollageID = $DB->inserted_id(); + ('$NameStr', '$Description', '0', " . G::$LoggedUser['ID'] . ")"); + $CollageID = G::$DB->inserted_id(); header('Location: collage.php?id='.$CollageID); die(); } - } diff --git a/classes/comments.class.php b/classes/comments.class.php new file mode 100644 index 00000000..3290eecd --- /dev/null +++ b/classes/comments.class.php @@ -0,0 +1,395 @@ +get_query_id(); + G::$DB->query(" + SELECT + CEIL( + ( + SELECT COUNT(ID)+1 + FROM comments + WHERE Page = '$Page' + AND PageID = $PageID + )/" . TORRENT_COMMENTS_PER_PAGE . " + ) AS Pages"); + list($Pages) = G::$DB->next_record(); + + G::$DB->query(" + INSERT INTO comments (Page, PageID, AuthorID, AddedTime, Body) + VALUES ('$Page', $PageID, " . G::$LoggedUser['ID'] . ", '" . sqltime() . "', '" . db_string($Body) . "')"); + $PostID = G::$DB->inserted_id(); + + $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + G::$Cache->delete_value($Page.'_comments_'.$PageID.'_catalogue_'.$CatalogueID); + G::$Cache->delete_value($Page.'_comments_'.$PageID); + + Subscriptions::flush_subscriptions($Page, $PageID); + Subscriptions::quote_notify($Body, $PostID, $Page, $PageID); + + G::$DB->set_query_id($QueryID); + + return $PostID; + } + + /** + * Edit a comment + * @param int $PostID + * @param string $NewBody + * @todo move permission check out of here/remove hardcoded error(404) + */ + public static function edit($PostID, $NewBody) { + $QueryID = G::$DB->get_query_id(); + + G::$DB->query(" + SELECT + Body, + AuthorID, + Page, + PageID, + AddedTime + FROM comments + WHERE ID = $PostID"); + if (!G::$DB->has_results()) { + return false; + } + list($OldBody, $AuthorID, $Page, $PageID, $AddedTime) = G::$DB->next_record(); + + if (G::$LoggedUser['ID'] != $AuthorID && !check_perms('site_moderate_forums')) { + return false; + } + + G::$DB->query(" + SELECT CEIL(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page + FROM comments + WHERE Page = '$Page' + AND PageID = $PageID + AND ID <= $PostID"); + list($CommPage) = G::$DB->next_record(); + + // Perform the update + G::$DB->query(" + UPDATE comments + SET + Body = '" . db_string($NewBody) . "', + EditedUserID = " . G::$LoggedUser['ID'] . ", + EditedTime = '" . sqltime() . "' + WHERE ID = $PostID"); + + // Update the cache + $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $CommPage - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + G::$Cache->delete_value($Page . '_comments_' . $PageID . '_catalogue_' . $CatalogueID); + + if ($Page == 'collages') { + // On collages, we also need to clear the collage key (collage_$CollageID), because it has the comments in it... (why??) + G::$Cache->delete_value('collage_' . $PageID); + } + + G::$DB->query(" + INSERT INTO comments_edits (Page, PostID, EditUser, EditTime, Body) + VALUES ('$Page', $PostID, " . G::$LoggedUser['ID'] . ", '" . sqltime() . "', '" . db_string($OldBody) . "')"); + + G::$DB->set_query_id($QueryID); + + return true; // TODO: this should reflect whether or not the update was actually successful, e.g. by checking G::$DB->affected_rows after the UPDATE query + } + + /** + * Delete a comment + * @param int $PostID + */ + public static function delete($PostID) { + $QueryID = G::$DB->get_query_id(); + // Get page, pageid + G::$DB->query("SELECT Page, PageID FROM comments WHERE ID = $PostID"); + if (!G::$DB->has_results()) { + // no such comment? + G::$DB->set_query_id($QueryID); + return false; + } + list ($Page, $PageID) = G::$DB->next_record(); + // get number of pages + G::$DB->query(" + SELECT + CEIL(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Pages, + CEIL(SUM(IF(ID <= $PostID, 1, 0)) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page + FROM comments + WHERE Page = '$Page' AND PageID = $PageID + GROUP BY PageID"); + if (!G::$DB->has_results()) { + // the comment $PostID was probably not posted on $Page + G::$DB->set_query_id($QueryID); + return false; + } + list($CommPages, $CommPage) = G::$DB->next_record(); + + // $CommPages = number of pages in the thread + // $CommPage = which page the post is on + // These are set for cache clearing. + + G::$DB->query("DELETE FROM comments WHERE ID = $PostID"); + G::$DB->query("DELETE FROM comments_edits WHERE Page = '$Page' AND PostID = $PostID"); + + G::$DB->query("DELETE FROM users_notify_quoted WHERE Page = '$Page' AND PostID = $PostID"); + + Subscriptions::flush_subscriptions($Page, $PageID); + Subscriptions::flush_quote_notifications($Page, $PageID); + + //We need to clear all subsequential catalogues as they've all been bumped with the absence of this post + $ThisCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $CommPage - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + $LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $CommPages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + for ($i = $ThisCatalogue; $i <= $LastCatalogue; ++$i) { + G::$Cache->delete_value($Page . '_comments_' . $PageID . '_catalogue_' . $i); + } + + G::$Cache->delete_value($Page . '_comments_' . $PageID); + + if ($Page == 'collages') { + // On collages, we also need to clear the collage key (collage_$CollageID), because it has the comments in it... (why??) + G::$Cache->delete_value('collage_' . $PageID); + } + + G::$DB->set_query_id($QueryID); + + return true; + } + + /** + * Get the URL to a comment, already knowing the Page and PostID + * @param string $Page + * @param int $PageID + * @param int $PostID + * @return string|bool The URL to the comment or false on error + */ + public static function get_url($Page, $PageID, $PostID = null) { + $Post = (!empty($PostID) ? "&postid=$PostID#post$PostID" : ''); + switch ($Page) { + case 'artist': + return "artist.php?id=$PageID$Post"; + case 'collages': + return "collages.php?action=comments&collageid=$PageID$Post"; + case 'requests': + return "requests.php?action=view&id=$PageID$Post"; + case 'torrents': + return "torrents.php?id=$PageID$Post"; + default: + return false; + } + } + + /** + * Get the URL to a comment + * @param int $PostID + * @return string|bool The URL to the comment or false on error + */ + public static function get_url_query($PostID) { + $QueryID = G::$DB->get_query_id(); + + G::$DB->query("SELECT Page, PageID FROM comments WHERE ID = $PostID"); + if (!G::$DB->has_results()) { + error(404); + } + list($Page, $PageID) = G::$DB->next_record(); + + G::$DB->set_query_id($QueryID); + + return self::get_url($Page, $PageID, $PostID); + } + + /** + * Load a page's comments. This takes care of `postid` and (indirectly) `page` parameters passed in $_GET. + * Quote notifications and last read are also handled here, unless $HandleSubscriptions = false is passed. + * @param string $Page + * @param int $PageID + * @param bool $HandleSubscriptions Whether or not to handle subscriptions (last read & quote notifications) + * @return array ($NumComments, $Page, $Thread, $LastRead) + * $NumComments: the total number of comments on this artist/request/torrent group + * $Page: the page we're currently on + * $Thread: an array of all posts on this page + * $LastRead: ID of the last comment read by the current user in this thread; + * will be false if $HandleSubscriptions == false or if there are no comments on this page + */ + public static function load($Page, $PageID, $HandleSubscriptions = true) { + $QueryID = G::$DB->get_query_id(); + + // Get the total number of comments + $NumComments = G::$Cache->get_value($Page.'_comments_'.$PageID); + if ($NumComments === false) { + G::$DB->query(" + SELECT COUNT(ID) + FROM comments + WHERE Page = '$Page' + AND PageID = $PageID"); + list($NumComments) = G::$DB->next_record(); + G::$Cache->cache_value($Page.'_comments_'.$PageID, $NumComments, 0); + } + + // If a postid was passed, we need to determine which page that comment is on. + // Format::page_limit handles a potential $_GET['page'] + if (isset($_GET['postid']) && is_number($_GET['postid']) && $NumComments > TORRENT_COMMENTS_PER_PAGE) { + G::$DB->query(" + SELECT COUNT(ID) + FROM comments + WHERE Page = '$Page' + AND PageID = $PageID + AND ID <= $_GET[postid]"); + list($PostNum) = G::$DB->next_record(); + list($CommPage, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $PostNum); + } else { + list($CommPage, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $NumComments); + } + + // Get the cache catalogue + $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $CommPage - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + + // Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page + $Catalogue = G::$Cache->get_value($Page.'_comments_'.$PageID.'_catalogue_'.$CatalogueID); + if ($Catalogue === false) { + $CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; + G::$DB->query(" + SELECT + c.ID, + c.AuthorID, + c.AddedTime, + c.Body, + c.EditedUserID, + c.EditedTime, + u.Username + FROM comments AS c + LEFT JOIN users_main AS u ON u.ID = c.EditedUserID + WHERE c.Page = '$Page' AND c.PageID = $PageID + ORDER BY c.ID + LIMIT $CatalogueLimit"); + $Catalogue = G::$DB->to_array(false, MYSQLI_ASSOC); + G::$Cache->cache_value($Page.'_comments_'.$PageID.'_catalogue_'.$CatalogueID, $Catalogue, 0); + } + + //This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue + $Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $CommPage - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); + + if ($HandleSubscriptions && count($Thread) > 0) { + // quote notifications + $LastPost = end($Thread); + $LastPost = $LastPost['ID']; + $FirstPost = reset($Thread); + $FirstPost = $FirstPost['ID']; + G::$DB->query(" + UPDATE users_notify_quoted + SET UnRead = false + WHERE UserID = " . G::$LoggedUser['ID'] . " + AND Page = '$Page' + AND PageID = $PageID + AND PostID >= $FirstPost + AND PostID <= $LastPost"); + if (G::$DB->affected_rows()) { + G::$Cache->delete_value('notify_quoted_' . G::$LoggedUser['ID']); + } + + // last read + G::$DB->query("SELECT PostID FROM users_comments_last_read WHERE UserID = " . G::$LoggedUser['ID'] . " AND Page = '$Page' AND PageID = $PageID"); + list($LastRead) = G::$DB->next_record(); + if($LastRead < $LastPost) { + G::$DB->query("INSERT INTO users_comments_last_read + (UserID, Page, PageID, PostID) VALUES + (" . G::$LoggedUser['ID'] . ", '$Page', $PageID, $LastPost) + ON DUPLICATE KEY UPDATE PostID = $LastPost"); + G::$Cache->delete_value('subscriptions_user_new_' . G::$LoggedUser['ID']); + } + } else { + $LastRead = false; + } + + G::$DB->set_query_id($QueryID); + + return array($NumComments, $CommPage, $Thread, $LastRead); + } + + /** + * Merges all comments from $Page/$PageID into $Page/$TargetPageID. This also takes care of quote notifications, subscriptions and cache. + * @param type $Page + * @param type $PageID + * @param type $TargetPageID + */ + public static function merge($Page, $PageID, $TargetPageID) { + $QueryID = G::$DB->get_query_id(); + + G::$DB->query("UPDATE comments SET PageID = $TargetPageID WHERE Page = '$Page' AND PageID = $PageID"); + + // quote notifications + G::$DB->query("UPDATE users_notify_quoted SET PageID = $TargetPageID WHERE Page = '$Page' AND PageID = $PageID"); + + // comment subscriptions + Subscriptions::move_subscriptions($Page, $PageID, $TargetPageID); + + // cache (we need to clear all comment catalogues) + G::$DB->query(" + SELECT + CEIL(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Pages + FROM comments + WHERE Page = '$Page' + AND PageID = $TargetPageID + GROUP BY PageID"); + list($CommPages) = G::$DB->next_record(); + $LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $CommPages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + for ($i = 0; $i <= $LastCatalogue; ++$i) { + G::$Cache->delete_value($Page . '_comments_' . $TargetPageID . '_catalogue_' . $i); + } + G::$Cache->delete_value($Page.'_comments_'.$TargetPageID); + G::$DB->set_query_id($QueryID); + } + + /** + * Delete all comments on $Page/$PageID (deals with quote notifications and subscriptions as well) + * @param string $Page + * @param int $PageID + * @return boolean + */ + public static function delete_page($Page, $PageID) { + $QueryID = G::$DB->get_query_id(); + + // get number of pages + G::$DB->query(" + SELECT + CEIL(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Pages + FROM comments + WHERE Page = '$Page' AND PageID = $PageID + GROUP BY PageID"); + if (!G::$DB->has_results()) { + return false; + } + list($CommPages) = G::$DB->next_record(); + + // Delete comments + G::$DB->query("DELETE FROM comments WHERE Page = '$Page' AND PageID = $PageID"); + + // Delete quote notifications + Subscriptions::flush_quote_notifications($Page, $PageID); + G::$DB->query("DELETE FROM users_notify_quoted WHERE Page = '$Page' AND PageID = $PageID"); + + // Deal with subscriptions + Subscriptions::move_subscriptions($Page, $PageID, null); + + // Clear cache + $LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $CommPages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); + for ($i = 0; $i <= $LastCatalogue; ++$i) { + G::$Cache->delete_value($Page . '_comments_' . $PageID . '_catalogue_' . $i); + } + G::$Cache->delete_value($Page.'_comments_'.$PageID); + + G::$DB->set_query_id($QueryID); + + return true; + } +} diff --git a/classes/commentsview.class.php b/classes/commentsview.class.php new file mode 100644 index 00000000..24f93d5b --- /dev/null +++ b/classes/commentsview.class.php @@ -0,0 +1,94 @@ + $LastRead)); + } + } + + /** + * Render one comment + * @param int $AuthorID + * @param int $PostID + * @param string $Body + * @param string $AddedTime + * @param int $EditedUserID + * @param string $EditedTime + * @param string $Link The link to the post elsewhere on the site + * @param string $Header The header used in the post + * @param bool $Tools Whether or not to show [Edit], [Report] etc. + * @todo Find a better way to pass the page (artist, collages, requests, torrents) to this function than extracting it from $Link + */ + function render_comment($AuthorID, $PostID, $Body, $AddedTime, $EditedUserID, $EditedTime, $Link, $Unread = false, $Header = '', $Tools = true) { + global $Text; // TODO: convert Text class to static and get rid of this crap + $UserInfo = Users::user_info($AuthorID); + $Header = '' . Users::format_username($AuthorID, true, true, true, true, false) . ' ' . time_diff($AddedTime) . $Header; +?> + + + + + + + + + + + + + + + + +
+
# + + + - Quote + + - Edit + + - Delete + +
+
+ Report += $UserInfo['Class']) { +?> + + - Warn + +   + + +
+
+ + +
+ full_format($Body)?> + +
+
+ + « + + Last edited by + + +
+
+warnings(); // see comment in MYSQL::query + G::$DB->warnings(); // see comment in MYSQL::query /*$Queries = $this->get_queries(); $DBWarningCount = 0; foreach ($Queries as $Query) { @@ -53,8 +53,7 @@ public function profile($Automatic = '') { }*/ if (isset($_REQUEST['profile'])) { - global $LoggedUser; - $Reason[] = 'Requested by '.$LoggedUser['Username']; + $Reason[] = 'Requested by ' . G::$LoggedUser['Username']; } $this->Perf['Memory usage'] = (($Ram>>10) / 1024).' MB'; @@ -70,12 +69,12 @@ public function profile($Automatic = '') { } public function analysis($Message, $Report = '', $Time = 43200) { - global $Cache, $Document; + global $Document; if (empty($Report)) { $Report = $Message; } $Identifier = Users::make_secret(5); - $Cache->cache_value( + G::$Cache->cache_value( 'analysis_'.$Identifier, array( 'url' => $_SERVER['REQUEST_URI'], @@ -269,13 +268,11 @@ public function get_includes() { } public function get_cache_time() { - global $Cache; - return $Cache->Time; + return G::$Cache->Time; } public function get_cache_keys() { - global $Cache; - return array_keys($Cache->CacheHits); + return array_keys(G::$Cache->CacheHits); } public function get_sphinx_queries() { @@ -301,13 +298,11 @@ public function get_sphinxql_time() { } public function get_queries() { - global $DB; - return $DB->Queries; + return G::$DB->Queries; } public function get_query_time() { - global $DB; - return $DB->Time; + return G::$DB->Time; } public function get_logged_vars() { @@ -467,7 +462,6 @@ public function constant_table($Constants = false) { } public function cache_table($CacheKeys = false) { - global $Cache; $Header = 'Cache keys'; if (!is_array($CacheKeys)) { $CacheKeys = $this->get_cache_keys(); @@ -492,7 +486,7 @@ public function cache_table($CacheKeys = false) { Clear this cache key - + diff --git a/classes/donations.class.php b/classes/donations.class.php new file mode 100644 index 00000000..f6459f1f --- /dev/null +++ b/classes/donations.class.php @@ -0,0 +1,836 @@ + $Source, + "Price" => $DonationAmount, + "Currency" => $Currency, + "Source" => $Source, + "Reason" => $Reason, + "SendPM" => true)); + } + + public static function donate($UserID, $Args) { + $UserID = (int) $UserID; + $QueryID = G::$DB->get_query_id(); + + G::$DB->query("SELECT 1 FROM users_main WHERE ID = '$UserID'"); + if (G::$DB->has_results()) { + G::$Cache->InternalCache = false; + foreach($Args as &$Arg) { + $Arg = db_string($Arg); + } + extract($Args); + + // We don't always get a date passed in. + if (empty($Date)) { + $Date = sqltime(); + } + + // Get the ID of the staff member making the edit + $AddedBy = 0; + if (!self::$IsSchedule) { + $AddedBy = G::$LoggedUser['ID']; + } + + // Legacy donor, should remove at some point + G::$DB->query("UPDATE users_info SET Donor = '1' WHERE UserID = '$UserID'"); + // Give them the extra invite + $ExtraInvite = G::$DB->affected_rows(); + + // A staff member is directly manipulating donor points + if ($Manipulation == "Direct") { + $DonorPoints = $Rank; + $AdjustedRank = $Rank >= MAX_EXTRA_RANK ? MAX_EXTRA_RANK : $Rank; + G::$DB->query(" + INSERT INTO users_donor_ranks + (UserID, Rank, TotalRank, DonationTime) + VALUES + ('$UserID', '$AdjustedRank', '$TotalRank', '$Date') + ON DUPLICATE KEY UPDATE + Rank = '$AdjustedRank', + TotalRank = '$TotalRank', + DonationTime = '$Date'"); + } + else { + // Donations from the store get donor points directly, no need to calculate them + if ($Source == "Store Parser") { + $ConvertedPrice = self::currency_exchange($Amount * $Price, $Currency); + } else { + $ConvertedPrice = self::currency_exchange($Price, $Currency); + $DonorPoints = self::calculate_rank($ConvertedPrice); + } + $IncreaseRank = $DonorPoints; + + // Rank is the same thing as DonorPoints + $CurrentRank = self::get_rank($UserID); + // A user's donor rank can never exceed MAX_EXTRA_RANK + // If the amount they donated causes it to overflow, chnage it to MAX_EXTRA_RANK + // The total rank isn't affected by this, so their original donor point value is added to it + if (($CurrentRank + $DonorPoints) >= MAX_EXTRA_RANK) { + $AdjustedRank = MAX_EXTRA_RANK; + } else { + $AdjustedRank = $CurrentRank + $DonorPoints; + } + G::$DB->query(" + INSERT INTO users_donor_ranks + (UserID, Rank, TotalRank, DonationTime) + VALUES + ('$UserID', '$AdjustedRank', '$DonorPoints', '$Date') + ON DUPLICATE KEY UPDATE + Rank = '$AdjustedRank', + TotalRank = TotalRank + '$DonorPoints', + DonationTime = '$Date'"); + } + // Clear the rank cache key + G::$Cache->delete_value("donor_rank_$UserID"); + + // Get their rank + $Rank = self::get_rank($UserID); + $TotalRank = self::get_total_rank($UserID); + + // Now that their rank and total rank has been set, we can calculate their special rank + self::calculate_special_rank($UserID); + + // Hand out invites + G::$DB->query("SELECT InvitesRecievedRank FROM users_donor_ranks WHERE UserID = '$UserID'"); + list($InvitesRecievedRank) = G::$DB->next_record(); + $AdjustedRank = $Rank >= MAX_RANK ? (MAX_RANK - 1) : $Rank; + $InviteRank = $AdjustedRank - $InvitesRecievedRank; + if ($InviteRank > 0) { + $Invites = $ExtraInvite ? ($InviteRank + 1) : $InviteRank; + G::$DB->query("UPDATE users_main SET Invites = Invites + '$Invites' WHERE ID = $UserID"); + G::$DB->query("UPDATE users_donor_ranks SET InvitesRecievedRank = '$AdjustedRank' WHERE UserID = '$UserID'"); + } + + // Send them a thank you PM + if ($SendPM) { + $Subject = "Your contribution has been received and credited. Thank you!"; + $Body = self::get_pm_body($Source, $Currency, $Price, $IncreaseRank, $Rank); + Misc::send_pm($UserID, 0, $Subject, $Body); + } + + // Lastly, add this donation to our history + G::$DB->query(" + INSERT INTO donations + (UserID, Amount, Source, Reason, Currency, Email, Time, AddedBy, Rank, TotalRank) + VALUES + ('$UserID', '$ConvertedPrice', '$Source', '$Reason', '$Currency', '$Email', '$Date', '$AddedBy', '$DonorPoints', '$TotalRank')"); + + + // Clear their user cache keys because the users_info values has been modified + G::$Cache->delete_value("user_info_$UserID"); + G::$Cache->delete_value("user_info_heavy_$UserID"); + G::$Cache->delete_value("donor_rank_$UserID"); + G::$Cache->delete_value("donor_special_rank_$UserID"); + + } + G::$DB->set_query_id($QueryID); + } + + private static function calculate_special_rank($UserID) { + $UserID = (int) $UserID; + $QueryID = G::$DB->get_query_id(); + // Are they are special? + G::$DB->query(" + SELECT TotalRank, SpecialRank + FROM users_donor_ranks + WHERE UserID = '$UserID'"); + if (G::$DB->has_results()) { + // Adjust their special rank depending on the total rank. + list($TotalRank, $SpecialRank) = G::$DB->next_record(); + if ($TotalRank < 10) { + $SpecialRank = 0; + } + if ($TotalRank >= 10) { + Misc::send_pm($UserID, 0, "You've Reached Special Donor Rank #1! You've Earned: One User Pick. Details Inside.", self::get_special_rank_one_pm()); + $SpecialRank = 1; + } + if ($TotalRank >= 20) { + Misc::send_pm($UserID, 0, "You've Reached Special Donor Rank #2! You've Earned: The Double-Avatar. Details Inside.", self::get_special_rank_two_pm()); + $SpecialRank = 2; + } + if ($TotalRank >= 50) { + Misc::send_pm($UserID, 0, "You've Reached Special Donor Rank #3! You've Earned: Diamond Rank. Details Inside.", self::get_special_rank_three_pm()); + $SpecialRank = 3; + } + // Make them special + G::$DB->query(" + UPDATE users_donor_ranks + SET SpecialRank = '$SpecialRank' + WHERE UserID = '$UserID'"); + G::$Cache->delete_value("donor_special_rank_$UserID"); + } + G::$DB->set_query_id($QueryID); + } + + public static function schedule() { + self::$IsSchedule = true; + + DonationsBitcoin::find_new_donations(); + //self::expire_ranks(); + } + + public static function expire_ranks() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT UserID, Rank + FROM users_donor_ranks + WHERE Rank > 1 + AND SpecialRank != 3 + AND DonationTime < NOW() - INTERVAL 32 DAY"); + + if (G::$DB->record_count() > 0) { + $UserIDs = array(); + while (list($UserID, $Rank) = G::$DB->next_record()) { + G::$Cache->delete_value("donor_rank_$UserID"); + G::$Cache->delete_value("donor_rewards_$UserID"); + $UserIDs[] = $UserID; + } + $In = implode(',', $UserIDs); + G::$DB->query(" + UPDATE users_donor_ranks + SET Rank = Rank - IF(Rank = " . MAX_RANK . ", 2, 1) + WHERE UserID IN ($In)"); + } + G::$DB->set_query_id($QueryID); + } + + private static function calculate_rank($Amount) { + return floor($Amount / 5); + } + + public static function update_rank($UserID, $Rank, $TotalRank, $Reason) { + $Rank = (int)$Rank; + $TotalRank = (int)$TotalRank; + + self::donate($UserID, array( + "Manipulation" => "Direct", + "Rank" => $Rank, + "TotalRank" => $TotalRank, + "Reason" => $Reason, + "Source" => "Modify Values", + "Currency" => "EUR")); + } + + public static function hide_stats($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + INSERT INTO users_donor_ranks + (UserID, Hidden) + VALUES + ('$UserID', '1') + ON DUPLICATE KEY UPDATE + Hidden = '1'"); + G::$DB->set_query_id($QueryID); + } + + public static function show_stats($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + INSERT INTO users_donor_ranks + (UserID, Hidden) + VALUES + ('$UserID', '0') + ON DUPLICATE KEY UPDATE + Hidden = '0'"); + G::$DB->set_query_id($QueryID); + } + + public static function is_visible($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Hidden + FROM users_donor_ranks + WHERE Hidden = '0' + AND UserID = '$UserID'"); + $HasResults = G::$DB->has_results(); + G::$DB->set_query_id($QueryID); + return $HasResults; + } + + public static function has_donor_forum($UserID) { + return self::get_rank($UserID) >= DONOR_FORUM_RANK || self::get_special_rank($UserID) >= MAX_SPECIAL_RANK; + } + + public static function is_mod($UserID) { + $Permissions = Permissions::get_permissions_for_user($UserID); + return $Permissions['users_mod']; + } + + + public static function get_rank($UserID) { + $Rank = G::$Cache->get_value("donor_rank_$UserID"); + if ($Rank === false) { + if (self::is_mod($UserID)) { + $Rank = MAX_EXTRA_RANK; + } else { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Rank + FROM users_donor_ranks + WHERE UserID = '$UserID'"); + list($Rank) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + } + G::$Cache->cache_value("donor_rank_$UserID", $Rank, 0); + } + return $Rank; + } + + public static function get_special_rank($UserID) { + $SpecialRank = G::$Cache->get_value("donor_special_rank_$UserID"); + if ($SpecialRank === false) { + if (self::is_mod($UserID)) { + $SpecialRank = MAX_SPECIAL_RANK; + } else { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT SpecialRank + FROM users_donor_ranks + WHERE UserID = '$UserID'"); + list($SpecialRank) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + } + G::$Cache->cache_value("donor_special_rank_$UserID", $SpecialRank, 0); + } + return $SpecialRank; + } + + public static function get_total_rank($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT TotalRank + FROM users_donor_ranks + WHERE UserID = '$UserID'"); + list($Rank) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + return $Rank; + } + + public static function get_donation_time($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT DonationTime + FROM users_donor_ranks + WHERE UserID = '$UserID'"); + list($DonationTime) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + return $DonationTime; + } + + public static function get_titles($UserID) { + $Results = G::$Cache->get_value("donor_title_$UserID"); + if ($Results === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Prefix, Suffix, UseComma + FROM donor_forum_usernames + WHERE UserID = '$UserID'"); + $Results = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value("donor_title_$UserID", $Results, 0); + } + return $Results; + } + + + + public static function get_enabled_rewards($UserID) { + $Rewards = array(); + $Rank = self::get_rank($UserID); + $SpecialRank = self::get_special_rank($UserID); + $HasAll = $SpecialRank == 3; + + if ($Rank >= 1 || $HasAll) { + + } + if ($Rank >= 2 || $HasAll) { + $Rewards["HasDonorIconMouseOverText"] = true; + $Rewards["HasProfileInfo1"] = true; + } + if ($Rank >= 3 || $HasAll) { + $Rewards["HasAvatarMouseOverText"] = true; + $Rewards["HasProfileInfo2"] = true; + } + if ($Rank >= 4 || $HasAll) { + $Rewards["HasDonorIconLink"] = true; + $Rewards["HasProfileInfo3"] = true; + } + if ($Rank >= MAX_RANK || $HasAll) { + $Rewards["HasCustomDonorIcon"] = true; + $Rewards["HasDonorForum"] = true; + $Rewards["HasProfileInfo4"] = true; + } + if ($SpecialRank >= 2) { + $Rewards["HasSecondAvatar"] = true; + } + return $Rewards; + } + + public static function get_rewards($UserID) { + $Results = G::$Cache->get_value("donor_rewards_$UserID"); + if ($Results === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + IconMouseOverText, + AvatarMouseOverText, + CustomIcon, + CustomIconLink, + SecondAvatar + FROM donor_rewards + WHERE UserID = '$UserID'"); + $Results = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value("donor_rewards_$UserID", $Results, 0); + } + return $Results; + } + + public static function get_profile_rewards($UserID) { + $Results = G::$Cache->get_value("donor_profile_rewards_$UserID"); + if ($Results === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + ProfileInfo1, + ProfileInfoTitle1, + ProfileInfo2, + ProfileInfoTitle2, + ProfileInfo3, + ProfileInfoTitle3, + ProfileInfo4, + ProfileInfoTitle4 + FROM donor_rewards + WHERE UserID = '$UserID'"); + $Results = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value("donor_profile_rewards_$UserID", $Results, 0); + } + return $Results; + } + + private static function add_profile_info_reward($Counter, &$Insert, &$Values, &$Update) { + if (isset($_POST["profile_title_" . $Counter]) && isset($_POST["profile_info_" . $Counter])) { + $ProfileTitle = db_string($_POST["profile_title_" . $Counter]); + $ProfileInfo = db_string($_POST["profile_info_" . $Counter]); + $ProfileInfoTitleSQL = "ProfileInfoTitle" . $Counter; + $ProfileInfoSQL = "ProfileInfo" . $Counter; + $Insert[] = "$ProfileInfoTitleSQL"; + $Values[] = "'$ProfileInfoTitle'"; + $Update[] = "$ProfileInfoTitleSQL = '$ProfileTitle'"; + $Insert[] = "$ProfileInfoSQL"; + $Values[] = "'$ProfileInfo'"; + $Update[] = "$ProfileInfoSQL = '$ProfileInfo'"; + } + } + + + + public static function update_rewards($UserID) { + $Rank = self::get_rank($UserID); + $SpecialRank = self::get_special_rank($UserID); + $HasAll = $SpecialRank == 3; + $Counter = 0; + $Insert = array(); + $Values = array(); + $Update = array(); + + $Insert[] = "UserID"; + $Values[] = "'$UserID'"; + if ($Rank >= 1 || $HasAll) { + + } + if ($Rank >= 2 || $HasAll) { + if (isset($_POST['donor_icon_mouse_over_text'])) { + $IconMouseOverText = db_string($_POST['donor_icon_mouse_over_text']); + $Insert[] = "IconMouseOverText"; + $Values[] = "'$IconMouseOverText'"; + $Update[] = "IconMouseOverText = '$IconMouseOverText'"; + } + $Counter++; + } + if ($Rank >= 3 || $HasAll) { + if (isset($_POST['avatar_mouse_over_text'])) { + $AvatarMouseOverText = db_string($_POST['avatar_mouse_over_text']); + $Insert[] = "AvatarMouseOverText"; + $Values[] = "'$AvatarMouseOverText'"; + $Update[] = "AvatarMouseOverText = '$AvatarMouseOverText'"; + } + $Counter++; + } + if ($Rank >= 4 || $HasAll) { + if (isset($_POST['donor_icon_link'])) { + $CustomIconLink = db_string($_POST['donor_icon_link']); + if (!Misc::is_valid_url($CustomIconLink)) { + $CustomIconLink = ''; + } + $Insert[] = "CustomIconLink"; + $Values[] = "'$CustomIconLink'"; + $Update[] = "CustomIconLink = '$CustomIconLink'"; + } + $Counter++; + } + if ($Rank >= MAX_RANK || $HasAll) { + if (isset($_POST['donor_icon_custom_url'])) { + $CustomIcon = db_string($_POST['donor_icon_custom_url']); + if (!Misc::is_valid_url($CustomIcon)) { + $CustomIcon = ''; + } + $Insert[] = "CustomIcon"; + $Values[] = "'$CustomIcon'"; + $Update[] = "CustomIcon = '$CustomIcon'"; + } + self::update_titles($UserID, $_POST['donor_title_prefix'], $_POST['donor_title_suffix'], $_POST['donor_title_comma']); + $Counter++; + } + for ($i = 1; $i <= $Counter; $i++) { + self::add_profile_info_reward($i, $Insert, $Values, $Update); + } + if ($SpecialRank >= 2) { + if (isset($_POST['second_avatar'])) { + $SecondAvatar = db_string($_POST['second_avatar']); + if (!Misc::is_valid_url($SecondAvatar)) { + $SecondAvatar = ''; + } + $Insert[] = "SecondAvatar"; + $Values[] = "'$SecondAvatar'"; + $Update[] = "SecondAvatar = '$SecondAvatar'"; + } + } + $Insert = implode(', ', $Insert); + $Values = implode(', ', $Values); + $Update = implode(', ', $Update); + if ($Counter > 0) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + INSERT INTO donor_rewards + ($Insert) + VALUES + ($Values) + ON DUPLICATE KEY UPDATE + $Update"); + G::$DB->set_query_id($QueryID); + } + G::$Cache->delete_value("donor_profile_rewards_$UserID"); + G::$Cache->delete_value("donor_rewards_$UserID"); + + } + + public static function update_titles($UserID, $Prefix, $Suffix, $UseComma) { + $QueryID = G::$DB->get_query_id(); + $Prefix = trim(db_string($Prefix)); + $Suffix = trim(db_string($Suffix)); + $UseComma = empty($UseComma) ? true : false; + G::$DB->query(" + INSERT INTO donor_forum_usernames + (UserID, Prefix, Suffix, UseComma) + VALUES + ('$UserID', '$Prefix', '$Suffix', '$UseComma') + ON DUPLICATE KEY UPDATE + Prefix = '$Prefix', + Suffix = '$Suffix', + UseComma = '$UseComma'"); + G::$Cache->delete_value("donor_title_$UserID"); + G::$DB->set_query_id($QueryID); + } + + + public static function get_donation_history($UserID) { + $UserID = (int) $UserID; + if (empty($UserID)) { + error(404); + } + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Amount, Email, Time, Currency, Reason, Source, AddedBy, Rank, TotalRank + FROM donations + WHERE UserID = '$UserID' + ORDER BY Time DESC"); + $DonationHistory = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); + return $DonationHistory; + } + + public static function get_rank_expiration($UserID) { + $UserID = (int) $UserID; + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT Rank, SpecialRank, (DonationTime + INTERVAL 32 DAY) AS Expiration FROM users_donor_ranks WHERE UserID = '$UserID'"); + $Return = ""; + if (G::$DB->has_results()) { + list($Rank, $SpecialRank, $Expiration) = G::$DB->next_record(); + $Expiration = time_diff($Expiration); + if ($Expiration != "Never") { + $Expiration = "in " . $Expiration; + } + $Return = $SpecialRank == MAX_SPECIAL_RANK || $Rank == 1 ? "Never" : $Expiration; + } + G::$DB->set_query_id($QueryID); + return $Return; + } + + public static function get_leaderboard_position($UserID) { + $UserID = (int) $UserID; + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SET @RowNum := 0"); + G::$DB->query("SELECT Position FROM (SELECT d.UserID, @RowNum := @RowNum + 1 AS Position FROM users_donor_ranks d ORDER BY TotalRank DESC) l WHERE UserID = '$UserID'"); + if (G::$DB->has_results()) { + list($Position) = G::$DB->next_record(); + } else { + $Position = 0; + } + G::$DB->set_query_id($QueryID); + return $Position; + } + + public static function is_donor($UserID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT 1 FROM users_donor_ranks WHERE UserID = '$UserID'"); + $HasResults = G::$DB->has_results(); + G::$DB->set_query_id($QueryID); + return $HasResults; + } + + public static function currency_exchange($Amount, $Currency) { + if (!self::is_valid_currency($Currency)) { + error("$Currency is not valid currency"); + } + switch ($Currency) { + case 'USD': + $Amount = self::usd_to_euro($Amount); + break; + case 'BTC': + $Amount = self::btc_to_euro($Amount); + break; + default: + break; + } + return round($Amount, 2); + } + + public static function is_valid_currency($Currency) { + return $Currency == 'EUR' || $Currency == 'BTC' || $Currency == 'USD'; + } + + public static function btc_to_euro($Amount) { + $Rate = G::$Cache->get_value('btc_rate'); + if (empty($Rate)) { + if ($Response = file_get_contents(BTC_API_URL)) { + $Response = json_decode($Response, true); + if (isset($Response['EUR'])) { + $Rate = round($Response['EUR']['24h'], 4); // We don't need good precision + self::set_stored_conversion_rate('BTC', $Rate); + $CacheTime = 86400; // Cache fresh value for 24 hours; + } + } + if (empty($Rate)) { + $Rate = self::get_stored_conversion_rate('BTC'); + $CacheTime = 3600; // Cache old value for 1 hour; + } + G::$Cache->cache_value('btc_rate', $Rate, $CacheTime); + } + return $Rate * $Amount; + } + + public static function usd_to_euro($Amount) { + $Rate = G::$Cache->get_value('usd_rate'); + if (empty($Rate)) { + if ($Response = file_get_contents(USD_API_URL)) { + // Valid JSON isn't returned so we make it valid. + $Replace = array( + 'lhs' => '"lhs"', + 'rhs' => '"rhs"', + 'error' => '"error"', + 'icc' => '"icc"' + ); + + $Response = str_replace(array_keys($Replace), array_values($Replace), $Response); + $Response = json_decode($Response, true); + if (isset($Response['rhs'])) { + // The response is in format "# Euroes", extracts the numbers. + $Rate = preg_split("/[\s,]+/", $Response['rhs']); + $Rate = round($Rate[0], 4); // We don't need good precision + self::set_stored_conversion_rate('USD', $Rate); + $CacheTime = 86400; // Cache fresh value for 24 hours; + } + } + if (empty($Rate)) { + $Rate = self::get_stored_conversion_rate('USD'); + $CacheTime = 3600; // Cache old value for 1 hour; + } + G::$Cache->cache_value('usd_rate', $Rate, $CacheTime); + } + return $Rate * $Amount; + } + + public static function get_stored_conversion_rate($Currency) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Rate + FROM currency_conversion_rates + WHERE Currency = '$Currency'"); + list($Rate) = G::$DB->next_record(MYSQLI_NUM, false); + G::$DB->set_query_id($QueryID); + return $Rate; + } + + private static function set_stored_conversion_rate($Currency, $Rate) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + REPLACE INTO currency_conversion_rates + (Currency, Rate, Time) + VALUES + ('$Currency', $Rate, NOW())"); + G::$DB->set_query_id($QueryID); + } + + public static function get_forum_description() { + return self::$ForumDescriptions[rand(0, count(self::$ForumDescriptions) - 1)]; + } + + private static function get_pm_body($Source, $Currency, $DonationAmount, $ReceivedRank, $CurrentRank) { + if ($Source == 'Store Parser') { + $String = "[*][b]You Purchased:[/b] $DonationAmount $Currency"; + } else { + $String = "[*][b]You Donated:[/b] $DonationAmount $Currency"; + } + + return 'Thank you for your generosity and support. It\'s users like you who make all of this possible. What follows is a brief description of your transaction: + +' . $String . ' +[*][b]You Received:[/b] ' . $ReceivedRank . ' Donor Point' . ($ReceivedRank == 1 ? '' : 's') . ' +[*][b]Your Donor Rank:[/b] Donor Rank # ' . $CurrentRank . ' +Once again, thank you for your continued support of the site. + +Sincerely, + +'.SITE_NAME.' Staff + +[align=center][If you have any questions or concerns, please [url=https://'.SSL_SITE_URL.'/staffpm.php]send a Staff PM[/url].]'; + } + + private static function get_special_rank_one_pm() { + return 'Congratulations on reaching [url=https://'.SSL_SITE_URL.'/staffpm.php]Special Rank #1[/url]! You\'ve been awarded [b]one user pick[/b]! This user pick will be featured on the '.SITE_NAME.' front page during an upcoming event. After you submit your pick, there is no guarantee as to how long it will take before your pick is featured. Picks will be featured on a first-submitted, first-served basis. Please abide by the following guidelines when making your selection: + +[*]Pick something that hasn\'t been chosen. You can tell if a pick has been used previously by looking at the collages it\'s in. +[*]Complete the enclosed form carefully and completely. +[*]Send a [url=https://'.SSL_SITE_URL.'/forums.php?action=viewthread&threadid=178640&postid=4839790#post4839790]Staff PM[/url] with the completed form. Title this PM "Special Rank User Pick". +[important][align=center]**The following form must be used. Do not edit the BBCode. Send a Staff PM with the completed form.**[/align][/important] +[quote][plain]FRONT PAGE:------------------------------------------------------------------------------------------------------------------------------------------ + + +[b][size=5][user][/user]\'s Special Donor Pick[/size][/b] + +[b]Artist Name - Album Title[/b] + +[b]Genre:[/b] Alternative, Rock, Grunge + +[b]Torrents:[/b] Link Goes Here + +[b]Review:[/b] [quote]Review Here (Limit: 1 Paragraph)[/quote] + + +FORUM POST:------------------------------------------------------------------------------------------------------------------------------------------ + + +[b][size=5][user][/user]\'s Special Donor Pick[/size][/b] + +[img=Album Cover] + +[b]Artist Name - Album Title[/b] + +[b]Genre:[/b] Alternative, Rock, Grunge + +[b]Torrents:[/b] Link Goes Here + +[b]Release Info[/b] + +[u]Release Date:[/u] Date +[u]Tracks:[/u] Tracks +[u]Length:[/u] Length +[u]Label:[/u] Label + +[u]Band Member — Instruments[/u] +Member 1 — Guitar +Member 2 — Drums + +[b]Track Listing:[/b] + +01. Remove +02. These +03. As Is +04. Necessary +05. Track 05 +06. Track 06 +07. Track 07 +08. Track 08 +09. Track 09 +10. Track 10 + +[b]Web site:[/b] Link + +[b]Review:[/b] [quote]Review Here (No Length Limit)[/quote] +[/plain][/quote]Alternately, you may use this [url=http://pick.thehash.es/]pick generator tool[/url] to assist you in properly formatting your pick. + +At this time, we\'d like to thank you for your continued support of the site. The fact that you\'ve reached this milestone is testament to your belief in '.SITE_NAME.' as a project. It\'s dedicated users like you that keep us alive. We look forward to featuring your pick in an upcoming announcement. + +Sincerely, + +'.SITE_NAME.' Staff'; + } + + private static function get_special_rank_two_pm() { + return 'Congratulations on reaching [url=https://'.SSL_SITE_URL.'/forums.php?action=viewthread&threadid=178640&postid=4839790#post4839790]Special Rank #2[/url]! You\'ve been awarded [b]double avatar functionality[/b]! To set a second avatar, please enter a URL leading to a valid image in the new field which has been unlocked in your [b]Personal Settings[/b]. Any avatar you choose must abide by normal avatar rules. When running your cursor over your avatar, it will flip to the alternate choice you\'ve established. Other users will also be able to view both of your avatars using this method. + +At this time, we\'d like to thank you for your continued support of the site. The fact that you\'ve reached this milestone is testament to your belief in '.SITE_NAME.' as a project. It\'s dedicated users like you that keep us alive. Have fun with the new toy. + +Sincerely, + +'.SITE_NAME.' Staff'; + } + + private static function get_special_rank_three_pm() { + return 'Congratulations on reaching [url=https://'.SSL_SITE_URL.'/forums.php?action=viewthread&threadid=178640&postid=4839790#post4839790]Special Rank #3[/url]! You\'ve been awarded [b]Diamond Rank[/b]! Diamond Rank grants you the benefits associated with every Donor Rank up to and including Gold ([url=https://'.SSL_SITE_URL.'/forums.php?action=viewthread&threadid=178640&postid=4839789#post4839789]Donor Rank #5[/url]). But unlike Donor Rank #5 - because Diamond Rank is a Special Rank - it will never expire. + +At this time, we\'d like to thank you for your continued support of the site. The fact that you\'ve reached this milestone is testament to your belief in '.SITE_NAME.' as a project. It\'s dedicated users like you that keep us alive. Consider yourself one of our top supporters! + +Sincerely, + +'.SITE_NAME.' Staff'; + } + +} diff --git a/classes/donationsbitcoin.class.php b/classes/donationsbitcoin.class.php new file mode 100644 index 00000000..9a00d025 --- /dev/null +++ b/classes/donationsbitcoin.class.php @@ -0,0 +1,186 @@ + Amount, ...) + */ + public static function get_received() { + if (defined('BITCOIN_RPC_URL')) { + $Donations = BitcoinRpc::listreceivedbyaddress(); + } + if (empty($Donations)) { + return array(); + } + $BTCUsers = array(); + foreach ($Donations as $Account) { + $BTCUsers[$Account->address] = $Account->amount; + } + return $BTCUsers; + } + + /** + * Ask bitcoind for the current account balance + * + * @return float balance + */ + public static function get_balance() { + if (defined('BITCOIN_RPC_URL')) { + return BitcoinRpc::getbalance(); + } + } + + /** + * Get a user's existing bitcoin address or generate a new one + * + * @param int $UserID + * @param bool $GenAddress whether to create a new address if it doesn't exist + * @return false if no address exists and $GenAddress is false + * string bitcoin address otherwise + */ + public static function get_address($UserID, $GenAddress = false) { + $UserID = (int)$UserID; + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT BitcoinAddress + FROM users_info + WHERE UserID = '$UserID'"); + list($Addr) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + + if (!empty($Addr)) { + return $Addr; + } elseif ($GenAddress) { + if (defined('BITCOIN_RPC_URL')) { + $NewAddr = BitcoinRpc::getnewaddress(); + } + if (empty($NewAddr)) { + error(0); + } + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + UPDATE users_info + SET BitcoinAddress = '".db_string($NewAddr)."' + WHERE UserID = '$UserID' + AND BitcoinAddress IS NULL"); + G::$DB->set_query_id($QueryID); + return $NewAddr; + } else { + return false; + } + } + + /** + * Ask bitcoind for the total amount of bitcoins received + * + * @return float amount + */ + public static function get_total_received() { + if (defined('BITCOIN_RPC_URL')) { + $Accounts = BitcoinRpc::listreceivedbyaccount(); + } + if (empty($Accounts)) { + return 0.0; + } + foreach ($Accounts as $Account) { + if ($Account->account == '') { + return $Account->amount; + } + } + return 0.0; + } + + /** + * Translate bitcoin addresses to user IDs + * + * @param array $Addresses list of bitcoin addresses + * @return array (BitcoinAddress => UserID, ...) + */ + public static function get_userids($Addresses) { + if (!is_array($Addresses) || empty($Addresses)) { + return false; + } + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT BitcoinAddress, UserID + FROM users_info + WHERE BitcoinAddress IN ('" . implode("', '", $Addresses) . "')"); + if (G::$DB->has_results()) { + $UserIDs = G::$DB->to_pair(0, 1); + } else { + $UserIDs = array(); + } + G::$DB->set_query_id($QueryID); + return $UserIDs; + } + + /** + * Find and process new donations since the last time this function was called. + */ + public static function find_new_donations() { + global $Debug; + if (($OldAmount = G::$Cache->get_value('btc_total_received')) === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT IFNULL(SUM(Amount), 0) + FROM donations_bitcoin"); + list($OldAmount) = G::$DB->next_record(MYSQLI_NUM, false); + G::$DB->set_query_id($QueryID); + } + $NewAmount = self::get_total_received(); + if ($NewAmount < $OldAmount) { + // This shouldn't happen. Perhaps bitcoind was restarted recently + // or the block index was removed. Either way, try again later + send_irc('PRIVMSG ' . LAB_CHAN . " :Bad bitcoin donation data (is $NewAmount, was $OldAmount). If this persists, something is probably wrong"); + return false; + } + if ($NewAmount > $OldAmount) { + // I really wish we didn't have to do it like this + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT BitcoinAddress, SUM(Amount) + FROM donations_bitcoin + GROUP BY BitcoinAddress"); + $OldDonations = G::$DB->to_pair(0, 1, false); + G::$DB->set_query_id($QueryID); + $NewDonations = self::get_received(); + foreach ($NewDonations as $Address => &$Amount) { + if (isset($OldDonations[$Address])) { + if ($Amount == $OldDonations[$Address]) { // Direct comparison should be fine as everything comes from bitcoind + unset($NewDonations[$Address]); + continue; + } + $Debug->log_var(array('old' => $OldDonations[$Address], 'new' => $Amount), "New donations from $Address"); + // PHP doesn't do fixed-point math, and json_decode has already botched the precision + // so let's just round this off to satoshis and pray that we're on a 64 bit system + $Amount = round($Amount - $OldDonations[$Address], 8); + } + $NewDonations[$Address] = $Amount; + } + $Debug->log_var($NewDonations, '$NewDonations'); + foreach (self::get_userids(array_keys($NewDonations)) as $Address => $UserID) { + Donations::regular_donate($UserID, $NewDonations[$Address], 'Bitcoin Parser', '', 'BTC'); + self::store_donation($Address, $NewDonations[$Address]); + } + G::$Cache->cache_value('btc_total_received', $NewAmount, 0); + } + } + + /** + * Record a donation in the database + * + * @param string $Address bitcoin address + * @param double $Amount amount of bitcoins transferred + */ + public static function store_donation($Address, $Amount) { + if (!is_numeric($Amount) || $Amount <= 0) { + // Panic! + return false; + } + G::$DB->query(" + INSERT INTO donations_bitcoin + (BitcoinAddress, Amount) + VALUES + ('$Address', $Amount)"); + } +} \ No newline at end of file diff --git a/classes/donationsview.class.php b/classes/donationsview.class.php new file mode 100644 index 00000000..25b49ac6 --- /dev/null +++ b/classes/donationsview.class.php @@ -0,0 +1,212 @@ + + + + + + + + + + + + + + + + +
+ # Donor System (add points) +
Value + + +
Reason
+ +
+ + + + + + + + + + + + + + + + + + + + +
+ # Donor System (modify values) +
Active points
Total points
Reason
+ +
+ +
+
Donor Statistics
+
    + +
  • + Total donor points: +
  • + +
  • + Current donor rank: +
  • +
  • + Leaderboard position: +
  • +
  • + Last donated: +
  • +
  • + Rank expires: +
  • + +
  • + This user hasn't donated. +
  • + +
+
+ +
+
+ + Hide +
+
+full_format($ProfileRewards['ProfileInfo' . $i]); ?> +
+
+ +
+
+ # Donation History View +
+ + +
+= MAX_RANK ? MAX_RANK : $Rank; + $Overflow = $Rank - $CurrentRank; + $Display = $CurrentRank; + if ($Display == 5 || $Display == 6) { + $Display--; + } + if ($ShowOverflow && $Overflow) { + $Display .= " (+$Overflow)"; + } + if ($Rank >= 6) { + $Display .= ' [Gold]'; + } elseif ($Rank >= 4) { + $Display .= ' [Silver]'; + } elseif ($Rank >= 3) { + $Display .= ' [Bronze]'; + } elseif ($Rank >= 2) { + $Display .= ' [Copper]'; + } elseif ($Rank >= 1) { + $Display .= ' [Red]'; + } + } + echo $Display; + } + +} diff --git a/classes/format.class.php b/classes/format.class.php index 8009c2c2..93d80376 100644 --- a/classes/format.class.php +++ b/classes/format.class.php @@ -53,6 +53,7 @@ public static function cut_string($Str, $Length, $Hard = false, $ShowDots = true $CutDesc = implode(' ', $DescArr); } if ($ShowDots) { + //TODO: should we replace the three dots with an ellipsis character? $CutDesc .= '...'; } } else { @@ -123,7 +124,7 @@ public static function get_ratio_html($Dividend, $Divisor, $Color = true) { * Returns ratio * @param int $Dividend * @param int $Divisor - * @param int $Decimal floor to n decimals (e.g. Subtract .005 to floor to 2 decimals) + * @param int $Decimal floor to n decimals (e.g. subtract .005 to floor to 2 decimals) * @return boolean|string */ public function get_ratio ($Dividend, $Divisor, $Decimal = 2) { @@ -170,7 +171,7 @@ public static function get_url($Exclude = false) { * @param $DefaultResult Optional, which result's page we want if no page is specified * If this parameter is not specified, we will default to page 1 * - * @return array(int,string) What page we are on, and what to use in the LIMIT section of a query + * @return array(int, string) What page we are on, and what to use in the LIMIT section of a query * e.g. "SELECT [...] LIMIT $Limit;" */ public static function page_limit($PerPage, $DefaultResult = 1) { @@ -188,7 +189,7 @@ public static function page_limit($PerPage, $DefaultResult = 1) { if ($Page <= 0) { $Page = 1; } - $Limit = $PerPage * $Page - $PerPage . ', ' . $PerPage; + $Limit = $PerPage * $Page - $PerPage . ", $PerPage"; } return array($Page, $Limit); } @@ -196,8 +197,8 @@ public static function page_limit($PerPage, $DefaultResult = 1) { // A9 magic. Some other poor soul can write the phpdoc. // For data stored in memcached catalogues (giant arrays), e.g. forum threads public static function catalogue_limit($Page, $PerPage, $CatalogueSize = 500) { - $CatalogueID = floor(($PerPage * $Page - $PerPage) / $CatalogueSize);; - $CatalogueLimit = ($CatalogueID * $CatalogueSize).', '.$CatalogueSize; + $CatalogueID = floor(($PerPage * $Page - $PerPage) / $CatalogueSize); + $CatalogueLimit = ($CatalogueID * $CatalogueSize).", $CatalogueSize"; return array($CatalogueID, $CatalogueLimit); } @@ -224,7 +225,7 @@ public static function catalogue_select($Catalogue, $Page, $PerPage, $CatalogueS */ public static function get_pages($StartPage, $TotalRecords, $ItemsPerPage, $ShowPages = 11, $Anchor = '') { global $Document, $Method, $Mobile; - $Location = $Document.'.php'; + $Location = "$Document.php"; $StartPage = ceil($StartPage); $TotalPages = 0; if ($TotalRecords > 0) { @@ -253,37 +254,37 @@ public static function get_pages($StartPage, $TotalRecords, $ItemsPerPage, $Show $StartPosition = max($StartPosition, 1); - $QueryString = self::get_url(array('page','post')); + $QueryString = self::get_url(array('page', 'post')); if ($QueryString != '') { - $QueryString = '&'.$QueryString; + $QueryString = "&$QueryString"; } $Pages = ''; if ($StartPage > 1) { - $Pages .= '<< First '; - $Pages .= '< Prev | '; + $Pages .= "<< First "; + $Pages .= "< Prev | '; } //End change if (!$Mobile) { for ($i = $StartPosition; $i <= $StopPage; $i++) { if ($i != $StartPage) { - $Pages .= ''; + $Pages .= ""; } - $Pages .= ""; + $Pages .= ''; if ($i * $ItemsPerPage > $TotalRecords) { - $Pages .= ((($i - 1) * $ItemsPerPage) + 1).'-'.($TotalRecords); + $Pages .= ((($i - 1) * $ItemsPerPage) + 1)."-$TotalRecords"; } else { $Pages .= ((($i - 1) * $ItemsPerPage) + 1).'-'.($i * $ItemsPerPage); } $Pages .= ''; if ($i != $StartPage) { - $Pages.=''; + $Pages .= ''; } if ($i < $StopPage) { - $Pages.=' | '; + $Pages .= ' | '; } } } else { @@ -291,8 +292,8 @@ public static function get_pages($StartPage, $TotalRecords, $ItemsPerPage, $Show } if ($StartPage && $StartPage < $TotalPages) { - $Pages .= ' | Next > '; - $Pages .= ' Last >>'; + $Pages .= " | Next > '; + $Pages .= " Last >>"; } } if ($TotalPages > 1) { @@ -303,14 +304,16 @@ public static function get_pages($StartPage, $TotalRecords, $ItemsPerPage, $Show /** * Format a size in bytes as a human readable string in KiB/MiB/... + * Note: KiB, MiB, etc. are the IEC units, which are in base 2. + * KB, MB are the SI units, which are in base 10. * * @param int $Size * @param int $Levels Number of decimal places. Defaults to 2, unless the size >= 1TB, in which case it defaults to 4. * @return string formatted number. */ public static function get_size($Size, $Levels = 2) { - $Units = array(' B',' KB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB'); - $Size = (double) $Size; + $Units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'); + $Size = (double)$Size; for ($Steps = 0; abs($Size) >= 1024; $Size /= 1024, $Steps++) { } if (func_num_args() == 1 && $Steps >= 4) { @@ -334,13 +337,13 @@ public static function human_format($Number) { } switch ($Steps) { case 0: return round($Number); break; - case 1: return round($Number,2).'k'; break; - case 2: return round($Number,2).'M'; break; - case 3: return round($Number,2).'G'; break; - case 4: return round($Number,2).'T'; break; - case 5: return round($Number,2).'P'; break; + case 1: return round($Number, 2).'k'; break; + case 2: return round($Number, 2).'M'; break; + case 3: return round($Number, 2).'G'; break; + case 4: return round($Number, 2).'T'; break; + case 5: return round($Number, 2).'P'; break; default: - return round($Number,2).'E + '.$Steps*3; + return round($Number, 2).'E + '.$Steps * 3; } } @@ -413,7 +416,7 @@ public static function selected($Name, $Value, $Attribute = 'selected', $Array = } if (isset($Array[$Name]) && $Array[$Name] !== '') { if ($Array[$Name] == $Value) { - echo ' '.$Attribute.'="'.$Attribute.'"'; + echo " $Attribute=\"$Attribute\""; } } } @@ -428,13 +431,12 @@ public static function selected($Name, $Value, $Attribute = 'selected', $Array = * 2-dimensional array: At least one array must be identical to $Target * @param string $ClassName CSS class name to return * @param bool $AddAttribute Whether to include the "class" attribute in the output - * @param string $UserIDKey Key in _REQUEST for a user id parameter, which if given will be compared to $LoggedUser[ID] + * @param string $UserIDKey Key in _REQUEST for a user ID parameter, which if given will be compared to G::$LoggedUser[ID] * * @return class name on match, otherwise an empty string */ public static function add_class($Target, $Tests, $ClassName, $AddAttribute, $UserIDKey = false) { - global $LoggedUser; - if ($UserIDKey && isset($_REQUEST[$UserIDKey]) && $LoggedUser['ID'] != $_REQUEST[$UserIDKey]) { + if ($UserIDKey && isset($_REQUEST[$UserIDKey]) && G::$LoggedUser['ID'] != $_REQUEST[$UserIDKey]) { return ''; } $Pass = true; @@ -469,7 +471,7 @@ public static function add_class($Target, $Tests, $ClassName, $AddAttribute, $Us return ''; } if ($AddAttribute) { - return ' class="'.$ClassName.'"'; + return " class=\"$ClassName\""; } return " $ClassName"; } @@ -508,14 +510,14 @@ public static function make_utf8($Str) { */ public static function is_utf8($Str) { return preg_match('%^(?: - [\x09\x0A\x0D\x20-\x7E] // ASCII - | [\xC2-\xDF][\x80-\xBF] // non-overlong 2-byte - | \xE0[\xA0-\xBF][\x80-\xBF] // excluding overlongs - | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} // straight 3-byte - | \xED[\x80-\x9F][\x80-\xBF] // excluding surrogates - | \xF0[\x90-\xBF][\x80-\xBF]{2} // planes 1-3 - | [\xF1-\xF3][\x80-\xBF]{3} // planes 4-15 - | \xF4[\x80-\x8F][\x80-\xBF]{2} // plane 16 + [\x09\x0A\x0D\x20-\x7E] // ASCII + | [\xC2-\xDF][\x80-\xBF] // non-overlong 2-byte + | \xE0[\xA0-\xBF][\x80-\xBF] // excluding overlongs + | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} // straight 3-byte + | \xED[\x80-\x9F][\x80-\xBF] // excluding surrogates + | \xF0[\x90-\xBF][\x80-\xBF]{2} // planes 1-3 + | [\xF1-\xF3][\x80-\xBF]{3} // planes 4-15 + | \xF4[\x80-\x8F][\x80-\xBF]{2} // plane 16 )*$%xs', $Str ); } diff --git a/classes/forums.class.php b/classes/forums.class.php index b7a27697..effb8636 100644 --- a/classes/forums.class.php +++ b/classes/forums.class.php @@ -1,71 +1,286 @@ 0 && preg_match(USERNAME_REGEX, $M[1])) { - $Usernames[] = preg_replace('/(^[.,]*)|([.,]*$)/', '', $M[1]); // wut? - } - ++$Level; - } else { - --$Level; - } + public static function get_thread_info($ThreadID, $Return = true, $SelectiveCache = false) { + if ((!$ThreadInfo = G::$Cache->get_value('thread_' . $ThreadID . '_info')) || !isset($ThreadInfo['OP'])) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT + t.Title, + t.ForumID, + t.IsLocked, + t.IsSticky, + COUNT(fp.id) AS Posts, + t.LastPostAuthorID, + ISNULL(p.TopicID) AS NoPoll, + t.StickyPostID, + t.AuthorID as OP + FROM forums_topics AS t + JOIN forums_posts AS fp ON fp.TopicID = t.ID + LEFT JOIN forums_polls AS p ON p.TopicID=t.ID + WHERE t.ID = '$ThreadID' + GROUP BY fp.TopicID"); + if (G::$DB->record_count() == 0) { + error(404); + } + $ThreadInfo = G::$DB->next_record(MYSQLI_ASSOC, false); + if ($ThreadInfo['StickyPostID']) { + $ThreadInfo['Posts']--; + G::$DB->query("SELECT + p.ID, + p.AuthorID, + p.AddedTime, + p.Body, + p.EditedUserID, + p.EditedTime, + ed.Username + FROM forums_posts as p + LEFT JOIN users_main AS ed ON ed.ID = p.EditedUserID + WHERE p.TopicID = '$ThreadID' AND p.ID = '" . $ThreadInfo['StickyPostID'] . "'"); + list ($ThreadInfo['StickyPost']) = G::$DB->to_array(false, MYSQLI_ASSOC); + } + G::$DB->set_query_id($QueryID); + if (!$SelectiveCache || !$ThreadInfo['IsLocked'] || $ThreadInfo['IsSticky']) { + G::$Cache->cache_value('thread_' . $ThreadID . '_info', $ThreadInfo, 0); } } - //remove any dupes in the array (the fast way) - $Usernames = array_flip(array_flip($Usernames)); - - $DB->query(" - SELECT m.ID, p.PushService - FROM users_main AS m - LEFT JOIN users_info AS i ON i.UserID = m.ID - LEFT JOIN users_push_notifications AS p ON p.UserID = m.ID - WHERE m.Username IN ('" . implode("', '", $Usernames) . "') - AND i.NotifyOnQuote = '1' - AND i.UserID != $LoggedUser[ID]"); - - $Results = $DB->to_array(); - foreach ($Results as $Result) { - $UserID = db_string($Result['ID']); - $PushService = $Result['PushService']; - $QuoterID = db_string($LoggedUser['ID']); - $Page = db_string($Page); - $PageID = db_string($PageID); - $PostID = db_string($PostID); - - $DB->query(" - INSERT IGNORE INTO users_notify_quoted - (UserID, QuoterID, Page, PageID, PostID, Date) - VALUES - ('$UserID', '$QuoterID', '$Page', '$PageID', '$PostID', '" . sqltime() . "')"); - $Cache->delete_value('notify_quoted_' . $UserID); - + if ($Return) { + return $ThreadInfo; } } + + /** + * Checks whether user has permissions on a forum. + * + * @param int $ForumID + * the forum ID. + * @param string $Perm + * the permissision to check, defaults to 'Read' + * @return boolean true if user has permission + */ + public static function check_forumperm($ForumID, $Perm = 'Read') { + $Forums = self::get_forums(); + if (G::$LoggedUser['CustomForums'][$ForumID] == 1) { + return true; + } + if ($ForumID == DONOR_FORUM && Donations::has_donor_forum(G::$LoggedUser['ID'])) { + return true; + } + if ($Forums[$ForumID]['MinClass' . $Perm] > G::$LoggedUser['Class'] && (!isset(G::$LoggedUser['CustomForums'][$ForumID]) || G::$LoggedUser['CustomForums'][$ForumID] == 0)) { + return false; + } + if (isset(G::$LoggedUser['CustomForums'][$ForumID]) && G::$LoggedUser['CustomForums'][$ForumID] == 0) { + return false; + } + return true; + } + + /** + * Gets basic info on a forum. + * + * @param int $ForumID + * the forum ID. + */ + public static function get_forum_info($ForumID) { + $Forum = G::$Cache->get_value('ForumInfo_' . $ForumID); + if (!$Forum) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT + Name, + MinClassRead, + MinClassWrite, + MinClassCreate, + COUNT(forums_topics.ID) AS Topics + FROM forums + LEFT JOIN forums_topics ON forums_topics.ForumID=forums.ID + WHERE forums.ID='$ForumID' + GROUP BY ForumID"); + if (G::$DB->record_count() == 0) { + return false; + } + // Makes an array, with $Forum['Name'], etc. + $Forum = G::$DB->next_record(MYSQLI_ASSOC); + + G::$DB->set_query_id($QueryID); + + G::$Cache->cache_value('ForumInfo_' . $ForumID, $Forum, 86400); + } + return $Forum; + } + + /** + * Get the forum categories + * @return array ForumCategoryID => Name + */ + public static function get_forum_categories() { + $ForumCats = G::$Cache->get_value('forums_categories'); + if ($ForumCats === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT ID, Name FROM forums_categories"); + $ForumCats = array(); + while (list ($ID, $Name) = G::$DB->next_record()) { + $ForumCats[$ID] = $Name; + } + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('forums_categories', $ForumCats, 0); + } + return $ForumCats; + } + + /** + * Get the forums + * @return array ForumID => (various information about the forum) + */ + public static function get_forums() { + if (!$Forums = G::$Cache->get_value('forums_list')) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + f.ID, + f.CategoryID, + f.Name, + f.Description, + f.MinClassRead AS MinClassRead, + f.MinClassWrite AS MinClassWrite, + f.MinClassCreate AS MinClassCreate, + f.NumTopics, + f.NumPosts, + f.LastPostID, + f.LastPostAuthorID, + f.LastPostTopicID, + f.LastPostTime, + 0 AS SpecificRules, + t.Title, + t.IsLocked AS Locked, + t.IsSticky AS Sticky + FROM forums AS f + JOIN forums_categories AS fc ON fc.ID = f.CategoryID + LEFT JOIN forums_topics as t ON t.ID = f.LastPostTopicID + GROUP BY f.ID + ORDER BY fc.Sort, fc.Name, f.CategoryID, f.Sort"); + $Forums = G::$DB->to_array('ID', MYSQLI_ASSOC, false); + + G::$DB->query("SELECT ForumID, ThreadID FROM forums_specific_rules"); + $SpecificRules = array(); + while (list($ForumID, $ThreadID) = G::$DB->next_record(MYSQLI_NUM, false)) { + $SpecificRules[$ForumID][] = $ThreadID; + } + G::$DB->set_query_id($QueryID); + foreach ($Forums as $ForumID => &$Forum) { + if (isset($SpecificRules[$ForumID])) { + $Forum['SpecificRules'] = $SpecificRules[$ForumID]; + } else { + $Forum['SpecificRules'] = array(); + } + } + G::$Cache->cache_value('forums_list', $Forums, 0); + } + return $Forums; + } + + /** + * Get all forums that the current user has special access to ("Extra forums" in the profile) + * @return array Array of ForumIDs + */ + public static function get_permitted_forums() { + return (array)array_keys(G::$LoggedUser['CustomForums'], 1); + } + + /** + * Get all forums that the current user does not have access to ("Restricted forums" in the profile) + * @return array Array of ForumIDs + */ + public static function get_restricted_forums() { + return (array)array_keys(G::$LoggedUser['CustomForums'], 0); + } + + /** + * Get the last read posts for the current user + * @param array $Forums Array of forums as returned by self::get_forums() + * @return array TopicID => array(TopicID, PostID, Page) where PostID is the ID of the last read post and Page is the page on which that post is + */ + public static function get_last_read($Forums) { + if (isset(G::$LoggedUser['PostsPerPage'])) { + $PerPage = G::$LoggedUser['PostsPerPage']; + } else { + $PerPage = POSTS_PER_PAGE; + } + $TopicIDs = array(); + foreach ($Forums as $Forum) { + if (!empty($Forum['LastPostTopicID'])) { + $TopicIDs[] = $Forum['LastPostTopicID']; + } + } + if (!empty($TopicIDs)) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT + l.TopicID, + l.PostID, + CEIL( + ( + SELECT + COUNT(ID) + FROM forums_posts + WHERE forums_posts.TopicID = l.TopicID + AND forums_posts.ID<=l.PostID + )/$PerPage + ) AS Page + FROM forums_last_read_topics AS l + WHERE TopicID IN(" . implode(',', $TopicIDs) . ") AND + UserID='" . G::$LoggedUser['ID'] . "'"); + $LastRead = G::$DB->to_array('TopicID', MYSQLI_ASSOC); + G::$DB->set_query_id($QueryID); + } else { + $LastRead = array(); + } + return $LastRead; + } + + /** + * Determine if a thread is unread + * @param bool $Locked + * @param bool $Sticky + * @param int $LastPostID + * @param array $LastRead An array as returned by self::get_last_read + * @param int $LastTopicID TopicID of the thread where the most recent post was made + * @param string $LastTime Datetime of the last post + * @return bool + */ + public static function is_unread($Locked, $Sticky, $LastPostID, $LastRead, $LastTopicID, $LastTime) { + return (!$Locked || $Sticky) && $LastPostID != 0 && ((empty($LastRead[$LastTopicID]) || $LastRead[$LastTopicID]['PostID'] < $LastPostID) && strtotime($LastTime) > G::$LoggedUser['CatchupTime']); + } + + /** + * Create the part of WHERE in the sql queries used to filter forums for a + * specific user (MinClassRead, restricted and permitted forums). + * @return string + */ + public static function user_forums_sql() { + // I couldn't come up with a good name, please rename this if you can. -- Y + $RestrictedForums = self::get_restricted_forums(); + $PermittedForums = self::get_permitted_forums(); + if (Donations::has_donor_forum(G::$LoggedUser['ID']) && !in_array(DONOR_FORUM, $PermittedForums)) { + $PermittedForums[] = DONOR_FORUM; + } + $SQL = "((f.MinClassRead <= '" . G::$LoggedUser['Class'] . "'"; + if (count($RestrictedForums)) { + $SQL .= " AND f.ID NOT IN ('" . implode("', '", $RestrictedForums) . "')"; + } + $SQL .= ')'; + if (count($PermittedForums)) { + $SQL .= " OR f.ID IN ('" . implode("', '", $PermittedForums) . "')"; + } + $SQL .= ')'; + return $SQL; + } } diff --git a/classes/g.class.php b/classes/g.class.php index a692b068..67718e77 100644 --- a/classes/g.class.php +++ b/classes/g.class.php @@ -8,6 +8,6 @@ public static function initialize() { global $DB, $Cache, $LoggedUser; self::$DB = $DB; self::$Cache = $Cache; - self::$LoggedUser = $LoggedUser; + self::$LoggedUser =& $LoggedUser; } } \ No newline at end of file diff --git a/classes/inbox.class.php b/classes/inbox.class.php index 9a005826..875da7f5 100644 --- a/classes/inbox.class.php +++ b/classes/inbox.class.php @@ -9,9 +9,8 @@ class Inbox { * @return string - the URL to a user's inbox */ public static function get_inbox_link($WhichBox = 'inbox') { - global $LoggedUser; - $ListFirst = $LoggedUser['ListUnreadPMsFirst']; + $ListFirst = G::$LoggedUser['ListUnreadPMsFirst']; if ($WhichBox == 'inbox') { if ($ListFirst) { diff --git a/classes/invite_tree.class.php b/classes/invite_tree.class.php index 644c1dc1..69f1bd8e 100644 --- a/classes/invite_tree.class.php +++ b/classes/invite_tree.class.php @@ -19,21 +19,22 @@ function INVITE_TREE($UserID, $Options = array()) { } function make_tree() { + $QueryID = G::$DB->get_query_id(); + $UserID = $this->UserID; - global $DB; ?>
query(" + G::$DB->query(" SELECT TreePosition, TreeID, TreeLevel FROM invite_tree WHERE UserID = $UserID"); - list($TreePosition, $TreeID, $TreeLevel) = $DB->next_record(MYSQLI_NUM, false); + list($TreePosition, $TreeID, $TreeLevel) = G::$DB->next_record(MYSQLI_NUM, false); if (!$TreeID) { return; } - $DB->query(" + G::$DB->query(" SELECT TreePosition FROM invite_tree WHERE TreeID = $TreeID @@ -41,12 +42,12 @@ function make_tree() { AND TreePosition > $TreePosition ORDER BY TreePosition ASC LIMIT 1"); - if ($DB->has_results()) { - list($MaxPosition) = $DB->next_record(MYSQLI_NUM, false); + if (G::$DB->has_results()) { + list($MaxPosition) = G::$DB->next_record(MYSQLI_NUM, false); } else { $MaxPosition = false; } - $TreeQuery = $DB->query(" + $TreeQuery = G::$DB->query(" SELECT it.UserID, Enabled, @@ -90,7 +91,7 @@ function make_tree() { // We store this in an output buffer, so we can show the summary at the top without having to loop through twice ob_start(); - while (list($ID, $Enabled, $Class, $Donor, $Uploaded, $Downloaded, $Paranoia, $TreePosition, $TreeLevel) = $DB->next_record()) { + while (list($ID, $Enabled, $Class, $Donor, $Uploaded, $Downloaded, $Paranoia, $TreePosition, $TreeLevel) = G::$DB->next_record()) { // Do stats $Count++; @@ -146,7 +147,7 @@ function make_tree() { ?> set_query_id($TreeQuery); + G::$DB->set_query_id($TreeQuery); } $Tree = ob_get_clean(); @@ -235,6 +236,7 @@ function make_tree() {
set_query_id($QueryID); } } ?> diff --git a/classes/irc.class.php b/classes/irc.class.php index 9569e18b..5efcf6fb 100644 --- a/classes/irc.class.php +++ b/classes/irc.class.php @@ -2,7 +2,6 @@ class IRC_DB extends DB_MYSQL { function halt($Msg) { global $Bot; - global $DB; $Bot->send_to($Bot->get_channel(),'The database is currently unavailable; try again later.'); } } @@ -135,7 +134,6 @@ protected function whois($Nick) { This function uses blacklisted_ip, which is no longer in RC2. You can probably find it in old RC1 code kicking aronud if you need it. protected function ip_check($IP, $Gline = false, $Channel = BOT_REPORT_CHAN) { - global $Cache, $DB; if (blacklisted_ip($IP)) { $this->send_to($Channel, 'TOR IP Detected: '.$IP); if ($Gline) { @@ -151,8 +149,7 @@ protected function ip_check($IP, $Gline = false, $Channel = BOT_REPORT_CHAN) { }*/ protected function listen() { - global $Cache, $DB; - $Cache->InternalCache = false; + G::$Cache->InternalCache = false; stream_set_timeout($this->Socket, 10000000000); while ($this->State == 1) { if ($this->Data = fgets($this->Socket, 256)) { @@ -182,20 +179,20 @@ protected function listen() { unset($this->Identified[$Nick[1]]); } if (isset($this->DisabledUsers[$Nick[1]])) { - $DB->query(" + G::$DB->query(" DELETE FROM disable_list WHERE Nick = '$Nick[1]'"); - $Cache->increment_value('num_disablees', -1); + G::$Cache->increment_value('num_disablees', -1); unset($this->DisabledUsers[$Nick[1]]); } } if (preg_match("/:([^!]+)![^\s]* PART ".BOT_DISABLED_CHAN.'/', $this->Data, $Nick)) { if (isset($this->DisabledUsers[$Nick[1]])) { - $DB->query(" + G::$DB->query(" DELETE FROM disable_list WHERE Nick = '$Nick[1]'"); - $Cache->increment_value('num_disablees', -1); + G::$Cache->increment_value('num_disablees', -1); unset($this->DisabledUsers[$Nick[1]]); } } @@ -203,10 +200,10 @@ protected function listen() { if (preg_match("/:([^!]+)![^\s]* KICK ".BOT_DISABLED_CHAN.'.* /', $this->Data, $Nick)) { $Nick = explode(' ', $Nick[0]); if (isset($this->DisabledUsers[$Nick[3]])) { - $DB->query(" + G::$DB->query(" DELETE FROM disable_list WHERE Nick = '$Nick[3]'"); - $Cache->increment_value('num_disablees', -1); + G::$Cache->increment_value('num_disablees', -1); unset($this->DisabledUsers[$Nick[3]]); } } @@ -232,8 +229,8 @@ protected function listen() { $this->listener_events(); } - $DB->LinkID = false; - $DB->Queries = array(); + G::$DB->LinkID = false; + G::$DB->Queries = array(); usleep(5000); } } diff --git a/classes/lastfm.class.php b/classes/lastfm.class.php index a5d530b3..424ba052 100644 --- a/classes/lastfm.class.php +++ b/classes/lastfm.class.php @@ -4,123 +4,121 @@ class LastFM { public static function get_artist_events($ArtistID, $Artist, $Limit = 15) { - global $Cache; - $ArtistEvents = $Cache->get_value("artist_events_$ArtistID"); + $ArtistEvents = G::$Cache->get_value("artist_events_$ArtistID"); if (empty($ArtistEvents)) { $ArtistEvents = self::lastfm_request("artist.getEvents", array("artist" => $Artist, "limit" => $Limit)); - $Cache->cache_value("artist_events_$ArtistID", $ArtistEvents, 432000); + G::$Cache->cache_value("artist_events_$ArtistID", $ArtistEvents, 432000); } return $ArtistEvents; } public static function get_user_info($Username) { - global $Cache; - $Response = $Cache->get_value("lastfm_user_info_$Username"); + $Response = G::$Cache->get_value("lastfm_user_info_$Username"); if (empty($Response)) { $Response = self::lastfm_request("user.getInfo", array("user" => $Username)); - $Cache->cache_value("lastfm_user_info_$Username", $Response, 86400); + G::$Cache->cache_value("lastfm_user_info_$Username", $Response, 86400); } return $Response; } public static function compare_user_with($Username1, $Limit = 15) { - global $Cache, $LoggedUser, $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT username FROM lastfm_users - WHERE ID = '$LoggedUser[ID]'"); - if ($DB->has_results()) { - list($Username2) = $DB->next_record(); + WHERE ID = '" . G::$LoggedUser['ID'] . "'"); + if (G::$DB->has_results()) { + list($Username2) = G::$DB->next_record(); //Make sure the usernames are in the correct order to avoid dupe cache keys. if (strcasecmp($Username1, $Username2)) { $Temp = $Username1; $Username1 = $Username2; $Username2 = $Temp; } - $Response = $Cache->get_value("lastfm_compare_$Username1" . "_$Username2"); + $Response = G::$Cache->get_value("lastfm_compare_$Username1" . "_$Username2"); if (empty($Response)) { $Response = self::lastfm_request("tasteometer.compare", array("type1" => "user", "type2" => "user", "value1" => $Username1, "value2" => $Username2, "limit" => $Limit)); $Response = json_encode($Response); - $Cache->cache_value("lastfm_compare_$Username1" . "_$Username2", $Response, 86400); + G::$Cache->cache_value("lastfm_compare_$Username1" . "_$Username2", $Response, 86400); } - return $Response; + } else { + $Response = null; } + G::$DB->set_query_id($QueryID); + return $Response; } public static function get_last_played_track($Username) { - global $Cache; - $Response = $Cache->get_value("lastfm_last_played_track_$Username"); + $Response = G::$Cache->get_value("lastfm_last_played_track_$Username"); if (empty($Response)) { $Response = self::lastfm_request("user.getRecentTracks", array("user" => $Username, "limit" => 1)); // Take the single last played track out of the response. $Response = $Response['recenttracks']['track']; $Response = json_encode($Response); - $Cache->cache_value("lastfm_last_played_track_$Username", $Response, 7200); + G::$Cache->cache_value("lastfm_last_played_track_$Username", $Response, 7200); } return $Response; } public static function get_top_artists($Username, $Limit = 15) { - global $Cache; - $Response = $Cache->get_value("lastfm_top_artists_$Username"); + $Response = G::$Cache->get_value("lastfm_top_artists_$Username"); if (empty($Response)) { sleep(1); $Response = self::lastfm_request("user.getTopArtists", array("user" => $Username, "limit" => $Limit)); $Response = json_encode($Response); - $Cache->cache_value("lastfm_top_artists_$Username", $Response, 86400); + G::$Cache->cache_value("lastfm_top_artists_$Username", $Response, 86400); } return $Response; } public static function get_top_albums($Username, $Limit = 15) { - global $Cache; - $Response = $Cache->get_value("lastfm_top_albums_$Username"); + $Response = G::$Cache->get_value("lastfm_top_albums_$Username"); if (empty($Response)) { sleep(2); $Response = self::lastfm_request("user.getTopAlbums", array("user" => $Username, "limit" => $Limit)); $Response = json_encode($Response); - $Cache->cache_value("lastfm_top_albums_$Username", $Response, 86400); + G::$Cache->cache_value("lastfm_top_albums_$Username", $Response, 86400); } return $Response; } public static function get_top_tracks($Username, $Limit = 15) { - global $Cache; - $Response = $Cache->get_value("lastfm_top_tracks_$Username"); + $Response = G::$Cache->get_value("lastfm_top_tracks_$Username"); if (empty($Response)) { sleep(3); $Response = self::lastfm_request("user.getTopTracks", array("user" => $Username, "limit" => $Limit)); $Response = json_encode($Response); - $Cache->cache_value("lastfm_top_tracks_$Username", $Response, 86400); + G::$Cache->cache_value("lastfm_top_tracks_$Username", $Response, 86400); } return $Response; } public static function clear_cache($Username, $Uid) { - global $Cache, $LoggedUser, $DB; - $Response = $Cache->get_value("lastfm_clear_cache_$LoggedUser" . '_' . $_GET['id']); + $Response = G::$Cache->get_value('lastfm_clear_cache_' . G::$LoggedUser['ID'] . '_' . $_GET['id']); if (empty($Response)) { // Prevent clearing the cache on the same uid page for the next 10 minutes. - $Response = $Cache->cache_value("lastfm_clear_cache_$LoggedUser" . "_$Uid", $Username, 600); - $Cache->delete_value("lastfm_user_info_$Username"); - $Cache->delete_value("lastfm_last_played_track_$Username"); - $Cache->delete_value("lastfm_top_artists_$Username"); - $Cache->delete_value("lastfm_top_albums_$Username"); - $Cache->delete_value("lastfm_top_tracks_$Username"); - $DB->query(" + $Response = G::$Cache->cache_value('lastfm_clear_cache_' . G::$LoggedUser['ID'] . "_$Uid", $Username, 600); + G::$Cache->delete_value("lastfm_user_info_$Username"); + G::$Cache->delete_value("lastfm_last_played_track_$Username"); + G::$Cache->delete_value("lastfm_top_artists_$Username"); + G::$Cache->delete_value("lastfm_top_albums_$Username"); + G::$Cache->delete_value("lastfm_top_tracks_$Username"); + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT username FROM lastfm_users - WHERE ID = '$LoggedUser[ID]'"); - if ($DB->has_results()) { - list($Username2) = $DB->next_record(); + WHERE ID = '" . G::$LoggedUser['ID'] . "'"); + if (G::$DB->has_results()) { + list($Username2) = G::$DB->next_record(); //Make sure the usernames are in the correct order to avoid dupe cache keys. if (strcasecmp($Username, $Username2)) { $Temp = $Username; $Username = $Username2; $Username2 = $Temp; } - $Cache->delete_value("lastfm_compare_$Username" . "_$Username2"); + G::$Cache->delete_value("lastfm_compare_$Username" . "_$Username2"); } + G::$DB->set_query_id($QueryID); } } diff --git a/classes/mass_user_bookmarks_editor.class.php b/classes/mass_user_bookmarks_editor.class.php index abe9d169..9411d624 100644 --- a/classes/mass_user_bookmarks_editor.class.php +++ b/classes/mass_user_bookmarks_editor.class.php @@ -17,13 +17,15 @@ public function __construct ($Table = 'bookmarks_torrents') { /** * Runs a SQL query and clears the Cache key * - * $Cache->delete_value didn't always work, but setting the key to null, did. (?) + * G::$Cache->delete_value didn't always work, but setting the key to null, did. (?) * * @param string $sql */ protected function query_and_clear_cache ($sql) { - if (is_string($sql) && $this->DB->query($sql)) - $this->Cache->delete_value('bookmarks_group_ids_' . $this->UserID); + $QueryID = G::$DB->get_query_id(); + if (is_string($sql) && G::$DB->query($sql)) + G::$Cache->delete_value('bookmarks_group_ids_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); } /** @@ -41,7 +43,7 @@ public function mass_remove () { if (!empty($SQL)) { $SQL = sprintf('DELETE FROM %s WHERE UserID = %d AND GroupID IN (%s)', $this->Table, - $this->UserID, + G::$LoggedUser['ID'], implode(', ', $SQL) ); $this->query_and_clear_cache($SQL); @@ -55,7 +57,7 @@ public function mass_update () { $SQL = array(); foreach ($_POST['sort'] as $GroupID => $Sort) { if (is_number($Sort) && is_number($GroupID)) - $SQL[] = sprintf('(%d, %d, %d)', $GroupID, $Sort, $this->UserID); + $SQL[] = sprintf('(%d, %d, %d)', $GroupID, $Sort, G::$LoggedUser['ID']); } if (!empty($SQL)) { diff --git a/classes/mass_user_torrents_editor.class.php b/classes/mass_user_torrents_editor.class.php index ec67d3ac..58c9e185 100644 --- a/classes/mass_user_torrents_editor.class.php +++ b/classes/mass_user_torrents_editor.class.php @@ -13,87 +13,49 @@ * * It could also be used for other types like collages. */ -abstract class MASS_USER_TORRENTS_EDITOR -{ - /** - * Internal access to the Cache - * @var Cache $Cache - */ - protected $Cache; - - /** - * Internal access to the Database - * @var DB_MYSQL $DB - */ - protected $DB; - - /** - * Current User's ID - * @var str|int $UserID - */ - protected $UserID; - +abstract class MASS_USER_TORRENTS_EDITOR { /** * The affected DB table * @var string $Table */ protected $Table; - /** - * Extended classes should call this method. - * @example parent::__construct() - * @global CACHE $Cache - * @global DB_MYSQL $DB - * @global string|int $UserID - */ - public function __construct (/*CACHE &$Cache, DB_MYSQL &$DB, $UserID*/) - { - global $Cache, $DB, $UserID; - $this->Cache = $Cache; - $this->DB = $DB; - $this->UserID = (int) $UserID; - if ($this->UserID < 1) error(403); - } - /** * Set the Table * @param string $Table */ - final public function set_table ($Table) - { + final public function set_table($Table) { $this->Table = db_string($Table); } /** * Get the Table - * @param sting $Table * @return string $Table */ - final public function get_table () - { + final public function get_table() { return $this->Table; } /** * The extending class must provide a method to send a query and clear the cache */ - abstract protected function query_and_clear_cache ($sql); + abstract protected function query_and_clear_cache($sql); /** * A method to insert many rows into a single table * Not required in subsequent classes */ - public function mass_add () {} + public function mass_add() {} /** * A method to remove many rows from a table * The extending class must have a mass_remove method */ - abstract public function mass_remove (); + abstract public function mass_remove(); /** * A method to update many rows in a table * The extending class must have a mass_update method */ - abstract public function mass_update (); + abstract public function mass_update(); } \ No newline at end of file diff --git a/classes/mass_user_torrents_table_view.class.php b/classes/mass_user_torrents_table_view.class.php index 025bd7b4..9c8c7531 100644 --- a/classes/mass_user_torrents_table_view.class.php +++ b/classes/mass_user_torrents_table_view.class.php @@ -36,24 +36,12 @@ class MASS_USER_TORRENTS_TABLE_VIEW { */ private $TorrentList; - /** - * Ref. to $LoggedUser - * @var array $LoggedUser - */ - private $LoggedUser; - /** * Ref. to $CollageDataList * @var array $CollageDataList */ private $CollageDataList; - /** - * The UserID - * @var int $UserID - */ - private $UserID; - /** * Counter for number of groups * @var in $NumGroups @@ -64,22 +52,15 @@ class MASS_USER_TORRENTS_TABLE_VIEW { * When creating a new instance of this class, TorrentList and * CollageDataList must be passed. Additionally, a heading can be added. * - * @global int|string $UserID - * @global array $LoggedUser * @param array $TorrentList * @param array $CollageDataList * @param string $EditType * @param string $Heading */ public function __construct (array &$TorrentList, array &$CollageDataList, $EditType, $Heading = null) { - global $UserID, $LoggedUser; - $this->set_heading($Heading); $this->set_edit_type($EditType); - $this->UserID = (int) $UserID; - $this->LoggedUser = &$LoggedUser; - $this->TorrentList = $TorrentList; $this->CollageDataList = $CollageDataList; @@ -116,7 +97,7 @@ public function render_all () { * form, table, etc. */ public function header () { - if ($this->HasTorrents) : + if ($this->HasTorrents) { ?>
@@ -134,14 +115,13 @@ public function header () {
  • Click and drag any row to change its order.
  • Double-click on a row to check it.
  • -
    -buttons(); ?> +buttons(); ?> @@ -157,31 +137,31 @@ public function header () { HasTorrents) : + if ($this->HasTorrents) { ?>
    -buttons(); ?> +buttons(); ?>
    - +
    get_query_id(); + if ($ConvID == '') { // Create a new conversation. - $DB->query(" + G::$DB->query(" INSERT INTO pm_conversations (Subject) VALUES ('$Subject')"); - $ConvID = $DB->inserted_id(); - $DB->query(" + $ConvID = G::$DB->inserted_id(); + G::$DB->query(" INSERT INTO pm_conversations_users (UserID, ConvID, InInbox, InSentbox, SentDate, ReceivedDate, UnRead) VALUES ('$ToID', '$ConvID', '1','0','".sqltime()."', '".sqltime()."', '1')"); if ($FromID != 0) { - $DB->query(" + G::$DB->query(" INSERT INTO pm_conversations_users (UserID, ConvID, InInbox, InSentbox, SentDate, ReceivedDate, UnRead) VALUES @@ -71,7 +74,7 @@ public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '') { $ToID = array($ToID); } else { // Update the pre-existing conversations. - $DB->query(" + G::$DB->query(" UPDATE pm_conversations_users SET InInbox='1', @@ -80,7 +83,7 @@ public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '') { WHERE UserID IN (".implode(',', $ToID).") AND ConvID='$ConvID'"); - $DB->query(" + G::$DB->query(" UPDATE pm_conversations_users SET InSentbox='1', @@ -90,7 +93,7 @@ public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '') { } // Now that we have a $ConvID for sure, send the message. - $DB->query(" + G::$DB->query(" INSERT INTO pm_messages (SenderID, ConvID, SentDate, Body) VALUES @@ -98,33 +101,35 @@ public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '') { // Update the cached new message count. foreach ($ToID as $ID) { - $DB->query(" + G::$DB->query(" SELECT COUNT(ConvID) FROM pm_conversations_users WHERE UnRead = '1' AND UserID='$ID' AND InInbox = '1'"); - list($UnRead) = $DB->next_record(); - $Cache->cache_value('inbox_new_'.$ID, $UnRead); + list($UnRead) = G::$DB->next_record(); + G::$Cache->cache_value('inbox_new_'.$ID, $UnRead); } - $DB->query(" + G::$DB->query(" SELECT Username FROM users_main WHERE ID = '$FromID'"); - list($SenderName) = $DB->next_record(); + list($SenderName) = G::$DB->next_record(); foreach ($ToID as $ID) { - $DB->query(" + G::$DB->query(" SELECT COUNT(ConvID) FROM pm_conversations_users WHERE UnRead = '1' AND UserID='$ID' AND InInbox = '1'"); - list($UnRead) = $DB->next_record(); - $Cache->cache_value('inbox_new_'.$ID, $UnRead); + list($UnRead) = G::$DB->next_record(); + G::$Cache->cache_value('inbox_new_'.$ID, $UnRead); } + G::$DB->set_query_id($QueryID); + return $ConvID; } @@ -139,40 +144,43 @@ public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '') { * @return -1 on error, -2 on user not existing, thread id on success. */ public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) { - global $DB, $Cache, $Time; + global $Time; if (!$ForumID || !$AuthorID || !is_number($AuthorID) || !$Title || !$PostBody) { return -1; } - $DB->query(" + $QueryID = G::$DB->get_query_id(); + + G::$DB->query(" SELECT Username FROM users_main WHERE ID=".$AuthorID); - if (!$DB->has_results()) { + if (!G::$DB->has_results()) { + G::$DB->set_query_id($QueryID); return -2; } - list($AuthorName) = $DB->next_record(); + list($AuthorName) = G::$DB->next_record(); $ThreadInfo = array(); $ThreadInfo['IsLocked'] = 0; $ThreadInfo['IsSticky'] = 0; - $DB->query(" + G::$DB->query(" INSERT INTO forums_topics (Title, AuthorID, ForumID, LastPostTime, LastPostAuthorID) VALUES ('$Title', '$AuthorID', '$ForumID', '".sqltime()."', '$AuthorID')"); - $TopicID = $DB->inserted_id(); + $TopicID = G::$DB->inserted_id(); $Posts = 1; - $DB->query(" + G::$DB->query(" INSERT INTO forums_posts (TopicID, AuthorID, AddedTime, Body) VALUES ('$TopicID', '$AuthorID', '".sqltime()."', '$PostBody')"); - $PostID = $DB->inserted_id(); + $PostID = G::$DB->inserted_id(); - $DB->query(" + G::$DB->query(" UPDATE forums SET NumPosts = NumPosts+1, @@ -183,7 +191,7 @@ public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) { LastPostTime = '".sqltime()."' WHERE ID = '$ForumID'"); - $DB->query(" + G::$DB->query(" UPDATE forums_topics SET NumPosts = NumPosts+1, @@ -193,16 +201,16 @@ public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) { WHERE ID = '$TopicID'"); // Bump this topic to head of the cache - list($Forum,,, $Stickies) = $Cache->get_value('forums_'.$ForumID); + list($Forum,,, $Stickies) = G::$Cache->get_value('forums_'.$ForumID); if (!empty($Forum)) { if (count($Forum) == TOPICS_PER_PAGE && $Stickies < TOPICS_PER_PAGE) { array_pop($Forum); } - $DB->query(" + G::$DB->query(" SELECT f.IsLocked, f.IsSticky, f.NumPosts FROM forums_topics AS f WHERE f.ID ='$TopicID'"); - list($IsLocked, $IsSticky, $NumPosts) = $DB->next_record(); + list($IsLocked, $IsSticky, $NumPosts) = G::$DB->next_record(); $Part1 = array_slice($Forum, 0, $Stickies, true); //Stickys $Part2 = array( $TopicID => array( @@ -228,11 +236,11 @@ public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) { if (is_null($Part1)) { $Part1 = array(); } if (is_null($Part3)) { $Part3 = array(); } $Forum = $Part1 + $Part2 + $Part3; - $Cache->cache_value('forums_'.$ForumID, array($Forum, '', 0, $Stickies), 0); + G::$Cache->cache_value('forums_'.$ForumID, array($Forum, '', 0, $Stickies), 0); } //Update the forum root - $Cache->begin_transaction('forums_list'); + G::$Cache->begin_transaction('forums_list'); $UpdateArray = array( 'NumPosts'=>'+1', 'NumTopics'=>'+1', @@ -247,26 +255,28 @@ public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) { $UpdateArray['NumTopics'] = '+1'; - $Cache->update_row($ForumID, $UpdateArray); - $Cache->commit_transaction(0); + G::$Cache->update_row($ForumID, $UpdateArray); + G::$Cache->commit_transaction(0); $CatalogueID = floor((POSTS_PER_PAGE * ceil($Posts / POSTS_PER_PAGE) - POSTS_PER_PAGE) / THREAD_CATALOGUE); - $Cache->begin_transaction('thread_'.$TopicID.'_catalogue_'.$CatalogueID); + G::$Cache->begin_transaction('thread_'.$TopicID.'_catalogue_'.$CatalogueID); $Post = array( 'ID'=>$PostID, - 'AuthorID'=>$LoggedUser['ID'], + 'AuthorID'=>G::$LoggedUser['ID'], 'AddedTime'=>sqltime(), 'Body'=>$PostBody, 'EditedUserID'=>0, 'EditedTime'=>'0000-00-00 00:00:00', 'Username'=>'' ); - $Cache->insert('', $Post); - $Cache->commit_transaction(0); + G::$Cache->insert('', $Post); + G::$Cache->commit_transaction(0); - $Cache->begin_transaction('thread_'.$TopicID.'_info'); - $Cache->update_row(false, array('Posts'=>'+1', 'LastPostAuthorID'=>$AuthorID)); - $Cache->commit_transaction(0); + G::$Cache->begin_transaction('thread_'.$TopicID.'_info'); + G::$Cache->update_row(false, array('Posts'=>'+1', 'LastPostAuthorID'=>$AuthorID)); + G::$Cache->commit_transaction(0); + + G::$DB->set_query_id($QueryID); return $TopicID; } @@ -355,24 +365,25 @@ public static function assert_isset_request($Request, $Keys = NULL, $AllowEmpty * @return array IDs */ public static function get_tags($TagNames) { - global $Cache, $DB; $TagIDs = array(); foreach ($TagNames as $Index => $TagName) { - $Tag = $Cache->get_value('tag_id_'.$TagName); + $Tag = G::$Cache->get_value('tag_id_'.$TagName); if (is_array($Tag)) { unset($TagNames[$Index]); $TagIDs[$Tag['ID']] = $Tag['Name']; } } if (count($TagNames) > 0) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT ID, Name FROM tags WHERE Name IN ('".implode("', '", $TagNames)."')"); - $SQLTagIDs = $DB->to_array(); + $SQLTagIDs = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); foreach ($SQLTagIDs as $Tag) { $TagIDs[$Tag['ID']] = $Tag['Name']; - $Cache->cache_value('tag_id_'.$Tag['Name'], $Tag, 0); + G::$Cache->cache_value('tag_id_'.$Tag['Name'], $Tag, 0); } } @@ -387,17 +398,19 @@ public static function get_tags($TagNames) { * @return string The aliased tag. */ public static function get_alias_tag($BadTag) { - global $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT AliasTag FROM tag_aliases WHERE BadTag = '$BadTag' LIMIT 1"); - if ($DB->has_results()) { - list($AliasTag) = $DB->next_record(); - return $AliasTag; + if (G::$DB->has_results()) { + list($AliasTag) = G::$DB->next_record(); + } else { + $AliasTag = $BadTag; } - return $BadTag; + G::$DB->set_query_id($QueryID); + return $AliasTag; } @@ -407,10 +420,12 @@ public static function get_alias_tag($BadTag) { * @param string $Message the message to write. */ public static function write_log($Message) { - global $DB, $Time; - $DB->query(" + global $Time; + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" INSERT INTO log (Message, Time) VALUES ('" . db_string($Message) . "', '" . sqltime() . "')"); + G::$DB->set_query_id($QueryID); } @@ -491,7 +506,6 @@ public static function is_new_torrent(&$Data) { } public static function display_recommend($ID, $Type, $Hide = true) { - global $DB, $LoggedUser; if ($Hide) { $Hide = ' style="display: none;"'; } @@ -509,5 +523,9 @@ public static function display_recommend($ID, $Type, $Hide = true) { diff --git a/classes/mysql.class.php b/classes/mysql.class.php index cc67628b..fc5e99ae 100644 --- a/classes/mysql.class.php +++ b/classes/mysql.class.php @@ -95,7 +95,7 @@ This class can only hold one result set at a time. Using set_query_id allows you to set the result set that the class is using to the result set in $ResultSet. This result set should have been obtained earlier by using - $DB-query(). + $DB->query(). Example: @@ -173,7 +173,7 @@ function __construct($Database = SQLDB, $User = SQLLOGIN, $Pass = SQLPASS, $Serv } function halt($Msg) { - global $LoggedUser, $Cache, $Debug, $argv; + global $Debug, $argv; $DBError = 'MySQL: '.strval($Msg).' SQL error: '.strval($this->Errno).' ('.strval($this->Error).')'; if ($this->Errno == 1194) { send_irc('PRIVMSG '.ADMIN_CHAN.' :'.$this->Error); @@ -205,7 +205,7 @@ function connect() { } function query($Query, $AutoHandle = 1) { - global $LoggedUser, $Debug; + global $Debug; /* * If there was a previous query, we store the warnings. We cannot do * this immediately after mysqli_query because mysqli_insert_id will diff --git a/classes/notificationsmanager.class.php b/classes/notificationsmanager.class.php new file mode 100644 index 00000000..101b16a8 --- /dev/null +++ b/classes/notificationsmanager.class.php @@ -0,0 +1,659 @@ + "information", + "critical" => "error", + "warning" => "warning", + "info" => "confirmation"); + + // Types. These names must correspond to column names in users_notifications_settings + const NEWS = "News"; + const BLOG = "Blog"; + const STAFFBLOG = "StaffBlog"; + const STAFFPM = "StaffPM"; + const INBOX = "Inbox"; + const QUOTES = "Quotes"; + const SUBSCRIPTIONS = "Subscriptions"; + const TORRENTS = "Torrents"; + const COLLAGES = "Collages"; + const SITEALERTS = "SiteAlerts"; + const FORUMALERTS = "ForumAlerts"; + const REQUESTALERTS = "RequestAlerts"; + const COLLAGEALERTS = "CollageAlerts"; + const TORRENTALERTS = "TorrentAlerts"; + const GLOBALNOTICE = "Global"; + + + public static $Types = array( + "News", + "Blog", + "StaffPM", + "Inbox", + "Quotes", + "Subscriptions", + "Torrents", + "Collages", + "SiteAlerts", + "ForumAlerts", + "RequestAlerts", + "CollageAlerts", + "TorrentAlerts"); + + private $UserID; + private $Notifications; + private $Settings; + + function __construct($UserID, $Skip = array(), $Load = true, $AutoSkip = true) { + $this->UserID = $UserID; + $this->Notifications = array(); + $this->Settings = self::get_settings($UserID); + if ($AutoSkip) { + foreach ($this->Settings as $Key => $Value) { + // Skip disabled and traditional settings + if ($Value == 0 || $Value == 2) { + $Skip[] = $Key; + } + } + } + if ($Load) { + $this->load_global_notification(); + if (!in_array(self::NEWS, $Skip)) { + $this->load_news(); + } + if (!in_array(self::BLOG, $Skip)) { + $this->load_blog(); + } + // if (!in_array(self::STAFFBLOG, $Skip)) { + // $this->load_staff_blog(); + // } + if (!in_array(self::STAFFPM, $Skip)) { + $this->load_staff_pms(); + } + if (!in_array(self::INBOX, $Skip)) { + $this->load_inbox(); + } + if (!in_array(self::TORRENTS, $Skip)) { + $this->load_torrent_notifications(); + } + if (!in_array(self::COLLAGES, $Skip)) { + $this->load_collage_subscriptions(); + } + if (!in_array(self::QUOTES, $Skip)) { + $this->load_quote_notifications(); + } + if (!in_array(self::SUBSCRIPTIONS, $Skip)) { + $this->load_subscriptions(); + } + $this->load_one_reads(); + + } + } + + public function get_notifications() { + return $this->Notifications; + } + + public function clear_notifications_array() { + unset($this->Notifications); + $this->Notifications = array(); + } + + private function create_notification($Type, $ID, $Message, $URL, $Importance) { + $this->Notifications[$Type] = array("contents" => array("id" => (int) $ID, "message" => $Message, "url" => $URL, "importance" => $Importance)); + } + + public static function notify_user($UserID, $Type, $Message, $URL, $Importance) { + self::notify_users(array($UserID), $Type, $Message, $URL, $Importance); + } + + public static function notify_users($UserIDs, $Type, $Message, $URL, $Importance) { + /** + if (!isset($Importance)) { + $Importance = self::INFO; + } + $Type = db_string($Type); + if (!empty($UserIDs)) { + $UserIDs = implode(',', $UserIDs); + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT UserID + FROM users_notifications_settings + WHERE $Type != 0 + AND UserID IN ($UserIDs)"); + $UserIDs = array(); + while (list($ID) = G::$DB->next_record()) { + $UserIDs[] = $ID; + } + G::$DB->set_query_id($QueryID); + foreach ($UserIDs as $UserID) { + $OneReads = G::$Cache->get_value("notifications_one_reads_$UserID"); + if (!$OneReads) { + $OneReads = array(); + } + array_unshift($OneReads, $this->create_notification($OneReads, "oneread_" . uniqid(), null, $Message, $URL, $Importance)); + $OneReads = array_filter($OneReads); + G::$Cache->cache_value("notifications_one_reads_$UserID", $OneReads, 0); + } + } + **/ + } + + public static function get_notification_enabled_users($Type, $UserID) { + $Type = db_string($Type); + $UserWhere = ''; + if (isset($UserID)) { + $UserID = (int) $UserID; + $UserWhere = " AND UserID = '$UserID'"; + } + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT UserID + FROM users_notifications_settings + WHERE $Type != 0 + $UserWhere"); + $IDs = array(); + while (list($ID) = G::$DB->next_record()) { + $IDs[] = $ID; + } + G::$DB->set_query_id($QueryID); + return $IDs; + } + + public function load_one_reads() { + $OneReads = G::$Cache->get_value('notifications_one_reads_' . G::$LoggedUser['ID']); + if (is_array($OneReads)) { + $this->Notifications = $this->Notifications + $OneReads; + } + } + + public static function clear_one_read($ID) { + $OneReads = G::$Cache->get_value('notifications_one_reads_' . G::$LoggedUser['ID']); + if ($OneReads) { + unset($OneReads[$ID]); + if (count($OneReads) > 0) { + G::$Cache->cache_value('notifications_one_reads_' . G::$LoggedUser['ID'], $OneReads, 0); + } else { + G::$Cache->delete_value('notifications_one_reads_' . G::$LoggedUser['ID']); + } + } + + } + + public function load_global_notification() { + $GlobalNotification = G::$Cache->get_value('global_notification'); + if ($GlobalNotification) { + $Read = G::$Cache->get_value('user_read_global_' . G::$LoggedUser['ID']); + if (!$Read) { + $this->create_notification(self::GLOBALNOTICE, null, $GlobalNotification['Message'], $GlobalNotification['URL'], $GlobalNotification['Importance']); + } + } + } + + public static function get_global_notification() { + return G::$Cache->get_value('global_notification'); + } + + public static function set_global_notification($Message, $URL, $Importance, $Expiration) { + if (empty($Message) || empty($Expiration)) { + error('Error setting notification'); + } + G::$Cache->cache_value('global_notification', array("Message" => $Message, "URL" => $URL, "Importance" => $Importance, "Expiration" => $Expiration), $Expiration); + } + + public static function delete_global_notification() { + G::$Cache->delete_value('global_notification'); + } + + public static function clear_global_notification() { + $GlobalNotification = G::$Cache->get_value('global_notification'); + if ($GlobalNotification) { + // This is some trickery + // since we can't know which users have the read cache key set + // wet set the expiration time of their cache key to that of the length of the notification + // this gaurantees that their cache key will expire after the notification expires + G::$Cache->cache_value('user_read_global_' . G::$LoggedUser['ID'], true, $GlobalNotification['Expiration']); + } + } + + public function load_news() { + $MyNews = G::$LoggedUser['LastReadNews']; + $CurrentNews = G::$Cache->get_value('news_latest_id'); + $Title = G::$Cache->get_value('news_latest_title'); + if ($CurrentNews === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(' + SELECT ID, Title + FROM news + ORDER BY Time DESC + LIMIT 1'); + if (G::$DB->has_results()) { + list($CurrentNews, $Title) = G::$DB->next_record(); + } else { + $CurrentNews = -1; + } + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('news_latest_id', $CurrentNews, 0); + G::$Cache->cache_value('news_latest_title', $Title, 0); + } + if ($MyNews < $CurrentNews) { + $this->create_notification(self::NEWS, $CurrentNews, "Announcement: $Title", "index.php#news$CurrentNews", self::IMPORTANT); + } + } + + public function load_blog() { + $MyBlog = G::$LoggedUser['LastReadBlog']; + $CurrentBlog = G::$Cache->get_value('blog_latest_id'); + $Title = G::$Cache->get_value('blog_latest_title'); + if ($CurrentBlog === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(' + SELECT ID, Title + FROM blog + WHERE Important = 1 + ORDER BY Time DESC + LIMIT 1'); + if (G::$DB->has_results()) { + list($CurrentBlog, $Title) = G::$DB->next_record(); + } else { + $CurrentBlog = -1; + } + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('blog_latest_id', $CurrentBlog, 0); + G::$Cache->cache_value('blog_latest_title', $Title, 0); + } + if ($MyBlog < $CurrentBlog) { + $this->create_notification(self::BLOG, $CurrentBlog, "Blog: $Title", "blog.php#blog$CurrentBlog", self::IMPORTANT); + } + } + + public function load_staff_blog() { + if (check_perms('users_mod')) { + global $SBlogReadTime, $LatestSBlogTime; + if (!$SBlogReadTime && ($SBlogReadTime = G::$Cache->get_value('staff_blog_read_' . G::$LoggedUser['ID'])) === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT Time + FROM staff_blog_visits + WHERE UserID = " . G::$LoggedUser['ID']); + if (list($SBlogReadTime) = G::$DB->next_record()) { + $SBlogReadTime = strtotime($SBlogReadTime); + } else { + $SBlogReadTime = 0; + } + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('staff_blog_read_' . G::$LoggedUser['ID'], $SBlogReadTime, 1209600); + } + if (!$LatestSBlogTime && ($LatestSBlogTime = G::$Cache->get_value('staff_blog_latest_time')) === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(' + SELECT MAX(Time) + FROM staff_blog'); + if (list($LatestSBlogTime) = G::$DB->next_record()) { + $LatestSBlogTime = strtotime($LatestSBlogTime); + } else { + $LatestSBlogTime = 0; + } + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('staff_blog_latest_time', $LatestSBlogTime, 1209600); + } + if ($SBlogReadTime < $LatestSBlogTime) { + $this->create_notification(self::STAFFBLOG, '', 'New Staff Blog Post!', 'staffblog.php', self::IMPORTANT); + } + } + } + + public function load_staff_pms() { + $NewStaffPMs = G::$Cache->get_value('staff_pm_new_' . G::$LoggedUser['ID']); + if ($NewStaffPMs === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT COUNT(ID) + FROM staff_pm_conversations + WHERE UserID = '" . G::$LoggedUser['ID'] . "' + AND Unread = '1'"); + list($NewStaffPMs) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('staff_pm_new_' . G::$LoggedUser['ID'], $NewStaffPMs, 0); + } + + if ($NewStaffPMs > 0) { + $Title = 'You have new ' . ($NewStaffPMs == 1 ? 'a' : $NewStaffPMs) . ' Staff PM' . ($NewStaffPMs > 1 ? 's' : ''); + $this->create_notification(self::STAFFPM, '', $Title, 'staffpm.php', self::INFO); + } + } + + public function load_inbox() { + $NewMessages = G::$Cache->get_value('inbox_new_' . G::$LoggedUser['ID']); + if ($NewMessages === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT COUNT(UnRead) + FROM pm_conversations_users + WHERE UserID = '" . G::$LoggedUser['ID'] . "' + AND UnRead = '1' + AND InInbox = '1'"); + list($NewMessages) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('inbox_new_' . G::$LoggedUser['ID'], $NewMessages, 0); + } + + if ($NewMessages > 0) { + $Title = 'You have ' . ($NewMessages == 1 ? 'a' : $NewMessages) . ' new message' . ($NewMessages > 1 ? 's' : ''); + $this->create_notification(self::INBOX, '', $Title, Inbox::get_inbox_link(), self::INFO); + } + } + + public function load_torrent_notifications() { + if (check_perms('site_torrents_notify')) { + $NewNotifications = G::$Cache->get_value('notifications_new_' . G::$LoggedUser['ID']); + if ($NewNotifications === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT COUNT(UserID) + FROM users_notify_torrents + WHERE UserID = ' " . G::$LoggedUser['ID'] . "' + AND UnRead = '1'"); + list($NewNotifications) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('notifications_new_' . G::$LoggedUser['ID'], $NewNotifications, 0); + } + } + if ($NewNotifications > 0) { + $Title = 'You have ' . ($NewNotifications == 1 ? 'a' : $NewNotifications) . ' new torrent notification' . ($NewNotifications > 1 ? 's' : ''); + $this->create_notification(self::TORRENTS, '', $Title, 'torrents.php?action=notify', self::INFO); + } + } + + public function load_collage_subscriptions() { + if (check_perms('site_collages_subscribe')) { + $NewCollages = G::$Cache->get_value('collage_subs_user_new_' . G::$LoggedUser['ID']); + if ($NewCollages === false) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT COUNT(DISTINCT s.CollageID) + FROM users_collage_subs as s + JOIN collages as c ON s.CollageID = c.ID + JOIN collages_torrents as ct on ct.CollageID = c.ID + WHERE s.UserID = " . G::$LoggedUser['ID'] . " + AND ct.AddedOn > s.LastVisit + AND c.Deleted = '0'"); + list($NewCollages) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('collage_subs_user_new_' . G::$LoggedUser['ID'], $NewCollages, 0); + } + if ($NewCollages > 0) { + $Title = 'You have ' . ($NewCollages == 1 ? 'a' : $NewCollages) . ' new collage update' . ($NewCollages > 1 ? 's' : ''); + $this->create_notification(self::COLLAGES, '', $Title, 'userhistory.php?action=subscribed_collages', self::INFO); + } + } + } + + public function load_quote_notifications() { + if (G::$LoggedUser['NotifyOnQuote']) { + $QuoteNotificationsCount = Subscriptions::has_new_quote_notifications(); + if ($QuoteNotificationsCount > 0) { + $Title = 'New quote' . ($QuoteNotificationsCount > 1 ? 's' : ''); + $this->create_notification(self::QUOTES, null, $Title, 'userhistory.php?action=quote_notifications', self::INFO); + } + } + } + + public function load_subscriptions() { + $SubscriptionsCount = Subscriptions::has_new_subscriptions(); + if ($SubscriptionsCount > 0) { + $Title = 'New subscription' . ($SubscriptionsCount > 1 ? 's' : ''); + $this->create_notification(self::SUBSCRIPTIONS, null, $Title, 'userhistory.php?action=subscriptions', self::INFO); + } + } + + + + public static function clear_news($News) { + $QueryID = G::$DB->get_query_id(); + if (!$News) { + if (!$News = G::$Cache->get_value('news')) { + G::$DB->query(' + SELECT + ID, + Title, + Body, + Time + FROM news + ORDER BY Time DESC + LIMIT 1'); + $News = G::$DB->to_array(false, MYSQLI_NUM, false); + G::$Cache->cache_value('news_latest_id', $News[0][0], 0); + } + } + + if (G::$LoggedUser['LastReadNews'] != $News[0][0]) { + G::$Cache->begin_transaction('user_info_heavy_' . G::$LoggedUser['ID']); + G::$Cache->update_row(false, array('LastReadNews' => $News[0][0])); + G::$Cache->commit_transaction(0); + G::$DB->query(" + UPDATE users_info + SET LastReadNews = '".$News[0][0]."' + WHERE UserID = " . G::$LoggedUser['ID']); + G::$LoggedUser['LastReadNews'] = $News[0][0]; + } + G::$DB->set_query_id($QueryID); + } + + public static function clear_blog($Blog) { + $QueryID = G::$DB->get_query_id(); + if (!$Blog) { + if (!$Blog = G::$Cache->get_value('blog')) { + G::$DB->query(" + SELECT + b.ID, + um.Username, + b.Title, + b.Body, + b.Time, + b.ThreadID + FROM blog AS b + LEFT JOIN users_main AS um ON b.UserID = um.ID + ORDER BY Time DESC + LIMIT 1"); + $Blog = G::$DB->to_array(); + } + } + if (G::$LoggedUser['LastReadBlog'] < $Blog[0][0]) { + G::$Cache->begin_transaction('user_info_heavy_' . G::$LoggedUser['ID']); + G::$Cache->update_row(false, array('LastReadBlog' => $Blog[0][0])); + G::$Cache->commit_transaction(0); + G::$DB->query(" + UPDATE users_info + SET LastReadBlog = '". $Blog[0][0]."' + WHERE UserID = " . G::$LoggedUser['ID']); + G::$LoggedUser['LastReadBlog'] = $Blog[0][0]; + } + G::$DB->set_query_id($QueryID); + } + + public static function clear_staff_pms() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT ID + FROM staff_pm_conversations + WHERE Unread = true + AND UserID = " . G::$LoggedUser['ID']); + $IDs = array(); + while (list($ID) = G::$DB->next_record()) { + $IDs[] = $ID; + } + $IDs = implode(',', $IDs); + if (!empty($IDs)) { + G::$DB->query(" + UPDATE staff_pm_conversations + SET Unread = false + WHERE ID IN ($IDs)"); + } + G::$Cache->delete_value('staff_pm_new_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function clear_inbox() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT ConvID + FROM pm_conversations_users + WHERE Unread = '1' + AND UserID = " . G::$LoggedUser['ID']); + $IDs = array(); + while (list($ID) = G::$DB->next_record()) { + $IDs[] = $ID; + } + $IDs = implode(',', $IDs); + if (!empty($IDs)) { + G::$DB->query(" + UPDATE pm_conversations_users + SET Unread = '0' + WHERE ConvID IN ($IDs) + AND UserID = " . G::$LoggedUser['ID']); + } + G::$Cache->delete_value('inbox_new_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function clear_torrents() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT TorrentID + FROM users_notify_torrents + WHERE UserID = ' " . G::$LoggedUser['ID'] . "' + AND UnRead = '1'"); + $IDs = array(); + while (list($ID) = G::$DB->next_record()) { + $IDs[] = $ID; + } + $IDs = implode(',', $IDs); + if (!empty($IDs)) { + G::$DB->query(" + UPDATE users_notify_torrents + SET Unread = '0' + WHERE TorrentID IN ($IDs) + AND UserID = " . G::$LoggedUser['ID']); + } + G::$Cache->delete_value('notifications_new_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function clear_collages() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + UPDATE users_collage_subs + SET LastVisit = NOW() + WHERE UserID = " . G::$LoggedUser['ID']); + G::$Cache->delete_value('collage_subs_user_new_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function clear_quotes() { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + UPDATE users_notify_quoted + SET UnRead = '0' + WHERE UserID = " . G::$LoggedUser['ID']); + G::$Cache->delete_value('notify_quoted_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function clear_subscriptions() { + $QueryID = G::$DB->get_query_id(); + if (($UserSubscriptions = G::$Cache->get_value('subscriptions_user_' . G::$LoggedUser['ID'])) === false) { + G::$DB->query(" + SELECT TopicID + FROM users_subscriptions + WHERE UserID = " . G::$LoggedUser['ID']); + if ($UserSubscriptions = G::$DB->collect(0)) { + G::$Cache->cache_value('subscriptions_user_' . G::$LoggedUser['ID'], $UserSubscriptions, 0); + } + } + if (!empty($UserSubscriptions)) { + G::$DB->query(" + INSERT INTO forums_last_read_topics (UserID, TopicID, PostID) + SELECT '" . G::$LoggedUser['ID'] . "', ID, LastPostID + FROM forums_topics + WHERE ID IN (".implode(',', $UserSubscriptions).') + ON DUPLICATE KEY + UPDATE PostID = LastPostID'); + } + G::$Cache->delete_value('subscriptions_user_new_' . G::$LoggedUser['ID']); + G::$DB->set_query_id($QueryID); + } + + public static function send_notification($UserID, $ID, $Type, $Message, $URL, $Importance = 'alert', $AutoExpire = false) { + $Notifications = G::$Cache->get_value("user_cache_notifications_$UserID"); + if (empty($Notifications)) { + $Notifications = array(); + } + array_unshift($Notifications, $this->create_notification($Type, $ID, $Message, $URL, $Importance, $AutoExpire)); + G::$Cache->cache_value("user_cache_notifications_$UserID", $Notifications, 0); + } + + + public static function clear_notification($UserID, $Index) { + $Notifications = G::$Cache->get_value("user_cache_notifications_$UserID"); + if (count($Notifications)) { + unset($Notifications[$Index]); + $Notifications = array_values($Notifications); + G::$Cache->cache_value("user_cache_notifications_$UserID", $Notifications, 0); + } + } + + public static function get_settings($UserID) { + $Results = G::$Cache->get_value("users_notifications_settings_$UserID"); + if (!$Results) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + SELECT * + FROM users_notifications_settings + WHERE UserID = '$UserID'"); + $Results = G::$DB->next_record(MYSQLI_ASSOC); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value("users_notifications_settings_$UserID", $Results, 0); + } + return $Results; + } + + public static function save_settings($UserID, $Settings) { + if (!is_array($Settings)) { + // A little cheat technique, gets all keys in the $_POST array starting with 'notifications_' + $Settings = array_intersect_key($_POST, array_flip(preg_grep('/^notifications_/', array_keys($_POST)))); + } + $Update = array(); + $Types = self::$Types; + foreach ($Types as $Type) { + $Popup = array_key_exists("notifications_$Type" . '_popup', $Settings); + $Traditional = array_key_exists("notifications_$Type" . '_traditional', $Settings); + $Result = 0; + if ($Popup) { + $Result = 1; + } elseif ($Traditional) { + $Result = 2; + } + $Update[] = "$Type = $Result"; + } + $Update = implode(',', $Update); + + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" + UPDATE users_notifications_settings + SET $Update + WHERE UserID = '$UserID'"); + G::$DB->set_query_id($QueryID); + G::$Cache->delete_value("users_notifications_settings_$UserID"); + } + + public function is_traditional($Type) { + return $this->Settings[$Type] == 2; + } +} diff --git a/classes/notificationsmanagerview.class.php b/classes/notificationsmanagerview.class.php new file mode 100644 index 00000000..6e1609f0 --- /dev/null +++ b/classes/notificationsmanagerview.class.php @@ -0,0 +1,151 @@ + + + + + + + + + News announcements + + + + + + + + Blog announcements + + + + + + + + Inbox messages + + + + + + + + Staff messages + + + + + + + + Thread subscriptions + + + + + + + + Quote notifications + + + + + + + + + Torrent notifications + + + + + + + + + Collage subscriptions + + + + + + + + Site alerts + + + + + + + + Forum alerts + + + + + + + + Request alerts + + + + + + + + Collage alerts + + + + + + + + Torrent alerts + + + + + + + /> + + + name="notifications__popup" id="notifications__popup" /> + +' . $Contents['message'] . ''; + } +} diff --git a/classes/paranoia.class.php b/classes/paranoia.class.php index fdfa1ea5..ed575583 100644 --- a/classes/paranoia.class.php +++ b/classes/paranoia.class.php @@ -46,7 +46,7 @@ define("PARANOIA_OVERRIDDEN", 2); function check_paranoia($Property, $Paranoia, $UserClass, $UserID = false) { - global $LoggedUser, $Classes; + global $Classes; if ($Property == false) { return false; } @@ -63,7 +63,7 @@ function check_paranoia($Property, $Paranoia, $UserClass, $UserID = false) { } return $all; } else { - if (($UserID !== false) && ($LoggedUser['ID'] == $UserID)) { + if (($UserID !== false) && (G::$LoggedUser['ID'] == $UserID)) { return PARANOIA_ALLOWED; } diff --git a/classes/permissions.class.php b/classes/permissions.class.php index 3d312a47..d1b00893 100644 --- a/classes/permissions.class.php +++ b/classes/permissions.class.php @@ -7,12 +7,11 @@ class Permissions { * @param string $MinClass Return false if the user's class level is below this. */ public static function check_perms($PermissionName, $MinClass = 0) { - global $LoggedUser; return ( - isset($LoggedUser['Permissions'][$PermissionName]) - && $LoggedUser['Permissions'][$PermissionName] - && ($LoggedUser['Class'] >= $MinClass - || $LoggedUser['EffectiveClass'] >= $MinClass) + isset(G::$LoggedUser['Permissions'][$PermissionName]) + && G::$LoggedUser['Permissions'][$PermissionName] + && (G::$LoggedUser['Class'] >= $MinClass + || G::$LoggedUser['EffectiveClass'] >= $MinClass) ) ? true : false; } @@ -23,16 +22,17 @@ public static function check_perms($PermissionName, $MinClass = 0) { * @return array permissions */ public static function get_permissions($PermissionID) { - global $DB, $Cache; - $Permission = $Cache->get_value('perm_'.$PermissionID); + $Permission = G::$Cache->get_value('perm_'.$PermissionID); if (empty($Permission)) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT p.Level AS Class, p.Values as Permissions, p.Secondary, p.PermittedForums FROM permissions AS p WHERE ID='$PermissionID'"); - $Permission = $DB->next_record(MYSQLI_ASSOC, array('Permissions')); + $Permission = G::$DB->next_record(MYSQLI_ASSOC, array('Permissions')); + G::$DB->set_query_id($QueryID); $Permission['Permissions'] = unserialize($Permission['Permissions']); - $Cache->cache_value('perm_'.$PermissionID, $Permission, 2592000); + G::$Cache->cache_value('perm_'.$PermissionID, $Permission, 2592000); } return $Permission; } @@ -47,17 +47,18 @@ public static function get_permissions($PermissionID) { * @return array Mapping of PermissionName=>bool/int */ public static function get_permissions_for_user($UserID, $CustomPermissions = false) { - global $DB; $UserInfo = Users::user_info($UserID); // Fetch custom permissions if they weren't passed in. if ($CustomPermissions === false) { - $DB->query(' + $QueryID = G::$DB->get_query_id(); + G::$DB->query(' SELECT um.CustomPermissions FROM users_main AS um WHERE um.ID = '.((int)$UserID)); - list($CustomPermissions) = $DB->next_record(MYSQLI_NUM, false); + list($CustomPermissions) = G::$DB->next_record(MYSQLI_NUM, false); + G::$DB->set_query_id($QueryID); } if (!empty($CustomPermissions) && !is_array($CustomPermissions)) { @@ -89,10 +90,12 @@ public static function get_permissions_for_user($UserID, $CustomPermissions = fa $DonorPerms = array('Permissions' => array()); } + $DonorCollages = self::get_personal_collages($UserID, $Permissions['Permissions']['users_mod']); + $MaxCollages = $Permissions['Permissions']['MaxCollages'] + $BonusCollages + $CustomPerms['MaxCollages'] - + $DonorPerms['Permissions']['MaxCollages']; + + $DonorCollages; //Combine the permissions return array_merge( @@ -102,5 +105,39 @@ public static function get_permissions_for_user($UserID, $CustomPermissions = fa $DonorPerms['Permissions'], array('MaxCollages' => $MaxCollages)); } + + private static function get_personal_collages($UserID, $HasAll) { + $QueryID = G::$DB->get_query_id(); + if (!$HasAll) { + $SpecialRank = G::$Cache->get_value("donor_special_rank_$UserID"); + if ($SpecialRank === false) { + G::$DB->query("SELECT SpecialRank FROM users_donor_ranks WHERE UserID = '$UserID'"); + list($SpecialRank) = G::$DB->next_record(); + $HasAll = $SpecialRank == MAX_SPECIAL_RANK ? true : false; + G::$Cache->cache_value("donor_special_rank_$UserID", $SpecialRank, 0); + } + } else { + G::$Cache->cache_value("donor_special_rank_$UserID", MAX_SPECIAL_RANK, 0); + } + + if ($HasAll) { + $Collages = 5; + } else { + $Collages = 0; + $Rank = G::$Cache->get_value("donor_rank_$UserID"); + if ($Rank === false) { + G::$DB->query("SELECT Rank FROM users_donor_ranks WHERE UserID = '$UserID'"); + list($Rank) = G::$DB->next_record(); + G::$Cache->cache_value("donor_rank_$UserID", $Rank, 0); + } + + $Rank = min($Rank, 5); + for ($i = 1; $i <= $Rank; $i++) { + $Collages++; + } + } + G::$DB->set_query_id($QueryID); + return $Collages; + } } ?> diff --git a/classes/permissions_form.php b/classes/permissions_form.php index d401f8be..440ecb32 100644 --- a/classes/permissions_form.php +++ b/classes/permissions_form.php @@ -229,7 +229,6 @@ function permissions_form() { ?> - diff --git a/classes/requests.class.php b/classes/requests.class.php index 08c96084..a337e103 100644 --- a/classes/requests.class.php +++ b/classes/requests.class.php @@ -6,9 +6,8 @@ class Requests { * @param $RequestID */ public static function update_sphinx_requests($RequestID) { - global $DB, $Cache; - - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" REPLACE INTO sphinx_requests_delta ( ID, UserID, TimeAdded, LastVote, CategoryID, Title, Year, ReleaseType, CatalogueNumber, BitrateList, @@ -25,8 +24,7 @@ public static function update_sphinx_requests($RequestID) { LEFT JOIN requests_votes AS rv ON rv.RequestID = r.ID WHERE ID = $RequestID GROUP BY r.ID"); - - $DB->query(" + G::$DB->query(" UPDATE sphinx_requests_delta SET ArtistList = ( SELECT GROUP_CONCAT(aa.Name SEPARATOR ' ') @@ -36,8 +34,9 @@ public static function update_sphinx_requests($RequestID) { GROUP BY NULL ) WHERE ID = $RequestID"); + G::$DB->set_query_id($QueryID); - $Cache->delete_value("requests_$RequestID"); + G::$Cache->delete_value("requests_$RequestID"); } @@ -55,14 +54,13 @@ public static function update_sphinx_requests($RequestID) { // //In places where the output from this is merged with sphinx filters, it will be in a different order. public static function get_requests($RequestIDs, $Return = true) { - global $DB, $Cache; // Try to fetch the requests from the cache first. $Found = array_flip($RequestIDs); $NotFound = array_flip($RequestIDs); foreach ($RequestIDs as $RequestID) { - $Data = $Cache->get_value("request_$RequestID"); + $Data = G::$Cache->get_value("request_$RequestID"); if (!empty($Data)) { unset($NotFound[$RequestID]); $Found[$RequestID] = $Data; @@ -76,7 +74,9 @@ public static function get_requests($RequestIDs, $Return = true) { */ if (count($NotFound) > 0) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + + G::$DB->query(" SELECT r.ID AS ID, r.UserID, @@ -106,13 +106,14 @@ public static function get_requests($RequestIDs, $Return = true) { LEFT JOIN users_main AS filler ON filler.ID = FillerID AND FillerID != 0 WHERE r.ID IN ($IDs) ORDER BY ID"); + $Requests = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); - $Requests = $DB->to_array(); foreach ($Requests as $Request) { unset($NotFound[$Request['ID']]); $Request['Tags'] = self::get_tags($Request['ID']); $Found[$Request['ID']] = $Request; - $Cache->cache_value('request_'.$Request['ID'], $Request, 0); + G::$Cache->cache_value('request_'.$Request['ID'], $Request, 0); } } @@ -122,53 +123,14 @@ public static function get_requests($RequestIDs, $Return = true) { } } - public static function get_comment_count($RequestID) { - global $Cache, $DB; - $NumComments = $Cache->get_value("request_comments_$RequestID"); - if ($NumComments === false) { - $DB->query(" - SELECT COUNT(ID) - FROM requests_comments - WHERE RequestID = '$RequestID'"); - list($NumComments) = $DB->next_record(); - $Cache->cache_value("request_comments_$RequestID", $NumComments, 0); - } - return $NumComments; - } - - public static function get_comment_catalogue($RequestID, $CatalogueID) { - global $Cache, $DB; - $Catalogue = $Cache->get_value("request_comments_$RequestID"."_catalogue_$CatalogueID"); - if ($Catalogue === false) { - $CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - $DB->query(" - SELECT - c.ID, - c.AuthorID, - c.AddedTime, - c.Body, - c.EditedUserID, - c.EditedTime, - u.Username - FROM requests_comments as c - LEFT JOIN users_main AS u ON u.ID = c.EditedUserID - WHERE c.RequestID = '$RequestID' - ORDER BY c.ID - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false, MYSQLI_ASSOC); - $Cache->cache_value("request_comments_$RequestID"."_catalogue_$CatalogueID", $Catalogue, 0); - } - return $Catalogue; - } - public static function get_artists($RequestID) { - global $Cache, $DB; - $Artists = $Cache->get_value("request_artists_$RequestID"); + $Artists = G::$Cache->get_value("request_artists_$RequestID"); if (is_array($Artists)) { $Results = $Artists; } else { $Results = array(); - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT ra.ArtistID, aa.Name, @@ -177,20 +139,20 @@ public static function get_artists($RequestID) { JOIN artists_alias AS aa ON ra.AliasID = aa.AliasID WHERE ra.RequestID = $RequestID ORDER BY ra.Importance ASC, aa.Name ASC;"); - - $ArtistRaw = $DB->to_array(); + $ArtistRaw = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); foreach ($ArtistRaw as $ArtistRow) { list($ArtistID, $ArtistName, $ArtistImportance) = $ArtistRow; $Results[$ArtistImportance][] = array('id' => $ArtistID, 'name' => $ArtistName); } - $Cache->cache_value("request_artists_$RequestID", $Results); + G::$Cache->cache_value("request_artists_$RequestID", $Results); } return $Results; } public static function get_tags($RequestID) { - global $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT rt.TagID, t.Name @@ -198,7 +160,8 @@ public static function get_tags($RequestID) { JOIN tags AS t ON rt.TagID = t.ID WHERE rt.RequestID = $RequestID ORDER BY rt.TagID ASC"); - $Tags = $DB->to_array(); + $Tags = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); $Results = array(); foreach ($Tags as $TagsRow) { list($TagID, $TagName) = $TagsRow; @@ -208,11 +171,11 @@ public static function get_tags($RequestID) { } public static function get_votes_array($RequestID) { - global $Cache, $DB; - $RequestVotes = $Cache->get_value("request_votes_$RequestID"); + $RequestVotes = G::$Cache->get_value("request_votes_$RequestID"); if (!is_array($RequestVotes)) { - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT rv.UserID, rv.Bounty, @@ -221,13 +184,13 @@ public static function get_votes_array($RequestID) { LEFT JOIN users_main AS u ON u.ID = rv.UserID WHERE rv.RequestID = $RequestID ORDER BY rv.Bounty DESC"); - if (!$DB->has_results()) { + if (!G::$DB->has_results()) { error(0); } else { - $Votes = $DB->to_array(); + $Votes = G::$DB->to_array(); $RequestVotes = array(); - $RequestVotes['TotalBounty'] = array_sum($DB->collect('Bounty')); + $RequestVotes['TotalBounty'] = array_sum(G::$DB->collect('Bounty')); foreach ($Votes as $Vote) { list($UserID, $Bounty, $Username) = $Vote; @@ -236,8 +199,9 @@ public static function get_votes_array($RequestID) { } $RequestVotes['Voters'] = $VotesArray; - $Cache->cache_value("request_votes_$RequestID", $RequestVotes); + G::$Cache->cache_value("request_votes_$RequestID", $RequestVotes); } + G::$DB->set_query_id($QueryID); } return $RequestVotes; } diff --git a/classes/script_start.php b/classes/script_start.php index c17a74c4..aac8ec0d 100644 --- a/classes/script_start.php +++ b/classes/script_start.php @@ -81,6 +81,10 @@ // Autoload classes. require(SERVER_ROOT.'/classes/classloader.php'); +// Note: G::initialize is called twice. +// This is necessary as the code inbetween (initialization of $LoggedUser) makes use of G::$DB and G::$Cache. +// TODO: remove one of the calls once we're moving everything into that class +G::initialize(); //Begin browser identification @@ -310,24 +314,24 @@ * Log out the current session */ function logout() { - global $SessionID, $LoggedUser, $DB, $Cache; + global $SessionID; setcookie('session', '', time() - 60 * 60 * 24 * 365, '/', '', false); setcookie('keeplogged', '', time() - 60 * 60 * 24 * 365, '/', '', false); setcookie('session', '', time() - 60 * 60 * 24 * 365, '/', '', false); if ($SessionID) { - $DB->query(" + G::$DB->query(" DELETE FROM users_sessions - WHERE UserID = '$LoggedUser[ID]' + WHERE UserID = '" . G::$LoggedUser['ID'] . "' AND SessionID = '".db_string($SessionID)."'"); - $Cache->begin_transaction('users_sessions_'.$LoggedUser['ID']); - $Cache->delete_row($SessionID); - $Cache->commit_transaction(0); + G::$Cache->begin_transaction('users_sessions_' . G::$LoggedUser['ID']); + G::$Cache->delete_row($SessionID); + G::$Cache->commit_transaction(0); } - $Cache->delete_value('user_info_'.$LoggedUser['ID']); - $Cache->delete_value('user_stats_'.$LoggedUser['ID']); - $Cache->delete_value('user_info_heavy_'.$LoggedUser['ID']); + G::$Cache->delete_value('user_info_' . G::$LoggedUser['ID']); + G::$Cache->delete_value('user_stats_' . G::$LoggedUser['ID']); + G::$Cache->delete_value('user_info_heavy_' . G::$LoggedUser['ID']); header('Location: login.php'); @@ -335,8 +339,8 @@ function logout() { } function enforce_login() { - global $SessionID, $LoggedUser; - if (!$SessionID || !$LoggedUser) { + global $SessionID; + if (!$SessionID || !G::$LoggedUser) { setcookie('redirect', $_SERVER['REQUEST_URI'], time() + 60 * 30, '/', '', false); logout(); } @@ -350,9 +354,8 @@ function enforce_login() { * @return authorisation status. Prints an error message to LAB_CHAN on IRC on failure. */ function authorize($Ajax = false) { - global $LoggedUser; - if (empty($_REQUEST['auth']) || $_REQUEST['auth'] != $LoggedUser['AuthKey']) { - send_irc("PRIVMSG ".LAB_CHAN." :".$LoggedUser['Username']." just failed authorize on ".$_SERVER['REQUEST_URI']." coming from ".$_SERVER['HTTP_REFERER']); + if (empty($_REQUEST['auth']) || $_REQUEST['auth'] != G::$LoggedUser['AuthKey']) { + send_irc("PRIVMSG ".LAB_CHAN." :".G::$LoggedUser['Username']." just failed authorize on ".$_SERVER['REQUEST_URI']." coming from ".$_SERVER['HTTP_REFERER']); error('Invalid authorization key. Go back, refresh, and try again.', $Ajax); return false; } diff --git a/classes/search.class.php b/classes/search.class.php index 939e3dfd..723ccfa5 100644 --- a/classes/search.class.php +++ b/classes/search.class.php @@ -45,7 +45,6 @@ function SPHINX_SEARCH() { ****************************************************************/ function search($Query = '', $CachePrefix = '', $CacheLength = 0, $ReturnData = array(), $SQL = '', $IDColumn = 'ID') { - global $Cache, $DB; $QueryStartTime = microtime(true); $Result = $this->Query($Query, $this->Index); $QueryEndTime = microtime(true); @@ -61,9 +60,9 @@ function search($Query = '', $CachePrefix = '', $CacheLength = 0, $ReturnData = $this->Time += ($QueryEndTime - $QueryStartTime) * 1000; if ($Result === false) { - if ($this->_connerror && !$Cache->get_value('sphinx_crash_reported')) { + if ($this->_connerror && !G::$Cache->get_value('sphinx_crash_reported')) { send_irc('PRIVMSG '.ADMIN_CHAN.' :!dev Connection to searchd failed'); - $Cache->cache_value('sphinx_crash_reported', 1, 3600); + G::$Cache->cache_value('sphinx_crash_reported', 1, 3600); } send_irc('PRIVMSG '.LAB_CHAN." :Search for \"$Query\" (".str_replace("\n", '', print_r($this->Filters, true)).') failed: '.$this->GetLastError()); } @@ -89,7 +88,7 @@ function search($Query = '', $CachePrefix = '', $CacheLength = 0, $ReturnData = foreach ($MatchIDs as $Match) { $Matches[$Match] = $Matches[$Match]['attrs']; if (!empty($CachePrefix)) { - $Data = $Cache->get_value($CachePrefix."_$Match"); + $Data = G::$Cache->get_value($CachePrefix."_$Match"); if ($Data == false) { $NotFound[] = $Match; continue; @@ -121,11 +120,13 @@ function search($Query = '', $CachePrefix = '', $CacheLength = 0, $ReturnData = if ($SQL != '') { if (!empty($NotFound)) { - $DB->query(str_replace('%ids', implode(',', $NotFound), $SQL)); - while ($Data = $DB->next_record(MYSQLI_ASSOC)) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query(str_replace('%ids', implode(',', $NotFound), $SQL)); + while ($Data = G::$DB->next_record(MYSQLI_ASSOC)) { $Matches[$Data[$IDColumn]] = array_merge($Matches[$Data[$IDColumn]], $Data); - $Cache->cache_value($CachePrefix.'_'.$Data[$IDColumn], $Data, $CacheLength); + G::$Cache->cache_value($CachePrefix.'_'.$Data[$IDColumn], $Data, $CacheLength); } + G::$DB->set_query_id($QueryID); } } else { $Matches = array('matches' => $Matches, 'notfound' => $NotFound); diff --git a/classes/sitehistory.class.php b/classes/sitehistory.class.php index da229c12..1f4f23ff 100644 --- a/classes/sitehistory.class.php +++ b/classes/sitehistory.class.php @@ -67,12 +67,14 @@ class SiteHistory { public static function get_months() { $Results = G::$Cache->get_value("site_history_months"); if (!$Results) { + $QueryID = G::$DB->get_query_id(); G::$DB->query(" SELECT DISTINCT YEAR(DATE) AS Year, MONTH(Date) AS Month, MONTHNAME(Date) AS MonthName FROM site_history ORDER BY Date DESC"); $Results = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); G::$Cache->cache_value("site_history_months", $Results, 0); } return $Results; @@ -80,13 +82,16 @@ public static function get_months() { public static function get_event($ID) { if (!empty($ID)) { + $QueryID = G::$DB->get_query_id(); G::$DB->query(" - SELECT - ID, Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date - FROM site_history - WHERE ID = '$ID' - ORDER BY Date DESC"); - return G::$DB->next_record(); + SELECT + ID, Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date + FROM site_history + WHERE ID = '$ID' + ORDER BY Date DESC"); + $Event = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + return $Event; } } @@ -95,13 +100,13 @@ public static function get_latest_events($Limit) { } public static function get_events($Month, $Year, $Title, $Category, $SubCategory, $Tags, $Limit) { - $Month = (int) $Month; - $Year = (int) $Year; + $Month = (int)$Month; + $Year = (int)$Year; $Title = db_string($Title); - $Category = (int) $Category; - $SubCategory = (int) $SubCategory; + $Category = (int)$Category; + $SubCategory = (int)$SubCategory; $Tags = db_string($Tags); - $Limit = (int) $Limit; + $Limit = (int)$Limit; $Where = array(); if (!empty($Month)) { $Where[] = " MONTH(Date) = '$Month' "; @@ -119,37 +124,40 @@ public static function get_events($Month, $Year, $Title, $Category, $SubCategory $Where[] = " SubCategory = '$SubCategory '"; } if (!empty($Tags)) { - $Tags = explode(",", $Tags); - $Or = "("; - foreach($Tags as $Tag) { + $Tags = explode(',', $Tags); + $Or = '('; + foreach ($Tags as $Tag) { $Tag = trim($Tag); $Or .= " Tags LIKE '%$Tag%' OR "; } if (strlen($Or) > 1) { - $Or = rtrim($Or, "OR "); - $Or .= ")"; + $Or = rtrim($Or, 'OR '); + $Or .= ')'; $Where[] = $Or; } } if (!empty($Limit)) { $Limit = " LIMIT $Limit"; } else { - $Limit = ""; + $Limit = ''; } if (count($Where) > 0) { - $Query = " WHERE " . implode("AND", $Where); + $Query = ' WHERE ' . implode('AND', $Where); } else { - $Query = ""; + $Query = ''; } + $QueryID = G::$DB->get_query_id(); G::$DB->query(" - SELECT - ID, Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date - FROM site_history - $Query - ORDER BY Date DESC - $Limit"); - return G::$DB->to_array(); + SELECT + ID, Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date + FROM site_history + $Query + ORDER BY Date DESC + $Limit"); + $Events = G::$DB->to_array(); + G::$DB->set_query_id($QueryID); + return $Events; } public static function add_event($Date, $Title, $Link, $Category, $SubCategory, $Tags, $Body, $UserID) { @@ -163,27 +171,29 @@ public static function add_event($Date, $Title, $Link, $Category, $SubCategory, } $Title = db_string($Title); $Link = db_string($Link); - $Category = (int) $Category; - $SubCategory = (int) $SubCategory; + $Category = (int)$Category; + $SubCategory = (int)$SubCategory; $Tags = db_string(strtolower((preg_replace('/\s+/', '', $Tags)))); - $ExplodedTags = explode(",", $Tags); - foreach($ExplodedTags as $Tag) { + $ExplodedTags = explode(',', $Tags); + foreach ($ExplodedTags as $Tag) { if (!in_array($Tag, self::get_tags())) { error("Invalid tag"); } } $Body = db_string($Body); - $UserID = (int) $UserID; + $UserID = (int)$UserID; if (empty($Title) || empty($Category) || empty($SubCategory)) { error("Error"); } + $QueryID = G::$DB->get_query_id(); G::$DB->query(" - INSERT INTO site_history - (Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date) - VALUES - ('$Title', '$Link', '$Category', '$SubCategory', '$Tags', '$Body', '$UserID', '$Date')"); + INSERT INTO site_history + (Title, Url, Category, SubCategory, Tags, Body, AddedBy, Date) + VALUES + ('$Title', '$Link', '$Category', '$SubCategory', '$Tags', '$Body', '$UserID', '$Date')"); + G::$DB->set_query_id($QueryID); G::$Cache->delete_value("site_history_months"); } @@ -197,14 +207,14 @@ public static function update_event($ID, $Date, $Title, $Link, $Category, $SubCa error("Error"); } } - $ID = (int) $ID; + $ID = (int)$ID; $Title = db_string($Title); $Link = db_string($Link); - $Category = (int) $Category; - $SubCategory = (int) $SubCategory; + $Category = (int)$Category; + $SubCategory = (int)$SubCategory; $Tags = db_string(strtolower((preg_replace('/\s+/', '', $Tags)))); $ExplodedTags = explode(",", $Tags); - foreach($ExplodedTags as $Tag) { + foreach ($ExplodedTags as $Tag) { if (!in_array($Tag, self::get_tags())) { error("Invalid tag"); } @@ -216,6 +226,7 @@ public static function update_event($ID, $Date, $Title, $Link, $Category, $SubCa error("Error"); } + $QueryID = G::$DB->get_query_id(); G::$DB->query(" UPDATE site_history SET @@ -229,6 +240,7 @@ public static function update_event($ID, $Date, $Title, $Link, $Category, $SubCa Date = '$Date' WHERE ID = '$ID'"); + G::$DB->set_query_id($QueryID); G::$Cache->delete_value("site_history_months"); } @@ -236,7 +248,9 @@ public static function delete_event($ID) { if (empty($ID)) { error(404); } + $QueryID = G::$DB->get_query_id(); G::$DB->query("DELETE FROM site_history WHERE ID = '$ID'"); + G::$DB->set_query_id($QueryID); G::$Cache->delete_value("site_history_months"); } @@ -251,4 +265,4 @@ public static function get_sub_categories() { public static function get_tags() { return self::$Tags; } -} \ No newline at end of file +} diff --git a/classes/sitehistoryview.class.php b/classes/sitehistoryview.class.php index 8f937eda..2daff6eb 100644 --- a/classes/sitehistoryview.class.php +++ b/classes/sitehistoryview.class.php @@ -16,7 +16,7 @@ public static function render_events($Events) { $Categories = SiteHistory::get_categories(); $SubCategories = SiteHistory::get_sub_categories(); $CanEdit = check_perms('users_mod') ; - foreach($Events as $Event) { ?> + foreach ($Events as $Event) { ?>
    @@ -51,8 +51,8 @@ public static function render_events($Events) { private static function render_tags($Tags) { $Tags = explode(',', $Tags); natcasesort($Tags); - $FormattedTags = ""; - foreach($Tags as $Tag) { + $FormattedTags = ''; + foreach ($Tags as $Tag) { $FormattedTags .= "" . $Tag . ", "; } echo rtrim($FormattedTags, ', '); @@ -87,7 +87,7 @@ public static function render_search() { ?> @@ -95,7 +95,7 @@ public static function render_search() { ?> @@ -143,7 +143,7 @@ public static function render_edit_form($Event) { ?> @@ -155,7 +155,7 @@ public static function render_edit_form($Event) { ?> @@ -168,7 +168,7 @@ public static function render_edit_form($Event) { ?> @@ -207,4 +207,4 @@ public static function render_recent_sidebar($Events) { ?>
    get_query_id(); + /* + * Explanation of the parameters PageID and Page: Page contains where + * this quote comes from and can be forums, artist, collages, requests + * or torrents. The PageID contains the additional value that is + * necessary for the users_notify_quoted table. The PageIDs for the + * different Page are: forums: TopicID artist: ArtistID collages: + * CollageID requests: RequestID torrents: GroupID + */ + $Matches = array(); + preg_match_all('/\[quote(?:=(.*)(?:\|.*)?)?]|\[\/quote]/iU', $Body, $Matches, PREG_SET_ORDER); + + if (count($Matches)) { + $Usernames = array(); + $Level = 0; + foreach ($Matches as $M) { + if ($M[0] != '[/quote]') { + if ($Level == 0 && isset($M[1]) && strlen($M[1]) > 0 && preg_match(USERNAME_REGEX, $M[1])) { + $Usernames[] = preg_replace('/(^[.,]*)|([.,]*$)/', '', $M[1]); // wut? + } + ++$Level; + } else { + --$Level; + } + } + } + // remove any dupes in the array (the fast way) + $Usernames = array_flip(array_flip($Usernames)); + + + G::$DB->query(" + SELECT m.ID + FROM users_main AS m + LEFT JOIN users_info AS i ON i.UserID = m.ID + WHERE m.Username IN ('" . implode("', '", $Usernames) . "') + AND i.NotifyOnQuote = '1' + AND i.UserID != " . G::$LoggedUser['ID']); + + + $Results = G::$DB->to_array(); + foreach ($Results as $Result) { + $UserID = db_string($Result['ID']); + $QuoterID = db_string(G::$LoggedUser['ID']); + $Page = db_string($Page); + $PageID = db_string($PageID); + $PostID = db_string($PostID); + + G::$DB->query(" + INSERT IGNORE INTO users_notify_quoted + (UserID, QuoterID, Page, PageID, PostID, Date) + VALUES + ('$UserID', '$QuoterID', '$Page', '$PageID', '$PostID', '" . sqltime() . "')"); + G::$Cache->delete_value('notify_quoted_' . $UserID); + + } + G::$DB->set_query_id($QueryID); + } + + /** + * (Un)subscribe from a forum thread. + * If UserID == 0, G::$LoggedUser[ID] is used + * @param int $TopicID + * @param int $UserID + */ + public static function subscribe($TopicID, $UserID = 0) { + if ($UserID == 0) { + $UserID = G::$LoggedUser['ID']; + } + $QueryID = G::$DB->get_query_id(); + $UserSubscriptions = self::get_subscriptions(); + $Key = self::has_subscribed($TopicID); + if ($Key !== false) { + G::$DB->query('DELETE FROM users_subscriptions WHERE UserID = ' . db_string($UserID) . ' AND TopicID = ' . db_string($TopicID)); + unset($UserSubscriptions[$Key]); + } else { + G::$DB->query("INSERT IGNORE INTO users_subscriptions (UserID, TopicID) VALUES ($UserID, " . db_string($TopicID) . ")"); + array_push($UserSubscriptions, $TopicID); + } + G::$Cache->replace_value('subscriptions_user_' . $UserID, $UserSubscriptions, 0); + G::$Cache->delete_value('subscriptions_user_new_' . $UserID); + G::$DB->set_query_id($QueryID); + } + + /** + * (Un)subscribe from comments. + * If UserID == 0, G::$LoggedUser[ID] is used + * @param string $Page 'artist', 'collages', 'requests' or 'torrents' + * @param int $PageID ArtistID, CollageID, RequestID or GroupID + * @param int $UserID + */ + public static function subscribe_comments($Page, $PageID, $UserID = 0) { + if ($UserID == 0) { + $UserID = G::$LoggedUser['ID']; + } + $QueryID = G::$DB->get_query_id(); + $UserCommentSubscriptions = self::get_comment_subscriptions(); + $Key = self::has_subscribed_comments($Page, $PageID); + if ($Key !== false) { + G::$DB->query("DELETE FROM users_subscriptions_comments WHERE UserID = " . db_string($UserID) . " AND Page = '" . db_string($Page) . "' AND PageID = " . db_string($PageID)); + unset($UserCommentSubscriptions[$Key]); + } else { + G::$DB->query("INSERT IGNORE INTO users_subscriptions_comments (UserID, Page, PageID) VALUES ($UserID, '" . db_string($Page) . "', " . db_string($PageID) . ")"); + array_push($UserCommentSubscriptions, array($Page, $PageID)); + } + G::$Cache->replace_value('subscriptions_comments_user_' . $UserID, $UserCommentSubscriptions, 0); + G::$Cache->delete_value('subscriptions_comments_user_new_' . $UserID); + G::$DB->set_query_id($QueryID); + } + + /** + * Read $UserID's subscriptions. If the cache key isn't set, it gets filled. + * If UserID == 0, G::$LoggedUser[ID] is used + * @param int $UserID + * @return array Array of TopicIDs + */ + public static function get_subscriptions($UserID = 0) { + if ($UserID == 0) { + $UserID = G::$LoggedUser['ID']; + } + $QueryID = G::$DB->get_query_id(); + $UserSubscriptions = G::$Cache->get_value('subscriptions_user_' . $UserID); + if ($UserSubscriptions === false) { + G::$DB->query('SELECT TopicID FROM users_subscriptions WHERE UserID = ' . db_string($UserID)); + $UserSubscriptions = G::$DB->collect(0); + G::$Cache->cache_value('subscriptions_user_' . $UserID, $UserSubscriptions, 0); + } + G::$DB->set_query_id($QueryID); + return $UserSubscriptions; + } + + /** + * Same as self::get_subscriptions, but for comment subscriptions + * @param int $UserID + * @return array Array of ($Page, $PageID) + */ + public static function get_comment_subscriptions($UserID = 0) { + if ($UserID == 0) { + $UserID = G::$LoggedUser['ID']; + } + $QueryID = G::$DB->get_query_id(); + $UserCommentSubscriptions = G::$Cache->get_value('subscriptions_comments_user_' . $UserID); + if ($UserCommentSubscriptions === false) { + G::$DB->query('SELECT Page, PageID FROM users_subscriptions_comments WHERE UserID = ' . db_string($UserID)); + $UserCommentSubscriptions = G::$DB->to_array(false, MYSQLI_NUM); + G::$Cache->cache_value('subscriptions_comments_user_' . $UserID, $UserCommentSubscriptions, 0); + } + G::$DB->set_query_id($QueryID); + return $UserCommentSubscriptions; + } + + /** + * Returns whether or not the current user has new subscriptions. This handles both forum and comment subscriptions. + * @return int Number of unread subscribed threads/comments + */ + public static function has_new_subscriptions() { + $QueryID = G::$DB->get_query_id(); + + $NewSubscriptions = G::$Cache->get_value('subscriptions_user_new_' . G::$LoggedUser['ID']); + if ($NewSubscriptions === false) { + // forum subscriptions + G::$DB->query("SELECT COUNT(1) + FROM users_subscriptions AS s + LEFT JOIN forums_last_read_topics AS l ON l.UserID = s.UserID AND l.TopicID = s.TopicID + JOIN forums_topics AS t ON t.ID = s.TopicID + JOIN forums AS f ON f.ID = t.ForumID + WHERE " . Forums::user_forums_sql() . " + AND IF(t.IsLocked = '1' AND t.IsSticky = '0'" . ", t.LastPostID, IF(l.PostID IS NULL, 0, l.PostID)) < t.LastPostID + AND s.UserID = " . G::$LoggedUser['ID']); + list($NewForumSubscriptions) = G::$DB->next_record(); + + // comment subscriptions + G::$DB->query("SELECT COUNT(1) + FROM users_subscriptions_comments AS s + LEFT JOIN users_comments_last_read AS lr ON lr.UserID = s.UserID AND lr.Page = s.Page AND lr.PageID = s.PageID + LEFT JOIN comments AS c ON c.ID = (SELECT MAX(ID) FROM comments WHERE Page = s.Page AND PageID = s.PageID) + LEFT JOIN collages AS co ON s.Page = 'collages' AND co.ID = s.PageID + WHERE s.UserID = " . G::$LoggedUser['ID'] . " + AND (s.Page != 'collages' OR co.Deleted = '0') + AND IF(lr.PostID IS NULL, 0, lr.PostID) < c.ID"); + list($NewCommentSubscriptions) = G::$DB->next_record(); + + $NewSubscriptions = $NewForumSubscriptions + $NewCommentSubscriptions; + G::$Cache->cache_value('subscriptions_user_new_' . G::$LoggedUser['ID'], $NewSubscriptions, 0); + } + G::$DB->set_query_id($QueryID); + return (int)$NewSubscriptions; + } + + /** + * Returns whether or not the current user has new quote notifications. + * @return int Number of unread quote notifications + */ + public static function has_new_quote_notifications() { + $QuoteNotificationsCount = G::$Cache->get_value('notify_quoted_' . G::$LoggedUser['ID']); + if ($QuoteNotificationsCount === false) { + $sql = " + SELECT COUNT(1) + FROM users_notify_quoted AS q + LEFT JOIN forums_topics AS t ON t.ID = q.PageID + LEFT JOIN forums AS f ON f.ID = t.ForumID + LEFT JOIN collages AS c ON q.Page = 'collages' AND c.ID = q.PageID + WHERE q.UserID = " . G::$LoggedUser['ID'] . " + AND q.UnRead + AND (q.Page != 'forums' OR " . Forums::user_forums_sql() . ") + AND (q.Page != 'collages' OR c.Deleted = '0')"; + $QueryID = G::$DB->get_query_id(); + G::$DB->query($sql); + list($QuoteNotificationsCount) = G::$DB->next_record(); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('notify_quoted_' . G::$LoggedUser['ID'], $QuoteNotificationsCount, 0); + } + return (int)$QuoteNotificationsCount; + } + + /** + * Returns the key which holds this $TopicID in the subscription array. + * Use type-aware comparison operators with this! (ie. if (self::has_subscribed($TopicID) !== false) { ... }) + * @param int $TopicID + * @return bool|int + */ + public static function has_subscribed($TopicID) { + $UserSubscriptions = self::get_subscriptions(); + return array_search($TopicID, $UserSubscriptions); + } + + /** + * Same as has_subscribed, but for comment subscriptions. + * @param string $Page 'artist', 'collages', 'requests' or 'torrents' + * @param int $PageID + * @return bool|int + */ + public static function has_subscribed_comments($Page, $PageID) { + $UserCommentSubscriptions = self::get_comment_subscriptions(); + return array_search(array($Page, $PageID), $UserCommentSubscriptions); + } + + /** + * Clear the subscription cache for all subscribers of a forum thread or artist/collage/request/torrent comments. + * @param type $Page 'forums', 'artist', 'collages', 'requests' or 'torrents' + * @param type $PageID TopicID, ArtistID, CollageID, RequestID or GroupID, respectively + */ + public static function flush_subscriptions($Page, $PageID) { + $QueryID = G::$DB->get_query_id(); + if ($Page == 'forums') { + G::$DB->query("SELECT UserID FROM users_subscriptions WHERE TopicID = '$PageID'"); + } else { + G::$DB->query("SELECT UserID FROM users_subscriptions_comments WHERE Page = '$Page' AND PageID = '$PageID'"); + } + $Subscribers = G::$DB->collect('UserID'); + foreach($Subscribers as $Subscriber) { + G::$Cache->delete_value('subscriptions_user_new_'.$Subscriber); + } + G::$DB->set_query_id($QueryID); + } + + /** + * Move all $Page subscriptions from $OldPageID to $NewPageID (for example when merging torrent groups). + * Passing $NewPageID = null will delete the subscriptions. + * @param string $Page 'forums', 'artist', 'collages', 'requests' or 'torrents' + * @param int $OldPageID TopicID, ArtistID, CollageID, RequestID or GroupID, respectively + * @param int|null $NewPageID As $OldPageID, or null to delete the subscriptions + */ + public static function move_subscriptions($Page, $OldPageID, $NewPageID) { + self::flush_subscriptions($Page, $OldPageID); + $QueryID = G::$DB->get_query_id(); + if ($Page == 'forums') { + if ($NewPageID !== null) { + G::$DB->query("UPDATE IGNORE users_subscriptions SET TopicID = '$NewPageID' WHERE TopicID = '$OldPageID'"); + // explanation see below + G::$DB->query("UPDATE IGNORE forums_last_read_topics SET TopicID = $NewPageID WHERE TopicID = $OldPageID"); + G::$DB->query(" + SELECT UserID, MIN(PostID) + FROM forums_last_read_topics + WHERE TopicID IN ($OldPageID, $NewPageID) + GROUP BY UserID + HAVING COUNT(1) = 2"); + $Results = G::$DB->to_array(false, MYSQLI_NUM); + foreach ($Results as $Result) { + G::$DB->query("UPDATE forums_last_read_topics SET PostID = $Result[1] WHERE TopicID = $NewPageID AND UserID = $Result[0]"); + } + } + G::$DB->query("DELETE FROM users_subscriptions WHERE TopicID = '$OldPageID'"); + G::$DB->query("DELETE FROM forums_last_read_topics WHERE TopicID = $OldPageID"); + } else { + if($NewPageID !== null) { + G::$DB->query("UPDATE IGNORE users_subscriptions_comments SET PageID = '$NewPageID' WHERE Page = '$Page' AND PageID = '$OldPageID'"); + // last read handling + // 1) update all rows that have no key collisions (i.e. users that haven't previously read both pages or if there are only comments on one page) + G::$DB->query("UPDATE IGNORE users_comments_last_read SET PageID = '$NewPageID' WHERE Page = '$Page' AND PageID = $OldPageID"); + // 2) get all last read records with key collisions (i.e. there are records for one user for both PageIDs) + G::$DB->query(" + SELECT UserID, MIN(PostID) + FROM users_comments_last_read + WHERE Page = '$Page' + AND PageID IN ($OldPageID, $NewPageID) + GROUP BY UserID + HAVING COUNT(1) = 2"); + $Results = G::$DB->to_array(false, MYSQLI_NUM); + // 3) update rows for those people found in 2) to the earlier post + foreach ($Results as $Result) { + G::$DB->query("UPDATE users_comments_last_read SET PostID = $Result[1] WHERE Page = '$Page' AND PageID = $NewPageID AND UserID = $Result[0]"); + } + } + G::$DB->query("DELETE FROM users_subscriptions_comments WHERE Page = '$Page' AND PageID = '$OldPageID'"); + G::$DB->query("DELETE FROM users_comments_last_read WHERE Page = '$Page' AND PageID = '$OldPageID'"); + } + G::$DB->set_query_id($QueryID); + } + + /** + * Clear the quote notification cache for all subscribers of a forum thread or artist/collage/request/torrent comments. + * @param string $Page 'forums', 'artist', 'collages', 'requests' or 'torrents' + * @param int $PageID TopicID, ArtistID, CollageID, RequestID or GroupID, respectively + */ + public static function flush_quote_notifications($Page, $PageID) { + $QueryID = G::$DB->get_query_id(); + G::$DB->query("SELECT UserID FROM users_notify_quoted WHERE Page = '$Page' AND PageID = $PageID"); + $Subscribers = G::$DB->collect('UserID'); + foreach($Subscribers as $Subscriber) { + G::$Cache->delete_value('notify_quoted_'.$Subscriber); + } + G::$DB->set_query_id($QueryID); + } +} diff --git a/classes/text.class.php b/classes/text.class.php index 1b3550b7..316d0e2d 100644 --- a/classes/text.class.php +++ b/classes/text.class.php @@ -727,9 +727,10 @@ private function to_html ($Array) { } if (!empty($Block['Attr'])) { $Exploded = explode('|', $this->to_html($Block['Attr'])); - if (isset($Exploded[1]) && is_numeric($Exploded[1])) { + if (isset($Exploded[1]) && (is_numeric($Exploded[1]) || (in_array($Exploded[1][0], array('a', 't', 'c', 'r')) && is_numeric(substr($Exploded[1], 1))))) { + // the part after | is either a number or starts with a, t, c or r, followed by a number (forum post, artist comment, torrent comment, collage comment or request comment, respectively) $PostID = trim($Exploded[1]); - $Str .= ''.$Exploded[0].' wrote: '; + $Str .= ''.$Exploded[0].' wrote: '; } else { $Str .= ''.$Exploded[0].' wrote: '; @@ -747,8 +748,7 @@ private function to_html ($Array) { $Str .= ''; break; case 'mature': - global $LoggedUser; - if ($LoggedUser['EnableMatureContent']) { + if (G::$LoggedUser['EnableMatureContent']) { if (!empty($Block['Attr'])) { $Str .= 'Mature content: ' . $Block['Attr'] . '
    Show'; $Str .= ''; @@ -758,7 +758,7 @@ private function to_html ($Array) { } } else { - $Str .= 'Mature content has been blocked. You can choose to view mature content by editing your settings.'; + $Str .= 'Mature content has been blocked. You can choose to view mature content by editing your settings.'; } break; case 'img': @@ -905,8 +905,7 @@ private function raw_text ($Array) { } private function smileys ($Str) { - global $LoggedUser; - if (!empty($LoggedUser['DisableSmileys'])) { + if (!empty(G::$LoggedUser['DisableSmileys'])) { return $Str; } $Str = strtr($Str, $this->Smileys); diff --git a/classes/time.class.php b/classes/time.class.php index bd12bd0b..3139bb54 100644 --- a/classes/time.class.php +++ b/classes/time.class.php @@ -62,69 +62,69 @@ function time_diff($TimeStamp, $Levels = 2, $Span = true, $Lowercase = false) { if ($Years > 0 && $Levels > 0) { if ($Years > 1) { - $Return .= $Years.' years'; + $Return .= "$Years years"; } else { - $Return .= $Years.' year'; + $Return .= "$Years year"; } $Levels--; } if ($Months > 0 && $Levels > 0) { if ($Return != '') { - $Return.=', '; + $Return .= ', '; } if ($Months > 1) { - $Return.=$Months.' months'; + $Return .= "$Months months"; } else { - $Return.=$Months.' month'; + $Return .= "$Months month"; } $Levels--; } if ($Weeks > 0 && $Levels > 0) { if ($Return != '') { - $Return.=', '; + $Return .= ', '; } - if ($Weeks>1) { - $Return.=$Weeks.' weeks'; + if ($Weeks > 1) { + $Return .= "$Weeks weeks"; } else { - $Return.=$Weeks.' week'; + $Return .= "$Weeks week"; } $Levels--; } if ($Days > 0 && $Levels > 0) { if ($Return != '') { - $Return.=', '; + $Return .= ', '; } if ($Days > 1) { - $Return.=$Days.' days'; + $Return .= "$Days days"; } else { - $Return.=$Days.' day'; + $Return .= "$Days day"; } $Levels--; } if ($Hours > 0 && $Levels > 0) { if ($Return != '') { - $Return.=', '; + $Return .= ', '; } if ($Hours > 1) { - $Return.=$Hours.' hours'; + $Return .= "$Hours hours"; } else { - $Return.=$Hours.' hour'; + $Return .= "$Hours hour"; } $Levels--; } if ($Minutes > 0 && $Levels > 0) { if ($Return != '') { - $Return.=' and '; + $Return .= ' and '; } if ($Minutes > 1) { - $Return.=$Minutes.' mins'; + $Return .= "$Minutes mins"; } else { - $Return.=$Minutes.' min'; + $Return .= "$Minutes min"; } $Levels--; } @@ -140,7 +140,7 @@ function time_diff($TimeStamp, $Levels = 2, $Span = true, $Lowercase = false) { } if ($Span) { - return ''.$Return.''; + return ''.$Return.''; } else { return $Return; } diff --git a/classes/tools.class.php b/classes/tools.class.php index 99f53271..648b2a79 100644 --- a/classes/tools.class.php +++ b/classes/tools.class.php @@ -6,18 +6,20 @@ class Tools { * @param string $IP */ public static function site_ban_ip($IP) { - global $DB, $Cache, $Debug; + global $Debug; $A = substr($IP, 0, strcspn($IP, '.')); $IPNum = Tools::ip_to_unsigned($IP); - $IPBans = $Cache->get_value('ip_bans_'.$A); + $IPBans = G::$Cache->get_value('ip_bans_'.$A); if (!is_array($IPBans)) { $SQL = sprintf(" SELECT ID, FromIP, ToIP FROM ip_bans WHERE FromIP BETWEEN %d << 24 AND (%d << 24) - 1", $A, $A + 1); - $DB->query($SQL); - $IPBans = $DB->to_array(0, MYSQLI_NUM); - $Cache->cache_value('ip_bans_'.$A, $IPBans, 0); + $QueryID = G::$DB->get_query_id(); + G::$DB->query($SQL); + $IPBans = G::$DB->to_array(0, MYSQLI_NUM); + G::$DB->set_query_id($QueryID); + G::$Cache->cache_value('ip_bans_'.$A, $IPBans, 0); } $Debug->log_var($IPBans, 'IP bans for class '.$A); foreach ($IPBans as $Index => $IPBan) { @@ -59,16 +61,17 @@ public static function geoip($IP) { if (!$Long || $Long == 2130706433) { // No need to check cc for 127.0.0.1 return false; } - global $DB; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT EndIP, Code FROM geoip_country WHERE $Long >= StartIP ORDER BY StartIP DESC LIMIT 1"); - if ((!list($EndIP, $Country) = $DB->next_record()) || $EndIP < $Long) { + if ((!list($EndIP, $Country) = G::$DB->next_record()) || $EndIP < $Long) { $Country = '?'; } + G::$DB->set_query_id($QueryID); $IPs[$IP] = $Country; return $Country; } @@ -115,7 +118,7 @@ public static function get_host_by_ajax($IP) { * @return string the host. */ public static function lookup_ip($IP) { - //TODO: use the $Cache + //TODO: use the G::$Cache $Output = explode(' ',shell_exec('host -W 1 '.escapeshellarg($IP))); if (count($Output) == 1 && empty($Output[0])) { //No output at all implies the command failed @@ -145,7 +148,7 @@ public static function display_ip($IP) { public static function get_country_code_by_ajax($IP) { static $ID = 0; ++$ID; - return 'Resolving CC...'; + return 'Resolving CC...'; } @@ -156,11 +159,11 @@ public static function get_country_code_by_ajax($IP) { * @param BanReason 0 - Unknown, 1 - Manual, 2 - Ratio, 3 - Inactive, 4 - Unused. */ public static function disable_users($UserIDs, $AdminComment, $BanReason = 1) { - global $Cache, $DB; + $QueryID = G::$DB->get_query_id(); if (!is_array($UserIDs)) { $UserIDs = array($UserIDs); } - $DB->query(" + G::$DB->query(" UPDATE users_info AS i JOIN users_main AS m ON m.ID=i.UserID SET m.Enabled='2', @@ -170,35 +173,35 @@ public static function disable_users($UserIDs, $AdminComment, $BanReason = 1) { i.BanReason='$BanReason', i.RatioWatchDownload=".($BanReason == 2 ? 'm.Downloaded' : "'0'")." WHERE m.ID IN(".implode(',', $UserIDs).') '); - $Cache->decrement('stats_user_count', $DB->affected_rows()); + G::$Cache->decrement('stats_user_count', G::$DB->affected_rows()); foreach ($UserIDs as $UserID) { - $Cache->delete_value('enabled_'.$UserID); - $Cache->delete_value('user_info_'.$UserID); - $Cache->delete_value('user_info_heavy_'.$UserID); - $Cache->delete_value('user_stats_'.$UserID); + G::$Cache->delete_value("enabled_$UserID"); + G::$Cache->delete_value("user_info_$UserID"); + G::$Cache->delete_value("user_info_heavy_$UserID"); + G::$Cache->delete_value("user_stats_$UserID"); - $DB->query(" + G::$DB->query(" SELECT SessionID FROM users_sessions - WHERE UserID='$UserID' + WHERE UserID = '$UserID' AND Active = 1"); - while (list($SessionID) = $DB->next_record()) { - $Cache->delete_value('session_'.$UserID.'_'.$SessionID); + while (list($SessionID) = G::$DB->next_record()) { + G::$Cache->delete_value("session_$UserID"."_$SessionID"); } - $Cache->delete_value('users_sessions_'.$UserID); + G::$Cache->delete_value("users_sessions_$UserID"); - $DB->query(" + G::$DB->query(" DELETE FROM users_sessions - WHERE UserID='$UserID'"); + WHERE UserID = '$UserID'"); } // Remove the users from the tracker. - $DB->query(" + G::$DB->query(' SELECT torrent_pass FROM users_main - WHERE ID in (".implode(', ', $UserIDs).')'); - $PassKeys = $DB->collect('torrent_pass'); + WHERE ID in ('.implode(', ', $UserIDs).')'); + $PassKeys = G::$DB->collect('torrent_pass'); $Concat = ''; foreach ($PassKeys as $PassKey) { if (strlen($Concat) > 3950) { // Ocelot's read buffer is 4 KiB and anything exceeding it is truncated @@ -209,6 +212,7 @@ public static function disable_users($UserIDs, $AdminComment, $BanReason = 1) { } } Tracker::update_tracker('remove_users', array('passkeys' => $Concat)); + G::$DB->set_query_id($QueryID); } /** @@ -219,49 +223,51 @@ public static function disable_users($UserIDs, $AdminComment, $BanReason = 1) { * @param string $reason */ public static function warn_user($UserID, $Duration, $Reason) { - global $LoggedUser, $DB, $Cache, $Time; + global $Time; - $DB->query(" + $QueryID = G::$DB->get_query_id(); + G::$DB->query(" SELECT Warned FROM users_info - WHERE UserID=$UserID + WHERE UserID = $UserID AND Warned != '0000-00-00 00:00:00'"); - if ($DB->has_results()) { + if (G::$DB->has_results()) { //User was already warned, appending new warning to old. - list($OldDate) = $DB->next_record(); + list($OldDate) = G::$DB->next_record(); $NewExpDate = date('Y-m-d H:i:s', strtotime($OldDate) + $Duration); Misc::send_pm($UserID, 0, 'You have received multiple warnings.', - "When you received your latest warning (set to expire on ".date('Y-m-d', (time() + $Duration)).'), you already had a different warning (set to expire on '.date('Y-m-d', strtotime($OldDate)).").\n\n Due to this collision, your warning status will now expire at ".$NewExpDate.'.'); + "When you received your latest warning (set to expire on ".date('Y-m-d', (time() + $Duration)).'), you already had a different warning (set to expire on '.date('Y-m-d', strtotime($OldDate)).").\n\n Due to this collision, your warning status will now expire at $NewExpDate."); - $AdminComment = date('Y-m-d').' - Warning (Clash) extended to expire at '.$NewExpDate.' by '.$LoggedUser['Username']."\nReason: $Reason\n\n"; + $AdminComment = date('Y-m-d')." - Warning (Clash) extended to expire at $NewExpDate by " . G::$LoggedUser['Username'] . "\nReason: $Reason\n\n"; - $DB->query(' + G::$DB->query(' UPDATE users_info SET - Warned=\''.db_string($NewExpDate).'\', - WarnedTimes=WarnedTimes+1, - AdminComment=CONCAT(\''.db_string($AdminComment).'\',AdminComment) - WHERE UserID=\''.db_string($UserID).'\''); + Warned = \''.db_string($NewExpDate).'\', + WarnedTimes = WarnedTimes + 1, + AdminComment = CONCAT(\''.db_string($AdminComment).'\', AdminComment) + WHERE UserID = \''.db_string($UserID).'\''); } else { //Not changing, user was not already warned $WarnTime = time_plus($Duration); - $Cache->begin_transaction('user_info_'.$UserID); - $Cache->update_row(false, array('Warned' => $WarnTime)); - $Cache->commit_transaction(0); + G::$Cache->begin_transaction("user_info_$UserID"); + G::$Cache->update_row(false, array('Warned' => $WarnTime)); + G::$Cache->commit_transaction(0); - $AdminComment = date('Y-m-d').' - Warned until '.$WarnTime.' by '.$LoggedUser['Username']."\nReason: $Reason\n\n"; + $AdminComment = date('Y-m-d')." - Warned until $WarnTime by " . G::$LoggedUser['Username'] . "\nReason: $Reason\n\n"; - $DB->query(' + G::$DB->query(' UPDATE users_info SET - Warned=\''.db_string($WarnTime).'\', - WarnedTimes=WarnedTimes+1, - AdminComment=CONCAT(\''.db_string($AdminComment).'\',AdminComment) - WHERE UserID=\''.db_string($UserID).'\''); + Warned = \''.db_string($WarnTime).'\', + WarnedTimes = WarnedTimes + 1, + AdminComment = CONCAT(\''.db_string($AdminComment).'\',AdminComment) + WHERE UserID = \''.db_string($UserID).'\''); } + G::$DB->set_query_id($QueryID); } /** @@ -270,11 +276,12 @@ public static function warn_user($UserID, $Duration, $Reason) { * @param unknown $AdminComment Comment to update with */ public static function update_user_notes($UserID, $AdminComment) { - global $DB; - $DB->query(' + $QueryID = G::$DB->get_query_id(); + G::$DB->query(' UPDATE users_info - SET AdminComment=CONCAT(\''.db_string($AdminComment).'\',AdminComment) - WHERE UserID=\''.db_string($UserID).'\''); + SET AdminComment = CONCAT(\''.db_string($AdminComment).'\',AdminComment) + WHERE UserID = \''.db_string($UserID).'\''); + G::$DB->set_query_id($QueryID); } } ?> diff --git a/classes/torrent_form.class.php b/classes/torrent_form.class.php index d3c8d474..b6d9c25a 100644 --- a/classes/torrent_form.class.php +++ b/classes/torrent_form.class.php @@ -45,14 +45,13 @@ function TORRENT_FORM($Torrent = false, $Error = false, $NewTorrent = true) { } function head() { - global $LoggedUser; ?>
    NewTorrent) { ?>

    Your personal announce URL is:
    - +

    Error) { @@ -62,7 +61,7 @@ function head() {
    - + NewTorrent) { ?> @@ -150,13 +149,13 @@ function foot() { function music_form($GenreTags) { + $QueryID = G::$DB->get_query_id(); $Torrent = $this->Torrent; $IsRemaster = !empty($Torrent['Remastered']); $UnknownRelease = !$this->NewTorrent && $IsRemaster && !$Torrent['RemasterYear']; if ($Torrent['GroupID']) { - global $DB; - $DB->query(' + G::$DB->query(' SELECT ID, RemasterYear, @@ -172,12 +171,11 @@ function music_form($GenreTags) { RemasterRecordLabel DESC, RemasterCatalogueNumber DESC"); - if ($DB->has_results()) { - $GroupRemasters = $DB->to_array(false, MYSQLI_BOTH, false); + if (G::$DB->has_results()) { + $GroupRemasters = G::$DB->to_array(false, MYSQLI_BOTH, false); } } - global $DB; $HasLog = $Torrent['HasLog']; $HasCue = $Torrent['HasCue']; $BadTags = $Torrent['BadTags']; @@ -244,7 +242,7 @@ function music_form($GenreTags) { - MusicBrainz: + MusicBrainz:
    @@ -336,7 +334,7 @@ function show() { onclick="Remaster();NewTorrent) { ?> CheckYear();" /> + + - + + value="Torrents" type="text" name="groupname" size="17" value="Torrents" type="text" name="searchstr" size="17" /> diff --git a/design/publicheader.php b/design/publicheader.php index 9e5bb947..e582f4f7 100644 --- a/design/publicheader.php +++ b/design/publicheader.php @@ -1,7 +1,6 @@ @@ -26,7 +25,6 @@ @@ -44,4 +42,4 @@
    - + 'Post comment', + 'InputName' => 'groupid', + 'InputID' => $GroupID, + 'TextareaCols' => 65, + 'SubscribeBox' => true + )); + */ + global $HeavyInfo, $UserSubscriptions, $ThreadInfo, $ForumsDoublePost, $Document; + + if (G::$LoggedUser['DisablePosting']) { return; } if (!isset($TextareaCols)) { @@ -40,6 +52,9 @@ if (!isset($InputTitle)) { $InputTitle = 'Post comment'; } + if (!isset($Action)) { + $Action = ''; + } // TODO: Remove inline styles @@ -69,7 +84,7 @@
    #XXXXXX - by Just now + by Just now
    Report @@ -81,7 +96,7 @@ - + @@ -91,9 +106,9 @@ - onsubmit="quickpostform.submit_button.disabled=true;" > + onsubmit="quickpostform.submit_button.disabled=true;" > - +
    + tabindex="2" /> + + - + if (isset($ForumID)) { + if (!Subscriptions::has_subscribed($InputID)) { ?> tabindex="2" /> + if (!G::$LoggedUser['DisableAutoSave']) { ?> get_value('subscriptions_user_'.$LoggedUser['ID'])) === false) { - $DB->query(" - SELECT TopicID - FROM users_subscriptions - WHERE UserID = '$LoggedUser[ID]'"); - $UserSubscriptions = $DB->collect(0); - $Cache->cache_value('subscriptions_user_'.$LoggedUser['ID'], $UserSubscriptions, 0); -} +//Handle subscriptions +$UserSubscriptions = Subscriptions::get_subscriptions(); if (empty($UserSubscriptions)) { $UserSubscriptions = array(); diff --git a/sections/ajax/get_user_notifications.php b/sections/ajax/get_user_notifications.php new file mode 100644 index 00000000..79c66967 --- /dev/null +++ b/sections/ajax/get_user_notifications.php @@ -0,0 +1,9 @@ +get_notifications()); + +//echo '{"status":"success","response":[[{"message":"1st notification","url":"https:\/\/www.google.com\/","importance":"alert","AutoExpire":false},{"message":"2nd notification","url":"","importance":"alert","AutoExpire":true}]]}'; \ No newline at end of file diff --git a/sections/ajax/index.php b/sections/ajax/index.php index 67f6dc74..3deff675 100644 --- a/sections/ajax/index.php +++ b/sections/ajax/index.php @@ -157,6 +157,12 @@ case 'raw_bbcode': require(SERVER_ROOT . '/sections/ajax/raw_bbcode.php'); break; + case 'get_user_notifications': + require(SERVER_ROOT . '/sections/ajax/get_user_notifications.php'); + break; + case 'clear_user_notification': + require(SERVER_ROOT . '/sections/ajax/clear_user_notification.php'); + break; default: // If they're screwing around with the query string json_die("failure"); diff --git a/sections/ajax/info.php b/sections/ajax/info.php index 85e7a152..a9194618 100644 --- a/sections/ajax/info.php +++ b/sections/ajax/info.php @@ -91,27 +91,7 @@ } // Subscriptions -$NewSubscriptions = $Cache->get_value('subscriptions_user_new_' . $LoggedUser['ID']); -if ($NewSubscriptions === false) { - if ($LoggedUser['CustomForums']) { - unset($LoggedUser['CustomForums']['']); - $RestrictedForums = implode("','", array_keys($LoggedUser['CustomForums'], 0)); - $PermittedForums = implode("','", array_keys($LoggedUser['CustomForums'], 1)); - } - $DB->query(" - SELECT COUNT(s.TopicID) - FROM users_subscriptions AS s - JOIN forums_last_read_topics AS l ON s.UserID = l.UserID AND s.TopicID = l.TopicID - JOIN forums_topics AS t ON l.TopicID = t.ID - JOIN forums AS f ON t.ForumID = f.ID - WHERE (f.MinClassRead <= " . $LoggedUser['Class'] . " OR f.ID IN ('$PermittedForums')) - AND l.PostID < t.LastPostID - AND s.UserID = " . $LoggedUser['ID'] . - (!empty($RestrictedForums) ? " - AND f.ID NOT IN ('" . $RestrictedForums . "')" : '')); - list($NewSubscriptions) = $DB->next_record(); - $Cache->cache_value('subscriptions_user_new_' . $LoggedUser['ID'], $NewSubscriptions, 0); -} +$NewSubscriptions = Subscriptions::has_new_subscriptions(); json_die("success", array( 'username' => $LoggedUser['Username'], diff --git a/sections/ajax/request.php b/sections/ajax/request.php index ac597f34..191bd637 100644 --- a/sections/ajax/request.php +++ b/sections/ajax/request.php @@ -1,5 +1,4 @@ get_value('request_comments_'.$RequestID); -if ($Results === false) { - $DB->query(" - SELECT COUNT(c.ID) - FROM requests_comments as c - WHERE c.RequestID = '$RequestID'"); - list($Results) = $DB->next_record(); - $Cache->cache_value('request_comments_'.$RequestID, $Results, 0); -} - -list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $Results); - -// Get the cache catalogue -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - -//---------- Get some data to start processing - -// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page -$Catalogue = $Cache->get_value('request_comments_'.$RequestID.'_catalogue_'.$CatalogueID); -if ($Catalogue === false) { - $DB->query(" - SELECT - c.ID, - c.AuthorID, - c.AddedTime, - c.Body, - c.EditedUserID, - c.EditedTime, - u.Username - FROM requests_comments as c - LEFT JOIN users_main AS u ON u.ID=c.EditedUserID - WHERE c.RequestID = '$RequestID' - ORDER BY c.ID - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false,MYSQLI_ASSOC); - $Cache->cache_value('request_comments_'.$RequestID.'_catalogue_'.$CatalogueID, $Catalogue, 0); -} - -//This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue -$Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); +list($NumComments, $Page, $Thread) = Comments::load('requests', $RequestID, false); $JsonRequestComments = array(); foreach ($Thread as $Key => $Post) { @@ -197,7 +156,7 @@ 'tags' => $JsonTags, 'comments' => $JsonRequestComments, 'commentPage' => (int) $Page, - 'commentPages' => (int) ceil($Results / TORRENT_COMMENTS_PER_PAGE), + 'commentPages' => (int) ceil($NumComments / TORRENT_COMMENTS_PER_PAGE), 'recordLabel' => $RecordLabel, 'oclc' => $OCLC )); diff --git a/sections/ajax/subscriptions.php b/sections/ajax/subscriptions.php index 7b40f987..1c56d67d 100644 --- a/sections/ajax/subscriptions.php +++ b/sections/ajax/subscriptions.php @@ -17,12 +17,6 @@ } list($Page, $Limit) = Format::page_limit($PerPage); -if ($LoggedUser['CustomForums']) { - unset($LoggedUser['CustomForums']['']); - $RestrictedForums = implode("','", array_keys($LoggedUser['CustomForums'], 0)); - $PermittedForums = implode("','", array_keys($LoggedUser['CustomForums'], 1)); -} - $ShowUnread = (!isset($_GET['showunread']) && !isset($HeavyInfo['SubscriptionsUnread']) || isset($HeavyInfo['SubscriptionsUnread']) && !!$HeavyInfo['SubscriptionsUnread'] || isset($_GET['showunread']) && !!$_GET['showunread']); $ShowCollapsed = (!isset($_GET['collapse']) && !isset($HeavyInfo['SubscriptionsCollapse']) || isset($HeavyInfo['SubscriptionsCollapse']) && !!$HeavyInfo['SubscriptionsCollapse'] || isset($_GET['collapse']) && !!$_GET['collapse']); $sql = ' @@ -36,15 +30,7 @@ LEFT JOIN forums_last_read_topics AS l ON p.TopicID = l.TopicID AND l.UserID = s.UserID WHERE s.UserID = '.$LoggedUser['ID'].' AND p.ID <= IFNULL(l.PostID,t.LastPostID) - AND ((f.MinClassRead <= '.$LoggedUser['Class']; -if (!empty($RestrictedForums)) { - $sql.=" AND f.ID NOT IN ('$RestrictedForums')"; -} -$sql .= ')'; -if (!empty($PermittedForums)) { - $sql.=" OR f.ID IN ('$PermittedForums')"; -} -$sql .= ')'; + AND ' . Forums::user_forums_sql(); if ($ShowUnread) { $sql .= ' AND IF(l.PostID IS NULL OR (t.IsLocked = \'1\' && t.IsSticky = \'0\'), t.LastPostID, l.PostID) < t.LastPostID'; diff --git a/sections/ajax/tcomments.php b/sections/ajax/tcomments.php index 8918da9f..908dd0ea 100644 --- a/sections/ajax/tcomments.php +++ b/sections/ajax/tcomments.php @@ -1,62 +1,12 @@ -get_value('torrent_comments_'.$GroupID); -if ($Results === false) { - $DB->query(" - SELECT - COUNT(c.ID) - FROM torrents_comments as c - WHERE c.GroupID = '$GroupID'"); - list($Results) = $DB->next_record(); - $Cache->cache_value('torrent_comments_'.$GroupID, $Results, 0); +if (empty($_GET['id']) || !is_number($_GET['id'])) { + json_die("failure"); } -if (isset($_GET['postid']) && is_number($_GET['postid']) && $Results > TORRENT_COMMENTS_PER_PAGE) { - $DB->query(" - SELECT COUNT(ID) - FROM torrents_comments - WHERE GroupID = $GroupID - AND ID <= $_GET[postid]"); - list($PostNum) = $DB->next_record(); - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $PostNum); -} else { - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $Results); -} - -//Get the cache catalogue -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - -//---------- Get some data to start processing - -// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page -$Catalogue = $Cache->get_value('torrent_comments_'.$GroupID.'_catalogue_'.$CatalogueID); -if ($Catalogue === false) { - $DB->query(" - SELECT - c.ID, - c.AuthorID, - c.AddedTime, - c.Body, - c.EditedUserID, - c.EditedTime, - u.Username - FROM torrents_comments as c - LEFT JOIN users_main AS u ON u.ID=c.EditedUserID - WHERE c.GroupID = '$GroupID' - ORDER BY c.ID - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false,MYSQLI_ASSOC); - $Cache->cache_value('torrent_comments_'.$GroupID.'_catalogue_'.$CatalogueID, $Catalogue, 0); -} - -//This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue -$Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); +list($NumComments, $Page, $Thread) = Comments::load('torrents', (int)$_GET['id'], false); //---------- Begin printing $JsonComments = array(); @@ -86,6 +36,6 @@ json_die("success", array( 'page' => (int) $Page, - 'pages' => ceil($Results / TORRENT_COMMENTS_PER_PAGE), + 'pages' => ceil($NumComments / TORRENT_COMMENTS_PER_PAGE), 'comments' => $JsonComments )); diff --git a/sections/ajax/user.php b/sections/ajax/user.php index 328d1827..a24cc893 100644 --- a/sections/ajax/user.php +++ b/sections/ajax/user.php @@ -35,7 +35,6 @@ i.JoinDate, i.Info, i.Avatar, - i.Country, i.Donor, i.Warned, COUNT(posts.id) AS ForumPosts, @@ -54,7 +53,7 @@ json_die("failure", "no such user"); } -list($Username, $Email, $LastAccess, $IP, $Class, $Uploaded, $Downloaded, $RequiredRatio, $Enabled, $Paranoia, $Invites, $CustomTitle, $torrent_pass, $DisableLeech, $JoinDate, $Info, $Avatar, $Country, $Donor, $Warned, $ForumPosts, $InviterID, $DisableInvites, $InviterName, $RatioWatchEnds, $RatioWatchDownload) = $DB->next_record(MYSQLI_NUM, array(9, 11)); +list($Username, $Email, $LastAccess, $IP, $Class, $Uploaded, $Downloaded, $RequiredRatio, $Enabled, $Paranoia, $Invites, $CustomTitle, $torrent_pass, $DisableLeech, $JoinDate, $Info, $Avatar, $Donor, $Warned, $ForumPosts, $InviterID, $DisableInvites, $InviterName, $RatioWatchEnds, $RatioWatchDownload) = $DB->next_record(MYSQLI_NUM, array(9, 11)); $Paranoia = unserialize($Paranoia); if (!is_array($Paranoia)) { @@ -188,8 +187,9 @@ function check_paranoia_here($Setting) { if (check_paranoia_here(array('torrentcomments', 'torrentcomments+'))) { $DB->query(" SELECT COUNT(ID) - FROM torrents_comments - WHERE AuthorID = '$UserID'"); + FROM comments + WHERE Page = 'torrents' + AND AuthorID = '$UserID'"); list($NumComments) = $DB->next_record(); } @@ -275,6 +275,11 @@ function check_paranoia_here($Setting) { if (!check_paranoia_here('lastseen')) { $LastAccess = ''; } +if (check_paranoia_here('ratio')) { + $Ratio = Format::get_ratio($Uploaded, $Downloaded, 5); +} else { + $Ratio = null; +} if (!check_paranoia_here('uploaded')) { $Uploaded = null; } diff --git a/sections/ajax/userhistory/post_history.php b/sections/ajax/userhistory/post_history.php index 6447a1b3..d3df13cf 100644 --- a/sections/ajax/userhistory/post_history.php +++ b/sections/ajax/userhistory/post_history.php @@ -36,11 +36,6 @@ function error_out($reason = '') { $UserInfo = Users::user_info($UserID); extract(array_intersect_key($UserInfo, array_flip(array('Username', 'Enabled', 'Title', 'Avatar', 'Donor', 'Warned')))); -if ($LoggedUser['CustomForums']) { - unset($LoggedUser['CustomForums']['']); - $RestrictedForums = implode("','", array_keys($LoggedUser['CustomForums'], 0)); - $PermittedForums = implode("','", array_keys($LoggedUser['CustomForums'], 1)); -} $ViewingOwn = ($UserID === $LoggedUser['ID']); $ShowUnread = ($ViewingOwn && (!isset($_GET['showunread']) || !!$_GET['showunread'])); $ShowGrouped = ($ViewingOwn && (!isset($_GET['group']) || !!$_GET['group'])); @@ -58,17 +53,7 @@ function error_out($reason = '') { $SQL .= ' LEFT JOIN forums AS f ON f.ID = t.ForumID WHERE p.AuthorID = '.$UserID.' - AND ((f.MinClassRead <= '.$LoggedUser['Class']; - if (!empty($RestrictedForums)) { - $SQL .= " - AND f.ID NOT IN ('$RestrictedForums')"; - } - $SQL .= ')'; - if (!empty($PermittedForums)) { - $SQL .= " - OR f.ID IN ('$PermittedForums')"; - } - $SQL .= ')'; + AND ' . Forums::user_forums_sql(); if ($ShowUnread) { $SQL .= ' AND ((t.IsLocked = \'0\' OR t.IsSticky = \'1\') @@ -145,21 +130,7 @@ function error_out($reason = '') { JOIN forums AS f ON f.ID = t.ForumID LEFT JOIN forums_last_read_topics AS l ON l.UserID = $UserID AND l.TopicID = t.ID WHERE p.AuthorID = $UserID - AND ((f.MinClassRead <= ".$LoggedUser['Class']; - - if (!empty($RestrictedForums)) { - $SQL .= " - AND f.ID NOT IN ('$RestrictedForums')"; - } - $SQL .= ' - )'; - - if (!empty($PermittedForums)) { - $SQL .= " - OR f.ID IN ('$PermittedForums')"; - } - $SQL .= ' - )'; + AND " . Forums::user_forums_sql(); if ($ShowUnread) { $SQL .= ' diff --git a/sections/api/index.php b/sections/api/index.php index 865c776d..264bcc8f 100644 --- a/sections/api/index.php +++ b/sections/api/index.php @@ -8,13 +8,13 @@ ); if ( - empty($_GET['req']) || - empty($_GET['uid']) || - empty($_GET['aid']) || - empty($_GET['key']) || - !is_number($_GET['uid']) || - !is_number($_GET['aid']) || - !in_array($_GET['req'], $Available, true) + empty($_GET['req']) + || empty($_GET['uid']) + || empty($_GET['aid']) + || empty($_GET['key']) + || !is_number($_GET['uid']) + || !is_number($_GET['aid']) + || !in_array($_GET['req'], $Available, true) ) { error('invalid'); } diff --git a/sections/artist/artist.php b/sections/artist/artist.php index 1a1e308a..f55a9490 100644 --- a/sections/artist/artist.php +++ b/sections/artist/artist.php @@ -9,7 +9,7 @@ function compare($X, $Y) { include(SERVER_ROOT.'/classes/text.class.php'); // Text formatting class $Text = new TEXT; -// Similar artist map +// Similar Artist Map include(SERVER_ROOT.'/classes/artists_similar.class.php'); $UserVotes = Votes::get_user_votes($LoggedUser['ID']); @@ -343,9 +343,9 @@ function compare($X, $Y) { } - $DisplayName = "$GroupName"; + $DisplayName = "$GroupName"; if (check_perms('users_mod') || check_perms('torrents_fix_ghosts')) { - $DisplayName .= ' Fix'; + $DisplayName .= ' Fix'; } @@ -390,22 +390,22 @@ function compare($X, $Y) { ?> -
    - +
    +
    - +
    - +
    Unbookmark"; + echo "Remove bookmark"; } else { - echo "Bookmark"; + echo "Bookmark"; } ?>
    format('torrents.php?taglist=', $Name)?>
    @@ -428,16 +428,19 @@ function compare($X, $Y) { } $SnatchedTorrentClass = ($Torrent['IsSnatched'] ? ' snatched_torrent' : ''); - if ($Torrent['RemasterTitle'] != $LastRemasterTitle || $Torrent['RemasterYear'] != $LastRemasterYear || - $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel || $Torrent['RemasterCatalogueNumber'] != - $LastRemasterCatalogueNumber || $FirstUnknown || $Torrent['Media'] != $LastMedia + if ($Torrent['RemasterTitle'] != $LastRemasterTitle + || $Torrent['RemasterYear'] != $LastRemasterYear + || $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel + || $Torrent['RemasterCatalogueNumber'] != $LastRemasterCatalogueNumber + || $FirstUnknown + || $Torrent['Media'] != $LastMedia ) { $EditionID++; ?> - + [ - | FL + | FL ]   »  - - - > - + + + +
    @@ -497,7 +500,7 @@ function compare($X, $Y) { $Notify = $DB->next_record(MYSQLI_ASSOC, false); $Cache->cache_value('notify_artists_'.$LoggedUser['ID'], $Notify, 0); } - if (stripos($Notify['Artists'], '|'.$Name.'|') === false) { + if (stripos($Notify['Artists'], "|$Name|") === false) { ?> Notify of new uploads @@ -512,6 +515,7 @@ function compare($X, $Y) { Bookmark +
    - +
    Tags
      - +
    @@ -651,10 +653,10 @@ function compare($X, $Y) { ass.Score, ass.SimilarID FROM artists_similar AS s1 - JOIN artists_similar AS s2 ON s1.SimilarID=s2.SimilarID AND s1.ArtistID!=s2.ArtistID - JOIN artists_similar_scores AS ass ON ass.SimilarID=s1.SimilarID - JOIN artists_group AS a ON a.ArtistID=s2.ArtistID - WHERE s1.ArtistID='$ArtistID' + JOIN artists_similar AS s2 ON s1.SimilarID = s2.SimilarID AND s1.ArtistID != s2.ArtistID + JOIN artists_similar_scores AS ass ON ass.SimilarID = s1.SimilarID + JOIN artists_group AS a ON a.ArtistID = s2.ArtistID + WHERE s1.ArtistID = '$ArtistID' ORDER BY ass.Score DESC LIMIT 30 "); @@ -663,12 +665,12 @@ function compare($X, $Y) { } ?>
    -
    Similar artists
    +
    Similar Artists
      - +
    • None found
    • -
    • - - + + + + - X + X

      @@ -744,23 +746,25 @@ function compare($X, $Y) {  This artist is in collage 1) ? 's' : '')?> # artists - +?> - +?> - + $Title [$Year]"; } else { - $FullName ="$Title"; + $FullName = "$Title"; } - $Row = ($Row == 'a') ? 'b' : 'a'; + $Row = $Row === 'a' ? 'b' : 'a'; $Tags = Requests::get_tags($RequestID); $ReqTagList = array(); @@ -833,7 +837,7 @@ function compare($X, $Y) { 0) { if ($SimilarData = $Cache->get_value("similar_positions_$ArtistID")) { @@ -862,7 +866,7 @@ function compare($X, $Y) {
        - Similar artist map + Similar Artist Map Switch to cloud
      @@ -871,7 +875,7 @@ function compare($X, $Y) { ?>
      full_format($Body)?>
      - -get_value("artist_comments_$ArtistID"); -if ($Results === false) { - $DB->query(" - SELECT - COUNT(c.ID) - FROM artist_comments as c - WHERE c.ArtistID = '$ArtistID'"); - list($Results) = $DB->next_record(); - $Cache->cache_value("artist_comments_$ArtistID", $Results, 0); -} +list($NumComments, $Page, $Thread, $LastRead) = Comments::load('artist', $ArtistID); +$Pages = Format::get_pages($Page, $NumComments, TORRENT_COMMENTS_PER_PAGE, 9, '#comments'); -if (isset($_GET['postid']) && is_number($_GET['postid']) && $Results > TORRENT_COMMENTS_PER_PAGE) { - $DB->query(" - SELECT COUNT(ID) - FROM artist_comments - WHERE ArtistID = $ArtistID - AND ID <= $_GET[postid]"); - list($PostNum) = $DB->next_record(); - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $PostNum); -} else { - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $Results); -} - -//Get the cache catalogue -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - -//---------- Get some data to start processing - -// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page -$Catalogue = $Cache->get_value("artist_comments_{$ArtistID}_catalogue_$CatalogueID"); -if ($Catalogue === false) { - $DB->query(" - SELECT - c.ID, - c.AuthorID, - c.AddedTime, - c.Body, - c.EditedUserID, - c.EditedTime, - u.Username - FROM artist_comments as c - LEFT JOIN users_main AS u ON u.ID = c.EditedUserID - WHERE c.ArtistID = '$ArtistID' - ORDER BY c.ID - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false, MYSQLI_ASSOC); - $Cache->cache_value("artist_comments_{$ArtistID}_catalogue_$CatalogueID", $Catalogue, 0); -} - -//This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue -$Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); ?> $Post) { - list($PostID, $AuthorID, $AddedTime, $CommentBody, $EditedUserID, $EditedTime, $EditedUsername) = array_values($Post); - list($AuthorID, $Username, $PermissionID, $Paranoia, $Artist, $Donor, $Warned, $Avatar, $Enabled, $UserTitle) = array_values(Users::user_info($AuthorID)); +CommentsView::render_comments($Thread, $LastRead, "artist.php?id=$ArtistID"); ?> - - - - - - - - - - - - - - - - -
      -
      # - - - Quote - - - Edit - - - Delete - -
      -
      - Report -= $AuthorInfo['Class']) { -?> - - - Warn - -   - -
      -
      - - -
      -full_format($CommentBody)?> - -
      -
      - - « - - Last edited by - - -
      -
      - 'artistid', - 'InputID' => $ArtistID)); + 'InputName' => 'pageid', + 'InputID' => $ArtistID, + 'Action' => 'comments.php?page=artist', + 'InputAction' => 'take_post', + 'SubscribeBox' => true + )); ?>
    @@ -1099,7 +986,7 @@ function require(file, callback) { if ($RevisionID) { $Key = "artist_$ArtistID" . "_revision_$RevisionID"; } else { - $Key = 'artist_' . $ArtistID; + $Key = "artist_$ArtistID"; } $Data = array(array($Name, $Image, $Body, $NumSimilar, $SimilarArray, array(), array(), $VanityHouseArtist)); diff --git a/sections/artist/delete.php b/sections/artist/delete.php index 7677edbc..d2a10a12 100644 --- a/sections/artist/delete.php +++ b/sections/artist/delete.php @@ -35,7 +35,7 @@ if ($DB->has_results()) { ?>
    - There are still torrents that have as an artist.
    + There are still torrents that have as an artist.
    Please remove the artist from these torrents manually before attempting to delete.
      @@ -63,7 +63,7 @@ if ($DB->has_results()) { ?>
      - There are still requests that have as an artist.
      + There are still requests that have as an artist.
      Please remove the artist from these requests manually before attempting to delete.
        diff --git a/sections/artist/edit.php b/sections/artist/edit.php index 40cb0bd2..08add9e1 100644 --- a/sections/artist/edit.php +++ b/sections/artist/edit.php @@ -112,14 +112,14 @@ } ?>
      • - . + . - User + User - (writes redirect to ) + (writes redirect to ) - X + X
      • diff --git a/sections/artist/index.php b/sections/artist/index.php index 0630b2bd..106eb992 100644 --- a/sections/artist/index.php +++ b/sections/artist/index.php @@ -34,61 +34,6 @@ case 'change_artistid': require(SERVER_ROOT . '/sections/artist/change_artistid.php'); break; - case 'reply': - authorize(); - - if (!isset($_POST['artistid']) || !isset($_POST['body']) || !is_number($_POST['artistid']) || trim($_POST['body']) === '') { - error(0); - } - if ($LoggedUser['DisablePosting']) { - error('Your posting privileges have been removed.'); - } - - $ArtistID = $_POST['artistid']; - if (!$ArtistID) { - error(404); - } - - $DB->query(" - SELECT - CEIL(( - SELECT COUNT(ID) + 1 - FROM artist_comments AS ac - WHERE ac.ArtistID = '" . db_string($ArtistID) . "' - ) / " . TORRENT_COMMENTS_PER_PAGE . " - ) AS Pages"); - list($Pages) = $DB->next_record(); - - $DB->query(" - INSERT INTO artist_comments - (ArtistID, AuthorID, AddedTime, Body) - VALUES - ('" . db_string($ArtistID) . "', '" . db_string($LoggedUser['ID']) . "', '" . sqltime() . "', '" . db_string($_POST['body']) . "')"); - $PostID = $DB->inserted_id(); - - $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $Cache->begin_transaction("artist_comments_$ArtistID" . "_catalogue_$CatalogueID"); - $Post = array( - 'ID' => $PostID, - 'AuthorID' => $LoggedUser['ID'], - 'AddedTime' => sqltime(), - 'Body' => $_POST['body'], - 'EditedUserID' => 0, - 'EditedTime' => '0000-00-00 00:00:00', - 'Username' => '' - ); - $Cache->insert('', $Post); - $Cache->commit_transaction(0); - $Cache->increment("artist_comments_$ArtistID"); - - header("Location: artist.php?id=$ArtistID&page=$Pages"); - break; - case 'warn' : - include(SERVER_ROOT . '/sections/artist/warn.php'); - break; - case 'take_warn' : - include(SERVER_ROOT . '/sections/artist/take_warn.php'); - break; case 'concert_thread': include(SERVER_ROOT . '/sections/artist/concert_thread.php'); break; @@ -103,135 +48,6 @@ case 'autocomplete': require('sections/artist/autocomplete.php'); break; - case 'get_post': - if (!$_GET['post'] || !is_number($_GET['post'])) { - error(0); - } - $DB->query(" - SELECT Body - FROM artist_comments - WHERE ID = '" . db_string($_GET['post']) . "'"); - list($Body) = $DB->next_record(MYSQLI_NUM); - echo trim($Body); - break; - - case 'delete_comment': - authorize(); - - // Quick SQL injection check - if (!$_GET['postid'] || !is_number($_GET['postid'])) { - error(0); - } - - // Make sure they are moderators - if (!check_perms('site_moderate_forums')) { - error(403); - } - - // Get topicid, forumid, number of pages - $DB->query(' - SELECT - ArtistID, - CEIL(COUNT(ac.ID) / ' . TORRENT_COMMENTS_PER_PAGE . ') AS Pages, - CEIL(SUM(IF(ac.ID <= ' . $_GET['postid'] . ', 1, 0)) / ' . TORRENT_COMMENTS_PER_PAGE . ') AS Page - FROM artist_comments AS ac - WHERE ac.ArtistID = ( - SELECT ArtistID - FROM artist_comments - WHERE ID = ' . $_GET['postid'] . ' - ) - GROUP BY ac.ArtistID'); - list($ArtistID, $Pages, $Page) = $DB->next_record(); - - // $Pages = number of pages in the thread - // $Page = which page the post is on - // These are set for cache clearing. - - $DB->query(" - DELETE FROM artist_comments - WHERE ID = '" . db_string($_GET['postid']) . "'"); - - //We need to clear all subsequential catalogues as they've all been bumped with the absence of this post - $ThisCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - for ($i = $ThisCatalogue; $i <= $LastCatalogue; $i++) { - $Cache->delete_value("artist_comments_$ArtistID" . "_catalogue_$i"); - } - - // Delete thread info cache (eg. number of pages) - $Cache->delete_value("artist_comments_$ArtistID"); - - break; - - case 'takeedit_post': - authorize(); - - include(SERVER_ROOT . '/classes/text.class.php'); // Text formatting class - $Text = new TEXT; - - // Quick SQL injection check - if (!$_POST['post'] || !is_number($_POST['post'])) { - error(0); - } - - // Mainly - $DB->query(" - SELECT - ac.Body, - ac.AuthorID, - ac.ArtistID, - ac.AddedTime - FROM artist_comments AS ac - WHERE ac.ID = '" . db_string($_POST['post']) . "'"); - list($OldBody, $AuthorID, $ArtistID, $AddedTime) = $DB->next_record(); - - $DB->query(" - SELECT ceil(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page - FROM artist_comments - WHERE ArtistID = $ArtistID - AND ID <= $_POST[post]"); - list($Page) = $DB->next_record(); - - if ($LoggedUser['ID'] != $AuthorID && !check_perms('site_moderate_forums')) { - error(404); - } - if (!$DB->has_results()) { - error(404); - } - - // Perform the update - $DB->query(" - UPDATE artist_comments - SET - Body = '" . db_string($_POST['body']) . "', - EditedUserID = '" . db_string($LoggedUser['ID']) . "', - EditedTime = '" . sqltime() . "' - WHERE ID = '" . db_string($_POST['post']) . "'"); - - // Update the cache - $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $Cache->begin_transaction("artist_comments_$ArtistID" . "_catalogue_$CatalogueID"); - - $Cache->update_row($_POST['key'], array( - 'ID' => $_POST['post'], - 'AuthorID' => $AuthorID, - 'AddedTime' => $AddedTime, - 'Body' => $_POST['body'], - 'EditedUserID' => db_string($LoggedUser['ID']), - 'EditedTime' => sqltime(), - 'Username' => $LoggedUser['Username'] - )); - $Cache->commit_transaction(0); - - $DB->query(" - INSERT INTO comments_edits - (Page, PostID, EditUser, EditTime, Body) - VALUES - ('artist', " . db_string($_POST['post']) . ", " . db_string($LoggedUser['ID']) . ", '" . sqltime() . "', '" . db_string($OldBody) . "')"); - - // This gets sent to the browser, which echoes it in place of the old body - echo $Text->full_format($_POST['body']); - break; case 'edit': require(SERVER_ROOT . '/sections/artist/edit.php'); diff --git a/sections/artist/rename.php b/sections/artist/rename.php index 7f66c08d..453c90dd 100644 --- a/sections/artist/rename.php +++ b/sections/artist/rename.php @@ -218,6 +218,8 @@ Requests::update_sphinx_requests($RequestID); } } + + Comments::merge('artist', $ArtistID, $TargetArtistID); } } diff --git a/sections/artist/take_warn.php b/sections/artist/take_warn.php deleted file mode 100644 index 041011b7..00000000 --- a/sections/artist/take_warn.php +++ /dev/null @@ -1,79 +0,0 @@ - $LoggedUser['Class']) { - error(403); -} -$URL = "https://". SSL_SITE_URL."/artist.php?id=$ArtistID&postid=$PostID#post$PostID"; -if ($Length != 'verbal') { - $Time = ((int)$Length) * (7 * 24 * 60 * 60); - Tools::warn_user($UserID, $Time, "$URL - $Reason"); - $Subject = 'You have received a warning'; - $PrivateMessage = "You have received a $Length week warning for [url=$URL]this artist comment.[/url]\n\n$PrivateMessage"; - $WarnTime = time_plus($Time); - $AdminComment = date('Y-m-d') . " - Warned until $WarnTime by " . $LoggedUser['Username'] . "\nReason: $URL - $Reason\n\n"; -} else { - $Subject = 'You have received a verbal warning'; - $PrivateMessage = "You have received a verbal warning for [url=$URL]this post.[/url]\n\n$PrivateMessage"; - $AdminComment = date('Y-m-d') . ' - Verbally warned by ' . $LoggedUser['Username'] . " for $URL \nReason: $Reason\n\n"; - Tools::update_user_notes($UserID, $AdminComment); -} -$DB->query(" - INSERT INTO users_warnings_forums (UserID, Comment) - VALUES('$UserID', '" . db_string($AdminComment) . "') - ON DUPLICATE KEY UPDATE Comment = CONCAT('" . db_string($AdminComment) . "', Comment)"); -Misc::send_pm($UserID, $LoggedUser['ID'], $Subject, $PrivateMessage); - -// Mainly -$DB->query(" - SELECT - ac.Body, - ac.AuthorID, - ac.ArtistID, - ac.AddedTime - FROM artist_comments AS ac - WHERE ac.ID = '$PostID'"); -list($OldBody, $AuthorID, $ArtistID, $AddedTime) = $DB->next_record(); - -$DB->query(" - SELECT ceil(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page - FROM artist_comments - WHERE ArtistID = $ArtistID - AND ID <= $PostID"); -list($Page) = $DB->next_record(); - -// Perform the update -$DB->query(" - UPDATE artist_comments - SET - Body = '" . db_string($Body) . "', - EditedUserID = '" . db_string($LoggedUser['ID']) . "', - EditedTime = '" . sqltime() . "' - WHERE ID = '$PostID'"); - -// Update the cache -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$Cache->begin_transaction("artist_comments_$ArtistID" . "_catalogue_$CatalogueID"); - -$Cache->update_row($_POST['key'], array('ID' => $_POST['postid'], 'AuthorID' => $AuthorID, 'AddedTime' => $AddedTime, 'Body' => $Body, 'EditedUserID' => db_string($LoggedUser['ID']), 'EditedTime' => sqltime(), 'Username' => $LoggedUser['Username'])); -$Cache->commit_transaction(0); - -$DB->query(" - INSERT INTO comments_edits (Page, PostID, EditUser, EditTime, Body) - VALUES ('artist', " . db_string($_POST['postid']) . ', ' . db_string($LoggedUser['ID']) . ", '" . sqltime() . "', '" . db_string($OldBody) . "')"); - -header("Location: artist.php?id=$ArtistID&postid=$PostID#post$PostID"); -?> diff --git a/sections/artist/warn.php b/sections/artist/warn.php deleted file mode 100644 index de1ac0e8..00000000 --- a/sections/artist/warn.php +++ /dev/null @@ -1,70 +0,0 @@ -query(" - SELECT ac.Body, ac.AddedTime - FROM artist_comments AS ac - WHERE ac.ID = '" . db_string($PostID) . "'"); -list($PostBody) = $DB -> next_record(); - -View::show_header('Warn User'); -?> - -
        -
        -

        Warning

        -
        -
        -
        - - - - - - - - - - - - - - - - - - - - - - -
        Reason: - -
        Length: -
        Private message: - -
        Edit post: - -
        - -
        -
        -
        -
        - diff --git a/sections/better/files.php b/sections/better/files.php index 03978ad1..87a18eae 100644 --- a/sections/better/files.php +++ b/sections/better/files.php @@ -66,7 +66,7 @@ } else { $DisplayName = ''; } - $DisplayName .= "$GroupName"; + $DisplayName .= "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/folders.php b/sections/better/folders.php index 56dc26f8..ff97e873 100644 --- a/sections/better/folders.php +++ b/sections/better/folders.php @@ -17,7 +17,7 @@ $Join = ''; $All = true; } else { - $Join = "JOIN xbt_snatched as x ON x.fid=tbf.TorrentID AND x.uid = ".$LoggedUser['ID']; + $Join = "JOIN xbt_snatched as x ON x.fid = tbf.TorrentID AND x.uid = ".$LoggedUser['ID']; $All = false; } @@ -66,7 +66,7 @@ } else { $DisplayName = ''; } - $DisplayName .= ''.$GroupName.''; + $DisplayName .= "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/single.php b/sections/better/single.php index faa7c703..a50f32ed 100644 --- a/sections/better/single.php +++ b/sections/better/single.php @@ -43,7 +43,7 @@ } $FlacID = $GroupIDs[$GroupID]['TorrentID']; - $DisplayName .= ''.$GroupName.''; + $DisplayName .= "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/snatch.php b/sections/better/snatch.php index 41b8d653..6508c6e4 100644 --- a/sections/better/snatch.php +++ b/sections/better/snatch.php @@ -191,7 +191,7 @@ if (!$Edition['FlacID'] || count($Edition['Formats']) === 3) { continue; } - $DisplayName = $ArtistNames . ''.$GroupName.''; + $DisplayName = $ArtistNames . ''.$GroupName.''; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/tags.php b/sections/better/tags.php index 3301b0bd..a82ab08b 100644 --- a/sections/better/tags.php +++ b/sections/better/tags.php @@ -17,7 +17,7 @@ $Join = ''; $All = true; } else { - $Join = "JOIN xbt_snatched as x ON x.fid=tbt.TorrentID AND x.uid = ".$LoggedUser['ID']; + $Join = "JOIN xbt_snatched as x ON x.fid = tbt.TorrentID AND x.uid = ".$LoggedUser['ID']; $All = false; } @@ -67,7 +67,7 @@ } else { $DisplayName = ''; } - $DisplayName .= ''.$GroupName.''; + $DisplayName .= "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/transcode.php b/sections/better/transcode.php index 51b5ee63..a42718f8 100644 --- a/sections/better/transcode.php +++ b/sections/better/transcode.php @@ -136,7 +136,7 @@ $Debug->log_var($Edition, 'Skipping '.$RemIdent); continue; } - $DisplayName = $ArtistNames . ''.$GroupName.''; + $DisplayName = $ArtistNames . ''.$GroupName.''; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/transcode_beta.php b/sections/better/transcode_beta.php index 0aaedff5..7a63d973 100644 --- a/sections/better/transcode_beta.php +++ b/sections/better/transcode_beta.php @@ -304,7 +304,7 @@ function transcode_parse_groups($Groups) { foreach ($Group['Editions'] as $RemIdent => $Edition) { // TODO: point to the correct FLAC (?) $FlacID = array_search(true, $Edition['FlacIDs']); - $DisplayName = $ArtistNames . "$GroupName"; + $DisplayName = $ArtistNames . "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/better/upload.php b/sections/better/upload.php index 3b6009bf..4c52ea10 100644 --- a/sections/better/upload.php +++ b/sections/better/upload.php @@ -166,7 +166,7 @@ if (!$Edition['FlacID'] || count($Edition['Formats']) === 3) { continue; } - $DisplayName = $ArtistNames . ''.$GroupName.''; + $DisplayName = $ArtistNames . ''.$GroupName.''; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } diff --git a/sections/bookmarks/torrents.php b/sections/bookmarks/torrents.php index 6c024e5c..3fcb78db 100644 --- a/sections/bookmarks/torrents.php +++ b/sections/bookmarks/torrents.php @@ -82,8 +82,8 @@ function compare($X, $Y) { ?> -
        - +
        +
        @@ -93,7 +93,7 @@ function compare($X, $Y) { - Unbookmark + Remove bookmark
        @@ -129,7 +129,7 @@ function compare($X, $Y) { $EditionID++; ?> - + [ DL - | FL + | FL | RP ]   »  - - - > - + + + + [ DL - | FL + | FL | RP ]
        format()?>
        - Unbookmark + Remove bookmark - - - > - + + + + query(" - SELECT - CEIL( - ( - SELECT COUNT(ID) + 1 - FROM collages_comments - WHERE CollageID = '".db_string($CollageID)."' - ) / ".TORRENT_COMMENTS_PER_PAGE." - ) AS Pages"); -list($Pages) = $DB->next_record(); - -$DB->query(" - INSERT INTO collages_comments - (CollageID, Body, UserID, Time) - VALUES - ('$CollageID', '".db_string($_POST['body'])."', '$LoggedUser[ID]', '".sqltime()."')"); - -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - -$Cache->delete_value("collage_$CollageID"); -$Cache->delete_value("collage_comments_{$CollageID}_catalogue_$CatalogueID"); -$Cache->increment("collage_comments_$CollageID"); -header('Location: collages.php?id='.$CollageID); - -?> diff --git a/sections/collages/all_comments.php b/sections/collages/all_comments.php index e4481f3a..1d71ff8f 100644 --- a/sections/collages/all_comments.php +++ b/sections/collages/all_comments.php @@ -14,37 +14,12 @@ $Text = new TEXT; // Check for lame SQL injection attempts -$CollageID = $_GET['collageid']; -if (!is_number($CollageID)) { +if (!is_number($_GET['collageid'])) { error(0); } +$CollageID = (int)$_GET['collageid']; -// gets the amount of comments for this collage -$NumComments = Collages::get_comment_count($CollageID); - -if (isset($_GET['postid']) && is_number($_GET['postid']) && $NumComments > TORRENT_COMMENTS_PER_PAGE) { - $DB->query(" - SELECT COUNT(ID) - FROM collages_comments - WHERE CollageID = $CollageID - AND ID <= $_GET[postid]"); - list($PostNum) = $DB->next_record(); - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $PostNum); -} else { - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $NumComments); -} - -//Get the cache catalogue -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - -//---------- Get some data to start processing - -// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page -$Catalogue = Collages::get_comment_catalogue($CollageID, $CatalogueID); - -//This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue -$Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); +list($NumComments, $Page, $Thread, $LastRead) = Comments::load('collages', $CollageID); $DB->query(" SELECT Name @@ -53,7 +28,7 @@ list($Name) = $DB->next_record(); // Start printing -View::show_header("Comments for collage $Name", 'comments,bbcode'); +View::show_header("Comments for collage $Name", 'comments,bbcode,subscriptions'); ?>
        @@ -62,63 +37,29 @@
        - - - - - - - - - - - - - - - - -
        - # - - - Quote - Edit - Delete - - - Report - - -
        - - -
        -full_format($Body)?> -
        -
        - 'collageid', + View::parse('generic/reply/quickreply.php', array( + 'InputName' => 'pageid', 'InputID' => $CollageID, - 'InputAction' => 'add_comment', - 'TextareaCols' => 90)); + 'Action' => 'comments.php?page=collages', + 'InputAction' => 'take_post', + 'TextareaCols' => 90, + 'SubscribeBox' => true + )); } } ?> diff --git a/sections/collages/artist_collage.php b/sections/collages/artist_collage.php index 8e6066f0..3b725d56 100644 --- a/sections/collages/artist_collage.php +++ b/sections/collages/artist_collage.php @@ -103,7 +103,7 @@

        - + Edit description @@ -112,9 +112,9 @@ - Remove bookmark + Remove bookmark - Bookmark + Bookmark @@ -205,15 +205,16 @@ if (empty($CommentList)) { $DB->query(" SELECT - cc.ID, - cc.Body, - cc.UserID, + c.ID, + c.Body, + c.AuthorID, um.Username, - cc.Time - FROM collages_comments AS cc - LEFT JOIN users_main AS um ON um.ID = cc.UserID - WHERE CollageID = '$CollageID' - ORDER BY ID DESC + c.AddedTime + FROM comments AS c + LEFT JOIN users_main AS um ON um.ID = c.AuthorID + WHERE c.Page = 'collages' + AND c.PageID = $CollageID + ORDER BY c.ID DESC LIMIT 15"); $CommentList = $DB->to_array(false, MYSQLI_NUM); } @@ -239,10 +240,11 @@ ?>
        Add comment
        -
        - + + + - +
        diff --git a/sections/collages/browse.php b/sections/collages/browse.php index c647b27f..7cd7f9ff 100644 --- a/sections/collages/browse.php +++ b/sections/collages/browse.php @@ -307,7 +307,7 @@ $Row = 'a'; // For the pretty colours foreach ($Collages as $Collage) { list($ID, $Name, $NumTorrents, $TagList, $CategoryID, $UserID, $Subscribers, $Updated) = $Collage; - $Row = ($Row === 'a') ? 'b' : 'a'; + $Row = $Row === 'a' ? 'b' : 'a'; $TorrentTags = new Tags($TagList); //Print results @@ -325,8 +325,8 @@
        format('collages.php?action=search&tags=')?>
        - - + + diff --git a/sections/collages/delete_comment.php b/sections/collages/delete_comment.php deleted file mode 100644 index 5ee7604b..00000000 --- a/sections/collages/delete_comment.php +++ /dev/null @@ -1,48 +0,0 @@ -query(" - SELECT - CollageID, - CEIL(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Pages, - CEIL(SUM(IF(ID <= '$PostID', 1, 0)) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page - FROM collages_comments - WHERE CollageID = ( - SELECT CollageID - FROM collages_comments - WHERE ID = '$PostID' - ) - GROUP BY CollageID"); -list($CollageID, $Pages, $Page) = $DB->next_record(); - -$DB->query(" - DELETE FROM collages_comments - WHERE ID = '$PostID'"); - -$Cache->delete_value("collage_$CollageID"); -$Cache->increment_value("collage_comments_$CollageID", -1); - -//We need to clear all subsequential catalogues as they've all been bumped with the absence of this post -$ThisCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -for ($i = $ThisCatalogue; $i <= $LastCatalogue; $i++) { - $Cache->delete_value("collage_comments_$CollageID"."_catalogue_$i"); -} -?> diff --git a/sections/collages/edit.php b/sections/collages/edit.php index 57fd3e4c..5f015fbf 100644 --- a/sections/collages/edit.php +++ b/sections/collages/edit.php @@ -73,7 +73,7 @@ - Featured + Featured /> query(" - SELECT Body - FROM collages_comments - WHERE ID = '$PostID'"); -list($Body) = $DB->next_record(MYSQLI_NUM); - -// This gets sent to the browser, which echoes it wherever - -echo trim($Body); diff --git a/sections/collages/index.php b/sections/collages/index.php index db18718c..6a0a45bc 100644 --- a/sections/collages/index.php +++ b/sections/collages/index.php @@ -76,21 +76,9 @@ case 'take_delete': require(SERVER_ROOT.'/sections/collages/take_delete.php'); break; - case 'add_comment': - require(SERVER_ROOT.'/sections/collages/add_comment.php'); - break; case 'comments': require(SERVER_ROOT.'/sections/collages/all_comments.php'); break; - case 'takeedit_comment': - require(SERVER_ROOT.'/sections/collages/takeedit_comment.php'); - break; - case 'delete_comment': - require(SERVER_ROOT.'/sections/collages/delete_comment.php'); - break; - case 'get_post': - require(SERVER_ROOT.'/sections/collages/get_post.php'); - break; case 'download': require(SERVER_ROOT.'/sections/collages/download.php'); break; diff --git a/sections/collages/manage.php b/sections/collages/manage.php index 5d4db7c7..aa049741 100644 --- a/sections/collages/manage.php +++ b/sections/collages/manage.php @@ -57,13 +57,12 @@
      • Press "Save All Changes" when you are finished sorting.
      • Press "Edit" or "Remove" to simply modify one entry.
      - @@ -129,7 +128,7 @@
      diff --git a/sections/collages/manage_artists.php b/sections/collages/manage_artists.php index de0f0431..36389c56 100644 --- a/sections/collages/manage_artists.php +++ b/sections/collages/manage_artists.php @@ -51,13 +51,12 @@
    • Press "Save All Changes" when you are finished sorting.
    • Press "Edit" or "Remove" to simply modify one entry.
    - @@ -98,7 +97,7 @@
    diff --git a/sections/collages/take_delete.php b/sections/collages/take_delete.php index db2f6932..622fdb39 100644 --- a/sections/collages/take_delete.php +++ b/sections/collages/take_delete.php @@ -33,21 +33,17 @@ } //Personal collages have CategoryID 0 -if ($CategoryID === '0') { - $DB->query(" - DELETE FROM collages - WHERE ID = '$CollageID'"); - $DB->query(" - DELETE FROM collages_torrents - WHERE CollageID = '$CollageID'"); - $DB->query(" - DELETE FROM collages_comments - WHERE CollageID = '$CollageID'"); +if ($CategoryID == 0) { + $DB->query("DELETE FROM collages WHERE ID = '$CollageID'"); + $DB->query("DELETE FROM collages_torrents WHERE CollageID = '$CollageID'"); + Comments::delete_page('collages', $CollageID); } else { $DB->query(" UPDATE collages SET Deleted = '1' WHERE ID = '$CollageID'"); + Subscriptions::flush_subscriptions('collages', $CollageID); + Subscriptions::flush_quote_notifications('collages', $CollageID); } Misc::write_log("Collage $CollageID ($Name) was deleted by ".$LoggedUser['Username'].": $Reason"); diff --git a/sections/collages/takeedit_comment.php b/sections/collages/takeedit_comment.php deleted file mode 100644 index ba83281a..00000000 --- a/sections/collages/takeedit_comment.php +++ /dev/null @@ -1,64 +0,0 @@ -query(" - SELECT - cc.Body, - cc.UserID, - cc.CollageID, - ( - SELECT COUNT(ID) - FROM collages_comments - WHERE ID <= $PostID - AND collages_comments.CollageID = cc.CollageID - ) - FROM collages_comments AS cc - WHERE cc.ID='$PostID'"); -list($OldBody, $AuthorID, $CollageID, $PostNum) = $DB->next_record(); - -// Make sure they aren't trying to edit posts they shouldn't -// We use die() here instead of error() because whatever we spit out is displayed to the user in the box where his forum post is -if ($UserID != $AuthorID && !check_perms('site_moderate_forums')) { - die('Permission denied'); -} -if (!$DB->has_results()) { - die('Post not found!'); -} - -// Perform the update -$DB->query(" - UPDATE collages_comments - SET - Body = '$Body' - WHERE ID='$PostID'"); - -$Cache->delete_value('collage_'.$CollageID); - - -$PageNum = ceil($PostNum / TORRENT_COMMENTS_PER_PAGE); -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $PageNum - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$Cache->delete_value('collage_comments_'.$CollageID.'_catalogue_'.$CatalogueID); - -$DB->query(" - INSERT INTO comments_edits (Page, PostID, EditUser, EditTime, Body) - VALUES ('collages', $PostID, $UserID, '".sqltime()."', '".db_string($OldBody)."')"); - -// This gets sent to the browser, which echoes it in place of the old body -echo $Text->full_format($_POST['body']); - -?> diff --git a/sections/collages/torrent_collage.php b/sections/collages/torrent_collage.php index ca171baf..d9af705d 100644 --- a/sections/collages/torrent_collage.php +++ b/sections/collages/torrent_collage.php @@ -98,8 +98,8 @@ ?> -
    - +
    +
    @@ -109,9 +109,9 @@ Unbookmark"; + echo "Remove bookmark"; } else { - echo "Bookmark"; + echo "Bookmark"; } echo "\n"; echo Votes::vote_link($GroupID, $UserVotes[$GroupID]['Type']); ?> @@ -135,12 +135,17 @@ } $SnatchedTorrentClass = ($Torrent['IsSnatched'] ? ' snatched_torrent' : ''); - if ($Torrent['RemasterTitle'] != $LastRemasterTitle || $Torrent['RemasterYear'] != $LastRemasterYear || - $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel || $Torrent['RemasterCatalogueNumber'] != $LastRemasterCatalogueNumber || $FirstUnknown || $Torrent['Media'] != $LastMedia) { + if ($Torrent['RemasterTitle'] != $LastRemasterTitle + || $Torrent['RemasterYear'] != $LastRemasterYear + || $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel + || $Torrent['RemasterCatalogueNumber'] != $LastRemasterCatalogueNumber + || $FirstUnknown + || $Torrent['Media'] != $LastMedia + ) { $EditionID++; ?> - + DL - | FL + | FL | RP   »  - - - > - + + + + DL - | FL + | FL | RP @@ -205,14 +210,14 @@
    format()?>
    - - - > - + + + + query(" SELECT - cc.ID, - cc.Body, - cc.UserID, + c.ID, + c.Body, + c.AuthorID, um.Username, - cc.Time - FROM collages_comments AS cc - LEFT JOIN users_main AS um ON um.ID = cc.UserID - WHERE CollageID = '$CollageID' - ORDER BY ID DESC + c.AddedTime + FROM comments AS c + LEFT JOIN users_main AS um ON um.ID = c.AuthorID + WHERE c.Page = 'collages' AND c.PageID = $CollageID + ORDER BY c.ID DESC LIMIT 15"); $CommentList = $DB->to_array(false, MYSQLI_NUM); } @@ -515,10 +520,11 @@ ?>
    Add comment
    - - + + + - +
    diff --git a/sections/comments/artistcomments.php b/sections/comments/artistcomments.php deleted file mode 100644 index e6eaf0c9..00000000 --- a/sections/comments/artistcomments.php +++ /dev/null @@ -1,62 +0,0 @@ -query(" - SELECT - SQL_CALC_FOUND_ROWS - ac.AuthorID, - a.ArtistID, - a.Name, - ac.ID, - ac.Body, - ac.AddedTime, - ac.EditedTime, - ac.EditedUserID as EditorID - FROM artists_group as a - JOIN artist_comments as ac ON ac.ArtistID = a.ArtistID - WHERE ac.AuthorId = $UserID - GROUP BY ac.ID - ORDER BY ac.AddedTime DESC - LIMIT $Limit; -"); - -$DB->query("SELECT FOUND_ROWS()"); -list($Results) = $DB->next_record(); -$Pages = Format::get_pages($Page, $Results, $PerPage, 11); - -$DB->set_query_id($Comments); -$GroupIDs = $DB->collect('GroupID'); - - -View::show_header($Title,'bbcode'); -$DB->set_query_id($Comments); - -?>
    -
    -

    - - - -
    - -next_record()) { - $permalink = "artist.php?id=$ArtistID&postid=$PostID#post$PostID"; - $postheader = ' on ' . "$ArtistName"; - - comment_body($UserID, $PostID, $postheader, $permalink, $Body, $EditorID, $AddedTime, $EditedTime); - -} /* end while loop*/ ?> - -
    -query(" - SELECT - SQL_CALC_FOUND_ROWS - cc.UserID, - c.ID as CollageID, - c.Name, - cc.ID as PostID, - cc.Body, - cc.Time - FROM collages as c - JOIN collages_comments as cc ON cc.CollageID = c.ID - $ExtraJoin - WHERE $Conditions - GROUP BY cc.ID - ORDER BY cc.ID DESC - LIMIT $Limit;"); -$Count = $DB->record_count(); - -$DB->query("SELECT FOUND_ROWS()"); -list($Results) = $DB->next_record(); -$Pages = Format::get_pages($Page, $Results, $PerPage, 11); - -View::show_header($Title,'bbcode'); -$DB->set_query_id($Comments); - -$Links = array(); -$BaseLink = 'comments.php?action=collages' . (!$Self ? '&id='.$UserID : ''); -if ($Mode != 'normal') { - $Links[] = 'Display collage comments ' . ($Self ? 'you\'ve' : $Username . ' has') . ' made'; -} -if ($Mode != 'created') { - $Links[] = 'Display comments left on ' . ($Self ? 'your collages' : 'collages created by ' .$Username) . ''; -} -if ($Mode != 'contributed') { - $Links[] = 'Display comments left on collages ' . ($Self ? 'you\'ve' : $Username . ' has') . ' contributed to'; -} -$Links = implode(' ', $Links); - -?>
    -
    -

    - - - -
    - - 0) { - while (list($UserID, $CollageID, $Name, $PostID, $Body, $AddedTime) = $DB->next_record()) { - $permalink = "collages.php?action=comments&collageid=$CollageID&postid=$PostID#post$PostID"; - $postheader = " on $Name"; - comment_body($UserID, $PostID, $postheader, $permalink, $Body, 0, $AddedTime, 0); - } -} else { ?> -
    No results.
    - - -
    - torrents.Time'; + $Conditions[] = "comments.AuthorID != $UserID"; + $Title = 'Comments left on torrents ' . ($Self ? 'you\'ve' : $Username . ' has') . ' uploaded'; + $Header = 'Comments left on torrents ' . ($Self ? 'you\'ve' : Users::format_username($UserID, false, false, false) . ' has') . ' uploaded'; + } else { + $Type = 'default'; + $Conditions[] = "comments.AuthorID = $UserID"; + $Title = 'Torrent comments left by ' . ($Self ? 'you' : $Username); + $Header = 'Torrent comments left by ' . ($Self ? 'you' : Users::format_username($UserID, false, false, false)); + } + break; +} +$Join[] = "JOIN comments ON comments.Page = '$Action' AND comments.PageID = $Field1"; +$Join = implode("\n\t\t", $Join); +$Conditions = implode(" AND ", $Conditions); +$Conditions = ($Conditions ? 'WHERE ' . $Conditions : ''); + +$SQL = " + SELECT + SQL_CALC_FOUND_ROWS + comments.AuthorID, + comments.Page, + comments.PageID, + $Field2, + comments.ID, + comments.Body, + comments.AddedTime, + comments.EditedTime, + comments.EditedUserID + FROM $Table + $Join + $Conditions + GROUP BY comments.ID + ORDER BY comments.ID DESC + LIMIT $Limit"; + +$Comments = $DB->query($SQL); +$Count = $DB->record_count(); + +$DB->query("SELECT FOUND_ROWS()"); +list($Results) = $DB->next_record(); +$Pages = Format::get_pages($Page, $Results, $PerPage, 11); + +$DB->set_query_id($Comments); +if ($Action == 'requests') { + $RequestIDs = array_flip(array_flip($DB->collect('PageID'))); + $Artists = array(); + foreach ($RequestIDs as $RequestID) { + $Artists[$RequestID] = Requests::get_artists($RequestID); + } + $DB->set_query_id($Comments); +} elseif ($Action == 'torrents') { + $GroupIDs = array_flip(array_flip($DB->collect('PageID'))); + $Artists = Artists::get_artists($GroupIDs); + $DB->set_query_id($Comments); +} + +$LinkID = (!$Self ? '&id=' . $UserID : ''); +$ActionLinks = $TypeLinks = array(); +if ($Action != 'artist') { + $ActionLinks[] = 'Artist comments'; +} +if ($Action != 'collages') { + $ActionLinks[] = 'Collage comments'; +} +if ($Action != 'requests') { + $ActionLinks[] = 'Request comments'; +} +if ($Action != 'torrents') { + $ActionLinks[] = 'Torrent comments'; +} +switch ($Action) { + case 'collages': + $BaseLink = 'comments.php?action=collages' . $LinkID; + if ($Type != 'default') { + $TypeLinks[] = 'Display collage comments ' . ($Self ? 'you\'ve' : $Username . ' has') . ' made'; + } + if ($Type != 'created') { + $TypeLinks[] = 'Display comments left on ' . ($Self ? 'your collages' : 'collages created by ' .$Username) . ''; + } + if ($Type != 'contributed') { + $TypeLinks[] = 'Display comments left on collages ' . ($Self ? 'you\'ve' : $Username . ' has') . ' contributed to'; + } + break; + case 'requests': + $BaseLink = 'comments.php?action=requests' . $LinkID; + if ($Type != 'default') { + $TypeLinks[] = 'Display request comments you\'ve made'; + } + if ($Type != 'created') { + $TypeLinks[] = 'Display comments left on your requests'; + } + if ($Type != 'voted') { + $TypeLinks[] = 'Display comments left on requests you\'ve voted on'; + } + break; + case 'torrents': + if ($Type != 'default') { + $TypeLinks[] = 'Display comments you have made'; + } + if ($Type != 'uploaded') { + $TypeLinks[] = 'Display comments left on your uploads'; + } + break; +} +$Links = implode(' ', $ActionLinks) . (count($TypeLinks) ? '
    ' . implode(' ', $TypeLinks) : ''); + +View::show_header($Title, 'bbcode,comments'); +?>
    +
    +

    + + + +
    + + 0) { + $DB->set_query_id($Comments); + while (list($AuthorID, $Page, $PageID, $Name, $PostID, $Body, $AddedTime, $EditedTime, $EditedUserID) = $DB->next_record()) { + $Link = Comments::get_url($Page, $PageID, $PostID); + switch ($Page) { + case 'artist': + $Header = " on $Name"; + break; + case 'collages': + $Header = " on $Name"; + break; + case 'requests': + $Header = ' on ' . Artists::display_artists($Artists[$PageID]) . " $Name"; + break; + case 'torrents': + $Header = ' on ' . Artists::display_artists($Artists[$PageID]) . " $Name"; + break; + } + CommentsView::render_comment($AuthorID, $PostID, $Body, $AddedTime, $EditedUserID, $EditedTime, $Link, false, $Header, false); + } +} else { ?> +
    No results.
    + + +
    +query(" + SELECT Body + FROM comments + WHERE ID = $PostID"); +list($Body) = $DB->next_record(MYSQLI_NUM); + +echo trim($Body); \ No newline at end of file diff --git a/sections/comments/index.php b/sections/comments/index.php index 36aa2cca..60f91160 100644 --- a/sections/comments/index.php +++ b/sections/comments/index.php @@ -1,67 +1,46 @@ -' . Users::format_username($UserID, true, true, true, true, false) . ' ' - . time_diff($AddedTime) . $postheader; - -?> - - - - - - - - - - - - - - - - -
    - # - - -
    - - - full_format($Body) ?> - -

    - Last edited by - - -
    -query(" - SELECT - SQL_CALC_FOUND_ROWS - rc.AuthorID, - r.ID as RequestID, - r.Title, - rc.ID as PostID, - rc.Body, - rc.AddedTime, - rc.EditedTime, - rc.EditedUserID as EditorID - FROM requests as r - JOIN requests_comments as rc ON rc.RequestID = r.ID - $ExtraJoin - $Conditions - GROUP BY rc.ID - ORDER BY rc.AddedTime DESC - LIMIT $Limit;"); -$Count = $DB->record_count(); - -$DB->query("SELECT FOUND_ROWS()"); -list($Results) = $DB->next_record(); -$Pages = Format::get_pages($Page, $Results, $PerPage, 11); - -View::show_header($Title,'bbcode'); -$DB->set_query_id($Comments); - -$Links = array(); -$BaseLink = 'comments.php?action=requests' . (!$Self ? '&id='.$UserID : ''); -if ($Mode != 'normal') { - $Links[] = 'Display request comments you\'ve made'; -} -if ($Mode != 'created') { - $Links[] = 'Display comments left on your requests'; -} -if ($Mode != 'voted') { - $Links[] = 'Display comments left on requests you\'ve voted on'; -} -$Links = implode(' ', $Links); - -?>
    -
    -

    - - - -
    - - 0) { - while (list($UserID, $RequestID, $Title, $PostID, $Body, $AddedTime, $EditedTime, $EditorID) = $DB->next_record()) { - $Artists = Requests::get_artists($RequestID); - $permalink = "requests.php?action=view&id=$RequestID&postid=$PostID#post$PostID"; - $postheader = " on " . Artists::display_artists($Artists) . " $Title"; - comment_body($UserID, $PostID, $postheader, $permalink, $Body, $EditorID, $AddedTime, $EditedTime); - $DB->set_query_id($Comments); - } -} else { ?> -
    No results.
    - - -
    -full_format($_POST['body']); \ No newline at end of file diff --git a/sections/comments/take_post.php b/sections/comments/take_post.php new file mode 100644 index 00000000..c0c6f2dd --- /dev/null +++ b/sections/comments/take_post.php @@ -0,0 +1,25 @@ +query(" + SELECT AuthorID + FROM comments + WHERE ID = $PostID"); +if (!$DB->has_results()) { + error(404); +} +list($AuthorID) = $DB->next_record(); + +$UserInfo = Users::user_info($AuthorID); +if ($UserInfo['Class'] > $LoggedUser['Class']) { + error(403); +} + +$URL = 'https://' . SSL_SITE_URL . '/' . Comments::get_url_query($PostID); +if ($Length != 'verbal') { + $Time = ((int)$Length) * (7 * 24 * 60 * 60); + Tools::warn_user($AuthorID, $Time, "$URL - $Reason"); + $Subject = 'You have received a warning'; + $PrivateMessage = "You have received a $Length week warning for [url=$URL]this comment.[/url]\n\n$PrivateMessage"; + $WarnTime = time_plus($Time); + $AdminComment = date('Y-m-d') . " - Warned until $WarnTime by " . $LoggedUser['Username'] . "\nReason: $URL - $Reason\n\n"; +} else { + $Subject = 'You have received a verbal warning'; + $PrivateMessage = "You have received a verbal warning for [url=$URL]this comment.[/url]\n\n$PrivateMessage"; + $AdminComment = date('Y-m-d') . ' - Verbally warned by ' . $LoggedUser['Username'] . " for $URL \nReason: $Reason\n\n"; + Tools::update_user_notes($AuthorID, $AdminComment); +} +$DB->query(" + INSERT INTO users_warnings_forums (UserID, Comment) + VALUES('$AuthorID', '" . db_string($AdminComment) . "') + ON DUPLICATE KEY UPDATE Comment = CONCAT('" . db_string($AdminComment) . "', Comment)"); +Misc::send_pm($AuthorID, $LoggedUser['ID'], $Subject, $PrivateMessage); + +Comments::edit($PostID, $Body); + +header("Location: $URL"); diff --git a/sections/comments/torrentcomments.php b/sections/comments/torrentcomments.php deleted file mode 100644 index 7ad5f348..00000000 --- a/sections/comments/torrentcomments.php +++ /dev/null @@ -1,91 +0,0 @@ -Artist comments Collage comments Request comments
    '; - -if ($MyTorrents) { - $Conditions = "WHERE t.UserID = $UserID AND tc.AuthorID != t.UserID AND tc.AddedTime > t.Time"; - $Title = 'Comments left on your torrents'; - $Header = 'Comments left on your uploads'; - if ($Self) { - $OtherLink .= 'Display comments you have made'; - } -} else { - $Conditions = "WHERE tc.AuthorID = $UserID"; - $Title = 'Comments made by '.($Self?'you':$Username); - $Header = 'Torrent comments left by '.($Self?'you':Users::format_username($UserID, false, false, false)).''; - if ($Self) { - $OtherLink .= 'Display comments left on your uploads'; - } -} - -$Comments = $DB->query(" - SELECT - SQL_CALC_FOUND_ROWS - tc.AuthorID, - t.ID, - t.GroupID, - tg.Name, - tc.ID, - tc.Body, - tc.AddedTime, - tc.EditedTime, - tc.EditedUserID as EditorID - FROM torrents as t - JOIN torrents_comments as tc ON tc.GroupID = t.GroupID - JOIN torrents_group as tg ON t.GroupID = tg.ID - $Conditions - GROUP BY tc.ID - ORDER BY tc.AddedTime DESC - LIMIT $Limit; -"); - -$DB->query("SELECT FOUND_ROWS()"); -list($Results) = $DB->next_record(); -$Pages = Format::get_pages($Page, $Results, $PerPage, 11); - -$DB->set_query_id($Comments); -$GroupIDs = $DB->collect('GroupID'); - -$Artists = Artists::get_artists($GroupIDs); - -View::show_header($Title,'bbcode'); -$DB->set_query_id($Comments); - -?>
    -
    -

    - - - -
    - -next_record()) { - $permalink = "torrents.php?id=$GroupID&postid=$PostID#post$PostID"; - $postheader = ' on ' . Artists::display_artists($Artists[$GroupID]) . " $Title"; - - comment_body($UserID, $PostID, $postheader, $permalink, $Body, $EditorID, $AddedTime, $EditedTime); - -} /* end while loop*/ ?> - -
    -query(" + SELECT Body, AuthorID + FROM comments + WHERE ID = $PostID"); +if (!$DB->has_results()) { + error(404); +} +list($PostBody, $AuthorID) = $DB->next_record(); +$UserInfo = Users::user_info($AuthorID); + +View::show_header('Warn User'); +?> + +
    +
    +

    Warning

    +
    +
    + + + + + + + + + + + + + + + + + + + + +
    Reason: + +
    Length: +
    Private message: + +
    Edit post: + +
    + +
    + +
    +
    + -
    - -
    -

    Test IPN

    -
    -
    - -
    - -
    -

    Donate

    -
    -
    -

    We accept donations to cover the costs associated with running the site and tracker. These costs come from the rental and purchase of the hardware the site runs on (servers, components, etc.), in addition to operating expenses (bandwidth, power, etc.).

    -

    Because we do not have any advertisements or sponsorships and this service is provided free of charge, we are entirely reliant upon user donations. If you are financially able, please consider making a donation to help us pay the bills!

    -

    We currently only accept one payment method: PayPal. Because of the fees they charge, there is a minimum donation amount of (Please note, this is only a minimum amount and we greatly appreciate any extra you can afford.).

    -

    You don't have to be a PayPal member to make a donation, you can simply donate with your credit or debit card. If you do not have a credit or debit card, you should be able to donate from your bank account, but you will need to make an account with them to do this.

    - + Why donate? +
    + has no advertisements, is not sponsored, and provides its services free of charge. For these reasons, 's financial obligations can only be met with the help of voluntary user donations. Supporting is and will always remain voluntary. If you are financially able, help pay 's bills by donating. 's survival is up to you.
    +
    + uses all voluntary donations to cover the costs of running the site, tracker, and IRC network. These costs represent the hardware the site runs on (e.g., servers, upgrades, fixes, etc.), and recurring operating expenses (e.g., hosting, bandwidth, power, etc.).
    +
    + Please note that is a nonprofit organization. No staff member or other individual responsible for the site's operation personally profits from user donations. As a donor, your financial support is exclusively applied to operating costs. When you donate you aren't paying the Staff, purchasing upload credit, or buying the ability to download. When you donate you are paying 's bills.
    +
    + 's Donor Rank system is currently available to all credited donors. This system provides donors with perks. Some of these perks are cosmetic (e.g., a donor icon added to your account), some are one-time benefits (e.g., additional invites), and others modify specific site options (e.g., additional profile information boxes, or personal collages). Please see the Donor Rank System FAQ Document for more information about these benefits.
    -

    What you will receive for a 5€ or 0.1 BTC minimum donation

    -
    -
      - -
    • Even more love! (You will not get multiple hearts.)
    • -
    • A warmer, fuzzier feeling than before!
    • - -
    • Our eternal love, as represented by the Donor you get next to your name.
    • -= USER_LIMIT && !check_perms('site_can_invite_always') && !isset($DonorPerms['site_can_invite_always'])) { -?> -
    • Note: Because the user limit has been reached, you will be unable to use the invites received until a later date.
    • - -
    • A warm fuzzy feeling.
    • - -
    -

    Please be aware that by making a donation you aren't purchasing donor status or invites. You are helping us pay the bills and cover the costs of running the site. We are doing our best to give our love back to donors, but sometimes it might take more than 48 hours. Feel free to contact us by sending us a Staff PM regarding any matter. We will answer as quickly as possible.

    + What you will receive for donating +
    + Any donation or contribution option listed above gives you the opportunity to receive Donor Points. After acquiring your first Donor Point, your account will unlock Donor Rank #1. This rank will last forever, and you'll receive the following perks upon unlocking it:
    +
    +
    • Our eternal love, as represented by the red heart you get next to your name
    • Inactivity timer immunity
    • Access to the notifications system
    • Two invites
    • Collage creation privileges
    • Personal collage creation privileges
    • One additional personal collage
    • A warm, fuzzy feeling

    + There are a number of additional perks waiting for you when you unlock additional Donor Ranks. View the FAQ or infographic below for more information about these perks.
    +
    +
    +
    + Be reminded that when you make a donation, you aren't "purchasing" Donor Ranks, invites, or any -specific benefit. When donating, you are helping pay its bills, and your donation should be made in this spirit. The Staff does its best to recognize 's financial supporters in a fair and fun way, but all Donor Perks are subject to change or cancellation at any time, without notice.
    -

    What you will not receive

    -
    -
      - -
    • 2 more invitations; these are one time only.
    • - -
    • Immunity from the rules.
    • -
    • Additional upload credit.
    • -
    + + What you won't receive for donating +
    +
    • Immunity from the rules
    • Additional upload credit
    diff --git a/sections/feeds/index.php b/sections/feeds/index.php index c7fbc03d..0255cc82 100644 --- a/sections/feeds/index.php +++ b/sections/feeds/index.php @@ -4,15 +4,15 @@ // Bear this in mind when you try to use script_start functions. if ( - empty($_GET['feed']) || - empty($_GET['authkey']) || - empty($_GET['auth']) || - empty($_GET['passkey']) || - empty($_GET['user']) || - !is_number($_GET['user']) || - strlen($_GET['authkey']) != 32 || - strlen($_GET['passkey']) != 32 || - strlen($_GET['auth']) != 32 + empty($_GET['feed']) + || empty($_GET['authkey']) + || empty($_GET['auth']) + || empty($_GET['passkey']) + || empty($_GET['user']) + || !is_number($_GET['user']) + || strlen($_GET['authkey']) != 32 + || strlen($_GET['passkey']) != 32 + || strlen($_GET['auth']) != 32 ) { $Feed->open_feed(); $Feed->channel('Blocked', 'RSS feed.'); diff --git a/sections/forums/ajax_get_edit.php b/sections/forums/ajax_get_edit.php index d4bb1e66..10a39e6d 100644 --- a/sections/forums/ajax_get_edit.php +++ b/sections/forums/ajax_get_edit.php @@ -54,8 +54,8 @@ case 'torrents' : $DB->query(" SELECT Body - FROM {$Type}_comments - WHERE ID = $PostID"); + FROM comments + WHERE Page = '$Type' AND ID = $PostID"); list($Body) = $DB->next_record(); break; } diff --git a/sections/forums/delete.php b/sections/forums/delete.php index 79be5fbe..3d31ffc4 100644 --- a/sections/forums/delete.php +++ b/sections/forums/delete.php @@ -139,4 +139,9 @@ $Cache->commit_transaction(); $Cache->delete_value("forums_$ForumID"); -?> + +Subscriptions::flush_subscriptions('forums', $TopicID); + +// quote notifications +Subscriptions::flush_quote_notifications('forums', $TopicID); +$DB->query("DELETE FROM users_notify_quoted WHERE Page = 'forums' AND PostID = '" . $PostID . "'"); diff --git a/sections/forums/forum.php b/sections/forums/forum.php index 5482f2b1..6043761f 100644 --- a/sections/forums/forum.php +++ b/sections/forums/forum.php @@ -16,6 +16,9 @@ error(0); } +$IsDonorForum = $ForumID == DONOR_FORUM ? true : false; +$Tooltip = $ForumID == DONOR_FORUM ? "tooltip_gold" : "tooltip"; + if (isset($LoggedUser['PostsPerPage'])) { $PerPage = $LoggedUser['PostsPerPage']; } else { @@ -72,17 +75,17 @@ $ForumName = display_str($Forums[$ForumID]['Name']); -if ($LoggedUser['CustomForums'][$ForumID] != 1 && $Forums[$ForumID]['MinClassRead'] > $LoggedUser['Class']) { +if (!Forums::check_forumperm($ForumID)) { error(403); } // Start printing -View::show_header('Forums > '. $Forums[$ForumID]['Name']); +View::show_header('Forums > '. $Forums[$ForumID]['Name'], '', $IsDonorForum ? 'donor' : ''); ?>

    Forums >

    - - -query(" - SELECT ForumID - FROM subscribed_forums - WHERE ForumID='$ForumID' - AND SubscriberID='$LoggedUser[ID]'"); - if (!$DB->has_results()) { ?> - Subscribe to forum - - Unsubscribe from forum - -
    diff --git a/sections/tools/data/bitcoin_balance.php b/sections/tools/data/bitcoin_balance.php index b16d7e0d..1e9f2e89 100644 --- a/sections/tools/data/bitcoin_balance.php +++ b/sections/tools/data/bitcoin_balance.php @@ -3,19 +3,17 @@ error(403); } -include(SERVER_ROOT.'/sections/donate/config.php'); - View::show_header('Bitcoin donation balance'); -$Balance = btc_balance() . ' BTC'; -$BitcoinAddresses = btc_received(); - +$Balance = DonationsBitcoin::get_balance() . ' BTC'; +$BitcoinAddresses = DonationsBitcoin::get_received(); $Debug->log_var($BitcoinAddresses, 'Bitcoin addresses'); -$DB->query(" + +$UserQ = $DB->query(" SELECT i.UserID, i.BitcoinAddress FROM users_info AS i JOIN users_main AS m ON m.ID = i.UserID - WHERE BitcoinAddress IS NOT NULL + WHERE BitcoinAddress != '' ORDER BY m.Username ASC"); ?>
    @@ -40,6 +38,7 @@ BTC set_query_id($UserQ); } ?> diff --git a/sections/tools/data/donation_log.php b/sections/tools/data/donation_log.php index afbeb7c5..a14743f8 100644 --- a/sections/tools/data/donation_log.php +++ b/sections/tools/data/donation_log.php @@ -1,4 +1,5 @@ -query($sql); -$Donations = $DB->to_array(false,MYSQLI_NUM); +$DB->query($SQL); +$Donations = $DB->to_array(); $DB->query('SELECT FOUND_ROWS()'); list($Results) = $DB->next_record(); -if (empty($_GET['search']) && !isset($_GET['page']) && !$DonationTimeline = $Cache->get_value('donation_timeline')) { +$DB->query("SELECT SUM(Amount) FROM donations"); +list($Total) = $DB->next_record(); + +if (empty($_GET['email']) && empty($_GET['username']) && empty($_GET['source']) && !isset($_GET['page']) && !$DonationTimeline = $Cache->get_value('donation_timeline')) { include(SERVER_ROOT.'/classes/charts.class.php'); $DB->query(" SELECT DATE_FORMAT(Time,'%b \'%y') AS Month, SUM(Amount) @@ -55,7 +92,7 @@ } View::show_header('Donation log'); -if (empty($_GET['search']) && !isset($_GET['page'])) { +if (empty($_GET['email']) && empty($_GET['source']) && empty($_GET['username']) && !isset($_GET['page'])) { ?>
    Donation timeline. The "y" axis is donation amount. @@ -64,13 +101,35 @@
    + + + + + + + + + + + + + + + + @@ -89,19 +148,29 @@ + + - - - - - - + $PageTotal += $Donation['Amount']; ?> + + + + + + + + + + + + + +
    Username: + +
    Email: - - -   + +
    Source: + +
    Date Range: + + +
    User Amount EmailSourceReason Time
    ()
    Page TotalTotal
    diff --git a/sections/top10/donors.php b/sections/top10/donors.php new file mode 100644 index 00000000..584fabbd --- /dev/null +++ b/sections/top10/donors.php @@ -0,0 +1,98 @@ + +
    +
    +

    Top Donors

    + +
    +query(" + SELECT + UserID, TotalRank, Rank, SpecialRank, DonationTime, Hidden + FROM users_donor_ranks + WHERE TotalRank > 0 + ORDER BY TotalRank DESC + LIMIT $Limit"); + +$Results = $DB->to_array(); + +generate_user_table('Top Donors', $Results, $Limit); + + +echo '
    '; +View::show_footer(); + +// generate a table based on data from most recent query to $DB +function generate_user_table($Caption, $Results, $Limit) { + global $Time, $IsMod; +?> +

    Top + + + - Top 10 + - Top 100 + - Top 250 + + - Top 10 + - Top 100 + - Top 250 + + - Top 10 + - Top 100 + - Top 250 + + +

    + + + + + + + + + + + + +
    PositionUserTotal Donor PointsCurrent Donor RankLast Donated
    + Found no users matching the criteria +

    '; + } + $Position = 0; + foreach ($Results as $Result) { + $Position++; + $Highlight = ($Position % 2 ? 'a' : 'b'); +?> + + + + + + + + +
    + diff --git a/sections/top10/history.php b/sections/top10/history.php index f88f5dd1..d08c6a55 100644 --- a/sections/top10/history.php +++ b/sections/top10/history.php @@ -99,7 +99,7 @@
    -

    Top 10 for

    +

    Top 10 for

    @@ -107,7 +107,7 @@ $GroupName"; + $DisplayName .= "$GroupName"; if ($GroupCategoryID == 1 && $GroupYear > 0) { $DisplayName .= " [$GroupYear]"; @@ -172,10 +172,10 @@ $DisplayName .= $ExtraInfo; $TorrentTags = new Tags($TorrentTags); - else: + } else { $DisplayName = "$TitleString (Deleted)"; $TorrentTags = new Tags($TagString); - endif; + } // if ($GroupID) ?> @@ -188,7 +188,7 @@
    Name

    diff --git a/sections/top10/index.php b/sections/top10/index.php index 95e7d2e8..aa9da84a 100644 --- a/sections/top10/index.php +++ b/sections/top10/index.php @@ -29,6 +29,9 @@ case 'votes' : include(SERVER_ROOT.'/sections/top10/votes.php'); break; + case 'donors' : + include(SERVER_ROOT.'/sections/top10/donors.php'); + break; default : error(404); break; diff --git a/sections/top10/tags.php b/sections/top10/tags.php index a9d43ead..b86d99c2 100644 --- a/sections/top10/tags.php +++ b/sections/top10/tags.php @@ -20,6 +20,7 @@ Users Tags Favorites + Donors
    @@ -96,7 +97,7 @@ exit; // generate a table based on data from most recent query to $DB -function generate_tag_table($Caption, $Tag, $Details, $Limit, $ShowVotes=true, $RequestsTable = false) { +function generate_tag_table($Caption, $Tag, $Details, $Limit, $ShowVotes = true, $RequestsTable = false) { if ($RequestsTable) { $URLString = 'requests.php?tags='; } else { @@ -156,10 +157,10 @@ function generate_tag_table($Caption, $Tag, $Details, $Limit, $ShowVotes=true, $ - + - - + + Users Tags Favorites + Donors
    -

    Top +

    Top $GroupName"; + $DisplayName .= "$GroupName"; if ($GroupCategoryID == 1 && $GroupYear > 0) { - $DisplayName.= " [$GroupYear]"; + $DisplayName .= " [$GroupYear]"; } if ($GroupCategoryID == 1 && $ReleaseType > 0) { - $DisplayName.= ' ['.$ReleaseTypes[$ReleaseType].']'; + $DisplayName .= ' ['.$ReleaseTypes[$ReleaseType].']'; } // append extra info to torrent title @@ -492,42 +493,42 @@ function generate_torrent_table($Caption, $Tag, $Details, $Limit) { $AddExtra = ''; if (empty($GroupBy)) { if ($Format) { - $ExtraInfo.= $Format; + $ExtraInfo .= $Format; $AddExtra = ' / '; } if ($Encoding) { - $ExtraInfo.= $AddExtra.$Encoding; + $ExtraInfo .= $AddExtra.$Encoding; $AddExtra = ' / '; } // "FLAC / Lossless / Log (100%) / Cue / CD"; if ($HasLog) { - $ExtraInfo.= $AddExtra.'Log ('.$LogScore.'%)'; + $ExtraInfo .= $AddExtra.'Log ('.$LogScore.'%)'; $AddExtra = ' / '; } if ($HasCue) { - $ExtraInfo.= $AddExtra.'Cue'; + $ExtraInfo .= $AddExtra.'Cue'; $AddExtra = ' / '; } if ($Media) { - $ExtraInfo.= $AddExtra.$Media; + $ExtraInfo .= $AddExtra.$Media; $AddExtra = ' / '; } if ($Scene) { - $ExtraInfo.= $AddExtra.'Scene'; + $ExtraInfo .= $AddExtra.'Scene'; $AddExtra = ' / '; } if ($Year > 0) { - $ExtraInfo.= $AddExtra.$Year; + $ExtraInfo .= $AddExtra.$Year; $AddExtra = ' '; } if ($RemasterTitle) { - $ExtraInfo.= $AddExtra.$RemasterTitle; + $ExtraInfo .= $AddExtra.$RemasterTitle; } if ($IsSnatched) { if ($GroupCategoryID == 1) { $ExtraInfo .= ' / '; } - $ExtraInfo.= Format::torrent_label('Snatched!'); + $ExtraInfo .= Format::torrent_label('Snatched!'); } if ($ExtraInfo != '') { $ExtraInfo = "- [$ExtraInfo]"; @@ -549,37 +550,37 @@ function generate_torrent_table($Caption, $Tag, $Details, $Limit) {
    - +
    - +
    DL - - Reported + - Reported - Unbookmark + Remove bookmark - Bookmark + Bookmark
    format()?>
    - - - - - - + + + + + +
    Users Tags Favorites + Donors

    "> - - /s - - /s - - - + + /s + + /s + + + - +
    Users Tags Favorites + Donors
    1 || $GroupCategoryID == 1) : + if (count($Torrents) > 1 || $GroupCategoryID == 1) { // Grouped torrents $GroupSnatched = false; foreach ($Torrents as &$Torrent) { @@ -210,32 +211,32 @@ ?> -
    - +
    +
    - +
    - + - upvotes out of total (Score: ). + upvotes out of total (Score: ). $Torrent) : + foreach ($Torrents as $TorrentID => $Torrent) { //Get report info, use the cache if available, if not, add to it. $Reported = false; $Reports = Torrents::get_reports($TorrentID); @@ -259,12 +260,17 @@ } $SnatchedTorrentClass = $Torrent['IsSnatched'] ? ' snatched_torrent' : ''; - if ($Torrent['RemasterTitle'] != $LastRemasterTitle || $Torrent['RemasterYear'] != $LastRemasterYear || - $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel || $Torrent['RemasterCatalogueNumber'] != $LastRemasterCatalogueNumber || $FirstUnknown || $Torrent['Media'] != $LastMedia) { + if ($Torrent['RemasterTitle'] != $LastRemasterTitle + || $Torrent['RemasterYear'] != $LastRemasterYear + || $Torrent['RemasterRecordLabel'] != $LastRemasterRecordLabel + || $Torrent['RemasterCatalogueNumber'] != $LastRemasterCatalogueNumber + || $FirstUnknown + || $Torrent['Media'] != $LastMedia + ) { $EditionID++; ?> - + [ DL - | FL + | FL | RP ] -   »  / Reported +   »  / Reported - - - > - + + + + 1 || $GroupCategoryID == 1) // Viewing a type that does not require grouping list($TorrentID, $Torrent) = each($Torrents); @@ -318,22 +324,22 @@
    - +
    - +
    [ DL - | FL + | FL | RP - | Unbookmark + | Remove bookmark - | Bookmark + | Bookmark ] @@ -341,13 +347,13 @@
    format()?>
    - - - > - + + + + 1 || $GroupCategoryID == 1) $TorrentTable .= ob_get_clean(); } ?> diff --git a/sections/torrents/browse.php b/sections/torrents/browse.php index e8a11d71..99078ccb 100644 --- a/sections/torrents/browse.php +++ b/sections/torrents/browse.php @@ -468,7 +468,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { } $Tags = explode(',', $_GET['searchtags']); - foreach ($Tags as $Key => $Tag) : + foreach ($Tags as $Key => $Tag) { if (trim($Tag) != '') { if ($TagSearch != '') { if ($_GET['tags_type']) { @@ -489,7 +489,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { $TagSearch .= "$TagField LIKE '%".db_string($Tag)."%'"; } } - endforeach; + } //foreach if ($TagSearch != '') { if ($DisableGrouping) { @@ -722,7 +722,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') {
    @@ -817,7 +817,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { - + - + @@ -866,7 +866,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { $CatName) : +foreach ($Categories as $CatKey => $CatName) { if ($x % 8 == 0 || $x == 1) { ?> @@ -875,13 +875,12 @@ function header_link($SortKey, $DefaultWay = 'DESC') { checked="checked" /> - + -
    Search terms: @@ -827,11 +827,11 @@ function header_link($SortKey, $DefaultWay = 'DESC') {
    Tags (comma-separated): -   +   checked="checked" />    checked="checked" />
    @@ -899,7 +898,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { } $x = 0; -foreach ($GenreTags as $Tag) : +foreach ($GenreTags as $Tag) { ?> @@ -930,7 +929,8 @@ function header_link($SortKey, $DefaultWay = 'DESC') {    - @@ -948,7 +948,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { - + @@ -1032,7 +1032,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { $DisplayName = Artists::display_artists($Artists[$GroupID]); if ((count($Torrents['id']) > 1 || $GroupCategoryID == 1) && !$DisableGrouping) { // These torrents are in a group - $DisplayName .= "$GroupName"; + $DisplayName .= "$GroupName"; if ($GroupYear > 0) { $DisplayName .= " [$GroupYear]"; } @@ -1044,28 +1044,29 @@ function header_link($SortKey, $DefaultWay = 'DESC') { +if ($LoggedUser['CoverArt']) { ?>
    - +
    -
    - Bookmark + Bookmark
    format('torrents.php?searchtags=')?>
    - - - - > - + + + + + $Val) : + foreach ($Torrents['id'] as $Key => $Val) { // All of the individual torrents in the group // If they're using the advanced search and have chosen enabled grouping, we just skip the torrents that don't check out @@ -1173,20 +1174,20 @@ function header_link($SortKey, $DefaultWay = 'DESC') { » - - - - > - + + + + + $Val) } else { // Either grouping is disabled, or we're viewing a type that does not require grouping if ($GroupCategoryID == 1) { - $DisplayName .= ''.$GroupName.''; + $DisplayName .= ''.$GroupName.''; } else { - $DisplayName .= ''.$GroupName.''; + $DisplayName .= ''.$GroupName.''; } $ExtraInfo = ''; @@ -1251,11 +1252,11 @@ function header_link($SortKey, $DefaultWay = 'DESC') { - - - - > - + + + + + Click here to toggle searching for specific remaster information @@ -1020,8 +1023,8 @@ function header_link($SortKey, $DefaultWay = 'desc') { $ShowGroups = !(!empty($LoggedUser['TorrentGrouping']) && $LoggedUser['TorrentGrouping'] == 1); ?> - - - - > - + + + + + - + [ - | FL + | FL | RP ] - » / Reported + » / Reported - - - > - + + + + title()?>" class="css_name()?>"> - - - - > - + + + + + - - + + Delete + /> - + Warning - - + + Upload + /> @@ -277,10 +277,10 @@ diff --git a/sections/torrents/details.php b/sections/torrents/details.php index 0e732240..6a957c7d 100644 --- a/sections/torrents/details.php +++ b/sections/torrents/details.php @@ -11,7 +11,7 @@ function compare($X, $Y) { $Text = NEW TEXT; -$GroupID=ceil($_GET['id']); +$GroupID = ceil($_GET['id']); if (!empty($_GET['revisionid']) && is_number($_GET['revisionid'])) { $RevisionID = $_GET['revisionid']; } else { @@ -37,32 +37,32 @@ function compare($X, $Y) { $Artists = Artists::get_artist($GroupID); if ($Artists) { - $DisplayName = ''.Artists::display_artists($Artists, true).$DisplayName.''; - $AltName = display_str(Artists::display_artists($Artists, false)).$AltName; + $DisplayName = ''.Artists::display_artists($Artists, true) . "$DisplayName"; + $AltName = display_str(Artists::display_artists($Artists, false)) . $AltName; $Title = $AltName; } if ($GroupYear > 0) { - $DisplayName.= " [$GroupYear]"; - $AltName.= " [$GroupYear]"; - $Title.= " [$GroupYear]"; + $DisplayName .= " [$GroupYear]"; + $AltName .= " [$GroupYear]"; + $Title .= " [$GroupYear]"; } if ($GroupVanityHouse) { - $DisplayName.=' [Vanity House]'; - $AltName.=' [Vanity House]'; + $DisplayName .= ' [Vanity House]'; + $AltName .= ' [Vanity House]'; } if ($GroupCategoryID == 1) { - $DisplayName.=' ['.$ReleaseTypes[$ReleaseType].']'; - $AltName.=' ['.$ReleaseTypes[$ReleaseType].']'; + $DisplayName .= ' ['.$ReleaseTypes[$ReleaseType].']'; + $AltName .= ' ['.$ReleaseTypes[$ReleaseType].']'; } $Tags = array(); if ($TorrentTags != '') { - $TorrentTags = explode('|',$TorrentTags); - $TorrentTagIDs = explode('|',$TorrentTagIDs); - $TorrentTagUserIDs = explode('|',$TorrentTagUserIDs); - $TagPositiveVotes = explode('|',$TagPositiveVotes); - $TagNegativeVotes = explode('|',$TagNegativeVotes); + $TorrentTags = explode('|', $TorrentTags); + $TorrentTagIDs = explode('|', $TorrentTagIDs); + $TorrentTagUserIDs = explode('|', $TorrentTagUserIDs); + $TagPositiveVotes = explode('|', $TagPositiveVotes); + $TagNegativeVotes = explode('|', $TagNegativeVotes); foreach ($TorrentTags as $TagKey => $TagName) { $Tags[$TagKey]['name'] = $TagName; @@ -80,7 +80,7 @@ function compare($X, $Y) { die(); }*/ -$CoverArt = $Cache->get_value('torrents_cover_art_' . $GroupID); +$CoverArt = $Cache->get_value("torrents_cover_art_$GroupID"); if (!$CoverArt) { $DB->query(" SELECT ID, Image, Summary, UserID, Time @@ -90,13 +90,13 @@ function compare($X, $Y) { $CoverArt = array(); $CoverArt = $DB->to_array(); if ($DB->has_results()) { - $Cache->cache_value('torrents_cover_art_' . $GroupID, $CoverArt, 0); + $Cache->cache_value("torrents_cover_art_$GroupID", $CoverArt, 0); } } // Start output -View::show_header($Title,'browse,comments,torrent,bbcode,recommend,cover_art'); +View::show_header($Title, 'browse,comments,torrent,bbcode,recommend,cover_art,subscriptions'); ?>
    @@ -108,18 +108,21 @@ function compare($X, $Y) { View history Revert to this revision - - Unbookmark + Remove bookmark - Bookmark + Bookmark + Add format - Request format @@ -131,7 +134,8 @@ function compare($X, $Y) {
    0 ? 'Covers (' . (count($CoverArt) + 1) . ')' : 'Cover')?> - 0) { + 0) { if (empty($LoggedUser['ShowExtraCovers'])) { for ($Index = 0; $Index <= count($CoverArt); $Index++) { ?> 0 ? ' style="display: none;"' : '')?>> @@ -149,17 +153,17 @@ function compare($X, $Y) { Next - Hide -
    - +
    @@ -174,25 +178,27 @@ function compare($X, $Y) { -
    > + -
    @@ -226,13 +232,15 @@ function compare($X, $Y) { Edit' : ''?>
      - 0) { + 0) { print '
    • Composers:
    • '; foreach ($Artists[4] as $Artist) { ?>
    • -query(" SELECT AliasID FROM artists_alias @@ -244,11 +252,12 @@ function compare($X, $Y) { $AliasID = $Artist['id']; } ?> - ()  + (X
    • - 0) { print '
    • DJ / Compiler:
    • '; @@ -268,8 +277,8 @@ function compare($X, $Y) { $AliasID = $Artist['id']; } ?> - ()  - X + ()  + X
    • - - ()  - X + ()  + X
    • - ()  - X + ()  + X - ()  - X + ()  + X - ()  - X + ()  + X - ()  - X + ()  + X
    - Tags get_value('deleted_tags_'.$GroupID.'_'.$LoggedUser['ID']); + $DeletedTag = $Cache->get_value("deleted_tags_$GroupID".'_'.$LoggedUser['ID']); if (!empty($DeletedTag)) { ?> @@ -456,14 +467,14 @@ function compare($X, $Y) {
  • - + - + + + - U + U - X + X

    @@ -590,7 +601,7 @@ function filelist($Str) { $FileTable = '
  • Name / YearName / Year Files Size (Max) (Max)
    - +
    - +
    [ DL | RP ] @@ -1264,11 +1265,11 @@ function header_link($SortKey, $DefaultWay = 'DESC') {
    Tags (comma-separated): -   +   />   /> -
    - +
    +
    @@ -1029,27 +1032,27 @@ function header_link($SortKey, $DefaultWay = 'desc') { - +
    - +
    - Unbookmark + Remove bookmark - Bookmark + Bookmark
    format('torrents.php?'.$Action.'&taglist=')?>
    (Max) (Max)
    - +
    - +
    - +
    [ DL - | FL + | FL | RP ]
    -
    format('torrents.php?'.$Action.'&taglist=')?>
    +
    format("torrents.php?$Action&taglist=")?>
    PM uploader: - + - +
    ", - $Name, Format::get_size($FileSize)); + $FileTable .= sprintf("\n", $Name, Format::get_size($FileSize)); } } else { $FileListSplit = explode("\n", $FileList); foreach ($FileListSplit as $File) { $FileInfo = Torrents::filelist_get_file($File); - $FileTable .= sprintf("\n", - $FileInfo['name'], Format::get_size($FileInfo['size'])); + $FileTable .= sprintf("\n", $FileInfo['name'], Format::get_size($FileInfo['size'])); } } $FileTable .= ' @@ -657,7 +666,7 @@ function filelist($Str) { ?> - + [ - | FL + | FL | RP @@ -685,10 +694,10 @@ function filelist($Str) { ] » - - - - + + + + - + - +
    -
    File name' . $RegenLink . '
    +
    File Names' . $RegenLink . '
    ' . ($FilePath ? "/$FilePath/" : '') . '
    Size @@ -604,15 +615,13 @@ function filelist($Str) { $Name = str_replace(' ', ' ', substr($Name, 0, $Spaces)) . substr($Name, $Spaces); } $FileSize = substr($File, $NameEnd + 3, -3); - $FileTable .= sprintf("\n
    %s%s
    %s%s
    %s%s
    %s%s
    @@ -718,8 +727,8 @@ function filelist($Str) {
    @@ -870,7 +879,7 @@ function filelist($Str) { ?> - + - + @@ -894,143 +903,27 @@ function filelist($Str) { get_value("torrent_comments_$GroupID"); -if ($Results === false) { - $DB->query(" - SELECT COUNT(c.ID) - FROM torrents_comments as c - WHERE c.GroupID = '$GroupID'"); - list($Results) = $DB->next_record(); - $Cache->cache_value("torrent_comments_$GroupID", $Results, 0); -} - -if (isset($_GET['postid']) && is_number($_GET['postid']) && $Results > TORRENT_COMMENTS_PER_PAGE) { - $DB->query(" - SELECT COUNT(ID) - FROM torrents_comments - WHERE GroupID = $GroupID - AND ID <= $_GET[postid]"); - list($PostNum) = $DB->next_record(); - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $PostNum); -} else { - list($Page, $Limit) = Format::page_limit(TORRENT_COMMENTS_PER_PAGE, $Results); -} - -//Get the cache catalogue -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$CatalogueLimit = $CatalogueID * THREAD_CATALOGUE . ', ' . THREAD_CATALOGUE; - -//---------- Get some data to start processing - -// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page -$Catalogue = $Cache->get_value("torrent_comments_{$GroupID}_catalogue_$CatalogueID"); -if ($Catalogue === false) { - $DB->query(" - SELECT - c.ID, - c.AuthorID, - c.AddedTime, - c.Body, - c.EditedUserID, - c.EditedTime, - u.Username - FROM torrents_comments as c - LEFT JOIN users_main AS u ON u.ID = c.EditedUserID - WHERE c.GroupID = '$GroupID' - ORDER BY c.ID - LIMIT $CatalogueLimit"); - $Catalogue = $DB->to_array(false, MYSQLI_ASSOC); - $Cache->cache_value("torrent_comments_{$GroupID}_catalogue_$CatalogueID", $Catalogue, 0); -} - -//This is a hybrid to reduce the catalogue down to the page elements: We use the page limit % catalogue -$Thread = array_slice($Catalogue, ((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) % THREAD_CATALOGUE), TORRENT_COMMENTS_PER_PAGE, true); +list($NumComments, $Page, $Thread, $LastRead) = Comments::load('torrents', $GroupID); +$Pages = Format::get_pages($Page, $NumComments, TORRENT_COMMENTS_PER_PAGE, 9, '#comments'); ?> - - $Post) { - list($PostID, $AuthorID, $AddedTime, $Body, $EditedUserID, $EditedTime, $EditedUsername) = array_values($Post); - list($AuthorID, $Username, $PermissionID, $Paranoia, $Artist, $Donor, $Warned, $Avatar, $Enabled, $UserTitle) = array_values(Users::user_info($AuthorID)); -?> - - - - - - - - - - - - - - - - -
    -
    # - - - Quote - - - Edit - - - Delete - -
    -
    - Report -= $AuthorInfo['Class']) { -?> - - - - - - - - - Warn - -   - -
    -
    - - -
    -full_format($Body)?> - -
    -
    - - « - - Last edited by - - -
    -
    - 'groupid', - 'InputID' => $GroupID, - 'TextareaCols' => 65)); + 'InputName' => 'pageid', + 'InputID' => $GroupID, + 'Action' => 'comments.php?page=torrents', + 'InputAction' => 'take_post', + 'TextareaCols' => 65, + 'SubscribeBox' => true + )); ?>
    diff --git a/sections/torrents/downloadlist.php b/sections/torrents/downloadlist.php index 0f721da1..f05accb9 100644 --- a/sections/torrents/downloadlist.php +++ b/sections/torrents/downloadlist.php @@ -12,15 +12,13 @@ $Limit = 100; } - - $DB->query(" SELECT SQL_CALC_FOUND_ROWS ud.UserID, ud.Time FROM users_downloads AS ud - WHERE ud.TorrentID='$TorrentID' + WHERE ud.TorrentID = '$TorrentID' ORDER BY ud.Time DESC LIMIT $Limit"); $UserIDs = $DB->collect('UserID'); @@ -30,26 +28,24 @@ list($NumResults) = $DB->next_record(); if (count($UserIDs) > 0) { - $UserIDs = implode(',',$UserIDs); + $UserIDs = implode(',', $UserIDs); $DB->query(" SELECT uid FROM xbt_snatched - WHERE fid='$TorrentID' + WHERE fid = '$TorrentID' AND uid IN($UserIDs)"); $Snatched = $DB->to_array('uid'); $DB->query(" SELECT uid FROM xbt_files_users - WHERE fid='$TorrentID' - AND Remaining=0 + WHERE fid = '$TorrentID' + AND Remaining = 0 AND uid IN($UserIDs)"); $Seeding = $DB->to_array('uid'); } - - ?> -

    List of Downloaders

    +

    List of Downloaders

    100) { ?> @@ -63,7 +59,6 @@ $Data) { diff --git a/sections/torrents/edit.php b/sections/torrents/edit.php index 4dd4110e..9bb51a94 100644 --- a/sections/torrents/edit.php +++ b/sections/torrents/edit.php @@ -29,8 +29,6 @@ t.Scene, t.FreeTorrent, t.FreeLeechType, - t.Dupable, - t.DupeReason, t.Description AS TorrentDescription, tg.CategoryID, tg.Name AS Title, diff --git a/sections/torrents/editgroupid.php b/sections/torrents/editgroupid.php index 9b2e6de5..48943b7b 100644 --- a/sections/torrents/editgroupid.php +++ b/sections/torrents/editgroupid.php @@ -87,10 +87,11 @@ WHERE GroupID = '$OldGroupID'"); list($TorrentsInGroup) = $DB->next_record(); if ($TorrentsInGroup == 0) { + // TODO: votes etc! $DB->query(" - UPDATE torrents_comments - SET GroupID = '$GroupID' - WHERE GroupID = '$OldGroupID'"); + UPDATE comments + SET PageID = '$GroupID' + WHERE Page = 'torrents' AND PageID = '$OldGroupID'"); $Cache->delete_value("torrent_comments_{$GroupID}_catalogue_0"); $Cache->delete_value("torrent_comments_$GroupID"); Torrents::delete_group($OldGroupID); diff --git a/sections/torrents/functions.php b/sections/torrents/functions.php index a43ace4b..5aab5515 100644 --- a/sections/torrents/functions.php +++ b/sections/torrents/functions.php @@ -342,7 +342,7 @@ function filelist($Str) { ", $Name, Format::get_size($FileSize)); + $FileTable .= sprintf("\n", $Name, Format::get_size($FileSize)); } } else { $FileListSplit = explode("\n", $FileList); foreach ($FileListSplit as $File) { $FileInfo = Torrents::filelist_get_file($File); - $FileTable .= sprintf("\n", $FileInfo['name'], Format::get_size($FileInfo['size'])); + $FileTable .= sprintf("\n", $FileInfo['name'], Format::get_size($FileInfo['size'])); } } $FileTable .= ' @@ -458,7 +458,7 @@ function filelist($Str) { $EditionID++; ?> - + [ - | FL + | FL | RP @@ -485,10 +485,10 @@ function filelist($Str) { ] » - - - - + + + + - diff --git a/sections/torrents/index.php b/sections/torrents/index.php index b90e7320..f5cf9986 100644 --- a/sections/torrents/index.php +++ b/sections/torrents/index.php @@ -175,189 +175,6 @@ function js_pages($Action, $TorrentID, $NumResults, $CurrentPage) { require(SERVER_ROOT.'/sections/torrents/download.php'); break; - case 'reply': - enforce_login(); - authorize(); - - if (!isset($_POST['groupid']) || !is_number($_POST['groupid']) || trim($_POST['body']) === '' || !isset($_POST['body'])) { - error(0); - } - if ($LoggedUser['DisablePosting']) { - error('Your posting privileges have been removed.'); - } - - $GroupID = $_POST['groupid']; - if (!$GroupID) { - error(404); - } - - $DB->query(" - SELECT - CEIL(( - SELECT COUNT(ID) + 1 - FROM torrents_comments AS tc - WHERE tc.GroupID = '".db_string($GroupID)."' - ) / ".TORRENT_COMMENTS_PER_PAGE.' - ) AS Pages'); - list($Pages) = $DB->next_record(); - - $DB->query(" - INSERT INTO torrents_comments - (GroupID, AuthorID, AddedTime, Body) - VALUES - ('".db_string($GroupID)."', '".db_string($LoggedUser['ID'])."', '".sqltime()."', '".db_string($_POST['body'])."')"); - $PostID = $DB->inserted_id(); - - $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $Cache->begin_transaction("torrent_comments_{$GroupID}_catalogue_$CatalogueID"); - $Post = array( - 'ID' => $PostID, - 'AuthorID' => $LoggedUser['ID'], - 'AddedTime' => sqltime(), - 'Body' => $_POST['body'], - 'EditedUserID' => 0, - 'EditedTime' => '0000-00-00 00:00:00', - 'Username' => '' - ); - $Cache->insert('', $Post); - $Cache->commit_transaction(0); - $Cache->increment("torrent_comments_$GroupID"); - - header("Location: torrents.php?id=$GroupID&page=$Pages"); - break; - - case 'get_post': - enforce_login(); - if (!$_GET['post'] || !is_number($_GET['post'])) { - error(0); - } - $DB->query(" - SELECT Body - FROM torrents_comments - WHERE ID = '".db_string($_GET['post'])."'"); - list($Body) = $DB->next_record(MYSQLI_NUM); - - echo trim($Body); - break; - - case 'takeedit_post': - enforce_login(); - authorize(); - - include(SERVER_ROOT.'/classes/text.class.php'); // Text formatting class - $Text = new TEXT; - - // Quick SQL injection check - if (!$_POST['post'] || !is_number($_POST['post'])) { - error(0); - } - - // Mainly - $DB->query(" - SELECT - tc.Body, - tc.AuthorID, - tc.GroupID, - tc.AddedTime - FROM torrents_comments AS tc - WHERE tc.ID = '".db_string($_POST['post'])."'"); - list($OldBody, $AuthorID, $GroupID, $AddedTime) = $DB->next_record(); - - $DB->query(" - SELECT ceil(COUNT(ID) / ".TORRENT_COMMENTS_PER_PAGE.") AS Page - FROM torrents_comments - WHERE GroupID = $GroupID - AND ID <= $_POST[post]"); - list($Page) = $DB->next_record(); - - if ($LoggedUser['ID'] != $AuthorID && !check_perms('site_moderate_forums')) { - error(404); - } - if (!$DB->has_results()) { - error(404); - } - - // Perform the update - $DB->query(" - UPDATE torrents_comments - SET - Body = '".db_string($_POST['body'])."', - EditedUserID = '".db_string($LoggedUser['ID'])."', - EditedTime = '".sqltime()."' - WHERE ID = '".db_string($_POST['post'])."'"); - - // Update the cache - $CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $Cache->begin_transaction("torrent_comments_{$GroupID}_catalogue_$CatalogueID"); - - $Cache->update_row($_POST['key'], array( - 'ID' => $_POST['post'], - 'AuthorID' => $AuthorID, - 'AddedTime' => $AddedTime, - 'Body' => $_POST['body'], - 'EditedUserID' => db_string($LoggedUser['ID']), - 'EditedTime' => sqltime(), - 'Username' => $LoggedUser['Username'] - )); - $Cache->commit_transaction(0); - - $DB->query(" - INSERT INTO comments_edits - (Page, PostID, EditUser, EditTime, Body) - VALUES - ('torrents', ".db_string($_POST['post']).", ".db_string($LoggedUser['ID']).", '".sqltime()."', '".db_string($OldBody)."')"); - - // This gets sent to the browser, which echoes it in place of the old body - echo $Text->full_format($_POST['body']); - break; - - case 'delete_post': - enforce_login(); - authorize(); - - // Quick SQL injection check - if (!$_GET['postid'] || !is_number($_GET['postid'])) { - error(0); - } - - // Make sure they are moderators - if (!check_perms('site_moderate_forums')) { - error(403); - } - - // Get topicid, forumid, number of pages - $DB->query(" - SELECT - GroupID, - CEIL(COUNT(tc.ID) / ".TORRENT_COMMENTS_PER_PAGE.") AS Pages, - CEIL(SUM(IF(tc.ID <= ".$_GET['postid'].", 1, 0)) / ".TORRENT_COMMENTS_PER_PAGE.") AS Page - FROM torrents_comments AS tc - WHERE tc.GroupID = - (SELECT GroupID - FROM torrents_comments - WHERE ID = ".$_GET['postid'].') - GROUP BY tc.GroupID'); - list($GroupID, $Pages, $Page) = $DB->next_record(); - - // $Pages = number of pages in the thread - // $Page = which page the post is on - // These are set for cache clearing. - - $DB->query(" - DELETE FROM torrents_comments - WHERE ID = '".db_string($_GET['postid'])."'"); - - //We need to clear all subsequential catalogues as they've all been bumped with the absence of this post - $ThisCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - $LastCatalogue = floor((TORRENT_COMMENTS_PER_PAGE * $Pages - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); - for ($i = $ThisCatalogue; $i <= $LastCatalogue; $i++) { - $Cache->delete_value("torrent_comments_{$GroupID}_catalogue_$i"); - } - - // Delete thread info cache (e.g. number of pages) - $Cache->delete_value("torrent_comments_$GroupID"); - - break; case 'regen_filelist': if (check_perms('users_mod') && !empty($_GET['torrentid']) && is_number($_GET['torrentid'])) { Torrents::regenerate_filelist($_GET['torrentid']); @@ -387,12 +204,6 @@ function js_pages($Action, $TorrentID, $NumResults, $CurrentPage) { error(403); } break; - case 'warn': - include(SERVER_ROOT.'/sections/torrents/warn.php'); - break; - case 'take_warn': - include(SERVER_ROOT.'/sections/torrents/take_warn.php'); - break; case 'add_cover_art': include(SERVER_ROOT.'/sections/torrents/add_cover_art.php'); break; diff --git a/sections/torrents/masspm.php b/sections/torrents/masspm.php index b0ab27cd..0d134124 100644 --- a/sections/torrents/masspm.php +++ b/sections/torrents/masspm.php @@ -15,8 +15,6 @@ t.RemasterTitle, t.Scene, t.FreeTorrent, - t.Dupable, - t.DupeReason, t.Description AS TorrentDescription, tg.CategoryID, tg.Name AS Title, diff --git a/sections/torrents/merge.php b/sections/torrents/merge.php index b59d9eb2..c352f568 100644 --- a/sections/torrents/merge.php +++ b/sections/torrents/merge.php @@ -124,20 +124,9 @@ UPDATE wiki_torrents SET PageID = '$NewGroupID' WHERE PageID = '$GroupID'"); - $DB->query(" - UPDATE torrents_comments - SET GroupID = '$NewGroupID' - WHERE GroupID = '$GroupID'"); - Torrents::delete_group($GroupID); - - Torrents::write_group_log($NewGroupID, 0, $LoggedUser['ID'], "Merged Group $GroupID ($Name) to $NewGroupID ($NewName)", 0); - $DB->query(" - UPDATE group_log - SET GroupID = $NewGroupID - WHERE GroupID = $GroupID"); - - $GroupID = $NewGroupID; + //Comments + Comments::merge('torrents', $OldGroupID, $NewGroupID); //Collages $DB->query(" @@ -167,11 +156,22 @@ $Requests = $DB->collect('ID'); $DB->query(" UPDATE requests - SET GroupID = 'NewGroupID' + SET GroupID = '$NewGroupID' WHERE GroupID = '$OldGroupID'"); foreach ($Requests as $RequestID) { $Cache->delete_value("request_$RequestID"); } + $Cache->delete_value('requests_group_'.$NewGroupID); + + Torrents::delete_group($GroupID); + + Torrents::write_group_log($NewGroupID, 0, $LoggedUser['ID'], "Merged Group $GroupID ($Name) to $NewGroupID ($NewName)", 0); + $DB->query(" + UPDATE group_log + SET GroupID = $NewGroupID + WHERE GroupID = $GroupID"); + + $GroupID = $NewGroupID; $DB->query(" SELECT ID @@ -181,8 +181,6 @@ $Cache->delete_value("torrent_download_$TorrentID"); } $Cache->delete_value("torrents_details_$GroupID"); - $Cache->delete_value("torrent_comments_{$GroupID}_catalogue_0"); - $Cache->delete_value("torrent_comments_$GroupID"); $Cache->delete_value("groups_artists_$GroupID"); Torrents::update_hash($GroupID); diff --git a/sections/torrents/notify.php b/sections/torrents/notify.php index 51515049..76e8d04d 100644 --- a/sections/torrents/notify.php +++ b/sections/torrents/notify.php @@ -271,7 +271,7 @@ function header_link($SortKey, $DefaultWay = 'desc') { $DisplayName .= " [$GroupInfo[Year]]"; } if ($GroupInfo['ReleaseType'] > 0) { - $DisplayName.= ' ['.$ReleaseTypes[$GroupInfo['ReleaseType']].']'; + $DisplayName .= ' ['.$ReleaseTypes[$GroupInfo['ReleaseType']].']'; } } @@ -289,20 +289,20 @@ function header_link($SortKey, $DefaultWay = 'desc') { - - + + - + - - + + query(" - SELECT - SQL_CALC_FOUND_ROWS - xs.uid, - xs.tstamp - FROM xbt_snatched AS xs - WHERE xs.fid = '$TorrentID' - ORDER BY xs.tstamp DESC - LIMIT $Limit"); + SELECT + SQL_CALC_FOUND_ROWS + xs.uid, + xs.tstamp + FROM xbt_snatched AS xs + WHERE xs.fid = '$TorrentID' + ORDER BY xs.tstamp DESC + LIMIT $Limit"); $Results = $DB->to_array('uid', MYSQLI_ASSOC); $DB->query('SELECT FOUND_ROWS()'); list($NumResults) = $DB->next_record(); ?> -

    List of Snatchers

    +

    List of Snatchers

    100) { ?> diff --git a/sections/torrents/take_warn.php b/sections/torrents/take_warn.php deleted file mode 100644 index 3f0d6e7b..00000000 --- a/sections/torrents/take_warn.php +++ /dev/null @@ -1,79 +0,0 @@ - $LoggedUser['Class']) { - error(403); -} -$URL = 'https://' . SSL_SITE_URL . "/torrents.php?id=$GroupID&postid=$PostID#post$PostID"; -if ($Length != 'verbal') { - $Time = ((int) $Length) * (7 * 24 * 60 * 60); - Tools::warn_user($UserID, $Time, "$URL - " . $Reason); - $Subject = 'You have received a warning'; - $PrivateMessage = "You have received a $Length week warning for [url=$URL]this post.[/url]\n\n" . $PrivateMessage; - $WarnTime = time_plus($Time); - $AdminComment = date('Y-m-d') . " - Warned until $WarnTime by " . $LoggedUser['Username'] . " for $URL \nReason: $Reason\n\n"; -} else { - $Subject = 'You have received a verbal warning'; - $PrivateMessage = "You have received a verbal warning for [url=$URL]this post.[/url]\n\n" . $PrivateMessage; - $AdminComment = date('Y-m-d') . ' - Verbally warned by ' . $LoggedUser['Username'] . " for $URL \nReason: $Reason\n\n"; - Tools::update_user_notes($UserID, $AdminComment); -} -$DB->query(" - INSERT INTO users_warnings_forums (UserID, Comment) - VALUES('$UserID', '" . db_string($AdminComment) . "') - ON DUPLICATE KEY UPDATE Comment = CONCAT('" . db_string($AdminComment) . "', Comment)"); -Misc::send_pm($UserID, $LoggedUser['ID'], $Subject, $PrivateMessage); - -// Mainly -$DB->query(" - SELECT - tc.Body, - tc.AuthorID, - tc.GroupID, - tc.AddedTime - FROM torrents_comments AS tc - WHERE tc.ID = '$PostID'"); -list($OldBody, $AuthorID, $GroupID, $AddedTime) = $DB->next_record(); - -$DB->query(" - SELECT ceil(COUNT(ID) / " . TORRENT_COMMENTS_PER_PAGE . ") AS Page - FROM torrents_comments - WHERE GroupID = $GroupID - AND ID <= $PostID"); -list($Page) = $DB->next_record(); - -// Perform the update -$DB->query(" - UPDATE torrents_comments - SET Body = '" . db_string($Body) . "', - EditedUserID = '" . db_string($LoggedUser['ID']) . "', - EditedTime = '" . sqltime() . "' - WHERE ID = '$PostID'"); - -// Update the cache -$CatalogueID = floor((TORRENT_COMMENTS_PER_PAGE * $Page - TORRENT_COMMENTS_PER_PAGE) / THREAD_CATALOGUE); -$Cache->begin_transaction("torrent_comments_{$GroupID}_catalogue_$CatalogueID"); - -$Cache->update_row($_POST['key'], array('ID' => $_POST['postid'], 'AuthorID' => $AuthorID, 'AddedTime' => $AddedTime, 'Body' => $Body, - 'EditedUserID' => db_string($LoggedUser['ID']), 'EditedTime' => sqltime(), 'Username' => $LoggedUser['Username'])); -$Cache->commit_transaction(0); - -$DB->query(" - INSERT INTO comments_edits (Page, PostID, EditUser, EditTime, Body) - VALUES ('torrents', " . db_string($_POST['postid']) . ", " . db_string($LoggedUser['ID']) . ", '" . sqltime() . "', '" . db_string($OldBody) . "')"); - -header("Location: torrents.php?id=$GroupID&postid=$PostID#post$PostID"); -?> diff --git a/sections/torrents/takechangecategory.php b/sections/torrents/takechangecategory.php index 8369ea5c..851bb57a 100644 --- a/sections/torrents/takechangecategory.php +++ b/sections/torrents/takechangecategory.php @@ -99,10 +99,12 @@ FROM torrents WHERE GroupID = '$OldGroupID'"); if (!$DB->has_results()) { + // TODO: votes etc. $DB->query(" - UPDATE torrents_comments - SET GroupID = '$GroupID' - WHERE GroupID = '$OldGroupID'"); + UPDATE comments + SET PageID = '$GroupID' + WHERE Page = 'torrents' + AND PageID = '$OldGroupID'"); Torrents::delete_group($OldGroupID); $Cache->delete_value("torrent_comments_{$GroupID}_catalogue_0"); } else { diff --git a/sections/torrents/takeedit.php b/sections/torrents/takeedit.php index fbcd495a..06607283 100644 --- a/sections/torrents/takeedit.php +++ b/sections/torrents/takeedit.php @@ -276,8 +276,7 @@ RemasterTitle = $T[RemasterTitle], RemasterRecordLabel = $T[RemasterRecordLabel], RemasterCatalogueNumber = $T[RemasterCatalogueNumber], - Scene = $T[Scene], - Description = $T[TorrentDescription],"; + Scene = $T[Scene],"; if (check_perms('torrents_freeleech')) { $SQL .= "FreeTorrent = $T[FreeLeech],"; @@ -419,7 +418,7 @@ } $SQL .= " - flags = '2' + Description = $T[TorrentDescription] WHERE ID = $TorrentID"; $DB->query($SQL); diff --git a/sections/torrents/user.php b/sections/torrents/user.php index e63e2c4b..b1c5a32a 100644 --- a/sections/torrents/user.php +++ b/sections/torrents/user.php @@ -409,7 +409,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { @@ -513,7 +513,7 @@ function header_link($SortKey, $DefaultWay = 'DESC') { $ExtraInfo = Torrents::torrent_info($Torrent); if ($ExtraInfo) { - $DisplayName .= ' - '.$ExtraInfo; + $DisplayName .= " - $ExtraInfo"; } ?> @@ -521,26 +521,26 @@ function header_link($SortKey, $DefaultWay = 'DESC') {
    - - - > - + + + +
    -
    File name' . $RegenLink . '
    +
    File Names' . $RegenLink . '
    ' . ($FilePath ? "/$FilePath/" : '') . '
    @@ -358,13 +358,13 @@ function filelist($Str) { $Name = str_replace(' ', ' ', substr($Name, 0, $Spaces)) . substr($Name, $Spaces); } $FileSize = substr($File, $NameEnd + 3, -3); - $FileTable .= sprintf("\n
    %s%s
    %s%s
    %s%s
    %s%s
    @@ -513,8 +513,8 @@ function filelist($Str) { (//) +
    - +
    - +
    [ DL - | FL + | FL - | CL + | CL ] @@ -313,9 +313,9 @@ function header_link($SortKey, $DefaultWay = 'desc') { } ?> - Unbookmark + Remove bookmark - Bookmark + Bookmark
    diff --git a/sections/torrents/peerlist.php b/sections/torrents/peerlist.php index c695ba4e..2988ec70 100644 --- a/sections/torrents/peerlist.php +++ b/sections/torrents/peerlist.php @@ -44,8 +44,8 @@
    User Active ConnectableUp%Up% Client
    Yes' : 'No' ?>Yes' : 'No' ?> Yes' : 'No' ?>
    Tags: -   +   />   />
    - +
    - +
    [ DL | RP ] - +
    format('torrents.php?type='.$Action.'&userid='.$UserID.'&tags=')?>
    diff --git a/sections/torrents/vote.php b/sections/torrents/vote.php index d09cda40..50459938 100644 --- a/sections/torrents/vote.php +++ b/sections/torrents/vote.php @@ -8,7 +8,7 @@ $Voted = isset($UserVotes[$GroupID]) ? $UserVotes[$GroupID]['Type'] : false; ?>
    -
    Album votes
    +
    Album Votes
    This has out of total.

    diff --git a/sections/torrents/warn.php b/sections/torrents/warn.php deleted file mode 100644 index 433dffab..00000000 --- a/sections/torrents/warn.php +++ /dev/null @@ -1,70 +0,0 @@ -query(" - SELECT tc.Body, tc.AddedTime - FROM torrents_comments AS tc - WHERE tc.ID = '" . db_string($PostID) . "'"); -list($PostBody) = $DB -> next_record(); - -View::show_header('Warn User'); -?> - -
    -
    -

    Warning

    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - -
    Reason: - -
    Length: -
    Private message: - -
    Edit post: - -
    - -
    -
    -
    -
    - diff --git a/sections/user/advancedsearch.php b/sections/user/advancedsearch.php index d3a27280..19e48e2f 100644 --- a/sections/user/advancedsearch.php +++ b/sections/user/advancedsearch.php @@ -14,7 +14,7 @@ FROM users_main WHERE Username = '".db_string($_GET['search'])."'"); if (list($ID) = $DB->next_record()) { - header('Location: user.php?id='.$ID); + header("Location: user.php?id=$ID"); die(); } $_GET['username'] = $_GET['search']; @@ -42,18 +42,18 @@ function wrap($String, $ForceMatch = '', $IPSearch = false) { // Fuzzy search // Stick in wildcards at beginning and end of string unless string starts or ends with | if (($String[0] != '|') && !$IPSearch) { - $String = '%'.$String; + $String = "%$String"; } elseif ($String[0] == '|') { $String = substr($String, 1, strlen($String)); } if (substr($String, -1, 1) != '|') { - $String = $String.'%'; + $String = "$String%"; } else { $String = substr($String, 0, -1); } } - $String="'$String'"; + $String = "'$String'"; return $String; } @@ -64,18 +64,18 @@ function date_compare($Field, $Operand, $Date1, $Date2 = '') { switch ($Operand) { case 'on': - $Return []= " $Field>='$Date1 00:00:00' "; - $Return []= " $Field<='$Date1 23:59:59' "; + $Return [] = " $Field >= '$Date1 00:00:00' "; + $Return [] = " $Field <= '$Date1 23:59:59' "; break; case 'before': - $Return []= " $Field<'$Date1 00:00:00' "; + $Return [] = " $Field < '$Date1 00:00:00' "; break; case 'after': - $Return []= " $Field>'$Date1 23:59:59' "; + $Return [] = " $Field > '$Date1 23:59:59' "; break; case 'between': - $Return []= " $Field>='$Date1 00:00:00' "; - $Return []= " $Field<='$Date2 00:00:00' "; + $Return [] = " $Field >= '$Date1 00:00:00' "; + $Return [] = " $Field <= '$Date2 00:00:00' "; break; } @@ -96,17 +96,17 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { switch ($Operand) { case 'equal': - $Return []= " $Field='$Num1' "; + $Return [] = " $Field = '$Num1' "; break; case 'above': - $Return []= " $Field>'$Num1' "; + $Return [] = " $Field > '$Num1' "; break; case 'below': - $Return []= " $Field<'$Num1' "; + $Return [] = " $Field < '$Num1' "; break; case 'between': - $Return []= " $Field>'$Num1' "; - $Return []= " $Field<'$Num2' "; + $Return [] = " $Field > '$Num1' "; + $Return [] = " $Field < '$Num2' "; break; default: print_r($Return); @@ -125,19 +125,19 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { $WayVals = array('inarray'=>array('Ascending', 'Descending')); if (count($_GET)) { - $DateRegex = array('regex'=>'/\d{4}-\d{2}-\d{2}/'); + $DateRegex = array('regex' => '/\d{4}-\d{2}-\d{2}/'); $ClassIDs = array(); $SecClassIDs = array(); foreach ($Classes as $ClassID => $Value) { if ($Value['Secondary']) { - $SecClassIDs[]=$ClassID; + $SecClassIDs[] = $ClassID; } else { - $ClassIDs[]=$ClassID; + $ClassIDs[] = $ClassID; } } - $Val->SetFields('comment','0','string','Comment is too long.', array('maxlength'=>512)); + $Val->SetFields('comment', '0', 'string', 'Comment is too long.', array('maxlength' => 512)); $Val->SetFields('disabled_invites', '0', 'inarray', 'Invalid disabled_invites field', $YesNo); @@ -154,12 +154,12 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { $Val->SetFields('downloaded', '0', 'inarray', 'Invalid downloaded field', $NumberChoices); //$Val->SetFields('snatched', '0', 'inarray', 'Invalid snatched field', $NumberChoices); - $Val->SetFields('matchtype', '0', 'inarray', 'Invalid matchtype field', array('inarray'=>array('strict', 'fuzzy', 'regex'))); + $Val->SetFields('matchtype', '0', 'inarray', 'Invalid matchtype field', array('inarray' => array('strict', 'fuzzy', 'regex'))); - $Val->SetFields('enabled', '0', 'inarray', 'Invalid enabled field', array('inarray'=>array('', 0, 1, 2))); - $Val->SetFields('class', '0', 'inarray', 'Invalid class', array('inarray'=>$ClassIDs)); - $Val->SetFields('secclass', '0', 'inarray', 'Invalid class', array('inarray'=>$SecClassIDs)); + $Val->SetFields('enabled', '0', 'inarray', 'Invalid enabled field', array('inarray' => array('', 0, 1, 2))); + $Val->SetFields('class', '0', 'inarray', 'Invalid class', array('inarray' => $ClassIDs)); + $Val->SetFields('secclass', '0', 'inarray', 'Invalid class', array('inarray' => $SecClassIDs)); $Val->SetFields('donor', '0', 'inarray', 'Invalid donor field', $YesNo); $Val->SetFields('warned', '0', 'inarray', 'Invalid warned field', $YesNo); $Val->SetFields('disabled_uploads', '0', 'inarray', 'Invalid disabled_uploads field', $YesNo); @@ -167,10 +167,10 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { $Val->SetFields('order', '0', 'inarray', 'Invalid ordering', $OrderVals); $Val->SetFields('way', '0', 'inarray', 'Invalid way', $WayVals); - $Val->SetFields('passkey', '0', 'string', 'Invalid passkey', array('maxlength'=>32)); - $Val->SetFields('avatar', '0', 'string', 'Avatar URL too long', array('maxlength'=>512)); + $Val->SetFields('passkey', '0', 'string', 'Invalid passkey', array('maxlength' => 32)); + $Val->SetFields('avatar', '0', 'string', 'Avatar URL too long', array('maxlength' => 512)); $Val->SetFields('stylesheet', '0', 'inarray', 'Invalid stylesheet', array_unique(array_keys($Stylesheets))); - $Val->SetFields('cc', '0', 'inarray', 'Invalid Country Code', array('maxlength'=>2)); + $Val->SetFields('cc', '0', 'inarray', 'Invalid Country Code', array('maxlength' => 2)); $Err = $Val->ValidateForm($_GET); @@ -186,7 +186,17 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { $Match = ' LIKE '; } - $OrderTable = array('Username'=>'um1.Username', 'Joined'=>'ui1.JoinDate', 'Email'=>'um1.Email', 'IP'=>'um1.IP', 'Last Seen'=>'um1.LastAccess', 'Uploaded'=>'um1.Uploaded', 'Downloaded'=>'um1.Downloaded', 'Ratio'=>'(um1.Uploaded/um1.Downloaded)', 'Invites'=>'um1.Invites', 'Snatches'=>'Snatches'); + $OrderTable = array( + 'Username' => 'um1.Username', + 'Joined' => 'ui1.JoinDate', + 'Email' => 'um1.Email', + 'IP' => 'um1.IP', + 'Last Seen' => 'um1.LastAccess', + 'Uploaded' => 'um1.Uploaded', + 'Downloaded' => 'um1.Downloaded', + 'Ratio' => '(um1.Uploaded / um1.Downloaded)', + 'Invites' => 'um1.Invites', + 'Snatches' => 'Snatches'); $WayTable = array('Ascending'=>'ASC', 'Descending'=>'DESC'); @@ -204,10 +214,15 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { um1.Username, um1.Uploaded, um1.Downloaded,'; - if ($_GET['snatched'] == "off") { + if ($_GET['snatched'] == 'off') { $SQL .= "'X' AS Snatches,"; } else { - $SQL .= "(SELECT COUNT(uid) FROM xbt_snatched AS xs WHERE xs.uid=um1.ID) AS Snatches,"; + $SQL .= " + ( + SELECT COUNT(uid) + FROM xbt_snatched AS xs + WHERE xs.uid = um1.ID + ) AS Snatches,"; } $SQL .= ' um1.PermissionID, @@ -221,17 +236,17 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { ui1.JoinDate, um1.LastAccess FROM users_main AS um1 - JOIN users_info AS ui1 ON ui1.UserID=um1.ID '; + JOIN users_info AS ui1 ON ui1.UserID = um1.ID '; if (!empty($_GET['username'])) { - $Where[]='um1.Username'.$Match.wrap($_GET['username']); + $Where[] = 'um1.Username'.$Match.wrap($_GET['username']); } if (!empty($_GET['email'])) { if (isset($_GET['email_history'])) { $Distinct = 'DISTINCT '; - $Join['he'] = ' JOIN users_history_emails AS he ON he.UserID=um1.ID '; + $Join['he'] = ' JOIN users_history_emails AS he ON he.UserID = um1.ID '; $Where[] = ' he.Email '.$Match.wrap($_GET['email']); } else { $Where[] = 'um1.Email'.$Match.wrap($_GET['email']); @@ -253,7 +268,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { if ($_GET['emails_opt'] === 'below') { $operator = '<'; } - $Query .= $operator." ".$_GET['email_cnt']; + $Query .= $operator.' '.$_GET['email_cnt']; $DB->query($Query); $Users = implode(',', $DB->collect('UserID')); if (!empty($Users)) { @@ -265,7 +280,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { if (!empty($_GET['ip'])) { if (isset($_GET['ip_history'])) { $Distinct = 'DISTINCT '; - $Join['hi'] = ' JOIN users_history_ips AS hi ON hi.UserID=um1.ID '; + $Join['hi'] = ' JOIN users_history_ips AS hi ON hi.UserID = um1.ID '; $Where[] = ' hi.IP '.$Match.wrap($_GET['ip'], '', true); } else { $Where[] = 'um1.IP'.$Match.wrap($_GET['ip'], '', true); @@ -273,7 +288,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { } if (!empty($_GET['cc'])) { - if ($_GET['cc_op'] == "equal") { + if ($_GET['cc_op'] == 'equal') { $Where[] = "um1.ipcc = '".db_string($_GET['cc'])."'"; } else { $Where[] = "um1.ipcc != '".db_string($_GET['cc'])."'"; @@ -282,13 +297,13 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { if (!empty($_GET['tracker_ip'])) { $Distinct = 'DISTINCT '; - $Join['xfu'] = ' JOIN xbt_files_users AS xfu ON um1.ID=xfu.uid '; + $Join['xfu'] = ' JOIN xbt_files_users AS xfu ON um1.ID = xfu.uid '; $Where[] = ' xfu.ip '.$Match.wrap($_GET['tracker_ip'], '', true); } // if (!empty($_GET['tracker_ip'])) { // $Distinct = 'DISTINCT '; -// $Join['xs'] = ' JOIN xbt_snatched AS xs ON um1.ID=xs.uid '; +// $Join['xs'] = ' JOIN xbt_snatched AS xs ON um1.ID = xs.uid '; // $Where[] = ' xs.IP '.$Match.wrap($_GET['ip']); // } @@ -310,15 +325,15 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { } if ($_GET['disabled_invites'] == 'yes') { - $Where[] = 'ui1.DisableInvites=\'1\''; + $Where[] = 'ui1.DisableInvites = \'1\''; } elseif ($_GET['disabled_invites'] == 'no') { - $Where[] = 'ui1.DisableInvites=\'0\''; + $Where[] = 'ui1.DisableInvites = \'0\''; } if ($_GET['disabled_uploads'] == 'yes') { - $Where[] = 'ui1.DisableUpload=\'1\''; + $Where[] = 'ui1.DisableUpload = \'1\''; } elseif ($_GET['disabled_uploads'] == 'no') { - $Where[] = 'ui1.DisableUpload=\'0\''; + $Where[] = 'ui1.DisableUpload = \'0\''; } if ($_GET['join1']) { @@ -341,72 +356,72 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { $Upload1 = round($_GET['uploaded1']); $Upload2 = round($_GET['uploaded2']); if ($_GET['uploaded'] != 'buffer') { - $Where[] = implode(' AND ', num_compare('ROUND(Uploaded/1024/1024/1024)', $_GET['uploaded'], $Upload1, $Upload2)); + $Where[] = implode(' AND ', num_compare('ROUND(Uploaded / 1024 / 1024 / 1024)', $_GET['uploaded'], $Upload1, $Upload2)); } else { - $Where[] = implode(' AND ', num_compare('ROUND((Uploaded/1024/1024/1024)-(Downloaded/1024/1024/1023))', 'between', $Upload1 * 0.9, $Upload1 * 1.1)); + $Where[] = implode(' AND ', num_compare('ROUND((Uploaded / 1024 / 1024 / 1024) - (Downloaded / 1024 / 1024 / 1023))', 'between', $Upload1 * 0.9, $Upload1 * 1.1)); } } if (strlen($_GET['downloaded1'])) { $Download1 = round($_GET['downloaded1']); $Download2 = round($_GET['downloaded2']); - $Where[]=implode(' AND ', num_compare('ROUND(Downloaded/1024/1024/1024)', $_GET['downloaded'], $Download1, $Download2)); + $Where[] = implode(' AND ', num_compare('ROUND(Downloaded / 1024 / 1024 / 1024)', $_GET['downloaded'], $Download1, $Download2)); } if (strlen($_GET['snatched1'])) { $Snatched1 = round($_GET['snatched1']); $Snatched2 = round($_GET['snatched2']); - $Having[]=implode(' AND ', num_compare('Snatches', $_GET['snatched'], $Snatched1, $Snatched2)); + $Having[] = implode(' AND ', num_compare('Snatches', $_GET['snatched'], $Snatched1, $Snatched2)); } if ($_GET['enabled'] != '') { - $Where[]='um1.Enabled='.wrap($_GET['enabled'], '='); + $Where[] = 'um1.Enabled = '.wrap($_GET['enabled'], '='); } if ($_GET['class'] != '') { - $Where[]='um1.PermissionID='.wrap($_GET['class'], '='); + $Where[] = 'um1.PermissionID = '.wrap($_GET['class'], '='); } if ($_GET['secclass'] != '') { - $Join['ul']=' JOIN users_levels AS ul ON um1.ID=ul.UserID '; - $Where[]='ul.PermissionID='.wrap($_GET['secclass'], '='); + $Join['ul'] = ' JOIN users_levels AS ul ON um1.ID = ul.UserID '; + $Where[] = 'ul.PermissionID = '.wrap($_GET['secclass'], '='); } if ($_GET['donor'] == 'yes') { - $Where[]='ui1.Donor=\'1\''; + $Where[] = 'ui1.Donor = \'1\''; } elseif ($_GET['donor'] == 'no') { - $Where[]='ui1.Donor=\'0\''; + $Where[] = 'ui1.Donor = \'0\''; } if ($_GET['warned'] == 'yes') { - $Where[]='ui1.Warned!=\'0000-00-00 00:00:00\''; + $Where[] = 'ui1.Warned != \'0000-00-00 00:00:00\''; } elseif ($_GET['warned'] == 'no') { - $Where[]='ui1.Warned=\'0000-00-00 00:00:00\''; + $Where[] = 'ui1.Warned = \'0000-00-00 00:00:00\''; } if ($_GET['disabled_ip']) { $Distinct = 'DISTINCT '; if ($_GET['ip_history']) { if (!isset($Join['hi'])) { - $Join['hi']=' JOIN users_history_ips AS hi ON hi.UserID=um1.ID '; + $Join['hi'] = ' JOIN users_history_ips AS hi ON hi.UserID = um1.ID '; } - $Join['hi2']=' JOIN users_history_ips AS hi2 ON hi2.IP=hi.IP '; - $Join['um2']=' JOIN users_main AS um2 ON um2.ID=hi2.UserID AND um2.Enabled=\'2\' '; + $Join['hi2'] = ' JOIN users_history_ips AS hi2 ON hi2.IP = hi.IP '; + $Join['um2'] = ' JOIN users_main AS um2 ON um2.ID = hi2.UserID AND um2.Enabled = \'2\' '; } else { - $Join['um2']=' JOIN users_main AS um2 ON um2.IP=um1.IP AND um2.Enabled=\'2\' '; + $Join['um2'] = ' JOIN users_main AS um2 ON um2.IP = um1.IP AND um2.Enabled = \'2\' '; } } if (!empty($_GET['passkey'])) { - $Where[]='um1.torrent_pass'.$Match.wrap($_GET['passkey']); + $Where[] = 'um1.torrent_pass'.$Match.wrap($_GET['passkey']); } if (!empty($_GET['avatar'])) { - $Where[]='ui1.Avatar'.$Match.wrap($_GET['avatar']); + $Where[] = 'ui1.Avatar'.$Match.wrap($_GET['avatar']); } - if ($_GET['stylesheet']!='') { - $Where[]='ui1.StyleID='.wrap($_GET['stylesheet'], '='); + if ($_GET['stylesheet'] != '') { + $Where[] = 'ui1.StyleID = '.wrap($_GET['stylesheet'], '='); } if ($OrderTable[$_GET['order']] && $WayTable[$_GET['way']]) { @@ -432,8 +447,10 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { } list($Page, $Limit) = Format::page_limit(USERS_PER_PAGE); - $SQL.=" LIMIT $Limit"; - } else { error($Err); } + $SQL .= " LIMIT $Limit"; + } else { + error($Err); + } } View::show_header('User search'); @@ -447,7 +464,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { - Joined: + Joined: - Last active: + Last active: @@ -530,11 +547,16 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { Extra: - /> - - - /> - +
      +
    • + /> + +
    • +
    • + /> + +
    • +
    Ratio: @@ -567,7 +589,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { - Uploaded: + Uploaded: - Downloaded: + Downloaded: - - + + /> @@ -666,7 +688,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { - Avatar URL: + Avatar URL: @@ -679,7 +701,7 @@ function num_compare($Field, $Operand, $Num1, $Num2 = '') { - Country code: + Country code: /> | - | - +
      +
    • + /> + +
    • +
    • + /> + +
    • +
    • + /> + +
    • +
    Order: diff --git a/sections/user/community_stats.php b/sections/user/community_stats.php index 35b1f931..7a9f72f4 100644 --- a/sections/user/community_stats.php +++ b/sections/user/community_stats.php @@ -1,27 +1,14 @@ query(" - SELECT COUNT(ID) - FROM torrents_comments - WHERE AuthorID = '$UserID'"); -list($NumComments) = $DB->next_record(); - -$DB->query(" - SELECT COUNT(ID) - FROM artist_comments - WHERE AuthorID = '$UserID'"); -list($NumArtistComments) = $DB->next_record(); - -$DB->query(" - SELECT COUNT(ID) - FROM collages_comments - WHERE UserID = '$UserID'"); -list($NumCollageComments) = $DB->next_record(); - -$DB->query(" - SELECT COUNT(ID) - FROM requests_comments - WHERE AuthorID = '$UserID'"); -list($NumRequestComments) = $DB->next_record(); + SELECT Page, COUNT(1) + FROM comments + WHERE AuthorID = $UserID + GROUP BY Page"); +$Comments = $DB->to_array('Page'); +$NumComments = $Comments['torrents'][1]; +$NumArtistComments = $Comments['artist'][1]; +$NumCollageComments = $Comments['collages'][1]; +$NumRequestComments = $Comments['requests'][1]; $DB->query(" SELECT COUNT(ID) @@ -71,7 +58,7 @@
  • >Artist comments: - View + View
  • >Collage comments: diff --git a/sections/user/connchecker.php b/sections/user/connchecker.php index cc49371d..5e96dea1 100644 --- a/sections/user/connchecker.php +++ b/sections/user/connchecker.php @@ -2,18 +2,18 @@ //TODO: Move to somewhere more appropriate, doesn't really belong under users, tools maybe but we don't have that page publicly accessible. if (isset($_GET['ip']) && isset($_GET['port'])) { - $Octets = explode(".", $_GET['ip']); + $Octets = explode('.', $_GET['ip']); if ( - empty($_GET['ip']) || - !preg_match('/'.IP_REGEX.'/', $_GET['ip']) || - $Octets[0] < 0 || - $Octets[0] > 255 || - $Octets[1] < 0 || - $Octets[1] > 255 || - $Octets[2] < 0 || - $Octets[2] > 255 || - $Octets[3] < 0 || - $Octets[3] > 255 || + empty($_GET['ip']) + || !preg_match('/'.IP_REGEX.'/', $_GET['ip']) + || $Octets[0] < 0 + || $Octets[0] > 255 + || $Octets[1] < 0 + || $Octets[1] > 255 + || $Octets[2] < 0 + || $Octets[2] > 255 + || $Octets[3] < 0 + || $Octets[3] > 255 /* * Per RFC 1918, the following CIDR blocks should never be found on the public Internet. * 10.0.0.0/8 @@ -23,10 +23,10 @@ * Per RFC 3330, the block 127.0.0.0/8 should never appear on any network. * */ - $Octets[0] == 127 || - $Octets[0] == 10 || - ($Octets[0] == 172 && ((16 <= $Octets[1]) && ($Octets[1] <= 31))) || - ($Octets[0] == 192 && $Octets[1] == 168) + || $Octets[0] == 127 + || $Octets[0] == 10 + || ($Octets[0] == 172 && ((16 <= $Octets[1]) && ($Octets[1] <= 31))) + || ($Octets[0] == 192 && $Octets[1] == 168) ) { die('Invalid IPv4 address'); } diff --git a/sections/user/donor_stats.php b/sections/user/donor_stats.php new file mode 100644 index 00000000..fe3e3d2e --- /dev/null +++ b/sections/user/donor_stats.php @@ -0,0 +1,18 @@ + +
    +
    Donor Statistics
    +
      +
    • + Total donor points: +
    • +
    • + Current donor rank: +
    • +
    • + Last donated: +
    • +
    +
    +query(" SELECT m.Username, @@ -14,18 +12,18 @@ m.Paranoia, i.Info, i.Avatar, - i.Country, i.StyleID, i.StyleURL, i.SiteOptions, i.UnseededAlerts, - p.Level AS Class + i.DownloadAlt, + p.Level AS Class, + i.InfoTitle FROM users_main AS m JOIN users_info AS i ON i.UserID = m.ID LEFT JOIN permissions AS p ON p.ID = m.PermissionID WHERE m.ID = '".db_string($UserID)."'"); -list($Username, $Email, $IRCKey, $Paranoia, $Info, $Avatar, $Country, $StyleID, $StyleURL, $SiteOptions, $UnseededAlerts, $Class) = $DB->next_record(MYSQLI_NUM, array(3, 9)); - +list($Username, $Email, $IRCKey, $Paranoia, $Info, $Avatar, $StyleID, $StyleURL, $SiteOptions, $UnseededAlerts, $DownloadAlt, $Class, $InfoTitle) = $DB->next_record(MYSQLI_NUM, array(3, 8)); if ($UserID != $LoggedUser['ID'] && !check_perms('users_edit_profiles', $Class)) { error(403); @@ -58,10 +56,23 @@ function checked($Checked) { $SiteOptions = array(); } -View::show_header($Username.' > Settings','user,jquery-ui,release_sort,password_validate,validate,push_settings,cssgallery,preview_paranoia,bbcode'); +View::show_header("$Username > Settings", 'user,jquery-ui,release_sort,password_validate,validate,push_settings,cssgallery,preview_paranoia,bbcode,user_settings,donor_titles'); + +$DonorRank = Donations::get_rank($UserID); +$DonorIsVisible = Donations::is_visible($UserID); + +if ($DonorIsVisible === null) { + $DonorIsVisible = true; +} + +extract(Donations::get_enabled_rewards($UserID)); +$Rewards = Donations::get_rewards($UserID); +$ProfileRewards = Donations::get_profile_rewards($UserID); +$DonorTitles = Donations::get_titles($UserID); + $DB->query(" SELECT username FROM lastfm_users @@ -74,51 +85,109 @@ function checked($Checked) {

    > Settings

    -
    + + +
    - +
    - - + + - - + + + + + + + + + + - - + + +
    - Site preferences + Site Appearance Settings
    Stylesheet
    Stylesheet    Show gallery -     - Or -     - External CSS:
    OpenDyslexic
    External stylesheet URL - checked="checked" /> - -

    Read about OpenDyslexic, a CC-BY 3.0 licensed font designed for users with dyslexia, at http://opendyslexic.org/.

    -

    This is an experimental feature, and some stylesheets will have display issues.

    + +
    OpenDyslexic +
    + /> + +
    +

    This is an experimental feature, and some stylesheets will have display issues.

    +
    Styled tooltips + /> +
    Profile stats
    Profile stats
    + - - + + - - + + + + + + - - + + - - + + - - + +
    - Torrent options + Torrent Settings
    Default search type
    Default search type
    • - checked="checked" /> + />
    • - checked="checked" /> + />
    Torrent grouping
    Torrent grouping
    /> - +
    +
    Torrent group display (search)
    -

    By default, torrent groups are:

    • - checked="checked" /> + />
    • - checked="checked" /> + />
    Default discography view
    Torrent group display (artist pages)
    • - checked="checked" /> + />
    • - checked="checked" /> + />
    Show snatched torrents
    Snatched torrents indicator - checked="checked" /> - + /> +
    Sort/hide release types
    Release type display (artist pages) - Expand