Failed Conditions
Pull Request — master (#6)
by Sander
01:53
created

lib/backend.php (14 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 35 and the first side effect is on line 26.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Nextcloud - ownnote
4
 *
5
 * @copyright Copyright (c) 2015, Ben Curtis <[email protected]>
6
 * @copyright Copyright (c) 2017, Sander Brand ([email protected])
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\OwnNote\Lib;
25
26
\OCP\User::checkLoggedIn();
27
28
use DateTime;
29
use DOMDocument;
30
use OC\Files\Filesystem;
31
use OCA\Admin_Audit\Actions\UserManagement;
32
use OCP\IConfig;
33
use OCP\IL10N;
34
35
class Backend {
36
37
38
	private $db;
39
	private $config;
40
41
	/**
42
	 * Backend constructor.
43
	 *
44
	 * @param $userManager \OC\User\Manager
45
	 * @param IConfig $config
46
	 */
47
	public function __construct(IConfig $config) {
48
		$this->db = \OC::$server->getDatabaseConnection();
49
		$this->config = $config;
50
	}
51
52
	/**
53
	 * @param $haystack
54
	 * @param $needle
55
	 * @return bool
56
	 */
57
	public function startsWith($haystack, $needle) {
58
		return $needle === "" || strripos($haystack, $needle, -strlen($haystack)) !== false;
59
	}
60
61
	/**
62
	 * @param $string
63
	 * @param $test
64
	 * @return bool
65
	 */
66 View Code Duplication
	public function endsWith($string, $test) {
1 ignored issue
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
		$strlen = strlen($string);
68
		$testlen = strlen($test);
69
		if ($testlen > $strlen) return false;
70
		return substr_compare($string, $test, $strlen - $testlen, $testlen, true) === 0;
71
	}
72
73
	/**
74
	 * @param $folder
75
	 * @param $file
76
	 */
77
	public function checkEvernote($folder, $file) {
78
		$html = "";
79
		if ($html = Filesystem::file_get_contents($folder . "/" . $file)) {
80
			$DOM = new DOMDocument;
81
			$DOM->loadHTML($html);
82
			$items = $DOM->getElementsByTagName('meta');
83
			$isEvernote = false;
84 View Code Duplication
			for ($i = 0; $i < $items->length; $i++) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
				$item = $items->item($i);
86
				if ($item->hasAttributes()) {
87
					$attrs = $item->attributes;
88
					foreach ($attrs as $a => $attr) {
89
						if ($attr->name == "name") {
90
							if ($attr->value == "exporter-version" || $attr->value == "Generator") {
91
								$isEvernote = true;
92
								continue;
93
							}
94
						}
95
					}
96
				}
97
			}
98
			if ($isEvernote) {
99
				$items = $DOM->getElementsByTagName('img');
100
				$isEvernote = false;
101
				for ($i = 0; $i < $items->length; $i++) {
102
					$item = $items->item($i);
103
					if ($item->hasAttributes()) {
104
						$attrs = $item->attributes;
105
						foreach ($attrs as $a => $attr) {
106
							if ($attr->name == "src") {
107
								$url = $attr->value;
108
								if (!$this->startsWith($url, "http") && !$this->startsWith($url, "/") && !$this->startsWith($url, "data")) {
109 View Code Duplication
									if ($data = Filesystem::file_get_contents($folder . "/" . $url)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
										$type = pathinfo($url, PATHINFO_EXTENSION);
111
										$base64 = "data:image/" . $type . ";base64," . base64_encode($data);
112
										$html = str_replace($url, $base64, $html);
113
									}
114
								}
115
							}
116
						}
117
					}
118
				}
119
				Filesystem::file_put_contents($folder . "/" . $file, $html);
120
			}
121
		}
122
	}
123
124
	/**
125
	 * @param $filetime DateTime
126
	 * @param $now DateTime
127
	 * @param $l IL10N
128
	 * @return mixed|string
129
	 */
130 View Code Duplication
	public function getTimeString($filetime, $now, $l) {
1 ignored issue
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
		$difftime = $filetime->diff($now);
132
		$years = $difftime->y;
133
		$months = $difftime->m;
134
		$days = $difftime->d;
135
		$hours = $difftime->h;
136
		$minutes = $difftime->i;
137
		$seconds = $difftime->s;
138
		$timestring = "";
139
		if ($timestring == "" && $years == 1) $timestring = str_replace('#', $years, $l->t("# year ago"));
140
		if ($timestring == "" && $years > 0) $timestring = str_replace('#', $years, $l->t("# years ago"));
141
		if ($timestring == "" && $months == 1) $timestring = str_replace('#', $months, $l->t("# month ago"));
142
		if ($timestring == "" && $months > 0) $timestring = str_replace('#', $months, $l->t("# months ago"));
143
		if ($timestring == "" && $days == 1) $timestring = str_replace('#', $days, $l->t("# day ago"));
144
		if ($timestring == "" && $days > 0) $timestring = str_replace('#', $days, $l->t("# days ago"));
145
		if ($timestring == "" && $hours == 1) $timestring = str_replace('#', $hours, $l->t("# hour ago"));
146
		if ($timestring == "" && $hours > 0) $timestring = str_replace('#', $hours, $l->t("# hours ago"));
147
		if ($timestring == "" && $minutes == 1) $timestring = str_replace('#', $minutes, $l->t("# minute ago"));
148
		if ($timestring == "" && $minutes > 0) $timestring = str_replace('#', $minutes, $l->t("# minutes ago"));
149
		if ($timestring == "" && $seconds == 1) $timestring = str_replace('#', $seconds, $l->t("# second ago"));
150
		if ($timestring == "" && $seconds > 0) $timestring = str_replace('#', $seconds, $l->t("# seconds ago"));
151
		return $timestring;
152
	}
153
154
	/**
155
	 * @param $str
156
	 * @return array
157
	 */
158 View Code Duplication
	public function splitContent($str) {
1 ignored issue
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
		$maxlength = 2621440; // 5 Megs (2 bytes per character)
160
		$count = 0;
161
		$strarray = array();
162
		while (true) {
163
			if (strlen($str) <= $maxlength) {
164
				$strarray[$count++] = $str;
165
				return $strarray;
166
			} else {
167
				$strarray[$count++] = substr($str, 0, $maxlength);
168
				$str = substr($str, $maxlength);
169
			}
170
		}
171
		return $strarray;
172
	}
173
174
	/**
175
	 * Returns a user's owned and shared notes
176
	 *
177
	 * @param string $uid the user's id
178
	 * @return array the owned notes (uid=uid) and shared notes (OwnnoteShareBackend)
179
	 */
180
	private function queryNotesWithUser($uid) {
181
		// Get owned notes
182
183
		$query = $this->db->executeQuery("SELECT id, uid, name, grouping, mtime, deleted FROM *PREFIX*ownnote WHERE uid=? ORDER BY name", Array($uid));
184
		$results = $query->fetchAll();
185
		// Get shares
186
		$shared_items = \OCP\Share::getItemsSharedWith('ownnote', 'populated_shares');
187
188
		return array_merge($results, $shared_items);
189
	}
190
191
	/**
192
	 * @param $FOLDER
193
	 * @param $showdel
194
	 * @return array
195
	 */
196
	public function getListing($FOLDER, $showdel) {
197
		// Get the listing from the database
198
		$requery = false;
199
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
200
		$results = $this->queryNotesWithUser($uid);
201
202
		$results2 = $results;
203
		if ($results)
204
			foreach ($results as $result) {
205
				foreach ($results2 as $result2) {
206 View Code Duplication
					if ($result['id'] != $result2['id'] && $result['name'] == $result2['name'] && $result['grouping'] == $result2['grouping']) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
207
						// We have a duplicate that should not exist. Need to remove the offending record first
208
						$delid = -1;
209
						if ($result['mtime'] == $result2['mtime']) {
210
							// If the mtime's match, delete the oldest ID.
211
							$delid = $result['id'];
212
							if ($result['id'] > $result2['id'])
213
								$delid = $result2['id'];
214
						} elseif ($result['mtime'] > $result2['mtime']) {
215
							// Again, delete the oldest
216
							$delid = $result2['id'];
217
						} elseif ($result['mtime'] < $result2['mtime']) {
218
							// The only thing left is if result is older
219
							$delid = $result['id'];
220
						}
221
						if ($delid != -1) {
222
							$this->db->executeQuery("DELETE FROM *PREFIX*ownnote WHERE id=?", Array($delid));
223
							$requery = true;
224
						}
225
					}
226
				}
227
			}
228
		if ($requery) {
229
			$results = $this->queryNotesWithUser($uid);
230
			$requery = false;
231
		}
232
		// Tests to add a bunch of notes
233
		//$now = new DateTime();
234
		//for ($x = 0; $x < 199; $x++) {
235
		//saveNote('', "Test ".$x, '', '', $now->getTimestamp());
236
		//}
237
		$farray = array();
238
		if ($FOLDER != '') {
239
			// Create the folder if it doesn't exist
240 View Code Duplication
			if (!Filesystem::is_dir($FOLDER)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
				if (!Filesystem::mkdir($FOLDER)) {
242
					\OCP\Util::writeLog('ownnote', 'Could not create ownNote directory.', \OCP\Util::ERROR);
243
					exit;
244
				}
245
			}
246
			// Synchronize files to the database
247
			$filearr = array();
248
			if ($listing = Filesystem::opendir($FOLDER)) {
249
				if (!$listing) {
250
					\OCP\Util::writeLog('ownnote', 'Error listing directory.', \OCP\Util::ERROR);
251
					exit;
252
				}
253
				while (($file = readdir($listing)) !== false) {
254
					$tmpfile = $file;
255
					if ($tmpfile == "." || $tmpfile == "..") continue;
256
					if (!$this->endsWith($tmpfile, ".htm") && !$this->endsWith($tmpfile, ".html")) continue;
257
					if ($info = Filesystem::getFileInfo($FOLDER . "/" . $tmpfile)) {
258
						// Check for EVERNOTE but wait to rename them to get around:
259
						// https://github.com/owncloud/core/issues/16202
260
						if ($this->endsWith($tmpfile, ".html")) {
261
							$this->checkEvernote($FOLDER, $tmpfile);
262
						}
263
						// Separate the name and group name
264
						$name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $tmpfile);
265
						$group = "";
266 View Code Duplication
						if (substr($name, 0, 1) == "[") {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
267
							$end = strpos($name, ']');
268
							$group = substr($name, 1, $end - 1);
269
							$name = substr($name, $end + 1, strlen($name) - $end + 1);
270
							$name = trim($name);
271
						}
272
						// Set array for later checking
273
						$filearr[] = $tmpfile;
274
						// Check to see if the file is in the DB
275
						$fileindb = false;
276
						if ($results)
277
							foreach ($results as $result) {
278
								if ($result['deleted'] == 0)
279
									if ($name == $result['name'] && $group == $result['grouping']) {
280
										$fileindb = true;
281
										// If it is in the DB, check if the filesystem file is newer than the DB
282
										if ($result['mtime'] < $info['mtime']) {
283
											// File is newer, this could happen if a user updates a file
284
											$html = "";
285
											$html = Filesystem::file_get_contents($FOLDER . "/" . $tmpfile);
286
											$this->saveNote('', $result['id'], $html, $info['mtime']);
287
											$requery = true;
288
										}
289
									}
290
							}
291
						if (!$fileindb) {
292
							// If it's not in the DB, add it.
293
							$html = "";
294
							if ($html = Filesystem::file_get_contents($FOLDER . "/" . $tmpfile)) {
295
							} else {
296
								$html = "";
297
							}
298
							$nid = $this->createNote('', $name, $group);
299
							$this->saveNote('', $nid, $html, $info['mtime']);
300
							$requery = true;
301
						}
302
						// We moved the rename down here to overcome the OC issue
303 View Code Duplication
						if ($this->endsWith($tmpfile, ".html")) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
304
							$tmpfile = substr($tmpfile, 0, -1);
305
							if (!Filesystem::file_exists($FOLDER . "/" . $tmpfile)) {
306
								Filesystem::rename($FOLDER . "/" . $file, $FOLDER . "/" . $tmpfile);
307
							}
308
						}
309
					}
310
				}
311
			}
312
			if ($requery) {
313
				$results = $this->queryNotesWithUser($uid);
314
			}
315
			// Now also make sure the files exist, they may not if the user switched folders in admin.
316
			if ($results)
317
				foreach ($results as $result) {
318
					if ($result['deleted'] == 0) {
319
						$tmpfile = $result['name'] . ".htm";
320 View Code Duplication
						if ($result['grouping'] != '')
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
321
							$tmpfile = '[' . $result['grouping'] . '] ' . $result['name'] . '.htm';
322
						$filefound = false;
323
						foreach ($filearr as $f) {
324
							if ($f == $tmpfile) {
325
								$filefound = true;
326
								break;
327
							}
328
						}
329
						if (!$filefound) {
330
							$content = $this->editNote($result['id']);
331
							$this->saveNote($FOLDER,$result['id'], $content, 0);
332
						}
333
					}
334
				}
335
		}
336
		// Now loop through and return the listing
337
		if ($results) {
338
			$count = 0;
339
			$now = new DateTime();
340
			$filetime = new DateTime();
341
			$l = \OCP\Util::getL10N('ownnote');
342
			foreach ($results as $result) {
343
				if ($result['deleted'] == 0 || $showdel == true) {
344
					$filetime->setTimestamp($result['mtime']);
345
					$timestring = $this->getTimeString($filetime, $now, $l);
346
					$f = array();
347
					$f['id'] = $result['id'];
348
					$f['uid'] = $result['uid'];
349
					$f['name'] = $result['name'];
350
					$f['group'] = $result['grouping'];
351
					$f['timestring'] = $timestring;
352
					$f['mtime'] = $result['mtime'];
353
					$f['timediff'] = $now->getTimestamp() - $result['mtime'];
354
					$f['deleted'] = $result['deleted'];
355
356
357
					$shared_with = \OCP\Share::getUsersItemShared('ownnote', $result['id'], $result['uid']);
358
					// add shares (all shares, if it's an owned note, only the user for shared notes (not disclosing other sharees))
359
					$f['shared_with'] = ($result['uid'] == $uid) ? $shared_with : [$uid];
360
361
					$farray[$count] = $f;
362
					$count++;
363
				}
364
			}
365
		}
366
		return $farray;
367
	}
368
369
	/**
370
	 * @param $FOLDER
371
	 * @param $in_name
372
	 * @param $in_group
373
	 * @return int
374
	 */
375
	public function createNote($FOLDER, $in_name, $in_group) {
376
		$name = str_replace("\\", "-", str_replace("/", "-", $in_name));
377
		$group = str_replace("\\", "-", str_replace("/", "-", $in_group));
378
		$now = new DateTime();
379
		$mtime = $now->getTimestamp();
380
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
381
		$fileindb = false;
382
		$filedeldb = false;
383
		$ret = -1;
384
		$query = $this->db->executeQuery("SELECT id, uid, name, grouping, mtime, deleted FROM *PREFIX*ownnote WHERE name=? and grouping=? and uid=?", Array($name, $group, $uid));
385
		$results = $query->fetchAll();
386
		foreach ($results as $result) {
387
			if ($result['deleted'] == 0) {
388
				$fileindb = true;
389
				$ret = $result['id'];
390
			} else {
391
				$filedeldb = true;
392
			}
393
		}
394
		if ($filedeldb) {
395
			$this->db->executeQuery("DELETE FROM *PREFIX*ownnote WHERE name=? and grouping=? and uid=?", Array($name, $group, $uid));
396
		}
397
		// new note
398
		if (!$fileindb) {
399 View Code Duplication
			if ($FOLDER != '') {
400
				$tmpfile = $FOLDER . "/" . $name . ".htm";
401
				if ($group != '')
402
					$tmpfile = $FOLDER . "/[" . $group . "] " . $name . ".htm";
403
				if (!Filesystem::file_exists($tmpfile)) {
404
					Filesystem::touch($tmpfile);
405
				}
406
				if ($info = Filesystem::getFileInfo($tmpfile)) {
407
					$mtime = $info['mtime'];
408
				}
409
			}
410
			$this->db->executeQuery("INSERT INTO *PREFIX*ownnote (uid, name, grouping, mtime, note, shared) VALUES (?,?,?,?,?,?)", Array($uid, $name, $group, $mtime, '', ''));
411
			$ret = $this->db->lastInsertId('*PREFIX*ownnote');
412
		}
413
		return $ret;
414
	}
415
416
	/**
417
	 * @param $FOLDER
418
	 * @param $nid
419
	 * @return bool
420
	 */
421
	public function deleteNote($FOLDER, $nid) {
422
		if (!$this->checkPermissions(\OCP\Constants::PERMISSION_DELETE, $nid)) {
423
			return false;
424
		}
425
426
		$now = new DateTime();
427
		$mtime = $now->getTimestamp();
428
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
0 ignored issues
show
$uid is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
429
		$note = $this->getNote($nid);
430
		$name = $note['name'];
431
		$group = $note['group'];
432
		$this->db->executeQuery("UPDATE *PREFIX*ownnote set note='', deleted=1, mtime=? WHERE id=?", Array($mtime, $nid));
433
		//$results = $query->fetchAll();
434
435
		$this->db->executeQuery("DELETE FROM *PREFIX*ownnote_parts WHERE id=?", Array($nid));
436
437 View Code Duplication
		if ($FOLDER != '') {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
438
			$tmpfile = $FOLDER . "/" . $name . ".htm";
439
			if ($group != '')
440
				$tmpfile = $FOLDER . "/[" . $group . "] " . $name . ".htm";
441
			if (Filesystem::file_exists($tmpfile))
442
				Filesystem::unlink($tmpfile);
443
		}
444
		return true;
445
	}
446
447
	/**
448
	 * @param $id
449
	 * @return string
450
	 */
451
	public function editNote($id) {
452
		$retVal = "";
453
		$note = $this->getNote($id);
454
455
		// query parts
456
		$query = $this->db->executeQuery("SELECT note FROM *PREFIX*ownnote_parts WHERE id=? order by pid", Array($note['id']));
457
		$results = $query->fetchAll();
458
		foreach ($results as $result) {
459
			$retVal .= $result['note'];
460
		}
461
462
		return $retVal;
463
	}
464
465
	/**
466
	 * @param $FOLDER
467
	 * @param $nid
468
	 * @param $content
469
	 * @param $in_mtime
470
	 * @return bool
471
	 */
472
	public function saveNote($FOLDER, $nid, $content, $in_mtime) {
473
		$maxlength = 2621440; // 5 Megs (2 bytes per character)
474
		$now = new DateTime();
475
		$mtime = $now->getTimestamp();
476
		if ($in_mtime != 0) {
477
			$mtime = $in_mtime;
478
		}
479
480
		// get the specific note
481
		$note = $this->getNote($nid);
482
		$name = $note['name'];
483
		$group = $note['grouping'];
484
485 View Code Duplication
		if ($FOLDER != '') {
486
			$tmpfile = $FOLDER . "/" . $name . ".htm";
487
			if ($group != '')
488
				$tmpfile = $FOLDER . "/[" . $group . "] " . $name . ".htm";
489
			Filesystem::file_put_contents($tmpfile, $content);
490
			if ($info = Filesystem::getFileInfo($tmpfile)) {
491
				$mtime = $info['mtime'];
492
			}
493
		}
494
		$this->db->executeQuery("UPDATE *PREFIX*ownnote set note='', mtime=? WHERE id=?", Array($mtime, $note['id']));
495
496
		$this->db->executeQuery("DELETE FROM *PREFIX*ownnote_parts WHERE id=?", Array($note['id']));
497
		$contentarr = $this->splitContent($content);
498
		for ($i = 0; $i < count($contentarr); $i++) {
499
			$this->db->executeQuery("INSERT INTO *PREFIX*ownnote_parts (id, note) values (?,?)", Array($note['id'], $contentarr[$i]));
500
		}
501
		return true;
502
	}
503
504
	/**
505
	 * @param $FOLDER
506
	 * @param $id
507
	 * @param $in_newname
508
	 * @param $in_newgroup
509
	 * @return bool
510
	 */
511
	public function renameNote($FOLDER, $id, $in_newname, $in_newgroup) {
512
		$newname = str_replace("\\", "-", str_replace("/", "-", $in_newname));
513
		$newgroup = str_replace("\\", "-", str_replace("/", "-", $in_newgroup));
514
515
		// We actually need to delete and create so that the delete flag exists for syncing clients
516
		$content = $this->editNote($id);
517
		$this->deleteNote($FOLDER, $id);
518
519
		$newId = $this->createNote($FOLDER, $newname, $newgroup);
520
		$this->saveNote($FOLDER, $newId, $content, 0);
521
522
		return true;
523
	}
524
525
	/**
526
	 * @param $FOLDER
527
	 * @param $group
528
	 * @return bool
529
	 */
530 View Code Duplication
	public function deleteGroup($FOLDER, $group) {
531
		// We actually need to just rename all the notes
532
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
533
		$query = $this->db->executeQuery("SELECT id, name, grouping, mtime FROM *PREFIX*ownnote WHERE deleted=0 and uid=? and grouping=?", Array($uid, $group));
534
		$results = $query->fetchAll();
535
		foreach ($results as $result) {
536
			$this->renameNote($FOLDER, $result['id'], $result['name'], '');
537
		}
538
		return true;
539
	}
540
541
	/**
542
	 * @param $FOLDER
543
	 * @param $group
544
	 * @param $newgroup
545
	 * @return bool
546
	 */
547 View Code Duplication
	public function renameGroup($FOLDER, $group, $newgroup) {
548
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
549
		$query = $this->db->executeQuery("SELECT id, name, grouping, mtime FROM *PREFIX*ownnote WHERE deleted=0 and uid=? and grouping=?", Array($uid, $group));
550
		$results = $query->fetchAll();
551
		foreach ($results as $result) {
552
			$this->renameNote($FOLDER, $result['id'], $result['name'], $newgroup);
553
		}
554
		return true;
555
	}
556
557
	/**
558
	 * @return string
559
	 */
560
	public function getVersion() {
561
		$v = file_get_contents(__DIR__ . "/../appinfo/version");
562
		if ($v)
563
			return trim($v);
564
		else
565
			return "";
566
	}
567
568
	/**
569
	 * @param $option
570
	 * @param $value
571
	 */
572
	public function setAdminVal($option, $value) {
573
		$this->config->setAppValue('ownnote', $option, $value);
574
		return true;
575
	}
576
577
	/**
578
	 * @param $noteid
579
	 * @return mixed
580
	 */
581
	private function getNote($noteid) {
582
		$query = $this->db->executeQuery("SELECT id, uid, name, grouping, mtime, note, deleted FROM *PREFIX*ownnote WHERE id=?", Array($noteid));
583
		$result = array_shift($query->fetchAll());
584
		return $result;
585
	}
586
587
	/**
588
	 * @param $permission
589
	 * @param $nid
590
	 * @return bool|int
591
	 */
592 View Code Duplication
	private function checkPermissions($permission, $nid) {
1 ignored issue
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
593
		// gather information
594
		$uid = \OC::$server->getUserSession()->getUser()->getUID();
595
		$note = $this->getNote($nid);
596
		// owner is allowed to change everything
597
		if ($uid === $note['uid']) {
598
			return true;
599
		}
600
601
		// check share permissions
602
		$shared_note = \OCP\Share::getItemSharedWith('ownnote', $nid, 'populated_shares')[0];
603
		return $shared_note['permissions'] & $permission;
604
	}
605
}
606
607
?>
608