Browse Source

fix bug with cached comment stats

max.mehl 5 months ago
parent
commit
16e44ab3f4
No account linked to committer's email address
1 changed files with 25 additions and 4 deletions
  1. 25
    4
      themes/hugo-mastodon-comments/static/comments/getcomments.php

+ 25
- 4
themes/hugo-mastodon-comments/static/comments/getcomments.php View File

@@ -5,7 +5,7 @@ require_once 'config.php';
5 5
 $instance = $config['mastodon-instance'];
6 6
 $uid = $config['user-id'];
7 7
 $searchurl = $config['search-url'];
8
-$search = isset($_GET['search']) ? $_GET['search'] : '';
8
+$search = isset($_GET['search']) ? strtolower($_GET['search']) : '';
9 9
 $debug_on = $config['debug'];
10 10
 /* cache files */
11 11
 $ctt = $config['cache_toots'];
@@ -40,6 +40,14 @@ function write_db($db, $data, $id) {
40 40
   $encoded = json_encode($file, JSON_PRETTY_PRINT);
41 41
   file_put_contents($db, $encoded, LOCK_EX);
42 42
 }
43
+/* delete file */
44
+function delete_db($db, $id) {
45
+  // if $id is given, it's a comments file. Replace placeholder in filename
46
+  if ($id) {
47
+    $db = str_replace('%id', $id, $db);
48
+  }
49
+  unlink($db);
50
+}
43 51
 /* access data from file */
44 52
 function read_db($db, &$data, $cachetime, &$cachebreak, $id) {
45 53
   // if $id is given, it's a comments file. Replace placeholder in filename
@@ -185,11 +193,19 @@ if ($cachebreak) {
185 193
   debug("Toots cache is up-to-date");
186 194
 }
187 195
 
188
-/* prepare empty $result array with structure */
189
-$result = ['comments' => [], 'stats' => ['reblogs' => 0, 'favs' => 0, 'replies' => 0, 'url' => '', 'root' => 0]];
196
+// create empty $result
197
+$result_empty = ['comments' => [], 'stats' => ['reblogs' => 0, 'favs' => 0, 'replies' => 0, 'url' => '', 'root' => 0]];
198
+$result = $result_empty;
190 199
 
191 200
 /* check if URL from $search exists in $toots */
192
-$id = array_keys(array_column($toots, 'url'), strtolower($search));
201
+$id = array_keys(
202
+  array_filter(
203
+    array_column($toots, 'url'),
204
+    function ($value) use ($search) {
205
+      return (strpos($value, $search) !== false);
206
+    }
207
+  )
208
+);
193 209
 if (empty($id)) {
194 210
   debug("Blog URL \"$search\" has not been found");
195 211
 } else {
@@ -202,6 +218,11 @@ if (empty($id)) {
202 218
 
203 219
   if ($cachebreak) {
204 220
     debug("Comments cache for $id outdated. Checking for new comments");
221
+    // delete old cache file, otherwise the stats would add up
222
+    delete_db($dbc, $id);
223
+    // re-create empty $result and new cache file
224
+    $result = $result_empty;
225
+    read_db($dbc, $result, $ctc, $cachebreak, $id);
205 226
     /* Extract comments and stats from toot */
206 227
     tootContext($instance, $id, $result);
207 228
     tootStats($instance, $id, $result);

Loading…
Cancel
Save