-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfunctions.php
More file actions
1871 lines (1746 loc) · 47 KB
/
functions.php
File metadata and controls
1871 lines (1746 loc) · 47 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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace KVSun\Functions;
use \shgysk8zer0\Core\{PDO, Console, Listener, Gravatar, URL, Headers, FormData};
use \shgysk8zer0\DOM\{HTML, HTMLElement, RSS};
use \KVSun\KVSAPI\{
Home,
Category,
Article,
Classifieds,
Contact,
Picture,
BusinessDirectory,
Abstracts\Content as KVSAPI
};
use \shgysk8zer0\Core_API\{Abstracts\HTTPStatusCodes as HTTP};
use \shgysk8zer0\Login\{User};
use \shgysk8zer0\PHPCrypt\{PublicKey, PrivateKey, KeyPair, AES};
use \SplFileObject as File;
use const \KVSun\Consts\{
DEBUG,
DB_CREDS,
PASSWD,
PUBLIC_KEY,
PRIVATE_KEY,
DOMAIN,
ICONS,
COMPONENTS,
EXT,
PAGES_DIR,
PAGE_COMPONENTS,
HTML_TEMPLATES,
SPRITES,
LOGO,
LOGO_SIZE,
DATE_FORMAT,
DATETIME_FORMAT,
PASSWORD_RESET_VALID,
CRLF
};
/**
* Builds all the things!
* @param Array $path URL path as an array
* @return DOMDocument The resulting document build
*/
function build_dom(): \DOMDocument
{
if (@file_exists(DB_CREDS) and PDO::load(DB_CREDS)->connected) {
HTMLElement::$import_path = COMPONENTS;
$dom = HTML::getInstance();
// If IE, show update and hide rest of document
$dom->body->ifIE(
file_get_contents(COMPONENTS . 'update.html')
. '<div style="display:none !important;">'
);
$dom->body->class = 'flex row wrap';
array_map([$dom->body, 'importHTMLFile'], HTML_TEMPLATES);
add_main_menu($dom->body);
load(...PAGE_COMPONENTS);
// Close `</div>` created in [if IE]
$dom->body->ifIE('</div>');
} else {
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadHTMLFile(COMPONENTS . 'install.html');
}
Listener::load();
return $dom;
}
/**
* Get Page content from URL
* @param URL $url Instance of URL class
* @return KVSAPI Article, Category, Classifieds, etc.
*/
function get_page(URL $url): KVSAPI
{
$path = explode('/', trim($url->path));
$path = array_filter($path);
$path = array_values($path);
$pdo = PDO::load(DB_CREDS);
if (empty($path)) {
// This would be a request for home
// $categories = \KVSun\get_categories();
$page = new Home($pdo, "$url", get_categories('url'));
} elseif (count($path) === 1) {
switch ($path[0]) {
case 'classifieds':
$page = new Classifieds($pdo, '../Classifieds');
break;
case 'contacting-us':
$page = new Contact($pdo, '/contacting-us');
break;
case 'businessdirectory':
$page = new BusinessDirectory($pdo, '/businessdirectory');
break;
default:
$page = new Category($pdo, "$url");
}
} elseif (count($path) === 2) {
$page = new Article($pdo, "$url");
}
return $page;
}
/**
* Wrapper function for `mail` as HTML
* @param Array $to ["user1@domain.com", ...]
* @param String $subject Subject of the email to be sent
* @param DOMDocuemnt $message Body of the email as a DOMDocuemnt
* @param array $headers ['From' => 'admin@domain.com', ...]
* @return Bool Whether or not the email sent
*/
function html_email(
Array $to,
String $subject,
\DOMDocument $message,
Array $headers = array()
): Bool
{
$encoding = $messsage->encoding ?? 'utf-8';
$headers['Content-Type'] = "text/html;charset={$encoding}";
return email($to, $subject, $message->saveHTML(), $headers);
}
/**
* Wrapper function for `mail`
* @param Array $to ["user1@domain.com", ...]
* @param String $subject Subject of the email to be sent
* @param String $message Body of the email
* @param array $headers ['From' => 'admin@domain.com', ...]
* @return Bool Whether or not the email sent
*/
function email(
Array $to,
String $subject,
String $message,
Array $headers = array()
): Bool
{
$headers = array_map(function(String $name, String $value): String
{
return "{$name}: {$value}";
}, array_keys($headers), array_values($headers));
$message = str_replace(PHP_EOL, CRLF, $message);
$message = wordwrap($message, 70, CRLF);
return mail(join(', ', $to), $subject, $message, join(CRLF, $headers));
}
/**
* Custom mail function using cURL and cryptographic signature for authentication
* @param String $to Receiver, or receivers of the mail
* @param String $subject Subject of the email to be sent
* @param String $message Message to be sent (use \r\n)
* @param string $additional_headers Optional headers: e.g. "From: user@domain.com" use \r\n
* @param string $additional_paramaters Pass additional flags as command line options
* @return Bool Whether or not it sent
* @see https://secure.php.net/manual/en/function.mail.php
* @todo Remove once email is working properly
*/
function mail(
String $to,
String $subject,
String $message,
String $additional_headers = '',
String $additional_paramaters = ''
): Bool
{
try {
$sent = true;
$url = new URL('http://kvsun.com:8888/mail.php');
$ch = curl_init($url);
$time = new \DateTime();
$private = PrivateKey::importFromFile(PRIVATE_KEY, PASSWD);
$email = [
'to' => $to,
'subject' => $subject,
'message' => $message,
'headers' => $additional_headers,
'params' => $additional_paramaters,
'sent' => $time->format(\Datetime::W3C),
];
$email['sig'] = $private->sign(json_encode($email));
if (DEBUG) {
return true;
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_POST => true,
CURLOPT_PORT => $url->port,
CURLOPT_POSTFIELDS => $email,
]);
if (curl_exec($ch)) {
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== HTTP::OK) {
throw new \Exception("<{$url}> {$status}");
}
} else {
throw new \RuntimeException(curl_error($ch));
}
} catch (\Throwable $e) {
$sent = false;
trigger_error($e->getMessage());
} finally {
curl_close($ch);
return $sent;
}
}
/**
* Send password reset emails
* @param User $user The user attempting to reset password
* @return Bool Whether or not the email sent
*/
function password_reset_email(User $user): Bool
{
if (isset($user->email, $user->name, $user->username)) {
$dom = new HTML();
$date = new \DateTime();
$url = new URL(DOMAIN);
$key = PrivateKey::importFromFile(PRIVATE_KEY, PASSWD);
$url->path = 'password_reset.php';
$url->query->user = $user->username;
$url->query->time = $date->getTimestamp();
$url->query->token = urlencode($key->sign(json_encode([
'user' => $user->username,
'time' => $date->format(DATETIME_FORMAT),
])));
$expires = clone($date);
$expires->modify(PASSWORD_RESET_VALID);
$dom->body->append(
'h2',
"A password reset request has been requested for {$user->username} on "
)->append('a', DOMAIN, ['href' => DOMAIN]);
$dom->body->append('br');
$dom->body->append('p', 'If you did not request a password reset, simply ignore this email.');
$dom->body->append('br');
$p = $dom->body->append('p');
$p->append('span', 'Otherwise, click ');
$link = $p->append('a', 'here');
$p->append('span', ' to reset your password');
$dom->body->append('br');
$dom->body->append('p', "This link will expire on {$expires->format(DATE_FORMAT)}");
$link->href = $url;
return html_email(
["{$user->name} <{$user->email}>"],
'Password reset',
$dom,
['From' => 'no-reply@kvsun.com']
);
} else {
return false;
}
}
/**
* Modifies a date to be the date of the most recent publication
* @param DateTime $date Date to modify
* @return DateTime Modified date
*/
function get_pub_date(\DateTime $date = null): \DateTime
{
if (is_null($date)) {
$date = new \DateTime('now');
} else {
$date = clone($date);
}
$dow = intval($date->format('N'));
// If $dow !== 3 ('Wednesday'), modify to be closest Wednesday
if ($dow !== 3) {
$date->modify(3 - $dow . ' days');
}
return $date;
}
/**
* Appends an E-Edition link to $parent element
* @param HTMLElement $parent Element to append to
* @param Array $attrs Array of attributes to set on link
* @param DateTime $date Optional date to create link for
* @return HTMLElement E-Edition link element
*/
function add_e_edition(
HTMLElement $parent = null,
Array $attrs = array(),
\DateTime $date = null
): HTMLElement
{
if (is_null($parent)) {
$dom = new HTML();
$parent = $dom->body;
}
if (is_null($date)) {
$date = new \DateTime('now');
}
$url = new URL('https://cloud.kvsun.com/s/W3Dfy1RkyAzvRAO');
$url->query->path = get_pub_date($date)->format('Y/m/d');
$add = $parent->append('a', null, array_merge($attrs, [
'href' => $url,
'title' => 'E-Edition',
'id' => 'E-Edition-link',
]));
$add->append('span', 'E-Edition ', ['class' => 'desktop-only']);
use_icon('section-e-edition', $add, ['class' => 'icon']);
return $add;
}
/**
* Create or update a post
* @param FormData $post Data for post submitted by form
* @param PDO $pdo Database instance
* @return Bool Whether or not the post was created / updated
*/
function add_post(FormData $post, PDO $pdo): Bool
{
if (! isset($post->author, $post->title, $post->content, $post->category)) {
return false;
}
$pdo->beginTransaction();
$stm = $pdo->prepare(
'INSERT INTO `posts` (
`sort`,
`cat-id`,
`title`,
`author`,
`content`,
`posted`,
`updated`,
`draft`,
`isFree`,
`url`,
`img`,
`posted_by`,
`keywords`,
`description`
) VALUES (
:sort,
:cat,
:title,
:author,
:content,
CURRENT_DATE,
CURRENT_TIMESTAMP,
:draft,
:free,
:url,
:img,
:posted,
:keywords,
:description
) ON DUPLICATE KEY UPDATE
`sort` = COALESCE(:sort, `sort`),
`cat-id` = COALESCE(:cat, `cat-id`),
`title` = COALESCE(:title, `title`),
`author` = COALESCE(:author, `author`),
`content` = COALESCE(:content, `content`),
`updated` = CURRENT_TIMESTAMP,
`draft` = :draft,
`isFree` = :free,
`img` = :img,
`keywords` = COALESCE(:keywords, `keywords`),
`description` = COALESCE(:description, `description`);'
);
try {
if (! (category_exists($post->category) or make_category($post->category))) {
return false;
}
$user = restore_login();
if (isset($post->url) and filter_var($post->url, FILTER_VALIDATE_URL, [
'flags' => FILTER_FLAG_PATH_REQUIRED,
])) {
$url = $url = explode('/', trim($post->url, '/'));
$url = end($url);
} else {
$url = strtolower(preg_replace(
'/[^A-z\d\-]/',
null,
str_replace([' ', '^'], ['-', null], $post->title)
));
}
$stm->title = utf8_encode(strip_tags($post->title));
$stm->sort = $post->sort ?? 1;
$stm->cat = get_cat_id($post->category);
$stm->author = utf8_encode(strip_tags($post->author));
$stm->draft = isset($post->draft) and $user->hasPermission('skipApproval');
$stm->free = isset($post->free);
$stm->url = trim($url, '/');
$stm->posted = $user->id;
$stm->keywords = utf8_encode(trim($post->keywords)) ?? null;
$stm->description = utf8_encode(trim($post->description)) ?? null;
$article_dom = new \DOMDocument('1.0', 'UTF-8');
$post->content = utf8_from_word($post->content);
libxml_use_internal_errors(true);
$article_dom->loadHTML("<div>$post->content</div>");
libxml_clear_errors();
if ($figures = $article_dom->getElementsByTagName('figure')) {
$picture = new Picture($pdo);
$main_img = null;
foreach ($figures as $figure) {
if ($figure->hasAttribute('data-image-id')) {
if (is_null($main_img)) {
$main_img = $figure->getAttribute('data-image-id');
}
$microdata = $picture->parseFigure($figure);
if (! empty($microdata)) {
try {
$picture->addImage($microdata, $user);
} catch (\Exception $e) {
trigger_error($e->getMessage());
}
}
$figure->removeAttribute('itemprop');
$figure->removeAttribute('itemtype');
$figure->removeAttribute('itemscope');
while ($figure->hasChildNodes() and $node = $figure->firstChild) {
$figure->removeChild($node);
}
}
}
}
$stm->img = $main_img;
$html = $article_dom->saveHTML($article_dom->documentElement->firstChild->firstChild);
$encoding = mb_detect_encoding($html);
if ($encoding !== 'UTF-8') {
$html = iconv($encoding, 'UTF-8', $post->content);
}
# Need to get the content out of DOM structured `<html><body><div>$content...`
$stm->content = $html;
unset($article_dom, $imgs, $img, $id, $url);
if ($stm->execute() and intval($stm->errorCode()) === 0) {
$pdo->commit();
return true;
} else {
throw new \RuntimeException(join(PHP_EOL, $stm->errorInfo()));
}
} catch (\Throwable $e) {
trigger_error($e->getMessage());
return false;
}
}
function utf8_from_word(String $string): String
{
$search = [ // www.fileformat.info/info/unicode/<NUM>/ <NUM> = 2018
"\xC2\xAB", // « (U+00AB) in UTF-8
"\xC2\xBB", // » (U+00BB) in UTF-8
"\xE2\x80\x98", // ‘ (U+2018) in UTF-8
"\xE2\x80\x99", // ’ (U+2019) in UTF-8
"\xE2\x80\x9A", // ‚ (U+201A) in UTF-8
"\xE2\x80\x9B", // ‛ (U+201B) in UTF-8
"\xE2\x80\x9C", // “ (U+201C) in UTF-8
"\xE2\x80\x9D", // ” (U+201D) in UTF-8
"\xE2\x80\x9E", // „ (U+201E) in UTF-8
"\xE2\x80\x9F", // ‟ (U+201F) in UTF-8
"\xE2\x80\xB9", // ‹ (U+2039) in UTF-8
"\xE2\x80\xBA", // › (U+203A) in UTF-8
"\xE2\x80\x93", // – (U+2013) in UTF-8
"\xE2\x80\x94", // — (U+2014) in UTF-8
"\xE2\x80\xA6", // … (U+2026) in UTF-8
"\xC3\x82",//,"Â",
"\xC3\x83",
" ",
];
$replacements = [
"<<",
">>",
"'",
"'",
"'",
"'",
'"',
'"',
'"',
'"',
"<",
">",
"-",
"-",
"...",
null,
null,
null,
];
return str_replace($search, $replacements, $string);
}
/**
* Get an array of User role names/ids
* @return Array [{name: $name, id: $id}, ...]
*/
function get_user_roles(): Array
{
$pdo = PDO::load(DB_CREDS);
return $pdo('SELECT `roleName` as `name`, `id` FROM `permissions`');
}
/**
* Get a User role name from its ID
* @param Int $id Role ID
* @return String Role name
*/
function get_role_name(Int $id): String
{
$pdo = PDO::load(DB_CREDS);
$stm = $pdo->prepare(
'SELECT `roleName`
FROM `permissions`
WHERE `id` = :id
LIMIT 1;'
);
$stm->bindParam('id', $id);
$stm->execute();
$role = $stm->fetchObject() ?? new \stdClass();
return $role->roleName ?? '';
}
/**
* Get a user role ID from its name
* @param String $role Role name
* @return Int Role ID
*/
function get_role_id(String $role): Int
{
$pdo = PDO::load(DB_CREDS);
$stm = $pdo->prepare(
'SELECT `id`
FROM `permissions`
WHERE `roleName` = :role
LIMIT 1;'
);
$stm->bindParam('role', $role);
$stm->execute();
$role = $stm->fetchObject() ?? new \stdClass();
return $role->id ?? 0;
}
/**
* Create or update an image using an array of data
* @param Array $data Image data
* @return Int The inserted id
* @todo Make this actually do what it is supposed to do
*/
function set_img(Array $data): Int
{
static $stm;
if (is_null($stm)) {
$stm = PDO::load(DB_CREDS)->prepare(
'INSERT INTO `images` (
`path`,
`fileFormat`,
`contentSize`,
`height`,
`width`,
`creator`,
`caption`,
`alt`,
`uploadedBy`
) VALUES (
:path,
:format,
:size,
:height,
:width,
:creator,
:caption,
:alt,
:uploader
) ON DUPLICATE KEY UPDATE
SET `caption` = :caption,
`alt` = COALESCE(:alt, `alt`),
`uploadedBy` = COALESCE(:uploader, `uploadedBy`);'
);
}
return 0;
}
/**
* Get an image id from its source / path
* @param String $src "/path/to/image"
* @return Int ID in `images` table
*/
function get_img_id(String $src): Int
{
static $stm;
if (is_null($stm)) {
$stm = PDO::load(DB_CREDS)->prepare(
'SELECT `id` FROM `images` WHERE `path` = :path LIMIT 1;'
);
}
$stm->bindParam(':path', $src);
$stm->execute();
$img = $stm->fetchObject() ?? new \stdClass();
return $img->id ?? 0;
}
/**
* Get the path to an image from its ID
* @param Int $id ID in `images` table
* @return String "/path/to/image"
*/
function get_img_path(Int $id): String
{
static $stm;
if (is_null($stm)) {
$stm = PDO::load(DB_CREDS)->prepare(
'SELECT `path` FROM `images` WHERE `id` = :id LIMIT 1;'
);
}
$stm->bindParam(':id', $id);
$stm->execute();
$img = $stm->fetchObject() ?? new \stdClass();
return $img->path ?? '';
}
/**
* Gets all data from `images` table from an ID
* @param Int $id Image's ID
* @return stdClass {"path": $path, ...}
*/
function get_img(Int $id): \stdClass
{
static $stm;
if (is_null($stm)) {
$stm = PDO::load(DB_CREDS)->prepare(
'SELECT * FROM `images` WHERE `id` = :id LIMIT 1;'
);
}
$stm->bindParam('id', $id);
$stm->execute();
if ($img = $stm->fetchObject()) {
return $img;
} else {
return new \stdClass();
}
}
/**
* Retrieves all images created from a parent images as a multi-dimensional array
* @param Int $id Parent image ID
* @return Array [$mime => ['width', 'height', 'filesize', 'path', 'format']]
*/
function get_srcset(Int $id): Array
{
static $srcset_stm = null;
if (is_null($srcset_stm)) {
$pdo = PDO::load(DB_CREDS);
$srcset_stm = $pdo->prepare('SELECT * FROM `srcset` WHERE `parentID` = :id;');
}
$srcset_stm->id = $id;
$srcset_stm->execute();
$imgs = $srcset_stm->fetchAll(PDO::FETCH_CLASS);
Console::table($imgs);
return array_reduce($imgs, function(Array $carry, \stdClass $img): Array
{
if (! array_key_exists($img->format, $carry)) {
$carry[$img->format] = [];
}
unset($img->parentId);
$carry[$img->format][] = get_object_vars($img);
return $carry;
}, []);
}
/**
* Create a `<figure>` & `<picture>` using image data from database
* @param HTMLElement $parent Element to append to
* @param Int $id Image ID
* @return HTMLElement Element with `<figure>` appended
*/
function get_picture(HTMLElement $parent, \stdClass $img): Bool
{
if (! isset($img->id) or $img->id !== 0) {
$srcset = get_srcset($img->id);
make_picture($srcset, $parent, $img->creator, $img->caption, $img);
return true;
} else {
return false;
}
}
/**
* Creates a `<dialog>` and appends it to optional $parent
* @param String $id The HTML ID attribute to set
* @param HTMLElement $parent Optional parent element
* @param Arary $attrs An array of additional attributes to set on `<dialog>`
* @return HTMLElement The `<dialog>`
*/
function make_dialog(
String $id,
HTMLElement $parent = null,
Array $attrs = array()
): HTMLElement
{
// Assume that, of there is not a parent element, the dialog is to be
// deleted rather than closed.
if (is_null($parent)) {
$dom = new HTML();
$parent = $dom->body;
$data_attr = 'data-delete';
} else {
$data_attr = 'data-close';
}
$attrs['id'] = $id;
$dialog = $parent->append('dialog', null, $attrs);
$dialog->append('nav')->append('button', null, [
'type' => 'button',
$data_attr => "#{$dialog->id}",
]);
$dialog->append('hr');
return $dialog;
}
/**
* Create a `<picture>` inside of a `<figure>` from an array of sources
* @param Array $imgs Image data, as from `Core\Image::responsiveImagesFromUpload`
* @param DOMElement $parent Parent element to append `<picture>` to
* @param String $by Who was the photo taken by?
* @param String $caption Photo cutline
* @return DOMHTMLElement `<figure><picture>...`
*/
function make_picture(
Array $imgs,
HTMLElement $parent,
String $by = null,
String $caption = null,
\stdClass $dflt_img = null
): HTMLElement
{
$dom = $parent->ownerDocument;
$figure = $parent->append('figure', null, [
'itemprop' => 'image',
'itemtype' => 'http://schema.org/ImageObject',
'itemscope' => '',
]);
$picture = $figure->append('picture');
if (isset($by) or isset($caption)) {
$cap = $figure->append('figcaption');
if (isset($by)) {
$cap->append('cite', null, [
'itemprop' => 'creator',
'itemtype' => 'http://schema.org/Person',
'itemscope' => ''
], [
['b', 'Photo by '],
['b', $by, ['itemprop' => 'name']],
]);
}
if (isset($caption)) {
$cap->append('blockquote', $caption, [
'itemprop' => 'caption',
]);
}
}
foreach($imgs as $format => $img) {
usort($img, function(Array $src1, Array $src2): Int
{
return $src2['width'] <=> $src1['width'];
});
$source = $picture->appendChild($dom->createElement('source'));
$source->setAttribute('type', $format);
$source->setAttribute('srcset', join(',', array_map(function(Array $src): String
{
return "{$src['path']} {$src['width']}w";
}, $img)));
}
if (isset(
$dflt_img,
$dflt_img->src,
$dflt_img->height,
$dflt_img->width
)) {
$img = $picture->append('img', null, [
'src' => $dflt_img->src,
'width' => $dflt_img->width,
'height' => $dflt_img->height,
'alt' => $dflt_img->alt ?? null,
'itemprop' => 'url',
]);
} else {
$img = $picture->append('img', null, [
'src' => $imgs['image/jpeg'][0]['path'],
'width' => $imgs['image/jpeg'][0]['width'],
'height' => $imgs['image/jpeg'][0]['height'],
'itemprop' => 'url',
]);
}
$figure->append('meta', null, [
'itemprop' => 'width',
'content' => $img->width,
]);
$figure->append('meta', null, [
'itemprop' => 'height',
'content' => $img->height,
]);
$figure->append('meta', null, [
'itemprop' => 'fileFormat',
'content' => 'image/jpeg',
]);
$figure->append('meta', null, [
'itemprop' => 'uploadDate',
'content' => date(\DateTime::W3C),
]);
$figure->append('meta', null, [
'itemprop' => 'contentSize',
'content' => (filesize(__DIR__ . $img->src) / 1024) . 'kB',
]);
return $figure;
}
/**
* Post a comment on an article
* @param String $url URL for post
* @param User $user User making comment
* @param String $comment The comment itself
* @param boolean $approved Automatically approve the comment?
* @param boolean $allow_html Allow HTML tags in the comment?
* @return Bool Whether or not the comment was added to table
*/
function post_comment(
String $url,
User $user,
String $comment,
Bool $approved = false,
Bool $allow_html = false
): Bool
{
try {
$path = parse_url($url, PHP_URL_PATH);
$path = trim($path, '/');
$path = explode('/', $path, 2);
$path = array_filter($path);
list($category, $post) = array_pad($path, 2, null);
$category = get_cat_id($category);
$post = get_post_id($post);
$stm = PDO::load(DB_CREDS)->prepare(
'INSERT INTO `post_comments` (
`postID`,
`catID`,
`userID`,
`approved`,
`text`
) VALUES (
:post,
:cat,
:user,
:approved,
:comment
);'
);
// $comment = strip_tags($comment);
// $comment = nl2br($comment);
// if (!$allow_html) {
// $comment = strip_tags($comment);
if (!$allow_html) {
$comment = strip_tags($comment);
}
$comment = preg_replace('/\r|\n|\t/', null, nl2br($comment));
// } else {
// $comment = html_entity_decode($comment, ENT_HTML5, 'UTF-8');
// }
$stm->bindParam(':post', $post);
$stm->bindParam(':cat', $category);
$stm->bindParam(':user', $user->id);
$stm->bindParam(':approved', $approved);
$stm->bindParam(':comment', $comment);
$stm->execute();
if (intval($stm->errorCode()) !== 0) {
throw new \Exception('SQL Error: '. join(PHP_EOL, $stm->errorInfo()));
} else {
return true;
}
} catch (\Throwable $e) {
trigger_error($e->getMessage());
return false;
}
}
/**
* Gets all comments with associated user/post/category data
* @return Array An Array of comments
*/
function get_comments(): Array
{
return (PDO::load(DB_CREDS))(
'SELECT
`post_comments`.`id` AS `ID`,
`post_comments`.`text` AS `comment`,
`post_comments`.`created`,
`post_comments`.`approved`,
`users`.`username`,
`users`.`email`,
`user_data`.`name`,
`posts`.`title` AS `Article`,
`posts`.`url` AS `postURL`,
`categories`.`url-name` AS `catURL`,
`categories`.`name` AS `category`
FROM `post_comments`
JOIN `users` ON `users`.`id` = `post_comments`.`userID`
JOIN `user_data` ON `user_data`.`id` = `post_comments`.`userID`
JOIN `posts` ON `posts`.`id` = `post_comments`.`postID`
JOIN `categories` ON `categories`.`id` = `post_comments`.`catID`;'
);
}
/**
* Delete comments by ID
* @param Int $ids A list of IDs to delete
* @return Bool Whether or not they were deleted
* @example delete_comments(1, 2, ...);
* @example delete_comments(...$ids);
*/
function delete_comments(Int ...$ids): Bool
{
$pdo = PDO::load(DB_CREDS);
$pdo->beginTransaction();
$stm = $pdo->prepare('DELETE FROM `post_comments` WHERE `id` = :id;');
$result = true;
try {
foreach ($ids as $id) {
$stm->bindParam(':id', $id);
$stm->execute();
if (intval($stm->errorCode()) !== 0) {
throw new \Exception('SQL Error: '. join(PHP_EOL, $stm->errorInfo()));
}
}
$pdo->commit();
} catch (\Throwable $e) {
trigger_error($e->getMessage());
$result = false;
} finally {
return $result;
}
}
function get_post_id(String $post): Int
{
static $q;
if (is_null($q)) {
$q = PDO::load(DB_CREDS)->prepare(
'SELECT `id` FROM `posts`
WHERE `title` = :post
OR `url` = :post
LIMIT 1;'
);
}
$q->bindParam(':post', $post);
$q->execute();
$match = $q->fetchObject();
return $match->id ?? 0;
}
/**
* Gets a category's ID from URL or name
* @param String $cat URL or name of category
* @return Int It's ID
*/
function get_cat_id(String $cat): Int
{
static $q;
if (is_null($q)) {
$q = PDO::load(DB_CREDS)->prepare(
'SELECT `id`
FROM `categories`
WHERE `name` = :cat
OR `url-name` = :cat
LIMIT 1;'