4in1_ws_web/lib/Post.php

129 lines
3.5 KiB
PHP

<?php
class Post extends model {
const DB_TABLE = 'posts';
public int $id;
public string $date;
public ?string $updateTime;
public bool $visible;
public string $shortName;
public string $sourceUrl;
protected array $texts = [];
public function edit(array $fields) {
$fields['update_time'] = date(mysql::DATETIME_FORMAT, time());
parent::edit($fields);
}
public function addText(PostLanguage $lang, string $title, string $md, string $keywords, bool $toc): ?PostText {
$html = markup::markdownToHtml($md, lang: $lang);
$text = markup::htmlToText($html);
$data = [
'title' => $title,
'lang' => $lang->value,
'post_id' => $this->id,
'html' => $html,
'text' => $text,
'md' => $md,
'toc' => $toc,
'keywords' => $keywords,
];
$db = DB();
if (!$db->insert('posts_texts', $data))
return null;
$id = $db->insertId();
$post_text = posts::getText($id);
$post_text->updateImagePreviews();
return $post_text;
}
public function registerText(PostText $postText): void {
if (array_key_exists($postText->lang->value, $this->texts))
throw new Exception("text for language {$postText->lang->value} has already been registered");
$this->texts[$postText->lang->value] = $postText;
}
public function loadTexts() {
if (!empty($this->texts))
return;
$db = DB();
$q = $db->query("SELECT * FROM posts_texts WHERE post_id=?", $this->id);
while ($row = $db->fetch($q)) {
$text = new PostText($row);
$this->registerText($text);
}
}
/**
* @return PostText[]
*/
public function getTexts(): array {
$this->loadTexts();
return $this->texts;
}
public function getText(PostLanguage|string $lang): ?PostText {
if (is_string($lang))
$lang = PostLanguage::from($lang);
$this->loadTexts();
return $this->texts[$lang->value] ?? null;
}
public function hasLang(PostLanguage $lang) {
$this->loadTexts();
foreach ($this->texts as $text) {
if ($text->lang == $lang)
return true;
}
return false;
}
public function hasSourceUrl(): bool {
return $this->sourceUrl != '';
}
public function getUrl(PostLanguage|string|null $lang = null): string {
$buf = $this->shortName != '' ? "/articles/{$this->shortName}/" : "/articles/{$this->id}/";
if ($lang) {
if (is_string($lang))
$lang = PostLanguage::from($lang);
if ($lang != PostLanguage::English)
$buf .= '?lang=' . $lang->value;
}
return $buf;
}
public function getTimestamp(): int {
return (new DateTime($this->date))->getTimestamp();
}
public function getUpdateTimestamp(): ?int {
if (!$this->updateTime)
return null;
return (new DateTime($this->updateTime))->getTimestamp();
}
public function getDate(): string {
return date('j M', $this->getTimestamp());
}
public function getYear(): int {
return (int)date('Y', $this->getTimestamp());
}
public function getFullDate(): string {
return date('j F Y', $this->getTimestamp());
}
public function getDateForInputField(): string {
return date('Y-m-d', $this->getTimestamp());
}
}