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