Page.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models;
  10. use ForkBB\Core\Container;
  11. use ForkBB\Models\Model;
  12. use function \ForkBB\__;
  13. abstract class Page extends Model
  14. {
  15. const FI_INDEX = 'index';
  16. const FI_USERS = 'userlist';
  17. const FI_RULES = 'rules';
  18. const FI_SRCH = 'search';
  19. const FI_REG = 'register';
  20. const FI_LOGIN = 'login';
  21. const FI_PROFL = 'profile';
  22. const FI_PM = 'pm';
  23. const FI_ADMIN = 'admin';
  24. const FI_LGOUT = 'logout';
  25. /**
  26. * Заголовки страницы
  27. * @var array
  28. */
  29. protected $pageHeaders = [];
  30. /**
  31. * Http заголовки
  32. * @var array
  33. */
  34. protected $httpHeaders = [];
  35. public function __construct(Container $container)
  36. {
  37. parent::__construct($container);
  38. $container->Lang->load('common');
  39. $formats = $container->DATE_FORMATS;
  40. $formats[0] = __($formats[0]);
  41. $formats[1] = __($formats[1]);
  42. $container->DATE_FORMATS = $formats;
  43. $formats = $container->TIME_FORMATS;
  44. $formats[0] = __($formats[0]);
  45. $formats[1] = __($formats[1]);
  46. $container->TIME_FORMATS = $formats;
  47. $this->fIndex = self::FI_INDEX; # string Указатель на активный пункт навигации
  48. $this->httpStatus = 200; # int HTTP статус ответа для данной страницы
  49. # $this->nameTpl = null; # null|string Имя шаблона
  50. # $this->titles = []; # array Массив титула страницы | setTitles()
  51. $this->fIswev = []; # array Массив info, success, warning, error, validation информации
  52. # $this->onlinePos = ''; # null|string Позиция для таблицы онлайн текущего пользователя
  53. $this->onlineDetail = false; # null|bool Формировать данные по посетителям online или нет
  54. $this->onlineFilter = true; # bool Посетители только по текущей странице или по всем
  55. # $this->robots = ''; # string Переменная для meta name="robots"
  56. # $this->canonical = ''; # string Переменная для link rel="canonical"
  57. $this->hhsLevel = 'common'; # string Ключ для $c->HTTP_HEADERS (для вывода заголовков HTTP из конфига)
  58. $this->fTitle = $container->config->o_board_title;
  59. $this->fDescription = $container->config->o_board_desc;
  60. $this->fRootLink = $container->Router->link('Index');
  61. if (1 === $container->config->b_announcement) {
  62. $this->fAnnounce = $container->config->o_announcement_message;
  63. }
  64. $this->user = $this->c->user; // передача текущего юзера в шаблон
  65. $this->pageHeader('mainStyle', 'link', 10000, [
  66. 'rel' => 'stylesheet',
  67. 'type' => 'text/css',
  68. 'href' => $this->publicLink("/style/{$this->user->style}/style.css"),
  69. ]);
  70. $now = \gmdate('D, d M Y H:i:s') . ' GMT';
  71. $this //->header('Cache-Control', 'no-cache, no-store, must-revalidate')
  72. ->header('Cache-Control', 'private, no-cache')
  73. ->header('Content-Type', 'text/html; charset=utf-8')
  74. ->header('Date', $now)
  75. ->header('Last-Modified', $now)
  76. ->header('Expires', $now);
  77. }
  78. /**
  79. * Подготовка страницы к отображению
  80. */
  81. public function prepare(): void
  82. {
  83. $this->pageHeader('commonJS', 'script', 10000, [
  84. 'src' => $this->publicLink('/js/common.js'),
  85. ]);
  86. $this->boardNavigation();
  87. $this->iswevMessages();
  88. }
  89. /**
  90. * Задает массивы главной навигации форума
  91. */
  92. protected function boardNavigation(): void
  93. {
  94. $r = $this->c->Router;
  95. $navUser = [];
  96. $navGen = [
  97. self::FI_INDEX => [
  98. $r->link('Index'),
  99. 'Index',
  100. 'Home page',
  101. ],
  102. ];
  103. if (
  104. 1 === $this->user->g_read_board
  105. && $this->user->viewUsers
  106. ) {
  107. $navGen[self::FI_USERS] = [
  108. $r->link('Userlist'),
  109. 'User list',
  110. 'List of users',
  111. ];
  112. }
  113. if (
  114. 1 === $this->c->config->b_rules
  115. && 1 === $this->user->g_read_board
  116. && (
  117. ! $this->user->isGuest
  118. || 1 === $this->c->config->b_regs_allow
  119. )
  120. ) {
  121. $navGen[self::FI_RULES] = [
  122. $r->link('Rules'),
  123. 'Rules',
  124. 'Board rules',
  125. ];
  126. }
  127. if (
  128. 1 === $this->user->g_read_board
  129. && 1 === $this->user->g_search
  130. ) {
  131. $sub = [];
  132. $sub['latest'] = [
  133. $r->link(
  134. 'SearchAction',
  135. [
  136. 'action' => 'latest_active_topics',
  137. ]
  138. ),
  139. 'Latest active topics',
  140. 'Find latest active topics',
  141. ];
  142. if (! $this->user->isGuest) {
  143. $sub['with-your-posts'] = [
  144. $r->link(
  145. 'SearchAction',
  146. [
  147. 'action' => 'topics_with_your_posts',
  148. ]
  149. ),
  150. 'Topics with your posts',
  151. 'Find topics with your posts',
  152. ];
  153. }
  154. $sub['unanswered'] = [
  155. $r->link(
  156. 'SearchAction',
  157. [
  158. 'action' => 'unanswered_topics',
  159. ]
  160. ),
  161. 'Unanswered topics',
  162. 'Find unanswered topics',
  163. ];
  164. $navGen[self::FI_SRCH] = [
  165. $r->link('Search'),
  166. 'Search',
  167. 'Search topics and posts',
  168. $sub
  169. ];
  170. }
  171. if ($this->user->isGuest) {
  172. if (1 === $this->c->config->b_regs_allow) {
  173. $navUser[self::FI_REG] = [
  174. $r->link('Register'),
  175. 'Register',
  176. 'Register',
  177. ];
  178. }
  179. $navUser[self::FI_LOGIN] = [
  180. $r->link('Login'),
  181. 'Login',
  182. 'Login',
  183. ];
  184. } else {
  185. $navUser[self::FI_PROFL] = [
  186. $this->user->link,
  187. ['User %s', $this->user->username],
  188. 'Your profile',
  189. ];
  190. if ($this->user->usePM) {
  191. $tmpPM = [];
  192. if (1 !== $this->user->u_pm) {
  193. $tmpPM[] = 'pmoff';
  194. }
  195. if ($this->user->u_pm_num_new > 0) {
  196. $tmpPM[] = 'pmnew';
  197. }
  198. $navUser[self::FI_PM] = [
  199. $r->link('PM'),
  200. $this->user->u_pm_num_new > 0 ? ['PM %s', $this->user->u_pm_num_new] : 'PM',
  201. 'Private messages',
  202. null,
  203. $tmpPM ?: null,
  204. ];
  205. }
  206. if ($this->user->isAdmMod) {
  207. $navUser[self::FI_ADMIN] = [
  208. $r->link('Admin'),
  209. 'Admin',
  210. 'Administration functions',
  211. ];
  212. }
  213. $navUser[self::FI_LGOUT] = [
  214. $r->link('Logout'),
  215. 'Logout',
  216. 'Logout',
  217. ];
  218. }
  219. if (
  220. 1 === $this->user->g_read_board
  221. && '' != $this->c->config->o_additional_navlinks
  222. ) {
  223. // position|name|link[|id]\n
  224. if (\preg_match_all('%^(\d+)\|([^\|\n\r]+)\|([^\|\n\r]+)(?:\|([^\|\n\r]+))?%m', $this->c->config->o_additional_navlinks . "\n", $matches)) {
  225. $k = \count($matches[0]);
  226. for ($i = 0; $i < $k; ++$i) {
  227. if (empty($matches[4][$i])) {
  228. $matches[4][$i] = 'extra' . $i;
  229. }
  230. if (isset($navGen[$matches[4][$i]])) {
  231. $navGen[$matches[4][$i]] = [$matches[3][$i], $matches[2][$i], $matches[2][$i]];
  232. } else {
  233. $navGen = \array_merge(
  234. \array_slice($navGen, 0, (int) $matches[1][$i]),
  235. [$matches[4][$i] => [$matches[3][$i], $matches[2][$i], $matches[2][$i]]],
  236. \array_slice($navGen, (int) $matches[1][$i])
  237. );
  238. }
  239. }
  240. }
  241. }
  242. $this->fNavigation = $navGen;
  243. $this->fNavigationUser = $navUser;
  244. }
  245. /**
  246. * Задает вывод различных сообщений по условиям
  247. */
  248. protected function iswevMessages(): void
  249. {
  250. if (
  251. 1 === $this->c->config->b_maintenance
  252. && $this->user->isAdmin
  253. ) {
  254. $this->fIswev = ['w', ['Maintenance mode enabled', $this->c->Router->link('AdminMaintenance')]];
  255. }
  256. if (
  257. $this->user->isAdmMod
  258. && $this->user->last_report_id < $this->c->reports->lastId()
  259. ) {
  260. $this->fIswev = ['i', ['New reports', $this->c->Router->link('AdminReports')]];
  261. }
  262. }
  263. /**
  264. * Возвращает title страницы
  265. * $this->pageTitle
  266. */
  267. protected function getpageTitle(array $titles = []): string
  268. {
  269. if (empty($titles)) {
  270. $titles = $this->titles;
  271. }
  272. $titles[] = ['%s', $this->c->config->o_board_title];
  273. return \implode(__('Title separator'), \array_map('\\ForkBB\\__', $titles));
  274. }
  275. /**
  276. * Задает/получает заголовок страницы
  277. */
  278. public function pageHeader(string $name, string $type, int $weight = 0, array $values = null) /* : mixed */
  279. {
  280. if (null === $values) {
  281. return $this->pageHeaders["{$name}_{$type}"] ?? null;
  282. } else {
  283. $this->pageHeaders["{$name}_{$type}"] = [
  284. 'weight' => $weight,
  285. 'type' => $type,
  286. 'values' => $values
  287. ];
  288. return $this;
  289. }
  290. }
  291. /**
  292. * Возвращает массива заголовков страницы
  293. * $this->pageHeaders
  294. */
  295. protected function getpageHeaders(): array
  296. {
  297. if ($this->canonical) {
  298. $this->pageHeader('canonical', 'link', 0, [
  299. 'rel' => 'canonical',
  300. 'href' => $this->canonical,
  301. ]);
  302. }
  303. if ($this->robots) {
  304. $this->pageHeader('robots', 'meta', 11000, [
  305. 'name' => 'robots',
  306. 'content' => $this->robots,
  307. ]);
  308. }
  309. \uasort($this->pageHeaders, function (array $a, array $b) {
  310. if ($a['weight'] === $b['weight']) {
  311. return 0;
  312. } else {
  313. return $a['weight'] > $b['weight'] ? -1 : 1;
  314. }
  315. });
  316. return $this->pageHeaders;
  317. }
  318. /**
  319. * Добавляет/заменяет/удаляет HTTP заголовок
  320. */
  321. public function header(string $header, ?string $value, bool $replace = true): Page
  322. {
  323. $key = \strtolower($header);
  324. if ('http/' === \substr($key, 0, 5)) {
  325. $key = 'http/';
  326. $replace = true;
  327. if (
  328. ! empty($_SERVER['SERVER_PROTOCOL'])
  329. && 'HTTP/' === \strtoupper(\substr($_SERVER['SERVER_PROTOCOL'], 0, 5))
  330. ) {
  331. $header = 'HTTP/' . \substr($_SERVER['SERVER_PROTOCOL'], 5);
  332. }
  333. } else {
  334. $header .= ':';
  335. }
  336. if (null === $value) {
  337. unset($this->httpHeaders[$key]);
  338. } elseif (
  339. true === $replace
  340. || empty($this->httpHeaders[$key])
  341. ) {
  342. $this->httpHeaders[$key] = [
  343. ["{$header} {$value}", $replace],
  344. ];
  345. } else {
  346. $this->httpHeaders[$key][] = ["{$header} {$value}", $replace];
  347. }
  348. return $this;
  349. }
  350. /**
  351. * Возвращает HTTP заголовки страницы
  352. * $this->httpHeaders
  353. */
  354. protected function gethttpHeaders(): array
  355. {
  356. foreach ($this->c->HTTP_HEADERS[$this->hhsLevel] as $header => $value) {
  357. $this->header($header, $value);
  358. }
  359. $this->httpStatus();
  360. return $this->httpHeaders;
  361. }
  362. /**
  363. * Устанавливает HTTP статус страницы
  364. */
  365. protected function httpStatus(): Page
  366. {
  367. $list = [
  368. 302 => '302 Moved Temporarily',
  369. 400 => '400 Bad Request',
  370. 403 => '403 Forbidden',
  371. 404 => '404 Not Found',
  372. 405 => '405 Method Not Allowed',
  373. 501 => '501 Not Implemented',
  374. 503 => '503 Service Unavailable',
  375. ];
  376. if (isset($list[$this->httpStatus])) {
  377. $this->header('HTTP/1.0', $list[$this->httpStatus]);
  378. }
  379. return $this;
  380. }
  381. /**
  382. * Дописывает в массив титула страницы новый элемент
  383. * $this->titles = ...
  384. */
  385. public function settitles(/* string|array */ $value): void
  386. {
  387. $attr = $this->getAttr('titles', []);
  388. $attr[] = $value;
  389. $this->setAttr('titles', $attr);
  390. }
  391. /**
  392. * Добавление новой ошибки
  393. * $this->fIswev = ...
  394. */
  395. public function setfIswev(array $value): void
  396. {
  397. $attr = $this->getAttr('fIswev', []);
  398. if (
  399. isset($value[0], $value[1])
  400. && \is_string($value[0])
  401. && 2 === \count($value)
  402. ) {
  403. $attr[$value[0]][] = $value[1];
  404. } else {
  405. $attr = \array_merge_recursive($attr, $value); // ???? добавить проверку?
  406. }
  407. $this->setAttr('fIswev', $attr) ;
  408. }
  409. /**
  410. * Возвращает массив хлебных крошек
  411. * Заполняет массив титула страницы
  412. */
  413. protected function crumbs(/* mixed */ ...$crumbs): array
  414. {
  415. $result = [];
  416. $active = true;
  417. foreach ($crumbs as $crumb) {
  418. // модель
  419. if ($crumb instanceof Model) {
  420. do {
  421. $name = $crumb->name ?? 'NO NAME';
  422. if (! \is_array($name)) {
  423. $name = ['%s', $name];
  424. }
  425. $result[] = [$crumb, $name, $active];
  426. $active = null;
  427. $this->titles = $name;
  428. if ($crumb->page > 1) {
  429. $this->titles = ['Page %s', $crumb->page];
  430. }
  431. $crumb = $crumb->parent;
  432. } while (
  433. $crumb instanceof Model
  434. && null !== $crumb->parent
  435. );
  436. // ссылка (передана массивом)
  437. } elseif (\is_array($crumb)) {
  438. $result[] = [$crumb[0], $crumb[1], $active];
  439. $this->titles = $crumb[1];
  440. // строка
  441. } else {
  442. $result[] = [null, (string) $crumb, $active];
  443. $this->titles = (string) $crumb;
  444. }
  445. $active = null;
  446. }
  447. // главная страница
  448. $result[] = [$this->c->Router->link('Index'), 'Index', $active];
  449. return \array_reverse($result);
  450. }
  451. /**
  452. * Возвращает url для $path заданного в каталоге public
  453. * Ведущий слеш обязателен O_o
  454. */
  455. public function publicLink(string $path): string
  456. {
  457. $fullPath = $this->c->DIR_PUBLIC . $path;
  458. if (\is_file($fullPath)) {
  459. $time = \filemtime($fullPath) ?: '0';
  460. if (\preg_match('%^(.+)\.([^.\\/]++)$%D', $path, $matches)) {
  461. return $this->c->PUBLIC_URL . "{$matches[1]}.v.{$time}.{$matches[2]}";
  462. }
  463. }
  464. return $this->c->PUBLIC_URL . $path;
  465. }
  466. }