Browse Source

Remove /sections/ajax

biotorrents 4 years ago
parent
commit
8ed8ffd1d8
65 changed files with 71 additions and 5764 deletions
  1. 0
    4
      ajax.php
  2. 1
    1
      manifest.php
  3. 0
    83
      sections/ajax/announcements.php
  4. 0
    362
      sections/ajax/artist.php
  5. 0
    60
      sections/ajax/autofill/anime.php
  6. 0
    234
      sections/ajax/autofill/jav.php
  7. 0
    106
      sections/ajax/autofill/manga.php
  8. 0
    38
      sections/ajax/better/index.php
  9. 0
    55
      sections/ajax/better/single.php
  10. 0
    131
      sections/ajax/better/transcode.php
  11. 0
    63
      sections/ajax/bookmarks/artists.php
  12. 0
    47
      sections/ajax/bookmarks/index.php
  13. 0
    124
      sections/ajax/bookmarks/torrents.php
  14. 0
    132
      sections/ajax/browse.php
  15. 0
    49
      sections/ajax/clear_user_notification.php
  16. 0
    174
      sections/ajax/collage.php
  17. 0
    70
      sections/ajax/community_stats.php
  18. 0
    180
      sections/ajax/forum/forum.php
  19. 0
    34
      sections/ajax/forum/index.php
  20. 0
    117
      sections/ajax/forum/main.php
  21. 0
    291
      sections/ajax/forum/thread.php
  22. 0
    21
      sections/ajax/get_friends.php
  23. 0
    8
      sections/ajax/get_user_notifications.php
  24. 0
    118
      sections/ajax/inbox/inbox.php
  25. 0
    13
      sections/ajax/inbox/index.php
  26. 0
    106
      sections/ajax/inbox/viewconv.php
  27. 0
    291
      sections/ajax/index.php
  28. 0
    117
      sections/ajax/info.php
  29. 0
    14
      sections/ajax/loadavg.php
  30. 0
    42
      sections/ajax/news_ajax.php
  31. 0
    110
      sections/ajax/notifications.php
  32. 0
    12
      sections/ajax/ontology.php
  33. 0
    12
      sections/ajax/preview.php
  34. 0
    32
      sections/ajax/raw_bbcode.php
  35. 0
    119
      sections/ajax/request.php
  36. 0
    369
      sections/ajax/requests.php
  37. 0
    90
      sections/ajax/send_recommendation.php
  38. 0
    165
      sections/ajax/stats.php
  39. 0
    92
      sections/ajax/subscriptions.php
  40. 0
    42
      sections/ajax/tcomments.php
  41. 0
    32
      sections/ajax/top10/index.php
  42. 0
    83
      sections/ajax/top10/tags.php
  43. 0
    185
      sections/ajax/top10/torrents.php
  44. 0
    130
      sections/ajax/top10/users.php
  45. 0
    105
      sections/ajax/torrent.php
  46. 0
    101
      sections/ajax/torrentgroup.php
  47. 0
    22
      sections/ajax/torrentgroupalbumart.php
  48. 0
    485
      sections/ajax/user.php
  49. 0
    96
      sections/ajax/user_recents.php
  50. 0
    20
      sections/ajax/userhistory/index.php
  51. 0
    186
      sections/ajax/userhistory/post_history.php
  52. 0
    58
      sections/ajax/usersearch.php
  53. 0
    41
      sections/ajax/wiki.php
  54. 1
    1
      sections/api/forum/thread.php
  55. 1
    1
      static/functions/ajax.class.js
  56. 4
    4
      static/functions/comments.js
  57. 1
    1
      static/functions/inbox.js
  58. 34
    34
      static/functions/news_ajax.js
  59. 0
    19
      static/functions/password_validate.js
  60. 20
    20
      static/functions/recommend.js
  61. 1
    1
      static/functions/requests.js
  62. 2
    5
      static/functions/textareapreview.class.js
  63. 3
    3
      static/functions/upload.js
  64. 2
    2
      static/functions/user.js
  65. 1
    1
      static/functions/user_notifications.js

+ 0
- 4
ajax.php View File

1
-<?php
2
-declare(strict_types=1);
3
-
4
-require_once 'classes/script_start.php';

+ 1
- 1
manifest.php View File

31
 
31
 
32
     # Print header and $manifest for remote addresses
32
     # Print header and $manifest for remote addresses
33
     # Return JSON for localhost (API manifest endpoint):
33
     # Return JSON for localhost (API manifest endpoint):
34
-    #   ajax.php?action=manifest
34
+    #   api.php?action=manifest
35
     if ($_SERVER['REMOTE_ADDR'] !== "127.0.0.1") {
35
     if ($_SERVER['REMOTE_ADDR'] !== "127.0.0.1") {
36
         header('Content-type: application/json; charset=utf-8');
36
         header('Content-type: application/json; charset=utf-8');
37
         echo $manifest;
37
         echo $manifest;

+ 0
- 83
sections/ajax/announcements.php View File

1
-<?
2
-if (!$News = $Cache->get_value('news')) {
3
-  $DB->query("
4
-    SELECT
5
-      ID,
6
-      Title,
7
-      Body,
8
-      Time
9
-    FROM news
10
-    ORDER BY Time DESC
11
-    LIMIT 5");
12
-  $News = $DB->to_array(false, MYSQLI_NUM, false);
13
-  $Cache->cache_value('news', $News, 3600 * 24 * 30);
14
-  $Cache->cache_value('news_latest_id', $News[0][0], 0);
15
-}
16
-
17
-if ($LoggedUser['LastReadNews'] != $News[0][0]) {
18
-  $Cache->begin_transaction("user_info_heavy_$UserID");
19
-  $Cache->update_row(false, array('LastReadNews' => $News[0][0]));
20
-  $Cache->commit_transaction(0);
21
-  $DB->query("
22
-    UPDATE users_info
23
-    SET LastReadNews = '".$News[0][0]."'
24
-    WHERE UserID = $UserID");
25
-  $LoggedUser['LastReadNews'] = $News[0][0];
26
-}
27
-
28
-if (($Blog = $Cache->get_value('blog')) === false) {
29
-  $DB->query("
30
-    SELECT
31
-      b.ID,
32
-      um.Username,
33
-      b.UserID,
34
-      b.Title,
35
-      b.Body,
36
-      b.Time,
37
-      b.ThreadID
38
-    FROM blog AS b
39
-      LEFT JOIN users_main AS um ON b.UserID = um.ID
40
-    ORDER BY Time DESC
41
-    LIMIT 20");
42
-  $Blog = $DB->to_array();
43
-  $Cache->cache_value('blog', $Blog, 1209600);
44
-}
45
-$JsonBlog = [];
46
-for ($i = 0; $i < 5; $i++) {
47
-  list($BlogID, $Author, $AuthorID, $Title, $Body, $BlogTime, $ThreadID) = $Blog[$i];
48
-  $JsonBlog[] = array(
49
-    'blogId' => (int)$BlogID,
50
-    'author' => $Author,
51
-    'title' => $Title,
52
-    'bbBody' => $Body,
53
-    'body' => Text::full_format($Body),
54
-    'blogTime' => $BlogTime,
55
-    'threadId' => (int)$ThreadID
56
-  );
57
-}
58
-
59
-$JsonAnnouncements = [];
60
-$Count = 0;
61
-foreach ($News as $NewsItem) {
62
-  list($NewsID, $Title, $Body, $NewsTime) = $NewsItem;
63
-  if (strtotime($NewsTime) > time()) {
64
-    continue;
65
-  }
66
-
67
-  $JsonAnnouncements[] = array(
68
-    'newsId' => (int)$NewsID,
69
-    'title' => $Title,
70
-    'bbBody' => $Body,
71
-    'body' => Text::full_format($Body),
72
-    'newsTime' => $NewsTime
73
-  );
74
-
75
-  if (++$Count > 4) {
76
-    break;
77
-  }
78
-}
79
-
80
-json_die("success", array(
81
-  'announcements' => $JsonAnnouncements,
82
-  'blogPosts' => $JsonBlog
83
-));

+ 0
- 362
sections/ajax/artist.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-
6
-// For sorting tags
7
-function compare($X, $Y)
8
-{
9
-    return($Y['count'] - $X['count']);
10
-}
11
-
12
-if (!empty($_GET['artistreleases'])) {
13
-    $OnlyArtistReleases = true;
14
-}
15
-
16
-if ($_GET['id'] && $_GET['artistname']) {
17
-    json_die('failure', 'bad parameters');
18
-}
19
-
20
-$ArtistID = $_GET['id'];
21
-if ($ArtistID && !is_number($ArtistID)) {
22
-    json_die('failure');
23
-}
24
-
25
-if (empty($ArtistID)) {
26
-    if (!empty($_GET['artistname'])) {
27
-        $Name = db_string(trim($_GET['artistname']));
28
-        $DB->query("
29
-      SELECT ArtistID
30
-      FROM artists_alias
31
-      WHERE Name LIKE '$Name'");
32
-        if (!(list($ArtistID) = $DB->next_record(MYSQLI_NUM, false))) {
33
-            json_die('failure');
34
-        }
35
-        // If we get here, we got the ID!
36
-    }
37
-}
38
-
39
-if (!empty($_GET['revisionid'])) { // if they're viewing an old revision
40
-    $RevisionID = $_GET['revisionid'];
41
-    if (!is_number($RevisionID)) {
42
-        error(0);
43
-    }
44
-    $Data = $Cache->get_value("artist_$ArtistID"."_revision_$RevisionID");
45
-} else { // viewing the live version
46
-    $Data = $Cache->get_value("artist_$ArtistID");
47
-    $RevisionID = false;
48
-}
49
-if ($Data) {
50
-    list($Name, $Image, $Body) = current($Data);
51
-} else {
52
-    if ($RevisionID) {
53
-        /*
54
-          $sql = "
55
-            SELECT
56
-              a.Name,
57
-              wiki.Image,
58
-              wiki.body,
59
-              a.VanityHouse
60
-            FROM wiki_artists AS wiki
61
-              LEFT JOIN artists_group AS a ON wiki.RevisionID = a.RevisionID
62
-            WHERE wiki.RevisionID = '$RevisionID' ";
63
-        */
64
-        $sql = "
65
-      SELECT
66
-        a.Name,
67
-        wiki.Image,
68
-        wiki.body
69
-      FROM wiki_artists AS wiki
70
-        LEFT JOIN artists_group AS a ON wiki.RevisionID = a.RevisionID
71
-      WHERE wiki.RevisionID = '$RevisionID' ";
72
-    } else {
73
-        /*
74
-          $sql = "
75
-            SELECT
76
-              a.Name,
77
-              wiki.Image,
78
-              wiki.body,
79
-              a.VanityHouse
80
-            FROM artists_group AS a
81
-              LEFT JOIN wiki_artists AS wiki ON wiki.RevisionID = a.RevisionID
82
-            WHERE a.ArtistID = '$ArtistID' ";
83
-        */
84
-        $sql = "
85
-      SELECT
86
-        a.Name,
87
-        wiki.Image,
88
-        wiki.body
89
-      FROM artists_group AS a
90
-        LEFT JOIN wiki_artists AS wiki ON wiki.RevisionID = a.RevisionID
91
-      WHERE a.ArtistID = '$ArtistID' ";
92
-    }
93
-    $sql .= " GROUP BY a.ArtistID";
94
-    $DB->query($sql);
95
-
96
-    if (!$DB->has_results()) {
97
-        json_die('failure');
98
-    }
99
-
100
-    //  list($Name, $Image, $Body, $VanityHouseArtist) = $DB->next_record(MYSQLI_NUM, array(0));
101
-    list($Name, $Image, $Body) = $DB->next_record(MYSQLI_NUM, array(0));
102
-}
103
-
104
-// Requests
105
-$Requests = [];
106
-if (empty($LoggedUser['DisableRequests'])) {
107
-    $Requests = $Cache->get_value("artists_requests_$ArtistID");
108
-    if (!is_array($Requests)) {
109
-        $DB->query("
110
-      SELECT
111
-        r.ID,
112
-        r.CategoryID,
113
-        r.Title,
114
-        r.Year,
115
-        r.TimeAdded,
116
-        COUNT(rv.UserID) AS Votes,
117
-        SUM(rv.Bounty) AS Bounty
118
-      FROM requests AS r
119
-        LEFT JOIN requests_votes AS rv ON rv.RequestID = r.ID
120
-        LEFT JOIN requests_artists AS ra ON r.ID = ra.RequestID
121
-      WHERE ra.ArtistID = $ArtistID
122
-        AND r.TorrentID = 0
123
-      GROUP BY r.ID
124
-      ORDER BY Votes DESC");
125
-
126
-        if ($DB->has_results()) {
127
-            $Requests = $DB->to_array('ID', MYSQLI_ASSOC, false);
128
-        } else {
129
-            $Requests = [];
130
-        }
131
-        $Cache->cache_value("artists_requests_$ArtistID", $Requests);
132
-    }
133
-}
134
-$NumRequests = count($Requests);
135
-
136
-if (($Importances = $Cache->get_value("artist_groups_$ArtistID")) === false) {
137
-    $DB->query("
138
-    SELECT DISTINCTROW
139
-      ta.`GroupID`,
140
-      ta.`Importance`,
141
-      tg.`published`
142
-    FROM
143
-      `torrents_artists` AS ta
144
-    JOIN `torrents_group` AS tg
145
-    ON
146
-      tg.`id` = ta.`GroupID`
147
-    WHERE
148
-      ta.`ArtistID` = '$ArtistID'
149
-    ORDER BY
150
-      tg.`published`,
151
-      tg.`Name`
152
-    DESC
153
-    ");
154
-    
155
-    $GroupIDs = $DB->collect('GroupID');
156
-    $Importances = $DB->to_array(false, MYSQLI_BOTH, false);
157
-    $Cache->cache_value("artist_groups_$ArtistID", $Importances, 0);
158
-} else {
159
-    $GroupIDs = [];
160
-    foreach ($Importances as $Group) {
161
-        $GroupIDs[] = $Group['GroupID'];
162
-    }
163
-}
164
-if (count($GroupIDs) > 0) {
165
-    $TorrentList = Torrents::get_groups($GroupIDs, true, true);
166
-} else {
167
-    $TorrentList = [];
168
-}
169
-$NumGroups = count($TorrentList);
170
-
171
-//Get list of used release types
172
-$UsedReleases = [];
173
-foreach ($TorrentList as $GroupID=>$Group) {
174
-    if ($Importances[$GroupID]['Importance'] == '2') {
175
-        $TorrentList[$GroupID]['ReleaseType'] = 1024;
176
-        $GuestAlbums = true;
177
-    }
178
-    if ($Importances[$GroupID]['Importance'] == '3') {
179
-        $TorrentList[$GroupID]['ReleaseType'] = 1023;
180
-        $RemixerAlbums = true;
181
-    }
182
-    if ($Importances[$GroupID]['Importance'] == '4') {
183
-        $TorrentList[$GroupID]['ReleaseType'] = 1022;
184
-        $ComposerAlbums = true;
185
-    }
186
-    if ($Importances[$GroupID]['Importance'] == '7') {
187
-        $TorrentList[$GroupID]['ReleaseType'] = 1021;
188
-        $ProducerAlbums = true;
189
-    }
190
-    if (!in_array($TorrentList[$GroupID]['ReleaseType'], $UsedReleases)) {
191
-        $UsedReleases[] = $TorrentList[$GroupID]['ReleaseType'];
192
-    }
193
-}
194
-
195
-if (!empty($GuestAlbums)) {
196
-    $ReleaseTypes[1024] = 'Guest Appearance';
197
-}
198
-if (!empty($RemixerAlbums)) {
199
-    $ReleaseTypes[1023] = 'Remixed By';
200
-}
201
-if (!empty($ComposerAlbums)) {
202
-    $ReleaseTypes[1022] = 'Composition';
203
-}
204
-if (!empty($ProducerAlbums)) {
205
-    $ReleaseTypes[1021] = 'Produced By';
206
-}
207
-
208
-reset($TorrentList);
209
-
210
-$JsonTorrents = [];
211
-$Tags = [];
212
-$NumTorrents = $NumSeeders = $NumLeechers = $NumSnatches = 0;
213
-foreach ($GroupIDs as $GroupID) {
214
-    if (!isset($TorrentList[$GroupID])) {
215
-        continue;
216
-    }
217
-    $Group = $TorrentList[$GroupID];
218
-    extract(Torrents::array_group($Group));
219
-
220
-    foreach ($Artists as &$Artist) {
221
-        $Artist['id'] = (int)$Artist['id'];
222
-        $Artist['aliasid'] = (int)$Artist['aliasid'];
223
-    }
224
-
225
-    foreach ($ExtendedArtists as &$ArtistGroup) {
226
-        foreach ($ArtistGroup as &$Artist) {
227
-            $Artist['id'] = (int)$Artist['id'];
228
-            $Artist['aliasid'] = (int)$Artist['aliasid'];
229
-        }
230
-    }
231
-
232
-    $Found = Misc::search_array($Artists, 'id', $ArtistID);
233
-    if (isset($OnlyArtistReleases) && empty($Found)) {
234
-        continue;
235
-    }
236
-
237
-    $GroupVanityHouse = $Importances[$GroupID]['VanityHouse'];
238
-
239
-    $TagList = explode(' ', str_replace('_', '.', $TagList));
240
-
241
-    // $Tags array is for the sidebar on the right
242
-    foreach ($TagList as $Tag) {
243
-        if (!isset($Tags[$Tag])) {
244
-            $Tags[$Tag] = array('name' => $Tag, 'count' => 1);
245
-        } else {
246
-            $Tags[$Tag]['count']++;
247
-        }
248
-    }
249
-    $InnerTorrents = [];
250
-    foreach ($Torrents as $Torrent) {
251
-        $NumTorrents++;
252
-        $NumSeeders += $Torrent['Seeders'];
253
-        $NumLeechers += $Torrent['Leechers'];
254
-        $NumSnatches += $Torrent['Snatched'];
255
-
256
-        $InnerTorrents[] = array(
257
-      'id' => (int)$Torrent['ID'],
258
-      'groupId' => (int)$Torrent['GroupID'],
259
-      'media' => $Torrent['Media'],
260
-      'format' => $Torrent['Format'],
261
-      'encoding' => $Torrent['Encoding'],
262
-      'remasterYear' => (int)$Torrent['RemasterYear'],
263
-      'remastered' => $Torrent['Remastered'] == 1,
264
-      'remasterTitle' => $Torrent['RemasterTitle'],
265
-      'remasterRecordLabel' => $Torrent['RemasterRecordLabel'],
266
-      'scene' => $Torrent['Scene'] == 1,
267
-      'hasLog' => $Torrent['HasLog'] == 1,
268
-      'hasCue' => $Torrent['HasCue'] == 1,
269
-      'logScore' => (int)$Torrent['LogScore'],
270
-      'fileCount' => (int)$Torrent['FileCount'],
271
-      'freeTorrent' => $Torrent['FreeTorrent'] == 1,
272
-      'size' => (int)$Torrent['Size'],
273
-      'leechers' => (int)$Torrent['Leechers'],
274
-      'seeders' => (int)$Torrent['Seeders'],
275
-      'snatched' => (int)$Torrent['Snatched'],
276
-      'time' => $Torrent['Time'],
277
-      'hasFile' => (int)$Torrent['HasFile']
278
-    );
279
-    }
280
-    $JsonTorrents[] = array(
281
-    'groupId' => (int)$GroupID,
282
-    'groupName' => $GroupName,
283
-    'groupYear' => (int)$GroupYear,
284
-    'groupRecordLabel' => $GroupRecordLabel,
285
-    'groupCatalogueNumber' => $GroupCatalogueNumber,
286
-    'groupCategoryID' => $GroupCategoryID,
287
-    'tags' => $TagList,
288
-    'releaseType' => (int)$ReleaseType,
289
-    'wikiImage' => $WikiImage,
290
-    'groupVanityHouse' => $GroupVanityHouse == 1,
291
-    'hasBookmarked' => Bookmarks::has_bookmarked('torrent', $GroupID),
292
-    'artists' => $Artists,
293
-    'extendedArtists' => $ExtendedArtists,
294
-    'torrent' => $InnerTorrents,
295
-
296
-  );
297
-}
298
-
299
-$JsonRequests = [];
300
-foreach ($Requests as $RequestID => $Request) {
301
-    $JsonRequests[] = array(
302
-    'requestId' => (int)$RequestID,
303
-    'categoryId' => (int)$Request['CategoryID'],
304
-    'title' => $Request['Title'],
305
-    'year' => (int)$Request['Year'],
306
-    'timeAdded' => $Request['TimeAdded'],
307
-    'votes' => (int)$Request['Votes'],
308
-    'bounty' => (int)$Request['Bounty']
309
-  );
310
-}
311
-
312
-//notifications disabled by default
313
-$notificationsEnabled = false;
314
-if (check_perms('site_torrents_notify')) {
315
-    if (($Notify = $Cache->get_value('notify_artists_'.$LoggedUser['ID'])) === false) {
316
-        $DB->query("
317
-      SELECT ID, Artists
318
-      FROM users_notify_filters
319
-      WHERE UserID = '$LoggedUser[ID]'
320
-        AND Label = 'Artist notifications'
321
-      LIMIT 1");
322
-        $Notify = $DB->next_record(MYSQLI_ASSOC, false);
323
-        $Cache->cache_value('notify_artists_'.$LoggedUser['ID'], $Notify, 0);
324
-    }
325
-    if (stripos($Notify['Artists'], "|$Name|") === false) {
326
-        $notificationsEnabled = false;
327
-    } else {
328
-        $notificationsEnabled = true;
329
-    }
330
-}
331
-
332
-// Cache page for later use
333
-
334
-if ($RevisionID) {
335
-    $Key = "artist_$ArtistID"."_revision_$RevisionID";
336
-} else {
337
-    $Key = "artist_$ArtistID";
338
-}
339
-
340
-$Data = array(array($Name, $Image, $Body));
341
-
342
-$Cache->cache_value($Key, $Data, 3600);
343
-
344
-json_die('success', array(
345
-  'id' => (int)$ArtistID,
346
-  'name' => $Name,
347
-  'notificationsEnabled' => $notificationsEnabled,
348
-  'hasBookmarked' => Bookmarks::has_bookmarked('artist', $ArtistID),
349
-  'image' => $Image,
350
-  'body' => Text::full_format($Body),
351
-  'vanityHouse' => $VanityHouseArtist == 1,
352
-  'tags' => array_values($Tags),
353
-  'statistics' => array(
354
-    'numGroups' => $NumGroups,
355
-    'numTorrents' => $NumTorrents,
356
-    'numSeeders' => $NumSeeders,
357
-    'numLeechers' => $NumLeechers,
358
-    'numSnatches' => $NumSnatches
359
-  ),
360
-  'torrentgroup' => $JsonTorrents,
361
-  'requests' => $JsonRequests
362
-));

+ 0
- 60
sections/ajax/autofill/anime.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (empty($_GET['aid'])) {
5
-  json_die();
6
-}
7
-
8
-$aid = $_GET['aid'];
9
-
10
-if ($Cache->get_value('anime_fill_json_'.$aid)) {
11
-  json_die("success", $Cache->get_value('anime_fill_json_'.$aid));
12
-} else {
13
-
14
-  $anidb_url = 'http://api.anidb.net:9001/httpapi?request=anime&client='.API_KEYS['ANIDB'].'&clientver=1&protover=1&aid='.$aid;
15
-
16
-  $crl = curl_init();
17
-  curl_setopt($crl, CURLOPT_URL, $anidb_url);
18
-  curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
19
-  curl_setopt($crl, CURLOPT_CONNEECTTIMEOUT, 5);
20
-  $ret = curl_exec($crl);
21
-  curl_close($curl);
22
-
23
-  $anidb_xml = new SimpleXMLElement(zlib_decode($ret));
24
-
25
-  if ($anidb_xml->xpath('/error')) {
26
-    json_die("failure", $anidb_xml->xpath('/error')[0]."");
27
-  }
28
-
29
-  $title = $anidb_xml->xpath('//titles/title[@xml:lang = "en" and @type = "official"]')[0].'';
30
-  $title = (empty($title))?$anidb_xml->xpath('//titles/title[@xml:lang = "en"]')[0].'':$title;
31
-  $title = (empty($title))?$anidb_xml->xpath('//titles/title[@type = "main"]')[0].'':$title;
32
-
33
-  $title_rj = $anidb_xml->xpath('//titles/title[@xml:lang = "x-jat" and @type = "official"]')[0].'';
34
-  $title_rj = (empty($title_rj))?$anidb_xml->xpath('//titles/title[@xml:lang = "x-jat"]')[0].'':$title_rj;
35
-
36
-  $title_jp = $anidb_xml->xpath('//titles/title[@xml:lang = "ja" and @type = "official"]')[0].'';
37
-  $title_jp = (empty($title_jp))?$anidb_xml->xpath('//titles/title[@xml:lang = "ja"]')[0].'':$title_jp;
38
-
39
-  $artist = $anidb_xml->xpath('//creators/name[@type = "Animation Work"]')[0].'';
40
-
41
-  $year = substr($anidb_xml->startdate, 0, 4);
42
-
43
-  $desc = preg_replace('/http:\/\/anidb.net\S+ \[(.*?)\]/', '$1', ($anidb_xml->description).'');
44
-
45
-  $json_str = array(
46
-    'id' => $aid,
47
-    'title' => $title,
48
-    'title_rj' => $title_rj,
49
-    'title_jp' => $title_jp,
50
-    'artist' => $artist,
51
-    'year' => $year,
52
-    'description' => $desc
53
-  );
54
-
55
-  $Cache->cache_value('anime_fill_json_'.$aid, $json_str, 86400);
56
-
57
-  json_die("success", $json_str);
58
-}
59
-
60
-?>

+ 0
- 234
sections/ajax/autofill/jav.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# Headers, cache, etc.
5
-$debug = false;
6
-
7
-if (empty($_GET['cn'])) {
8
-  json_die();
9
-}
10
-
11
-$cn = strtoupper($_GET['cn']);
12
-
13
-if (!strpos($cn, '-')) {
14
-  preg_match('/\d/', $cn, $m, PREG_OFFSET_CAPTURE);
15
-  if ($m) { $cn = substr_replace($cn, '-', $m[0][1], 0); }
16
-}
17
-
18
-if (!$debug && $Cache->get_value('jav_fill_json_'.$cn)) {
19
-  json_die('success', $Cache->get_value('jav_fill_json_'.$cn));
20
-} else {
21
-
22
-  # Query the API
23
-  # todo: Validate to change $db
24
-
25
-/* todo
26
- * switch $category:
27
- *   case 'DNA' || 'RNA':
28
- *     if $number = refseq_regex:
29
- *        $db = 'refseq';
30
- *     break;
31
- *   case 'Protein':
32
- *     if $number = uniprot_regex:
33
- *        $db = 'uniprot';
34
- *     break;
35
- *   default:
36
- *     error 'invalid number';
37
- *     break;
38
- */
39
-$id = 'NM_001183340.1';
40
-
41
-# Assemble the esearch URL
42
-$base = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/';
43
-$url = $base . "esummary.fcgi?db=$db&id=$id&version=2.0";
44
-
45
-# Post the esearch URL
46
-$output = file_get_contents($url);
47
-
48
-# Parse WebEnv and QueryKey
49
-#$web = $1 if ($output =~ /<WebEnv>(\S+)<\/WebEnv>/);
50
-#$key = $1 if ($output =~ /<QueryKey>(\d+)<\/QueryKey>/);
51
-
52
-### Include this code for ESearch-ESummary
53
-# Assemble the esummary URL
54
-$url = $base . "esummary.fcgi?db=$db&query_key=$key&WebEnv=$web";
55
-
56
-# Post the esummary URL
57
-$docsums = file_get_contents($url);
58
-echo "$docsums";
59
-
60
-### Include this code for ESearch-EFetch
61
-# Assemble the efetch URL
62
-$url = $base . "efetch.fcgi?db=$db&query_key=$key&WebEnv=$web";
63
-$url .= "&rettype=abstract&retmode=text";
64
-
65
-# Post the efetch URL
66
-$data = file_get_contents($url);
67
-echo "$data";
68
-
69
-  /*
70
-  $jlib_jp_url = ('http://www.javlibrary.com/ja/vl_searchbyid.php?keyword='.$cn);
71
-  $jlib_en_url = ('http://www.javlibrary.com/en/vl_searchbyid.php?keyword='.$cn);
72
-  $jdb_url     = ('http://javdatabase.com/movies/'.$cn.'/');
73
-
74
-  $jlib_page_jp = file_get_contents($jlib_jp_url);
75
-  $jlib_page_en = file_get_contents($jlib_en_url);
76
-  $jdb_page     = file_get_contents($jdb_url);
77
-
78
-  if ($jlib_page_en) {
79
-    $jlib_dom_en = new DOMDocument();
80
-    $jlib_dom_en->loadHTML($jlib_page_en);
81
-    $jlib_en = new DOMXPath($jlib_dom_en);
82
-
83
-    // Check if we're still on the search page and fix it if so
84
-    if($jlib_en->query("//a[starts-with(@title, \"$cn\")]")->item(0)) {
85
-      $href = substr($jlib_en->query("//a[starts-with(@title, \"$cn\")]")->item(0)->getAttribute('href'),1);
86
-      $jlib_page_en = file_get_contents('http://www.javlibrary.com/en/'.$href);
87
-      $jlib_page_jp = file_get_contents('http://www.javlibrary.com/ja/'.$href);
88
-      $jlib_dom_en->loadHTML($jlib_page_en);
89
-      $jlib_en = new DOMXPath($jlib_dom_en);
90
-      // If the provided CN was so bad that search provided a different match, die
91
-      if(strtoupper($jlib_en->query('//*[@id="video_id"]/table/tr/td[2]')->item(0)->nodeValue) != $cn) {
92
-        json_die('failure', 'Movie not found');
93
-      }
94
-    }
95
-  }
96
-  if ($jlib_page_jp) {
97
-    $jlib_dom_jp = new DOMDocument();
98
-    $jlib_dom_jp->loadHTML($jlib_page_jp);
99
-    $jlib_jp = new DOMXPath($jlib_dom_jp);
100
-  }
101
-  if ($jdb_page) {
102
-    $jdb_dom = new DOMDocument();
103
-    $jdb_dom->loadHTML($jdb_page);
104
-    $jdb = new DOMXPath($jdb_dom);
105
-  }
106
-
107
-  list($idols, $genres, $screens, $title, $title_jp, $year, $studio, $label, $desc, $image) = array([],[],[],'','','','','','','');
108
-
109
-  if (!$jdb_page && !$jlib_page_jp && !$jlib_page_en) {
110
-    json_die('failure', 'Movie not found');
111
-  }
112
-
113
-  $degraded = false;
114
-
115
-  if ($jlib_page_jp && $jlib_jp->query('//*[@id="video_title"]')['length']) {
116
-    $title_jp = $jlib_jp->query('//*[@id="video_title"]/h3/a')->item(0)->nodeValue;
117
-    $title_jp = substr($title_jp, strlen($cn) + 1);
118
-  } else {
119
-    $degraded = true;
120
-  }
121
-  if ($jlib_page_en && $jlib_en->query('//*[@id="video_title"]')['length']) {
122
-    $title = $jlib_en->query('//*[@id="video_title"]/h3/a')->item(0)->nodeValue;
123
-    $title = substr($title, strlen($cn) + 1);
124
-    $idols = [];
125
-    foreach ($jlib_en->query('//*[starts-with(@id, "cast")]/span[1]/a') as $idol) {
126
-      $idols[] = $idol->nodeValue;
127
-    }
128
-    $year = $jlib_en->query('//*[@id="video_date"]/table/tr/td[2]')->item(0)->nodeValue;
129
-    $year = explode('-', $year)[0];
130
-    $studio = $jlib_en->query('//*[starts-with(@id, "maker")]/a')->item(0)->nodeValue;
131
-    $label = $jlib_en->query('//*[starts-with(@id, "label")]/a')->item(0)->nodeValue;
132
-    $image = $jlib_en->query('//*[@id="video_jacket_img"]')->item(0)->getAttribute('src');
133
-    $comments = "";
134
-    foreach ($jlib_en->query('//*[@class="comment"]//*[@class="t"]//textarea') as $comment) {
135
-      $comments .= ($comment->nodeValue).' ';
136
-    }
137
-    preg_match_all("/\[img\b[^\]]*\]([^\[]*?)\[\/img\](?!\[\/url)/is", $comments, $screens_t);
138
-    if (isset($screens_t[1])) {
139
-      $screens = $screens_t[1];
140
-      function f($s) { return !(preg_match('/(rapidgator)|(uploaded)|(javsecret)|(\.gif)|(google)|(thumb)|(imgur)|(fileboom)|(openload)/', $s)); }
141
-      $screens = array_values(array_filter($screens, f));
142
-    }
143
-    if (preg_match('/http:\/\/imagetwist.com\/\S*jpg.html/', $comments, $twist)) {
144
-      $twist_t = file_get_contents($twist[0]);
145
-      $twist = new DOMDocument();
146
-      $twist->loadHTML($twist_t);
147
-      $twist = new DOMXPath($twist);
148
-      if ($twist->query('//img[@class="pic"]')->item(0)) {
149
-        $screens[] =  $twist->query('//img[@class="pic"]')->item(0)->getAttribute('src');
150
-      }
151
-    }
152
-    $desc = '';
153
-    $genres = [];
154
-    foreach ($jlib_en->query('//*[starts-with(@id, "genre")]/a') as $genre) {
155
-      $genres[] =  str_replace(' ', '.', strtolower($genre->nodeValue));
156
-    }
157
-  } else {
158
-    $degraded = true;
159
-  }
160
-  if ($jdb_page) {
161
-    if (!$title) {
162
-      $title = trim(substr($jdb->query("//h1[contains(@class, 'entry-title')]")[0]->nodeValue, strlen($cn) + 3));
163
-    }
164
-    if (!$studio) {
165
-      $studio = $jdb->query("//b[contains(., 'Studio:')]")[0]->nextSibling->nodeValue;
166
-    }
167
-    if (!$label) {
168
-      $label = $jdb->query("//b[contains(., 'Label:')]")[0]->nextSibling->nodeValue;
169
-    }
170
-    if (!$idols) {
171
-      $idols_raw = $jdb->query("//b[contains(., 'Idol(s): ')]")[0]->nextSibling;
172
-
173
-      for ($i = 0; $i < 10; $i++) {
174
-        if ($idols_raw->tagName == "a") {
175
-          $idol_name = $idols_raw->nodeValue;
176
-          $idol_lower = strtolower(str_replace(' ', '-', $idol_name));
177
-          // ensure it's actually an idol name
178
-          if (strpos($idols_raw->attributes->item(0)->nodeValue, '.com/idols/' . $idol_lower) !== false) {
179
-            $idols[] = $idols_raw->nodeValue;
180
-          }
181
-        }
182
-        $idols_raw = $idols_raw->nextSibling;
183
-      }
184
-    }
185
-    if (!$year) {
186
-      $year = substr($jdb->query("//b[contains(., 'Release Date:')]")[0]->nextSibling->nodeValue, 1, 4);
187
-    }
188
-    if (!$image) {
189
-      $image = $jdb->query("//img[contains(@alt, ' download or stream.')]")->item(0)->getAttribute('src');
190
-    }
191
-    if (substr($image, 0, 2) == '//') {
192
-      $image = 'https:'.$image;
193
-    }
194
-    if (!$desc) {
195
-      // Shit neither of the sites have descriptions
196
-      $desc = '';
197
-    }
198
-  }
199
-
200
-  if (!($title || $idols || $year || $studio || $label || $genres)) {
201
-    json_die('failure', 'Movie not found');
202
-  }
203
-
204
-  // Only show "genres" we have tags for
205
-  if (!$Cache->get_value('genre_tags')) {
206
-    $DB->query('
207
-      SELECT Name
208
-      FROM tags
209
-      WHERE TagType = \'genre\'
210
-      ORDER BY Name');
211
-    $Cache->cache_value('genre_tags', $DB->collect('Name'), 3600 * 6);
212
-  }
213
-  $genres = array_values(array_intersect(array_values($Cache->get_value('genre_tags')), str_replace('_','.',array_values(Tags::remove_aliases(array('include' => str_replace('.','_',$genres)))['include']))));
214
-
215
-  $json = array(
216
-    'cn'          => $cn,
217
-    'title'       => ($title ? $title : ''),
218
-    'title_jp'    => ($title_jp ? $title_jp : ''),
219
-    'idols'       => ($idols ? $idols : []),
220
-    'year'        => ($year ? $year : ''),
221
-    'studio'      => ($studio ? $studio : ''),
222
-    'label'       => ($label ? $label : ''),
223
-    'image'       => ($image ? $image : ''),
224
-    'description' => ($desc ? $desc : ''),
225
-    'tags'        => ($genres ? $genres : []),
226
-    'screens'     => ($screens ? $screens : []),
227
-    'degraded'    => $degraded
228
-  );
229
-
230
-  $Cache->cache_value('jav_fill_json_'.$cn, $json, 86400);
231
-
232
-  json_die('success', $json);
233
-*/
234
-}

+ 0
- 106
sections/ajax/autofill/manga.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (empty($_GET['url'])) {
5
-    json_die();
6
-}
7
-
8
-$url = str_replace('exhentai', 'e-hentai', $_GET['url']);
9
-
10
-$matches = [];
11
-preg_match('/^https?:\/\/g?\.?e.hentai\.org\/g\/(\d+)\/([\w\d]+)\/?$/', $url, $matches);
12
-
13
-$gid = $matches[1] ?? '';
14
-$token = $matches[2] ?? '';
15
-
16
-if (empty($gid) || empty($token)) {
17
-    json_die("failure", "Invalid URL");
18
-}
19
-
20
-if ($Cache->get_value('manga_fill_json_'.$gid)) {
21
-    json_die("success", $Cache->get_value('manga_fill_json_'.$gid));
22
-} else {
23
-    $data = json_encode(["method" => "gdata", "gidlist" => [[$gid, $token]], "namespace" => 1]);
24
-    $curl = curl_init('http://api.e-hentai.org/api.php');
25
-    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
26
-    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
27
-    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
28
-    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
29
-    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: '.strlen($data)]);
30
-
31
-    $json = curl_exec($curl);
32
-
33
-    if (empty($json)) {
34
-        json_die("failure", "Could not get page");
35
-    }
36
-
37
-    $json = json_decode($json, true)["gmetadata"][0];
38
-
39
-    $artists = [];
40
-    $tags = [];
41
-    $lang = null;
42
-    $circle = null;
43
-    $censored = true;
44
-    foreach ($json["tags"] as $tag) {
45
-        if (strpos($tag, ':') !== false) {
46
-            list($namespace, $tag) = explode(':', $tag);
47
-        } else {
48
-            $namespace = '';
49
-        }
50
-
51
-        if ($namespace == "artist") {
52
-            array_push($artists, ucwords($tag));
53
-        } elseif ($namespace == "group") {
54
-            $circle = empty($circle) ? ucfirst($tag) : $circle;
55
-        } elseif ($tag == "uncensored") {
56
-            $censored = false;
57
-        } else {
58
-            if ($namespace) {
59
-                $tag = $tag.':'.$namespace;
60
-            }
61
-            array_push($tags, str_replace(' ', '.', $tag));
62
-        }
63
-    }
64
-
65
-    // get the cover for ants
66
-    $cover = $json['thumb'];
67
-    // and let's see if we can replace it with something better
68
-    $gallery_page = file_get_contents($url);
69
-    $re = '/'.preg_quote('-0px 0 no-repeat"><a href="').'(.*)'.preg_quote('"><img alt="01"').'/';
70
-    preg_match($re, $gallery_page, $galmatch);
71
-    // were we able to find the first page of the gallery?
72
-    if ($galmatch[1]) {
73
-        $image_page = file_get_contents($galmatch[1]);
74
-        $re = '/'.preg_quote('"><img id="img" src="').'([^<]*)'.preg_quote('" style=').'/';
75
-        preg_match($re, $image_page, $imgmatch);
76
-        // were we able to find the image url?
77
-        if ($imgmatch[1]) {
78
-            $cover = $imgmatch[1];
79
-        }
80
-    }
81
-
82
-    $title = html_entity_decode($json['title'], ENT_QUOTES);
83
-    $title = preg_replace("/\(([^()]*+|(?R))*\)/", "", $title);
84
-    $title = trim(preg_replace("/\[([^\[\]]*+|(?R))*\]/", "", $title));
85
-    $title_jp = html_entity_decode($json['title_jpn'], ENT_QUOTES);
86
-    $title_jp = preg_replace("/\(([^()]*+|(?R))*\)/", "", $title_jp);
87
-    $title_jp = trim(preg_replace("/\[([^\[\]]*+|(?R))*\]/", "", $title_jp));
88
-
89
-    $json_str = [
90
-    'id'          => $gid,
91
-    'title'       => $title,
92
-    'title_jp'    => $title_jp,
93
-    'artists'     => $artists,
94
-    'circle'      => $circle,
95
-    'censored'    => $censored,
96
-    'year'        => null,
97
-    'tags'        => $tags,
98
-    'lang'        => $lang ?? 'Japanese',
99
-    'description' => '',
100
-    'cover'       => $cover
101
-  ];
102
-
103
-    $Cache->cache_value('manga_fill_json_'.$gid, $json_str, 86400);
104
-
105
-    json_die("success", $json_str);
106
-}

+ 0
- 38
sections/ajax/better/index.php View File

1
-<?
2
-//Include all the basic stuff...
3
-
4
-enforce_login();
5
-if (isset($_GET['method'])) {
6
-  switch ($_GET['method']) {
7
-    case 'transcode':
8
-      include(SERVER_ROOT.'/sections/ajax/better/transcode.php');
9
-      break;
10
-    case 'single':
11
-      include(SERVER_ROOT.'/sections/ajax/better/single.php');
12
-      break;
13
-    case 'snatch':
14
-      include(SERVER_ROOT.'/sections/ajax/better/snatch.php');
15
-      break;
16
-    case 'artistless':
17
-      include(SERVER_ROOT.'/sections/ajax/better/artistless.php');
18
-      break;
19
-    case 'tags':
20
-      include(SERVER_ROOT.'/sections/ajax/better/tags.php');
21
-      break;
22
-    case 'folders':
23
-      include(SERVER_ROOT.'/sections/ajax/better/folders.php');
24
-      break;
25
-    case 'files':
26
-      include(SERVER_ROOT.'/sections/ajax/better/files.php');
27
-      break;
28
-    case 'upload':
29
-      include(SERVER_ROOT.'/sections/ajax/better/upload.php');
30
-      break;
31
-    default:
32
-      echo json_encode(array('status' => 'failure'));
33
-      break;
34
-  }
35
-} else {
36
-  echo json_encode(array('status' => 'failure'));
37
-}
38
-?>

+ 0
- 55
sections/ajax/better/single.php View File

1
-<?
2
-if (($Results = $Cache->get_value('better_single_groupids')) === false) {
3
-  $DB->query("
4
-    SELECT
5
-      t.ID AS TorrentID,
6
-      t.GroupID AS GroupID
7
-    FROM xbt_files_users AS x
8
-      JOIN torrents AS t ON t.ID=x.fid
9
-    WHERE t.Format='FLAC'
10
-    GROUP BY x.fid
11
-    HAVING COUNT(x.uid) = 1
12
-    ORDER BY t.LogScore DESC, t.Time ASC
13
-    LIMIT 30");
14
-
15
-  $Results = $DB->to_pair('GroupID', 'TorrentID', false);
16
-  $Cache->cache_value('better_single_groupids', $Results, 30 * 60);
17
-}
18
-
19
-$Groups = Torrents::get_groups(array_keys($Results));
20
-
21
-$JsonResults = [];
22
-foreach ($Results as $GroupID => $FlacID) {
23
-  if (!isset($Groups[$GroupID])) {
24
-    continue;
25
-  }
26
-  $Group = $Groups[$GroupID];
27
-  extract(Torrents::array_group($Group));
28
-
29
-  $JsonArtists = [];
30
-  if (count($Artists) > 0) {
31
-    foreach ($Artists as $Artist) {
32
-      $JsonArtists[] = array(
33
-        'id' => (int)$Artist['id'],
34
-        'name' => $Artist['name'],
35
-        'aliasId' => (int)$Artist['aliasid']
36
-      );
37
-    }
38
-  }
39
-
40
-  $JsonResults[] = array(
41
-    'torrentId' => (int)$FlacID,
42
-    'groupId' => (int)$GroupID,
43
-    'artist' => $JsonArtists,
44
-    'groupName' => $GroupName,
45
-    'groupYear' => (int)$GroupYear,
46
-    'downloadUrl' => "torrents.php?action=download&id=$FlacID&authkey=".$LoggedUser['AuthKey'].'&torrent_pass='.$LoggedUser['torrent_pass']
47
-  );
48
-}
49
-
50
-echo json_encode(
51
-  array(
52
-    'status' => 'success',
53
-    'response' => $JsonResults
54
-  )
55
-);

+ 0
- 131
sections/ajax/better/transcode.php View File

1
-<?
2
-if (!isset($_GET['type']) || !is_number($_GET['type']) || $_GET['type'] > 3) {
3
-  error(0);
4
-}
5
-
6
-$Options = array('v0', 'v2', '320');
7
-$Encodings = array('V0 (VBR)', 'V2 (VBR)', '320');
8
-$EncodingKeys = array_fill_keys($Encodings, true);
9
-
10
-if ($_GET['type'] === '3') {
11
-  $List = "!(v0 | v2 | 320)";
12
-} else {
13
-  $List = '!'.$Options[$_GET['type']];
14
-  if ($_GET['type'] !== '0') {
15
-    $_GET['type'] = display_str($_GET['type']);
16
-  }
17
-}
18
-$SphQL = new SphinxqlQuery();
19
-$SphQL->select('id, groupid')
20
-  ->from('better_transcode')
21
-  ->where('logscore', 100)
22
-  ->where_match('FLAC', 'format')
23
-  ->where_match($List, 'encoding', false)
24
-  ->order_by('RAND()')
25
-  ->limit(0, TORRENTS_PER_PAGE, TORRENTS_PER_PAGE);
26
-if (!empty($_GET['search'])) {
27
-  $SphQL->where_match($_GET['search'], '(groupname,artistname,year,taglist)');
28
-}
29
-
30
-$SphQLResult = $SphQL->query();
31
-$TorrentCount = $SphQLResult->get_meta('total');
32
-
33
-if ($TorrentCount == 0) {
34
-  error('No results found!');
35
-}
36
-
37
-$Results = $SphQLResult->to_array('groupid');
38
-$Groups = Torrents::get_groups(array_keys($Results));
39
-
40
-$TorrentGroups = [];
41
-foreach ($Groups as $GroupID => $Group) {
42
-  if (empty($Group['Torrents'])) {
43
-    unset($Groups[$GroupID]);
44
-    continue;
45
-  }
46
-  foreach ($Group['Torrents'] as $Torrent) {
47
-    $TorRemIdent = "$Torrent[Media] $Torrent[RemasterYear] $Torrent[RemasterTitle] $Torrent[RemasterRecordLabel] $Torrent[RemasterCatalogueNumber]";
48
-    if (!isset($TorrentGroups[$Group['ID']])) {
49
-      $TorrentGroups[$Group['ID']] = array(
50
-        $TorRemIdent => array(
51
-          'FlacID' => 0,
52
-          'Formats' => [],
53
-          'RemasterTitle' => $Torrent['RemasterTitle'],
54
-          'RemasterYear' => $Torrent['RemasterYear'],
55
-          'RemasterRecordLabel' => $Torrent['RemasterRecordLabel'],
56
-          'RemasterCatalogueNumber' => $Torrent['RemasterCatalogueNumber'],
57
-          'IsSnatched' => false
58
-        )
59
-      );
60
-    } elseif (!isset($TorrentGroups[$Group['ID']][$TorRemIdent])) {
61
-      $TorrentGroups[$Group['ID']][$TorRemIdent] = array(
62
-        'FlacID' => 0,
63
-        'Formats' => [],
64
-        'RemasterTitle' => $Torrent['RemasterTitle'],
65
-        'RemasterYear' => $Torrent['RemasterYear'],
66
-        'RemasterRecordLabel' => $Torrent['RemasterRecordLabel'],
67
-        'RemasterCatalogueNumber' => $Torrent['RemasterCatalogueNumber'],
68
-        'IsSnatched' => false
69
-      );
70
-    }
71
-    if (isset($EncodingKeys[$Torrent['Encoding']])) {
72
-      $TorrentGroups[$Group['ID']][$TorRemIdent]['Formats'][$Torrent['Encoding']] = true;
73
-    } elseif ($TorrentGroups[$Group['ID']][$TorRemIdent]['FlacID'] == 0 && $Torrent['Format'] == 'FLAC' && $Torrent['LogScore'] == 100) {
74
-      $TorrentGroups[$Group['ID']][$TorRemIdent]['FlacID'] = $Torrent['ID'];
75
-      $TorrentGroups[$Group['ID']][$TorRemIdent]['IsSnatched'] = $Torrent['IsSnatched'];
76
-    }
77
-  }
78
-}
79
-
80
-$JsonResults = [];
81
-foreach ($TorrentGroups as $GroupID => $Editions) {
82
-  $GroupInfo = $Groups[$GroupID];
83
-  $GroupYear = $GroupInfo['Year'];
84
-  $ExtendedArtists = $GroupInfo['ExtendedArtists'];
85
-  $GroupCatalogueNumber = $GroupInfo['CatalogueNumber'];
86
-  $GroupName = $GroupInfo['Name'];
87
-  $GroupRecordLabel = $GroupInfo['RecordLabel'];
88
-  $ReleaseType = $GroupInfo['ReleaseType'];
89
-
90
-  if (!empty($ExtendedArtists[1]) || !empty($ExtendedArtists[4]) || !empty($ExtendedArtists[5]) || !empty($ExtendedArtists[6])) {
91
-    unset($ExtendedArtists[2]);
92
-    unset($ExtendedArtists[3]);
93
-    $ArtistNames = Artists::display_artists($ExtendedArtists, false, false, false);
94
-  } else {
95
-    $ArtistNames = '';
96
-  }
97
-
98
-  $TagList = [];
99
-  $TagList = explode(' ', str_replace('_', '.', $GroupInfo['TagList']));
100
-  $TorrentTags = [];
101
-  foreach ($TagList as $Tag) {
102
-    $TorrentTags[] = "<a href=\"torrents.php?taglist=$Tag\">$Tag</a>";
103
-  }
104
-  $TorrentTags = implode(', ', $TorrentTags);
105
-  foreach ($Editions as $RemIdent => $Edition) {
106
-    if (!$Edition['FlacID']
107
-        || !empty($Edition['Formats']) && $_GET['type'] === '3'
108
-        || $Edition['Formats'][$Encodings[$_GET['type']]] == true) {
109
-      continue;
110
-    }
111
-
112
-    $JsonResults[] = array(
113
-      'torrentId' => (int)$Edition['FlacID'],
114
-      'groupId' => (int)$GroupID,
115
-      'artist' => $ArtistNames,
116
-      'groupName' => $GroupName,
117
-      'groupYear' => (int)$GroupYear,
118
-      'missingV2' => !isset($Edition['Formats']['V2 (VBR)']),
119
-      'missingV0' => !isset($Edition['Formats']['V0 (VBR)']),
120
-      'missing320' => !isset($Encodings['Formats']['320']),
121
-      'downloadUrl' => 'torrents.php?action=download&id='.$Edition['FlacID'].'&authkey='.$LoggedUser['AuthKey'].'&torrent_pass='.$LoggedUser['torrent_pass']
122
-    );
123
-  }
124
-}
125
-
126
-echo json_encode(
127
-  array(
128
-    'status' => 'success',
129
-    'response' => $JsonResults
130
-  )
131
-);

+ 0
- 63
sections/ajax/bookmarks/artists.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (!empty($_GET['userid'])) {
5
-    if (!check_perms('users_override_paranoia')) {
6
-        json_die('failure');
7
-    }
8
-   
9
-    $UserID = $_GET['userid'];
10
-    $Sneaky = ($UserID !== $LoggedUser['ID']);
11
-
12
-    if (!is_number($UserID)) {
13
-        json_die('failure');
14
-    }
15
-
16
-    $DB->query("
17
-    SELECT
18
-      `Username`
19
-    FROM
20
-      `users_main`
21
-    WHERE
22
-      `ID` = '$UserID'
23
-    ");
24
-    list($Username) = $DB->next_record();
25
-} else {
26
-    $UserID = $LoggedUser['ID'];
27
-}
28
-
29
-//$ArtistList = Bookmarks::all_bookmarks('artist', $UserID);
30
-
31
-$DB->query("
32
-SELECT
33
-  ag.`ArtistID`,
34
-  ag.`Name`
35
-FROM
36
-  `bookmarks_artists` AS ba
37
-INNER JOIN `artists_group` AS ag
38
-ON
39
-  ba.`ArtistID` = ag.`ArtistID`
40
-WHERE
41
-  ba.`UserID` = $UserID
42
-");
43
-
44
-$ArtistList = $DB->to_array();
45
-$JsonArtists = [];
46
-
47
-foreach ($ArtistList as $Artist) {
48
-    list($ArtistID, $Name) = $Artist;
49
-    $JsonArtists[] = array(
50
-      'artistId'   => (int) $ArtistID,
51
-      'artistName' => $Name
52
-  );
53
-}
54
-
55
-print
56
-  json_encode(
57
-      array(
58
-      'status' => 'success',
59
-      'response' => array(
60
-        'artists' => $JsonArtists
61
-      )
62
-    )
63
-  );

+ 0
- 47
sections/ajax/bookmarks/index.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-// Number of users per page
5
-define('BOOKMARKS_PER_PAGE', '20');
6
-
7
-if (empty($_REQUEST['type'])) {
8
-    $_REQUEST['type'] = 'torrents';
9
-}
10
-
11
-switch ($_REQUEST['type']) {
12
-  case 'torrents':
13
-    require SERVER_ROOT.'/sections/ajax/bookmarks/torrents.php';
14
-    break;
15
-
16
-  case 'artists':
17
-    require SERVER_ROOT.'/sections/ajax/bookmarks/artists.php';
18
-    break;
19
-
20
-  /*
21
-  case 'collages':
22
-    $_GET['bookmarks'] = 1;
23
-    require SERVER_ROOT.'/sections/ajax/collages/browse.php';
24
-    break;
25
-  */
26
-
27
-  /*
28
-  case 'requests':
29
-    $_GET['type'] = 'bookmarks';
30
-    require SERVER_ROOT.'/sections/ajax/requests/requests.php';
31
-    break;
32
-  */
33
-
34
-  default:
35
-    json_die('failure');
36
-    break;
37
-
38
-    /*
39
-    print
40
-      json_encode(
41
-          array(
42
-          'status' => 'failure'
43
-        )
44
-      );
45
-    error();
46
-    */
47
-}

+ 0
- 124
sections/ajax/bookmarks/torrents.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-ini_set('memory_limit', -1);
5
-
6
-function compare($X, $Y)
7
-{
8
-    return($Y['count'] - $X['count']);
9
-}
10
-
11
-if (!empty($_GET['userid'])) {
12
-    if (!check_perms('users_override_paranoia')) {
13
-        error(403);
14
-    }
15
-
16
-    $UserID = $_GET['userid'];
17
-    if (!is_number($UserID)) {
18
-        error(404);
19
-    }
20
-
21
-    $DB->query("
22
-    SELECT
23
-      `Username`
24
-    FROM
25
-      `users_main`
26
-    WHERE
27
-      `ID` = '$UserID'
28
-    ");
29
-    list($Username) = $DB->next_record();
30
-} else {
31
-    $UserID = $LoggedUser['ID'];
32
-}
33
-
34
-$Sneaky = ($UserID !== $LoggedUser['ID']);
35
-$JsonBookmarks = [];
36
-
37
-list($GroupIDs, $CollageDataList, $GroupList) = Users::get_bookmarks($UserID);
38
-foreach ($GroupIDs as $GroupID) {
39
-    if (!isset($GroupList[$GroupID])) {
40
-        continue;
41
-    }
42
-
43
-    $Group = $GroupList[$GroupID];
44
-    $JsonTorrents = [];
45
-
46
-    foreach ($Group['Torrents'] as $Torrent) {
47
-        $JsonTorrents[] = array(
48
-          'id'          => (int) $Torrent['ID'],
49
-          'groupId'     => (int) $Torrent['GroupID'],
50
-          'platform'    => $Torrent['Media'],
51
-          'fileCount'   => (int) $Torrent['FileCount'],
52
-          'freeTorrent' => $Torrent['FreeTorrent'] === 1,
53
-          'size'        => (float) $Torrent['Size'],
54
-          'leechers'    => (int) $Torrent['Leechers'],
55
-          'seeders'     => (int) $Torrent['Seeders'],
56
-          'snatched'    => (int) $Torrent['Snatched'],
57
-          'time'        => $Torrent['Time'],
58
-          'hasFile'     => (int) $Torrent['HasFile']
59
-        );
60
-
61
-        /*
62
-        $JsonTorrents[] = array(
63
-          'id'                      => (int) $Torrent['ID'],
64
-          'groupId'                 => (int) $Torrent['GroupID'],
65
-          'media'                   => $Torrent['Media'],
66
-          'format'                  => $Torrent['Format'],
67
-          'encoding'                => $Torrent['Encoding'],
68
-          'remasterYear'            => (int) $Torrent['RemasterYear'],
69
-          'remastered'              => $Torrent['Remastered'] == 1,
70
-          'remasterTitle'           => $Torrent['RemasterTitle'],
71
-          'remasterRecordLabel'     => $Torrent['RemasterRecordLabel'],
72
-          'remasterCatalogueNumber' => $Torrent['RemasterCatalogueNumber'],
73
-          'scene'                   => $Torrent['Scene'] === 1,
74
-          'hasLog'                  => $Torrent['HasLog'] === 1,
75
-          'hasCue'                  => $Torrent['HasCue'] === 1,
76
-          'logScore'                => (float) $Torrent['LogScore'],
77
-          'fileCount'               => (int) $Torrent['FileCount'],
78
-          'freeTorrent'             => $Torrent['FreeTorrent'] === 1,
79
-          'size'                    => (float) $Torrent['Size'],
80
-          'leechers'                => (int) $Torrent['Leechers'],
81
-          'seeders'                 => (int) $Torrent['Seeders'],
82
-          'snatched'                => (int) $Torrent['Snatched'],
83
-          'time'                    => $Torrent['Time'],
84
-          'hasFile'                 => (int) $Torrent['HasFile']
85
-        );
86
-        */
87
-    }
88
-
89
-    $JsonBookmarks[] = array(
90
-    'id'          => (int) $Group['ID'],
91
-    'name'        => $Group['Name'],
92
-    'year'        => (int) $Group['Year'],
93
-    'accession'   => $Group['CatalogueNumber'],
94
-    'tagList'     => $Group['TagList'],
95
-    'vanityHouse' => $Group['VanityHouse'] === 1,
96
-    'picture'     => $Group['WikiImage'],
97
-    'torrents'    => $JsonTorrents
98
-  );
99
-
100
-    /*
101
-    $JsonBookmarks[] = array(
102
-      'id'              => (int) $Group['ID'],
103
-      'name'            => $Group['Name'],
104
-      'year'            => (int) $Group['Year'],
105
-      'recordLabel'     => $Group['RecordLabel'],
106
-      'catalogueNumber' => $Group['CatalogueNumber'],
107
-      'tagList'         => $Group['TagList'],
108
-      'releaseType'     => $Group['ReleaseType'],
109
-      'vanityHouse'     => $Group['VanityHouse'] === 1,
110
-      'image'           => $Group['WikiImage'],
111
-      'torrents'        => $JsonTorrents
112
-    );
113
-    */
114
-}
115
-
116
-print
117
-  json_encode(
118
-      array(
119
-      'status' => 'success',
120
-      'response' => array(
121
-        'bookmarks' => $JsonBookmarks
122
-      )
123
-    )
124
-  );

+ 0
- 132
sections/ajax/browse.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-include SERVER_ROOT.'/sections/torrents/functions.php';
5
-
6
-if (!empty($_GET['order_way']) && $_GET['order_way'] === 'asc') {
7
-    $OrderWay = 'asc';
8
-} else {
9
-    $OrderWay = 'desc';
10
-}
11
-
12
-if (empty($_GET['order_by']) || !isset(TorrentSearch::$SortOrders[$_GET['order_by']])) {
13
-    $OrderBy = 'time';
14
-} else {
15
-    $OrderBy = $_GET['order_by'];
16
-}
17
-
18
-$GroupResults = !isset($_GET['group_results']) || (int) $_GET['group_results'] !== 0;
19
-$Page = !empty($_GET['page']) ? (int) $_GET['page'] : 1;
20
-
21
-$Search = new TorrentSearch($GroupResults, $OrderBy, $OrderWay, $Page, TORRENTS_PER_PAGE);
22
-$Results = $Search->query($_GET);
23
-
24
-$Groups = $Search->get_groups();
25
-$NumResults = $Search->record_count();
26
-
27
-if ($Results === false) {
28
-    json_die('error', 'Search returned an error. Make sure all parameters are valid and of the expected types.');
29
-}
30
-
31
-if ($NumResults === 0) {
32
-    json_die('success', [
33
-    'results' => []
34
-  ]);
35
-}
36
-
37
-$Bookmarks = Bookmarks::all_bookmarks('torrent');
38
-
39
-$JsonGroups = [];
40
-foreach ($Results as $Key => $GroupID) {
41
-    $GroupInfo = $Groups[$GroupID];
42
-    if (empty($GroupInfo['Torrents'])) {
43
-        continue;
44
-    }
45
-
46
-    $CategoryID = $GroupInfo['CategoryID'];
47
-    $Artists = $GroupInfo['Artists'];
48
-    $GroupCatalogueNumber = $GroupInfo['CatalogueNumber'];
49
-    $GroupName = $GroupInfo['Name'];
50
-
51
-    if ($GroupResults) {
52
-        $Torrents = $GroupInfo['Torrents'];
53
-        $GroupTime = $MaxSize = $TotalLeechers = $TotalSeeders = $TotalSnatched = 0;
54
-
55
-        foreach ($Torrents as $T) {
56
-            $GroupTime = max($GroupTime, strtotime($T['Time']));
57
-            $MaxSize = max($MaxSize, $T['Size']);
58
-            $TotalLeechers += $T['Leechers'];
59
-            $TotalSeeders += $T['Seeders'];
60
-            $TotalSnatched += $T['Snatched'];
61
-        }
62
-    } else {
63
-        $TorrentID = $Key;
64
-        $Torrents = [$TorrentID => $GroupInfo['Torrents'][$TorrentID]];
65
-    }
66
-
67
-    $TagList = explode(' ', str_replace('_', '.', $GroupInfo['TagList']));
68
-    $JsonArtists = [];
69
-    $DisplayName = '';
70
-
71
-    if (!empty($Artists)) {
72
-        $DisplayName = Artists::display_artists($Artists, false, false, false);
73
-        foreach ($Artists as $Artist) {
74
-            $JsonArtists[] = [
75
-              'id' => (int) $Artist['id'],
76
-              'name' => $Artist['name']
77
-            ];
78
-        }
79
-    }
80
-
81
-    $JsonTorrents = [];
82
-    foreach ($Torrents as $TorrentID => $Data) {
83
-        // All of the individual torrents in the group
84
-
85
-        $JsonTorrents[] = [
86
-          'torrentId'           => (int) $TorrentID,
87
-          'authors'             => $JsonArtists,
88
-          'platform'            => $Data['Media'],
89
-          'format'              => $Data['Container'],
90
-          'license'             => $Data['Codec'],
91
-          'scope'               => $Data['Resolution'],
92
-          'annotated'           => $Data['Censored'],
93
-          'archive'             => $Data['Archive'],
94
-          'fileCount'           => (int) $Data['FileCount'],
95
-          'time'                => $Data['Time'],
96
-          'size'                => (int) $Data['Size'],
97
-          'snatches'            => (int) $Data['Snatched'],
98
-          'seeders'             => (int) $Data['Seeders'],
99
-          'leechers'            => (int) $Data['Leechers'],
100
-          'isFreeleech'         => (int) $Data['FreeTorrent'] === 1,
101
-          'isNeutralLeech'      => (int) $Data['FreeTorrent'] === 2,
102
-          'isPersonalFreeleech' => $Data['PersonalFL'],
103
-          'canUseToken'         => Torrents::can_use_token($Data),
104
-          'hasSnatched'         => $Data['IsSnatched']
105
-        ];
106
-    }
107
-
108
-    $JsonGroups[] = [
109
-      'groupId'       => (int) $GroupID,
110
-      'groupName'     => $GroupName,
111
-      'author'        => $DisplayName,
112
-      'picture'       => $GroupInfo['WikiImage'],
113
-      'tags'          => $TagList,
114
-      'bookmarked'    => (in_array($GroupID, $Bookmarks)),
115
-      'groupYear'     => (int) $GroupInfo['Year'],
116
-      'groupTime'     => (int) $GroupTime,
117
-      'accession'     => $GroupInfo['CatalogueNumber'],
118
-      'lab'           => $GroupInfo['Studio'],
119
-      'location'      => $GroupInfo['Series'],
120
-      'maxSize'       => (int) $MaxSize,
121
-      'totalSnatched' => (int) $TotalSnatched,
122
-      'totalSeeders'  => (int) $TotalSeeders,
123
-      'totalLeechers' => (int) $TotalLeechers,
124
-      'torrents'      => $JsonTorrents
125
-    ];
126
-}
127
-
128
-json_print('success', [
129
-  'currentPage' => intval($Page),
130
-  'pages' => ceil($NumResults / TORRENTS_PER_PAGE),
131
-  'results' => $JsonGroups
132
-]);

+ 0
- 49
sections/ajax/clear_user_notification.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$Type = $_POST['type'];
5
-
6
-switch ($Type) {
7
-  case NotificationsManager::INBOX:
8
-    NotificationsManager::clear_inbox();
9
-    break;
10
-
11
-  case NotificationsManager::NEWS:
12
-    NotificationsManager::clear_news(false);
13
-    break;
14
-
15
-  case NotificationsManager::BLOG:
16
-    NotificationsManager::clear_blog(false);
17
-    break;
18
-
19
-  case NotificationsManager::STAFFPM:
20
-    NotificationsManager::clear_staff_pms();
21
-    break;
22
-
23
-  case NotificationsManager::TORRENTS:
24
-    NotificationsManager::clear_torrents();
25
-    break;
26
-
27
-  case NotificationsManager::QUOTES:
28
-    NotificationsManager::clear_quotes();
29
-    break;
30
-
31
-  case NotificationsManager::SUBSCRIPTIONS:
32
-    NotificationsManager::clear_subscriptions();
33
-    break;
34
-
35
-  case NotificationsManager::COLLAGES:
36
-    NotificationsManager::clear_collages();
37
-    break;
38
-
39
-  case NotificationsManager::GLOBALNOTICE:
40
-    NotificationsManager::clear_global_notification();
41
-    break;
42
-    
43
-  default:
44
-    break;
45
-}
46
-
47
-if (strpos($Type, "oneread_") === 0) {
48
-    NotificationsManager::clear_one_read($Type);
49
-}

+ 0
- 174
sections/ajax/collage.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-define('ARTIST_COLLAGE', 'Artists');
5
-
6
-if (empty($_GET['id']) || !is_number($_GET['id'])) {
7
-    json_die('failure', 'bad parameters');
8
-}
9
-
10
-$CollageID = $_GET['id'];
11
-$CacheKey = "collage_$CollageID";
12
-$CollageData = $Cache->get_value($CacheKey);
13
-
14
-if ($CollageData) {
15
-    list($Name, $Description, $CommentList, $Deleted, $CollageCategoryID, $CreatorID, $Locked, $MaxGroups, $MaxGroupsPerUser, $Updated, $Subscribers) = $CollageData;
16
-} else {
17
-    $DB->query("
18
-    SELECT
19
-      `Name`,
20
-      `Description`,
21
-      `UserID`,
22
-      `Deleted`,
23
-      `CategoryID`,
24
-      `Locked`,
25
-      `MaxGroups`,
26
-      `MaxGroupsPerUser`,
27
-      `Updated`,
28
-      `Subscribers`
29
-    FROM
30
-      `collages`
31
-    WHERE
32
-      `ID` = '$CollageID'
33
-    ");
34
-
35
-    if (!$DB->has_results()) {
36
-        json_die("failure");
37
-    }
38
-
39
-    list($Name, $Description, $CreatorID, $Deleted, $CollageCategoryID, $Locked, $MaxGroups, $MaxGroupsPerUser, $Updated, $Subscribers) = $DB->next_record(MYSQLI_NUM);
40
-    $CommentList = null;
41
-    $SetCache = true;
42
-}
43
-
44
-// todo: Cache this
45
-$DB->query("
46
-SELECT
47
-  `GroupID`
48
-FROM
49
-  `collages_torrents`
50
-WHERE
51
-  `CollageID` = $CollageID
52
-");
53
-$TorrentGroups = $DB->collect('GroupID');
54
-
55
-$JSON = array(
56
-  'id'                  => (int) $CollageID,
57
-  'name'                => $Name,
58
-  'description'         => Text::full_format($Description),
59
-  'creatorID'           => (int) $CreatorID,
60
-  'deleted'             => (bool) $Deleted,
61
-  'collageCategoryID'   => (int) $CollageCategoryID,
62
-  'collageCategoryName' => $CollageCats[(int) $CollageCategoryID],
63
-  'locked'              => (bool) $Locked,
64
-  'maxGroups'           => (int) $MaxGroups,
65
-  'maxGroupsPerUser'    => (int) $MaxGroupsPerUser,
66
-  'hasBookmarked'       => Bookmarks::has_bookmarked('collage', $CollageID),
67
-  'subscriberCount'     => (int) $Subscribers,
68
-  'torrentGroupIDList'  => $TorrentGroups
69
-);
70
-
71
-if ($CollageCategoryID !== array_search(ARTIST_COLLAGE, $CollageCats)) {
72
-    // Torrent collage
73
-    $TorrentGroups = [];
74
-    $DB->query("
75
-    SELECT
76
-      ct.`GroupID`
77
-    FROM
78
-      `collages_torrents` AS ct
79
-    JOIN `torrents_group` AS tg
80
-    ON
81
-      tg.`ID` = ct.`GroupID`
82
-    WHERE
83
-      ct.`CollageID` = '$CollageID'
84
-    ORDER BY
85
-      ct.`Sort`
86
-    ");
87
-
88
-    $GroupIDs = $DB->collect('GroupID');
89
-    $GroupList = Torrents::get_groups($GroupIDs);
90
-
91
-    foreach ($GroupIDs as $GroupID) {
92
-        if (!empty($GroupList[$GroupID])) {
93
-            $GroupDetails = Torrents::array_group($GroupList[$GroupID]);
94
-            $TorrentList = [];
95
-
96
-            foreach ($GroupDetails['Torrents'] as $Torrent) {
97
-                $TorrentList[] = array(
98
-                  'torrentid'   => (int)$Torrent['ID'],
99
-                  'platform'    => $Torrent['Media'],
100
-                  'fileCount'   => (int)$Torrent['FileCount'],
101
-                  'size'        => (int)$Torrent['Size'],
102
-                  'seeders'     => (int)$Torrent['Seeders'],
103
-                  'leechers'    => (int)$Torrent['Leechers'],
104
-                  'snatched'    => (int)$Torrent['Snatched'],
105
-                  'freeTorrent' => ($Torrent['FreeTorrent'] === 1),
106
-                  'reported'    => (count(Torrents::get_reports((int)$Torrent['ID'])) > 0),
107
-                  'time'        => $Torrent['Time']
108
-                );
109
-            }
110
-
111
-            $TorrentGroups[] = array(
112
-              'id'          => $GroupDetails['GroupID'],
113
-              'name'        => $GroupDetails['GroupName'],
114
-              'year'        => $GroupDetails['GroupYear'],
115
-              'categoryId'  => $GroupDetails['GroupCategoryID'],
116
-              'accession'   => $GroupDetails['GroupCatalogueNumber'],
117
-              'vanityHouse' => $GroupDetails['GroupVanityHouse'],
118
-              'tagList'     => $GroupDetails['TagList'],
119
-              'picture'     => $GroupDetails['WikiImage'],
120
-              'torrents'    => $TorrentList
121
-            );
122
-        }
123
-    }
124
-    $JSON['torrentgroups'] = $TorrentGroups;
125
-} else {
126
-    // Artist collage
127
-    $DB->query("
128
-    SELECT
129
-      ca.`ArtistID`,
130
-      ag.`Name`,
131
-      aw.`Image`
132
-    FROM
133
-      `collages_artists` AS ca
134
-    JOIN `artists_group` AS ag
135
-    ON
136
-      ag.`ArtistID` = ca.`ArtistID`
137
-    LEFT JOIN `wiki_artists` AS aw
138
-    ON
139
-      aw.`RevisionID` = ag.`RevisionID`
140
-    WHERE
141
-      ca.`CollageID` = '$CollageID'
142
-    ORDER BY
143
-      ca.`Sort`
144
-    ");
145
-
146
-    $Artists = [];
147
-    while (list($ArtistID, $ArtistName, $ArtistImage) = $DB->next_record()) {
148
-        $Artists[] = array(
149
-          'id'      => (int) $ArtistID,
150
-          'name'    => $ArtistName,
151
-          'picture' => $ArtistImage
152
-        );
153
-    }
154
-    $JSON['artists'] = $Artists;
155
-}
156
-
157
-if (isset($SetCache)) {
158
-    $CollageData = array(
159
-      $Name,
160
-      $Description,
161
-      $CommentList,
162
-      (bool) $Deleted,
163
-      (int) $CollageCategoryID,
164
-      (int) $CreatorID,
165
-      (bool) $Locked,
166
-      (int) $MaxGroups,
167
-      (int) $MaxGroupsPerUser,
168
-      $Updated,
169
-      (int) $Subscribers
170
-    );
171
-    $Cache->cache_value($CacheKey, $CollageData, 3600);
172
-}
173
-
174
-json_print('success', $JSON);

+ 0
- 70
sections/ajax/community_stats.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (!isset($_GET['userid']) || !is_number($_GET['userid'])) {
5
-    json_die('failure');
6
-}
7
-
8
-$UserID = $_GET['userid'];
9
-$CommStats = array(
10
-  'leeching' => false,
11
-  'seeding' => false,
12
-  'snatched' => false,
13
-  'usnatched' => false,
14
-  'downloaded' => false,
15
-  'udownloaded' => false,
16
-  'seedingperc' => false,
17
-);
18
-
19
-$User = Users::user_info($UserID);
20
-
21
-function check_paranoia_here($Setting)
22
-{
23
-    global $User;
24
-    return check_paranoia($Setting, $User['Paranoia'], $User['Class'], $User['ID']);
25
-}
26
-
27
-if (check_paranoia_here('seeding+') || check_paranoia_here('leeching+')) {
28
-    $DB->query("
29
-    SELECT IF(remaining = 0, 'Seeding', 'Leeching') AS Type, COUNT(x.uid)
30
-    FROM xbt_files_users AS x
31
-      INNER JOIN torrents AS t ON t.ID = x.fid
32
-    WHERE x.uid = '$UserID'
33
-      AND x.active = 1
34
-    GROUP BY Type");
35
-    $PeerCount = $DB->to_array(0, MYSQLI_NUM, false);
36
-    if (check_paranoia('seeding+')) {
37
-        $Seeding = isset($PeerCount['Seeding']) ? $PeerCount['Seeding'][1] : 0;
38
-        $CommStats['seeding'] = number_format($Seeding);
39
-    }
40
-    if (check_paranoia('leeching+')) {
41
-        $CommStats['leeching'] = isset($PeerCount['Leeching']) ? number_format($PeerCount['Leeching'][1]) : 0;
42
-    }
43
-}
44
-if (check_paranoia_here('snatched+')) {
45
-    $DB->query("
46
-    SELECT COUNT(x.uid), COUNT(DISTINCT x.fid)
47
-    FROM xbt_snatched AS x
48
-      INNER JOIN torrents AS t ON t.ID = x.fid
49
-    WHERE x.uid = '$UserID'");
50
-    list($Snatched, $UniqueSnatched) = $DB->next_record(MYSQLI_NUM, false);
51
-    $CommStats['snatched'] = number_format($Snatched);
52
-    if (check_perms('site_view_torrent_snatchlist', $User['Class'])) {
53
-        $CommStats['usnatched'] = number_format($UniqueSnatched);
54
-    }
55
-    if (check_paranoia_here('seeding+') && check_paranoia_here('snatched+') && $UniqueSnatched > 0) {
56
-        $CommStats['seedingperc'] = 100 * min(1, round($Seeding / $UniqueSnatched, 2));
57
-    }
58
-}
59
-if (check_perms('site_view_torrent_snatchlist', $Class)) {
60
-    $DB->query("
61
-    SELECT COUNT(ud.UserID), COUNT(DISTINCT ud.TorrentID)
62
-    FROM users_downloads AS ud
63
-      JOIN torrents AS t ON t.ID = ud.TorrentID
64
-    WHERE ud.UserID = '$UserID'");
65
-    list($NumDownloads, $UniqueDownloads) = $DB->next_record(MYSQLI_NUM, false);
66
-    $CommStats['downloaded'] = number_format($NumDownloads);
67
-    $CommStats['udownloaded'] = number_format($UniqueDownloads);
68
-}
69
-
70
-json_die('success', $CommStats);

+ 0
- 180
sections/ajax/forum/forum.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-
6
-/**********|| Page to show individual forums || ********************************\
7
-
8
-Things to expect in $_GET:
9
-  ForumID: ID of the forum curently being browsed
10
-  page: The page the user's on.
11
-  page = 1 is the same as no page
12
-
13
-********************************************************************************/
14
-
15
-//---------- Things to sort out before it can start printing/generating content
16
-
17
-// Check for lame SQL injection attempts
18
-$ForumID = $_GET['forumid'];
19
-if (!is_number($ForumID)) {
20
-    echo json_encode(array('status' => 'failure'));
21
-    error();
22
-}
23
-
24
-if (isset($_GET['pp'])) {
25
-    $PerPage = intval($_GET['pp']);
26
-} elseif (isset($LoggedUser['PostsPerPage'])) {
27
-    $PerPage = $LoggedUser['PostsPerPage'];
28
-} else {
29
-    $PerPage = POSTS_PER_PAGE;
30
-}
31
-
32
-list($Page, $Limit) = Format::page_limit(TOPICS_PER_PAGE);
33
-
34
-//---------- Get some data to start processing
35
-
36
-// Caching anything beyond the first page of any given forum is just wasting ram
37
-// users are more likely to search then to browse to page 2
38
-if ($Page === 1) {
39
-    list($Forum, , , $Stickies) = $Cache->get_value("forums_$ForumID");
40
-}
41
-if (!isset($Forum) || !is_array($Forum)) {
42
-    $DB->query("
43
-    SELECT
44
-      ID,
45
-      Title,
46
-      AuthorID,
47
-      IsLocked,
48
-      IsSticky,
49
-      NumPosts,
50
-      LastPostID,
51
-      LastPostTime,
52
-      LastPostAuthorID
53
-    FROM forums_topics
54
-    WHERE ForumID = '$ForumID'
55
-    ORDER BY IsSticky DESC, LastPostTime DESC
56
-    LIMIT $Limit"); // Can be cached until someone makes a new post
57
-    $Forum = $DB->to_array('ID', MYSQLI_ASSOC, false);
58
-    if ($Page === 1) {
59
-        $DB->query("
60
-      SELECT COUNT(ID)
61
-      FROM forums_topics
62
-      WHERE ForumID = '$ForumID'
63
-        AND IsSticky = '1'");
64
-        list($Stickies) = $DB->next_record();
65
-        $Cache->cache_value("forums_$ForumID", array($Forum, '', 0, $Stickies), 0);
66
-    }
67
-}
68
-
69
-if (!isset($Forums[$ForumID])) {
70
-    json_die("failure");
71
-}
72
-// Make sure they're allowed to look at the page
73
-if (!check_perms('site_moderate_forums')) {
74
-    if (isset($LoggedUser['CustomForums'][$ForumID]) && $LoggedUser['CustomForums'][$ForumID] === 0) {
75
-        json_die("failure", "insufficient permissions to view page");
76
-    }
77
-}
78
-if ($LoggedUser['CustomForums'][$ForumID] != 1 && $Forums[$ForumID]['MinClassRead'] > $LoggedUser['Class']) {
79
-    json_die("failure", "insufficient permissions to view page");
80
-}
81
-
82
-$ForumName = display_str($Forums[$ForumID]['Name']);
83
-$JsonSpecificRules = [];
84
-foreach ($Forums[$ForumID]['SpecificRules'] as $ThreadIDs) {
85
-    $Thread = Forums::get_thread_info($ThreadIDs);
86
-    $JsonSpecificRules[] = array(
87
-    'threadId' => (int)$ThreadIDs,
88
-    'thread' => display_str($Thread['Title'])
89
-  );
90
-}
91
-
92
-$Pages = Format::get_pages($Page, $Forums[$ForumID]['NumTopics'], TOPICS_PER_PAGE, 9);
93
-
94
-if (count($Forum) === 0) {
95
-    print
96
-    json_encode(
97
-        array(
98
-        'status' => 'success',
99
-        'forumName' => $ForumName,
100
-        'threads' => []
101
-      )
102
-    );
103
-} else {
104
-    // forums_last_read_topics is a record of the last post a user read in a topic, and what page that was on
105
-    $DB->query("
106
-    SELECT
107
-      l.TopicID,
108
-      l.PostID,
109
-      CEIL(
110
-        (
111
-          SELECT COUNT(p.ID)
112
-          FROM forums_posts AS p
113
-          WHERE p.TopicID = l.TopicID
114
-            AND p.ID <= l.PostID
115
-        ) / $PerPage
116
-      ) AS Page
117
-    FROM forums_last_read_topics AS l
118
-    WHERE l.TopicID IN(".implode(', ', array_keys($Forum)).')
119
-      AND l.UserID = \''.$LoggedUser['ID'].'\'');
120
-
121
-    // Turns the result set into a multi-dimensional array, with
122
-    // forums_last_read_topics.TopicID as the key.
123
-    // This is done here so we get the benefit of the caching, and we
124
-    // don't have to make a database query for each topic on the page
125
-    $LastRead = $DB->to_array('TopicID');
126
-
127
-    $JsonTopics = [];
128
-    foreach ($Forum as $Topic) {
129
-        list($TopicID, $Title, $AuthorID, $Locked, $Sticky, $PostCount, $LastID, $LastTime, $LastAuthorID) = array_values($Topic);
130
-
131
-        // Handle read/unread posts - the reason we can't cache the whole page
132
-        if ((!$Locked || $Sticky)
133
-        && ((empty($LastRead[$TopicID]) || $LastRead[$TopicID]['PostID'] < $LastID)
134
-          && strtotime($LastTime) > $LoggedUser['CatchupTime'])
135
-    ) {
136
-            $Read = 'unread';
137
-        } else {
138
-            $Read = 'read';
139
-        }
140
-        $UserInfo = Users::user_info($AuthorID);
141
-        $AuthorName = $UserInfo['Username'];
142
-        $UserInfo = Users::user_info($LastAuthorID);
143
-        $LastAuthorName = $UserInfo['Username'];
144
-        // Bug fix for no last time available
145
-        if (!$LastTime) {
146
-            $LastTime = '';
147
-        }
148
-
149
-        $JsonTopics[] = array(
150
-      'topicId' => (int)$TopicID,
151
-      'title' => display_str($Title),
152
-      'authorId' => (int)$AuthorID,
153
-      'authorName' => $AuthorName,
154
-      'locked' => $Locked === 1,
155
-      'sticky' => $Sticky === 1,
156
-      'postCount' => (int)$PostCount,
157
-      'lastID' => ($LastID === null) ? 0 : (int)$LastID,
158
-      'lastTime' => $LastTime,
159
-      'lastAuthorId' => ($LastAuthorID === null) ? 0 : (int)$LastAuthorID,
160
-      'lastAuthorName' => ($LastAuthorName === null) ? '' : $LastAuthorName,
161
-      'lastReadPage' => ($LastRead[$TopicID]['Page'] === null) ? 0 : (int)$LastRead[$TopicID]['Page'],
162
-      'lastReadPostId' => ($LastRead[$TopicID]['PostID'] === null) ? 0 : (int)$LastRead[$TopicID]['PostID'],
163
-      'read' => $Read === 'read'
164
-    );
165
-    }
166
-
167
-    print
168
-    json_encode(
169
-        array(
170
-        'status' => 'success',
171
-        'response' => array(
172
-          'forumName' => $ForumName,
173
-          'specificRules' => $JsonSpecificRules,
174
-          'currentPage' => (int)$Page,
175
-          'pages' => ceil($Forums[$ForumID]['NumTopics'] / TOPICS_PER_PAGE),
176
-          'threads' => $JsonTopics
177
-        )
178
-      )
179
-    );
180
-}

+ 0
- 34
sections/ajax/forum/index.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-// Already done in /sections/ajax/index.php
5
-//enforce_login();
6
-
7
-if (!empty($LoggedUser['DisableForums'])) {
8
-    echo json_encode(array('status' => 'failure'));
9
-    error();
10
-} else {
11
-    // Replace the old hard-coded forum categories
12
-    $ForumCats = Forums::get_forum_categories();
13
-
14
-    // This variable contains all our lovely forum data
15
-    $Forums = Forums::get_forums();
16
-
17
-    if (empty($_GET['type']) || $_GET['type'] === 'main') {
18
-        include SERVER_ROOT.'/sections/ajax/forum/main.php';
19
-    } else {
20
-        switch ($_GET['type']) {
21
-        case 'viewforum':
22
-          include SERVER_ROOT.'/sections/ajax/forum/forum.php';
23
-          break;
24
-
25
-        case 'viewthread':
26
-          include SERVER_ROOT.'/sections/ajax/forum/thread.php';
27
-          break;
28
-
29
-        default:
30
-          echo json_encode(array('status' => 'failure'));
31
-          break;
32
-        }
33
-    }
34
-}

+ 0
- 117
sections/ajax/forum/main.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-if (isset($LoggedUser['PostsPerPage'])) {
6
-    $PerPage = $LoggedUser['PostsPerPage'];
7
-} else {
8
-    $PerPage = POSTS_PER_PAGE;
9
-}
10
-
11
-// We have to iterate here because if one is empty it breaks the query
12
-$TopicIDs = [];
13
-foreach ($Forums as $Forum) {
14
-    if (!empty($Forum['LastPostTopicID'])) {
15
-        $TopicIDs[] = $Forum['LastPostTopicID'];
16
-    }
17
-}
18
-
19
-// Now if we have IDs' we run the query
20
-if (!empty($TopicIDs)) {
21
-    $DB->query("
22
-    SELECT
23
-      l.TopicID,
24
-      l.PostID,
25
-      CEIL(
26
-        (
27
-          SELECT COUNT(p.ID)
28
-          FROM forums_posts AS p
29
-          WHERE p.TopicID = l.TopicID
30
-            AND p.ID <= l.PostID
31
-        ) / $PerPage
32
-      ) AS Page
33
-    FROM forums_last_read_topics AS l
34
-    WHERE l.TopicID IN(".implode(',', $TopicIDs).")
35
-      AND l.UserID = '$LoggedUser[ID]'");
36
-    $LastRead = $DB->to_array('TopicID', MYSQLI_ASSOC);
37
-} else {
38
-    $LastRead = [];
39
-}
40
-
41
-$DB->query("
42
-  SELECT RestrictedForums
43
-  FROM users_info
44
-  WHERE UserID = ".$LoggedUser['ID']);
45
-list($RestrictedForums) = $DB->next_record();
46
-$RestrictedForums = explode(',', $RestrictedForums);
47
-$PermittedForums = array_keys($LoggedUser['PermittedForums']);
48
-
49
-$JsonCategories = [];
50
-$JsonCategory = [];
51
-$JsonForums = [];
52
-foreach ($Forums as $Forum) {
53
-    list($ForumID, $CategoryID, $ForumName, $ForumDescription, $MinRead, $MinWrite, $MinCreate, $NumTopics, $NumPosts, $LastPostID, $LastAuthorID, $LastTopicID, $LastTime, $SpecificRules, $LastTopic, $Locked, $Sticky) = array_values($Forum);
54
-    if ($LoggedUser['CustomForums'][$ForumID] != 1
55
-      && ($MinRead > $LoggedUser['Class']
56
-      || array_search($ForumID, $RestrictedForums) !== false)
57
-  ) {
58
-        continue;
59
-    }
60
-    $ForumDescription = display_str($ForumDescription);
61
-
62
-    if ($CategoryID != $LastCategoryID) {
63
-        if (!empty($JsonForums) && !empty($JsonCategory)) {
64
-            $JsonCategory['forums'] = $JsonForums;
65
-            $JsonCategories[] = $JsonCategory;
66
-        }
67
-        $LastCategoryID = $CategoryID;
68
-        $JsonCategory = array(
69
-      'categoryID' => (int)$CategoryID,
70
-      'categoryName' => $ForumCats[$CategoryID]
71
-    );
72
-        $JsonForums = [];
73
-    }
74
-
75
-    if ((!$Locked || $Sticky)
76
-      && $LastPostID != 0
77
-      && ((empty($LastRead[$LastTopicID]) || $LastRead[$LastTopicID]['PostID'] < $LastPostID)
78
-        && strtotime($LastTime) > $LoggedUser['CatchupTime'])
79
-  ) {
80
-        $Read = 'unread';
81
-    } else {
82
-        $Read = 'read';
83
-    }
84
-    $UserInfo = Users::user_info($LastAuthorID);
85
-
86
-    $JsonForums[] = array(
87
-    'forumId' => (int)$ForumID,
88
-    'forumName' => $ForumName,
89
-    'forumDescription' => $ForumDescription,
90
-    'numTopics' => (float)$NumTopics,
91
-    'numPosts' => (float)$NumPosts,
92
-    'lastPostId' => (float)$LastPostID,
93
-    'lastAuthorId' => (float)$LastAuthorID,
94
-    'lastPostAuthorName' => $UserInfo['Username'],
95
-    'lastTopicId' => (float)$LastTopicID,
96
-    'lastTime' => $LastTime,
97
-    'specificRules' => $SpecificRules,
98
-    'lastTopic' => display_str($LastTopic),
99
-    'read' => $Read === 1,
100
-    'locked' => $Locked === 1,
101
-    'sticky' => $Sticky === 1
102
-  );
103
-}
104
-// ...And an extra one to catch the last category.
105
-if (!empty($JsonForums) && !empty($JsonCategory)) {
106
-    $JsonCategory['forums'] = $JsonForums;
107
-    $JsonCategories[] = $JsonCategory;
108
-}
109
-
110
-echo json_encode(
111
-    array(
112
-    'status' => 'success',
113
-    'response' => array(
114
-      'categories' => $JsonCategories
115
-    )
116
-  )
117
-);

+ 0
- 291
sections/ajax/forum/thread.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-// todo: Normalize thread_*_info don't need to waste all that ram on things that are already in other caches
6
-
7
-/**********|| Page to show individual threads || ********************************\
8
-
9
-Things to expect in $_GET:
10
-  ThreadID: ID of the forum curently being browsed
11
-  page: The page the user's on.
12
-  page = 1 is the same as no page
13
-
14
-********************************************************************************/
15
-
16
-//---------- Things to sort out before it can start printing/generating content
17
-
18
-// Check for lame SQL injection attempts
19
-if (!isset($_GET['threadid']) || !is_number($_GET['threadid'])) {
20
-    if (isset($_GET['topicid']) && is_number($_GET['topicid'])) {
21
-        $ThreadID = $_GET['topicid'];
22
-    } elseif (isset($_GET['postid']) && is_number($_GET['postid'])) {
23
-        $DB->query("
24
-        SELECT TopicID
25
-        FROM forums_posts
26
-          WHERE ID = $_GET[postid]");
27
-        list($ThreadID) = $DB->next_record();
28
-
29
-        if ($ThreadID) {
30
-            // Redirect postid to threadid when necessary
31
-            header("Location: ajax.php?action=forum&type=viewthread&threadid=$ThreadID&postid=$_GET[postid]");
32
-            error();
33
-        } else {
34
-            echo json_encode(array('status' => 'failure'));
35
-            error();
36
-        }
37
-    } else {
38
-        echo json_encode(array('status' => 'failure'));
39
-        error();
40
-    }
41
-} else {
42
-    $ThreadID = $_GET['threadid'];
43
-}
44
-
45
-if (isset($_GET['pp'])) {
46
-    $PerPage = $_GET['pp'];
47
-} elseif (isset($LoggedUser['PostsPerPage'])) {
48
-    $PerPage = $LoggedUser['PostsPerPage'];
49
-} else {
50
-    $PerPage = POSTS_PER_PAGE;
51
-}
52
-
53
-//---------- Get some data to start processing
54
-
55
-// Thread information, constant across all pages
56
-$ThreadInfo = Forums::get_thread_info($ThreadID, true, true);
57
-if ($ThreadInfo === null) {
58
-    json_die('failure', 'no such thread exists');
59
-}
60
-$ForumID = $ThreadInfo['ForumID'];
61
-
62
-// Make sure they're allowed to look at the page
63
-if (!Forums::check_forumperm($ForumID)) {
64
-    echo json_encode(array('status' => 'failure'));
65
-    error();
66
-}
67
-
68
-// Post links utilize the catalogue & key params to prevent issues with custom posts per page
69
-if ($ThreadInfo['Posts'] > $PerPage) {
70
-    if (isset($_GET['post']) && is_number($_GET['post'])) {
71
-        $PostNum = $_GET['post'];
72
-    } elseif (isset($_GET['postid']) && is_number($_GET['postid'])) {
73
-        $DB->query("
74
-        SELECT COUNT(ID)
75
-        FROM forums_posts
76
-          WHERE TopicID = $ThreadID
77
-          AND ID <= $_GET[postid]");
78
-        list($PostNum) = $DB->next_record();
79
-    } else {
80
-        $PostNum = 1;
81
-    }
82
-} else {
83
-    $PostNum = 1;
84
-}
85
-list($Page, $Limit) = Format::page_limit($PerPage, min($ThreadInfo['Posts'], $PostNum));
86
-if (($Page - 1) * $PerPage > $ThreadInfo['Posts']) {
87
-    $Page = ceil($ThreadInfo['Posts'] / $PerPage);
88
-}
89
-list($CatalogueID, $CatalogueLimit) = Format::catalogue_limit($Page, $PerPage, THREAD_CATALOGUE);
90
-
91
-// Cache catalogue from which the page is selected, allows block caches and future ability to specify posts per page
92
-if (!$Catalogue = $Cache->get_value("thread_$ThreadID"."_catalogue_$CatalogueID")) {
93
-    $DB->query("
94
-    SELECT
95
-      p.ID,
96
-      p.AuthorID,
97
-      p.AddedTime,
98
-      p.Body,
99
-      p.EditedUserID,
100
-      p.EditedTime
101
-    FROM forums_posts AS p
102
-    WHERE p.TopicID = '$ThreadID'
103
-      AND p.ID != '".$ThreadInfo['StickyPostID']."'
104
-    LIMIT $CatalogueLimit");
105
-    $Catalogue = $DB->to_array(false, MYSQLI_ASSOC);
106
-    if (!$ThreadInfo['IsLocked'] || $ThreadInfo['IsSticky']) {
107
-        $Cache->cache_value("thread_$ThreadID"."_catalogue_$CatalogueID", $Catalogue, 0);
108
-    }
109
-}
110
-$Thread = Format::catalogue_select($Catalogue, $Page, $PerPage, THREAD_CATALOGUE);
111
-
112
-if ($_GET['updatelastread'] !== '0') {
113
-    $LastPost = end($Thread);
114
-    $LastPost = $LastPost['ID'];
115
-    reset($Thread);
116
-    if ($ThreadInfo['Posts'] <= $PerPage * $Page && $ThreadInfo['StickyPostID'] > $LastPost) {
117
-        $LastPost = $ThreadInfo['StickyPostID'];
118
-    }
119
-    // Handle last read
120
-    if (!$ThreadInfo['IsLocked'] || $ThreadInfo['IsSticky']) {
121
-        $DB->query("
122
-        SELECT PostID
123
-        FROM forums_last_read_topics
124
-          WHERE UserID = '$LoggedUser[ID]'
125
-          AND TopicID = '$ThreadID'");
126
-        list($LastRead) = $DB->next_record();
127
-
128
-        if ($LastRead < $LastPost) {
129
-            $DB->query("
130
-            INSERT INTO forums_last_read_topics
131
-              (UserID, TopicID, PostID)
132
-            VALUES
133
-              ('$LoggedUser[ID]', '$ThreadID', '".db_string($LastPost)."')
134
-            ON DUPLICATE KEY UPDATE
135
-              PostID = '$LastPost'");
136
-        }
137
-    }
138
-}
139
-
140
-// Handle subscriptions
141
-$UserSubscriptions = Subscriptions::get_subscriptions();
142
-
143
-if (empty($UserSubscriptions)) {
144
-    $UserSubscriptions = [];
145
-}
146
-
147
-if (in_array($ThreadID, $UserSubscriptions)) {
148
-    $Cache->delete_value('subscriptions_user_new_'.$LoggedUser['ID']);
149
-}
150
-
151
-$JsonPoll = [];
152
-if ($ThreadInfo['NoPoll'] === 0) {
153
-    if (!list($Question, $Answers, $Votes, $Featured, $Closed) = $Cache->get_value("polls_$ThreadID")) {
154
-        $DB->query("
155
-        SELECT Question, Answers, Featured, Closed
156
-        FROM forums_polls
157
-          WHERE TopicID = '$ThreadID'");
158
-        list($Question, $Answers, $Featured, $Closed) = $DB->next_record(MYSQLI_NUM, array(1));
159
-        $Answers = unserialize($Answers);
160
-        $DB->query("
161
-        SELECT Vote, COUNT(UserID)
162
-        FROM forums_polls_votes
163
-          WHERE TopicID = '$ThreadID'
164
-        GROUP BY Vote");
165
-        $VoteArray = $DB->to_array(false, MYSQLI_NUM);
166
-
167
-        $Votes = [];
168
-        foreach ($VoteArray as $VoteSet) {
169
-            list($Key, $Value) = $VoteSet;
170
-            $Votes[$Key] = $Value;
171
-        }
172
-
173
-        foreach (array_keys($Answers) as $i) {
174
-            if (!isset($Votes[$i])) {
175
-                $Votes[$i] = 0;
176
-            }
177
-        }
178
-        $Cache->cache_value("polls_$ThreadID", array($Question, $Answers, $Votes, $Featured, $Closed), 0);
179
-    }
180
-
181
-    if (!empty($Votes)) {
182
-        $TotalVotes = array_sum($Votes);
183
-        $MaxVotes = max($Votes);
184
-    } else {
185
-        $TotalVotes = 0;
186
-        $MaxVotes = 0;
187
-    }
188
-
189
-    #$RevealVoters = in_array($ForumID, FORUMS_TO_REVEAL_VOTERS);
190
-
191
-    // Polls lose the you voted arrow thingy
192
-    $DB->query("
193
-    SELECT Vote
194
-    FROM forums_polls_votes
195
-      WHERE UserID = '".$LoggedUser['ID']."'
196
-      AND TopicID = '$ThreadID'");
197
-    list($UserResponse) = $DB->next_record();
198
-    if (!empty($UserResponse) && $UserResponse !== 0) {
199
-        $Answers[$UserResponse] = '&rsaquo; '.$Answers[$UserResponse];
200
-    } /* else {
201
-        if (!empty($UserResponse) && $RevealVoters) {
202
-            $Answers[$UserResponse] = '&rsaquo; '.$Answers[$UserResponse];
203
-        }
204
-    }
205
-    */
206
-
207
-    $JsonPoll['closed'] = ($Closed === 1);
208
-    $JsonPoll['featured'] = $Featured;
209
-    $JsonPoll['question'] = $Question;
210
-    $JsonPoll['maxVotes'] = (int)$MaxVotes;
211
-    $JsonPoll['totalVotes'] = $TotalVotes;
212
-    $JsonPollAnswers = [];
213
-
214
-    foreach ($Answers as $i => $Answer) {
215
-        if (!empty($Votes[$i]) && $TotalVotes > 0) {
216
-            $Ratio = $Votes[$i] / $MaxVotes;
217
-            $Percent = $Votes[$i] / $TotalVotes;
218
-        } else {
219
-            $Ratio = 0;
220
-            $Percent = 0;
221
-        }
222
-        $JsonPollAnswers[] = array(
223
-            'answer' => $Answer,
224
-            'ratio' => $Ratio,
225
-            'percent' => $Percent
226
-    );
227
-    }
228
-
229
-    if ($UserResponse !== null || $Closed || $ThreadInfo['IsLocked'] || $LoggedUser['Class'] < $Forums[$ForumID]['MinClassWrite']) {
230
-        $JsonPoll['voted'] = true;
231
-    } else {
232
-        $JsonPoll['voted'] = false;
233
-    }
234
-
235
-    $JsonPoll['answers'] = $JsonPollAnswers;
236
-}
237
-
238
-// Sqeeze in stickypost
239
-if ($ThreadInfo['StickyPostID']) {
240
-    if ($ThreadInfo['StickyPostID'] !== $Thread[0]['ID']) {
241
-        array_unshift($Thread, $ThreadInfo['StickyPost']);
242
-    }
243
-    if ($ThreadInfo['StickyPostID'] !== $Thread[count($Thread) - 1]['ID']) {
244
-        $Thread[] = $ThreadInfo['StickyPost'];
245
-    }
246
-}
247
-
248
-$JsonPosts = [];
249
-foreach ($Thread as $Key => $Post) {
250
-    list($PostID, $AuthorID, $AddedTime, $Body, $EditedUserID, $EditedTime) = array_values($Post);
251
-    list($AuthorID, $Username, $PermissionID, $Paranoia, $Artist, $Donor, $Warned, $Avatar, $Enabled, $UserTitle) = array_values(Users::user_info($AuthorID));
252
-
253
-    $UserInfo = Users::user_info($EditedUserID);
254
-    $JsonPosts[] = [
255
-    'postId' => (int)$PostID,
256
-    'addedTime' => $AddedTime,
257
-    'bbBody' => $Body,
258
-    'body' => Text::full_format($Body),
259
-    'editedUserId' => (int)$EditedUserID,
260
-    'editedTime' => $EditedTime,
261
-    'editedUsername' => $UserInfo['Username'],
262
-    'author' => [
263
-      'authorId' => (int)$AuthorID,
264
-      'authorName' => $Username,
265
-      'paranoia' => $Paranoia,
266
-      'artist' => $Artist === '1',
267
-      'donor' => $Donor === '1',
268
-      'warned' => (bool)$Warned,
269
-      'avatar' => $Avatar,
270
-      'enabled' => $Enabled === '2' ? false : true,
271
-      'userTitle' => $UserTitle
272
-    ]
273
-  ];
274
-}
275
-
276
-echo json_encode([
277
-  'status' => 'success',
278
-  'response' => [
279
-    'forumId' => (int)$ForumID,
280
-    'forumName' => $Forums[$ForumID]['Name'],
281
-    'threadId' => (int)$ThreadID,
282
-    'threadTitle' => display_str($ThreadInfo['Title']),
283
-    'subscribed' => in_array($ThreadID, $UserSubscriptions),
284
-    'locked' => $ThreadInfo['IsLocked'] === 1,
285
-    'sticky' => $ThreadInfo['IsSticky'] === 1,
286
-    'currentPage' => (int)$Page,
287
-    'pages' => ceil($ThreadInfo['Posts'] / $PerPage),
288
-    'poll' => empty($JsonPoll) ? null : $JsonPoll,
289
-    'posts' => $JsonPosts
290
-  ]
291
-]);

+ 0
- 21
sections/ajax/get_friends.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$DB->query("
5
-SELECT
6
-  f.FriendID,
7
-  u.Username
8
-FROM friends AS f
9
-  RIGHT JOIN users_enable_recommendations AS r
10
-  ON r.ID = f.FriendID
11
-    AND r.Enable = 1
12
-  RIGHT JOIN users_main AS u
13
-  ON u.ID = f.FriendID
14
-WHERE f.UserID = '$LoggedUser[ID]'
15
-ORDER BY u.Username ASC
16
-");
17
-
18
-json_die('success', json_encode($DB->to_array(false, MYSQLI_ASSOC)));
19
-
20
-#echo json_encode($DB->to_array(false, MYSQLI_ASSOC));
21
-#die();

+ 0
- 8
sections/ajax/get_user_notifications.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$Skip = [];
5
-$Skip[] = db_string($_GET['skip']);
6
-
7
-$NotificationsManager = new NotificationsManager($LoggedUser['ID'], $Skip);
8
-json_die('success', $NotificationsManager->get_notifications());

+ 0
- 118
sections/ajax/inbox/inbox.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$UserID = $LoggedUser['ID'];
5
-
6
-
7
-if (empty($_GET['type'])) {
8
-  $Section = 'inbox';
9
-} else {
10
-  $Section = $_GET['type']; // either 'inbox' or 'sentbox'
11
-}
12
-if (!in_array($Section, array('inbox', 'sentbox'))) {
13
-  print
14
-    json_encode(
15
-      array(
16
-        'status' => 'failure'
17
-      )
18
-    );
19
-  error();
20
-}
21
-
22
-list($Page, $Limit) = Format::page_limit(MESSAGES_PER_PAGE);
23
-
24
-$Sort = empty($_GET['sort']) || $_GET['sort'] != "unread" ? "Date DESC" : "cu.Unread = '1' DESC, DATE DESC";
25
-
26
-$sql = "
27
-  SELECT
28
-    SQL_CALC_FOUND_ROWS
29
-    c.ID,
30
-    c.Subject,
31
-    cu.Unread,
32
-    cu.Sticky,
33
-    cu.ForwardedTo,
34
-    um2.Username AS ForwardedName,
35
-    cu2.UserID,
36
-    um.Username,
37
-    ui.Donor,
38
-    ui.Warned,
39
-    um.Enabled,
40
-    ui.Avatar,";
41
-$sql .= $Section === 'sentbox' ? ' cu.SentDate ' : ' cu.ReceivedDate ';
42
-$sql .= "AS Date
43
-  FROM pm_conversations AS c
44
-    LEFT JOIN pm_conversations_users AS cu ON cu.ConvID = c.ID AND cu.UserID = '$UserID'
45
-    LEFT JOIN pm_conversations_users AS cu2 ON cu2.ConvID = c.ID AND cu2.UserID != '$UserID' AND cu2.ForwardedTo = 0
46
-    LEFT JOIN users_main AS um ON um.ID = cu2.UserID
47
-    LEFT JOIN users_info AS ui ON ui.UserID = um.ID
48
-    LEFT JOIN users_main AS um2 ON um2.ID = cu.ForwardedTo";
49
-
50
-if (!empty($_GET['search']) && $_GET['searchtype'] === 'message') {
51
-  $sql .= ' JOIN pm_messages AS m ON c.ID = m.ConvID';
52
-}
53
-$sql .= " WHERE ";
54
-if (!empty($_GET['search'])) {
55
-  $Search = db_string($_GET['search']);
56
-  if ($_GET['searchtype'] === 'user') {
57
-    $sql .= "um.Username LIKE '$Search' AND ";
58
-  } elseif ($_GET['searchtype'] === 'subject') {
59
-    $Words = explode(' ', $Search);
60
-    $sql .= "c.Subject LIKE '%".implode("%' AND c.Subject LIKE '%", $Words)."%' AND ";
61
-  } elseif ($_GET['searchtype'] === 'message') {
62
-    $Words = explode(' ', $Search);
63
-    $sql .= "m.Body LIKE '%".implode("%' AND m.Body LIKE '%", $Words)."%' AND ";
64
-  }
65
-}
66
-$sql .= $Section === 'sentbox' ? ' cu.InSentbox' : ' cu.InInbox';
67
-$sql .= " = '1'";
68
-
69
-$sql .= "
70
-  GROUP BY c.ID
71
-  ORDER BY cu.Sticky, $Sort
72
-  LIMIT $Limit";
73
-$Results = $DB->query($sql);
74
-$DB->query('SELECT FOUND_ROWS()');
75
-list($NumResults) = $DB->next_record();
76
-$DB->set_query_id($Results);
77
-
78
-$CurURL = Format::get_url(array('sort'));
79
-if (empty($CurURL)) {
80
-  $CurURL = "inbox.php?";
81
-} else {
82
-  $CurURL = "inbox.php?".$CurURL."&";
83
-}
84
-
85
-$Pages = Format::get_pages($Page, $NumResults, MESSAGES_PER_PAGE, 9);
86
-
87
-$JsonMessages = [];
88
-while (list($ConvID, $Subject, $Unread, $Sticky, $ForwardedID, $ForwardedName, $SenderID, $Username, $Donor, $Warned, $Enabled, $Avatar, $Date) = $DB->next_record()) {
89
-  $JsonMessage = array(
90
-    'convId' => (int)$ConvID,
91
-    'subject' => $Subject,
92
-    'unread' => $Unread == 1,
93
-    'sticky' => $Sticky == 1,
94
-    'forwardedId' => (int)$ForwardedID,
95
-    'forwardedName' => $ForwardedName,
96
-    'senderId' => (int)$SenderID,
97
-    'username' => $Username,
98
-    'avatar' => $Avatar,
99
-    'donor' => $Donor == 1,
100
-    'warned' => $Warned == 1,
101
-    'enabled' => $Enabled == 2 ? false : true,
102
-    'date' => $Date
103
-  );
104
-  $JsonMessages[] = $JsonMessage;
105
-}
106
-
107
-print
108
-  json_encode(
109
-    array(
110
-      'status' => 'success',
111
-      'response' => array(
112
-        'currentPage' => (int)$Page,
113
-        'pages' => ceil($NumResults / MESSAGES_PER_PAGE),
114
-        'messages' => $JsonMessages
115
-      )
116
-    )
117
-  );
118
-?>

+ 0
- 13
sections/ajax/inbox/index.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (empty($_GET['type']) || $_GET['type'] == 'inbox' || $_GET['type'] == 'sentbox') {
5
-  require(SERVER_ROOT.'/sections/ajax/inbox/inbox.php');
6
-} elseif ($_GET['type'] == 'viewconv') {
7
-  require(SERVER_ROOT.'/sections/ajax/inbox/viewconv.php');
8
-} else {
9
-  echo json_encode(array('status' => 'failure'));
10
-  error();
11
-}
12
-
13
-?>

+ 0
- 106
sections/ajax/inbox/viewconv.php View File

1
-<?
2
-$ConvID = $_GET['id'];
3
-if (!$ConvID || !is_number($ConvID)) {
4
-  echo json_encode(array('status' => 'failure'));
5
-  error();
6
-}
7
-
8
-
9
-
10
-$UserID = $LoggedUser['ID'];
11
-$DB->query("
12
-  SELECT InInbox, InSentbox
13
-  FROM pm_conversations_users
14
-  WHERE UserID = '$UserID'
15
-    AND ConvID = '$ConvID'");
16
-if (!$DB->has_results()) {
17
-  echo json_encode(array('status' => 'failure'));
18
-  error();
19
-}
20
-list($InInbox, $InSentbox) = $DB->next_record();
21
-
22
-
23
-
24
-
25
-if (!$InInbox && !$InSentbox) {
26
-  echo json_encode(array('status' => 'failure'));
27
-  error();
28
-}
29
-
30
-// Get information on the conversation
31
-$DB->query("
32
-  SELECT
33
-    c.Subject,
34
-    cu.Sticky,
35
-    cu.UnRead,
36
-    cu.ForwardedTo,
37
-    um.Username
38
-  FROM pm_conversations AS c
39
-    JOIN pm_conversations_users AS cu ON c.ID = cu.ConvID
40
-    LEFT JOIN users_main AS um ON um.ID = cu.ForwardedTo
41
-  WHERE c.ID = '$ConvID'
42
-    AND UserID = '$UserID'");
43
-list($Subject, $Sticky, $UnRead, $ForwardedID, $ForwardedName) = $DB->next_record();
44
-
45
-$DB->query("
46
-  SELECT um.ID, Username
47
-  FROM pm_messages AS pm
48
-    JOIN users_main AS um ON um.ID = pm.SenderID
49
-  WHERE pm.ConvID = '$ConvID'");
50
-
51
-while (list($PMUserID, $Username) = $DB->next_record()) {
52
-  $PMUserID = (int)$PMUserID;
53
-  $Users[$PMUserID]['UserStr'] = Users::format_username($PMUserID, true, true, true, true);
54
-  $Users[$PMUserID]['Username'] = $Username;
55
-  $UserInfo = Users::user_info($PMUserID);
56
-  $Users[$PMUserID]['Avatar'] = $UserInfo['Avatar'];
57
-}
58
-$Users[0]['UserStr'] = 'System'; // in case it's a message from the system
59
-$Users[0]['Username'] = 'System';
60
-$Users[0]['Avatar'] = '';
61
-
62
-if ($UnRead == '1') {
63
-  $DB->query("
64
-    UPDATE pm_conversations_users
65
-    SET UnRead = '0'
66
-    WHERE ConvID = '$ConvID'
67
-      AND UserID = '$UserID'");
68
-  // Clear the caches of the inbox and sentbox
69
-  $Cache->decrement("inbox_new_$UserID");
70
-}
71
-
72
-// Get messages
73
-$DB->query("
74
-  SELECT SentDate, SenderID, Body, ID
75
-  FROM pm_messages
76
-  WHERE ConvID = '$ConvID'
77
-  ORDER BY ID");
78
-
79
-$JsonMessages = [];
80
-while (list($SentDate, $SenderID, $Body, $MessageID) = $DB->next_record()) {
81
-  $Body = apcu_exists('DBKEY') ? Crypto::decrypt($Body) : '[Encrypted]';
82
-  $JsonMessage = array(
83
-    'messageId' => (int)$MessageID,
84
-    'senderId' => (int)$SenderID,
85
-    'senderName' => $Users[(int)$SenderID]['Username'],
86
-    'sentDate' => $SentDate,
87
-    'avatar' => $Users[(int)$SenderID]['Avatar'],
88
-    'bbBody' => $Body,
89
-    'body' => Text::full_format($Body)
90
-  );
91
-  $JsonMessages[] = $JsonMessage;
92
-}
93
-
94
-print
95
-  json_encode(
96
-    array(
97
-      'status' => 'success',
98
-      'response' => array(
99
-        'convId' => (int)$ConvID,
100
-        'subject' => $Subject.($ForwardedID > 0 ? " (Forwarded to $ForwardedName)" : ''),
101
-        'sticky' => $Sticky == 1,
102
-        'messages' => $JsonMessages
103
-      )
104
-    )
105
-  );
106
-?>

+ 0
- 291
sections/ajax/index.php View File

1
-<?php
2
-declare(strict_types = 1);
3
-
4
-/**
5
- * AJAX Switch Center
6
- *
7
- * This page acts as an AJAX "switch" - it's called by scripts, and it includes the required pages.
8
- * The required page is determined by $_GET['action'].
9
- */
10
-
11
-# $_POST login cookie
12
-if (!isset($FullToken)) {
13
-    enforce_login();
14
-}
15
-
16
-/*
17
-# I wish...
18
-else {
19
-  authorize(true);
20
-}
21
-*/
22
-
23
-
24
-/**
25
- * These users aren't rate limited.
26
- * This array should contain user IDs.
27
- */
28
-
29
-# Get people with Donor permissions
30
-$Donors = $DB->query("
31
-SELECT
32
-  `ID`
33
-FROM
34
-  `users_main`
35
-WHERE
36
-  `PermissionID` = 20
37
-");
38
-
39
-# Add Donors to $UserExceptions or define manually
40
-if ($DB->record_count()) {
41
-    $UserExceptions = array_unique($DB->collect('ID'));
42
-} else {
43
-    $UserExceptions = array(
44
-      # 1, 2, 3, etc.
45
-    );
46
-}
47
-
48
-# System and admin fix
49
-array_push($UserExceptions, 0, 1);
50
-
51
-
52
-/**
53
- * AJAX_LIMIT = array($x, $y) = $x requests every $y seconds,
54
- * e.g., array(5, 10) = 5 requests every 10 seconds.
55
- */
56
-$AJAX_LIMIT = array(1, 6);
57
-$UserID = $LoggedUser['ID'];
58
-
59
-# Set proper headers for JSON output
60
-# https://github.com/OPSnet/Gazelle/blob/master/sections/ajax/index.php
61
-if (!empty($_SERVER['CONTENT_TYPE']) && substr($_SERVER['CONTENT_TYPE'], 0, 16) === 'application/json') {
62
-    $_POST = json_decode(file_get_contents('php://input'), true);
63
-}
64
-header('Content-Type: application/json; charset=utf-8');
65
-
66
-//  Enforce rate limiting everywhere except info.php
67
-if (!in_array($UserID, $UserExceptions) && isset($_GET['action'])) {
68
-    if (!$UserRequests = $Cache->get_value("ajax_requests_$UserID")) {
69
-        $UserRequests = 0;
70
-        $Cache->cache_value("ajax_requests_$UserID", '0', $AJAX_LIMIT[1]);
71
-    }
72
-
73
-    if ($UserRequests > $AJAX_LIMIT[0]) {
74
-        json_die('failure', 'rate limit exceeded');
75
-    } else {
76
-        $Cache->increment_value("ajax_requests_$UserID");
77
-    }
78
-}
79
-
80
-
81
-/**
82
- * Actions
83
- */
84
-switch ($_GET['action']) {
85
-  /**
86
-   * Torrents
87
-   */
88
-  case 'torrent':
89
-    require_once 'torrent.php';
90
-    break;
91
-
92
-  case 'torrentgroup':
93
-    require_once 'torrentgroup.php';
94
-    break;
95
-
96
-  // So the album art script can function without breaking the rate limit
97
-  case 'torrentgroupalbumart':
98
-    require_once SERVER_ROOT.'/sections/ajax/torrentgroupalbumart.php';
99
-    break;
100
-
101
-  case 'browse':
102
-    require_once SERVER_ROOT.'/sections/ajax/browse.php';
103
-    break;
104
-  
105
-   case 'tcomments':
106
-    require_once SERVER_ROOT.'/sections/ajax/tcomments.php';
107
-    break;
108
-
109
-  /**
110
-   * Features
111
-   */
112
-  case 'collage':
113
-    require_once SERVER_ROOT.'/sections/ajax/collage.php';
114
-    break;
115
-  
116
-  case 'artist':
117
-    require_once SERVER_ROOT.'/sections/ajax/artist.php';
118
-    break;
119
-
120
-  case 'request':
121
-    require_once SERVER_ROOT.'/sections/ajax/request.php';
122
-    break;
123
-
124
-  case 'requests':
125
-    require_once SERVER_ROOT.'/sections/ajax/requests.php';
126
-    break;
127
-
128
-  case 'top10':
129
-    require_once SERVER_ROOT.'/sections/ajax/top10/index.php';
130
-    break;
131
-
132
-  /**
133
-   * Users
134
-   */
135
-  case 'user':
136
-    require_once SERVER_ROOT.'/sections/ajax/user.php';
137
-    break;
138
-
139
-  case 'usersearch':
140
-    require_once SERVER_ROOT.'/sections/ajax/usersearch.php';
141
-    break;
142
-  
143
-  case 'community_stats':
144
-    require_once SERVER_ROOT.'/sections/ajax/community_stats.php';
145
-    break;
146
-
147
-  case 'user_recents':
148
-    require_once SERVER_ROOT.'/sections/ajax/user_recents.php';
149
-    break;
150
-
151
-  case 'userhistory':
152
-    require_once SERVER_ROOT.'/sections/ajax/userhistory/index.php';
153
-    break;
154
-
155
-  /**
156
-   * Account
157
-   */
158
-  case 'inbox':
159
-    require_once SERVER_ROOT.'/sections/ajax/inbox/index.php';
160
-    break;
161
-
162
-  case 'bookmarks':
163
-    require_once SERVER_ROOT.'/sections/ajax/bookmarks/index.php';
164
-    break;
165
-
166
-  case 'notifications':
167
-    require_once SERVER_ROOT.'/sections/ajax/notifications.php';
168
-    break;
169
-
170
-  case 'get_user_notifications':
171
-    require_once SERVER_ROOT.'/sections/ajax/get_user_notifications.php';
172
-    break;
173
-
174
-  case 'clear_user_notification':
175
-    require_once SERVER_ROOT.'/sections/ajax/clear_user_notification.php';
176
-    break;
177
-
178
-  /**
179
-   * Forums
180
-   */
181
-  case 'forum':
182
-    require_once SERVER_ROOT.'/sections/ajax/forum/index.php';
183
-    break;
184
-
185
-  case 'subscriptions':
186
-    require_once SERVER_ROOT.'/sections/ajax/subscriptions.php';
187
-    break;
188
-
189
-  case 'raw_bbcode':
190
-    require_once SERVER_ROOT.'/sections/ajax/raw_bbcode.php';
191
-    break;
192
-
193
-  /**
194
-   * Meta
195
-   */
196
-  case 'index':
197
-    require_once SERVER_ROOT.'/sections/ajax/info.php';
198
-    break;
199
-
200
-  case 'manifest':
201
-    require_once SERVER_ROOT.'/manifest.php';
202
-    json_die('success', manifest());
203
-    break;
204
-
205
-  case 'stats':
206
-    require_once SERVER_ROOT.'/sections/ajax/stats.php';
207
-    break;
208
-
209
-  case 'loadavg':
210
-    require_once SERVER_ROOT.'/sections/ajax/loadavg.php';
211
-    break;
212
-
213
-  case 'announcements':
214
-    require_once SERVER_ROOT.'/sections/ajax/announcements.php';
215
-    break;
216
-
217
-  case 'wiki':
218
-    require_once SERVER_ROOT.'/sections/ajax/wiki.php';
219
-    break;
220
-  
221
-  case 'ontology':
222
-    require_once SERVER_ROOT.'/sections/ajax/ontology.php';
223
-    break;
224
-  
225
-  /**
226
-   * Under construction
227
-   */
228
-  case 'preview':
229
-    require_once 'preview.php';
230
-    break;
231
-
232
-  case 'better':
233
-    require_once SERVER_ROOT.'/sections/ajax/better/index.php';
234
-    break;
235
-
236
-  case 'get_friends':
237
-    require_once SERVER_ROOT.'/sections/ajax/get_friends.php';
238
-    break;
239
-
240
-  case 'news_ajax':
241
-    require_once SERVER_ROOT.'/sections/ajax/news_ajax.php';
242
-    break;
243
-
244
-  case 'send_recommendation':
245
-    require_once SERVER_ROOT.'/sections/ajax/send_recommendation.php';
246
-    break;
247
-
248
-  /*
249
-  case 'similar_artists':
250
-    require_once SERVER_ROOT.'/sections/ajax/similar_artists.php';
251
-    break;
252
-  */
253
-
254
-  /*
255
-  case 'votefavorite':
256
-    require_once SERVER_ROOT.'/sections/ajax/takevote.php';
257
-    break;
258
-  */
259
-
260
-  /*
261
-  case 'torrent_info':
262
-    require_once 'torrent_info.php';
263
-    break;
264
-  */
265
-
266
-  /*
267
-  case 'checkprivate':
268
-    include 'checkprivate.php';
269
-    break;
270
-  */
271
-
272
-  case 'autofill':
273
-    /*
274
-    if ($_GET['cat'] === 'anime') {
275
-        require_once SERVER_ROOT.'/sections/ajax/autofill/anime.php';
276
-    }
277
-
278
-    if ($_GET['cat'] === 'jav') {
279
-        require_once SERVER_ROOT.'/sections/ajax/autofill/jav.php';
280
-    }
281
-
282
-    if ($_GET['cat'] === 'manga') {
283
-        require_once SERVER_ROOT.'/sections/ajax/autofill/manga.php';
284
-    }
285
-    */
286
-    break;
287
-
288
-  default:
289
-    // If they're screwing around with the query string
290
-    json_die('failure');
291
-}

+ 0
- 117
sections/ajax/info.php View File

1
-<?
2
-//calculate ratio
3
-//returns 0 for DNE and -1 for infinity, because we don't want strings being returned for a numeric value in our java
4
-$Ratio = 0;
5
-if ($LoggedUser['BytesUploaded'] == 0 && $LoggedUser['BytesDownloaded'] == 0) {
6
-  $Ratio = 0;
7
-} elseif ($LoggedUser['BytesDownloaded'] == 0) {
8
-  $Ratio = -1;
9
-} else {
10
-  $Ratio = number_format(max($LoggedUser['BytesUploaded'] / $LoggedUser['BytesDownloaded'] - 0.005, 0), 2); //Subtract .005 to floor to 2 decimals
11
-}
12
-
13
-$MyNews = $LoggedUser['LastReadNews'];
14
-$CurrentNews = $Cache->get_value('news_latest_id');
15
-if ($CurrentNews === false) {
16
-  $DB->query("
17
-    SELECT ID
18
-    FROM news
19
-    ORDER BY Time DESC
20
-    LIMIT 1");
21
-  if ($DB->record_count() === 1) {
22
-    list($CurrentNews) = $DB->next_record();
23
-  } else {
24
-    $CurrentNews = -1;
25
-  }
26
-  $Cache->cache_value('news_latest_id', $CurrentNews, 0);
27
-}
28
-
29
-$NewMessages = $Cache->get_value('inbox_new_' . $LoggedUser['ID']);
30
-if ($NewMessages === false) {
31
-  $DB->query("
32
-    SELECT COUNT(UnRead)
33
-    FROM pm_conversations_users
34
-    WHERE UserID = '" . $LoggedUser['ID'] . "'
35
-      AND UnRead = '1'
36
-      AND InInbox = '1'");
37
-  list($NewMessages) = $DB->next_record();
38
-  $Cache->cache_value('inbox_new_' . $LoggedUser['ID'], $NewMessages, 0);
39
-}
40
-
41
-if (check_perms('site_torrents_notify')) {
42
-  $NewNotifications = $Cache->get_value('notifications_new_' . $LoggedUser['ID']);
43
-  if ($NewNotifications === false) {
44
-    $DB->query("
45
-      SELECT COUNT(UserID)
46
-      FROM users_notify_torrents
47
-      WHERE UserID = '$LoggedUser[ID]'
48
-        AND UnRead = '1'");
49
-    list($NewNotifications) = $DB->next_record();
50
-    /* if ($NewNotifications && !check_perms('site_torrents_notify')) {
51
-        $DB->query("DELETE FROM users_notify_torrents WHERE UserID='$LoggedUser[ID]'");
52
-        $DB->query("DELETE FROM users_notify_filters WHERE UserID='$LoggedUser[ID]'");
53
-    } */
54
-    $Cache->cache_value('notifications_new_' . $LoggedUser['ID'], $NewNotifications, 0);
55
-  }
56
-}
57
-
58
-// News
59
-$MyNews = $LoggedUser['LastReadNews'];
60
-$CurrentNews = $Cache->get_value('news_latest_id');
61
-if ($CurrentNews === false) {
62
-  $DB->query("
63
-    SELECT ID
64
-    FROM news
65
-    ORDER BY Time DESC
66
-    LIMIT 1");
67
-  if ($DB->record_count() === 1) {
68
-    list($CurrentNews) = $DB->next_record();
69
-  } else {
70
-    $CurrentNews = -1;
71
-  }
72
-  $Cache->cache_value('news_latest_id', $CurrentNews, 0);
73
-}
74
-
75
-// Blog
76
-$MyBlog = $LoggedUser['LastReadBlog'];
77
-$CurrentBlog = $Cache->get_value('blog_latest_id');
78
-if ($CurrentBlog === false) {
79
-  $DB->query("
80
-    SELECT ID
81
-    FROM blog
82
-    WHERE Important = 1
83
-    ORDER BY Time DESC
84
-    LIMIT 1");
85
-  if ($DB->record_count() === 1) {
86
-    list($CurrentBlog) = $DB->next_record();
87
-  } else {
88
-    $CurrentBlog = -1;
89
-  }
90
-  $Cache->cache_value('blog_latest_id', $CurrentBlog, 0);
91
-}
92
-
93
-// Subscriptions
94
-$NewSubscriptions = Subscriptions::has_new_subscriptions();
95
-
96
-json_die("success", array(
97
-  'username' => $LoggedUser['Username'],
98
-  'id' => (int)$LoggedUser['ID'],
99
-  'authkey' => $LoggedUser['AuthKey'],
100
-  'passkey' => $LoggedUser['torrent_pass'],
101
-  'notifications' => array(
102
-    'messages' => (int)$NewMessages,
103
-    'notifications' => (int)$NewNotifications,
104
-    'newAnnouncement' => $MyNews < $CurrentNews,
105
-    'newBlog' => $MyBlog < $CurrentBlog,
106
-    'newSubscriptions' => $NewSubscriptions == 1
107
-  ),
108
-  'userstats' => array(
109
-    'uploaded' => (int)$LoggedUser['BytesUploaded'],
110
-    'downloaded' => (int)$LoggedUser['BytesDownloaded'],
111
-    'ratio' => (float)$Ratio,
112
-    'requiredratio' => (float)$LoggedUser['RequiredRatio'],
113
-    'class' => $ClassLevels[$LoggedUser['Class']]['Name']
114
-  )
115
-));
116
-
117
-?>

+ 0
- 14
sections/ajax/loadavg.php View File

1
-<?php
2
-declare(strict_types=1);
3
-
4
-#authorize();
5
-
6
-print
7
-  json_encode(
8
-      array(
9
-        'status' => 'success',
10
-        'response' => array(
11
-          'loadAverage' => sys_getloadavg()
12
-        )
13
-      )
14
-  );

+ 0
- 42
sections/ajax/news_ajax.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-// Don't allow bigger queries than specified below regardless of called function
5
-$SizeLimit = 10;
6
-
7
-$Count = (int)$_GET['count'];
8
-$Offset = (int)$_GET['offset'];
9
-
10
-if (!isset($_GET['count']) || !isset($_GET['offset']) || $Count <= 0 || $Offset < 0 || $Count > $SizeLimit) {
11
-    json_die('failure');
12
-}
13
-
14
-Text::$TOC = true;
15
-
16
-global $DB;
17
-$DB->query("
18
-    SELECT
19
-      ID,
20
-      Title,
21
-      Body,
22
-      Time
23
-    FROM news
24
-    ORDER BY Time DESC
25
-    LIMIT $Offset, $Count");
26
-$News = $DB->to_array(false, MYSQLI_NUM, false);
27
-
28
-$NewsResponse = [];
29
-foreach ($News as $NewsItem) {
30
-    list($NewsID, $Title, $Body, $NewsTime) = $NewsItem;
31
-    array_push(
32
-        $NewsResponse,
33
-        array(
34
-      $NewsID,
35
-      Text::full_format($Title),
36
-      time_diff($NewsTime),
37
-      Text::full_format($Body)
38
-    )
39
-    );
40
-}
41
-
42
-json_die('success', json_encode($NewsResponse));

+ 0
- 110
sections/ajax/notifications.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-if (!check_perms('site_torrents_notify')) {
6
-    json_die('failure');
7
-}
8
-
9
-define('NOTIFICATIONS_PER_PAGE', 50);
10
-list($Page, $Limit) = Format::page_limit(NOTIFICATIONS_PER_PAGE);
11
-
12
-$Results = $DB->query("
13
-    SELECT
14
-      SQL_CALC_FOUND_ROWS
15
-      unt.TorrentID,
16
-      unt.UnRead,
17
-      unt.FilterID,
18
-      unf.Label,
19
-      t.GroupID
20
-    FROM users_notify_torrents AS unt
21
-      JOIN torrents AS t ON t.ID = unt.TorrentID
22
-      LEFT JOIN users_notify_filters AS unf ON unf.ID = unt.FilterID
23
-    WHERE unt.UserID = $LoggedUser[ID]".
24
-    ((!empty($_GET['filterid']) && is_number($_GET['filterid']))
25
-      ? " AND unf.ID = '$_GET[filterid]'"
26
-      : '')."
27
-    ORDER BY TorrentID DESC
28
-    LIMIT $Limit");
29
-$GroupIDs = array_unique($DB->collect('GroupID'));
30
-
31
-$DB->query('SELECT FOUND_ROWS()');
32
-list($TorrentCount) = $DB->next_record();
33
-
34
-if (count($GroupIDs)) {
35
-    $TorrentGroups = Torrents::get_groups($GroupIDs);
36
-    $DB->query("
37
-    UPDATE users_notify_torrents
38
-    SET UnRead = '0'
39
-    WHERE UserID = $LoggedUser[ID]");
40
-    $Cache->delete_value("notifications_new_$LoggedUser[ID]");
41
-}
42
-
43
-$DB->set_query_id($Results);
44
-
45
-$JsonNotifications = [];
46
-$NumNew = 0;
47
-
48
-$FilterGroups = [];
49
-while ($Result = $DB->next_record(MYSQLI_ASSOC)) {
50
-    if (!$Result['FilterID']) {
51
-        $Result['FilterID'] = 0;
52
-    }
53
-    if (!isset($FilterGroups[$Result['FilterID']])) {
54
-        $FilterGroups[$Result['FilterID']] = [];
55
-        $FilterGroups[$Result['FilterID']]['FilterLabel'] = ($Result['Label'] ? $Result['Label'] : false);
56
-    }
57
-    array_push($FilterGroups[$Result['FilterID']], $Result);
58
-}
59
-unset($Result);
60
-
61
-foreach ($FilterGroups as $FilterID => $FilterResults) {
62
-    unset($FilterResults['FilterLabel']);
63
-    foreach ($FilterResults as $Result) {
64
-        $TorrentID = $Result['TorrentID'];
65
-//    $GroupID = $Result['GroupID'];
66
-
67
-        $GroupInfo = $TorrentGroups[$Result['GroupID']];
68
-        extract(Torrents::array_group($GroupInfo)); // all group data
69
-        $TorrentInfo = $GroupInfo['Torrents'][$TorrentID];
70
-
71
-        if ($Result['UnRead'] == 1) {
72
-            $NumNew++;
73
-        }
74
-
75
-        $JsonNotifications[] = array(
76
-      'torrentId' => (int)$TorrentID,
77
-      'groupId' => (int)$GroupID,
78
-      'groupName' => $GroupName,
79
-      'groupCategoryId' => (int)$GroupCategoryID,
80
-      'wikiImage' => $WikiImage,
81
-      'torrentTags' => $TagList,
82
-      'size' => (float)$TorrentInfo['Size'],
83
-      'fileCount' => (int)$TorrentInfo['FileCount'],
84
-      'format' => $TorrentInfo['Format'],
85
-      'encoding' => $TorrentInfo['Encoding'],
86
-      'media' => $TorrentInfo['Media'],
87
-      'scene' => $TorrentInfo['Scene'] == 1,
88
-      'groupYear' => (int)$GroupYear,
89
-      'remasterYear' => (int)$TorrentInfo['RemasterYear'],
90
-      'remasterTitle' => $TorrentInfo['RemasterTitle'],
91
-      'snatched' => (int)$TorrentInfo['Snatched'],
92
-      'seeders' => (int)$TorrentInfo['Seeders'],
93
-      'leechers' => (int)$TorrentInfo['Leechers'],
94
-      'notificationTime' => $TorrentInfo['Time'],
95
-      'hasLog' => $TorrentInfo['HasLog'] == 1,
96
-      'hasCue' => $TorrentInfo['HasCue'] == 1,
97
-      'logScore' => (float)$TorrentInfo['LogScore'],
98
-      'freeTorrent' => $TorrentInfo['FreeTorrent'] == 1,
99
-      'logInDb' => $TorrentInfo['HasLog'] == 1,
100
-      'unread' => $Result['UnRead'] == 1
101
-    );
102
-    }
103
-}
104
-
105
-json_die('success', array(
106
-  'currentPages' => intval($Page),
107
-  'pages' => ceil($TorrentCount / NOTIFICATIONS_PER_PAGE),
108
-  'numNew' => $NumNew,
109
-  'results' => $JsonNotifications
110
-));

+ 0
- 12
sections/ajax/ontology.php View File

1
-<?php
2
-declare(strict_types = 1);
3
-
4
-# Quick proof-of-concept
5
-$ENV = ENV::go();
6
-print
7
-  json_encode(
8
-      array(
9
-        'status' => 'success',
10
-        'response' => $ENV->CATS
11
-      )
12
-  );

+ 0
- 12
sections/ajax/preview.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-/* AJAX previews, simple stuff */
5
-Text::$TOC = true;
6
-
7
-if (!empty($_POST['AdminComment'])) {
8
-    echo Text::full_format($_POST['AdminComment']);
9
-} else {
10
-    $Content = $_REQUEST['body']; // Don't use URL decode
11
-    echo Text::full_format($Content);
12
-}

+ 0
- 32
sections/ajax/raw_bbcode.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$PostID = (int) $_GET['postid'];
5
-
6
-if (empty($PostID)) {
7
-    json_die('error', 'empty postid');
8
-}
9
-
10
-$DB->query("
11
-SELECT
12
-  t.`ForumID`,
13
-  p.`Body`
14
-FROM
15
-  `forums_posts` AS p
16
-JOIN `forums_topics` AS t
17
-ON
18
-  p.`TopicID` = t.`ID`
19
-WHERE
20
-  p.`ID` = '$PostID'
21
-");
22
-
23
-if (!$DB->has_results()) {
24
-    json_die('error', 'no results');
25
-}
26
-
27
-list($ForumID, $Body) = $DB->next_record();
28
-if (!Forums::check_forumperm($ForumID)) {
29
-    json_die('error', 'assholes');
30
-}
31
-
32
-json_die('success', array('body' => nl2br($Body)));

+ 0
- 119
sections/ajax/request.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$RequestTax = 0.1;
5
-
6
-// Minimum and default amount of upload to remove from the user when they vote.
7
-// Also change in static/functions/requests.js
8
-$MinimumVote = 20 * 1024 * 1024;
9
-
10
-/*
11
- * This is the page that displays the request to the end user after being created.
12
- */
13
-
14
-if (empty($_GET['id']) || !is_number($_GET['id'])) {
15
-    json_die("failure");
16
-}
17
-
18
-$RequestID = (int)$_GET['id'];
19
-
20
-//First things first, lets get the data for the request.
21
-
22
-$Request = Requests::get_request($RequestID);
23
-if ($Request === false) {
24
-    json_die("failure");
25
-}
26
-
27
-$CategoryID = $Request['CategoryID'];
28
-$Requestor = Users::user_info($Request['UserID']);
29
-$Filler = $Request['FillerID'] ? Users::user_info($Request['FillerID']) : null;
30
-//Convenience variables
31
-$IsFilled = !empty($Request['TorrentID']);
32
-$CanVote = !$IsFilled && check_perms('site_vote');
33
-
34
-if ($CategoryID == 0) {
35
-    $CategoryName = 'Unknown';
36
-} else {
37
-    $CategoryName = $Categories[$CategoryID - 1];
38
-}
39
-
40
-$JsonArtists = Requests::get_artists($RequestID);
41
-
42
-//Votes time
43
-$RequestVotes = Requests::get_votes_array($RequestID);
44
-$VoteCount = count($RequestVotes['Voters']);
45
-$ProjectCanEdit = (check_perms('project_team') && !$IsFilled && (($CategoryID == 0) || ($CategoryName == 'Music' && $Request['Year'] == 0)));
46
-$UserCanEdit = (!$IsFilled && $LoggedUser['ID'] == $Request['UserID'] && $VoteCount < 2);
47
-$CanEdit = ($UserCanEdit || $ProjectCanEdit || check_perms('site_moderate_requests'));
48
-
49
-$JsonTopContributors = [];
50
-$VoteMax = ($VoteCount < 5 ? $VoteCount : 5);
51
-for ($i = 0; $i < $VoteMax; $i++) {
52
-    $User = array_shift($RequestVotes['Voters']);
53
-    $JsonTopContributors[] = array(
54
-    'userId'   => (int)$User['UserID'],
55
-    'userName' => $User['Username'],
56
-    'bounty'   => (int)$User['Bounty']
57
-  );
58
-}
59
-reset($RequestVotes['Voters']);
60
-
61
-list($NumComments, $Page, $Thread) = Comments::load('requests', $RequestID, false);
62
-
63
-$JsonRequestComments = [];
64
-foreach ($Thread as $Key => $Post) {
65
-    list($PostID, $AuthorID, $AddedTime, $Body, $EditedUserID, $EditedTime, $EditedUsername) = array_values($Post);
66
-    list($AuthorID, $Username, $PermissionID, $Paranoia, $Artist, $Donor, $Warned, $Avatar, $Enabled, $UserTitle) = array_values(Users::user_info($AuthorID));
67
-    $JsonRequestComments[] = array(
68
-    'postId'          => (int)$PostID,
69
-    'authorId'        => (int)$AuthorID,
70
-    'name'            => $Username,
71
-    'donor'           => ($Donor == 1),
72
-    'warned'          => (bool)$Warned,
73
-    'enabled'         => ($Enabled == 2 ? false : true),
74
-    'class'           => Users::make_class_string($PermissionID),
75
-    'addedTime'       => $AddedTime,
76
-    'avatar'          => $Avatar,
77
-    'comment'         => Text::full_format($Body),
78
-    'editedUserId'    => (int)$EditedUserID,
79
-    'editedUsername'  => $EditedUsername,
80
-    'editedTime'      => $EditedTime
81
-  );
82
-}
83
-
84
-$JsonTags = [];
85
-foreach ($Request['Tags'] as $Tag) {
86
-    $JsonTags[] = $Tag;
87
-}
88
-json_die('success', array(
89
-  'requestId'       => (int)$RequestID,
90
-  'requestorId'     => (int)$Request['UserID'],
91
-  'requestorName'   => $Requestor['Username'],
92
-  'isBookmarked'    => Bookmarks::has_bookmarked('request', $RequestID),
93
-  'requestTax'      => (float)$RequestTax,
94
-  'timeAdded'       => $Request['TimeAdded'],
95
-  'canEdit'         => (bool)$CanEdit,
96
-  'canVote'         => (bool)$CanVote,
97
-  'minimumVote'     => (int)$MinimumVote,
98
-  'voteCount'       => (int)$VoteCount,
99
-  'lastVote'        => $Request['LastVote'],
100
-  'topContributors' => $JsonTopContributors,
101
-  'totalBounty'     => (int)$RequestVotes['TotalBounty'],
102
-  'categoryId'      => (int)$CategoryID,
103
-  'categoryName'    => $CategoryName,
104
-  'title'           => $Request['Title'],
105
-  'year'            => (int)$Request['Year'],
106
-  'image'           => $Request['Image'],
107
-  'bbDescription'   => $Request['Description'],
108
-  'description'     => Text::full_format($Request['Description']),
109
-  'artists'         => $JsonArtists,
110
-  'isFilled'        => (bool)$IsFilled,
111
-  'fillerId'        => (int)$Request['FillerID'],
112
-  'fillerName'      => $Filler ? $Filler['Username'] : '',
113
-  'torrentId'       => (int)$Request['TorrentID'],
114
-  'timeFilled'      => $Request['TimeFilled'],
115
-  'tags'            => $JsonTags,
116
-  'comments'        => $JsonRequestComments,
117
-  'commentPage'     => (int)$Page,
118
-  'commentPages'    => (int)ceil($NumComments / TORRENT_COMMENTS_PER_PAGE)
119
-));

+ 0
- 369
sections/ajax/requests.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-$SphQL = new SphinxqlQuery();
6
-$SphQL->select('id, votes, bounty')->from('requests, requests_delta');
7
-
8
-$SortOrders = array(
9
-  'votes' => 'votes',
10
-  'bounty' => 'bounty',
11
-  'lastvote' => 'lastvote',
12
-  'filled' => 'timefilled',
13
-  'year' => 'year',
14
-  'created' => 'timeadded',
15
-  'random' => false);
16
-
17
-if (empty($_GET['order']) || !isset($SortOrders[$_GET['order']])) {
18
-    $_GET['order'] = 'created';
19
-}
20
-$OrderBy = $_GET['order'];
21
-
22
-if (!empty($_GET['sort']) && $_GET['sort'] === 'asc') {
23
-    $OrderWay = 'asc';
24
-} else {
25
-    $_GET['sort'] = 'desc';
26
-    $OrderWay = 'desc';
27
-}
28
-$NewSort = $_GET['sort'] === 'asc' ? 'desc' : 'asc';
29
-
30
-if ($OrderBy === 'random') {
31
-    $SphQL->order_by('RAND()', '');
32
-    unset($_GET['page']);
33
-} else {
34
-    $SphQL->order_by($SortOrders[$OrderBy], $OrderWay);
35
-}
36
-
37
-$Submitted = !empty($_GET['submit']);
38
-
39
-//Paranoia
40
-if (!empty($_GET['userid'])) {
41
-    if (!is_number($_GET['userid'])) {
42
-        json_die("failure");
43
-    }
44
-    $UserInfo = Users::user_info($_GET['userid']);
45
-    if (empty($UserInfo)) {
46
-        json_die("failure");
47
-    }
48
-    $Perms = Permissions::get_permissions($UserInfo['PermissionID']);
49
-    $UserClass = $Perms['Class'];
50
-}
51
-$BookmarkView = false;
52
-
53
-if (empty($_GET['type'])) {
54
-    $Title = 'Requests';
55
-    if (empty($_GET['showall'])) {
56
-        $SphQL->where('visible', 1);
57
-    }
58
-} else {
59
-    switch ($_GET['type']) {
60
-    case 'created':
61
-      if (!empty($UserInfo)) {
62
-          if (!check_paranoia('requestsvoted_list', $UserInfo['Paranoia'], $Perms['Class'], $UserInfo['ID'])) {
63
-              json_die("failure");
64
-          }
65
-          $Title = "Requests created by $UserInfo[Username]";
66
-          $SphQL->where('userid', $UserInfo['ID']);
67
-      } else {
68
-          $Title = 'My requests';
69
-          $SphQL->where('userid', $LoggedUser['ID']);
70
-      }
71
-      break;
72
-    case 'voted':
73
-      if (!empty($UserInfo)) {
74
-          if (!check_paranoia('requestsvoted_list', $UserInfo['Paranoia'], $Perms['Class'], $UserInfo['ID'])) {
75
-              json_die("failure");
76
-          }
77
-          $Title = "Requests voted for by $UserInfo[Username]";
78
-          $SphQL->where('voter', $UserInfo['ID']);
79
-      } else {
80
-          $Title = 'Requests I have voted on';
81
-          $SphQL->where('voter', $LoggedUser['ID']);
82
-      }
83
-      break;
84
-    case 'filled':
85
-      if (!empty($UserInfo)) {
86
-          if (!check_paranoia('requestsfilled_list', $UserInfo['Paranoia'], $Perms['Class'], $UserInfo['ID'])) {
87
-              json_die("failure");
88
-          }
89
-          $Title = "Requests filled by $UserInfo[Username]";
90
-          $SphQL->where('fillerid', $UserInfo['ID']);
91
-      } else {
92
-          $Title = 'Requests I have filled';
93
-          $SphQL->where('fillerid', $LoggedUser['ID']);
94
-      }
95
-      break;
96
-    case 'bookmarks':
97
-      $Title = 'Your bookmarked requests';
98
-      $BookmarkView = true;
99
-      $SphQL->where('bookmarker', $LoggedUser['ID']);
100
-      break;
101
-    default:
102
-      json_die("failure");
103
-  }
104
-}
105
-
106
-if ($Submitted && empty($_GET['show_filled'])) {
107
-    $SphQL->where('torrentid', 0);
108
-}
109
-
110
-if (!empty($_GET['formats'])) {
111
-    $FormatArray = $_GET['formats'];
112
-    if (count($FormatArray) !== count($Formats)) {
113
-        $FormatNameArray = [];
114
-        foreach ($FormatArray as $Index => $MasterIndex) {
115
-            if (isset($Formats[$MasterIndex])) {
116
-                $FormatNameArray[$Index] = '"' . strtr(Sphinxql::sph_escape_string($Formats[$MasterIndex]), '-.', '  ') . '"';
117
-            }
118
-        }
119
-        if (count($FormatNameArray) >= 1) {
120
-            if (!empty($_GET['formats_strict'])) {
121
-                $SearchString = '(' . implode(' | ', $FormatNameArray) . ')';
122
-            } else {
123
-                $SearchString = '(any | ' . implode(' | ', $FormatNameArray) . ')';
124
-            }
125
-            $SphQL->where_match($SearchString, 'formatlist', false);
126
-        }
127
-    }
128
-}
129
-
130
-if (!empty($_GET['media'])) {
131
-    $MediaArray = $_GET['media'];
132
-    if (count($MediaArray) !== count($Media)) {
133
-        $MediaNameArray = [];
134
-        foreach ($MediaArray as $Index => $MasterIndex) {
135
-            if (isset($Media[$MasterIndex])) {
136
-                $MediaNameArray[$Index] = '"' . strtr(Sphinxql::sph_escape_string($Media[$MasterIndex]), '-.', '  ') . '"';
137
-            }
138
-        }
139
-
140
-        if (count($MediaNameArray) >= 1) {
141
-            if (!empty($_GET['media_strict'])) {
142
-                $SearchString = '(' . implode(' | ', $MediaNameArray) . ')';
143
-            } else {
144
-                $SearchString = '(any | ' . implode(' | ', $MediaNameArray) . ')';
145
-            }
146
-            $SphQL->where_match($SearchString, 'medialist', false);
147
-        }
148
-    }
149
-}
150
-
151
-if (!empty($_GET['bitrates'])) {
152
-    $BitrateArray = $_GET['bitrates'];
153
-    if (count($BitrateArray) !== count($Bitrates)) {
154
-        $BitrateNameArray = [];
155
-        foreach ($BitrateArray as $Index => $MasterIndex) {
156
-            if (isset($Bitrates[$MasterIndex])) {
157
-                $BitrateNameArray[$Index] = '"' . strtr(Sphinxql::sph_escape_string($Bitrates[$MasterIndex]), '-.', '  ') . '"';
158
-            }
159
-        }
160
-
161
-        if (count($BitrateNameArray) >= 1) {
162
-            if (!empty($_GET['bitrate_strict'])) {
163
-                $SearchString = '(' . implode(' | ', $BitrateNameArray) . ')';
164
-            } else {
165
-                $SearchString = '(any | ' . implode(' | ', $BitrateNameArray) . ')';
166
-            }
167
-            $SphQL->where_match($SearchString, 'bitratelist', false);
168
-        }
169
-    }
170
-}
171
-
172
-if (!empty($_GET['search'])) {
173
-    $SearchString = trim($_GET['search']);
174
-    if ($SearchString !== '') {
175
-        $SearchWords = array('include' => [], 'exclude' => []);
176
-        $Words = explode(' ', $SearchString);
177
-        foreach ($Words as $Word) {
178
-            $Word = trim($Word);
179
-            // Skip isolated hyphens to enable "Artist - Title" searches
180
-            if ($Word === '-') {
181
-                continue;
182
-            }
183
-            if ($Word[0] === '!' && strlen($Word) >= 2) {
184
-                if (strpos($Word, '!', 1) === false) {
185
-                    $SearchWords['exclude'][] = $Word;
186
-                } else {
187
-                    $SearchWords['include'][] = $Word;
188
-                }
189
-            } elseif ($Word !== '') {
190
-                $SearchWords['include'][] = $Word;
191
-            }
192
-        }
193
-    }
194
-}
195
-
196
-if (!isset($_GET['tags_type']) || $_GET['tags_type'] === '1') {
197
-    $TagType = 1;
198
-    $_GET['tags_type'] = '1';
199
-} else {
200
-    $TagType = 0;
201
-    $_GET['tags_type'] = '0';
202
-}
203
-if (!empty($_GET['tags'])) {
204
-    $SearchTags = array('include' => [], 'exclude' => []);
205
-    $Tags = explode(',', $_GET['tags']);
206
-    foreach ($Tags as $Tag) {
207
-        $Tag = trim($Tag);
208
-        if ($Tag[0] === '!' && strlen($Tag) >= 2) {
209
-            if (strpos($Tag, '!', 1) === false) {
210
-                $SearchTags['exclude'][] = $Tag;
211
-            } else {
212
-                $SearchTags['include'][] = $Tag;
213
-            }
214
-        } elseif ($Tag !== '') {
215
-            $SearchTags['include'][] = $Tag;
216
-        }
217
-    }
218
-
219
-    $TagFilter = Tags::tag_filter_sph($SearchTags, $TagType);
220
-
221
-    if (!empty($TagFilter['predicate'])) {
222
-        $SphQL->where_match($TagFilter['predicate'], 'taglist', false);
223
-    }
224
-} elseif (!isset($_GET['tags_type']) || $_GET['tags_type'] !== '0') {
225
-    $_GET['tags_type'] = 1;
226
-} else {
227
-    $_GET['tags_type'] = 0;
228
-}
229
-
230
-if (isset($SearchWords)) {
231
-    $QueryParts = [];
232
-    foreach ($SearchWords['include'] as $Word) {
233
-        $QueryParts[] = Sphinxql::sph_escape_string($Word);
234
-    }
235
-    if (!empty($SearchWords['exclude'])) {
236
-        foreach ($SearchWords['exclude'] as $Word) {
237
-            $QueryParts[] = '!' . Sphinxql::sph_escape_string(substr($Word, 1));
238
-        }
239
-    }
240
-    if (!empty($QueryParts)) {
241
-        $SearchString = implode(' ', $QueryParts);
242
-        $SphQL->where_match($SearchString, '*', false);
243
-    }
244
-}
245
-
246
-if (!empty($_GET['filter_cat'])) {
247
-    $CategoryArray = array_keys($_GET['filter_cat']);
248
-    if (count($CategoryArray) !== count($Categories)) {
249
-        foreach ($CategoryArray as $Key => $Index) {
250
-            if (!isset($Categories[$Index - 1])) {
251
-                unset($CategoryArray[$Key]);
252
-            }
253
-        }
254
-        if (count($CategoryArray) >= 1) {
255
-            $SphQL->where('categoryid', $CategoryArray);
256
-        }
257
-    }
258
-}
259
-
260
-if (!empty($_GET['releases'])) {
261
-    $ReleaseArray = $_GET['releases'];
262
-    if (count($ReleaseArray) !== count($ReleaseTypes)) {
263
-        foreach ($ReleaseArray as $Index => $Value) {
264
-            if (!isset($ReleaseTypes[$Value])) {
265
-                unset($ReleaseArray[$Index]);
266
-            }
267
-        }
268
-        if (count($ReleaseArray) >= 1) {
269
-            $SphQL->where('releasetype', $ReleaseArray);
270
-        }
271
-    }
272
-}
273
-
274
-if (!empty($_GET['requestor'])) {
275
-    if (is_number($_GET['requestor'])) {
276
-        $SphQL->where('userid', $_GET['requestor']);
277
-    } else {
278
-        error(404);
279
-    }
280
-}
281
-
282
-if (isset($_GET['year'])) {
283
-    if (is_number($_GET['year']) || $_GET['year'] === '0') {
284
-        $SphQL->where('year', $_GET['year']);
285
-    } else {
286
-        error(404);
287
-    }
288
-}
289
-
290
-if (!empty($_GET['page']) && is_number($_GET['page']) && $_GET['page'] > 0) {
291
-    $Page = $_GET['page'];
292
-    $Offset = ($Page - 1) * REQUESTS_PER_PAGE;
293
-    $SphQL->limit($Offset, REQUESTS_PER_PAGE, $Offset + REQUESTS_PER_PAGE);
294
-} else {
295
-    $Page = 1;
296
-    $SphQL->limit(0, REQUESTS_PER_PAGE, REQUESTS_PER_PAGE);
297
-}
298
-
299
-$SphQLResult = $SphQL->query();
300
-$NumResults = (int)$SphQLResult->get_meta('total_found');
301
-if ($NumResults > 0) {
302
-    $SphRequests = $SphQLResult->to_array('id');
303
-    if ($OrderBy === 'random') {
304
-        $NumResults = count($RequestIDs);
305
-    }
306
-    if ($NumResults > REQUESTS_PER_PAGE) {
307
-        if (($Page - 1) * REQUESTS_PER_PAGE > $NumResults) {
308
-            $Page = 0;
309
-        }
310
-    }
311
-}
312
-
313
-if ($NumResults == 0) {
314
-    json_die("success", array(
315
-    'currentPage' => 1,
316
-    'pages'       => 1,
317
-    'results'     => []
318
-  ));
319
-} else {
320
-    $JsonResults = [];
321
-    $Requests = Requests::get_requests(array_keys($SphRequests));
322
-    foreach ($SphRequests as $RequestID => $SphRequest) {
323
-        $Request = $Requests[$RequestID];
324
-        $VoteCount = $SphRequest['votes'];
325
-        $Bounty = $SphRequest['bounty'] * 1024; // Sphinx stores bounty in kB
326
-        $Requestor = Users::user_info($Request['UserID']);
327
-        $Filler = $Request['FillerID'] ? Users::user_info($Request['FillerID']) : null;
328
-
329
-        if ($Request['CategoryID'] == 0) {
330
-            $CategoryName = 'Unknown';
331
-        } else {
332
-            $CategoryName = $Categories[$Request['CategoryID'] - 1];
333
-        }
334
-
335
-        $JsonArtists = Requests::get_artists($RequestID);
336
-
337
-        $Tags = $Request['Tags'];
338
-
339
-        $JsonResults[] = array(
340
-      'requestId'     => (int)$RequestID,
341
-      'requestorId'   => (int)$Requestor['ID'],
342
-      'requestorName' => $Requestor['Username'],
343
-      'timeAdded'     => $Request['TimeAdded'],
344
-      'lastVote'      => $Request['LastVote'],
345
-      'voteCount'     => (int)$VoteCount,
346
-      'bounty'        => (int)$Bounty,
347
-      'categoryId'    => (int)$Request['CategoryID'],
348
-      'categoryName'  => $CategoryName,
349
-      'authors'       => $JsonArtists,
350
-      #'artists'       => $JsonArtists,
351
-      'title'         => $Request['Title'],
352
-      'year'          => (int)$Request['Year'],
353
-      'picture'         => $Request['Image'],
354
-      #'image'         => $Request['Image'],
355
-      'description'   => $Request['Description'],
356
-      'isFilled'      => ($Request['TorrentID'] > 0),
357
-      'fillerId'      => (int)$Request['FillerID'],
358
-      'fillerName'    => $Filler ? $Filler['Username'] : '',
359
-      'torrentId'     => (int)$Request['TorrentID'],
360
-      'timeFilled'    => $Request['TimeFilled'] == 0 ? '' : $Request['TimeFilled']
361
-    );
362
-    }
363
-
364
-    json_die("success", array(
365
-    'currentPage' => intval($Page),
366
-    'pages'       => ceil($NumResults / REQUESTS_PER_PAGE),
367
-    'results'     => $JsonResults
368
-  ));
369
-}

+ 0
- 90
sections/ajax/send_recommendation.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-$FriendID = (int) $_POST['friend'];
5
-$Type = $_POST['type'];
6
-$ID = (int) $_POST['id'];
7
-$Note = $_POST['note'];
8
-
9
-if (empty($FriendID) || empty($Type) || empty($ID)) {
10
-    echo json_encode(array('status' => 'error', 'response' => 'Error.'));
11
-    error();
12
-}
13
-
14
-// Make sure the recipient is on your friends list and not some random dude.
15
-$DB->query("
16
-SELECT
17
-  f.`FriendID`,
18
-  u.`Username`
19
-FROM
20
-  `friends` AS f
21
-RIGHT JOIN `users_enable_recommendations` AS r
22
-ON
23
-  r.`ID` = f.`FriendID` AND r.`Enable` = 1
24
-RIGHT JOIN `users_main` AS u
25
-ON
26
-  u.`ID` = f.`FriendID`
27
-WHERE
28
-  f.`UserID` = '$LoggedUser[ID]' AND f.`FriendID` = '$FriendID'
29
-");
30
-
31
-if (!$DB->has_results()) {
32
-    echo json_encode(array('status' => 'error', 'response' => 'Not on friend list.'));
33
-    error();
34
-}
35
-
36
-$Type = strtolower($Type);
37
-$Link = '';
38
-// "a" vs "an", english language is so confusing.
39
-// https://en.wikipedia.org/wiki/English_articles#Distinction_between_a_and_an
40
-$Article = 'a';
41
-switch ($Type) {
42
-    case 'torrent':
43
-    $Link = "torrents.php?id=$ID";
44
-    $DB->query("
45
-    SELECT
46
-      `title`
47
-    FROM
48
-      `torrents_group`
49
-    WHERE
50
-      `id` = '$ID'
51
-    ");
52
-      break;
53
-
54
-    case 'artist':
55
-    $Article = 'an';
56
-    $Link = "artist.php?id=$ID";
57
-    $DB->query("
58
-    SELECT
59
-      `Name`
60
-    FROM
61
-      `artists_group`
62
-    WHERE
63
-      `ArtistID` = '$ID'
64
-    ");
65
-    break;
66
-
67
-    case 'collage':
68
-    $Link = "collages.php?id=$ID";
69
-    $DB->query("
70
-    SELECT
71
-      `Name`
72
-    FROM
73
-      `collages`
74
-    WHERE
75
-      `ID` = '$ID'
76
-    ");
77
-    break;
78
-}
79
-
80
-list($Name) = $DB->next_record();
81
-$Subject = $LoggedUser['Username'] . " recommended you $Article $Type!";
82
-$Body = $LoggedUser['Username'] . " recommended you the $Type [url=".site_url()."$Link]$Name".'[/url].';
83
-
84
-if (!empty($Note)) {
85
-    $Body = "$Body\n\n$Note";
86
-}
87
-
88
-Misc::send_pm($FriendID, $LoggedUser['ID'], $Subject, $Body);
89
-echo json_encode(array('status' => 'success', 'response' => 'Sent!'));
90
-die();

+ 0
- 165
sections/ajax/stats.php View File

1
-<?php
2
-declare(strict_types=1);
3
-
4
-// Begin user stats
5
-if (($UserCount = $Cache->get_value('stats_user_count')) === false) {
6
-    $DB->query("
7
-    SELECT
8
-      COUNT(`ID`)
9
-    FROM
10
-      `users_main`
11
-    WHERE
12
-      `Enabled` = '1'
13
-    ");
14
-    list($UserCount) = $DB->next_record();
15
-    $Cache->cache_value('stats_user_count', $UserCount, 0); // inf cache
16
-}
17
-
18
-if (($UserStats = $Cache->get_value('stats_users')) === false) {
19
-    $DB->query("
20
-    SELECT
21
-      COUNT(`ID`)
22
-    FROM
23
-      `users_main`
24
-    WHERE
25
-      `Enabled` = '1'
26
-    AND `LastAccess` > '".time_minus(3600 * 24)."'
27
-    ");
28
-    list($UserStats['Day']) = $DB->next_record();
29
-
30
-    $DB->query("
31
-    SELECT
32
-      COUNT(`ID`)
33
-    FROM
34
-      `users_main`
35
-    WHERE
36
-      `Enabled` = '1'
37
-    AND `LastAccess` > '".time_minus(3600 * 24 * 7)."'
38
-    ");
39
-    list($UserStats['Week']) = $DB->next_record();
40
-
41
-    $DB->query("
42
-    SELECT
43
-      COUNT(`ID`)
44
-    FROM
45
-      `users_main`
46
-    WHERE
47
-      `Enabled` = '1'
48
-    AND LastAccess > '".time_minus(3600 * 24 * 30)."'
49
-    ");
50
-    list($UserStats['Month']) = $DB->next_record();
51
-
52
-    $Cache->cache_value('stats_users', $UserStats, 0);
53
-}
54
-
55
-// Begin torrent stats
56
-if (($TorrentCount = $Cache->get_value('stats_torrent_count')) === false) {
57
-    $DB->query("
58
-    SELECT
59
-      COUNT(`ID`)
60
-    FROM
61
-      `torrents`
62
-    ");
63
-    list($TorrentCount) = $DB->next_record();
64
-    $Cache->cache_value('stats_torrent_count', $TorrentCount, 604800); // staggered 1 week cache
65
-}
66
-
67
-if (($AlbumCount = $Cache->get_value('stats_album_count')) === false) {
68
-    $DB->query("
69
-    SELECT
70
-      COUNT(`id`)
71
-    FROM
72
-      `torrents_group`
73
-    WHERE
74
-      `category_id` = '1'
75
-    ");
76
-
77
-    list($AlbumCount) = $DB->next_record();
78
-    $Cache->cache_value('stats_album_count', $AlbumCount, 604830); // staggered 1 week cache
79
-}
80
-
81
-if (($ArtistCount = $Cache->get_value('stats_artist_count')) === false) {
82
-    $DB->query("
83
-    SELECT
84
-      COUNT(`ArtistID`)
85
-    FROM
86
-      `artists_group`
87
-    ");
88
-    
89
-    list($ArtistCount) = $DB->next_record();
90
-    $Cache->cache_value('stats_artist_count', $ArtistCount, 604860); // staggered 1 week cache
91
-}
92
-
93
-// Begin request stats
94
-if (($RequestStats = $Cache->get_value('stats_requests')) === false) {
95
-    $DB->query("
96
-    SELECT
97
-      COUNT(`ID`)
98
-    FROM
99
-      `requests`
100
-    ");
101
-    list($RequestCount) = $DB->next_record();
102
-
103
-    $DB->query("
104
-    SELECT
105
-      COUNT(`ID`)
106
-    FROM
107
-      `requests`
108
-    WHERE
109
-      `FillerID` > 0
110
-    ");
111
-    list($FilledCount) = $DB->next_record();
112
-    $Cache->cache_value('stats_requests', array($RequestCount, $FilledCount), 11280);
113
-} else {
114
-    list($RequestCount, $FilledCount) = $RequestStats;
115
-}
116
-
117
-// Begin swarm stats
118
-if (($PeerStats = $Cache->get_value('stats_peers')) === false) {
119
-    // Cache lock!
120
-    if ($Cache->get_query_lock('peer_stats')) {
121
-        $DB->query("
122
-        SELECT
123
-        IF(
124
-          `remaining` = 0,
125
-          'Seeding',
126
-          'Leeching'
127
-        ) AS `Type`,
128
-        COUNT(`uid`)
129
-        FROM
130
-          `xbt_files_users`
131
-        WHERE
132
-          `active` = 1
133
-        GROUP BY
134
-          `Type`
135
-        ");
136
-
137
-        $PeerCount = $DB->to_array(0, MYSQLI_NUM, false);
138
-        $LeecherCount = isset($PeerCount['Leeching']) ? $PeerCount['Leeching'][1] : 0;
139
-        $SeederCount = isset($PeerCount['Seeding']) ? $PeerCount['Seeding'][1] : 0;
140
-        $Cache->cache_value('stats_peers', array($LeecherCount, $SeederCount), 1209600); // 2 week cache
141
-        $Cache->clear_query_lock('peer_stats');
142
-    } else {
143
-        $LeecherCount = $SeederCount = 0;
144
-    }
145
-} else {
146
-    list($LeecherCount, $SeederCount) = $PeerStats;
147
-}
148
-
149
-json_print('success', array(
150
-  'maxUsers' => USER_LIMIT,
151
-  'enabledUsers' => (int) $UserCount,
152
-  'usersActiveThisDay' => (int) $UserStats['Day'],
153
-  'usersActiveThisWeek' => (int) $UserStats['Week'],
154
-  'usersActiveThisMonth' => (int) $UserStats['Month'],
155
-
156
-  'torrentCount' => (int) $TorrentCount,
157
-  'groupCount' => (int) $AlbumCount,
158
-  'artistCount' => (int) $ArtistCount,
159
-
160
-  'requestCount' => (int) $RequestCount,
161
-  'filledRequestCount' => (int) $FilledCount,
162
-
163
-  'seederCount' => (int) $SeederCount,
164
-  'leecherCount' => (int) $LeecherCount
165
-));

+ 0
- 92
sections/ajax/subscriptions.php View File

1
-<?php
2
-/*
3
-User topic subscription page
4
-*/
5
-
6
-if (!empty($LoggedUser['DisableForums'])) {
7
-  json_die('failure');
8
-}
9
-
10
-if (isset($LoggedUser['PostsPerPage'])) {
11
-  $PerPage = $LoggedUser['PostsPerPage'];
12
-} else {
13
-  $PerPage = POSTS_PER_PAGE;
14
-}
15
-list($Page, $Limit) = Format::page_limit($PerPage);
16
-
17
-$ShowUnread = (!isset($_GET['showunread']) && !isset($HeavyInfo['SubscriptionsUnread']) || isset($HeavyInfo['SubscriptionsUnread']) && !!$HeavyInfo['SubscriptionsUnread'] || isset($_GET['showunread']) && !!$_GET['showunread']);
18
-$ShowCollapsed = (!isset($_GET['collapse']) && !isset($HeavyInfo['SubscriptionsCollapse']) || isset($HeavyInfo['SubscriptionsCollapse']) && !!$HeavyInfo['SubscriptionsCollapse'] || isset($_GET['collapse']) && !!$_GET['collapse']);
19
-$sql = '
20
-  SELECT
21
-    SQL_CALC_FOUND_ROWS
22
-    MAX(p.ID) AS ID
23
-  FROM forums_posts AS p
24
-    LEFT JOIN forums_topics AS t ON t.ID = p.TopicID
25
-    JOIN users_subscriptions AS s ON s.TopicID = t.ID
26
-    LEFT JOIN forums AS f ON f.ID = t.ForumID
27
-    LEFT JOIN forums_last_read_topics AS l ON p.TopicID = l.TopicID AND l.UserID = s.UserID
28
-  WHERE s.UserID = '.$LoggedUser['ID'].'
29
-    AND p.ID <= IFNULL(l.PostID, t.LastPostID)
30
-    AND ' . Forums::user_forums_sql();
31
-if ($ShowUnread) {
32
-  $sql .= '
33
-    AND IF(l.PostID IS NULL OR (t.IsLocked = \'1\' && t.IsSticky = \'0\'), t.LastPostID, l.PostID) < t.LastPostID';
34
-}
35
-$sql .= "
36
-  GROUP BY t.ID
37
-  ORDER BY t.LastPostID DESC
38
-  LIMIT $Limit";
39
-$PostIDs = $DB->query($sql);
40
-$DB->query('SELECT FOUND_ROWS()');
41
-list($NumResults) = $DB->next_record();
42
-
43
-if ($NumResults > $PerPage * ($Page - 1)) {
44
-  $DB->set_query_id($PostIDs);
45
-  $PostIDs = $DB->collect('ID');
46
-  $sql = '
47
-    SELECT
48
-      f.ID AS ForumID,
49
-      f.Name AS ForumName,
50
-      p.TopicID,
51
-      t.Title,
52
-      p.Body,
53
-      t.LastPostID,
54
-      t.IsLocked,
55
-      t.IsSticky,
56
-      p.ID,
57
-      um.ID,
58
-      um.Username,
59
-      ui.Avatar,
60
-      p.EditedUserID,
61
-      p.EditedTime,
62
-      ed.Username AS EditedUsername
63
-    FROM forums_posts AS p
64
-      LEFT JOIN forums_topics AS t ON t.ID = p.TopicID
65
-      LEFT JOIN forums AS f ON f.ID = t.ForumID
66
-      LEFT JOIN users_main AS um ON um.ID = p.AuthorID
67
-      LEFT JOIN users_info AS ui ON ui.UserID = um.ID
68
-      LEFT JOIN users_main AS ed ON ed.ID = um.ID
69
-    WHERE p.ID IN ('.implode(',', $PostIDs).')
70
-    ORDER BY f.Name ASC, t.LastPostID DESC';
71
-  $DB->query($sql);
72
-}
73
-
74
-$JsonPosts = [];
75
-while (list($ForumID, $ForumName, $TopicID, $ThreadTitle, $Body, $LastPostID, $Locked, $Sticky, $PostID, $AuthorID, $AuthorName, $AuthorAvatar, $EditedUserID, $EditedTime, $EditedUsername) = $DB->next_record()) {
76
-  $JsonPost = array(
77
-    'forumId' => (int)$ForumID,
78
-    'forumName' => $ForumName,
79
-    'threadId' => (int)$TopicID,
80
-    'threadTitle' => $ThreadTitle,
81
-    'postId' => (int)$PostID,
82
-    'lastPostId' => (int)$LastPostID,
83
-    'locked' => $Locked == 1,
84
-    'new' => ($PostID < $LastPostID && !$Locked)
85
-  );
86
-  $JsonPosts[] = $JsonPost;
87
-}
88
-
89
-json_die('success', array(
90
-  'threads' => $JsonPosts
91
-));
92
-?>

+ 0
- 42
sections/ajax/tcomments.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (empty($_GET['id']) || !is_number($_GET['id'])) {
5
-    json_die('failure');
6
-}
7
-
8
-list($NumComments, $Page, $Thread) = Comments::load('torrents', (int)$_GET['id'], false);
9
-
10
-# Begin printing
11
-$JsonComments = [];
12
-foreach ($Thread as $Key => $Post) {
13
-    list($PostID, $AuthorID, $AddedTime, $Body, $EditedUserID, $EditedTime, $EditedUsername) = array_values($Post);
14
-    list($AuthorID, $Username, $PermissionID, $Paranoia, $Artist, $Donor, $Warned, $Avatar, $Enabled, $UserTitle) = array_values(Users::user_info($AuthorID));
15
-
16
-    $JsonComments[] = [
17
-      'postId' => (int) $PostID,
18
-      'addedTime' => $AddedTime,
19
-      'bbBody' => $Body,
20
-      'body' => Text::full_format($Body),
21
-      'editedUserId' => (int) $EditedUserID,
22
-      'editedTime' => $EditedTime,
23
-      'editedUsername' => $EditedUsername,
24
-
25
-      'userinfo' => [
26
-        'authorId' => (int) $AuthorID,
27
-        'authorName' => $Username,
28
-        'artist' => $Artist === 1,
29
-        'donor' => $Donor === 1,
30
-        'warned' => (bool) $Warned,
31
-        'avatar' => $Avatar,
32
-        'enabled' => ($Enabled === 2 ? false : true),
33
-        'userTitle' => $UserTitle
34
-      ]
35
-    ];
36
-}
37
-
38
-json_die('success', [
39
-  'page' => (int) $Page,
40
-  'pages' => ceil($NumComments / TORRENT_COMMENTS_PER_PAGE),
41
-  'comments' => $JsonComments
42
-]);

+ 0
- 32
sections/ajax/top10/index.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-// Already done in /sections/ajax/index.php
5
-//enforce_login();
6
-
7
-if (!check_perms('site_top10')) {
8
-    echo json_encode(array('status' => 'failure'));
9
-    error();
10
-}
11
-
12
-if (empty($_GET['type']) || $_GET['type'] === 'torrents') {
13
-    include SERVER_ROOT.'/sections/ajax/top10/torrents.php';
14
-} else {
15
-    switch ($_GET['type']) {
16
-    case 'users':
17
-      include SERVER_ROOT.'/sections/ajax/top10/users.php';
18
-      break;
19
-
20
-    case 'tags':
21
-      include SERVER_ROOT.'/sections/ajax/top10/tags.php';
22
-      break;
23
-
24
-    case 'history':
25
-      include SERVER_ROOT.'/sections/ajax/top10/history.php';
26
-      break;
27
-
28
-    default:
29
-      echo json_encode(array('status' => 'failure'));
30
-      break;
31
-  }
32
-}

+ 0
- 83
sections/ajax/top10/tags.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-
6
-// Error out on invalid requests (before caching)
7
-if (isset($_GET['details'])) {
8
-    if (in_array($_GET['details'], ['ut','ur'])) {
9
-        $Details = $_GET['details'];
10
-    } else {
11
-        echo json_encode(['status' => 'failure']);
12
-        error();
13
-    }
14
-} else {
15
-    $Details = 'all';
16
-}
17
-
18
-// Defaults to 10 (duh)
19
-$Limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
20
-$Limit = in_array($Limit, [10, 100, 250]) ? $Limit : 10;
21
-$OuterResults = [];
22
-
23
-if ($Details == 'all' || $Details == 'ut') {
24
-    if (!$TopUsedTags = $Cache->get_value("topusedtag_$Limit")) {
25
-        $DB->query("
26
-      SELECT
27
-        t.ID,
28
-        t.Name,
29
-        COUNT(tt.GroupID) AS Uses
30
-      FROM tags AS t
31
-        JOIN torrents_tags AS tt ON tt.TagID = t.ID
32
-      GROUP BY tt.TagID
33
-      ORDER BY Uses DESC
34
-      LIMIT $Limit");
35
-        $TopUsedTags = $DB->to_array();
36
-        $Cache->cache_value("topusedtag_$Limit", $TopUsedTags, 3600 * 12);
37
-    }
38
-
39
-    $OuterResults[] = generate_tag_json('Most Used Torrent Tags', 'ut', $TopUsedTags, $Limit);
40
-}
41
-
42
-if ($Details == 'all' || $Details == 'ur') {
43
-    if (!$TopRequestTags = $Cache->get_value("toprequesttag_$Limit")) {
44
-        $DB->query("
45
-      SELECT
46
-        t.ID,
47
-        t.Name,
48
-        COUNT(r.RequestID) AS Uses,
49
-        '',''
50
-      FROM tags AS t
51
-        JOIN requests_tags AS r ON r.TagID = t.ID
52
-      GROUP BY r.TagID
53
-      ORDER BY Uses DESC
54
-      LIMIT $Limit");
55
-        $TopRequestTags = $DB->to_array();
56
-        $Cache->cache_value("toprequesttag_$Limit", $TopRequestTags, 3600 * 12);
57
-    }
58
-
59
-    $OuterResults[] = generate_tag_json('Most Used Request Tags', 'ur', $TopRequestTags, $Limit);
60
-}
61
-
62
-echo json_encode([
63
-  'status' => 'success',
64
-  'response' => $OuterResults
65
-]);
66
-
67
-function generate_tag_json($Caption, $Tag, $Details, $Limit)
68
-{
69
-    $results = [];
70
-    foreach ($Details as $Detail) {
71
-        $results[] = [
72
-      'name' => $Detail['Name'],
73
-      'uses' => (int)$Detail['Uses']
74
-    ];
75
-    }
76
-
77
-    return [
78
-    'caption' => $Caption,
79
-    'tag' => $Tag,
80
-    'limit' => (int)$Limit,
81
-    'results' => $results
82
-  ];
83
-}

+ 0
- 185
sections/ajax/top10/torrents.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-if (isset($_GET['details'])) {
6
-    if (in_array($_GET['details'], array('day','week','overall','snatched','data','seeded'))) {
7
-        $Details = $_GET['details'];
8
-    } else {
9
-        echo json_encode(array('status' => 'failure'));
10
-        error();
11
-    }
12
-} else {
13
-    $Details = 'all';
14
-}
15
-
16
-// Defaults to 10 (duh)
17
-$Limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
18
-$Limit = in_array($Limit, array(10, 100, 250)) ? $Limit : 10;
19
-
20
-$WhereSum = (empty($Where)) ? '' : md5($Where);
21
-$BaseQuery = "
22
-SELECT
23
-  t.`ID`,
24
-  g.`id`,
25
-  g.`title`,
26
-  g.`category_id`,
27
-  g.`picture`,
28
-  g.`tag_list`,
29
-  t.`Media`,
30
-  g.`published`,
31
-  t.`Snatched`,
32
-  t.`Seeders`,
33
-  t.`Leechers`,
34
-  (
35
-    (t.`Size` * t.`Snatched`) +(t.`Size` * 0.5 * t.`Leechers`)
36
-  ) AS `Data`,
37
-  t.`Size`
38
-FROM
39
-  `torrents` AS t
40
-LEFT JOIN `torrents_group` AS g
41
-ON
42
-  g.`id` = t.`GroupID`
43
-";
44
-
45
-$OuterResults = [];
46
-
47
-if ($Details == 'all' || $Details == 'day') {
48
-    if (!$TopTorrentsActiveLastDay = $Cache->get_value('top10tor_day_'.$Limit.$WhereSum)) {
49
-        $DayAgo = time_minus(86400);
50
-        $Query = $BaseQuery.' WHERE t.Seeders>0 AND ';
51
-        if (!empty($Where)) {
52
-            $Query .= $Where.' AND ';
53
-        }
54
-        $Query .= "
55
-      t.Time>'$DayAgo'
56
-      ORDER BY (t.Seeders + t.Leechers) DESC
57
-      LIMIT $Limit;";
58
-        $DB->query($Query);
59
-        $TopTorrentsActiveLastDay = $DB->to_array(false, MYSQLI_NUM);
60
-        $Cache->cache_value('top10tor_day_'.$Limit.$WhereSum, $TopTorrentsActiveLastDay, 3600 * 2);
61
-    }
62
-    $OuterResults[] = generate_torrent_json('Most Active Torrents Uploaded in the Past Day', 'day', $TopTorrentsActiveLastDay, $Limit);
63
-}
64
-if ($Details == 'all' || $Details == 'week') {
65
-    if (!$TopTorrentsActiveLastWeek = $Cache->get_value('top10tor_week_'.$Limit.$WhereSum)) {
66
-        $WeekAgo = time_minus(604800);
67
-        $Query = $BaseQuery.' WHERE ';
68
-        if (!empty($Where)) {
69
-            $Query .= $Where.' AND ';
70
-        }
71
-        $Query .= "
72
-      t.Time>'$WeekAgo'
73
-      ORDER BY (t.Seeders + t.Leechers) DESC
74
-      LIMIT $Limit;";
75
-        $DB->query($Query);
76
-        $TopTorrentsActiveLastWeek = $DB->to_array(false, MYSQLI_NUM);
77
-        $Cache->cache_value('top10tor_week_'.$Limit.$WhereSum, $TopTorrentsActiveLastWeek, 3600*6);
78
-    }
79
-    $OuterResults[] = generate_torrent_json('Most Active Torrents Uploaded in the Past Week', 'week', $TopTorrentsActiveLastWeek, $Limit);
80
-}
81
-
82
-if ($Details == 'all' || $Details == 'overall') {
83
-    if (!$TopTorrentsActiveAllTime = $Cache->get_value("top10tor_overall_$Limit$WhereSum")) {
84
-        $Query = $BaseQuery;
85
-        if (!empty($Where)) {
86
-            $Query .= " WHERE $Where";
87
-        }
88
-        $Query .= "
89
-      ORDER BY (t.Seeders + t.Leechers) DESC
90
-      LIMIT $Limit;";
91
-        $DB->query($Query);
92
-        $TopTorrentsActiveAllTime = $DB->to_array(false, MYSQLI_NUM);
93
-        $Cache->cache_value("top10tor_overall_$Limit$WhereSum", $TopTorrentsActiveAllTime, 3600 * 6);
94
-    }
95
-    $OuterResults[] = generate_torrent_json('Most Active Torrents of All Time', 'overall', $TopTorrentsActiveAllTime, $Limit);
96
-}
97
-
98
-if (($Details == 'all' || $Details == 'snatched') && empty($Where)) {
99
-    if (!$TopTorrentsSnatched = $Cache->get_value("top10tor_snatched_$Limit$WhereSum")) {
100
-        $Query = $BaseQuery;
101
-        $Query .= "
102
-      ORDER BY t.Snatched DESC
103
-      LIMIT $Limit;";
104
-        $DB->query($Query);
105
-        $TopTorrentsSnatched = $DB->to_array(false, MYSQLI_NUM);
106
-        $Cache->cache_value("top10tor_snatched_$Limit$WhereSum", $TopTorrentsSnatched, 3600 * 6);
107
-    }
108
-    $OuterResults[] = generate_torrent_json('Most Snatched Torrents', 'snatched', $TopTorrentsSnatched, $Limit);
109
-}
110
-
111
-if (($Details == 'all' || $Details == 'data') && empty($Where)) {
112
-    if (!$TopTorrentsTransferred = $Cache->get_value("top10tor_data_$Limit$WhereSum")) {
113
-        $Query = $BaseQuery;
114
-        $Query .= "
115
-      ORDER BY Data DESC
116
-      LIMIT $Limit;";
117
-        $DB->query($Query);
118
-        $TopTorrentsTransferred = $DB->to_array(false, MYSQLI_NUM);
119
-        $Cache->cache_value("top10tor_data_$Limit$WhereSum", $TopTorrentsTransferred, 3600 * 6);
120
-    }
121
-    $OuterResults[] = generate_torrent_json('Most Data Transferred Torrents', 'data', $TopTorrentsTransferred, $Limit);
122
-}
123
-
124
-if (($Details == 'all' || $Details == 'seeded') && empty($Where)) {
125
-    if (!$TopTorrentsSeeded = $Cache->get_value("top10tor_seeded_$Limit$WhereSum")) {
126
-        $Query = $BaseQuery."
127
-      ORDER BY t.Seeders DESC
128
-      LIMIT $Limit;";
129
-        $DB->query($Query);
130
-        $TopTorrentsSeeded = $DB->to_array(false, MYSQLI_NUM);
131
-        $Cache->cache_value("top10tor_seeded_$Limit$WhereSum", $TopTorrentsSeeded, 3600 * 6);
132
-    }
133
-    $OuterResults[] = generate_torrent_json('Best Seeded Torrents', 'seeded', $TopTorrentsSeeded, $Limit);
134
-}
135
-
136
-json_print("success", $OuterResults);
137
-
138
-function generate_torrent_json($Caption, $Tag, $Details, $Limit)
139
-{
140
-    global $LoggedUser, $Categories;
141
-    $results = [];
142
-    foreach ($Details as $Detail) {
143
-        list($TorrentID, $GroupID, $GroupName, $GroupCategoryID, $WikiImage, $TorrentTags,
144
-      $Media, $GroupYear,
145
-      $Snatched, $Seeders, $Leechers, $Data, $Size) = $Detail;
146
-
147
-        # todo: Make JSON object if multiple artists
148
-        $Artist = Artists::display_artists(Artists::get_artist($GroupID), false, false);
149
-
150
-        $TagList = [];
151
-
152
-        if ($TorrentTags != '') {
153
-            $TorrentTags = explode(' ', $TorrentTags);
154
-            foreach ($TorrentTags as $TagKey => $TagName) {
155
-                $TagName = str_replace('_', '.', $TagName);
156
-                $TagList[] = $TagName;
157
-            }
158
-        }
159
-
160
-        // Append to the existing array
161
-        $results[] = array(
162
-          'torrentId'     => (int) $TorrentID,
163
-          'groupId'       => (int) $GroupID,
164
-          'author'        => $Artist, # todo
165
-          'groupName'     => $GroupName,
166
-          'groupCategory' => (int) $GroupCategoryID,
167
-          'groupYear'     => (int) $GroupYear,
168
-          'platform'      => $Media,
169
-          'tags'          => $TagList,
170
-          'snatched'      => (int) $Snatched,
171
-          'seeders'       => (int) $Seeders,
172
-          'leechers'      => (int) $Leechers,
173
-          'data'          => (int) $Data,
174
-          'size'          => (int) $Size,
175
-          'picture'       => $WikiImage,
176
-        );
177
-    }
178
-
179
-    return array(
180
-      'caption' => $Caption,
181
-      'tag'     => $Tag,
182
-      'limit'   => (int)$Limit,
183
-      'results' => $results
184
-    );
185
-}

+ 0
- 130
sections/ajax/top10/users.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-if (isset($_GET['details'])) {
6
-    if (in_array($_GET['details'], array('ul','dl','numul','uls','dls'))) {
7
-        $Details = $_GET['details'];
8
-    } else {
9
-        echo json_encode(array('status' => 'failure'));
10
-        error();
11
-    }
12
-} else {
13
-    $Details = 'all';
14
-}
15
-
16
-// Defaults to 10 (duh)
17
-$Limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
18
-$Limit = in_array($Limit, array(10,100,250)) ? $Limit : 10;
19
-
20
-$BaseQuery = "
21
-  SELECT
22
-    u.ID,
23
-    u.Username,
24
-    ui.JoinDate,
25
-    u.Uploaded,
26
-    u.Downloaded,
27
-    ABS(u.Uploaded-524288000) / (".time()." - UNIX_TIMESTAMP(ui.JoinDate)) AS UpSpeed,
28
-    u.Downloaded / (".time()." - UNIX_TIMESTAMP(ui.JoinDate)) AS DownSpeed,
29
-    COUNT(t.ID) AS NumUploads
30
-  FROM users_main AS u
31
-    JOIN users_info AS ui ON ui.UserID = u.ID
32
-    LEFT JOIN torrents AS t ON t.UserID = u.ID
33
-  WHERE u.Enabled = '1'
34
-    AND Uploaded > '". 5 * 1024 * 1024 * 1024 ."'
35
-    AND Downloaded > '". 5 * 1024 * 1024 * 1024 ."'
36
-    AND (Paranoia IS NULL OR (Paranoia NOT LIKE '%\"uploaded\"%' AND Paranoia NOT LIKE '%\"downloaded\"%'))
37
-  GROUP BY u.ID";
38
-
39
-$OuterResults = [];
40
-
41
-if ($Details == 'all' || $Details == 'ul') {
42
-    if (!$TopUserUploads = $Cache->get_value("topuser_ul_$Limit")) {
43
-        $DB->query("
44
-      $BaseQuery
45
-      ORDER BY u.Uploaded DESC
46
-      LIMIT $Limit;");
47
-        $TopUserUploads = $DB->to_array();
48
-        $Cache->cache_value("topuser_ul_$Limit", $TopUserUploads, 3600 * 12);
49
-    }
50
-    $OuterResults[] = generate_user_json('Uploaders', 'ul', $TopUserUploads, $Limit);
51
-}
52
-
53
-if ($Details == 'all' || $Details == 'dl') {
54
-    if (!$TopUserDownloads = $Cache->get_value("topuser_dl_$Limit")) {
55
-        $DB->query("
56
-      $BaseQuery
57
-      ORDER BY u.Downloaded DESC
58
-      LIMIT $Limit;");
59
-        $TopUserDownloads = $DB->to_array();
60
-        $Cache->cache_value("topuser_dl_$Limit", $TopUserDownloads, 3600 * 12);
61
-    }
62
-    $OuterResults[] = generate_user_json('Downloaders', 'dl', $TopUserDownloads, $Limit);
63
-}
64
-
65
-if ($Details == 'all' || $Details == 'numul') {
66
-    if (!$TopUserNumUploads = $Cache->get_value("topuser_numul_$Limit")) {
67
-        $DB->query("
68
-      $BaseQuery
69
-      ORDER BY NumUploads DESC
70
-      LIMIT $Limit;");
71
-        $TopUserNumUploads = $DB->to_array();
72
-        $Cache->cache_value("topuser_numul_$Limit", $TopUserNumUploads, 3600 * 12);
73
-    }
74
-    $OuterResults[] = generate_user_json('Torrents Uploaded', 'numul', $TopUserNumUploads, $Limit);
75
-}
76
-
77
-if ($Details == 'all' || $Details == 'uls') {
78
-    if (!$TopUserUploadSpeed = $Cache->get_value("topuser_ulspeed_$Limit")) {
79
-        $DB->query("
80
-      $BaseQuery
81
-      ORDER BY UpSpeed DESC
82
-      LIMIT $Limit;");
83
-        $TopUserUploadSpeed = $DB->to_array();
84
-        $Cache->cache_value("topuser_ulspeed_$Limit", $TopUserUploadSpeed, 3600 * 12);
85
-    }
86
-    $OuterResults[] = generate_user_json('Fastest Uploaders', 'uls', $TopUserUploadSpeed, $Limit);
87
-}
88
-
89
-if ($Details == 'all' || $Details == 'dls') {
90
-    if (!$TopUserDownloadSpeed = $Cache->get_value("topuser_dlspeed_$Limit")) {
91
-        $DB->query("
92
-      $BaseQuery
93
-      ORDER BY DownSpeed DESC
94
-      LIMIT $Limit;");
95
-        $TopUserDownloadSpeed = $DB->to_array();
96
-        $Cache->cache_value("topuser_dlspeed_$Limit", $TopUserDownloadSpeed, 3600 * 12);
97
-    }
98
-    $OuterResults[] = generate_user_json('Fastest Downloaders', 'dls', $TopUserDownloadSpeed, $Limit);
99
-}
100
-
101
-print
102
-  json_encode(
103
-      array(
104
-      'status' => 'success',
105
-      'response' => $OuterResults
106
-    )
107
-  );
108
-
109
-function generate_user_json($Caption, $Tag, $Details, $Limit)
110
-{
111
-    $results = [];
112
-    foreach ($Details as $Detail) {
113
-        $results[] = array(
114
-      'id' => (int)$Detail['ID'],
115
-      'username' => $Detail['Username'],
116
-      'uploaded' => (float)$Detail['Uploaded'],
117
-      'upSpeed' => (float)$Detail['UpSpeed'],
118
-      'downloaded' => (float)$Detail['Downloaded'],
119
-      'downSpeed' => (float)$Detail['DownSpeed'],
120
-      'numUploads' => (int)$Detail['NumUploads'],
121
-      'joinDate' => $Detail['JoinDate']
122
-    );
123
-    }
124
-    return array(
125
-    'caption' => $Caption,
126
-    'tag' => $Tag,
127
-    'limit' => (int)$Limit,
128
-    'results' => $results
129
-    );
130
-}

+ 0
- 105
sections/ajax/torrent.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-require_once SERVER_ROOT.'/sections/torrents/functions.php';
5
-
6
-$TorrentID = (int) $_GET['id'];
7
-$TorrentHash = (string) $_GET['hash'];
8
-
9
-if ($TorrentID && $TorrentHash) {
10
-    json_die('failure', 'bad parameters');
11
-}
12
-
13
-if ($TorrentHash) {
14
-    if (!is_valid_torrenthash($TorrentHash)) {
15
-        json_die('failure', 'bad hash parameter');
16
-    } else {
17
-        $TorrentID = (int) torrenthash_to_torrentid($TorrentHash);
18
-        if (!$TorrentID) {
19
-            json_die('failure', 'bad hash parameter');
20
-        }
21
-    }
22
-}
23
-
24
-if ($TorrentID <= 0) {
25
-    json_die('failure', 'bad id parameter');
26
-}
27
-
28
-$TorrentCache = get_torrent_info($TorrentID, true, 0, true, true);
29
-if (!$TorrentCache) {
30
-    json_die('failure', 'bad id parameter');
31
-}
32
-
33
-list($TorrentDetails, $TorrentList) = $TorrentCache;
34
-if (!isset($TorrentList[$TorrentID])) {
35
-    json_die('failure', 'bad id parameter');
36
-}
37
-
38
-$GroupID = $TorrentDetails['ID'];
39
-$Artists = Artists::get_artist($GroupID);
40
-
41
-if ($TorrentDetails['CategoryID'] === 0) {
42
-    $CategoryName = 'Unknown';
43
-} else {
44
-    $CategoryName = $Categories[$TorrentDetails['CategoryID'] - 1];
45
-}
46
-
47
-$TagList = explode('|', $TorrentDetails['GROUP_CONCAT(DISTINCT tags.Name SEPARATOR \'|\')']);
48
-
49
-$JsonTorrentDetails = [
50
-  'description'  => Text::full_format($TorrentDetails['WikiBody']),
51
-  'picture'      => $TorrentDetails['WikiImage'],
52
-  'id'           => (int) $TorrentDetails['ID'],
53
-  'name'         => $TorrentDetails['Name'],
54
-  'organism'     => $TorrentDetails['Title2'],
55
-  'strain'       => $TorrentDetails['NameJP'],
56
-  'authors'      => $Artists,
57
-  'year'         => (int) $TorrentDetails['Year'],
58
-  'accession'    => $TorrentDetails['CatalogueNumber'],
59
-  'categoryId'   => (int) $TorrentDetails['CategoryID'],
60
-  'categoryName' => $CategoryName,
61
-  'time'         => $TorrentDetails['Time'],
62
-  'isBookmarked' => Bookmarks::has_bookmarked('torrent', $GroupID),
63
-  'tags'         => $TagList
64
-];
65
-
66
-$Torrent = $TorrentList[$TorrentID];
67
-
68
-$Reports = Torrents::get_reports($TorrentID);
69
-$Torrent['Reported'] = (count($Reports) > 0);
70
-
71
-// Convert file list back to the old format
72
-$FileList = explode("\n", $Torrent['FileList']);
73
-foreach ($FileList as &$File) {
74
-    $File = Torrents::filelist_old_format($File);
75
-}
76
-
77
-unset($File);
78
-$FileList = implode('|||', $FileList);
79
-$Userinfo = Users::user_info($Torrent['UserID']);
80
-
81
-$JsonTorrentList[] = [
82
-  'id'          => (int) $Torrent['ID'],
83
-  'infoHash'    => $Torrent['InfoHash'],
84
-  'platform'    => $Torrent['Media'],
85
-  'format'      => $Torrent['Container'],
86
-  'license'     => $Torrent['Codec'],
87
-  'scope'       => $Torrent['Resolution'],
88
-  'annotated'   => (bool) $Torrent['Censored'],
89
-  'archive'     => $Torrent['Archive'],
90
-  'fileCount'   => (int) $Torrent['FileCount'],
91
-  'size'        => (int) $Torrent['Size'],
92
-  'seeders'     => (int) $Torrent['Seeders'],
93
-  'leechers'    => (int) $Torrent['Leechers'],
94
-  'snatched'    => (int) $Torrent['Snatched'],
95
-  'freeTorrent' => ($Torrent['FreeTorrent'] == 1),
96
-  'reported'    => (bool) $Torrent['Reported'],
97
-  'time'        => $Torrent['Time'],
98
-  'description' => $Torrent['Description'],
99
-  'fileList'    => $FileList,
100
-  'filePath'    => $Torrent['FilePath'],
101
-  'userId'      => (int) ($Torrent['Anonymous'] ? 0 : $Torrent['UserID']),
102
-  'username'    => ($Torrent['Anonymous'] ? 'Anonymous' : $Userinfo['Username'])
103
-];
104
-
105
-json_die('success', ['group' => $JsonTorrentDetails, 'torrent' => array_pop($JsonTorrentList)]);

+ 0
- 101
sections/ajax/torrentgroup.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-require_once SERVER_ROOT.'/sections/torrents/functions.php';
5
-
6
-$GroupID = (int) $_GET['id'];
7
-$TorrentHash = (string) $_GET['hash'];
8
-
9
-if ($GroupID && $TorrentHash) {
10
-    json_die('failure', 'bad parameters');
11
-}
12
-
13
-if ($TorrentHash) {
14
-    if (!is_valid_torrenthash($TorrentHash)) {
15
-        json_die('failure', 'bad hash parameter');
16
-    } else {
17
-        $GroupID = (int) torrenthash_to_groupid($TorrentHash);
18
-        if (!$GroupID) {
19
-            json_die('failure', 'bad hash parameter');
20
-        }
21
-    }
22
-}
23
-
24
-if ($GroupID <= 0) {
25
-    json_die('failure', 'bad id parameter');
26
-}
27
-
28
-$TorrentCache = get_group_info($GroupID, true, 0, true, true);
29
-if (!$TorrentCache) {
30
-    json_die('failure', 'bad id parameter');
31
-}
32
-
33
-list($TorrentDetails, $TorrentList) = $TorrentCache;
34
-$Artists = Artists::get_artist($GroupID);
35
-
36
-if ($TorrentDetails['CategoryID'] === 0) {
37
-    $CategoryName = 'Unknown';
38
-} else {
39
-    $CategoryName = $Categories[$TorrentDetails['CategoryID'] - 1];
40
-}
41
-
42
-$TagList = explode('|', $TorrentDetails['GROUP_CONCAT(DISTINCT tags.Name SEPARATOR \'|\')']);
43
-
44
-$JsonTorrentDetails = [
45
-  'description'  => Text::full_format($TorrentDetails['WikiBody']),
46
-  'picture'      => $TorrentDetails['WikiImage'],
47
-  'id'           => (int) $TorrentDetails['ID'],
48
-  'name'         => $TorrentDetails['Name'],
49
-  'organism'     => $TorrentDetails['Title2'],
50
-  'strain'       => $TorrentDetails['NameJP'],
51
-  'authors'      => $Artists,
52
-  'year'         => (int) $TorrentDetails['Year'],
53
-  'accession'    => $TorrentDetails['CatalogueNumber'],
54
-  'categoryId'   => (int) $TorrentDetails['CategoryID'],
55
-  'categoryName' => $CategoryName,
56
-  'time'         => $TorrentDetails['Time'],
57
-  'isBookmarked' => Bookmarks::has_bookmarked('torrent', $GroupID),
58
-  'tags'         => $TagList
59
-];
60
-
61
-$JsonTorrentList = [];
62
-foreach ($TorrentList as $Torrent) {
63
-    // Convert file list back to the old format
64
-    $FileList = explode("\n", $Torrent['FileList']);
65
-    foreach ($FileList as &$File) {
66
-        $File = Torrents::filelist_old_format($File);
67
-    }
68
-
69
-    unset($File);
70
-    $FileList = implode('|||', $FileList);
71
-    $Userinfo = Users::user_info($Torrent['UserID']);
72
-
73
-    $Reports = Torrents::get_reports($Torrent['ID']);
74
-    $Torrent['Reported'] = count($Reports) > 0;
75
-
76
-    $JsonTorrentList[] = [
77
-      'id'          => (int) $Torrent['ID'],
78
-      'infoHash'    => $Torrent['InfoHash'],
79
-      'platform'    => $Torrent['Media'],
80
-      'format'      => $Torrent['Container'],
81
-      'license'     => $Torrent['Codec'],
82
-      'scope'       => $Torrent['Resolution'],
83
-      'annotated'   => (bool) $Torrent['Censored'],
84
-      'archive'     => $Torrent['Archive'],
85
-      'fileCount'   => (int) $Torrent['FileCount'],
86
-      'size'        => (int) $Torrent['Size'],
87
-      'seeders'     => (int) $Torrent['Seeders'],
88
-      'leechers'    => (int) $Torrent['Leechers'],
89
-      'snatched'    => (int) $Torrent['Snatched'],
90
-      'freeTorrent' => ($Torrent['FreeTorrent'] == 1),
91
-      'reported'    => (bool) $Torrent['Reported'],
92
-      'time'        => $Torrent['Time'],
93
-      'description' => $Torrent['Description'],
94
-      'fileList'    => $FileList,
95
-      'filePath'    => $Torrent['FilePath'],
96
-      'userId'      => (int) ($Torrent['Anonymous'] ? 0 : $Torrent['UserID']),
97
-      'username'    => ($Torrent['Anonymous'] ? 'Anonymous' : $Userinfo['Username'])
98
-    ];
99
-}
100
-
101
-json_die('success', ['group' => $JsonTorrentDetails, 'torrents' => $JsonTorrentList]);

+ 0
- 22
sections/ajax/torrentgroupalbumart.php View File

1
-<?php
2
-declare(strict_types=1);
3
-
4
-require_once SERVER_ROOT.'/sections/torrents/functions.php';
5
-
6
-$GroupID = (int) $_GET['id'];
7
-if ($GroupID === 0) {
8
-    error('Bad ID parameter', true);
9
-}
10
-
11
-$TorrentDetails = get_group_info($GroupID, true, 0, false);
12
-$TorrentDetails = $TorrentDetails[0];
13
-$Image = $TorrentDetails['WikiImage'];
14
-
15
-// Handle no artwork
16
-if (!$Image) {
17
-    $Image = STATIC_SERVER.'common/noartwork/music.png';
18
-}
19
-
20
-json_die('success', array(
21
-  'picture' => $Image
22
-));

+ 0
- 485
sections/ajax/user.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
5
-    json_die('failure', 'bad id parameter');
6
-}
7
-
8
-$UserID = $_GET['id'];
9
-if ($UserID === $LoggedUser['ID']) {
10
-    $OwnProfile = true;
11
-} else {
12
-    $OwnProfile = false;
13
-}
14
-
15
-// Always view as a normal user
16
-$DB->query("
17
-SELECT
18
-  m.`Username`,
19
-  m.`Email`,
20
-  m.`LastAccess`,
21
-  m.`IP`,
22
-  p.`Level` AS Class,
23
-  m.`Uploaded`,
24
-  m.`Downloaded`,
25
-  m.`RequiredRatio`,
26
-  m.`Enabled`,
27
-  m.`Paranoia`,
28
-  m.`Invites`,
29
-  m.`Title`,
30
-  m.`torrent_pass`,
31
-  m.`can_leech`,
32
-  i.`JoinDate`,
33
-  i.`Info`,
34
-  i.`Avatar`,
35
-  i.`Donor`,
36
-  i.`Warned`,
37
-COUNT(posts.`id`) AS ForumPosts,
38
-  i.`Inviter`,
39
-  i.`DisableInvites`,
40
-  inviter.`username`
41
-FROM
42
-  `users_main` AS m
43
-JOIN `users_info` AS i
44
-ON
45
-  i.`UserID` = m.`ID`
46
-LEFT JOIN `permissions` AS p
47
-ON
48
-  p.`ID` = m.`PermissionID`
49
-LEFT JOIN `users_main` AS inviter
50
-ON
51
-  i.`Inviter` = inviter.`ID`
52
-LEFT JOIN `forums_posts` AS posts
53
-ON
54
-  posts.`AuthorID` = m.`ID`
55
-WHERE
56
-  m.`ID` = $UserID
57
-GROUP BY
58
-  `AuthorID`
59
-");
60
-
61
-// If user doesn't exist
62
-if (!$DB->has_results()) {
63
-    json_die('failure', 'no such user');
64
-}
65
-
66
-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) = $DB->next_record(MYSQLI_NUM, array(9, 11));
67
-
68
-$Paranoia = unserialize($Paranoia);
69
-if (!is_array($Paranoia)) {
70
-    $Paranoia = [];
71
-}
72
-
73
-$ParanoiaLevel = 0;
74
-foreach ($Paranoia as $P) {
75
-    $ParanoiaLevel++;
76
-    if (strpos($P, '+') !== false) {
77
-        $ParanoiaLevel++;
78
-    }
79
-}
80
-
81
-// Raw time is better for JSON
82
-//$JoinedDate = time_diff($JoinDate);
83
-//$LastAccess = time_diff($LastAccess);
84
-
85
-function check_paranoia_here($Setting)
86
-{
87
-    global $Paranoia, $Class, $UserID;
88
-    return check_paranoia($Setting, $Paranoia, $Class, $UserID);
89
-}
90
-
91
-$Friend = false;
92
-$DB->query("
93
-SELECT
94
-  `FriendID`
95
-FROM
96
-  `friends`
97
-WHERE
98
-  `UserID` = '$LoggedUser[ID]'
99
-  AND `FriendID` = '$UserID'
100
-");
101
-
102
-if ($DB->has_results()) {
103
-    $Friend = true;
104
-}
105
-
106
-if (check_paranoia_here('requestsfilled_count') || check_paranoia_here('requestsfilled_bounty')) {
107
-    $DB->query("
108
-    SELECT
109
-      COUNT(DISTINCT r.`ID`),
110
-      SUM(rv.`Bounty`)
111
-    FROM
112
-      `requests` AS r
113
-    LEFT JOIN `requests_votes` AS rv
114
-    ON
115
-      r.`ID` = rv.`RequestID`
116
-    WHERE
117
-      r.`FillerID` = $UserID
118
-    ");
119
-    list($RequestsFilled, $TotalBounty) = $DB->next_record();
120
-
121
-    $DB->query("
122
-    SELECT
123
-      COUNT(`RequestID`),
124
-      SUM(`Bounty`)
125
-    FROM
126
-      `requests_votes`
127
-    WHERE
128
-      `UserID` = $UserID
129
-    ");
130
-    list($RequestsVoted, $TotalSpent) = $DB->next_record();
131
-
132
-    $DB->query("
133
-    SELECT
134
-      COUNT(`ID`)
135
-    FROM
136
-      `torrents`
137
-    WHERE
138
-      `UserID` = '$UserID'
139
-    ");
140
-    list($Uploads) = $DB->next_record();
141
-} else {
142
-    $RequestsFilled = null;
143
-    $TotalBounty = null;
144
-    $RequestsVoted = 0;
145
-    $TotalSpent = 0;
146
-}
147
-
148
-if (check_paranoia_here('uploads+')) {
149
-    $DB->query("
150
-    SELECT
151
-      COUNT(`ID`)
152
-    FROM
153
-      `torrents`
154
-    WHERE
155
-      `UserID` = '$UserID'
156
-    ");
157
-    list($Uploads) = $DB->next_record();
158
-} else {
159
-    $Uploads = null;
160
-}
161
-
162
-if (check_paranoia_here('artistsadded')) {
163
-    $DB->query("
164
-    SELECT
165
-      COUNT(`ArtistID`)
166
-    FROM
167
-      `torrents_artists`
168
-    WHERE
169
-      `UserID` = $UserID
170
-    ");
171
-    list($ArtistsAdded) = $DB->next_record();
172
-} else {
173
-    $ArtistsAdded = null;
174
-}
175
-
176
-// Do the ranks
177
-if (check_paranoia_here('uploaded')) {
178
-    $UploadedRank = UserRank::get_rank('uploaded', $Uploaded);
179
-} else {
180
-    $UploadedRank = null;
181
-}
182
-
183
-if (check_paranoia_here('downloaded')) {
184
-    $DownloadedRank = UserRank::get_rank('downloaded', $Downloaded);
185
-} else {
186
-    $DownloadedRank = null;
187
-}
188
-
189
-if (check_paranoia_here('uploads+')) {
190
-    $UploadsRank = UserRank::get_rank('uploads', $Uploads);
191
-} else {
192
-    $UploadsRank = null;
193
-}
194
-
195
-if (check_paranoia_here('requestsfilled_count')) {
196
-    $RequestRank = UserRank::get_rank('requests', $RequestsFilled);
197
-} else {
198
-    $RequestRank = null;
199
-}
200
-
201
-$PostRank = UserRank::get_rank('posts', $ForumPosts);
202
-
203
-if (check_paranoia_here('requestsvoted_bounty')) {
204
-    $BountyRank = UserRank::get_rank('bounty', $TotalSpent);
205
-} else {
206
-    $BountyRank = null;
207
-}
208
-
209
-if (check_paranoia_here('artistsadded')) {
210
-    $ArtistsRank = UserRank::get_rank('artists', $ArtistsAdded);
211
-} else {
212
-    $ArtistsRank = null;
213
-}
214
-
215
-if ($Downloaded === 0) {
216
-    $Ratio = 1;
217
-} elseif ($Uploaded === 0) {
218
-    $Ratio = 0.5;
219
-} else {
220
-    $Ratio = round($Uploaded / $Downloaded, 2);
221
-}
222
-
223
-if (check_paranoia_here(array('uploaded', 'downloaded', 'uploads+', 'requestsfilled_count', 'requestsvoted_bounty', 'artistsadded'))) {
224
-    $OverallRank = floor(UserRank::overall_score($UploadedRank, $DownloadedRank, $UploadsRank, $RequestRank, $PostRank, $BountyRank, $ArtistsRank, $Ratio));
225
-} else {
226
-    $OverallRank = null;
227
-}
228
-
229
-// Community section
230
-if (check_paranoia_here('snatched+')) {
231
-    $DB->query("
232
-    SELECT
233
-      COUNT(x.`uid`),
234
-      COUNT(DISTINCT x.`fid`)
235
-    FROM
236
-      `xbt_snatched` AS x
237
-    INNER JOIN `torrents` AS t
238
-    ON
239
-      t.`ID` = x.`fid`
240
-    WHERE
241
-      x.`uid` = '$UserID'
242
-    ");
243
-    list($Snatched, $UniqueSnatched) = $DB->next_record();
244
-}
245
-
246
-if (check_paranoia_here('torrentcomments+')) {
247
-    $DB->query("
248
-    SELECT
249
-      COUNT(`ID`)
250
-    FROM
251
-      `comments`
252
-    WHERE
253
-      `Page` = 'torrents'
254
-      AND `AuthorID` = '$UserID'
255
-    ");
256
-    list($NumComments) = $DB->next_record();
257
-}
258
-
259
-if (check_paranoia_here('torrentcomments+')) {
260
-    $DB->query("
261
-    SELECT
262
-      COUNT(`ID`)
263
-    FROM
264
-      `comments`
265
-    WHERE
266
-      `Page` = 'artist'
267
-      AND `AuthorID` = '$UserID'
268
-    ");
269
-    list($NumArtistComments) = $DB->next_record();
270
-}
271
-
272
-if (check_paranoia_here('torrentcomments+')) {
273
-    $DB->query("
274
-    SELECT
275
-      COUNT(`ID`)
276
-    FROM
277
-      `comments`
278
-    WHERE
279
-      `Page` = 'collages'
280
-      AND `AuthorID` = '$UserID'
281
-    ");
282
-    list($NumCollageComments) = $DB->next_record();
283
-}
284
-
285
-if (check_paranoia_here('torrentcomments+')) {
286
-    $DB->query("
287
-    SELECT
288
-      COUNT(`ID`)
289
-    FROM
290
-      `comments`
291
-    WHERE
292
-      `Page` = 'requests'
293
-      AND `AuthorID` = '$UserID'
294
-    ");
295
-    list($NumRequestComments) = $DB->next_record();
296
-}
297
-
298
-if (check_paranoia_here('collages+')) {
299
-    $DB->query("
300
-    SELECT
301
-      COUNT(`ID`)
302
-    FROM
303
-      `collages`
304
-    WHERE
305
-      `Deleted` = '0'
306
-      AND `UserID` = '$UserID'
307
-    ");
308
-    list($NumCollages) = $DB->next_record();
309
-}
310
-
311
-if (check_paranoia_here('collagecontribs+')) {
312
-    $DB->query("
313
-    SELECT
314
-      COUNT(DISTINCT ct.`CollageID`)
315
-    FROM
316
-      `collages_torrents` AS ct
317
-    JOIN `collages` AS c
318
-    ON
319
-      ct.`CollageID` = c.`ID`
320
-    WHERE
321
-      c.`Deleted` = '0'
322
-      AND ct.`UserID` = '$UserID'
323
-    ");
324
-    list($NumCollageContribs) = $DB->next_record();
325
-}
326
-
327
-if (check_paranoia_here('uniquegroups+')) {
328
-    $DB->query("
329
-    SELECT
330
-      COUNT(DISTINCT `GroupID`)
331
-    FROM
332
-      `torrents`
333
-    WHERE
334
-      `UserID` = '$UserID'
335
-    ");
336
-    list($UniqueGroups) = $DB->next_record();
337
-}
338
-
339
-if (check_paranoia_here('seeding+')) {
340
-    $DB->query("
341
-    SELECT
342
-      COUNT(x.`uid`)
343
-    FROM
344
-      `xbt_files_users` AS x
345
-    INNER JOIN `torrents` AS t
346
-    ON
347
-      t.`ID` = x.`fid`
348
-    WHERE
349
-      x.`uid` = '$UserID'
350
-      AND x.`remaining` = 0
351
-    ");
352
-    list($Seeding) = $DB->next_record();
353
-}
354
-
355
-if (check_paranoia_here('leeching+')) {
356
-    $DB->query("
357
-    SELECT
358
-      COUNT(x.`uid`)
359
-    FROM
360
-      `xbt_files_users` AS x
361
-    INNER JOIN `torrents` AS t
362
-    ON
363
-      t.`ID` = x.`fid`
364
-    WHERE
365
-      x.`uid` = '$UserID'
366
-      AND x.`remaining` > 0
367
-    ");
368
-    list($Leeching) = $DB->next_record();
369
-}
370
-
371
-if (check_paranoia_here('invitedcount')) {
372
-    $DB->query("
373
-    SELECT
374
-      COUNT(`UserID`)
375
-    FROM
376
-      `users_info`
377
-    WHERE
378
-      `Inviter` = '$UserID'
379
-    ");
380
-    list($Invited) = $DB->next_record();
381
-}
382
-
383
-if (!$OwnProfile) {
384
-    $torrent_pass = '';
385
-}
386
-
387
-// Run through some paranoia stuff to decide what we can send out
388
-if (!check_paranoia_here('lastseen')) {
389
-    $LastAccess = '';
390
-}
391
-
392
-if (check_paranoia_here('ratio')) {
393
-    $Ratio = Format::get_ratio($Uploaded, $Downloaded, 5);
394
-} else {
395
-    $Ratio = null;
396
-}
397
-
398
-if (!check_paranoia_here('uploaded')) {
399
-    $Uploaded = null;
400
-}
401
-
402
-if (!check_paranoia_here('downloaded')) {
403
-    $Downloaded = null;
404
-}
405
-
406
-if (isset($RequiredRatio) && !check_paranoia_here('requiredratio')) {
407
-    $RequiredRatio = null;
408
-}
409
-
410
-if ($ParanoiaLevel === 0) {
411
-    $ParanoiaLevelText = 'Off';
412
-} elseif ($ParanoiaLevel === 1) {
413
-    $ParanoiaLevelText = 'Very Low';
414
-} elseif ($ParanoiaLevel <= 5) {
415
-    $ParanoiaLevelText = 'Low';
416
-} elseif ($ParanoiaLevel <= 20) {
417
-    $ParanoiaLevelText = 'High';
418
-} else {
419
-    $ParanoiaLevelText = 'Very high';
420
-}
421
-
422
-// Bugfix for no access time available
423
-if (!$LastAccess) {
424
-    $LastAccess = '';
425
-}
426
-
427
-header('Content-Type: text/plain; charset=utf-8');
428
-
429
-json_print('success', [
430
-  'username'    => $Username,
431
-  'avatar'      => $Avatar,
432
-  'isFriend'    => (bool) $Friend,
433
-  'profileText' => Text::full_format($Info),
434
-
435
-  'stats' => [
436
-    'joinedDate'    => $JoinDate,
437
-    'lastAccess'    => $LastAccess,
438
-    'uploaded'      => (int) $Uploaded,
439
-    'downloaded'    => (int) $Downloaded,
440
-    'ratio'         => (float) $Ratio,
441
-    'requiredRatio' => (float) $RequiredRatio
442
-  ],
443
-
444
-  'ranks' => [
445
-    'uploaded'   => (int) $UploadedRank,
446
-    'downloaded' => (int) $DownloadedRank,
447
-    'uploads'    => (int) $UploadsRank,
448
-    'requests'   => (int) $RequestRank,
449
-    'bounty'     => (int) $BountyRank,
450
-    'posts'      => (int) $PostRank,
451
-    'artists'    => (int) $ArtistsRank,
452
-    'overall'    => (int) $OverallRank
453
-  ],
454
-
455
-  'personal' => [
456
-    'class'        => $ClassLevels[$Class]['Name'],
457
-    'paranoia'     => (int) $ParanoiaLevel,
458
-    'paranoiaText' => $ParanoiaLevelText,
459
-    'donor'        => ($Donor === 1),
460
-    'warned'       => (bool) $Warned,
461
-    'enabled'      => ((int) $Enabled === 1 || (int) $Enabled === 0 || !$Enabled),
462
-    'passkey'      => $torrent_pass
463
-  ],
464
-
465
-  'community' => [
466
-    'posts'           => (int) $ForumPosts,
467
-    'torrentComments' => (int) $NumComments,
468
-    'artistComments'  => (int) $NumArtistComments,
469
-    'collageComments' => (int) $NumCollageComments,
470
-    'requestComments' => (int) $NumRequestComments,
471
-    'collagesStarted' => (int) $NumCollages,
472
-    'collagesContrib' => (int) $NumCollageContribs,
473
-    'requestsFilled'  => (int) $RequestsFilled,
474
-    'bountyEarned'    => (int) $TotalBounty,
475
-    'requestsVoted'   => (int) $RequestsVoted,
476
-    'bountySpent'     => (int) $TotalSpent,
477
-    'uploaded'        => (int) $Uploads,
478
-    'groups'          => (int) $UniqueGroups,
479
-    'seeding'         => (int) $Seeding,
480
-    'leeching'        => (int) $Leeching,
481
-    'snatched'        => (int) $Snatched,
482
-    'invited'         => (int) $Invited,
483
-    'artistsAdded'    => (int) $ArtistsAdded
484
-  ]
485
-]);

+ 0
- 96
sections/ajax/user_recents.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-$UserID = (int) $_GET['userid'];
6
-$Limit = (int) $_GET['limit'];
7
-
8
-if (empty($UserID) || $Limit > 50) {
9
-    json_die('failure', 'bad parameters');
10
-}
11
-
12
-if (empty($Limit)) {
13
-    $Limit = 15;
14
-}
15
-
16
-$Results = [];
17
-if (check_paranoia_here('snatched')) {
18
-    $DB->query("
19
-    SELECT
20
-      g.`id`,
21
-      g.`title`,
22
-      g.`picture`
23
-    FROM
24
-      `xbt_snatched` AS s
25
-    INNER JOIN `torrents` AS t
26
-    ON
27
-      t.`ID` = s.`fid`
28
-    INNER JOIN `torrents_group` AS g
29
-    ON
30
-      t.`GroupID` = g.`id`
31
-    WHERE
32
-      s.`uid` = '$UserID' AND g.`category_id` = '1' AND g.`picture` != ''
33
-    GROUP BY
34
-      g.`id`
35
-    ORDER BY
36
-      s.`tstamp`
37
-    DESC
38
-    LIMIT $Limit
39
-    ");
40
-
41
-    $RecentSnatches = $DB->to_array(false, MYSQLI_ASSOC);
42
-    $Artists = Artists::get_artists($DB->collect('ID'));
43
-
44
-    foreach ($RecentSnatches as $Key => $SnatchInfo) {
45
-        $RecentSnatches[$Key]['artists'][] = $Artists[$SnatchInfo['ID']];
46
-        $RecentSnatches[$Key]['ID'] = (int)$RecentSnatches[$Key]['ID'];
47
-    }
48
-    $Results['snatches'] = $RecentSnatches;
49
-} else {
50
-    $Results['snatches'] = 'hidden';
51
-}
52
-
53
-if (check_paranoia_here('uploads')) {
54
-    $DB->query("
55
-    SELECT
56
-      g.`id`,
57
-      g.`title`,
58
-      g.`picture`
59
-    FROM
60
-      `torrents_group` AS g
61
-    INNER JOIN `torrents` AS t
62
-    ON
63
-      t.`GroupID` = g.`id`
64
-    WHERE
65
-      t.`UserID` = '$UserID' AND g.`category_id` = '1' AND g.`picture` != ''
66
-    GROUP BY
67
-      g.`id`
68
-    ORDER BY
69
-      t.`Time`
70
-    DESC
71
-    LIMIT $Limit
72
-    ");
73
-
74
-    $RecentUploads = $DB->to_array(false, MYSQLI_ASSOC);
75
-    $Artists = Artists::get_artists($DB->collect('ID'));
76
-
77
-    foreach ($RecentUploads as $Key => $UploadInfo) {
78
-        $RecentUploads[$Key]['artists'][] = $Artists[$UploadInfo['ID']];
79
-        $RecentUploads[$Key]['ID'] = (int)$RecentUploads[$Key]['ID'];
80
-    }
81
-    $Results['uploads'] = $RecentUploads;
82
-} else {
83
-    $Results['uploads'] = 'hidden';
84
-}
85
-
86
-json_die('success', $Results);
87
-
88
-function check_paranoia_here($Setting)
89
-{
90
-    global $Paranoia, $Class, $UserID, $Preview;
91
-    if ($Preview == 1) {
92
-        return check_paranoia($Setting, $Paranoia, $Class);
93
-    } else {
94
-        return check_paranoia($Setting, $Paranoia, $Class, $UserID);
95
-    }
96
-}

+ 0
- 20
sections/ajax/userhistory/index.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if ($_GET['type']) {
5
-    switch ($_GET['type']) {
6
-    case 'posts':
7
-      // Load post history page
8
-      include('post_history.php');
9
-      break;
10
-
11
-    default:
12
-      echo json_encode(
13
-          array('status' => 'failure')
14
-      );
15
-  }
16
-} else {
17
-    echo json_encode(
18
-        array('status' => 'failure')
19
-    );
20
-}

+ 0
- 186
sections/ajax/userhistory/post_history.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-# todo: Go through line by line
5
-function error_out($reason = '')
6
-{
7
-    $error = array('status' => 'failure');
8
-    if ($reason !== '') {
9
-        $error['reason'] = $reason;
10
-    }
11
-    echo $error;
12
-    error();
13
-}
14
-
15
-if (!empty($LoggedUser['DisableForums'])) {
16
-    error_out('You do not have access to the forums!');
17
-}
18
-
19
-$UserID = empty($_GET['userid']) ? $LoggedUser['ID'] : $_GET['userid'];
20
-if (!is_number($UserID)) {
21
-    error_out('User does not exist!');
22
-}
23
-
24
-if (isset($LoggedUser['PostsPerPage'])) {
25
-    $PerPage = $LoggedUser['PostsPerPage'];
26
-} else {
27
-    $PerPage = POSTS_PER_PAGE;
28
-}
29
-
30
-list($Page, $Limit) = Format::page_limit($PerPage);
31
-
32
-$UserInfo = Users::user_info($UserID);
33
-extract(array_intersect_key($UserInfo, array_flip(array('Username', 'Enabled', 'Title', 'Avatar', 'Donor', 'Warned'))));
34
-
35
-$ViewingOwn = ($UserID === $LoggedUser['ID']);
36
-$ShowUnread = ($ViewingOwn && (!isset($_GET['showunread']) || !!$_GET['showunread']));
37
-$ShowGrouped = ($ViewingOwn && (!isset($_GET['group']) || !!$_GET['group']));
38
-if ($ShowGrouped) {
39
-    $SQL = '
40
-    SELECT
41
-      SQL_CALC_FOUND_ROWS
42
-      MAX(p.ID) AS ID
43
-    FROM forums_posts AS p
44
-      LEFT JOIN forums_topics AS t ON t.ID = p.TopicID';
45
-    if ($ShowUnread) {
46
-        $SQL .= '
47
-      LEFT JOIN forums_last_read_topics AS l ON l.TopicID = t.ID AND l.UserID = '.$LoggedUser['ID'];
48
-    }
49
-    $SQL .= '
50
-      LEFT JOIN forums AS f ON f.ID = t.ForumID
51
-    WHERE p.AuthorID = '.$UserID.'
52
-      AND ' . Forums::user_forums_sql();
53
-    if ($ShowUnread) {
54
-        $SQL .= '
55
-      AND ((t.IsLocked = \'0\' OR t.IsSticky = \'1\')
56
-      AND (l.PostID < t.LastPostID OR l.PostID IS NULL))';
57
-    }
58
-    $SQL .= "
59
-    GROUP BY t.ID
60
-    ORDER BY p.ID DESC
61
-    LIMIT $Limit";
62
-    $PostIDs = $DB->query($SQL);
63
-    $DB->query('SELECT FOUND_ROWS()');
64
-    list($Results) = $DB->next_record();
65
-
66
-    if ($Results > $PerPage * ($Page - 1)) {
67
-        $DB->set_query_id($PostIDs);
68
-        $PostIDs = $DB->collect('ID');
69
-        $SQL = "
70
-      SELECT
71
-        p.ID,
72
-        p.AddedTime,
73
-        p.Body,
74
-        p.EditedUserID,
75
-        p.EditedTime,
76
-        ed.Username,
77
-        p.TopicID,
78
-        t.Title,
79
-        t.LastPostID,
80
-        l.PostID AS LastRead,
81
-        t.IsLocked,
82
-        t.IsSticky
83
-      FROM forums_posts AS p
84
-        LEFT JOIN users_main AS um ON um.ID = p.AuthorID
85
-        LEFT JOIN users_info AS ui ON ui.UserID = p.AuthorID
86
-        LEFT JOIN users_main AS ed ON ed.ID = p.EditedUserID
87
-        JOIN forums_topics AS t ON t.ID = p.TopicID
88
-        JOIN forums AS f ON f.ID = t.ForumID
89
-        LEFT JOIN forums_last_read_topics AS l ON l.UserID = $UserID AND l.TopicID = t.ID
90
-      WHERE p.ID IN (".implode(',', $PostIDs).')
91
-      ORDER BY p.ID DESC';
92
-        $Posts = $DB->query($SQL);
93
-    }
94
-} else {
95
-    $SQL = '
96
-    SELECT
97
-      SQL_CALC_FOUND_ROWS';
98
-    if ($ShowGrouped) {
99
-        $SQL .= '
100
-      *
101
-    FROM (
102
-      SELECT';
103
-    }
104
-    $SQL .= '
105
-        p.ID,
106
-        p.AddedTime,
107
-        p.Body,
108
-        p.EditedUserID,
109
-        p.EditedTime,
110
-        ed.Username,
111
-        p.TopicID,
112
-        t.Title,
113
-        t.LastPostID,';
114
-    if ($UserID === $LoggedUser['ID']) {
115
-        $SQL .= '
116
-        l.PostID AS LastRead,';
117
-    }
118
-    $SQL .= "
119
-        t.IsLocked,
120
-        t.IsSticky
121
-      FROM forums_posts AS p
122
-        LEFT JOIN users_main AS um ON um.ID = p.AuthorID
123
-        LEFT JOIN users_info AS ui ON ui.UserID = p.AuthorID
124
-        LEFT JOIN users_main AS ed ON ed.ID = p.EditedUserID
125
-        JOIN forums_topics AS t ON t.ID = p.TopicID
126
-        JOIN forums AS f ON f.ID = t.ForumID
127
-        LEFT JOIN forums_last_read_topics AS l ON l.UserID = $UserID AND l.TopicID = t.ID
128
-      WHERE p.AuthorID = $UserID
129
-        AND " . Forums::user_forums_sql();
130
-
131
-    if ($ShowUnread) {
132
-        $SQL .= '
133
-        AND ((t.IsLocked = \'0\' OR t.IsSticky = \'1\')
134
-          AND (l.PostID < t.LastPostID OR l.PostID IS NULL)
135
-        ) ';
136
-    }
137
-
138
-    $SQL .= '
139
-      ORDER BY p.ID DESC';
140
-
141
-    if ($ShowGrouped) {
142
-        $SQL .= '
143
-    ) AS sub
144
-    GROUP BY TopicID
145
-    ORDER BY ID DESC';
146
-    }
147
-
148
-    $SQL .= "
149
-    LIMIT $Limit";
150
-    $Posts = $DB->query($SQL);
151
-
152
-    $DB->query('SELECT FOUND_ROWS()');
153
-    list($Results) = $DB->next_record();
154
-
155
-    $DB->set_query_id($Posts);
156
-}
157
-
158
-$JsonResults = [];
159
-while (list($PostID, $AddedTime, $Body, $EditedUserID, $EditedTime, $EditedUsername, $TopicID, $ThreadTitle, $LastPostID, $LastRead, $Locked, $Sticky) = $DB->next_record()) {
160
-    $JsonResults[] = array(
161
-    'postId' => (int)$PostID,
162
-    'topicId' => (int)$TopicID,
163
-    'threadTitle' => $ThreadTitle,
164
-    'lastPostId' => (int)$LastPostID,
165
-    'lastRead' => (int)$LastRead,
166
-    'locked' => $Locked === '1',
167
-    'sticky' => $Sticky === '1',
168
-    'addedTime' => $AddedTime,
169
-    'body' => Text::full_format($Body),
170
-    'bbbody' => $Body,
171
-    'editedUserId' => (int)$EditedUserID,
172
-    'editedTime' => $EditedTime,
173
-    'editedUsername' => $EditedUsername
174
-    );
175
-}
176
-
177
-echo json_encode(
178
-    array(
179
-    'status' => 'success',
180
-    'response' => array(
181
-      'currentPage' => (int)$Page,
182
-      'pages' => ceil($Results / $PerPage),
183
-      'threads' => $JsonResults
184
-      )
185
-    )
186
-);

+ 0
- 58
sections/ajax/usersearch.php View File

1
-<?php
2
-/**********************************************************************
3
- *>>>>>>>>>>>>>>>>>>>>>>>>>>> User search <<<<<<<<<<<<<<<<<<<<<<<<<<<<*
4
- **********************************************************************/
5
-
6
-if (empty($_GET['search'])) {
7
-  json_die("failure", "no search terms");
8
-} else {
9
-  $_GET['username'] = $_GET['search'];
10
-}
11
-
12
-define('USERS_PER_PAGE', 30);
13
-
14
-if (isset($_GET['username'])) {
15
-  $_GET['username'] = trim($_GET['username']);
16
-
17
-  list($Page, $Limit) = Format::page_limit(USERS_PER_PAGE);
18
-  $DB->query("
19
-    SELECT
20
-      SQL_CALC_FOUND_ROWS
21
-      ID,
22
-      Username,
23
-      Enabled,
24
-      PermissionID,
25
-      Donor,
26
-      Warned,
27
-      Avatar
28
-    FROM users_main AS um
29
-      JOIN users_info AS ui ON ui.UserID = um.ID
30
-    WHERE Username LIKE '%".db_string($_GET['username'])."%'
31
-    ORDER BY Username
32
-    LIMIT $Limit");
33
-  $Results = $DB->to_array();
34
-  $DB->query('SELECT FOUND_ROWS();');
35
-  list($NumResults) = $DB->next_record();
36
-
37
-}
38
-
39
-$JsonUsers = [];
40
-foreach ($Results as $Result) {
41
-  list($UserID, $Username, $Enabled, $PermissionID, $Donor, $Warned, $Avatar) = $Result;
42
-
43
-  $JsonUsers[] = [
44
-    'userId' => (int)$UserID,
45
-    'username' => $Username,
46
-    'donor' => $Donor == 1,
47
-    'warned' => (bool)$Warned,
48
-    'enabled' => ($Enabled == 2 ? false : true),
49
-    'class' => Users::make_class_string($PermissionID),
50
-    'avatar' => $Avatar
51
-  ];
52
-}
53
-
54
-json_die("success", [
55
-  'currentPage' => (int)$Page,
56
-  'pages' => ceil($NumResults / USERS_PER_PAGE),
57
-  'results' => $JsonUsers
58
-]);

+ 0
- 41
sections/ajax/wiki.php View File

1
-<?php
2
-#declare(strict_types=1);
3
-
4
-if (!empty($_GET['id']) && is_number($_GET['id'])) {
5
-    // Visiting article via ID
6
-    $ArticleID = $_GET['id'];
7
-} elseif ($_GET['name'] !== '') {
8
-    // Retrieve article ID via alias
9
-    $ArticleID = Wiki::alias_to_id($_GET['name']);
10
-} else {
11
-    json_die('failure');
12
-}
13
-
14
-// No article found
15
-if (!$ArticleID) {
16
-    json_die('failure', 'article not found');
17
-}
18
-
19
-$Article = Wiki::get_article($ArticleID, false);
20
-if (!$Article) {
21
-    json_die('failure', 'article not found');
22
-}
23
-
24
-list($Revision, $Title, $Body, $Read, $Edit, $Date, $AuthorID, $AuthorName, $Aliases, $UserIDs) = array_shift($Article);
25
-if ($Read > $LoggedUser['EffectiveClass']) {
26
-    json_die('failure', 'higher user class required to view article');
27
-}
28
-
29
-Text::$TOC = true;
30
-$TextBody = Text::full_format($Body, false);
31
-
32
-json_die('success', array(
33
-  'title'      => $Title,
34
-  'bbBody'     => $Body,
35
-  'body'       => $TextBody,
36
-  'aliases'    => $Aliases,
37
-  'authorID'   => (int) $AuthorID,
38
-  'authorName' => $AuthorName,
39
-  'date'       => $Date,
40
-  'revision'   => (int) $Revision
41
-));

+ 1
- 1
sections/api/forum/thread.php View File

28
 
28
 
29
         if ($ThreadID) {
29
         if ($ThreadID) {
30
             // Redirect postid to threadid when necessary
30
             // Redirect postid to threadid when necessary
31
-            header("Location: ajax.php?action=forum&type=viewthread&threadid=$ThreadID&postid=$_GET[postid]");
31
+            header("Location: api.php?action=forum&type=viewthread&threadid=$ThreadID&postid=$_GET[postid]");
32
             error();
32
             error();
33
         } else {
33
         } else {
34
             echo json_encode(array('status' => 'failure'));
34
             echo json_encode(array('status' => 'failure'));

+ 1
- 1
static/functions/ajax.class.js View File

11
     $('#preview' + postid).raw().innerHTML = ajax.response;
11
     $('#preview' + postid).raw().innerHTML = ajax.response;
12
     $('#editbox' + postid).ghide();
12
     $('#editbox' + postid).ghide();
13
   }
13
   }
14
-  ajax.post("ajax.php?action=preview","#form-id" + postid);
14
+  ajax.post("api.php?action=preview","#form-id" + postid);
15
 
15
 
16
   Example usage 2:
16
   Example usage 2:
17
   ajax.handle = function() {
17
   ajax.handle = function() {

+ 4
- 4
static/functions/comments.js View File

70
 
70
 
71
       $.ajax({
71
       $.ajax({
72
         type: "POST",
72
         type: "POST",
73
-        url: "ajax.php?action=raw_bbcode",
73
+        url: "api.php?action=raw_bbcode",
74
         dataType: "json",
74
         dataType: "json",
75
         data: {
75
         data: {
76
           "postid": postid
76
           "postid": postid
198
  */
198
  */
199
 function Preview_Edit(postid) {
199
 function Preview_Edit(postid) {
200
   $('#bar' + postid).raw().innerHTML = "<input type=\"button\" value=\"Editor\" onclick=\"Cancel_Preview(" + postid + ");\" /><input type=\"button\" value=\"Post\" onclick=\"Save_Edit(" + postid + ")\" /><input type=\"button\" value=\"Cancel\" onclick=\"Cancel_Edit(" + postid + ");\" />";
200
   $('#bar' + postid).raw().innerHTML = "<input type=\"button\" value=\"Editor\" onclick=\"Cancel_Preview(" + postid + ");\" /><input type=\"button\" value=\"Post\" onclick=\"Save_Edit(" + postid + ")\" /><input type=\"button\" value=\"Cancel\" onclick=\"Cancel_Edit(" + postid + ");\" />";
201
-  ajax.post("ajax.php?action=preview", "form" + postid, function (response) {
201
+  ajax.post("api.php?action=preview", "form" + postid, function (response) {
202
     $('#preview' + postid).raw().innerHTML = response;
202
     $('#preview' + postid).raw().innerHTML = response;
203
     $('#editbox' + postid).ghide();
203
     $('#editbox' + postid).ghide();
204
     if ($('#editbox' + postid).raw().previousSibling.classList.contains('bbcode_bar')) $($('#editbox' + postid).raw().previousSibling).ghide();
204
     if ($('#editbox' + postid).raw().previousSibling.classList.contains('bbcode_bar')) $($('#editbox' + postid).raw().previousSibling).ghide();
268
   var quickreplybuttons;
268
   var quickreplybuttons;
269
   $('#post_preview').raw().value = "Make changes";
269
   $('#post_preview').raw().value = "Make changes";
270
   $('#post_preview').raw().preview = true;
270
   $('#post_preview').raw().preview = true;
271
-  ajax.post("ajax.php?action=preview", "quickpostform", function (response) {
271
+  ajax.post("api.php?action=preview", "quickpostform", function (response) {
272
     $('#quickreplypreview').gshow();
272
     $('#quickreplypreview').gshow();
273
     $('#contentpreview').raw().innerHTML = response;
273
     $('#contentpreview').raw().innerHTML = response;
274
     $('#quickreplytext').ghide();
274
     $('#quickreplytext').ghide();
295
   $('#newthreadpreviewbutton').gtoggle();
295
   $('#newthreadpreviewbutton').gtoggle();
296
   $('#newthreadeditbutton').gtoggle();
296
   $('#newthreadeditbutton').gtoggle();
297
   if (mode) { // Preview
297
   if (mode) { // Preview
298
-    ajax.post("ajax.php?action=preview", "newthreadform", function (response) {
298
+    ajax.post("api.php?action=preview", "newthreadform", function (response) {
299
       $('#contentpreview').raw().innerHTML = response;
299
       $('#contentpreview').raw().innerHTML = response;
300
     });
300
     });
301
     $('#newthreadtitle').raw().innerHTML = $('#title').raw().value;
301
     $('#newthreadtitle').raw().innerHTML = $('#title').raw().value;

+ 1
- 1
static/functions/inbox.js View File

2
 
2
 
3
 function Quick_Preview() {
3
 function Quick_Preview() {
4
   $('#buttons').raw().innerHTML = "<input type=\"button\" value=\"Editor\" onclick=\"Quick_Edit();\" /><input type=\"submit\" value=\"Send Message\" />";
4
   $('#buttons').raw().innerHTML = "<input type=\"button\" value=\"Editor\" onclick=\"Quick_Edit();\" /><input type=\"submit\" value=\"Send Message\" />";
5
-  ajax.post("ajax.php?action=preview","messageform", function(response) {
5
+  ajax.post("api.php?action=preview", "messageform", function (response) {
6
     $('#quickpost').ghide();
6
     $('#quickpost').ghide();
7
     $('#preview').raw().innerHTML = response;
7
     $('#preview').raw().innerHTML = response;
8
     $('#preview').gshow();
8
     $('#preview').gshow();

+ 34
- 34
static/functions/news_ajax.js View File

8
   // Unbind onclick to avoid spamclicks.
8
   // Unbind onclick to avoid spamclicks.
9
   $(event.target).attr('onclick', 'return false;');
9
   $(event.target).attr('onclick', 'return false;');
10
   // Fetch news data, check for errors etc.
10
   // Fetch news data, check for errors etc.
11
-  $.get("ajax.php", {
11
+  $.get("api.php", {
12
     action: "news_ajax",
12
     action: "news_ajax",
13
     count: count,
13
     count: count,
14
     offset: offset
14
     offset: offset
15
   })
15
   })
16
-  .done(function(data) {
17
-    var response = $.parseJSON(data.response);
18
-    if (typeof data == 'undefined' || data == null || data.status != "success" || typeof response == 'undefined' || response == null) {
19
-      console.log("ERR ajax_news(" + (new Error).lineNumber + "): Unknown data or failure returned.");
20
-      // Return to original paremeters, no news were added.
21
-      $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + offset + ', ' + privileged + '); return false;');
22
-    } else {
23
-      if (response.length == 0) {
24
-        $(event.target).parent().remove();
16
+    .done(function (data) {
17
+      var response = $.parseJSON(data.response);
18
+      if (typeof data == 'undefined' || data == null || data.status != "success" || typeof response == 'undefined' || response == null) {
19
+        console.log("ERR ajax_news(" + (new Error).lineNumber + "): Unknown data or failure returned.");
20
+        // Return to original paremeters, no news were added.
21
+        $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + offset + ', ' + privileged + '); return false;');
25
       } else {
22
       } else {
26
-        var targetClass = $('#more_news').prev().attr('class');
27
-        $.each(response, function() {
28
-          // Create a new element, insert the news.
29
-          $('#more_news').before($('<div/>', {
30
-            id: 'news' + this[0],
31
-            Class: targetClass
32
-          }));
33
-          // I'm so happy with this condition statement.
34
-          if (privileged) {
35
-            $('#news' + this[0]).append('<div class="head"><strong>' + this[1] + '</strong> ' + this[2] + ' - <a href="tools.php?action=editnews&amp;id=' + this[0] + '" class="brackets">Edit</a><span class="float_right"><a class="brackets" data-toggle-target="#newsbody' + this[0] + '" data-toggle-replace="Show">Hide</a></span></div>');
36
-          } else {
37
-            $('#news' + this[0]).append('<div class="head"><strong>' + this[1] + '</strong> ' + this[2] + '<span class="float_right"><a class="brackets" data-toggle-target="#newsbody' + this[0] + '" data-toggle-replace="Show">Hide</a></span></div>');
38
-          }
39
-          $('#news' + this[0]).append('<div class="pad" id="newsbody'+this[0]+'">' + this[3] + '</div>');
40
-        });
41
-        // Update the onclick parameters to appropriate offset.
42
-        $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + (count + offset) + ', ' + privileged + '); return false;');
23
+        if (response.length == 0) {
24
+          $(event.target).parent().remove();
25
+        } else {
26
+          var targetClass = $('#more_news').prev().attr('class');
27
+          $.each(response, function () {
28
+            // Create a new element, insert the news.
29
+            $('#more_news').before($('<div/>', {
30
+              id: 'news' + this[0],
31
+              Class: targetClass
32
+            }));
33
+            // I'm so happy with this condition statement.
34
+            if (privileged) {
35
+              $('#news' + this[0]).append('<div class="head"><strong>' + this[1] + '</strong> ' + this[2] + ' - <a href="tools.php?action=editnews&amp;id=' + this[0] + '" class="brackets">Edit</a><span class="float_right"><a class="brackets" data-toggle-target="#newsbody' + this[0] + '" data-toggle-replace="Show">Hide</a></span></div>');
36
+            } else {
37
+              $('#news' + this[0]).append('<div class="head"><strong>' + this[1] + '</strong> ' + this[2] + '<span class="float_right"><a class="brackets" data-toggle-target="#newsbody' + this[0] + '" data-toggle-replace="Show">Hide</a></span></div>');
38
+            }
39
+            $('#news' + this[0]).append('<div class="pad" id="newsbody' + this[0] + '">' + this[3] + '</div>');
40
+          });
41
+          // Update the onclick parameters to appropriate offset.
42
+          $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + (count + offset) + ', ' + privileged + '); return false;');
43
+        }
43
       }
44
       }
44
-    }
45
-  })
46
-  .fail(function() {
47
-    console.log("WARN ajax_news(" + (new Error).lineNumber + "): AJAX get failed.");
48
-    // Return to original paremeters, no news were added.
49
-    $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + offset + ', ' + privileged + '); return false;');
50
-  });
45
+    })
46
+    .fail(function () {
47
+      console.log("WARN ajax_news(" + (new Error).lineNumber + "): AJAX get failed.");
48
+      // Return to original paremeters, no news were added.
49
+      $(event.target).attr('onclick', 'news_ajax(event, ' + count + ', ' + offset + ', ' + privileged + '); return false;');
50
+    });
51
 }
51
 }

+ 0
- 19
static/functions/password_validate.js View File

29
 
29
 
30
       if (password1.length == 0 && password2.length == 0) {
30
       if (password1.length == 0 && password2.length == 0) {
31
         enableSubmit();
31
         enableSubmit();
32
-      } else if (getStrong() == true) {
33
-        validatePassword(password1);
34
       }
32
       }
35
     });
33
     });
36
 
34
 
59
 
57
 
60
   });
58
   });
61
 
59
 
62
-  function validatePassword(password) {
63
-    if (isUserPage()) {
64
-      $.ajax({
65
-        type: 'POST',
66
-        dataType: 'text',
67
-        url: 'ajax.php?action=password_validate',
68
-        data: 'password=' + password,
69
-        async: false,
70
-        success: function (value) {
71
-          if (value == 'false') {
72
-            setStatus(COMMON);
73
-          }
74
-        }
75
-      });
76
-    }
77
-  }
78
-
79
   function calculateComplexity(password) {
60
   function calculateComplexity(password) {
80
     var length = password.length;
61
     var length = password.length;
81
     var username;
62
     var username;

+ 20
- 20
static/functions/recommend.js View File

1
-(function() {
1
+(function () {
2
   var sent = new Array();
2
   var sent = new Array();
3
   var loaded = false;
3
   var loaded = false;
4
   var type;
4
   var type;
5
   var id;
5
   var id;
6
-  $(document).ready(function() {
6
+  $(document).ready(function () {
7
     type = $("#recommendation_div").data('type');
7
     type = $("#recommendation_div").data('type');
8
     id = $("#recommendation_div").data('id');
8
     id = $("#recommendation_div").data('id');
9
-    $("#recommend").click(function() {
9
+    $("#recommend").click(function () {
10
       $("#recommendation_div").slideToggle(150);
10
       $("#recommendation_div").slideToggle(150);
11
       if (!loaded) {
11
       if (!loaded) {
12
         $("#recommendation_status").html("Loading...");
12
         $("#recommendation_status").html("Loading...");
13
         $.ajax({
13
         $.ajax({
14
-          type : "POST",
15
-          url : "ajax.php?action=get_friends",
16
-          dataType : "json",
17
-          success : function(response) {
18
-            $.each(response, function(key, value) {
14
+          type: "POST",
15
+          url: "api.php?action=get_friends",
16
+          dataType: "json",
17
+          success: function (response) {
18
+            $.each(response, function (key, value) {
19
               var id = value['FriendID'];
19
               var id = value['FriendID'];
20
               var friend = value['Username'];
20
               var friend = value['Username'];
21
               $("#friend").append($("<option></option>").attr("value", id).text(friend));
21
               $("#friend").append($("<option></option>").attr("value", id).text(friend));
26
         });
26
         });
27
       }
27
       }
28
     });
28
     });
29
-    $("#friend").change(function() {
29
+    $("#friend").change(function () {
30
       var friend = $("select#friend").val();
30
       var friend = $("select#friend").val();
31
       if (friend == 0) {
31
       if (friend == 0) {
32
         $("#send_recommendation").attr("disabled", "disabled");
32
         $("#send_recommendation").attr("disabled", "disabled");
36
       $("#recommendation_status").html("<br />");
36
       $("#recommendation_status").html("<br />");
37
     });
37
     });
38
 
38
 
39
-    $("#send_recommendation").click(function() {
39
+    $("#send_recommendation").click(function () {
40
       send_recommendation();
40
       send_recommendation();
41
     });
41
     });
42
-    $("#recommendation_note").keypress(function(e) {
42
+    $("#recommendation_note").keypress(function (e) {
43
       state = $("#send_recommendation").attr("disabled");
43
       state = $("#send_recommendation").attr("disabled");
44
       if (typeof state === 'undefined' && e.keyCode == 13) {
44
       if (typeof state === 'undefined' && e.keyCode == 13) {
45
         e.preventDefault();
45
         e.preventDefault();
52
     var note = $("#recommendation_note").val();
52
     var note = $("#recommendation_note").val();
53
     if (friend != 0) {
53
     if (friend != 0) {
54
       $.ajax({
54
       $.ajax({
55
-        type : "POST",
56
-        dataType : "json",
57
-        url : "ajax.php?action=send_recommendation",
58
-        data : {
59
-          "friend" : friend,
60
-          "note" : note,
61
-          "type" : type,
62
-          "id" : id
55
+        type: "POST",
56
+        dataType: "json",
57
+        url: "api.php?action=send_recommendation",
58
+        data: {
59
+          "friend": friend,
60
+          "note": note,
61
+          "type": type,
62
+          "id": id
63
         }
63
         }
64
-      }).done(function(response) {
64
+      }).done(function (response) {
65
         $("#recommendation_status").html("<strong>" + response['response'] + "</strong>");
65
         $("#recommendation_status").html("<strong>" + response['response'] + "</strong>");
66
         $("#send_recommendation").attr("disabled", "disabled");
66
         $("#send_recommendation").attr("disabled", "disabled");
67
         $("#recommendation_note").val("");
67
         $("#recommendation_note").val("");

+ 1
- 1
static/functions/requests.js View File

188
     description: 'req_desc'
188
     description: 'req_desc'
189
   }
189
   }
190
   var cn = $('#catalogue').raw().value.toUpperCase()
190
   var cn = $('#catalogue').raw().value.toUpperCase()
191
-  $.getJSON('/ajax.php?action=javfill&cn=' + cn, function (data) {
191
+  $.getJSON('/api.php?action=javfill&cn=' + cn, function (data) {
192
     if (data.status != "success") {
192
     if (data.status != "success") {
193
       $('#catalogue').raw().value = 'Failed'
193
       $('#catalogue').raw().value = 'Failed'
194
       return
194
       return

+ 2
- 5
static/functions/textareapreview.class.js View File

1
 var TextareaPreview;
1
 var TextareaPreview;
2
+
2
 $(document).ready(function () {
3
 $(document).ready(function () {
3
   'use strict';
4
   'use strict';
4
 
5
 
81
     },
82
     },
82
 
83
 
83
     post: function () {
84
     post: function () {
84
-      $.post('ajax.php?action=preview',
85
+      $.post('api.php?action=preview',
85
         { body: this.el.textarea.val() },
86
         { body: this.el.textarea.val() },
86
         $.proxy(this.html, this),
87
         $.proxy(this.html, this),
87
         'html'
88
         'html'
88
       );
89
       );
89
-
90
-      // .fail(function (jqXHR, textStatus) {
91
-      //   alert('Request failed: ' + textStatus);
92
-      // });
93
     },
90
     },
94
 
91
 
95
     html: function (data) {
92
     html: function (data) {

+ 3
- 3
static/functions/upload.js View File

403
   }
403
   }
404
 
404
 
405
   var aid = $('#anidb').raw().value
405
   var aid = $('#anidb').raw().value
406
-  $.getJSON('/ajax.php?action=autofill&cat=anime&aid=' + aid, function (data) {
406
+  $.getJSON('/api.php?action=autofill&cat=anime&aid=' + aid, function (data) {
407
     if (data.status != "success") return
407
     if (data.status != "success") return
408
     for (i in data.response) {
408
     for (i in data.response) {
409
       if (map[i] && !($('#' + map[i]).raw().value)) {
409
       if (map[i] && !($('#' + map[i]).raw().value)) {
431
   }
431
   }
432
 
432
 
433
   var cn = $('#javdb_tr #catalogue').raw().value.toUpperCase()
433
   var cn = $('#javdb_tr #catalogue').raw().value.toUpperCase()
434
-  $.getJSON('/ajax.php?action=autofill&cat=jav&cn=' + cn, function (data) {
434
+  $.getJSON('/api.php?action=autofill&cat=jav&cn=' + cn, function (data) {
435
     if (data.status != "success") {
435
     if (data.status != "success") {
436
       $('#catalogue').raw().value = 'Failed'
436
       $('#catalogue').raw().value = 'Failed'
437
       return
437
       return
484
   }
484
   }
485
 
485
 
486
   var nh = $('#ehentai_tr #catalogue').raw().value
486
   var nh = $('#ehentai_tr #catalogue').raw().value
487
-  $.getJSON('/ajax.php?action=autofill&cat=manga&url=' + nh, function (data) {
487
+  $.getJSON('/api.php?action=autofill&cat=manga&url=' + nh, function (data) {
488
     if (data.status != "success") {
488
     if (data.status != "success") {
489
       $('#catalogue').raw().value = 'Failed'
489
       $('#catalogue').raw().value = 'Failed'
490
       return
490
       return

+ 2
- 2
static/functions/user.js View File

12
         }
12
         }
13
 
13
 
14
     } else if (to == "links") {
14
     } else if (to == "links") {
15
-        ajax.post("ajax.php?action=preview", "form", function (response) {
15
+        ajax.post("api.php?action=preview", "form", function (response) {
16
             $('#admincommentlinks').raw().innerHTML = response;
16
             $('#admincommentlinks').raw().innerHTML = response;
17
             $('#admincomment').ghide();
17
             $('#admincomment').ghide();
18
             $('#admincommentlinks').gshow();
18
             $('#admincommentlinks').gshow();
184
 function commStats(userid) {
184
 function commStats(userid) {
185
     $('.user_commstats').html('Loading&hellip;');
185
     $('.user_commstats').html('Loading&hellip;');
186
     console.log(userid);
186
     console.log(userid);
187
-    ajax.get('ajax.php?action=community_stats&userid=' + userid, function (JSONresponse) {
187
+    ajax.get('api.php?action=community_stats&userid=' + userid, function (JSONresponse) {
188
         var response = JSON.parse(JSONresponse) || false;
188
         var response = JSON.parse(JSONresponse) || false;
189
         console.log(response);
189
         console.log(response);
190
 
190
 

+ 1
- 1
static/functions/user_notifications.js View File

131
 function clear(type, id) {
131
 function clear(type, id) {
132
   $.ajax({
132
   $.ajax({
133
     type: 'POST',
133
     type: 'POST',
134
-    url: 'ajax.php?action=clear_user_notification',
134
+    url: 'api.php?action=clear_user_notification',
135
     dataType: 'json',
135
     dataType: 'json',
136
     data: {
136
     data: {
137
       'type': type,
137
       'type': type,

Loading…
Cancel
Save