8ebea8c58f5b8900e4dfeb7a14cc97ed1e079f13
[grauphel.git] / controller / guicontroller.php
1 <?php
2 /**
3  * Part of grauphel
4  *
5  * PHP version 5
6  *
7  * @category  Tools
8  * @package   Grauphel
9  * @author    Christian Weiske <cweiske@cweiske.de>
10  * @copyright 2014 Christian Weiske
11  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
12  * @link      http://cweiske.de/grauphel.htm
13  */
14 namespace OCA\Grauphel\Controller;
15
16 use \OCP\AppFramework\Controller;
17 use \OCP\AppFramework\Http\TemplateResponse;
18 use \OCA\Grauphel\Lib\Client;
19 use \OCA\Grauphel\Lib\TokenStorage;
20 use \OCA\Grauphel\Lib\Response\ErrorResponse;
21
22 /**
23  * Owncloud frontend
24  *
25  * @category  Tools
26  * @package   Grauphel
27  * @author    Christian Weiske <cweiske@cweiske.de>
28  * @copyright 2014 Christian Weiske
29  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
30  * @version   Release: @package_version@
31  * @link      http://cweiske.de/grauphel.htm
32  */
33 class GuiController extends Controller
34 {
35     /**
36      * constructor of the controller
37      *
38      * @param string   $appName Name of the app
39      * @param IRequest $request Instance of the request
40      */
41     public function __construct($appName, \OCP\IRequest $request, $user, $urlGen)
42     {
43         parent::__construct($appName, $request);
44         $this->user   = $user;
45         $this->urlGen = $urlGen;
46
47         //default http header: we assume something is broken
48         header('HTTP/1.0 500 Internal Server Error');
49     }
50
51     /**
52      * Main page /
53      *
54      * Tomdroid wants this to be a public page. Sync fails otherwise.
55      *
56      * @NoAdminRequired
57      * @NoCSRFRequired
58      * @PublicPage
59      */
60     public function index()
61     {
62         try {
63             $this->checkDeps();
64         } catch (\Exception $e) {
65             $res = new TemplateResponse('grauphel', 'error');
66             $res->setParams(
67                 array(
68                     'message' => $e->getMessage(),
69                     'code' => $e->getCode(),
70                 )
71             );
72             return $res;
73         }
74
75         $res = new TemplateResponse('grauphel', 'index');
76         $res->setParams(
77             array(
78                 'apiroot' => $this->getApiRootUrl(),
79                 'apiurl'  => $this->urlGen->linkToRoute('grauphel.api.index')
80             )
81         );
82         $this->addNavigation($res);
83         $this->addStats($res);
84         return $res;
85     }
86
87     /**
88      * Show contents of a note
89      *
90      * @NoAdminRequired
91      * @NoCSRFRequired
92      */
93     public function note($guid)
94     {
95         $res = new TemplateResponse('grauphel', 'gui-note');
96
97         $note = $this->getNotes()->load($guid, false);
98         if ($note === null) {
99             $res = new ErrorResponse('Note does not exist');
100             $res->setStatus(\OCP\AppFramework\Http::STATUS_NOT_FOUND);
101             return $res;
102         }
103
104         $converter = new \OCA\Grauphel\Converter\Html();
105         $converter->internalLinkHandler = array($this, 'noteLinkHandler');
106
107         try {
108             $contentHtml = $converter->convert($note->{'note-content'});
109         } catch (\OCA\Grauphel\Converter\Exception $e) {
110             $contentHtml = '<div class="error">'
111                 . '<p>There was an error converting the note to HTML:</p>'
112                 . '<blockquote><tt>' . htmlspecialchars($e->getMessage()) . '</tt></blockquote>'
113                 . '<p>Please open a bug report at'
114                 . ' <a class="lined" href="http://github.com/cweiske/grauphel/issues">'
115                 . 'github.com/cweiske/grauphel/issues</a>'
116                 . ' and attach the XML version of the note.'
117                 . '</div>';
118         }
119
120         $res->setParams(
121             array(
122                 'note' => $note,
123                 'note-content' => $contentHtml,
124                 'links' => array(
125                     'json' => $this->urlGen->linkToRoute(
126                         'grauphel.api.note', array(
127                             'guid' => $guid, 'username' => $this->user->getUid()
128                         )
129                     ),
130                     'xml' => $this->urlGen->linkToRoute(
131                         'grauphel.notes.xml', array('guid' => $guid)
132                     ),
133                 )
134             )
135         );
136
137         $selectedRawtag = 'grauphel:special:untagged';
138         if (count($note->tags) > 0) {
139             $selectedRawtag = $note->tags[0];
140         }
141
142         $this->addNavigation($res, $selectedRawtag);
143         return $res;
144     }
145
146     public function noteLinkHandler($noteTitle)
147     {
148         $guid = $this->getNotes()->loadGuidByTitle($noteTitle);
149         if ($guid === null) {
150             return '#';
151         }
152         return $this->urlGen->linkToRoute(
153             'grauphel.gui.note', array('guid' => $guid)
154         );
155     }
156
157     /**
158      * Show all notes of a tag
159      *
160      * @NoAdminRequired
161      * @NoCSRFRequired
162      */
163     public function tag($rawtag)
164     {
165         $notes = $this->getNotes()->loadNotesOverview(null, $rawtag, true);
166         usort(
167             $notes,
168             function($noteA, $noteB) {
169                 return strcmp($noteA['title'], $noteB['title']);
170             }
171         );
172
173         foreach ($notes as &$note) {
174             $diffInDays = intval(
175                 (time() - strtotime($note['last-change-date'])) / 86400
176             );
177             $value = 0 + $diffInDays;
178             if ($value > 160) {
179                 $value = 160;
180             }
181             $note['dateColor'] = '#' . str_repeat(sprintf('%02X', $value), 3);
182         }
183
184         $res = new TemplateResponse('grauphel', 'tag');
185         $res->setParams(
186             array(
187                 'tag'    => $this->getPrettyTagName($rawtag),
188                 'rawtag' => $rawtag,
189                 'notes'  => $notes,
190             )
191         );
192         $this->addNavigation($res, $rawtag);
193
194         return $res;
195     }
196
197     /**
198      * Show access tokens
199      *
200      * @NoAdminRequired
201      * @NoCSRFRequired
202      */
203     public function tokens()
204     {
205         $tokens = new TokenStorage();
206         $res = new TemplateResponse('grauphel', 'tokens');
207         $res->setParams(
208             array(
209                 'tokens' => $tokens->loadForUser(
210                     $this->user->getUid(), 'access'
211                 ),
212                 'client' => new Client(),
213                 'username' => $this->user->getUid(),
214             )
215         );
216         $this->addNavigation($res, null);
217
218         return $res;
219     }
220
221     /**
222      * Allow the user to clear his database
223      *
224      * @NoAdminRequired
225      * @NoCSRFRequired
226      */
227     public function database($reset = null)
228     {
229         $res = new TemplateResponse('grauphel', 'gui-database');
230         $res->setParams(array('reset' => $reset));
231         $this->addNavigation($res, null);
232         $this->addStats($res);
233
234         return $res;
235     }
236
237     /**
238      * Resets the database by deleting all notes and deleting the user's
239      * sync data.
240      *
241      * @NoAdminRequired
242      */
243     public function databaseReset()
244     {
245         $reset = false;
246         if ($_POST['username'] != '' && $_POST['username'] == $this->user->getUid()) {
247             $notes = $this->getNotes();
248             $notes->deleteAll();
249             $notes->deleteSyncData();
250             $reset = true;
251         }
252
253         return $this->database($reset);
254     }
255
256     protected function addNavigation(TemplateResponse $res, $selectedRawtag = null)
257     {
258         $nav = new \OCP\Template('grauphel', 'appnavigation', '');
259         $nav->assign('apiroot', $this->getApiRootUrl());
260         $nav->assign('tags', array());
261
262         $params = $res->getParams();
263         $params['appNavigation'] = $nav;
264         $res->setParams($params);
265
266         if ($this->user === null) {
267             return;
268         }
269
270         $rawtags = $this->getNotes()->getTags();
271         sort($rawtags);
272         array_unshift(
273             $rawtags,
274             'grauphel:special:all', 'grauphel:special:untagged'
275         );
276
277         $tags = array();
278         foreach ($rawtags as $rawtag) {
279             $name = $this->getPrettyTagName($rawtag);
280             if ($name !== false) {
281                 $tags[] = array(
282                     'name' => $name,
283                     'id'   => $rawtag,
284                     'href' => $this->urlGen->linkToRoute(
285                         'grauphel.gui.tag', array('rawtag' => $rawtag)
286                     ),
287                     'selected' => $rawtag == $selectedRawtag,
288                 );
289             }
290         }
291         $nav->assign('tags', $tags);
292     }
293
294     protected function addStats(TemplateResponse $res)
295     {
296         if ($this->user === null) {
297             return;
298         }
299
300         $username = $this->user->getUid();
301         $notes  = $this->getNotes();
302         $tokens = new \OCA\Grauphel\Lib\TokenStorage();
303
304         $nav = new \OCP\Template('grauphel', 'indexStats', '');
305         $nav->assign('notes', count($notes->loadNotesOverview()));
306         $nav->assign('syncrev', $notes->loadSyncData()->latestSyncRevision);
307         $nav->assign('tokens', count($tokens->loadForUser($username, 'access')));
308
309         $params = $res->getParams();
310         $params['stats'] = $nav;
311         $res->setParams($params);
312     }
313
314     protected function checkDeps()
315     {
316         if (!class_exists('OAuthProvider')) {
317             throw new \Exception('PHP extension "oauth" is required', 1001);
318         }
319     }
320
321     protected function getApiRootUrl()
322     {
323         //we need to remove the trailing / for tomdroid and conboy
324         return rtrim(
325             $this->urlGen->getAbsoluteURL(
326                 $this->urlGen->linkToRoute('grauphel.gui.index')
327             ),
328             '/'
329         );
330     }
331
332     protected function getNotes()
333     {
334         $username = $this->user->getUid();
335         $notes  = new \OCA\Grauphel\Lib\NoteStorage($this->urlGen);
336         $notes->setUsername($username);
337         return $notes;
338     }
339
340     protected function getPrettyTagName($rawtag)
341     {
342         if (substr($rawtag, 0, 16) == 'system:notebook:') {
343             return substr($rawtag, 16);
344         } else if (substr($rawtag, 0, 17) == 'grauphel:special:') {
345             return '*' . substr($rawtag, 17) . '*';
346         }
347         return false;
348     }
349 }
350 ?>