store client name and last use time for tokens. show them in token management
[grauphel.git] / lib / notestorage.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\Lib;
15
16 /**
17  * Flat file storage for notes
18  *
19  * @category  Tools
20  * @package   Grauphel
21  * @author    Christian Weiske <cweiske@cweiske.de>
22  * @copyright 2014 Christian Weiske
23  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
24  * @version   Release: @package_version@
25  * @link      http://cweiske.de/grauphel.htm
26  */
27 class NoteStorage
28 {
29     protected $urlGen;
30     protected $username;
31
32     public function __construct($urlGen)
33     {
34         $this->urlGen   = $urlGen;
35     }
36
37     public function setUsername($username)
38     {
39         $this->username = $username;
40     }
41
42     /**
43      * Create a new sync data object for fresh users.
44      * Used by loadSyncData()
45      *
46      * @return SyncData New synchronization statistics
47      */
48     protected function getNewSyncData()
49     {
50         $syncdata = new SyncData();
51         $syncdata->initNew($this->username);
52         return $syncdata;
53     }
54
55     public function getTags()
56     {
57         $result = \OC_DB::executeAudited(
58             'SELECT `note_tags` FROM `*PREFIX*grauphel_notes`'
59             . ' WHERE note_user = ?',
60             array($this->username)
61         );
62
63         $tags = array();
64         while ($row = $result->fetchRow()) {
65             $tags = array_merge($tags, json_decode($row['note_tags']));
66         }
67         return array_unique($tags);
68     }
69
70     /**
71      * Updates the given $note object with data from $noteUpdate.
72      * Sets the last-sync-revision to $syncRevision
73      *
74      * @param object  $note         Original note object
75      * @param object  $noteUpdate   Update note object from a PUT to the API
76      * @param integer $syncRevision Current sync revision number
77      *
78      * @return void
79      */
80     public function update($note, $noteUpdate, $syncRevision)
81     {
82         static $updateFields = array(
83             'create-date',
84             'last-change-date',
85             'last-metadata-change-date',
86             'note-content',
87             'note-content-version',
88             'open-on-startup',
89             'pinned',
90             'tags',
91             'title',
92         );
93
94         $changed = array();
95         foreach ($updateFields as $field) {
96             $changed[$field] = false;
97             if (isset($noteUpdate->$field)) {
98                 if ($note->$field != $noteUpdate->$field) {
99                     $note->$field = $noteUpdate->$field;
100                     $changed[$field] = true;
101                 }
102             }
103         }
104
105         if (!isset($noteUpdate->{'last-change-date'})
106             && ($changed['title'] || $changed['note-content'])
107         ) {
108             //no idea how to get the microseconds in there
109             $note->{'last-change-date'} = date('c');
110         }
111
112         if (!isset($noteUpdate->{'last-metadata-change-date'})) {
113             //no idea how to get the microseconds in there
114             $note->{'last-metadata-change-date'} = date('c');
115         }
116
117         if (isset($noteUpdate->{'node-content'})
118             && $note->{'note-content-version'} == 0
119         ) {
120             $note->{'note-content-version'} = 0.3;
121         }
122
123         $note->{'last-sync-revision'} = $syncRevision;
124     }
125
126     /**
127      * Loads synchronization data for the given user.
128      * Creates fresh sync data if there are none for the user.
129      *
130      * @return SyncData Synchronization statistics (revision, sync guid)
131      */
132     public function loadSyncData()
133     {
134         $row = \OC_DB::executeAudited(
135             'SELECT * FROM `*PREFIX*grauphel_syncdata`'
136             . ' WHERE `syncdata_user` = ?',
137             array($this->username)
138         )->fetchRow();
139
140         if ($row === false) {
141             $syncdata = $this->getNewSyncData();
142             $this->saveSyncData($syncdata);
143         } else {
144             $syncdata = new SyncData();
145             $syncdata->latestSyncRevision = (int) $row['syncdata_latest_sync_revision'];
146             $syncdata->currentSyncGuid    = $row['syncdata_current_sync_guid'];
147         }
148
149         return $syncdata;
150     }
151
152     /**
153      * Save synchronization data for the given user.
154      *
155      * @param SyncData $syncdata Synchronization data object
156      *
157      * @return void
158      */
159     public function saveSyncData(SyncData $syncdata)
160     {
161         $row = \OC_DB::executeAudited(
162             'SELECT * FROM `*PREFIX*grauphel_syncdata`'
163             . ' WHERE `syncdata_user` = ?',
164             array($this->username)
165         )->fetchRow();
166
167         if ($row === false) {
168             //INSERT
169             $sql = 'INSERT INTO `*PREFIX*grauphel_syncdata`'
170                 . '(`syncdata_user`, `syncdata_latest_sync_revision`, `syncdata_current_sync_guid`)'
171                 . ' VALUES(?, ?, ?)';
172             $params = array(
173                 $this->username,
174                 $syncdata->latestSyncRevision,
175                 $syncdata->currentSyncGuid
176             );
177         } else {
178             //UPDATE
179             $data = array(
180                 'syncdata_latest_sync_revision' => $syncdata->latestSyncRevision,
181                 'syncdata_current_sync_guid'    => $syncdata->currentSyncGuid,
182             );
183             $sql = 'UPDATE `*PREFIX*grauphel_syncdata` SET'
184                 . ' `' . implode('` = ?, `', array_keys($data)) . '` = ?'
185                 . ' WHERE `syncdata_user` = ?';
186             $params = array_values($data);
187             $params[] = $this->username;
188         }
189         \OC_DB::executeAudited($sql, $params);
190     }
191
192     /**
193      * Load a note from the storage.
194      *
195      * @param string  $guid      Note identifier
196      * @param boolean $createNew Create a new note if it does not exist
197      *
198      * @return object Note object, NULL if !$createNew and note does not exist
199      */
200     public function load($guid, $createNew = true)
201     {
202         $row = \OC_DB::executeAudited(
203             'SELECT * FROM `*PREFIX*grauphel_notes`'
204             . ' WHERE `note_user` = ? AND `note_guid` = ?',
205             array($this->username, $guid)
206         )->fetchRow();
207
208         if ($row === false) {
209             if (!$createNew) {
210                 return null;
211             }
212             return (object) array(
213                 'guid' => $guid,
214
215                 'create-date'               => null,
216                 'last-change-date'          => null,
217                 'last-metadata-change-date' => null,
218
219                 'title'                => null,
220                 'note-content'         => null,
221                 'note-content-version' => 0.3,
222
223                 'open-on-startup' => false,
224                 'pinned'          => false,
225                 'tags'            => array(),
226             );
227         }
228         
229         return $this->noteFromRow($row);
230     }
231
232     /**
233      * Save a note into storage.
234      *
235      * @param object $note Note to save
236      *
237      * @return void
238      */
239     public function save($note)
240     {
241         $row = \OC_DB::executeAudited(
242             'SELECT * FROM `*PREFIX*grauphel_notes`'
243             . ' WHERE `note_user` = ? AND `note_guid` = ?',
244             array($this->username, $note->guid)
245         )->fetchRow();
246
247         $data = $this->rowFromNote($note);
248         if ($row === false) {
249             //INSERT
250             $data['note_user'] = $this->username;
251             $sql = 'INSERT INTO `*PREFIX*grauphel_notes`'
252                 . ' (`' . implode('`, `', array_keys($data)) . '`)'
253                 . ' VALUES(' . implode(', ', array_fill(0, count($data), '?')) . ')';
254             $params = array_values($data);
255         } else {
256             //UPDATE
257             $sql = 'UPDATE `*PREFIX*grauphel_notes` SET '
258                 . '`' . implode('` = ?, `', array_keys($data)) . '` = ?'
259                 . ' WHERE `note_user` = ? AND `note_guid` = ?';
260             $params = array_values($data);
261             $params[] = $this->username;
262             $params[] = $note->guid;
263         }
264         \OC_DB::executeAudited($sql, $params);
265     }
266
267     /**
268      * Delete a note from storage.
269      *
270      * @param object $guid ID of the note
271      *
272      * @return void
273      */
274     public function delete($guid)
275     {
276         \OC_DB::executeAudited(
277             'DELETE FROM `*PREFIX*grauphel_notes`'
278             . ' WHERE `note_user` = ? AND `note_guid` = ?',
279             array($this->username, $guid)
280         );
281     }
282
283     /**
284      * Load notes for the given user in short form.
285      * Optionally only those changed after $since revision
286      *
287      * @param integer $since  Revision number after which the notes changed
288      * @param string  $rawtag Filter by tag. Special tags:
289      *                        - grauphel:special:all
290      *                        - grauphel:special:untagged
291      *
292      * @return array Array of short note objects
293      */
294     public function loadNotesOverview($since = null, $rawtag = null)
295     {
296         $result = \OC_DB::executeAudited(
297             'SELECT `note_guid`, `note_title`, `note_last_sync_revision`, `note_tags`'
298             . ' FROM `*PREFIX*grauphel_notes`'
299             . ' WHERE note_user = ?',
300             array($this->username)
301         );
302
303         $notes = array();
304         if ($rawtag == 'grauphel:special:all') {
305             $rawtag = null;
306         } else if ($rawtag == 'grauphel:special:untagged') {
307             $jsRawtag = json_encode(array());
308         } else {
309             $jsRawtag = json_encode($rawtag);
310         }
311         while ($row = $result->fetchRow()) {
312             if ($since !== null && $row['note_last_sync_revision'] <= $since) {
313                 continue;
314             }
315             if ($rawtag !== null && strpos($row['note_tags'], $jsRawtag) === false) {
316                 continue;
317             }
318             $notes[] = array(
319                 'guid' => $row['note_guid'],
320                 'ref'  => array(
321                     'api-ref' => $this->urlGen->getAbsoluteURL(
322                         $this->urlGen->linkToRoute(
323                             'grauphel.api.note',
324                             array(
325                                 'username' => $this->username,
326                                 'guid' => $row['note_guid']
327                             )
328                         )
329                     ),
330                     'href' => null,//FIXME
331                 ),
332                 'title' => $row['note_title'],
333             );
334         }
335
336         return $notes;
337     }
338
339     /**
340      * Load notes for the given user in full form.
341      * Optionally only those changed after $since revision
342      *
343      * @param integer $since Revision number after which the notes changed
344      *
345      * @return array Array of full note objects
346      */
347     public function loadNotesFull($since = null)
348     {
349         $result = \OC_DB::executeAudited(
350             'SELECT * FROM `*PREFIX*grauphel_notes`'
351             . ' WHERE note_user = ?',
352             array($this->username)
353         );
354
355         $notes = array();
356         while ($row = $result->fetchRow()) {
357             if ($since !== null && $row['note_last_sync_revision'] <= $since) {
358                 continue;
359             }
360             $notes[] = $this->noteFromRow($row);
361         }
362
363         return $notes;
364     }
365
366     protected function fixDate($date)
367     {
368         if (strlen($date) == 32) {
369             //Bug in grauphel 0.1.1; date fields in DB had only 32 instead of 33
370             // characters. The last digit of the time zone was missing
371             $date .= '0';
372         }
373         return $date;
374     }
375
376     protected function noteFromRow($row)
377     {
378         return (object) array(
379             'guid'  => $row['note_guid'],
380
381             'create-date'               => $this->fixDate($row['note_create_date']),
382             'last-change-date'          => $this->fixDate($row['note_last_change_date']),
383             'last-metadata-change-date' => $this->fixDate($row['note_last_metadata_change_date']),
384
385             'title'                => $row['note_title'],
386             'note-content'         => $row['note_content'],
387             'note-content-version' => $row['note_content_version'],
388
389             'open-on-startup' => (bool) $row['note_open_on_startup'],
390             'pinned'          => (bool) $row['note_pinned'],
391             'tags'            => json_decode($row['note_tags']),
392
393             'last-sync-revision' => (int) $row['note_last_sync_revision'],
394         );
395     }
396
397     protected function rowFromNote($note)
398     {
399         return array(
400             'note_guid'  => $note->guid,
401             'note_title' => $note->title,
402
403             'note_content'         => $note->{'note-content'},
404             'note_content_version' => $note->{'note-content-version'},
405
406             'note_create_date'               => $note->{'create-date'},
407             'note_last_change_date'          => $note->{'last-change-date'},
408             'note_last_metadata_change_date' => $note->{'last-metadata-change-date'},
409             
410             'note_open_on_startup' => (int) $note->{'open-on-startup'},
411             'note_pinned'          => (int) $note->pinned,
412             'note_tags'            => json_encode($note->tags),
413
414             'note_last_sync_revision' => $note->{'last-sync-revision'},
415         );
416     }
417 }
418 ?>