-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathBlog.php
More file actions
314 lines (245 loc) · 8.06 KB
/
Blog.php
File metadata and controls
314 lines (245 loc) · 8.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
namespace App\Libraries;
use App\Entities\Post;
use App\Exceptions\BlogException;
use CodeIgniter\Exceptions\PageNotFoundException;
use Config\Blog as BlogConfig;
use League\CommonMark\CommonMarkConverter;
use Throwable;
/**
* Class Blog
*
* Handles reading and parsing content posts.
* Posts are markdown files versioned with the
* site repo, with a simple yaml header section
* to define meta data.
*/
class Blog
{
/**
* @var BlogConfig
*/
protected $config;
public function __construct()
{
$this->config = config(BlogConfig::class);
}
/**
* Gets the posts, sorted by most recent first.
* If $category is present, will locate within a
* subfolder of that name.
*
* @return list<Post>
*
* @throws BlogException
*/
public function getRecentPosts(int $limit = 5, int $offset = 0, ?string $category = null)
{
$cacheKey = "blog_files_{$offset}_{$limit}_{$category}";
if (! $posts = cache($cacheKey)) {
helper('filesystem');
if (! is_dir($this->config->contentPath)) {
log_message('error', 'Blog Content Path is not a valid directory: ' . $this->config->contentPath);
throw BlogException::forInvalidContent();
}
// Restrict files to the main directory for now - no sub-directories.
$files = directory_map($this->config->contentPath, 1);
// We only want .md files.
$files = array_filter($files, static fn ($file) => substr(strrchr($file, '.'), 1) === 'md');
if ($files === []) {
throw BlogException::forInvalidContent();
}
// Don't trust filesystem, order by date.
arsort($files);
// Get the current page's worth.
$files = array_splice($files, $offset, $limit);
$posts = [];
foreach ($files as $file) {
$temp = $this->readPost($this->config->contentPath, $file);
// Only collect from the correct category.
if ($category !== null && ! in_array($category, $temp->tags, true)) {
continue;
}
$posts[] = $temp;
}
cache()->save($cacheKey, $posts);
}
return $posts;
}
public function getPopularPosts(int $limit = 5)
{
helper('filesystem');
$path = WRITEPATH . 'blog_visits.txt';
if (! is_file($path)) {
return [];
}
$lines = unserialize(file_get_contents($path));
if (! (is_countable($lines) ? count($lines) : 0)) {
return [];
}
arsort($lines);
$slugs = array_slice($lines, 0, $limit);
// Restrict files to the main directory for now - no sub-directories.
$files = directory_map($this->config->contentPath, 1);
// We only want .md files.
$files = array_filter($files, static fn ($file) => substr(strrchr($file, '.'), 1) === 'md');
$posts = [];
foreach ($files as $file) {
foreach ($slugs as $slug => $count) {
try {
if (stripos($file, $slug) !== false) {
$posts[$count] = $this->getPost($slug);
}
}
// Don't fail if we can't find the file anymore...
catch (Throwable $e) {
continue;
}
}
}
// It seems to lose it's ordering above,
// so ensure we're sorted.
krsort($posts);
return $posts;
}
/**
* Gets a single post
*
* @return Post|null
*/
public function getPost(string $slug)
{
$cacheKey = "blog_post_{$slug}";
if (! $post = cache($cacheKey)) {
$files = glob("{$this->config->contentPath}*.{$slug}.md");
if ($files === [] || $files === false) {
throw PageNotFoundException::forPageNotFound();
}
$post = $this->readPost($this->config->contentPath, basename($files[0]));
cache()->save($cacheKey, $post);
}
return $post;
}
/**
* Records a single "hit", or visit to a page
* so that we can track "popular" pages.
*/
public function recordVisit(string $slug)
{
$path = WRITEPATH . 'blog_visits.txt';
$lines = file_exists($path)
? unserialize(file_get_contents($path))
: [];
if (! isset($lines[$slug])) {
$lines[$slug] = 1;
} else {
$lines[$slug]++;
}
// Update our records
helper('filesystem');
write_file($path, serialize($lines));
}
/**
* Displays the HTML "widget" for the list of recent posts
* in the sidebar.
*/
public function recentPostsWidget(int $limit, string $view = 'blog/_widget'): string
{
$posts = $this->getRecentPosts($limit);
if ($posts === []) {
return '';
}
return view($view, [
'title' => 'Recent Posts',
'rows' => $posts,
]);
}
/**
* Displays the HTML "widget" for the list of popular posts
* in the sidebar.
*/
public function popularPostsWidget(int $limit): string
{
$posts = $this->getPopularPosts($limit);
if (is_countable($posts) ? count($posts) : 0) {
return '';
}
return view('blog/_widget', [
'title' => 'Popular Posts',
'rows' => $posts,
]);
}
/**
* Reads in a post from file and parses it
* into a Post Entity.
*
* @return Post|null
*/
protected function readPost(string $folder, string $filename)
{
$contents = file($folder . $filename);
if ($contents === [] || $contents === false) {
return null;
}
$post = new Post();
// Get slug and date
preg_match('|^([\d-]+).(\S+).md$|i', $filename, $matches);
if ($matches === []) {
return null;
}
$post->date = $matches[1];
$post->slug = $matches[2];
// Get the attributes from the front-matter of the file (between lines with ---)
$inFrontMatter = false;
$inBody = false;
$body = [];
foreach ($contents as $line) {
if (trim($line) === '---') {
$inFrontMatter = ! $inFrontMatter;
if (! $inFrontMatter) {
$inBody = true;
}
continue;
}
if (! $inBody) {
$key = substr($line, 0, strpos($line, ':'));
$post->{$key} = trim(substr($line, strpos($line, ':') + 1));
continue;
}
$body[] = trim($line);
}
$post->body = implode("\n", $body);
// Convert body using Markdown
$markdown = new CommonMarkConverter();
$post->html = $markdown->convert($post->body);
$post->html = $this->parseVideoTags($post->html);
return $post;
}
/**
* Parses the post body for our custom video tags
* and provides embeds for the video.
*
* Embed syntax:
* !video[ https://www.youtube.com/watch?v=1GYoEMiXcX0&feature=youtu.be ]
*
* @return list<string>|string|null
*/
protected function parseVideoTags(?string $html = null)
{
helper('video');
// Since the plugin doesn't support video embeds, yet,
// wire our own up. The syntax for video embeds is
// ![[ https://youtube.com/watch?v=xlkjsdfhlk ]]
$result = preg_match_all('|!video\[([\s\w:/.?=&;]*)\]|i', $html, $matches);
if ($result < 1) {
return $html;
}
for ($i = 0; $i < count($matches) - 1; $i++) {
if (empty($matches[0]) || empty($matches[1])) {
continue;
}
$html = str_replace($matches[0][$i], embedVideo($matches[1][$i]), $html);
}
return $html;
}
}