Fix #41: Use correct SQL datetime format for tokens
[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                     'html' => $this->urlGen->linkToRoute(
126                         'grauphel.notes.html', array('guid' => $guid)
127                     ),
128                     'json' => $this->urlGen->linkToRoute(
129                         'grauphel.api.note', array(
130                             'guid' => $guid, 'username' => $this->user->getUid()
131                         )
132                     ),
133                     'text' => $this->urlGen->linkToRoute(
134                         'grauphel.notes.text', array('guid' => $guid)
135                     ),
136                     'xml' => $this->urlGen->linkToRoute(
137                         'grauphel.notes.xml', array('guid' => $guid)
138                     ),
139                 )
140             )
141         );
142
143         $selectedRawtag = 'grauphel:special:untagged';
144         if (count($note->tags) > 0) {
145             $selectedRawtag = $note->tags[0];
146         }
147
148         $this->addNavigation($res, $selectedRawtag);
149         return $res;
150     }
151
152     public function noteLinkHandler($noteTitle)
153     {
154         $guid = $this->getNotes()->loadGuidByTitle($noteTitle);
155         if ($guid === null) {
156             return '#';
157         }
158         return $this->urlGen->linkToRoute(
159             'grauphel.gui.note', array('guid' => $guid)
160         );
161     }
162
163     /**
164      * Show all notes of a tag
165      *
166      * @NoAdminRequired
167      * @NoCSRFRequired
168      */
169     public function tag($rawtag)
170     {
171         $rawtag = $this->unescapeTagFromUrl($rawtag);
172         $notes = $this->getNotes()->loadNotesOverview(null, $rawtag, true);
173         usort(
174             $notes,
175             function($noteA, $noteB) {
176                 return strcmp($noteA['title'], $noteB['title']);
177             }
178         );
179
180         foreach ($notes as &$note) {
181             $diffInDays = intval(
182                 (time() - strtotime($note['last-change-date'])) / 86400
183             );
184             $value = 0 + $diffInDays;
185             if ($value > 160) {
186                 $value = 160;
187             }
188             $note['dateColor'] = '#' . str_repeat(sprintf('%02X', $value), 3);
189         }
190
191         $res = new TemplateResponse('grauphel', 'tag');
192         $res->setParams(
193             array(
194                 'tag'    => $this->getPrettyTagName($rawtag),
195                 'rawtag' => $rawtag,
196                 'notes'  => $notes,
197             )
198         );
199         $this->addNavigation($res, $rawtag);
200
201         return $res;
202     }
203
204     /**
205      * Show access tokens
206      *
207      * @NoAdminRequired
208      * @NoCSRFRequired
209      */
210     public function tokens()
211     {
212         $tokens = new TokenStorage();
213         $res = new TemplateResponse('grauphel', 'tokens');
214         $res->setParams(
215             array(
216                 'tokens' => $tokens->loadForUser(
217                     $this->user->getUid(), 'access'
218                 ),
219                 'client' => new Client(),
220                 'username' => $this->user->getUid(),
221             )
222         );
223         $this->addNavigation($res, null);
224
225         return $res;
226     }
227
228     /**
229      * Allow the user to clear his database
230      *
231      * @NoAdminRequired
232      * @NoCSRFRequired
233      */
234     public function database($reset = null)
235     {
236         $res = new TemplateResponse('grauphel', 'gui-database');
237         $res->setParams(array('reset' => $reset));
238         $this->addNavigation($res, null);
239         $this->addStats($res);
240
241         return $res;
242     }
243
244     /**
245      * Resets the database by deleting all notes and deleting the user's
246      * sync data.
247      *
248      * @NoAdminRequired
249      */
250     public function databaseReset()
251     {
252         $reset = false;
253         if ($_POST['username'] != '' && $_POST['username'] == $this->user->getUid()) {
254             $notes = $this->getNotes();
255             $notes->deleteAll();
256             $notes->deleteSyncData();
257             $reset = true;
258         }
259
260         return $this->database($reset);
261     }
262
263     protected function addNavigation(TemplateResponse $res, $selectedRawtag = null)
264     {
265         $nav = new \OCP\Template('grauphel', 'appnavigation', '');
266         $nav->assign('apiroot', $this->getApiRootUrl());
267         $nav->assign('tags', array());
268
269         $params = $res->getParams();
270         $params['appNavigation'] = $nav;
271         $res->setParams($params);
272
273         if ($this->user === null) {
274             return;
275         }
276
277         $rawtags = $this->getNotes()->getTags();
278         sort($rawtags);
279         array_unshift(
280             $rawtags,
281             'grauphel:special:all', 'grauphel:special:untagged'
282         );
283
284         $tags = array();
285         foreach ($rawtags as $rawtag) {
286             $name = $this->getPrettyTagName($rawtag);
287             if ($name !== false) {
288                 $tags[] = array(
289                     'name' => $name,
290                     'id'   => $rawtag,
291                     'href' => $this->urlGen->linkToRoute(
292                         'grauphel.gui.tag',
293                         array('rawtag' => $this->escapeTagForUrl($rawtag))
294                     ),
295                     'selected' => $rawtag == $selectedRawtag,
296                 );
297             }
298         }
299         $nav->assign('tags', $tags);
300     }
301
302     protected function addStats(TemplateResponse $res)
303     {
304         if ($this->user === null) {
305             return;
306         }
307
308         $username = $this->user->getUid();
309         $notes  = $this->getNotes();
310         $tokens = new \OCA\Grauphel\Lib\TokenStorage();
311
312         $nav = new \OCP\Template('grauphel', 'indexStats', '');
313         $nav->assign('notes', count($notes->loadNotesOverview()));
314         $nav->assign('syncrev', $notes->loadSyncData()->latestSyncRevision);
315         $nav->assign('tokens', count($tokens->loadForUser($username, 'access')));
316
317         $params = $res->getParams();
318         $params['stats'] = $nav;
319         $res->setParams($params);
320     }
321
322     protected function checkDeps()
323     {
324         if (!class_exists('OAuthProvider')) {
325             throw new \Exception('PHP extension "oauth" is required', 1001);
326         }
327     }
328
329     protected function getApiRootUrl()
330     {
331         //we need to remove the trailing / for tomdroid and conboy
332         return rtrim(
333             $this->urlGen->getAbsoluteURL(
334                 $this->urlGen->linkToRoute('grauphel.gui.index')
335             ),
336             '/'
337         );
338     }
339
340     protected function getNotes()
341     {
342         $username = $this->user->getUid();
343         $notes  = new \OCA\Grauphel\Lib\NoteStorage($this->urlGen);
344         $notes->setUsername($username);
345         return $notes;
346     }
347
348     protected function getPrettyTagName($rawtag)
349     {
350         if (substr($rawtag, 0, 16) == 'system:notebook:') {
351             return substr($rawtag, 16);
352         } else if (substr($rawtag, 0, 17) == 'grauphel:special:') {
353             return '*' . substr($rawtag, 17) . '*';
354         }
355         return false;
356     }
357
358     protected function escapeTagForUrl($rawtag)
359     {
360         return str_replace('/', '%2F', $rawtag);
361     }
362
363     protected function unescapeTagFromUrl($rawtag)
364     {
365         return str_replace('%2F', '/', $rawtag);
366     }
367 }
368 ?>