Completed
Pull Request — master (#242)
by
unknown
14:48
created

NotesService::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
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
        $notes = [];
48
49 1
        foreach($files as $file) {
50 1
            if($this->isNote($file)) {
51 1
                $notes[] = Note::fromFile($file);
52 1
            }
53 1
        }
54
55 1
        return $notes;
56
    }
57
58
59
    /**
60
     * Used to get a single note by id
61
     * @param int $id the id of the note to get
62
     * @param string $userId
63
     * @throws NoteDoesNotExistException if note does not exist
64
     * @return Note
65
     */
66 3
    public function get ($id, $userId) {
67 3
        $folder = $this->getFolderForUser($userId);
68 3
        return Note::fromFile($this->getFileById($folder, $id));
69
    }
70
71
72
    /**
73
     * Creates a note and returns the empty note
74
     * @param string $userId
75
     * @see update for setting note content
76
     * @return Note the newly created note
77
     */
78 2
    public function create ($userId) {
79 2
        $title = $this->l10n->t('New note');
80 2
        $folder = $this->getFolderForUser($userId);
81
82
        // check new note exists already and we need to number it
83
        // pass -1 because no file has id -1 and that will ensure
84
        // to only return filenames that dont yet exist
85 2
        $path = $this->generateFileName($folder, $title, "txt", -1);
86 2
        $file = $folder->newFile($path);
87
88 2
        return Note::fromFile($file);
89
    }
90
91
92
    /**
93
     * Updates a note. Be sure to check the returned note since the title is
94
     * dynamically generated and filename conflicts are resolved
95
     * @param int $id the id of the note used to update
96
     * @param string $content the content which will be written into the note
97
     * the title is generated from the first line of the content
98
     * @throws NoteDoesNotExistException if note does not exist
99
     * @return \OCA\Notes\Db\Note the updated note
100
     */
101 2
    public function update ($id, $content, $userId){
102 2
        $folder = $this->getFolderForUser($userId);
103 2
        $file = $this->getFileById($folder, $id);
104
105
        // generate content from the first line of the title
106 2
        $splitContent = explode("\n", $content);
107 2
        $title = $splitContent[0];
108
109 2
        if(!$title) {
110 1
            $title = $this->l10n->t('New note');
111 1
        }
112
113
        // prevent directory traversal
114 2
        $title = str_replace(array('/', '\\'), '',  $title);
115
        // remove hash and space characters from the beginning of the filename
116
        // in case of markdown
117 2
        $title = ltrim($title, ' #');
118
        // using a maximum of 100 chars should be enough
119 2
        $title = mb_substr($title, 0, 100, "UTF-8");
120
121
        // generate filename if there were collisions
122 2
        $currentFilePath = $file->getPath();
123 2
        $basePath = '/' . $userId . '/files/Notes/';
124 2
        $fileExtension = pathinfo($file->getName(), PATHINFO_EXTENSION);
125 2
        $newFilePath = $basePath . $this->generateFileName($folder, $title, $fileExtension, $id);
126
127
        // if the current path is not the new path, the file has to be renamed
128 2
        if($currentFilePath !== $newFilePath) {
129 2
            $file->move($newFilePath);
130 2
        }
131
132 2
        $file->putContent($content);
133
134 2
        return Note::fromFile($file);
135
    }
136
137
138
    /**
139
     * Deletes a note
140
     * @param int $id the id of the note which should be deleted
141
     * @param string $userId
142
     * @throws NoteDoesNotExistException if note does not
143
     * exist
144
     */
145 3
    public function delete ($id, $userId) {
146 3
        $folder = $this->getFolderForUser($userId);
147 3
        $file = $this->getFileById($folder, $id);
148 1
        $file->delete();
149 1
    }
150
151
152
    /**
153
     * @param Folder $folder
154
     * @param int $id
155
     * @throws NoteDoesNotExistException
156
     * @return \OCP\Files\File
157
     */
158 8
    private function getFileById ($folder, $id) {
159 8
        $file = $folder->getById($id);
160
161 8
        if(count($file) <= 0 || !$this->isNote($file[0])) {
162 4
            throw new NoteDoesNotExistException();
163
        }
164
165 4
        return $file[0];
166
    }
167
168
169
    /**
170
     * @param string $userId the user id
171
     * @return Folder
172
     */
173 11
    private function getFolderForUser ($userId) {
174 11
        $path = '/' . $userId . '/files/Notes';
175 11
        if ($this->root->nodeExists($path)) {
176 11
            $folder = $this->root->get($path);
177 11
        } else {
178
            $folder = $this->root->newFolder($path);
179
        }
180 11
        return $folder;
181
    }
182
183
184
    /**
185
     * get path of file and the title.txt and check if they are the same
186
     * file. If not the title needs to be renamed
187
     *
188
     * @param Folder $folder a folder to the notes directory
189
     * @param string $title the filename which should be used
190
     * @param string $extension the extension which should be used
191
     * @param int $id the id of the note for which the title should be generated
192
     * used to see if the file itself has the title and not a different file for
193
     * checking for filename collisions
194
     * @return string the resolved filename to prevent overwriting different
195
     * files with the same title
196
     */
197 4
    private function generateFileName (Folder $folder, $title, $extension, $id) {
198 4
        $path = $title . '.' . $extension;
199
200
        // if file does not exist, that name has not been taken. Similar we don't
201
        // need to handle file collisions if it is the filename did not change
202 4
        if (!$folder->nodeExists($path) || $folder->get($path)->getId() === $id) {
203 4
            return $path;
204
        } else {
205
            // increments name (2) to name (3)
206 3
            $match = preg_match('/\((?P<id>\d+)\)$/', $title, $matches);
207 3
            if($match) {
208 3
                $newId = ((int) $matches['id']) + 1;
209 3
                $newTitle = preg_replace('/(.*)\s\((\d+)\)$/',
210 3
                    '$1 (' . $newId . ')', $title);
211 3
            } else {
212 3
                $newTitle = $title . ' (2)';
213
            }
214 3
            return $this->generateFileName($folder, $newTitle, $extension, $id);
215
        }
216
    }
217
218
    /**
219
     * test if file is a note
220
     *
221
     * @param \OCP\Files\File $file
222
     * @return bool
223
     */
224 7
    private function isNote($file) {
225 7
        $allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note'];
226
227 7
        if($file->getType() !== 'file') return false;
228 7
        if(!in_array(
229 7
            pathinfo($file->getName(), PATHINFO_EXTENSION),
230
            $allowedExtensions
231 7
        )) return false;
232
233 5
        return true;
234
    }
235
236
}
237