Completed
Push — master ( bbae65...c4726b )
by
unknown
22:25
created

NotesService::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * ownCloud - Notes
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Bernhard Posselt <[email protected]>
9
 * @copyright Bernhard Posselt 2012, 2014
10
 */
11
12
namespace OCA\Notes\Service;
13
14
use OCP\IL10N;
15
use OCP\Files\IRootFolder;
16
use OCP\Files\Folder;
17
18
use OCA\Notes\Db\Note;
19
20
/**
21
 * Class NotesService
22
 *
23
 * @package OCA\Notes\Service
24
 */
25
class NotesService {
26
27
    private $l10n;
28
    private $root;
29
30
    /**
31
     * @param IRootFolder $root
32
     * @param IL10N $l10n
33
     */
34 11
    public function __construct (IRootFolder $root, IL10N $l10n) {
35 11
        $this->root = $root;
36 11
        $this->l10n = $l10n;
37 11
    }
38
39
40
    /**
41
     * @param string $userId
42
     * @return array with all notes in the current directory
43
     */
44 1
    public function getAll ($userId){
45 1
        $folder = $this->getFolderForUser($userId);
46 1
        $files = $folder->getDirectoryListing();
47 1
        $filesById = [];
48
        foreach($files as $file) {
49 1
            if($this->isNote($file)) {
50 1
                $filesById[$file->getId()] = $file;
51 1
            }
52 1
        }
53 1
        $tagger = \OC::$server->getTagManager()->load('files');
54
        if($tagger==null) {
55 1
            $tags = [];
56
        } else {
57
            $tags = $tagger->getTagsForObjects(array_keys($filesById));
58
        }
59
60
        $notes = [];
61
        foreach($filesById as $id=>$file) {
62
            $notes[] = Note::fromFile($file, array_key_exists($id, $tags) ? $tags[$id] : []);
63
        }
64
65
        return $notes;
66 3
    }
67 3
68 3
69
    /**
70
     * Used to get a single note by id
71
     * @param int $id the id of the note to get
72
     * @param string $userId
73
     * @throws NoteDoesNotExistException if note does not exist
74
     * @return Note
75
     */
76
    public function get ($id, $userId) {
77
        $folder = $this->getFolderForUser($userId);
78 2
        return Note::fromFile($this->getFileById($folder, $id), $this->getTags($id));
79 2
    }
80 2
81
    private function getTags ($id) {
82
        $tagger = \OC::$server->getTagManager()->load('files');
83
        if($tagger==null) {
84
            $tags = [];
85 2
        } else {
86 2
            $tags = $tagger->getTagsForObjects([$id]);
87
        }
88 2
        return array_key_exists($id, $tags) ? $tags[$id] : [];
89
    }
90
91
    /**
92
     * Creates a note and returns the empty note
93
     * @param string $userId
94
     * @see update for setting note content
95
     * @return Note the newly created note
96
     */
97
    public function create ($userId) {
98
        $title = $this->l10n->t('New note');
99
        $folder = $this->getFolderForUser($userId);
100
101 2
        // check new note exists already and we need to number it
102 2
        // pass -1 because no file has id -1 and that will ensure
103 2
        // to only return filenames that dont yet exist
104
        $path = $this->generateFileName($folder, $title, "txt", -1);
105
        $file = $folder->newFile($path);
106 2
107 2
        return Note::fromFile($file);
108
    }
109 2
110 1
111 1
    /**
112
     * Updates a note. Be sure to check the returned note since the title is
113
     * dynamically generated and filename conflicts are resolved
114 2
     * @param int $id the id of the note used to update
115
     * @param string $content the content which will be written into the note
116
     * the title is generated from the first line of the content
117 2
     * @throws NoteDoesNotExistException if note does not exist
118
     * @return \OCA\Notes\Db\Note the updated note
119 2
     */
120
    public function update ($id, $content, $userId){
121
        $folder = $this->getFolderForUser($userId);
122 2
        $file = $this->getFileById($folder, $id);
123 2
124 2
        // generate content from the first line of the title
125 2
        $splitContent = explode("\n", $content);
126
        $title = $splitContent[0];
127
128 2
        if(!$title) {
129 2
            $title = $this->l10n->t('New note');
130 2
        }
131
132 2
        // prevent directory traversal
133
        $title = str_replace(array('/', '\\'), '',  $title);
134 2
        // remove hash and space characters from the beginning of the filename
135
        // in case of markdown
136
        $title = ltrim($title, ' #');
137
        // using a maximum of 100 chars should be enough
138
        $title = mb_substr($title, 0, 100, "UTF-8");
139
140
        // generate filename if there were collisions
141
        $currentFilePath = $file->getPath();
142
        $basePath = '/' . $userId . '/files/Notes/';
143
        $fileExtension = pathinfo($file->getName(), PATHINFO_EXTENSION);
144
        $newFilePath = $basePath . $this->generateFileName($folder, $title, $fileExtension, $id);
145 3
146 3
        // if the current path is not the new path, the file has to be renamed
147 3
        if($currentFilePath !== $newFilePath) {
148 1
            $file->move($newFilePath);
149 1
        }
150
151
        $file->putContent($content);
152
153
        return Note::fromFile($file, $this->getTags($id));
154
    }
155
156
157
    /**
158 8
     * Set or unset a note as favorite.
159 8
     * @param int $id the id of the note used to update
160
     * @param boolean $favorite whether the note should be a favorite or not
161 8
     * @throws NoteDoesNotExistException if note does not exist
162 4
     * @return boolean the new favorite state of the note
163
     */
164
    public function favorite ($id, $favorite, $userId){
165 4
        $folder = $this->getFolderForUser($userId);
166
        $file = $this->getFileById($folder, $id);
167
        if(!$this->isNote($file)) {
168
            throw new NoteDoesNotExistException();
169
        }
170
        $tagger = \OC::$server->getTagManager()->load('files');
171
        if($favorite)
172
            $tagger->addToFavorites($id);
173 11
        else
174 11
            $tagger->removeFromFavorites($id);
175 11
176 11
        $tags = $tagger->getTagsForObjects([$id]);
177 11
        return in_array(\OC\Tags::TAG_FAVORITE, $tags[$id]);
178
    }
179
180 11
181
    /**
182
     * Deletes a note
183
     * @param int $id the id of the note which should be deleted
184
     * @param string $userId
185
     * @throws NoteDoesNotExistException if note does not
186
     * exist
187
     */
188
    public function delete ($id, $userId) {
189
        $folder = $this->getFolderForUser($userId);
190
        $file = $this->getFileById($folder, $id);
191
        $file->delete();
192
    }
193
194
195
    /**
196
     * @param Folder $folder
197 4
     * @param int $id
198 4
     * @throws NoteDoesNotExistException
199
     * @return \OCP\Files\File
200
     */
201
    private function getFileById ($folder, $id) {
202 4
        $file = $folder->getById($id);
203 4
204
        if(count($file) <= 0 || !$this->isNote($file[0])) {
205
            throw new NoteDoesNotExistException();
206 3
        }
207 3
        return $file[0];
208 3
    }
209 3
210 3
211 3
    /**
212 3
     * @param string $userId the user id
213
     * @return Folder
214 3
     */
215
    private function getFolderForUser ($userId) {
216
        $path = '/' . $userId . '/files/Notes';
217
        if ($this->root->nodeExists($path)) {
218
            $folder = $this->root->get($path);
219
        } else {
220
            $folder = $this->root->newFolder($path);
221
        }
222
        return $folder;
223
    }
224 7
225 7
226
    /**
227 7
     * get path of file and the title.txt and check if they are the same
228 7
     * file. If not the title needs to be renamed
229 7
     *
230
     * @param Folder $folder a folder to the notes directory
231 7
     * @param string $title the filename which should be used
232
     * @param string $extension the extension which should be used
233 5
     * @param int $id the id of the note for which the title should be generated
234
     * used to see if the file itself has the title and not a different file for
235
     * checking for filename collisions
236
     * @return string the resolved filename to prevent overwriting different
237
     * files with the same title
238
     */
239
    private function generateFileName (Folder $folder, $title, $extension, $id) {
240
        $path = $title . '.' . $extension;
241
242
        // if file does not exist, that name has not been taken. Similar we don't
243
        // need to handle file collisions if it is the filename did not change
244
        if (!$folder->nodeExists($path) || $folder->get($path)->getId() === $id) {
245
            return $path;
246
        } else {
247
            // increments name (2) to name (3)
248
            $match = preg_match('/\((?P<id>\d+)\)$/', $title, $matches);
249
            if($match) {
250
                $newId = ((int) $matches['id']) + 1;
251
                $newTitle = preg_replace('/(.*)\s\((\d+)\)$/',
252
                    '$1 (' . $newId . ')', $title);
253
            } else {
254
                $newTitle = $title . ' (2)';
255
            }
256
            return $this->generateFileName($folder, $newTitle, $extension, $id);
257
        }
258
    }
259
260
    /**
261
     * test if file is a note
262
     *
263
     * @param \OCP\Files\File $file
264
     * @return bool
265
     */
266
    private function isNote($file) {
267
        $allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note'];
268
269
        if($file->getType() !== 'file') return false;
270
        if(!in_array(
271
            pathinfo($file->getName(), PATHINFO_EXTENSION),
272
            $allowedExtensions
273
        )) return false;
274
275
        return true;
276
    }
277
278
}
279