]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/render/PageBuilder.php
c2fae7052f71116579b136433f7eeb110989db55
[github/shaarli/Shaarli.git] / application / render / PageBuilder.php
1 <?php
2
3 namespace Shaarli\Render;
4
5 use Exception;
6 use Psr\Log\LoggerInterface;
7 use RainTPL;
8 use Shaarli\Bookmark\BookmarkServiceInterface;
9 use Shaarli\Config\ConfigManager;
10 use Shaarli\Helper\ApplicationUtils;
11 use Shaarli\Security\SessionManager;
12 use Shaarli\Thumbnailer;
13
14 /**
15 * This class is in charge of building the final page.
16 * (This is basically a wrapper around RainTPL which pre-fills some fields.)
17 * $p = new PageBuilder();
18 * $p->assign('myfield','myvalue');
19 * $p->renderPage('mytemplate');
20 */
21 class PageBuilder
22 {
23 /**
24 * @var RainTPL RainTPL instance.
25 */
26 private $tpl;
27
28 /**
29 * @var ConfigManager $conf Configuration Manager instance.
30 */
31 protected $conf;
32
33 /**
34 * @var array $_SESSION
35 */
36 protected $session;
37
38 /** @var LoggerInterface */
39 protected $logger;
40
41 /**
42 * @var BookmarkServiceInterface $bookmarkService instance.
43 */
44 protected $bookmarkService;
45
46 /**
47 * @var null|string XSRF token
48 */
49 protected $token;
50
51 /**
52 * @var bool $isLoggedIn Whether the user is logged in
53 */
54 protected $isLoggedIn = false;
55
56 /**
57 * PageBuilder constructor.
58 * $tpl is initialized at false for lazy loading.
59 *
60 * @param ConfigManager $conf Configuration Manager instance (reference).
61 * @param array $session $_SESSION array
62 * @param LoggerInterface $logger
63 * @param null $linkDB instance.
64 * @param null $token Session token
65 * @param bool $isLoggedIn
66 */
67 public function __construct(
68 ConfigManager &$conf,
69 array $session,
70 LoggerInterface $logger,
71 $linkDB = null,
72 $token = null,
73 $isLoggedIn = false
74 ) {
75 $this->tpl = false;
76 $this->conf = $conf;
77 $this->session = $session;
78 $this->logger = $logger;
79 $this->bookmarkService = $linkDB;
80 $this->token = $token;
81 $this->isLoggedIn = $isLoggedIn;
82 }
83
84 /**
85 * Reset current state of template rendering.
86 * Mostly useful for error handling. We remove everything, and display the error template.
87 */
88 public function reset(): void
89 {
90 $this->tpl = false;
91 }
92
93 /**
94 * Initialize all default tpl tags.
95 */
96 private function initialize()
97 {
98 $this->tpl = new RainTPL();
99
100 try {
101 $version = ApplicationUtils::checkUpdate(
102 SHAARLI_VERSION,
103 $this->conf->get('resource.update_check'),
104 $this->conf->get('updates.check_updates_interval'),
105 $this->conf->get('updates.check_updates'),
106 $this->isLoggedIn,
107 $this->conf->get('updates.check_updates_branch')
108 );
109 $this->tpl->assign('newVersion', escape($version));
110 $this->tpl->assign('versionError', '');
111 } catch (Exception $exc) {
112 $this->logger->error(format_log('Error: ' . $exc->getMessage(), client_ip_id($_SERVER)));
113 $this->tpl->assign('newVersion', '');
114 $this->tpl->assign('versionError', escape($exc->getMessage()));
115 }
116
117 $this->tpl->assign('is_logged_in', $this->isLoggedIn);
118 $this->tpl->assign('feedurl', escape(index_url($_SERVER)));
119 $searchcrits = ''; // Search criteria
120 if (!empty($_GET['searchtags'])) {
121 $searchcrits .= '&searchtags=' . urlencode($_GET['searchtags']);
122 }
123 if (!empty($_GET['searchterm'])) {
124 $searchcrits .= '&searchterm=' . urlencode($_GET['searchterm']);
125 }
126 $this->tpl->assign('searchcrits', $searchcrits);
127 $this->tpl->assign('source', index_url($_SERVER));
128 $this->tpl->assign('version', SHAARLI_VERSION);
129 $this->tpl->assign(
130 'version_hash',
131 ApplicationUtils::getVersionHash(SHAARLI_VERSION, $this->conf->get('credentials.salt'))
132 );
133 $this->tpl->assign('index_url', index_url($_SERVER));
134 $visibility = !empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
135 $this->tpl->assign('visibility', $visibility);
136 $this->tpl->assign('untaggedonly', !empty($_SESSION['untaggedonly']));
137 $this->tpl->assign('pagetitle', $this->conf->get('general.title', 'Shaarli'));
138 if ($this->conf->exists('general.header_link')) {
139 $this->tpl->assign('titleLink', $this->conf->get('general.header_link'));
140 }
141 $this->tpl->assign('shaarlititle', $this->conf->get('general.title', 'Shaarli'));
142 $this->tpl->assign('openshaarli', $this->conf->get('security.open_shaarli', false));
143 $this->tpl->assign('showatom', $this->conf->get('feed.show_atom', true));
144 $this->tpl->assign('feed_type', $this->conf->get('feed.show_atom', true) !== false ? 'atom' : 'rss');
145 $this->tpl->assign('hide_timestamps', $this->conf->get('privacy.hide_timestamps', false));
146 $this->tpl->assign('token', $this->token);
147
148 $this->tpl->assign('language', $this->conf->get('translation.language'));
149
150 if ($this->bookmarkService !== null) {
151 $this->tpl->assign('tags', escape($this->bookmarkService->bookmarksCountPerTag()));
152 }
153
154 $this->tpl->assign(
155 'thumbnails_enabled',
156 $this->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
157 );
158 $this->tpl->assign('thumbnails_width', $this->conf->get('thumbnails.width'));
159 $this->tpl->assign('thumbnails_height', $this->conf->get('thumbnails.height'));
160
161 $this->tpl->assign('formatter', $this->conf->get('formatter', 'default'));
162
163 $this->tpl->assign('links_per_page', $this->session['LINKS_PER_PAGE'] ?? 20);
164
165 // To be removed with a proper theme configuration.
166 $this->tpl->assign('conf', $this->conf);
167 }
168
169 /**
170 * Affect variable after controller processing.
171 * Used for alert messages.
172 */
173 protected function finalize(string $basePath): void
174 {
175 // TODO: use the SessionManager
176 $messageKeys = [
177 SessionManager::KEY_SUCCESS_MESSAGES,
178 SessionManager::KEY_WARNING_MESSAGES,
179 SessionManager::KEY_ERROR_MESSAGES
180 ];
181 foreach ($messageKeys as $messageKey) {
182 if (!empty($_SESSION[$messageKey])) {
183 $this->tpl->assign('global_' . $messageKey, $_SESSION[$messageKey]);
184 unset($_SESSION[$messageKey]);
185 }
186 }
187
188 $rootPath = preg_replace('#/index\.php$#', '', $basePath);
189 $this->assign('base_path', $basePath);
190 $this->assign('root_path', $rootPath);
191 $this->assign(
192 'asset_path',
193 $rootPath . '/' .
194 rtrim($this->conf->get('resource.raintpl_tpl', 'tpl'), '/') . '/' .
195 $this->conf->get('resource.theme', 'default')
196 );
197 }
198
199 /**
200 * The following assign() method is basically the same as RainTPL (except lazy loading)
201 *
202 * @param string $placeholder Template placeholder.
203 * @param mixed $value Value to assign.
204 */
205 public function assign($placeholder, $value)
206 {
207 if ($this->tpl === false) {
208 $this->initialize();
209 }
210 $this->tpl->assign($placeholder, $value);
211 }
212
213 /**
214 * Assign an array of data to the template builder.
215 *
216 * @param array $data Data to assign.
217 *
218 * @return false if invalid data.
219 */
220 public function assignAll($data)
221 {
222 if ($this->tpl === false) {
223 $this->initialize();
224 }
225
226 if (empty($data) || !is_array($data)) {
227 return false;
228 }
229
230 foreach ($data as $key => $value) {
231 $this->assign($key, $value);
232 }
233 return true;
234 }
235
236 /**
237 * Render a specific page as string (using a template file).
238 * e.g. $pb->render('picwall');
239 *
240 * @param string $page Template filename (without extension).
241 *
242 * @return string Processed template content
243 */
244 public function render(string $page, string $basePath): string
245 {
246 if ($this->tpl === false) {
247 $this->initialize();
248 }
249
250 $this->finalize($basePath);
251
252 return $this->tpl->draw($page, true);
253 }
254 }