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