Completed
Push — master ( 3d30c3...97b2e9 )
by
unknown
08:12
created

NotesService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
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
        $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 = substr($title, 0, 100);
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
        \OCP\Util::writeLog('notes', print_r(Note::fromFile($file), true), \OCP\Util::ERROR);
135
136 2
        return Note::fromFile($file);
137
    }
138
139
140
    /**
141
     * Deletes a note
142
     * @param int $id the id of the note which should be deleted
143
     * @param string $userId
144
     * @throws NoteDoesNotExistException if note does not
145
     * exist
146
     */
147 3
    public function delete ($id, $userId) {
148 3
        $folder = $this->getFolderForUser($userId);
149 3
        $file = $this->getFileById($folder, $id);
150 1
        $file->delete();
151 1
    }
152
153
154
    /**
155
     * @param Folder $folder
156
     * @param int $id
157
     * @throws NoteDoesNotExistException
158
     * @return \OCP\Files\File
159
     */
160 8
    private function getFileById ($folder, $id) {
161 8
        $file = $folder->getById($id);
162
163 8
        if(count($file) <= 0 || !$this->isNote($file[0])) {
164 4
            throw new NoteDoesNotExistException();
165
        }
166
167 4
        return $file[0];
168
    }
169
170
171
    /**
172
     * @param string $userId the user id
173
     * @return Folder
174
     */
175 11
    private function getFolderForUser ($userId) {
176 11
        $path = '/' . $userId . '/files/Notes';
177 11
        if ($this->root->nodeExists($path)) {
178 11
            $folder = $this->root->get($path);
179 11
        } else {
180
            $folder = $this->root->newFolder($path);
181
        }
182 11
        return $folder;
183
    }
184
185
186
    /**
187
     * get path of file and the title.txt and check if they are the same
188
     * file. If not the title needs to be renamed
189
     *
190
     * @param Folder $folder a folder to the notes directory
191
     * @param string $title the filename which should be used
192
     * @param string $extension the extension which should be used
193
     * @param int $id the id of the note for which the title should be generated
194
     * used to see if the file itself has the title and not a different file for
195
     * checking for filename collisions
196
     * @return string the resolved filename to prevent overwriting different
197
     * files with the same title
198
     */
199 4
    private function generateFileName (Folder $folder, $title, $extension, $id) {
200 4
        $path = $title . '.' . $extension;
201
202
        // if file does not exist, that name has not been taken. Similar we don't
203
        // need to handle file collisions if it is the filename did not change
204 4
        if (!$folder->nodeExists($path) || $folder->get($path)->getId() === $id) {
205 4
            return $path;
206
        } else {
207
            // increments name (2) to name (3)
208 3
            $match = preg_match('/\((?P<id>\d+)\)$/', $title, $matches);
209 3
            if($match) {
210 3
                $newId = ((int) $matches['id']) + 1;
211 3
                $newTitle = preg_replace('/(.*)\s\((\d+)\)$/',
212 3
                    '$1 (' . $newId . ')', $title);
213 3
            } else {
214 3
                $newTitle = $title . ' (2)';
215
            }
216 3
            return $this->generateFileName($folder, $newTitle, $extension, $id);
217
        }
218
    }
219
220
    /**
221
     * test if file is a note
222
     *
223
     * @param \OCP\Files\File $file
224
     * @return bool
225
     */
226 7
    private function isNote($file) {
227 7
        $allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note'];
228
229 7
        if($file->getType() !== 'file') return false;
230 7
        if(!in_array(
231 7
            pathinfo($file->getName(), PATHINFO_EXTENSION),
232
            $allowedExtensions
233 7
        )) return false;
234
235 5
        return true;
236
    }
237
238
}
239