aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/front/controller
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2020-06-06 14:01:03 +0200
committerArthurHoaro <arthur@hoa.ro>2020-07-23 21:19:21 +0200
commitc22fa57a5505fe95fd01860e3d3dfbb089f869cd (patch)
treea72b57e49b7b2b995ace278bad00fc47d5b6d61d /application/front/controller
parent8eac2e54882d8adae8cbb45386dca1b465242632 (diff)
downloadShaarli-c22fa57a5505fe95fd01860e3d3dfbb089f869cd.tar.gz
Shaarli-c22fa57a5505fe95fd01860e3d3dfbb089f869cd.tar.zst
Shaarli-c22fa57a5505fe95fd01860e3d3dfbb089f869cd.zip
Handle shaare creation/edition/deletion through Slim controllers
Diffstat (limited to 'application/front/controller')
-rw-r--r--application/front/controller/admin/PostBookmarkController.php258
-rw-r--r--application/front/controller/admin/ToolsController.php2
-rw-r--r--application/front/controller/visitor/DailyController.php2
-rw-r--r--application/front/controller/visitor/FeedController.php2
-rw-r--r--application/front/controller/visitor/ShaarliVisitorController.php14
5 files changed, 269 insertions, 9 deletions
diff --git a/application/front/controller/admin/PostBookmarkController.php b/application/front/controller/admin/PostBookmarkController.php
new file mode 100644
index 00000000..dbe570e2
--- /dev/null
+++ b/application/front/controller/admin/PostBookmarkController.php
@@ -0,0 +1,258 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Admin;
6
7use Shaarli\Bookmark\Bookmark;
8use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
9use Shaarli\Formatter\BookmarkMarkdownFormatter;
10use Shaarli\Thumbnailer;
11use Slim\Http\Request;
12use Slim\Http\Response;
13
14/**
15 * Class PostBookmarkController
16 *
17 * Slim controller used to handle Shaarli create or edit bookmarks.
18 */
19class PostBookmarkController extends ShaarliAdminController
20{
21 /**
22 * GET /add-shaare - Displays the form used to create a new bookmark from an URL
23 */
24 public function addShaare(Request $request, Response $response): Response
25 {
26 $this->assignView(
27 'pagetitle',
28 t('Shaare a new link') .' - '. $this->container->conf->get('general.title', 'Shaarli')
29 );
30
31 return $response->write($this->render('addlink'));
32 }
33
34 /**
35 * GET /shaare - Displays the bookmark form for creation.
36 * Note that if the URL is found in existing bookmarks, then it will be in edit mode.
37 */
38 public function displayCreateForm(Request $request, Response $response): Response
39 {
40 $url = cleanup_url($request->getParam('post'));
41
42 $linkIsNew = false;
43 // Check if URL is not already in database (in this case, we will edit the existing link)
44 $bookmark = $this->container->bookmarkService->findByUrl($url);
45 if (null === $bookmark) {
46 $linkIsNew = true;
47 // Get shaare data if it was provided in URL (e.g.: by the bookmarklet).
48 $title = $request->getParam('title');
49 $description = $request->getParam('description');
50 $tags = $request->getParam('tags');
51 $private = filter_var($request->getParam('private'), FILTER_VALIDATE_BOOLEAN);
52
53 // If this is an HTTP(S) link, we try go get the page to extract
54 // the title (otherwise we will to straight to the edit form.)
55 if (empty($title) && strpos(get_url_scheme($url) ?: '', 'http') !== false) {
56 $retrieveDescription = $this->container->conf->get('general.retrieve_description');
57 // Short timeout to keep the application responsive
58 // The callback will fill $charset and $title with data from the downloaded page.
59 $this->container->httpAccess->getHttpResponse(
60 $url,
61 $this->container->conf->get('general.download_timeout', 30),
62 $this->container->conf->get('general.download_max_size', 4194304),
63 $this->container->httpAccess->getCurlDownloadCallback(
64 $charset,
65 $title,
66 $description,
67 $tags,
68 $retrieveDescription
69 )
70 );
71 if (! empty($title) && strtolower($charset) !== 'utf-8') {
72 $title = mb_convert_encoding($title, 'utf-8', $charset);
73 }
74 }
75
76 if (empty($url) && empty($title)) {
77 $title = $this->container->conf->get('general.default_note_title', t('Note: '));
78 }
79
80 $link = escape([
81 'title' => $title,
82 'url' => $url ?? '',
83 'description' => $description ?? '',
84 'tags' => $tags ?? '',
85 'private' => $private,
86 ]);
87 } else {
88 $formatter = $this->container->formatterFactory->getFormatter('raw');
89 $link = $formatter->format($bookmark);
90 }
91
92 return $this->displayForm($link, $linkIsNew, $request, $response);
93 }
94
95 /**
96 * GET /shaare-{id} - Displays the bookmark form in edition mode.
97 */
98 public function displayEditForm(Request $request, Response $response, array $args): Response
99 {
100 $id = $args['id'];
101 try {
102 if (false === ctype_digit($id)) {
103 throw new BookmarkNotFoundException();
104 }
105 $bookmark = $this->container->bookmarkService->get($id); // Read database
106 } catch (BookmarkNotFoundException $e) {
107 $this->saveErrorMessage(t('Bookmark not found'));
108
109 return $response->withRedirect('./');
110 }
111
112 $formatter = $this->container->formatterFactory->getFormatter('raw');
113 $link = $formatter->format($bookmark);
114
115 return $this->displayForm($link, false, $request, $response);
116 }
117
118 /**
119 * POST /shaare
120 */
121 public function save(Request $request, Response $response): Response
122 {
123 $this->checkToken($request);
124
125 // lf_id should only be present if the link exists.
126 $id = $request->getParam('lf_id') ? intval(escape($request->getParam('lf_id'))) : null;
127 if (null !== $id && true === $this->container->bookmarkService->exists($id)) {
128 // Edit
129 $bookmark = $this->container->bookmarkService->get($id);
130 } else {
131 // New link
132 $bookmark = new Bookmark();
133 }
134
135 $bookmark->setTitle($request->getParam('lf_title'));
136 $bookmark->setDescription($request->getParam('lf_description'));
137 $bookmark->setUrl($request->getParam('lf_url'), $this->container->conf->get('security.allowed_protocols', []));
138 $bookmark->setPrivate(filter_var($request->getParam('lf_private'), FILTER_VALIDATE_BOOLEAN));
139 $bookmark->setTagsString($request->getParam('lf_tags'));
140
141 if ($this->container->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
142 && false === $bookmark->isNote()
143 ) {
144 $bookmark->setThumbnail($this->container->thumbnailer->get($bookmark->getUrl()));
145 }
146 $this->container->bookmarkService->addOrSet($bookmark, false);
147
148 // To preserve backward compatibility with 3rd parties, plugins still use arrays
149 $formatter = $this->container->formatterFactory->getFormatter('raw');
150 $data = $formatter->format($bookmark);
151 $data = $this->executeHooks('save_link', $data);
152
153 $bookmark->fromArray($data);
154 $this->container->bookmarkService->set($bookmark);
155
156 // If we are called from the bookmarklet, we must close the popup:
157 if ($request->getParam('source') === 'bookmarklet') {
158 return $response->write('<script>self.close();</script>');
159 }
160
161 if (!empty($request->getParam('returnurl'))) {
162 $this->container->environment['HTTP_REFERER'] = escape($request->getParam('returnurl'));
163 }
164
165 return $this->redirectFromReferer(
166 $request,
167 $response,
168 ['add-shaare', 'shaare'], ['addlink', 'post', 'edit_link'],
169 $bookmark->getShortUrl()
170 );
171 }
172
173 public function deleteBookmark(Request $request, Response $response): Response
174 {
175 $this->checkToken($request);
176
177 $ids = escape(trim($request->getParam('lf_linkdate')));
178 if (strpos($ids, ' ') !== false) {
179 // multiple, space-separated ids provided
180 $ids = array_values(array_filter(preg_split('/\s+/', $ids), 'strlen'));
181 } else {
182 $ids = [$ids];
183 }
184
185 // assert at least one id is given
186 if (0 === count($ids)) {
187 $this->saveErrorMessage(t('Invalid bookmark ID provided.'));
188
189 return $this->redirectFromReferer($request, $response, [], ['delete-shaare']);
190 }
191
192 $formatter = $this->container->formatterFactory->getFormatter('raw');
193 foreach ($ids as $id) {
194 $id = (int) $id;
195 // TODO: check if it exists
196 $bookmark = $this->container->bookmarkService->get($id);
197 $data = $formatter->format($bookmark);
198 $this->container->pluginManager->executeHooks('delete_link', $data);
199 $this->container->bookmarkService->remove($bookmark, false);
200 }
201
202 $this->container->bookmarkService->save();
203
204 // If we are called from the bookmarklet, we must close the popup:
205 if ($request->getParam('source') === 'bookmarklet') {
206 return $response->write('<script>self.close();</script>');
207 }
208
209 // Don't redirect to where we were previously because the datastore has changed.
210 return $response->withRedirect('./');
211 }
212
213 protected function displayForm(array $link, bool $isNew, Request $request, Response $response): Response
214 {
215 $tags = $this->container->bookmarkService->bookmarksCountPerTag();
216 if ($this->container->conf->get('formatter') === 'markdown') {
217 $tags[BookmarkMarkdownFormatter::NO_MD_TAG] = 1;
218 }
219
220 $data = [
221 'link' => $link,
222 'link_is_new' => $isNew,
223 'http_referer' => escape($this->container->environment['HTTP_REFERER'] ?? ''),
224 'source' => $request->getParam('source') ?? '',
225 'tags' => $tags,
226 'default_private_links' => $this->container->conf->get('privacy.default_private_links', false),
227 ];
228
229 $data = $this->executeHooks('render_editlink', $data);
230
231 foreach ($data as $key => $value) {
232 $this->assignView($key, $value);
233 }
234
235 $editLabel = false === $isNew ? t('Edit') .' ' : '';
236 $this->assignView(
237 'pagetitle',
238 $editLabel . t('Shaare') .' - '. $this->container->conf->get('general.title', 'Shaarli')
239 );
240
241 return $response->write($this->render('editlink'));
242 }
243
244 /**
245 * @param mixed[] $data Variables passed to the template engine
246 *
247 * @return mixed[] Template data after active plugins render_picwall hook execution.
248 */
249 protected function executeHooks(string $hook, array $data): array
250 {
251 $this->container->pluginManager->executeHooks(
252 $hook,
253 $data
254 );
255
256 return $data;
257 }
258}
diff --git a/application/front/controller/admin/ToolsController.php b/application/front/controller/admin/ToolsController.php
index 66db5ad9..d087f2cd 100644
--- a/application/front/controller/admin/ToolsController.php
+++ b/application/front/controller/admin/ToolsController.php
@@ -21,7 +21,7 @@ class ToolsController extends ShaarliAdminController
21 'sslenabled' => is_https($this->container->environment), 21 'sslenabled' => is_https($this->container->environment),
22 ]; 22 ];
23 23
24 $this->executeHooks($data); 24 $data = $this->executeHooks($data);
25 25
26 foreach ($data as $key => $value) { 26 foreach ($data as $key => $value) {
27 $this->assignView($key, $value); 27 $this->assignView($key, $value);
diff --git a/application/front/controller/visitor/DailyController.php b/application/front/controller/visitor/DailyController.php
index 47e2503a..e5c9ddac 100644
--- a/application/front/controller/visitor/DailyController.php
+++ b/application/front/controller/visitor/DailyController.php
@@ -71,7 +71,7 @@ class DailyController extends ShaarliVisitorController
71 ]; 71 ];
72 72
73 // Hooks are called before column construction so that plugins don't have to deal with columns. 73 // Hooks are called before column construction so that plugins don't have to deal with columns.
74 $this->executeHooks($data); 74 $data = $this->executeHooks($data);
75 75
76 $data['cols'] = $this->calculateColumns($data['linksToDisplay']); 76 $data['cols'] = $this->calculateColumns($data['linksToDisplay']);
77 77
diff --git a/application/front/controller/visitor/FeedController.php b/application/front/controller/visitor/FeedController.php
index 70664635..f76f55fd 100644
--- a/application/front/controller/visitor/FeedController.php
+++ b/application/front/controller/visitor/FeedController.php
@@ -46,7 +46,7 @@ class FeedController extends ShaarliVisitorController
46 46
47 $data = $this->container->feedBuilder->buildData($feedType, $request->getParams()); 47 $data = $this->container->feedBuilder->buildData($feedType, $request->getParams());
48 48
49 $this->executeHooks($data, $feedType); 49 $data = $this->executeHooks($data, $feedType);
50 $this->assignAllView($data); 50 $this->assignAllView($data);
51 51
52 $content = $this->render('feed.'. $feedType); 52 $content = $this->render('feed.'. $feedType);
diff --git a/application/front/controller/visitor/ShaarliVisitorController.php b/application/front/controller/visitor/ShaarliVisitorController.php
index f12915c1..98423d90 100644
--- a/application/front/controller/visitor/ShaarliVisitorController.php
+++ b/application/front/controller/visitor/ShaarliVisitorController.php
@@ -78,16 +78,16 @@ abstract class ShaarliVisitorController
78 ]; 78 ];
79 79
80 foreach ($common_hooks as $name) { 80 foreach ($common_hooks as $name) {
81 $plugin_data = []; 81 $pluginData = [];
82 $this->container->pluginManager->executeHooks( 82 $this->container->pluginManager->executeHooks(
83 'render_' . $name, 83 'render_' . $name,
84 $plugin_data, 84 $pluginData,
85 [ 85 [
86 'target' => $template, 86 'target' => $template,
87 'loggedin' => $this->container->loginManager->isLoggedIn() 87 'loggedin' => $this->container->loginManager->isLoggedIn()
88 ] 88 ]
89 ); 89 );
90 $this->assignView('plugins_' . $name, $plugin_data); 90 $this->assignView('plugins_' . $name, $pluginData);
91 } 91 }
92 } 92 }
93 93
@@ -102,9 +102,10 @@ abstract class ShaarliVisitorController
102 Request $request, 102 Request $request,
103 Response $response, 103 Response $response,
104 array $loopTerms = [], 104 array $loopTerms = [],
105 array $clearParams = [] 105 array $clearParams = [],
106 string $anchor = null
106 ): Response { 107 ): Response {
107 $defaultPath = $request->getUri()->getBasePath(); 108 $defaultPath = rtrim($request->getUri()->getBasePath(), '/') . '/';
108 $referer = $this->container->environment['HTTP_REFERER'] ?? null; 109 $referer = $this->container->environment['HTTP_REFERER'] ?? null;
109 110
110 if (null !== $referer) { 111 if (null !== $referer) {
@@ -133,7 +134,8 @@ abstract class ShaarliVisitorController
133 } 134 }
134 135
135 $queryString = count($params) > 0 ? '?'. http_build_query($params) : ''; 136 $queryString = count($params) > 0 ? '?'. http_build_query($params) : '';
137 $anchor = $anchor ? '#' . $anchor : '';
136 138
137 return $response->withRedirect($path . $queryString); 139 return $response->withRedirect($path . $queryString . $anchor);
138 } 140 }
139} 141}