-
Notifications
You must be signed in to change notification settings - Fork 20
/
PageListener.php
560 lines (468 loc) · 14.8 KB
/
PageListener.php
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
<?php
namespace V17Development\FlarumSeo\Listeners;
// FlarumSEO classes
use V17Development\FlarumSeo\Managers\Discussion;
use V17Development\FlarumSeo\Managers\Page;
use V17Development\FlarumSeo\Managers\Profile;
use V17Development\FlarumSeo\Managers\QADiscussion;
use V17Development\FlarumSeo\Managers\Tag;
// Flarum classes
use Flarum\Frontend\Document;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\Discussion\DiscussionRepository;
use Flarum\User\UserRepository;
// Laravel classes
use Psr\Http\Message\ServerRequestInterface;
/**
* Class PageListener
* @package V17Development\FlarumSeo\Listeners
*/
class PageListener
{
// Config
protected $config;
protected $applicationUrl;
// Settings
protected $settings;
protected $discussionRepository;
protected $userRepository;
protected $enabled_extensions;
// Document
protected $flarumDocument;
// Server request data
protected $serverRequest;
private $requestType = null;
private $canonicalUrl = null;
// Schema.org LD JSON
protected $schemaArray = [
'@context' => 'http://schema.org',
'@type' => 'WebPage'
];
protected $schemaBreadcrumb = [];
// Meta data with property tags
protected $metaProperty;
protected $discussionType = 1; // Special Google results as default, check check readme for different results
/**
* PageListener constructor.
*
* @param SettingsRepositoryInterface $settings
* @param DiscussionRepository $discussionRepository
* @param UserRepository $userRepository
*/
public function __construct(SettingsRepositoryInterface $settings, DiscussionRepository $discussionRepository, UserRepository $userRepository)
{
// Get Flarum settings
$this->settings = $settings;
// Get Discussion Repository
$this->discussionRepository = $discussionRepository;
// Get User Repository
$this->userRepository = $userRepository;
// Get Flarum config
$this->config = app('flarum.config');
// Set forum base URL
$this->applicationUrl = $this->config['url']; // Set site url
// List enabled extensions
$this->enabled_extensions = json_decode($this->settings->get("extensions_enabled"), true);
// Fancy SEO question-answer?
$this->discussionType = $this->settings->get("seo_post_crawler") === '1' ? 2 : 1;
// When Flarum likes is disabled, then automatically index as default discussion page
if(!$this->extensionEnabled("flarum-likes"))
{
$this->discussionType = 1;
}
// Settings debug settings: var_dump($this->settings->all());exit;
}
/**
* Get current Flarum document and current Server Request
*
* @param Document $flarumDocument
* @param ServerRequestInterface $serverRequestInterface
*/
public function __invoke(Document $flarumDocument, ServerRequestInterface $serverRequestInterface)
{
// Flarum document
$this->flarumDocument = $flarumDocument;
// Current Server Request
$this->serverRequest = $serverRequestInterface;
// Default site tags
$this->setSiteTags();
// Check out type of page
$this->determine();
// Finish process
$this->finish();
}
/**
* Determine the current page type
*/
private function determine()
{
// Request type
$this->requestType = substr($this->serverRequest->getUri()->getPath(), 1, 2);
// Query params
$queryParams = $this->serverRequest->getQueryParams();
// User profile page
if($this->requestType === 'u/') {
new Profile($this, $this->userRepository, isset($queryParams['username']) ? $queryParams['username'] : false);
}
// Tag page
else if($this->requestType === 't/') {
new Tag($this,isset($queryParams['slug']) ? $queryParams['slug'] : false);
}
// Friends Of Flarum pages
else if($this->requestType === 'p/') {
new Page($this, isset($queryParams['id']) ? $queryParams['id'] : false);
}
// Default SEO (no fancy QA layout)
else if($this->requestType === 'd/' && $this->discussionType === 1) {
new Discussion($this, $this->discussionRepository, isset($queryParams['id']) ? $queryParams['id'] : false);
}
// QuestionAnswer page
else if($this->requestType === 'd/' && $this->discussionType === 2) {
new QADiscussion($this, $this->discussionRepository, isset($queryParams['id']) ? $queryParams['id'] : false);
}
// Home page/discussion overview page
else if($this->requestType === "" || $this->requestType === "al") {
$this->setDescription($this->settings->get('forum_description'));
$this->setKeywords($this->settings->get('forum_keywords'));
$this->setTitle($this->settings->get('forum_title'));
$this->setUrl();
$this->setCanonicalUrl('');
// Update meta tag URL when it's the discussion overview page
if($this->requestType === "al" && $this->settings->get('default_route') !== '/all') {
$this->setUrl('/all');
$this->setCanonicalUrl('/all');
}
}
}
/**
* Default site meta tags
* Available for all webpages
*/
private function setSiteTags()
{
$applicationName = $this->settings->get('forum_title');
$applicationDescription = $this->settings->get('forum_description');
$applicationFavicon = $this->settings->get('favicon_path');
$applicationLogo = $this->settings->get('logo_path');
$applicationSeoSocialMediaImage = $this->settings->get('seo_social_media_image_path');
$this
// Add application name
->setMetaTag('application-name', $applicationName)
->setMetaPropertyTag('og:site_name', $applicationName)
->setMetaPropertyTag('og:type', 'website')
// Robots, follow please! :)
->setMetaTag('robots', 'index, follow')
// Twitter card
->setMetaTag('twitter:card', 'summary');
// Add application information
$this->setSchemaJson('publisher', [
"@type" => "Organization",
"name" => $applicationName,
"url" => $this->applicationUrl,
"description" => $applicationDescription,
"logo" => $applicationLogo ? $this->applicationUrl . '/assets/' . $applicationLogo : null
]);
// Set image
if($applicationSeoSocialMediaImage !== null)
{
$this->setImage($this->applicationUrl . '/assets/' . $applicationSeoSocialMediaImage);
}
// Fallback to the logo
else if($applicationLogo !== null)
{
$this->setImage($this->applicationUrl . '/assets/' . $applicationLogo);
}
// Fallback to the favicon
else if($applicationFavicon !== null)
{
$this->setImage($this->applicationUrl . '/assets/' . $applicationFavicon);
}
}
/**
* Finish process and output language, meta property tags, canonical urls & Schema.org json
*/
private function finish()
{
// Add language attribute to html tag
$this->flarumDocument->language = $this->serverRequest->getAttribute('locale');
// Write meta property tags
foreach ($this->metaProperty as $name => $content) {
$this->flarumDocument->head[] = '<meta property="'.e($name).'" content="'.e($content).'">';
}
// Add canonical url
if($this->canonicalUrl !== null)
{
$this->flarumDocument->head[] = '<link rel="canonical" href="'. $this->canonicalUrl .'">';
}
// Add schema.org json
$this->flarumDocument->head[] = $this->writeSchemesOrgJson();
}
/**
* Schema.org json
*/
private function writeSchemesOrgJson()
{
$show = [];
$show[] = $this->schemaArray;
if(count($this->schemaBreadcrumb) > 0) {
$show[] = $this->schemaBreadcrumb;
}
$show[] = $this->addSearchBar();
return '<script type="application/ld+json">' . json_encode($show, true) . '</script>';
}
/**
* Add the potential search bar
*
* @return array
*/
private function addSearchBar()
{
return [
'@context' => 'http://schema.org',
'@type' => 'WebSite',
'url' => $this->applicationUrl . '/',
'potentialAction' => [
"@type" => "SearchAction",
"target" => $this->applicationUrl . '/?q={search_term_string}',
"query-input" => 'required name=search_term_string'
]
];
}
/**
* @param $key
* @param $value
* @return PageListener
*/
public function setMetaPropertyTag($key, $value)
{
$this->metaProperty[$key] = $value;
return $this;
}
/**
* @param $key
* @param $value
* @return PageListener
*/
public function setMetaTag($key, $value)
{
$this->flarumDocument->meta[$key] = $value;
return $this;
}
/**
* @param $key
* @param $value
* @return PageListener
*/
public function setSchemaJson($key, $value)
{
$this->schemaArray[$key] = $value;
return $this;
}
/**
* @param $discussion
*/
public function setSchemaBreadcrumb($discussion)
{
$tags = $discussion->getAttribute("tags");
$list = [];
// Foreach tags
$number = 0;
foreach ($tags as $tag)
{
$number++;
$list = [
'@type' => 'ListItem',
'name' => $tag->getAttribute('name'),
'item' => $this->applicationUrl . '/t/' . $tag->getAttribute('slug'),
'position' => $number
];
}
$this->schemaBreadcrumb = [
"@context" => "http://schema.org",
"@type" => "BreadcrumbList",
"itemListElement" => $list
];
}
/**
* @param $name
* @return bool
*/
public function extensionEnabled($name)
{
return in_array($name, $this->enabled_extensions);
}
/**
* Current page URL
*
* @param $path
* @return PageListener
*/
public function setUrl($path = '')
{
$this->setMetaTag('twitter:url', $this->applicationUrl . $path);
$this->setMetaPropertyTag('og:url', $this->applicationUrl . $path);
$this->setSchemaJson("url", $this->applicationUrl . $path);
return $this;
}
/**
* Set canonical url
*
* @param $path
* @return PageListener
*/
public function setCanonicalUrl($path)
{
$this->canonicalUrl = $this->applicationUrl . $path;
return $this;
}
/**
* @param $path
* @return string
*/
public function getApplicationPath($path)
{
return $this->applicationUrl . $path;
}
/**
* Get user data
*
* @param $userId
* @return mixed
*/
public function getUser($userId)
{
return $this->userRepository->findOrFail($userId);
}
/**
* Set title
*
* @param $title
* @return PageListener
*/
public function setTitle($title)
{
$this
->setMetaPropertyTag('og:title', $title)
->setMetaTag('twitter:title', $title);
return $this;
}
/**
* Set description
*
* @param $content
* @return PageListener
*/
public function setDescription($content)
{
$description = strip_tags($content);
$description = trim(preg_replace('/\s+/', ' ', mb_substr($description, 0, 157))) . (mb_strlen($description) > 157 ? '...' : '');
$this
->setMetaPropertyTag('og:description', $description)
->setMetaTag('description', $description)
->setMetaTag('twitter:description', $description)
->setSchemaJson("description", $description);
if($this->requestType === 'd/')
{
$this->setSchemaJson("headline", $description);
}
return $this;
}
/**
* Set page keywords
*
* @param $keywords
*/
public function setKeywords($keywords)
{
if(!$keywords || $keywords === "") return;
// Possible array of keywords
if(is_array($keywords)) {
$keywords = implode(", ", $keywords);
}
// Set keywords meta tag
$this->setMetaTag('keywords', $keywords);
}
/**
* Set setImageFromContent
*
* @param $content
* @return PageListener
*/
public function setImageFromContent($content = null)
{
// Check post content is not empty
if($content !== null) {
// Read Post content and filter image url
$pattern = '/(http.*\.)(jpe?g|png|[tg]iff?|svg)/';
// Use image from post for social media og:image
if (preg_match_all($pattern, $content, $matches) && count($matches) > 0) {
$contentImage = $matches[0][0];
if ($contentImage !== null) {
$this->setImage($contentImage);
return $this;
}
}
}
return $this;
}
/**
* Set published on
*
* @param $published
* @return PageListener
*/
public function setPublishedOn($published)
{
$date = (new \DateTime($published))->format("c");
$this
->setMetaTag('article:published_time', $date)
->setSchemaJson('datePublished', $date);
return $this;
}
/**
* Set updated time
* Only used when a discussion has newer posts
*
* @param $updated
* @return PageListener
*/
public function setUpdatedOn($updated)
{
$date = (new \DateTime($updated))->format("c");
$this
->setMetaTag('article:updated_time', $date)
->setSchemaJson('dateModified', $date);
return $this;
}
/**
* Set page image
*
* @param $imagePath
* @return PageListener
*/
public function setImage($imagePath)
{
return $this
->setMetaPropertyTag('og:image', $imagePath)
->setMetaTag('twitter:image', $imagePath)
->setSchemaJson('image', $imagePath);
}
/**
* Set page title
*
* @param $title
*/
public function setPageTitle($title)
{
$this->flarumDocument->title = $title;
return $this;
}
/**
* Return server request
*
* @return mixed
*/
public function getServerRequest() {
return $this->serverRequest;
}
}