951bf06e23647a00aa6adb296ad5ec606cc2577b
[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      * Delete synchronization data for the given user.
194      *
195      * @param SyncData $syncdata Synchronization data object
196      *
197      * @return void
198      */
199     public function deleteSyncData()
200     {
201         \OC_DB::executeAudited(
202             'DELETE FROM `*PREFIX*grauphel_syncdata`'
203             . ' WHERE `syncdata_user` = ?',
204             array($this->username)
205         );
206     }
207
208     /**
209      * Load a note from the storage.
210      *
211      * @param string  $guid      Note identifier
212      * @param boolean $createNew Create a new note if it does not exist
213      *
214      * @return object Note object, NULL if !$createNew and note does not exist
215      */
216     public function load($guid, $createNew = true)
217     {
218         $row = \OC_DB::executeAudited(
219             'SELECT * FROM `*PREFIX*grauphel_notes`'
220             . ' WHERE `note_user` = ? AND `note_guid` = ?',
221             array($this->username, $guid)
222         )->fetchRow();
223
224         if ($row === false) {
225             if (!$createNew) {
226                 return null;
227             }
228             return (object) array(
229                 'guid' => $guid,
230
231                 'create-date'               => null,
232                 'last-change-date'          => null,
233                 'last-metadata-change-date' => null,
234
235                 'title'                => null,
236                 'note-content'         => null,
237                 'note-content-version' => 0.3,
238
239                 'open-on-startup' => false,
240                 'pinned'          => false,
241                 'tags'            => array(),
242             );
243         }
244
245         return $this->noteFromRow($row);
246     }
247
248     /**
249      * Load a GUID of a note by the note title.
250      *
251      * The note title is stored html-escaped in the database because we
252      * get it that way from tomboy. Thus we have to escape the search
253      * input, too.
254      *
255      * @param string $title Note title.
256      *
257      * @return string GUID, NULL if note could not be found
258      */
259     public function loadGuidByTitle($title)
260     {
261         $row = \OC_DB::executeAudited(
262             'SELECT note_guid FROM `*PREFIX*grauphel_notes`'
263             . ' WHERE `note_user` = ? AND `note_title` = ?',
264             array($this->username, htmlspecialchars($title))
265         )->fetchRow();
266
267         if ($row === false) {
268             return null;
269         }
270
271         return $row['note_guid'];
272     }
273
274     /**
275      * Search for a note
276      *
277      * @param string $query Query string
278      *
279      * @return array Database rows with note_guid and note_title
280      */
281     public function search($query)
282     {
283         $result = \OC_DB::executeAudited(
284             'SELECT `note_guid`, `note_title`'
285             . ' FROM `*PREFIX*grauphel_notes`'
286             . ' WHERE note_user = ? AND note_title LIKE ?',
287             array($this->username, '%' . $query . '%')
288         );
289
290         $notes = array();
291         while ($row = $result->fetchRow()) {
292             $notes[] = $row;
293         }
294         return $notes;
295     }
296
297     /**
298      * Save a note into storage.
299      *
300      * @param object $note Note to save
301      *
302      * @return void
303      */
304     public function save($note)
305     {
306         $row = \OC_DB::executeAudited(
307             'SELECT * FROM `*PREFIX*grauphel_notes`'
308             . ' WHERE `note_user` = ? AND `note_guid` = ?',
309             array($this->username, $note->guid)
310         )->fetchRow();
311
312         $data = $this->rowFromNote($note);
313         if ($row === false) {
314             //INSERT
315             $data['note_user'] = $this->username;
316             $sql = 'INSERT INTO `*PREFIX*grauphel_notes`'
317                 . ' (`' . implode('`, `', array_keys($data)) . '`)'
318                 . ' VALUES(' . implode(', ', array_fill(0, count($data), '?')) . ')';
319             $params = array_values($data);
320         } else {
321             //UPDATE
322             $sql = 'UPDATE `*PREFIX*grauphel_notes` SET '
323                 . '`' . implode('` = ?, `', array_keys($data)) . '` = ?'
324                 . ' WHERE `note_user` = ? AND `note_guid` = ?';
325             $params = array_values($data);
326             $params[] = $this->username;
327             $params[] = $note->guid;
328         }
329         \OC_DB::executeAudited($sql, $params);
330     }
331
332     /**
333      * Delete a note from storage.
334      *
335      * @param object $guid ID of the note
336      *
337      * @return void
338      */
339     public function delete($guid)
340     {
341         \OC_DB::executeAudited(
342             'DELETE FROM `*PREFIX*grauphel_notes`'
343             . ' WHERE `note_user` = ? AND `note_guid` = ?',
344             array($this->username, $guid)
345         );
346     }
347
348     /**
349      * Delete all notes from storage.
350      *
351      * @return void
352      */
353     public function deleteAll()
354     {
355         \OC_DB::executeAudited(
356             'DELETE FROM `*PREFIX*grauphel_notes`'
357             . ' WHERE `note_user` = ?',
358             array($this->username)
359         );
360     }
361
362     /**
363      * Load notes for the given user in short form.
364      * Optionally only those changed after $since revision
365      *
366      * @param integer $since  Revision number after which the notes changed
367      * @param string  $rawtag Filter by tag. Special tags:
368      *                        - grauphel:special:all
369      *                        - grauphel:special:untagged
370      *
371      * @return array Array of short note objects
372      */
373     public function loadNotesOverview($since = null, $rawtag = null)
374     {
375         $result = \OC_DB::executeAudited(
376             'SELECT `note_guid`, `note_title`, `note_last_sync_revision`, `note_tags`'
377             . ' FROM `*PREFIX*grauphel_notes`'
378             . ' WHERE note_user = ?',
379             array($this->username)
380         );
381
382         $notes = array();
383         if ($rawtag == 'grauphel:special:all') {
384             $rawtag = null;
385         } else if ($rawtag == 'grauphel:special:untagged') {
386             $jsRawtag = json_encode(array());
387         } else {
388             $jsRawtag = json_encode($rawtag);
389         }
390         while ($row = $result->fetchRow()) {
391             if ($since !== null && $row['note_last_sync_revision'] <= $since) {
392                 continue;
393             }
394             if ($rawtag !== null && strpos($row['note_tags'], $jsRawtag) === false) {
395                 continue;
396             }
397             $notes[] = array(
398                 'guid' => $row['note_guid'],
399                 'ref'  => array(
400                     'api-ref' => $this->urlGen->getAbsoluteURL(
401                         $this->urlGen->linkToRoute(
402                             'grauphel.api.note',
403                             array(
404                                 'username' => $this->username,
405                                 'guid' => $row['note_guid']
406                             )
407                         )
408                     ),
409                     'href' => null,//FIXME
410                 ),
411                 'title' => $row['note_title'],
412             );
413         }
414
415         return $notes;
416     }
417
418     /**
419      * Load notes for the given user in full form.
420      * Optionally only those changed after $since revision
421      *
422      * @param integer $since Revision number after which the notes changed
423      *
424      * @return array Array of full note objects
425      */
426     public function loadNotesFull($since = null)
427     {
428         $result = \OC_DB::executeAudited(
429             'SELECT * FROM `*PREFIX*grauphel_notes`'
430             . ' WHERE note_user = ?',
431             array($this->username)
432         );
433
434         $notes = array();
435         while ($row = $result->fetchRow()) {
436             if ($since !== null && $row['note_last_sync_revision'] <= $since) {
437                 continue;
438             }
439             $notes[] = $this->noteFromRow($row);
440         }
441
442         return $notes;
443     }
444
445     protected function fixDate($date)
446     {
447         if (strlen($date) == 32) {
448             //Bug in grauphel 0.1.1; date fields in DB had only 32 instead of 33
449             // characters. The last digit of the time zone was missing
450             $date .= '0';
451         }
452         return $date;
453     }
454
455     protected function noteFromRow($row)
456     {
457         return (object) array(
458             'guid'  => $row['note_guid'],
459
460             'create-date'               => $this->fixDate($row['note_create_date']),
461             'last-change-date'          => $this->fixDate($row['note_last_change_date']),
462             'last-metadata-change-date' => $this->fixDate($row['note_last_metadata_change_date']),
463
464             'title'                => $row['note_title'],
465             'note-content'         => $row['note_content'],
466             'note-content-version' => $row['note_content_version'],
467
468             'open-on-startup' => (bool) $row['note_open_on_startup'],
469             'pinned'          => (bool) $row['note_pinned'],
470             'tags'            => json_decode($row['note_tags']),
471
472             'last-sync-revision' => (int) $row['note_last_sync_revision'],
473         );
474     }
475
476     protected function rowFromNote($note)
477     {
478         return array(
479             'note_guid'  => $note->guid,
480             'note_title' => (string) $note->title,
481
482             'note_content'         => (string) $note->{'note-content'},
483             'note_content_version' => (string) $note->{'note-content-version'},
484
485             'note_create_date'               => $note->{'create-date'},
486             'note_last_change_date'          => $note->{'last-change-date'},
487             'note_last_metadata_change_date' => $note->{'last-metadata-change-date'},
488
489             'note_open_on_startup' => (int) $note->{'open-on-startup'},
490             'note_pinned'          => (int) $note->pinned,
491             'note_tags'            => json_encode($note->tags),
492
493             'note_last_sync_revision' => $note->{'last-sync-revision'},
494         );
495     }
496 }
497 ?>