Completed
Pull Request — master (#3218)
by Vars
46:46 queued 34:29
created
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.
lib/private/Share/MailNotifications.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 
31 31
 namespace OC\Share;
32 32
 
33
-use DateTime;
34 33
 use OCP\IL10N;
35 34
 use OCP\IURLGenerator;
36 35
 use OCP\IUser;
Please login to merge, or discard this patch.
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -46,113 +46,113 @@
 block discarded – undo
46 46
  */
47 47
 class MailNotifications {
48 48
 
49
-	/** @var IUser sender userId */
50
-	private $user;
51
-	/** @var string sender email address */
52
-	private $replyTo;
53
-	/** @var string */
54
-	private $senderDisplayName;
55
-	/** @var IL10N */
56
-	private $l;
57
-	/** @var IMailer */
58
-	private $mailer;
59
-	/** @var Defaults */
60
-	private $defaults;
61
-	/** @var ILogger */
62
-	private $logger;
63
-	/** @var IURLGenerator */
64
-	private $urlGenerator;
49
+    /** @var IUser sender userId */
50
+    private $user;
51
+    /** @var string sender email address */
52
+    private $replyTo;
53
+    /** @var string */
54
+    private $senderDisplayName;
55
+    /** @var IL10N */
56
+    private $l;
57
+    /** @var IMailer */
58
+    private $mailer;
59
+    /** @var Defaults */
60
+    private $defaults;
61
+    /** @var ILogger */
62
+    private $logger;
63
+    /** @var IURLGenerator */
64
+    private $urlGenerator;
65 65
 
66
-	/**
67
-	 * @param IUser $user
68
-	 * @param IL10N $l10n
69
-	 * @param IMailer $mailer
70
-	 * @param ILogger $logger
71
-	 * @param Defaults $defaults
72
-	 * @param IURLGenerator $urlGenerator
73
-	 */
74
-	public function __construct(IUser $user,
75
-								IL10N $l10n,
76
-								IMailer $mailer,
77
-								ILogger $logger,
78
-								Defaults $defaults,
79
-								IURLGenerator $urlGenerator) {
80
-		$this->l = $l10n;
81
-		$this->user = $user;
82
-		$this->mailer = $mailer;
83
-		$this->logger = $logger;
84
-		$this->defaults = $defaults;
85
-		$this->urlGenerator = $urlGenerator;
66
+    /**
67
+     * @param IUser $user
68
+     * @param IL10N $l10n
69
+     * @param IMailer $mailer
70
+     * @param ILogger $logger
71
+     * @param Defaults $defaults
72
+     * @param IURLGenerator $urlGenerator
73
+     */
74
+    public function __construct(IUser $user,
75
+                                IL10N $l10n,
76
+                                IMailer $mailer,
77
+                                ILogger $logger,
78
+                                Defaults $defaults,
79
+                                IURLGenerator $urlGenerator) {
80
+        $this->l = $l10n;
81
+        $this->user = $user;
82
+        $this->mailer = $mailer;
83
+        $this->logger = $logger;
84
+        $this->defaults = $defaults;
85
+        $this->urlGenerator = $urlGenerator;
86 86
 
87
-		$this->replyTo = $this->user->getEMailAddress();
88
-		$this->senderDisplayName = $this->user->getDisplayName();
89
-	}
87
+        $this->replyTo = $this->user->getEMailAddress();
88
+        $this->senderDisplayName = $this->user->getDisplayName();
89
+    }
90 90
 
91
-	/**
92
-	 * inform recipient about public link share
93
-	 *
94
-	 * @param string $recipient recipient email address
95
-	 * @param string $filename the shared file
96
-	 * @param string $link the public link
97
-	 * @param int $expiration expiration date (timestamp)
98
-	 * @return string[] $result of failed recipients
99
-	 */
100
-	public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
-		$subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102
-		list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
91
+    /**
92
+     * inform recipient about public link share
93
+     *
94
+     * @param string $recipient recipient email address
95
+     * @param string $filename the shared file
96
+     * @param string $link the public link
97
+     * @param int $expiration expiration date (timestamp)
98
+     * @return string[] $result of failed recipients
99
+     */
100
+    public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
+        $subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102
+        list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
103 103
 
104
-		$recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
105
-		$recipients = explode(',', $recipient);
106
-		try {
107
-			$message = $this->mailer->createMessage();
108
-			$message->setSubject($subject);
109
-			$message->setTo($recipients);
110
-			$message->setHtmlBody($htmlBody);
111
-			$message->setPlainBody($textBody);
112
-			$message->setFrom([
113
-				Util::getDefaultEmailAddress('sharing-noreply') =>
114
-					(string)$this->l->t('%s via %s', [
115
-						$this->senderDisplayName,
116
-						$this->defaults->getName()
117
-					]),
118
-			]);
119
-			if(!is_null($this->replyTo)) {
120
-				$message->setReplyTo([$this->replyTo]);
121
-			}
104
+        $recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
105
+        $recipients = explode(',', $recipient);
106
+        try {
107
+            $message = $this->mailer->createMessage();
108
+            $message->setSubject($subject);
109
+            $message->setTo($recipients);
110
+            $message->setHtmlBody($htmlBody);
111
+            $message->setPlainBody($textBody);
112
+            $message->setFrom([
113
+                Util::getDefaultEmailAddress('sharing-noreply') =>
114
+                    (string)$this->l->t('%s via %s', [
115
+                        $this->senderDisplayName,
116
+                        $this->defaults->getName()
117
+                    ]),
118
+            ]);
119
+            if(!is_null($this->replyTo)) {
120
+                $message->setReplyTo([$this->replyTo]);
121
+            }
122 122
 
123
-			return $this->mailer->send($message);
124
-		} catch (\Exception $e) {
125
-			$this->logger->error("Can't send mail with public link to $recipient: ".$e->getMessage(), ['app' => 'sharing']);
126
-			return [$recipient];
127
-		}
128
-	}
123
+            return $this->mailer->send($message);
124
+        } catch (\Exception $e) {
125
+            $this->logger->error("Can't send mail with public link to $recipient: ".$e->getMessage(), ['app' => 'sharing']);
126
+            return [$recipient];
127
+        }
128
+    }
129 129
 
130
-	/**
131
-	 * create mail body for plain text and html mail
132
-	 *
133
-	 * @param string $filename the shared file
134
-	 * @param string $link link to the shared file
135
-	 * @param int $expiration expiration date (timestamp)
136
-	 * @param string $prefix prefix of mail template files
137
-	 * @return array an array of the html mail body and the plain text mail body
138
-	 */
139
-	private function createMailBody($filename, $link, $expiration, $prefix = '') {
140
-		$formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
130
+    /**
131
+     * create mail body for plain text and html mail
132
+     *
133
+     * @param string $filename the shared file
134
+     * @param string $link link to the shared file
135
+     * @param int $expiration expiration date (timestamp)
136
+     * @param string $prefix prefix of mail template files
137
+     * @return array an array of the html mail body and the plain text mail body
138
+     */
139
+    private function createMailBody($filename, $link, $expiration, $prefix = '') {
140
+        $formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
141 141
 
142
-		$html = new \OC_Template('core', $prefix . 'mail', '');
143
-		$html->assign ('link', $link);
144
-		$html->assign ('user_displayname', $this->senderDisplayName);
145
-		$html->assign ('filename', $filename);
146
-		$html->assign('expiration',  $formattedDate);
147
-		$htmlMail = $html->fetchPage();
142
+        $html = new \OC_Template('core', $prefix . 'mail', '');
143
+        $html->assign ('link', $link);
144
+        $html->assign ('user_displayname', $this->senderDisplayName);
145
+        $html->assign ('filename', $filename);
146
+        $html->assign('expiration',  $formattedDate);
147
+        $htmlMail = $html->fetchPage();
148 148
 
149
-		$plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
-		$plainText->assign ('link', $link);
151
-		$plainText->assign ('user_displayname', $this->senderDisplayName);
152
-		$plainText->assign ('filename', $filename);
153
-		$plainText->assign('expiration', $formattedDate);
154
-		$plainTextMail = $plainText->fetchPage();
149
+        $plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
+        $plainText->assign ('link', $link);
151
+        $plainText->assign ('user_displayname', $this->senderDisplayName);
152
+        $plainText->assign ('filename', $filename);
153
+        $plainText->assign('expiration', $formattedDate);
154
+        $plainTextMail = $plainText->fetchPage();
155 155
 
156
-		return [$htmlMail, $plainTextMail];
157
-	}
156
+        return [$htmlMail, $plainTextMail];
157
+    }
158 158
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 	 * @return string[] $result of failed recipients
99 99
 	 */
100 100
 	public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
-		$subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
101
+		$subject = (string) $this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102 102
 		list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
103 103
 
104 104
 		$recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
@@ -111,12 +111,12 @@  discard block
 block discarded – undo
111 111
 			$message->setPlainBody($textBody);
112 112
 			$message->setFrom([
113 113
 				Util::getDefaultEmailAddress('sharing-noreply') =>
114
-					(string)$this->l->t('%s via %s', [
114
+					(string) $this->l->t('%s via %s', [
115 115
 						$this->senderDisplayName,
116 116
 						$this->defaults->getName()
117 117
 					]),
118 118
 			]);
119
-			if(!is_null($this->replyTo)) {
119
+			if (!is_null($this->replyTo)) {
120 120
 				$message->setReplyTo([$this->replyTo]);
121 121
 			}
122 122
 
@@ -139,17 +139,17 @@  discard block
 block discarded – undo
139 139
 	private function createMailBody($filename, $link, $expiration, $prefix = '') {
140 140
 		$formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
141 141
 
142
-		$html = new \OC_Template('core', $prefix . 'mail', '');
143
-		$html->assign ('link', $link);
144
-		$html->assign ('user_displayname', $this->senderDisplayName);
145
-		$html->assign ('filename', $filename);
146
-		$html->assign('expiration',  $formattedDate);
142
+		$html = new \OC_Template('core', $prefix.'mail', '');
143
+		$html->assign('link', $link);
144
+		$html->assign('user_displayname', $this->senderDisplayName);
145
+		$html->assign('filename', $filename);
146
+		$html->assign('expiration', $formattedDate);
147 147
 		$htmlMail = $html->fetchPage();
148 148
 
149
-		$plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
-		$plainText->assign ('link', $link);
151
-		$plainText->assign ('user_displayname', $this->senderDisplayName);
152
-		$plainText->assign ('filename', $filename);
149
+		$plainText = new \OC_Template('core', $prefix.'altmail', '');
150
+		$plainText->assign('link', $link);
151
+		$plainText->assign('user_displayname', $this->senderDisplayName);
152
+		$plainText->assign('filename', $filename);
153 153
 		$plainText->assign('expiration', $formattedDate);
154 154
 		$plainTextMail = $plainText->fetchPage();
155 155
 
Please login to merge, or discard this patch.
lib/private/legacy/app.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,6 @@
 block discarded – undo
51 51
 use OC\App\InfoParser;
52 52
 use OC\App\Platform;
53 53
 use OC\Installer;
54
-use OC\OCSClient;
55 54
 use OC\Repair;
56 55
 use OCP\App\ManagerEvent;
57 56
 
Please login to merge, or discard this patch.
Doc Comments   +6 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 	 * @param string $app
1064 1064
 	 * @param \OCP\IConfig $config
1065 1065
 	 * @param \OCP\IL10N $l
1066
-	 * @return bool
1066
+	 * @return string
1067 1067
 	 *
1068 1068
 	 * @throws Exception if app is not compatible with this version of ownCloud
1069 1069
 	 * @throws Exception if no app-name was specified
@@ -1243,6 +1243,11 @@  discard block
 block discarded – undo
1243 1243
 		}
1244 1244
 	}
1245 1245
 
1246
+	/**
1247
+	 * @param string $lang
1248
+	 *
1249
+	 * @return string
1250
+	 */
1246 1251
 	protected static function findBestL10NOption($options, $lang) {
1247 1252
 		$fallback = $similarLangFallback = $englishFallback = false;
1248 1253
 
Please login to merge, or discard this patch.
Indentation   +1334 added lines, -1334 removed lines patch added patch discarded remove patch
@@ -61,1338 +61,1338 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * @internal
181
-	 * @param string $app
182
-	 * @param string $path
183
-	 */
184
-	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
187
-			return;
188
-		}
189
-		self::$alreadyRegistered[$key] = true;
190
-		// Register on PSR-4 composer autoloader
191
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
-		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
-		}
197
-
198
-		// Register on legacy autoloader
199
-		\OC::$loader->addValidRoot($path);
200
-	}
201
-
202
-	/**
203
-	 * Load app.php from the given app
204
-	 *
205
-	 * @param string $app app name
206
-	 */
207
-	private static function requireAppFile($app) {
208
-		try {
209
-			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
211
-		} catch (Error $ex) {
212
-			\OC::$server->getLogger()->logException($ex);
213
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
-			if (!in_array($app, $blacklist)) {
215
-				self::disable($app);
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * check if an app is of a specific type
222
-	 *
223
-	 * @param string $app
224
-	 * @param string|array $types
225
-	 * @return bool
226
-	 */
227
-	public static function isType($app, $types) {
228
-		if (is_string($types)) {
229
-			$types = array($types);
230
-		}
231
-		$appTypes = self::getAppTypes($app);
232
-		foreach ($types as $type) {
233
-			if (array_search($type, $appTypes) !== false) {
234
-				return true;
235
-			}
236
-		}
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * get the types of an app
242
-	 *
243
-	 * @param string $app
244
-	 * @return array
245
-	 */
246
-	private static function getAppTypes($app) {
247
-		//load the cache
248
-		if (count(self::$appTypes) == 0) {
249
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
-		}
251
-
252
-		if (isset(self::$appTypes[$app])) {
253
-			return explode(',', self::$appTypes[$app]);
254
-		} else {
255
-			return array();
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * read app types from info.xml and cache them in the database
261
-	 */
262
-	public static function setAppTypes($app) {
263
-		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
265
-			return;
266
-		}
267
-
268
-		if (isset($appData['types'])) {
269
-			$appTypes = implode(',', $appData['types']);
270
-		} else {
271
-			$appTypes = '';
272
-			$appData['types'] = [];
273
-		}
274
-
275
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
-
277
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
-			if ($enabled !== 'yes' && $enabled !== 'no') {
280
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
-			}
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * check if app is shipped
287
-	 *
288
-	 * @param string $appId the id of the app to check
289
-	 * @return bool
290
-	 *
291
-	 * Check if an app that is installed is a shipped app or installed from the appstore.
292
-	 */
293
-	public static function isShipped($appId) {
294
-		return \OC::$server->getAppManager()->isShipped($appId);
295
-	}
296
-
297
-	/**
298
-	 * get all enabled apps
299
-	 */
300
-	protected static $enabledAppsCache = array();
301
-
302
-	/**
303
-	 * Returns apps enabled for the current user.
304
-	 *
305
-	 * @param bool $forceRefresh whether to refresh the cache
306
-	 * @param bool $all whether to return apps for all users, not only the
307
-	 * currently logged in one
308
-	 * @return string[]
309
-	 */
310
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
311
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
-			return array();
313
-		}
314
-		// in incognito mode or when logged out, $user will be false,
315
-		// which is also the case during an upgrade
316
-		$appManager = \OC::$server->getAppManager();
317
-		if ($all) {
318
-			$user = null;
319
-		} else {
320
-			$user = \OC::$server->getUserSession()->getUser();
321
-		}
322
-
323
-		if (is_null($user)) {
324
-			$apps = $appManager->getInstalledApps();
325
-		} else {
326
-			$apps = $appManager->getEnabledAppsForUser($user);
327
-		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
330
-		});
331
-		sort($apps);
332
-		array_unshift($apps, 'files');
333
-		return $apps;
334
-	}
335
-
336
-	/**
337
-	 * checks whether or not an app is enabled
338
-	 *
339
-	 * @param string $app app
340
-	 * @return bool
341
-	 *
342
-	 * This function checks whether or not an app is enabled.
343
-	 */
344
-	public static function isEnabled($app) {
345
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
346
-	}
347
-
348
-	/**
349
-	 * enables an app
350
-	 *
351
-	 * @param string $appId
352
-	 * @param array $groups (optional) when set, only these groups will have access to the app
353
-	 * @throws \Exception
354
-	 * @return void
355
-	 *
356
-	 * This function set an app as enabled in appconfig.
357
-	 */
358
-	public function enable($appId,
359
-						   $groups = null) {
360
-		self::$enabledAppsCache = []; // flush
361
-		$l = \OC::$server->getL10N('core');
362
-		$config = \OC::$server->getConfig();
363
-
364
-		// Check if app is already downloaded
365
-		$installer = new Installer(
366
-			\OC::$server->getAppFetcher(),
367
-			\OC::$server->getHTTPClientService(),
368
-			\OC::$server->getTempManager(),
369
-			\OC::$server->getLogger()
370
-		);
371
-		$isDownloaded = $installer->isDownloaded($appId);
372
-
373
-		if(!$isDownloaded) {
374
-			$installer->downloadApp($appId);
375
-		}
376
-
377
-		if (!Installer::isInstalled($appId)) {
378
-			$appId = self::installApp(
379
-				$appId,
380
-				$config,
381
-				$l
382
-			);
383
-			$appPath = self::getAppPath($appId);
384
-			self::registerAutoloading($appId, $appPath);
385
-			$installer->installApp($appId);
386
-		} else {
387
-			// check for required dependencies
388
-			$info = self::getAppInfo($appId);
389
-			self::checkAppDependencies($config, $l, $info);
390
-			$appPath = self::getAppPath($appId);
391
-			self::registerAutoloading($appId, $appPath);
392
-			$installer->installApp($appId);
393
-		}
394
-
395
-		$appManager = \OC::$server->getAppManager();
396
-		if (!is_null($groups)) {
397
-			$groupManager = \OC::$server->getGroupManager();
398
-			$groupsList = [];
399
-			foreach ($groups as $group) {
400
-				$groupItem = $groupManager->get($group);
401
-				if ($groupItem instanceof \OCP\IGroup) {
402
-					$groupsList[] = $groupManager->get($group);
403
-				}
404
-			}
405
-			$appManager->enableAppForGroups($appId, $groupsList);
406
-		} else {
407
-			$appManager->enableApp($appId);
408
-		}
409
-
410
-		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
412
-			$appPath = self::getAppPath($appId);
413
-			self::registerAutoloading($appId, $appPath);
414
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * @param string $app
420
-	 * @return bool
421
-	 */
422
-	public static function removeApp($app) {
423
-		if (self::isShipped($app)) {
424
-			return false;
425
-		}
426
-
427
-		$installer = new Installer(
428
-			\OC::$server->getAppFetcher(),
429
-			\OC::$server->getHTTPClientService(),
430
-			\OC::$server->getTempManager(),
431
-			\OC::$server->getLogger()
432
-		);
433
-		return $installer->removeApp($app);
434
-	}
435
-
436
-	/**
437
-	 * This function set an app as disabled in appconfig.
438
-	 *
439
-	 * @param string $app app
440
-	 * @throws Exception
441
-	 */
442
-	public static function disable($app) {
443
-		// flush
444
-		self::$enabledAppsCache = array();
445
-
446
-		// run uninstall steps
447
-		$appData = OC_App::getAppInfo($app);
448
-		if (!is_null($appData)) {
449
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
-		}
451
-
452
-		// emit disable hook - needed anymore ?
453
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
-
455
-		// finally disable it
456
-		$appManager = \OC::$server->getAppManager();
457
-		$appManager->disableApp($app);
458
-	}
459
-
460
-	/**
461
-	 * Returns the Settings Navigation
462
-	 *
463
-	 * @return string[]
464
-	 *
465
-	 * This function returns an array containing all settings pages added. The
466
-	 * entries are sorted by the key 'order' ascending.
467
-	 */
468
-	public static function getSettingsNavigation() {
469
-		$l = \OC::$server->getL10N('lib');
470
-		$urlGenerator = \OC::$server->getURLGenerator();
471
-
472
-		$settings = array();
473
-		// by default, settings only contain the help menu
474
-		if (\OC::$server->getSystemConfig()->getValue('knowledgebaseenabled', true)) {
475
-			$settings = array(
476
-				array(
477
-					"id" => "help",
478
-					"order" => 4,
479
-					"href" => $urlGenerator->linkToRoute('settings_help'),
480
-					"name" => $l->t("Help"),
481
-					"icon" => $urlGenerator->imagePath("settings", "help.svg")
482
-				)
483
-			);
484
-		}
485
-
486
-		// if the user is logged-in
487
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
488
-			// personal menu
489
-			$settings[] = array(
490
-				"id" => "personal",
491
-				"order" => 1,
492
-				"href" => $urlGenerator->linkToRoute('settings_personal'),
493
-				"name" => $l->t("Personal"),
494
-				"icon" => $urlGenerator->imagePath("settings", "personal.svg")
495
-			);
496
-
497
-			//SubAdmins are also allowed to access user management
498
-			$userObject = \OC::$server->getUserSession()->getUser();
499
-			$isSubAdmin = false;
500
-			if($userObject !== null) {
501
-				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502
-			}
503
-			if ($isSubAdmin) {
504
-				// admin users menu
505
-				$settings[] = array(
506
-					"id" => "core_users",
507
-					"order" => 3,
508
-					"href" => $urlGenerator->linkToRoute('settings_users'),
509
-					"name" => $l->t("Users"),
510
-					"icon" => $urlGenerator->imagePath("settings", "users.svg")
511
-				);
512
-			}
513
-
514
-			// if the user is an admin
515
-			if (OC_User::isAdminUser(OC_User::getUser())) {
516
-				// admin settings
517
-				$settings[] = array(
518
-					"id" => "admin",
519
-					"order" => 2,
520
-					"href" => $urlGenerator->linkToRoute('settings.AdminSettings.index'),
521
-					"name" => $l->t("Admin"),
522
-					"icon" => $urlGenerator->imagePath("settings", "admin.svg")
523
-				);
524
-			}
525
-		}
526
-
527
-		$navigation = self::proceedNavigation($settings);
528
-		return $navigation;
529
-	}
530
-
531
-	// This is private as well. It simply works, so don't ask for more details
532
-	private static function proceedNavigation($list) {
533
-		$headerIconCount = 8;
534
-		if(OC_User::isAdminUser(OC_User::getUser())) {
535
-			$headerIconCount--;
536
-		}
537
-		usort($list, function($a, $b) {
538
-			if (isset($a['order']) && isset($b['order'])) {
539
-				return ($a['order'] < $b['order']) ? -1 : 1;
540
-			} else if (isset($a['order']) || isset($b['order'])) {
541
-				return isset($a['order']) ? -1 : 1;
542
-			} else {
543
-				return ($a['name'] < $b['name']) ? -1 : 1;
544
-			}
545
-		});
546
-
547
-		$activeAppIndex = -1;
548
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
549
-		foreach ($list as $index => &$navEntry) {
550
-			if ($navEntry['id'] == $activeApp) {
551
-				$navEntry['active'] = true;
552
-				$activeAppIndex = $index;
553
-			} else {
554
-				$navEntry['active'] = false;
555
-			}
556
-		}
557
-		unset($navEntry);
558
-
559
-		if($activeAppIndex > ($headerIconCount-1)) {
560
-			$active = $list[$activeAppIndex];
561
-			$lastInHeader = $list[$headerIconCount-1];
562
-			$list[$headerIconCount-1] = $active;
563
-			$list[$activeAppIndex] = $lastInHeader;
564
-		}
565
-
566
-		foreach ($list as $index => &$navEntry) {
567
-			$navEntry['showInHeader'] = false;
568
-			if($index < $headerIconCount) {
569
-				$navEntry['showInHeader'] = true;
570
-			}
571
-		}
572
-
573
-
574
-
575
-		return $list;
576
-	}
577
-
578
-	public static function proceedAppNavigation($entries) {
579
-		$headerIconCount = 8;
580
-		if(OC_User::isAdminUser(OC_User::getUser())) {
581
-			$headerIconCount--;
582
-		}
583
-		$activeAppIndex = -1;
584
-		$list = self::proceedNavigation($entries);
585
-
586
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
587
-		foreach ($list as $index => &$navEntry) {
588
-			if ($navEntry['id'] == $activeApp) {
589
-				$navEntry['active'] = true;
590
-				$activeAppIndex = $index;
591
-			} else {
592
-				$navEntry['active'] = false;
593
-			}
594
-		}
595
-		// move active item to last position
596
-		if($activeAppIndex > ($headerIconCount-1)) {
597
-			$active = $list[$activeAppIndex];
598
-			$lastInHeader = $list[$headerIconCount-1];
599
-			$list[$headerIconCount-1] = $active;
600
-			$list[$activeAppIndex] = $lastInHeader;
601
-		}
602
-		$list = array_slice($list, 0, $headerIconCount);
603
-
604
-		return $list;
605
-	}
606
-
607
-	/**
608
-	 * Get the path where to install apps
609
-	 *
610
-	 * @return string|false
611
-	 */
612
-	public static function getInstallPath() {
613
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
614
-			return false;
615
-		}
616
-
617
-		foreach (OC::$APPSROOTS as $dir) {
618
-			if (isset($dir['writable']) && $dir['writable'] === true) {
619
-				return $dir['path'];
620
-			}
621
-		}
622
-
623
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
624
-		return null;
625
-	}
626
-
627
-
628
-	/**
629
-	 * search for an app in all app-directories
630
-	 *
631
-	 * @param string $appId
632
-	 * @return false|string
633
-	 */
634
-	public static function findAppInDirectories($appId) {
635
-		$sanitizedAppId = self::cleanAppId($appId);
636
-		if($sanitizedAppId !== $appId) {
637
-			return false;
638
-		}
639
-		static $app_dir = array();
640
-
641
-		if (isset($app_dir[$appId])) {
642
-			return $app_dir[$appId];
643
-		}
644
-
645
-		$possibleApps = array();
646
-		foreach (OC::$APPSROOTS as $dir) {
647
-			if (file_exists($dir['path'] . '/' . $appId)) {
648
-				$possibleApps[] = $dir;
649
-			}
650
-		}
651
-
652
-		if (empty($possibleApps)) {
653
-			return false;
654
-		} elseif (count($possibleApps) === 1) {
655
-			$dir = array_shift($possibleApps);
656
-			$app_dir[$appId] = $dir;
657
-			return $dir;
658
-		} else {
659
-			$versionToLoad = array();
660
-			foreach ($possibleApps as $possibleApp) {
661
-				$version = self::getAppVersionByPath($possibleApp['path']);
662
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
663
-					$versionToLoad = array(
664
-						'dir' => $possibleApp,
665
-						'version' => $version,
666
-					);
667
-				}
668
-			}
669
-			$app_dir[$appId] = $versionToLoad['dir'];
670
-			return $versionToLoad['dir'];
671
-			//TODO - write test
672
-		}
673
-	}
674
-
675
-	/**
676
-	 * Get the directory for the given app.
677
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
678
-	 *
679
-	 * @param string $appId
680
-	 * @return string|false
681
-	 */
682
-	public static function getAppPath($appId) {
683
-		if ($appId === null || trim($appId) === '') {
684
-			return false;
685
-		}
686
-
687
-		if (($dir = self::findAppInDirectories($appId)) != false) {
688
-			return $dir['path'] . '/' . $appId;
689
-		}
690
-		return false;
691
-	}
692
-
693
-	/**
694
-	 * Get the path for the given app on the access
695
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
696
-	 *
697
-	 * @param string $appId
698
-	 * @return string|false
699
-	 */
700
-	public static function getAppWebPath($appId) {
701
-		if (($dir = self::findAppInDirectories($appId)) != false) {
702
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
703
-		}
704
-		return false;
705
-	}
706
-
707
-	/**
708
-	 * get the last version of the app from appinfo/info.xml
709
-	 *
710
-	 * @param string $appId
711
-	 * @param bool $useCache
712
-	 * @return string
713
-	 */
714
-	public static function getAppVersion($appId, $useCache = true) {
715
-		if($useCache && isset(self::$appVersion[$appId])) {
716
-			return self::$appVersion[$appId];
717
-		}
718
-
719
-		$file = self::getAppPath($appId);
720
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
721
-		return self::$appVersion[$appId];
722
-	}
723
-
724
-	/**
725
-	 * get app's version based on it's path
726
-	 *
727
-	 * @param string $path
728
-	 * @return string
729
-	 */
730
-	public static function getAppVersionByPath($path) {
731
-		$infoFile = $path . '/appinfo/info.xml';
732
-		$appData = self::getAppInfo($infoFile, true);
733
-		return isset($appData['version']) ? $appData['version'] : '';
734
-	}
735
-
736
-
737
-	/**
738
-	 * Read all app metadata from the info.xml file
739
-	 *
740
-	 * @param string $appId id of the app or the path of the info.xml file
741
-	 * @param bool $path
742
-	 * @param string $lang
743
-	 * @return array|null
744
-	 * @note all data is read from info.xml, not just pre-defined fields
745
-	 */
746
-	public static function getAppInfo($appId, $path = false, $lang = null) {
747
-		if ($path) {
748
-			$file = $appId;
749
-		} else {
750
-			if ($lang === null && isset(self::$appInfo[$appId])) {
751
-				return self::$appInfo[$appId];
752
-			}
753
-			$appPath = self::getAppPath($appId);
754
-			if($appPath === false) {
755
-				return null;
756
-			}
757
-			$file = $appPath . '/appinfo/info.xml';
758
-		}
759
-
760
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
761
-		$data = $parser->parse($file);
762
-
763
-		if (is_array($data)) {
764
-			$data = OC_App::parseAppInfo($data, $lang);
765
-		}
766
-		if(isset($data['ocsid'])) {
767
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
769
-				$data['ocsid'] = $storedId;
770
-			}
771
-		}
772
-
773
-		if ($lang === null) {
774
-			self::$appInfo[$appId] = $data;
775
-		}
776
-
777
-		return $data;
778
-	}
779
-
780
-	/**
781
-	 * Returns the navigation
782
-	 *
783
-	 * @return array
784
-	 *
785
-	 * This function returns an array containing all entries added. The
786
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
787
-	 * given for each app the following keys exist:
788
-	 *   - active: boolean, signals if the user is on this navigation entry
789
-	 */
790
-	public static function getNavigation() {
791
-		$entries = OC::$server->getNavigationManager()->getAll();
792
-		$navigation = self::proceedNavigation($entries);
793
-		return $navigation;
794
-	}
795
-
796
-	/**
797
-	 * Returns the navigation inside the header bar
798
-	 *
799
-	 * @return array
800
-	 *
801
-	 * This function returns an array containing all entries added. The
802
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
803
-	 * given for each app the following keys exist:
804
-	 *   - active: boolean, signals if the user is on this navigation entry
805
-	 */
806
-	public static function getHeaderNavigation() {
807
-		$entries = OC::$server->getNavigationManager()->getAll();
808
-		$navigation = self::proceedAppNavigation($entries);
809
-		return $navigation;
810
-	}
811
-
812
-	/**
813
-	 * get the id of loaded app
814
-	 *
815
-	 * @return string
816
-	 */
817
-	public static function getCurrentApp() {
818
-		$request = \OC::$server->getRequest();
819
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
820
-		$topFolder = substr($script, 0, strpos($script, '/'));
821
-		if (empty($topFolder)) {
822
-			$path_info = $request->getPathInfo();
823
-			if ($path_info) {
824
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
825
-			}
826
-		}
827
-		if ($topFolder == 'apps') {
828
-			$length = strlen($topFolder);
829
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
830
-		} else {
831
-			return $topFolder;
832
-		}
833
-	}
834
-
835
-	/**
836
-	 * @param string $type
837
-	 * @return array
838
-	 */
839
-	public static function getForms($type) {
840
-		$forms = array();
841
-		switch ($type) {
842
-			case 'admin':
843
-				$source = self::$adminForms;
844
-				break;
845
-			case 'personal':
846
-				$source = self::$personalForms;
847
-				break;
848
-			default:
849
-				return array();
850
-		}
851
-		foreach ($source as $form) {
852
-			$forms[] = include $form;
853
-		}
854
-		return $forms;
855
-	}
856
-
857
-	/**
858
-	 * register an admin form to be shown
859
-	 *
860
-	 * @param string $app
861
-	 * @param string $page
862
-	 */
863
-	public static function registerAdmin($app, $page) {
864
-		self::$adminForms[] = $app . '/' . $page . '.php';
865
-	}
866
-
867
-	/**
868
-	 * register a personal form to be shown
869
-	 * @param string $app
870
-	 * @param string $page
871
-	 */
872
-	public static function registerPersonal($app, $page) {
873
-		self::$personalForms[] = $app . '/' . $page . '.php';
874
-	}
875
-
876
-	/**
877
-	 * @param array $entry
878
-	 */
879
-	public static function registerLogIn(array $entry) {
880
-		self::$altLogin[] = $entry;
881
-	}
882
-
883
-	/**
884
-	 * @return array
885
-	 */
886
-	public static function getAlternativeLogIns() {
887
-		return self::$altLogin;
888
-	}
889
-
890
-	/**
891
-	 * get a list of all apps in the apps folder
892
-	 *
893
-	 * @return array an array of app names (string IDs)
894
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
895
-	 */
896
-	public static function getAllApps() {
897
-
898
-		$apps = array();
899
-
900
-		foreach (OC::$APPSROOTS as $apps_dir) {
901
-			if (!is_readable($apps_dir['path'])) {
902
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
903
-				continue;
904
-			}
905
-			$dh = opendir($apps_dir['path']);
906
-
907
-			if (is_resource($dh)) {
908
-				while (($file = readdir($dh)) !== false) {
909
-
910
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
911
-
912
-						$apps[] = $file;
913
-					}
914
-				}
915
-			}
916
-		}
917
-
918
-		return $apps;
919
-	}
920
-
921
-	/**
922
-	 * List all apps, this is used in apps.php
923
-	 *
924
-	 * @return array
925
-	 */
926
-	public function listAllApps() {
927
-		$installedApps = OC_App::getAllApps();
928
-
929
-		//we don't want to show configuration for these
930
-		$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
931
-		$appList = array();
932
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
933
-		$urlGenerator = \OC::$server->getURLGenerator();
934
-
935
-		foreach ($installedApps as $app) {
936
-			if (array_search($app, $blacklist) === false) {
937
-
938
-				$info = OC_App::getAppInfo($app, false, $langCode);
939
-				if (!is_array($info)) {
940
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
941
-					continue;
942
-				}
943
-
944
-				if (!isset($info['name'])) {
945
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
946
-					continue;
947
-				}
948
-
949
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
950
-				$info['groups'] = null;
951
-				if ($enabled === 'yes') {
952
-					$active = true;
953
-				} else if ($enabled === 'no') {
954
-					$active = false;
955
-				} else {
956
-					$active = true;
957
-					$info['groups'] = $enabled;
958
-				}
959
-
960
-				$info['active'] = $active;
961
-
962
-				if (self::isShipped($app)) {
963
-					$info['internal'] = true;
964
-					$info['level'] = self::officialApp;
965
-					$info['removable'] = false;
966
-				} else {
967
-					$info['internal'] = false;
968
-					$info['removable'] = true;
969
-				}
970
-
971
-				$appPath = self::getAppPath($app);
972
-				if($appPath !== false) {
973
-					$appIcon = $appPath . '/img/' . $app . '.svg';
974
-					if (file_exists($appIcon)) {
975
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
976
-						$info['previewAsIcon'] = true;
977
-					} else {
978
-						$appIcon = $appPath . '/img/app.svg';
979
-						if (file_exists($appIcon)) {
980
-							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981
-							$info['previewAsIcon'] = true;
982
-						}
983
-					}
984
-				}
985
-				// fix documentation
986
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
987
-					foreach ($info['documentation'] as $key => $url) {
988
-						// If it is not an absolute URL we assume it is a key
989
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
990
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
991
-							$url = $urlGenerator->linkToDocs($url);
992
-						}
993
-
994
-						$info['documentation'][$key] = $url;
995
-					}
996
-				}
997
-
998
-				$info['version'] = OC_App::getAppVersion($app);
999
-				$appList[] = $info;
1000
-			}
1001
-		}
1002
-
1003
-		return $appList;
1004
-	}
1005
-
1006
-	/**
1007
-	 * Returns the internal app ID or false
1008
-	 * @param string $ocsID
1009
-	 * @return string|false
1010
-	 */
1011
-	public static function getInternalAppIdByOcs($ocsID) {
1012
-		if(is_numeric($ocsID)) {
1013
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
-			if(array_search($ocsID, $idArray)) {
1015
-				return array_search($ocsID, $idArray);
1016
-			}
1017
-		}
1018
-		return false;
1019
-	}
1020
-
1021
-	public static function shouldUpgrade($app) {
1022
-		$versions = self::getAppVersions();
1023
-		$currentVersion = OC_App::getAppVersion($app);
1024
-		if ($currentVersion && isset($versions[$app])) {
1025
-			$installedVersion = $versions[$app];
1026
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
1027
-				return true;
1028
-			}
1029
-		}
1030
-		return false;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Adjust the number of version parts of $version1 to match
1035
-	 * the number of version parts of $version2.
1036
-	 *
1037
-	 * @param string $version1 version to adjust
1038
-	 * @param string $version2 version to take the number of parts from
1039
-	 * @return string shortened $version1
1040
-	 */
1041
-	private static function adjustVersionParts($version1, $version2) {
1042
-		$version1 = explode('.', $version1);
1043
-		$version2 = explode('.', $version2);
1044
-		// reduce $version1 to match the number of parts in $version2
1045
-		while (count($version1) > count($version2)) {
1046
-			array_pop($version1);
1047
-		}
1048
-		// if $version1 does not have enough parts, add some
1049
-		while (count($version1) < count($version2)) {
1050
-			$version1[] = '0';
1051
-		}
1052
-		return implode('.', $version1);
1053
-	}
1054
-
1055
-	/**
1056
-	 * Check whether the current ownCloud version matches the given
1057
-	 * application's version requirements.
1058
-	 *
1059
-	 * The comparison is made based on the number of parts that the
1060
-	 * app info version has. For example for ownCloud 6.0.3 if the
1061
-	 * app info version is expecting version 6.0, the comparison is
1062
-	 * made on the first two parts of the ownCloud version.
1063
-	 * This means that it's possible to specify "requiremin" => 6
1064
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1065
-	 *
1066
-	 * @param string $ocVersion ownCloud version to check against
1067
-	 * @param array $appInfo app info (from xml)
1068
-	 *
1069
-	 * @return boolean true if compatible, otherwise false
1070
-	 */
1071
-	public static function isAppCompatible($ocVersion, $appInfo) {
1072
-		$requireMin = '';
1073
-		$requireMax = '';
1074
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1075
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1076
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1077
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1078
-		} else if (isset($appInfo['requiremin'])) {
1079
-			$requireMin = $appInfo['requiremin'];
1080
-		} else if (isset($appInfo['require'])) {
1081
-			$requireMin = $appInfo['require'];
1082
-		}
1083
-
1084
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1085
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1086
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1087
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1088
-		} else if (isset($appInfo['requiremax'])) {
1089
-			$requireMax = $appInfo['requiremax'];
1090
-		}
1091
-
1092
-		if (is_array($ocVersion)) {
1093
-			$ocVersion = implode('.', $ocVersion);
1094
-		}
1095
-
1096
-		if (!empty($requireMin)
1097
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1098
-		) {
1099
-
1100
-			return false;
1101
-		}
1102
-
1103
-		if (!empty($requireMax)
1104
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1105
-		) {
1106
-			return false;
1107
-		}
1108
-
1109
-		return true;
1110
-	}
1111
-
1112
-	/**
1113
-	 * get the installed version of all apps
1114
-	 */
1115
-	public static function getAppVersions() {
1116
-		static $versions;
1117
-
1118
-		if(!$versions) {
1119
-			$appConfig = \OC::$server->getAppConfig();
1120
-			$versions = $appConfig->getValues(false, 'installed_version');
1121
-		}
1122
-		return $versions;
1123
-	}
1124
-
1125
-	/**
1126
-	 * @param string $app
1127
-	 * @param \OCP\IConfig $config
1128
-	 * @param \OCP\IL10N $l
1129
-	 * @return bool
1130
-	 *
1131
-	 * @throws Exception if app is not compatible with this version of ownCloud
1132
-	 * @throws Exception if no app-name was specified
1133
-	 */
1134
-	public function installApp($app,
1135
-							   \OCP\IConfig $config,
1136
-							   \OCP\IL10N $l) {
1137
-		if ($app !== false) {
1138
-			// check if the app is compatible with this version of ownCloud
1139
-			$info = self::getAppInfo($app);
1140
-			if(!is_array($info)) {
1141
-				throw new \Exception(
1142
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143
-						[$info['name']]
1144
-					)
1145
-				);
1146
-			}
1147
-
1148
-			$version = \OCP\Util::getVersion();
1149
-			if (!self::isAppCompatible($version, $info)) {
1150
-				throw new \Exception(
1151
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1152
-						array($info['name'])
1153
-					)
1154
-				);
1155
-			}
1156
-
1157
-			// check for required dependencies
1158
-			self::checkAppDependencies($config, $l, $info);
1159
-
1160
-			$config->setAppValue($app, 'enabled', 'yes');
1161
-			if (isset($appData['id'])) {
1162
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1163
-			}
1164
-
1165
-			if(isset($info['settings']) && is_array($info['settings'])) {
1166
-				$appPath = self::getAppPath($app);
1167
-				self::registerAutoloading($app, $appPath);
1168
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1169
-			}
1170
-
1171
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172
-		} else {
1173
-			if(empty($appName) ) {
1174
-				throw new \Exception($l->t("No app name specified"));
1175
-			} else {
1176
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1177
-			}
1178
-		}
1179
-
1180
-		return $app;
1181
-	}
1182
-
1183
-	/**
1184
-	 * update the database for the app and call the update script
1185
-	 *
1186
-	 * @param string $appId
1187
-	 * @return bool
1188
-	 */
1189
-	public static function updateApp($appId) {
1190
-		$appPath = self::getAppPath($appId);
1191
-		if($appPath === false) {
1192
-			return false;
1193
-		}
1194
-		$appData = self::getAppInfo($appId);
1195
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1197
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1198
-		}
1199
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201
-		unset(self::$appVersion[$appId]);
1202
-		// run upgrade code
1203
-		if (file_exists($appPath . '/appinfo/update.php')) {
1204
-			self::loadApp($appId);
1205
-			include $appPath . '/appinfo/update.php';
1206
-		}
1207
-		self::setupBackgroundJobs($appData['background-jobs']);
1208
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1209
-			$appPath = self::getAppPath($appId);
1210
-			self::registerAutoloading($appId, $appPath);
1211
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1212
-		}
1213
-
1214
-		//set remote/public handlers
1215
-		if (array_key_exists('ocsid', $appData)) {
1216
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219
-		}
1220
-		foreach ($appData['remote'] as $name => $path) {
1221
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1222
-		}
1223
-		foreach ($appData['public'] as $name => $path) {
1224
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1225
-		}
1226
-
1227
-		self::setAppTypes($appId);
1228
-
1229
-		$version = \OC_App::getAppVersion($appId);
1230
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1231
-
1232
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1233
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1234
-		));
1235
-
1236
-		return true;
1237
-	}
1238
-
1239
-	/**
1240
-	 * @param string $appId
1241
-	 * @param string[] $steps
1242
-	 * @throws \OC\NeedsUpdateException
1243
-	 */
1244
-	public static function executeRepairSteps($appId, array $steps) {
1245
-		if (empty($steps)) {
1246
-			return;
1247
-		}
1248
-		// load the app
1249
-		self::loadApp($appId);
1250
-
1251
-		$dispatcher = OC::$server->getEventDispatcher();
1252
-
1253
-		// load the steps
1254
-		$r = new Repair([], $dispatcher);
1255
-		foreach ($steps as $step) {
1256
-			try {
1257
-				$r->addStep($step);
1258
-			} catch (Exception $ex) {
1259
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1260
-				\OC::$server->getLogger()->logException($ex);
1261
-			}
1262
-		}
1263
-		// run the steps
1264
-		$r->run();
1265
-	}
1266
-
1267
-	public static function setupBackgroundJobs(array $jobs) {
1268
-		$queue = \OC::$server->getJobList();
1269
-		foreach ($jobs as $job) {
1270
-			$queue->add($job);
1271
-		}
1272
-	}
1273
-
1274
-	/**
1275
-	 * @param string $appId
1276
-	 * @param string[] $steps
1277
-	 */
1278
-	private static function setupLiveMigrations($appId, array $steps) {
1279
-		$queue = \OC::$server->getJobList();
1280
-		foreach ($steps as $step) {
1281
-			$queue->add('OC\Migration\BackgroundRepair', [
1282
-				'app' => $appId,
1283
-				'step' => $step]);
1284
-		}
1285
-	}
1286
-
1287
-	/**
1288
-	 * @param string $appId
1289
-	 * @return \OC\Files\View|false
1290
-	 */
1291
-	public static function getStorage($appId) {
1292
-		if (OC_App::isEnabled($appId)) { //sanity check
1293
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1295
-				if (!$view->file_exists($appId)) {
1296
-					$view->mkdir($appId);
1297
-				}
1298
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1299
-			} else {
1300
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1301
-				return false;
1302
-			}
1303
-		} else {
1304
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1305
-			return false;
1306
-		}
1307
-	}
1308
-
1309
-	protected static function findBestL10NOption($options, $lang) {
1310
-		$fallback = $similarLangFallback = $englishFallback = false;
1311
-
1312
-		$lang = strtolower($lang);
1313
-		$similarLang = $lang;
1314
-		if (strpos($similarLang, '_')) {
1315
-			// For "de_DE" we want to find "de" and the other way around
1316
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1317
-		}
1318
-
1319
-		foreach ($options as $option) {
1320
-			if (is_array($option)) {
1321
-				if ($fallback === false) {
1322
-					$fallback = $option['@value'];
1323
-				}
1324
-
1325
-				if (!isset($option['@attributes']['lang'])) {
1326
-					continue;
1327
-				}
1328
-
1329
-				$attributeLang = strtolower($option['@attributes']['lang']);
1330
-				if ($attributeLang === $lang) {
1331
-					return $option['@value'];
1332
-				}
1333
-
1334
-				if ($attributeLang === $similarLang) {
1335
-					$similarLangFallback = $option['@value'];
1336
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1337
-					if ($similarLangFallback === false) {
1338
-						$similarLangFallback =  $option['@value'];
1339
-					}
1340
-				}
1341
-			} else {
1342
-				$englishFallback = $option;
1343
-			}
1344
-		}
1345
-
1346
-		if ($similarLangFallback !== false) {
1347
-			return $similarLangFallback;
1348
-		} else if ($englishFallback !== false) {
1349
-			return $englishFallback;
1350
-		}
1351
-		return (string) $fallback;
1352
-	}
1353
-
1354
-	/**
1355
-	 * parses the app data array and enhanced the 'description' value
1356
-	 *
1357
-	 * @param array $data the app data
1358
-	 * @param string $lang
1359
-	 * @return array improved app data
1360
-	 */
1361
-	public static function parseAppInfo(array $data, $lang = null) {
1362
-
1363
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1364
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1365
-		}
1366
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1367
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1368
-		}
1369
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1370
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371
-		} else if (isset($data['description']) && is_string($data['description'])) {
1372
-			$data['description'] = trim($data['description']);
1373
-		} else  {
1374
-			$data['description'] = '';
1375
-		}
1376
-
1377
-		return $data;
1378
-	}
1379
-
1380
-	/**
1381
-	 * @param \OCP\IConfig $config
1382
-	 * @param \OCP\IL10N $l
1383
-	 * @param array $info
1384
-	 * @throws \Exception
1385
-	 */
1386
-	protected static function checkAppDependencies($config, $l, $info) {
1387
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1388
-		$missing = $dependencyAnalyzer->analyze($info);
1389
-		if (!empty($missing)) {
1390
-			$missingMsg = join(PHP_EOL, $missing);
1391
-			throw new \Exception(
1392
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1393
-					[$info['name'], $missingMsg]
1394
-				)
1395
-			);
1396
-		}
1397
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+    }
178
+
179
+    /**
180
+     * @internal
181
+     * @param string $app
182
+     * @param string $path
183
+     */
184
+    public static function registerAutoloading($app, $path) {
185
+        $key = $app . '-' . $path;
186
+        if(isset(self::$alreadyRegistered[$key])) {
187
+            return;
188
+        }
189
+        self::$alreadyRegistered[$key] = true;
190
+        // Register on PSR-4 composer autoloader
191
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
+        \OC::$server->registerNamespace($app, $appNamespace);
193
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
+        }
197
+
198
+        // Register on legacy autoloader
199
+        \OC::$loader->addValidRoot($path);
200
+    }
201
+
202
+    /**
203
+     * Load app.php from the given app
204
+     *
205
+     * @param string $app app name
206
+     */
207
+    private static function requireAppFile($app) {
208
+        try {
209
+            // encapsulated here to avoid variable scope conflicts
210
+            require_once $app . '/appinfo/app.php';
211
+        } catch (Error $ex) {
212
+            \OC::$server->getLogger()->logException($ex);
213
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
+            if (!in_array($app, $blacklist)) {
215
+                self::disable($app);
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * check if an app is of a specific type
222
+     *
223
+     * @param string $app
224
+     * @param string|array $types
225
+     * @return bool
226
+     */
227
+    public static function isType($app, $types) {
228
+        if (is_string($types)) {
229
+            $types = array($types);
230
+        }
231
+        $appTypes = self::getAppTypes($app);
232
+        foreach ($types as $type) {
233
+            if (array_search($type, $appTypes) !== false) {
234
+                return true;
235
+            }
236
+        }
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * get the types of an app
242
+     *
243
+     * @param string $app
244
+     * @return array
245
+     */
246
+    private static function getAppTypes($app) {
247
+        //load the cache
248
+        if (count(self::$appTypes) == 0) {
249
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
+        }
251
+
252
+        if (isset(self::$appTypes[$app])) {
253
+            return explode(',', self::$appTypes[$app]);
254
+        } else {
255
+            return array();
256
+        }
257
+    }
258
+
259
+    /**
260
+     * read app types from info.xml and cache them in the database
261
+     */
262
+    public static function setAppTypes($app) {
263
+        $appData = self::getAppInfo($app);
264
+        if(!is_array($appData)) {
265
+            return;
266
+        }
267
+
268
+        if (isset($appData['types'])) {
269
+            $appTypes = implode(',', $appData['types']);
270
+        } else {
271
+            $appTypes = '';
272
+            $appData['types'] = [];
273
+        }
274
+
275
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
+
277
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
+            if ($enabled !== 'yes' && $enabled !== 'no') {
280
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
+            }
282
+        }
283
+    }
284
+
285
+    /**
286
+     * check if app is shipped
287
+     *
288
+     * @param string $appId the id of the app to check
289
+     * @return bool
290
+     *
291
+     * Check if an app that is installed is a shipped app or installed from the appstore.
292
+     */
293
+    public static function isShipped($appId) {
294
+        return \OC::$server->getAppManager()->isShipped($appId);
295
+    }
296
+
297
+    /**
298
+     * get all enabled apps
299
+     */
300
+    protected static $enabledAppsCache = array();
301
+
302
+    /**
303
+     * Returns apps enabled for the current user.
304
+     *
305
+     * @param bool $forceRefresh whether to refresh the cache
306
+     * @param bool $all whether to return apps for all users, not only the
307
+     * currently logged in one
308
+     * @return string[]
309
+     */
310
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
311
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
+            return array();
313
+        }
314
+        // in incognito mode or when logged out, $user will be false,
315
+        // which is also the case during an upgrade
316
+        $appManager = \OC::$server->getAppManager();
317
+        if ($all) {
318
+            $user = null;
319
+        } else {
320
+            $user = \OC::$server->getUserSession()->getUser();
321
+        }
322
+
323
+        if (is_null($user)) {
324
+            $apps = $appManager->getInstalledApps();
325
+        } else {
326
+            $apps = $appManager->getEnabledAppsForUser($user);
327
+        }
328
+        $apps = array_filter($apps, function ($app) {
329
+            return $app !== 'files';//we add this manually
330
+        });
331
+        sort($apps);
332
+        array_unshift($apps, 'files');
333
+        return $apps;
334
+    }
335
+
336
+    /**
337
+     * checks whether or not an app is enabled
338
+     *
339
+     * @param string $app app
340
+     * @return bool
341
+     *
342
+     * This function checks whether or not an app is enabled.
343
+     */
344
+    public static function isEnabled($app) {
345
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
346
+    }
347
+
348
+    /**
349
+     * enables an app
350
+     *
351
+     * @param string $appId
352
+     * @param array $groups (optional) when set, only these groups will have access to the app
353
+     * @throws \Exception
354
+     * @return void
355
+     *
356
+     * This function set an app as enabled in appconfig.
357
+     */
358
+    public function enable($appId,
359
+                            $groups = null) {
360
+        self::$enabledAppsCache = []; // flush
361
+        $l = \OC::$server->getL10N('core');
362
+        $config = \OC::$server->getConfig();
363
+
364
+        // Check if app is already downloaded
365
+        $installer = new Installer(
366
+            \OC::$server->getAppFetcher(),
367
+            \OC::$server->getHTTPClientService(),
368
+            \OC::$server->getTempManager(),
369
+            \OC::$server->getLogger()
370
+        );
371
+        $isDownloaded = $installer->isDownloaded($appId);
372
+
373
+        if(!$isDownloaded) {
374
+            $installer->downloadApp($appId);
375
+        }
376
+
377
+        if (!Installer::isInstalled($appId)) {
378
+            $appId = self::installApp(
379
+                $appId,
380
+                $config,
381
+                $l
382
+            );
383
+            $appPath = self::getAppPath($appId);
384
+            self::registerAutoloading($appId, $appPath);
385
+            $installer->installApp($appId);
386
+        } else {
387
+            // check for required dependencies
388
+            $info = self::getAppInfo($appId);
389
+            self::checkAppDependencies($config, $l, $info);
390
+            $appPath = self::getAppPath($appId);
391
+            self::registerAutoloading($appId, $appPath);
392
+            $installer->installApp($appId);
393
+        }
394
+
395
+        $appManager = \OC::$server->getAppManager();
396
+        if (!is_null($groups)) {
397
+            $groupManager = \OC::$server->getGroupManager();
398
+            $groupsList = [];
399
+            foreach ($groups as $group) {
400
+                $groupItem = $groupManager->get($group);
401
+                if ($groupItem instanceof \OCP\IGroup) {
402
+                    $groupsList[] = $groupManager->get($group);
403
+                }
404
+            }
405
+            $appManager->enableAppForGroups($appId, $groupsList);
406
+        } else {
407
+            $appManager->enableApp($appId);
408
+        }
409
+
410
+        $info = self::getAppInfo($appId);
411
+        if(isset($info['settings']) && is_array($info['settings'])) {
412
+            $appPath = self::getAppPath($appId);
413
+            self::registerAutoloading($appId, $appPath);
414
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * @param string $app
420
+     * @return bool
421
+     */
422
+    public static function removeApp($app) {
423
+        if (self::isShipped($app)) {
424
+            return false;
425
+        }
426
+
427
+        $installer = new Installer(
428
+            \OC::$server->getAppFetcher(),
429
+            \OC::$server->getHTTPClientService(),
430
+            \OC::$server->getTempManager(),
431
+            \OC::$server->getLogger()
432
+        );
433
+        return $installer->removeApp($app);
434
+    }
435
+
436
+    /**
437
+     * This function set an app as disabled in appconfig.
438
+     *
439
+     * @param string $app app
440
+     * @throws Exception
441
+     */
442
+    public static function disable($app) {
443
+        // flush
444
+        self::$enabledAppsCache = array();
445
+
446
+        // run uninstall steps
447
+        $appData = OC_App::getAppInfo($app);
448
+        if (!is_null($appData)) {
449
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
+        }
451
+
452
+        // emit disable hook - needed anymore ?
453
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
+
455
+        // finally disable it
456
+        $appManager = \OC::$server->getAppManager();
457
+        $appManager->disableApp($app);
458
+    }
459
+
460
+    /**
461
+     * Returns the Settings Navigation
462
+     *
463
+     * @return string[]
464
+     *
465
+     * This function returns an array containing all settings pages added. The
466
+     * entries are sorted by the key 'order' ascending.
467
+     */
468
+    public static function getSettingsNavigation() {
469
+        $l = \OC::$server->getL10N('lib');
470
+        $urlGenerator = \OC::$server->getURLGenerator();
471
+
472
+        $settings = array();
473
+        // by default, settings only contain the help menu
474
+        if (\OC::$server->getSystemConfig()->getValue('knowledgebaseenabled', true)) {
475
+            $settings = array(
476
+                array(
477
+                    "id" => "help",
478
+                    "order" => 4,
479
+                    "href" => $urlGenerator->linkToRoute('settings_help'),
480
+                    "name" => $l->t("Help"),
481
+                    "icon" => $urlGenerator->imagePath("settings", "help.svg")
482
+                )
483
+            );
484
+        }
485
+
486
+        // if the user is logged-in
487
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
488
+            // personal menu
489
+            $settings[] = array(
490
+                "id" => "personal",
491
+                "order" => 1,
492
+                "href" => $urlGenerator->linkToRoute('settings_personal'),
493
+                "name" => $l->t("Personal"),
494
+                "icon" => $urlGenerator->imagePath("settings", "personal.svg")
495
+            );
496
+
497
+            //SubAdmins are also allowed to access user management
498
+            $userObject = \OC::$server->getUserSession()->getUser();
499
+            $isSubAdmin = false;
500
+            if($userObject !== null) {
501
+                $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502
+            }
503
+            if ($isSubAdmin) {
504
+                // admin users menu
505
+                $settings[] = array(
506
+                    "id" => "core_users",
507
+                    "order" => 3,
508
+                    "href" => $urlGenerator->linkToRoute('settings_users'),
509
+                    "name" => $l->t("Users"),
510
+                    "icon" => $urlGenerator->imagePath("settings", "users.svg")
511
+                );
512
+            }
513
+
514
+            // if the user is an admin
515
+            if (OC_User::isAdminUser(OC_User::getUser())) {
516
+                // admin settings
517
+                $settings[] = array(
518
+                    "id" => "admin",
519
+                    "order" => 2,
520
+                    "href" => $urlGenerator->linkToRoute('settings.AdminSettings.index'),
521
+                    "name" => $l->t("Admin"),
522
+                    "icon" => $urlGenerator->imagePath("settings", "admin.svg")
523
+                );
524
+            }
525
+        }
526
+
527
+        $navigation = self::proceedNavigation($settings);
528
+        return $navigation;
529
+    }
530
+
531
+    // This is private as well. It simply works, so don't ask for more details
532
+    private static function proceedNavigation($list) {
533
+        $headerIconCount = 8;
534
+        if(OC_User::isAdminUser(OC_User::getUser())) {
535
+            $headerIconCount--;
536
+        }
537
+        usort($list, function($a, $b) {
538
+            if (isset($a['order']) && isset($b['order'])) {
539
+                return ($a['order'] < $b['order']) ? -1 : 1;
540
+            } else if (isset($a['order']) || isset($b['order'])) {
541
+                return isset($a['order']) ? -1 : 1;
542
+            } else {
543
+                return ($a['name'] < $b['name']) ? -1 : 1;
544
+            }
545
+        });
546
+
547
+        $activeAppIndex = -1;
548
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
549
+        foreach ($list as $index => &$navEntry) {
550
+            if ($navEntry['id'] == $activeApp) {
551
+                $navEntry['active'] = true;
552
+                $activeAppIndex = $index;
553
+            } else {
554
+                $navEntry['active'] = false;
555
+            }
556
+        }
557
+        unset($navEntry);
558
+
559
+        if($activeAppIndex > ($headerIconCount-1)) {
560
+            $active = $list[$activeAppIndex];
561
+            $lastInHeader = $list[$headerIconCount-1];
562
+            $list[$headerIconCount-1] = $active;
563
+            $list[$activeAppIndex] = $lastInHeader;
564
+        }
565
+
566
+        foreach ($list as $index => &$navEntry) {
567
+            $navEntry['showInHeader'] = false;
568
+            if($index < $headerIconCount) {
569
+                $navEntry['showInHeader'] = true;
570
+            }
571
+        }
572
+
573
+
574
+
575
+        return $list;
576
+    }
577
+
578
+    public static function proceedAppNavigation($entries) {
579
+        $headerIconCount = 8;
580
+        if(OC_User::isAdminUser(OC_User::getUser())) {
581
+            $headerIconCount--;
582
+        }
583
+        $activeAppIndex = -1;
584
+        $list = self::proceedNavigation($entries);
585
+
586
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
587
+        foreach ($list as $index => &$navEntry) {
588
+            if ($navEntry['id'] == $activeApp) {
589
+                $navEntry['active'] = true;
590
+                $activeAppIndex = $index;
591
+            } else {
592
+                $navEntry['active'] = false;
593
+            }
594
+        }
595
+        // move active item to last position
596
+        if($activeAppIndex > ($headerIconCount-1)) {
597
+            $active = $list[$activeAppIndex];
598
+            $lastInHeader = $list[$headerIconCount-1];
599
+            $list[$headerIconCount-1] = $active;
600
+            $list[$activeAppIndex] = $lastInHeader;
601
+        }
602
+        $list = array_slice($list, 0, $headerIconCount);
603
+
604
+        return $list;
605
+    }
606
+
607
+    /**
608
+     * Get the path where to install apps
609
+     *
610
+     * @return string|false
611
+     */
612
+    public static function getInstallPath() {
613
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
614
+            return false;
615
+        }
616
+
617
+        foreach (OC::$APPSROOTS as $dir) {
618
+            if (isset($dir['writable']) && $dir['writable'] === true) {
619
+                return $dir['path'];
620
+            }
621
+        }
622
+
623
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
624
+        return null;
625
+    }
626
+
627
+
628
+    /**
629
+     * search for an app in all app-directories
630
+     *
631
+     * @param string $appId
632
+     * @return false|string
633
+     */
634
+    public static function findAppInDirectories($appId) {
635
+        $sanitizedAppId = self::cleanAppId($appId);
636
+        if($sanitizedAppId !== $appId) {
637
+            return false;
638
+        }
639
+        static $app_dir = array();
640
+
641
+        if (isset($app_dir[$appId])) {
642
+            return $app_dir[$appId];
643
+        }
644
+
645
+        $possibleApps = array();
646
+        foreach (OC::$APPSROOTS as $dir) {
647
+            if (file_exists($dir['path'] . '/' . $appId)) {
648
+                $possibleApps[] = $dir;
649
+            }
650
+        }
651
+
652
+        if (empty($possibleApps)) {
653
+            return false;
654
+        } elseif (count($possibleApps) === 1) {
655
+            $dir = array_shift($possibleApps);
656
+            $app_dir[$appId] = $dir;
657
+            return $dir;
658
+        } else {
659
+            $versionToLoad = array();
660
+            foreach ($possibleApps as $possibleApp) {
661
+                $version = self::getAppVersionByPath($possibleApp['path']);
662
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
663
+                    $versionToLoad = array(
664
+                        'dir' => $possibleApp,
665
+                        'version' => $version,
666
+                    );
667
+                }
668
+            }
669
+            $app_dir[$appId] = $versionToLoad['dir'];
670
+            return $versionToLoad['dir'];
671
+            //TODO - write test
672
+        }
673
+    }
674
+
675
+    /**
676
+     * Get the directory for the given app.
677
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
678
+     *
679
+     * @param string $appId
680
+     * @return string|false
681
+     */
682
+    public static function getAppPath($appId) {
683
+        if ($appId === null || trim($appId) === '') {
684
+            return false;
685
+        }
686
+
687
+        if (($dir = self::findAppInDirectories($appId)) != false) {
688
+            return $dir['path'] . '/' . $appId;
689
+        }
690
+        return false;
691
+    }
692
+
693
+    /**
694
+     * Get the path for the given app on the access
695
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
696
+     *
697
+     * @param string $appId
698
+     * @return string|false
699
+     */
700
+    public static function getAppWebPath($appId) {
701
+        if (($dir = self::findAppInDirectories($appId)) != false) {
702
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
703
+        }
704
+        return false;
705
+    }
706
+
707
+    /**
708
+     * get the last version of the app from appinfo/info.xml
709
+     *
710
+     * @param string $appId
711
+     * @param bool $useCache
712
+     * @return string
713
+     */
714
+    public static function getAppVersion($appId, $useCache = true) {
715
+        if($useCache && isset(self::$appVersion[$appId])) {
716
+            return self::$appVersion[$appId];
717
+        }
718
+
719
+        $file = self::getAppPath($appId);
720
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
721
+        return self::$appVersion[$appId];
722
+    }
723
+
724
+    /**
725
+     * get app's version based on it's path
726
+     *
727
+     * @param string $path
728
+     * @return string
729
+     */
730
+    public static function getAppVersionByPath($path) {
731
+        $infoFile = $path . '/appinfo/info.xml';
732
+        $appData = self::getAppInfo($infoFile, true);
733
+        return isset($appData['version']) ? $appData['version'] : '';
734
+    }
735
+
736
+
737
+    /**
738
+     * Read all app metadata from the info.xml file
739
+     *
740
+     * @param string $appId id of the app or the path of the info.xml file
741
+     * @param bool $path
742
+     * @param string $lang
743
+     * @return array|null
744
+     * @note all data is read from info.xml, not just pre-defined fields
745
+     */
746
+    public static function getAppInfo($appId, $path = false, $lang = null) {
747
+        if ($path) {
748
+            $file = $appId;
749
+        } else {
750
+            if ($lang === null && isset(self::$appInfo[$appId])) {
751
+                return self::$appInfo[$appId];
752
+            }
753
+            $appPath = self::getAppPath($appId);
754
+            if($appPath === false) {
755
+                return null;
756
+            }
757
+            $file = $appPath . '/appinfo/info.xml';
758
+        }
759
+
760
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
761
+        $data = $parser->parse($file);
762
+
763
+        if (is_array($data)) {
764
+            $data = OC_App::parseAppInfo($data, $lang);
765
+        }
766
+        if(isset($data['ocsid'])) {
767
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
769
+                $data['ocsid'] = $storedId;
770
+            }
771
+        }
772
+
773
+        if ($lang === null) {
774
+            self::$appInfo[$appId] = $data;
775
+        }
776
+
777
+        return $data;
778
+    }
779
+
780
+    /**
781
+     * Returns the navigation
782
+     *
783
+     * @return array
784
+     *
785
+     * This function returns an array containing all entries added. The
786
+     * entries are sorted by the key 'order' ascending. Additional to the keys
787
+     * given for each app the following keys exist:
788
+     *   - active: boolean, signals if the user is on this navigation entry
789
+     */
790
+    public static function getNavigation() {
791
+        $entries = OC::$server->getNavigationManager()->getAll();
792
+        $navigation = self::proceedNavigation($entries);
793
+        return $navigation;
794
+    }
795
+
796
+    /**
797
+     * Returns the navigation inside the header bar
798
+     *
799
+     * @return array
800
+     *
801
+     * This function returns an array containing all entries added. The
802
+     * entries are sorted by the key 'order' ascending. Additional to the keys
803
+     * given for each app the following keys exist:
804
+     *   - active: boolean, signals if the user is on this navigation entry
805
+     */
806
+    public static function getHeaderNavigation() {
807
+        $entries = OC::$server->getNavigationManager()->getAll();
808
+        $navigation = self::proceedAppNavigation($entries);
809
+        return $navigation;
810
+    }
811
+
812
+    /**
813
+     * get the id of loaded app
814
+     *
815
+     * @return string
816
+     */
817
+    public static function getCurrentApp() {
818
+        $request = \OC::$server->getRequest();
819
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
820
+        $topFolder = substr($script, 0, strpos($script, '/'));
821
+        if (empty($topFolder)) {
822
+            $path_info = $request->getPathInfo();
823
+            if ($path_info) {
824
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
825
+            }
826
+        }
827
+        if ($topFolder == 'apps') {
828
+            $length = strlen($topFolder);
829
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
830
+        } else {
831
+            return $topFolder;
832
+        }
833
+    }
834
+
835
+    /**
836
+     * @param string $type
837
+     * @return array
838
+     */
839
+    public static function getForms($type) {
840
+        $forms = array();
841
+        switch ($type) {
842
+            case 'admin':
843
+                $source = self::$adminForms;
844
+                break;
845
+            case 'personal':
846
+                $source = self::$personalForms;
847
+                break;
848
+            default:
849
+                return array();
850
+        }
851
+        foreach ($source as $form) {
852
+            $forms[] = include $form;
853
+        }
854
+        return $forms;
855
+    }
856
+
857
+    /**
858
+     * register an admin form to be shown
859
+     *
860
+     * @param string $app
861
+     * @param string $page
862
+     */
863
+    public static function registerAdmin($app, $page) {
864
+        self::$adminForms[] = $app . '/' . $page . '.php';
865
+    }
866
+
867
+    /**
868
+     * register a personal form to be shown
869
+     * @param string $app
870
+     * @param string $page
871
+     */
872
+    public static function registerPersonal($app, $page) {
873
+        self::$personalForms[] = $app . '/' . $page . '.php';
874
+    }
875
+
876
+    /**
877
+     * @param array $entry
878
+     */
879
+    public static function registerLogIn(array $entry) {
880
+        self::$altLogin[] = $entry;
881
+    }
882
+
883
+    /**
884
+     * @return array
885
+     */
886
+    public static function getAlternativeLogIns() {
887
+        return self::$altLogin;
888
+    }
889
+
890
+    /**
891
+     * get a list of all apps in the apps folder
892
+     *
893
+     * @return array an array of app names (string IDs)
894
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
895
+     */
896
+    public static function getAllApps() {
897
+
898
+        $apps = array();
899
+
900
+        foreach (OC::$APPSROOTS as $apps_dir) {
901
+            if (!is_readable($apps_dir['path'])) {
902
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
903
+                continue;
904
+            }
905
+            $dh = opendir($apps_dir['path']);
906
+
907
+            if (is_resource($dh)) {
908
+                while (($file = readdir($dh)) !== false) {
909
+
910
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
911
+
912
+                        $apps[] = $file;
913
+                    }
914
+                }
915
+            }
916
+        }
917
+
918
+        return $apps;
919
+    }
920
+
921
+    /**
922
+     * List all apps, this is used in apps.php
923
+     *
924
+     * @return array
925
+     */
926
+    public function listAllApps() {
927
+        $installedApps = OC_App::getAllApps();
928
+
929
+        //we don't want to show configuration for these
930
+        $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
931
+        $appList = array();
932
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
933
+        $urlGenerator = \OC::$server->getURLGenerator();
934
+
935
+        foreach ($installedApps as $app) {
936
+            if (array_search($app, $blacklist) === false) {
937
+
938
+                $info = OC_App::getAppInfo($app, false, $langCode);
939
+                if (!is_array($info)) {
940
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
941
+                    continue;
942
+                }
943
+
944
+                if (!isset($info['name'])) {
945
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
946
+                    continue;
947
+                }
948
+
949
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
950
+                $info['groups'] = null;
951
+                if ($enabled === 'yes') {
952
+                    $active = true;
953
+                } else if ($enabled === 'no') {
954
+                    $active = false;
955
+                } else {
956
+                    $active = true;
957
+                    $info['groups'] = $enabled;
958
+                }
959
+
960
+                $info['active'] = $active;
961
+
962
+                if (self::isShipped($app)) {
963
+                    $info['internal'] = true;
964
+                    $info['level'] = self::officialApp;
965
+                    $info['removable'] = false;
966
+                } else {
967
+                    $info['internal'] = false;
968
+                    $info['removable'] = true;
969
+                }
970
+
971
+                $appPath = self::getAppPath($app);
972
+                if($appPath !== false) {
973
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
974
+                    if (file_exists($appIcon)) {
975
+                        $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
976
+                        $info['previewAsIcon'] = true;
977
+                    } else {
978
+                        $appIcon = $appPath . '/img/app.svg';
979
+                        if (file_exists($appIcon)) {
980
+                            $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981
+                            $info['previewAsIcon'] = true;
982
+                        }
983
+                    }
984
+                }
985
+                // fix documentation
986
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
987
+                    foreach ($info['documentation'] as $key => $url) {
988
+                        // If it is not an absolute URL we assume it is a key
989
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
990
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
991
+                            $url = $urlGenerator->linkToDocs($url);
992
+                        }
993
+
994
+                        $info['documentation'][$key] = $url;
995
+                    }
996
+                }
997
+
998
+                $info['version'] = OC_App::getAppVersion($app);
999
+                $appList[] = $info;
1000
+            }
1001
+        }
1002
+
1003
+        return $appList;
1004
+    }
1005
+
1006
+    /**
1007
+     * Returns the internal app ID or false
1008
+     * @param string $ocsID
1009
+     * @return string|false
1010
+     */
1011
+    public static function getInternalAppIdByOcs($ocsID) {
1012
+        if(is_numeric($ocsID)) {
1013
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
+            if(array_search($ocsID, $idArray)) {
1015
+                return array_search($ocsID, $idArray);
1016
+            }
1017
+        }
1018
+        return false;
1019
+    }
1020
+
1021
+    public static function shouldUpgrade($app) {
1022
+        $versions = self::getAppVersions();
1023
+        $currentVersion = OC_App::getAppVersion($app);
1024
+        if ($currentVersion && isset($versions[$app])) {
1025
+            $installedVersion = $versions[$app];
1026
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
1027
+                return true;
1028
+            }
1029
+        }
1030
+        return false;
1031
+    }
1032
+
1033
+    /**
1034
+     * Adjust the number of version parts of $version1 to match
1035
+     * the number of version parts of $version2.
1036
+     *
1037
+     * @param string $version1 version to adjust
1038
+     * @param string $version2 version to take the number of parts from
1039
+     * @return string shortened $version1
1040
+     */
1041
+    private static function adjustVersionParts($version1, $version2) {
1042
+        $version1 = explode('.', $version1);
1043
+        $version2 = explode('.', $version2);
1044
+        // reduce $version1 to match the number of parts in $version2
1045
+        while (count($version1) > count($version2)) {
1046
+            array_pop($version1);
1047
+        }
1048
+        // if $version1 does not have enough parts, add some
1049
+        while (count($version1) < count($version2)) {
1050
+            $version1[] = '0';
1051
+        }
1052
+        return implode('.', $version1);
1053
+    }
1054
+
1055
+    /**
1056
+     * Check whether the current ownCloud version matches the given
1057
+     * application's version requirements.
1058
+     *
1059
+     * The comparison is made based on the number of parts that the
1060
+     * app info version has. For example for ownCloud 6.0.3 if the
1061
+     * app info version is expecting version 6.0, the comparison is
1062
+     * made on the first two parts of the ownCloud version.
1063
+     * This means that it's possible to specify "requiremin" => 6
1064
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1065
+     *
1066
+     * @param string $ocVersion ownCloud version to check against
1067
+     * @param array $appInfo app info (from xml)
1068
+     *
1069
+     * @return boolean true if compatible, otherwise false
1070
+     */
1071
+    public static function isAppCompatible($ocVersion, $appInfo) {
1072
+        $requireMin = '';
1073
+        $requireMax = '';
1074
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1075
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1076
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1077
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1078
+        } else if (isset($appInfo['requiremin'])) {
1079
+            $requireMin = $appInfo['requiremin'];
1080
+        } else if (isset($appInfo['require'])) {
1081
+            $requireMin = $appInfo['require'];
1082
+        }
1083
+
1084
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1085
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1086
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1087
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1088
+        } else if (isset($appInfo['requiremax'])) {
1089
+            $requireMax = $appInfo['requiremax'];
1090
+        }
1091
+
1092
+        if (is_array($ocVersion)) {
1093
+            $ocVersion = implode('.', $ocVersion);
1094
+        }
1095
+
1096
+        if (!empty($requireMin)
1097
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1098
+        ) {
1099
+
1100
+            return false;
1101
+        }
1102
+
1103
+        if (!empty($requireMax)
1104
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1105
+        ) {
1106
+            return false;
1107
+        }
1108
+
1109
+        return true;
1110
+    }
1111
+
1112
+    /**
1113
+     * get the installed version of all apps
1114
+     */
1115
+    public static function getAppVersions() {
1116
+        static $versions;
1117
+
1118
+        if(!$versions) {
1119
+            $appConfig = \OC::$server->getAppConfig();
1120
+            $versions = $appConfig->getValues(false, 'installed_version');
1121
+        }
1122
+        return $versions;
1123
+    }
1124
+
1125
+    /**
1126
+     * @param string $app
1127
+     * @param \OCP\IConfig $config
1128
+     * @param \OCP\IL10N $l
1129
+     * @return bool
1130
+     *
1131
+     * @throws Exception if app is not compatible with this version of ownCloud
1132
+     * @throws Exception if no app-name was specified
1133
+     */
1134
+    public function installApp($app,
1135
+                                \OCP\IConfig $config,
1136
+                                \OCP\IL10N $l) {
1137
+        if ($app !== false) {
1138
+            // check if the app is compatible with this version of ownCloud
1139
+            $info = self::getAppInfo($app);
1140
+            if(!is_array($info)) {
1141
+                throw new \Exception(
1142
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143
+                        [$info['name']]
1144
+                    )
1145
+                );
1146
+            }
1147
+
1148
+            $version = \OCP\Util::getVersion();
1149
+            if (!self::isAppCompatible($version, $info)) {
1150
+                throw new \Exception(
1151
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1152
+                        array($info['name'])
1153
+                    )
1154
+                );
1155
+            }
1156
+
1157
+            // check for required dependencies
1158
+            self::checkAppDependencies($config, $l, $info);
1159
+
1160
+            $config->setAppValue($app, 'enabled', 'yes');
1161
+            if (isset($appData['id'])) {
1162
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1163
+            }
1164
+
1165
+            if(isset($info['settings']) && is_array($info['settings'])) {
1166
+                $appPath = self::getAppPath($app);
1167
+                self::registerAutoloading($app, $appPath);
1168
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1169
+            }
1170
+
1171
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172
+        } else {
1173
+            if(empty($appName) ) {
1174
+                throw new \Exception($l->t("No app name specified"));
1175
+            } else {
1176
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1177
+            }
1178
+        }
1179
+
1180
+        return $app;
1181
+    }
1182
+
1183
+    /**
1184
+     * update the database for the app and call the update script
1185
+     *
1186
+     * @param string $appId
1187
+     * @return bool
1188
+     */
1189
+    public static function updateApp($appId) {
1190
+        $appPath = self::getAppPath($appId);
1191
+        if($appPath === false) {
1192
+            return false;
1193
+        }
1194
+        $appData = self::getAppInfo($appId);
1195
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1197
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1198
+        }
1199
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201
+        unset(self::$appVersion[$appId]);
1202
+        // run upgrade code
1203
+        if (file_exists($appPath . '/appinfo/update.php')) {
1204
+            self::loadApp($appId);
1205
+            include $appPath . '/appinfo/update.php';
1206
+        }
1207
+        self::setupBackgroundJobs($appData['background-jobs']);
1208
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1209
+            $appPath = self::getAppPath($appId);
1210
+            self::registerAutoloading($appId, $appPath);
1211
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1212
+        }
1213
+
1214
+        //set remote/public handlers
1215
+        if (array_key_exists('ocsid', $appData)) {
1216
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219
+        }
1220
+        foreach ($appData['remote'] as $name => $path) {
1221
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1222
+        }
1223
+        foreach ($appData['public'] as $name => $path) {
1224
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1225
+        }
1226
+
1227
+        self::setAppTypes($appId);
1228
+
1229
+        $version = \OC_App::getAppVersion($appId);
1230
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1231
+
1232
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1233
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1234
+        ));
1235
+
1236
+        return true;
1237
+    }
1238
+
1239
+    /**
1240
+     * @param string $appId
1241
+     * @param string[] $steps
1242
+     * @throws \OC\NeedsUpdateException
1243
+     */
1244
+    public static function executeRepairSteps($appId, array $steps) {
1245
+        if (empty($steps)) {
1246
+            return;
1247
+        }
1248
+        // load the app
1249
+        self::loadApp($appId);
1250
+
1251
+        $dispatcher = OC::$server->getEventDispatcher();
1252
+
1253
+        // load the steps
1254
+        $r = new Repair([], $dispatcher);
1255
+        foreach ($steps as $step) {
1256
+            try {
1257
+                $r->addStep($step);
1258
+            } catch (Exception $ex) {
1259
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1260
+                \OC::$server->getLogger()->logException($ex);
1261
+            }
1262
+        }
1263
+        // run the steps
1264
+        $r->run();
1265
+    }
1266
+
1267
+    public static function setupBackgroundJobs(array $jobs) {
1268
+        $queue = \OC::$server->getJobList();
1269
+        foreach ($jobs as $job) {
1270
+            $queue->add($job);
1271
+        }
1272
+    }
1273
+
1274
+    /**
1275
+     * @param string $appId
1276
+     * @param string[] $steps
1277
+     */
1278
+    private static function setupLiveMigrations($appId, array $steps) {
1279
+        $queue = \OC::$server->getJobList();
1280
+        foreach ($steps as $step) {
1281
+            $queue->add('OC\Migration\BackgroundRepair', [
1282
+                'app' => $appId,
1283
+                'step' => $step]);
1284
+        }
1285
+    }
1286
+
1287
+    /**
1288
+     * @param string $appId
1289
+     * @return \OC\Files\View|false
1290
+     */
1291
+    public static function getStorage($appId) {
1292
+        if (OC_App::isEnabled($appId)) { //sanity check
1293
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1295
+                if (!$view->file_exists($appId)) {
1296
+                    $view->mkdir($appId);
1297
+                }
1298
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1299
+            } else {
1300
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1301
+                return false;
1302
+            }
1303
+        } else {
1304
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1305
+            return false;
1306
+        }
1307
+    }
1308
+
1309
+    protected static function findBestL10NOption($options, $lang) {
1310
+        $fallback = $similarLangFallback = $englishFallback = false;
1311
+
1312
+        $lang = strtolower($lang);
1313
+        $similarLang = $lang;
1314
+        if (strpos($similarLang, '_')) {
1315
+            // For "de_DE" we want to find "de" and the other way around
1316
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1317
+        }
1318
+
1319
+        foreach ($options as $option) {
1320
+            if (is_array($option)) {
1321
+                if ($fallback === false) {
1322
+                    $fallback = $option['@value'];
1323
+                }
1324
+
1325
+                if (!isset($option['@attributes']['lang'])) {
1326
+                    continue;
1327
+                }
1328
+
1329
+                $attributeLang = strtolower($option['@attributes']['lang']);
1330
+                if ($attributeLang === $lang) {
1331
+                    return $option['@value'];
1332
+                }
1333
+
1334
+                if ($attributeLang === $similarLang) {
1335
+                    $similarLangFallback = $option['@value'];
1336
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1337
+                    if ($similarLangFallback === false) {
1338
+                        $similarLangFallback =  $option['@value'];
1339
+                    }
1340
+                }
1341
+            } else {
1342
+                $englishFallback = $option;
1343
+            }
1344
+        }
1345
+
1346
+        if ($similarLangFallback !== false) {
1347
+            return $similarLangFallback;
1348
+        } else if ($englishFallback !== false) {
1349
+            return $englishFallback;
1350
+        }
1351
+        return (string) $fallback;
1352
+    }
1353
+
1354
+    /**
1355
+     * parses the app data array and enhanced the 'description' value
1356
+     *
1357
+     * @param array $data the app data
1358
+     * @param string $lang
1359
+     * @return array improved app data
1360
+     */
1361
+    public static function parseAppInfo(array $data, $lang = null) {
1362
+
1363
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1364
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1365
+        }
1366
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1367
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1368
+        }
1369
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1370
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371
+        } else if (isset($data['description']) && is_string($data['description'])) {
1372
+            $data['description'] = trim($data['description']);
1373
+        } else  {
1374
+            $data['description'] = '';
1375
+        }
1376
+
1377
+        return $data;
1378
+    }
1379
+
1380
+    /**
1381
+     * @param \OCP\IConfig $config
1382
+     * @param \OCP\IL10N $l
1383
+     * @param array $info
1384
+     * @throws \Exception
1385
+     */
1386
+    protected static function checkAppDependencies($config, $l, $info) {
1387
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1388
+        $missing = $dependencyAnalyzer->analyze($info);
1389
+        if (!empty($missing)) {
1390
+            $missingMsg = join(PHP_EOL, $missing);
1391
+            throw new \Exception(
1392
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1393
+                    [$info['name'], $missingMsg]
1394
+                )
1395
+            );
1396
+        }
1397
+    }
1398 1398
 }
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 		$apps = self::getEnabledApps();
112 112
 
113 113
 		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
114
+		foreach ($apps as $app) {
115 115
 			$path = self::getAppPath($app);
116
-			if($path !== false) {
116
+			if ($path !== false) {
117 117
 				self::registerAutoloading($app, $path);
118 118
 			}
119 119
 		}
@@ -138,15 +138,15 @@  discard block
 block discarded – undo
138 138
 	public static function loadApp($app) {
139 139
 		self::$loadedApps[] = $app;
140 140
 		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
141
+		if ($appPath === false) {
142 142
 			return;
143 143
 		}
144 144
 
145 145
 		// in case someone calls loadApp() directly
146 146
 		self::registerAutoloading($app, $appPath);
147 147
 
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
148
+		if (is_file($appPath.'/appinfo/app.php')) {
149
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
150 150
 			self::requireAppFile($app);
151 151
 			if (self::isType($app, array('authentication'))) {
152 152
 				// since authentication apps affect the "is app enabled for group" check,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 				// enabled for groups
156 156
 				self::$enabledAppsCache = array();
157 157
 			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
159 159
 		}
160 160
 
161 161
 		$info = self::getAppInfo($app);
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 	 * @param string $path
183 183
 	 */
184 184
 	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
185
+		$key = $app.'-'.$path;
186
+		if (isset(self::$alreadyRegistered[$key])) {
187 187
 			return;
188 188
 		}
189 189
 		self::$alreadyRegistered[$key] = true;
190 190
 		// Register on PSR-4 composer autoloader
191 191
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192 192
 		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
+		\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
194 194
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
196 196
 		}
197 197
 
198 198
 		// Register on legacy autoloader
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	private static function requireAppFile($app) {
208 208
 		try {
209 209
 			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
210
+			require_once $app.'/appinfo/app.php';
211 211
 		} catch (Error $ex) {
212 212
 			\OC::$server->getLogger()->logException($ex);
213 213
 			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public static function setAppTypes($app) {
263 263
 		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
264
+		if (!is_array($appData)) {
265 265
 			return;
266 266
 		}
267 267
 
@@ -325,8 +325,8 @@  discard block
 block discarded – undo
325 325
 		} else {
326 326
 			$apps = $appManager->getEnabledAppsForUser($user);
327 327
 		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
328
+		$apps = array_filter($apps, function($app) {
329
+			return $app !== 'files'; //we add this manually
330 330
 		});
331 331
 		sort($apps);
332 332
 		array_unshift($apps, 'files');
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 		);
371 371
 		$isDownloaded = $installer->isDownloaded($appId);
372 372
 
373
-		if(!$isDownloaded) {
373
+		if (!$isDownloaded) {
374 374
 			$installer->downloadApp($appId);
375 375
 		}
376 376
 
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 		}
409 409
 
410 410
 		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
411
+		if (isset($info['settings']) && is_array($info['settings'])) {
412 412
 			$appPath = self::getAppPath($appId);
413 413
 			self::registerAutoloading($appId, $appPath);
414 414
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 			//SubAdmins are also allowed to access user management
498 498
 			$userObject = \OC::$server->getUserSession()->getUser();
499 499
 			$isSubAdmin = false;
500
-			if($userObject !== null) {
500
+			if ($userObject !== null) {
501 501
 				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502 502
 			}
503 503
 			if ($isSubAdmin) {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	// This is private as well. It simply works, so don't ask for more details
532 532
 	private static function proceedNavigation($list) {
533 533
 		$headerIconCount = 8;
534
-		if(OC_User::isAdminUser(OC_User::getUser())) {
534
+		if (OC_User::isAdminUser(OC_User::getUser())) {
535 535
 			$headerIconCount--;
536 536
 		}
537 537
 		usort($list, function($a, $b) {
@@ -556,16 +556,16 @@  discard block
 block discarded – undo
556 556
 		}
557 557
 		unset($navEntry);
558 558
 
559
-		if($activeAppIndex > ($headerIconCount-1)) {
559
+		if ($activeAppIndex > ($headerIconCount - 1)) {
560 560
 			$active = $list[$activeAppIndex];
561
-			$lastInHeader = $list[$headerIconCount-1];
562
-			$list[$headerIconCount-1] = $active;
561
+			$lastInHeader = $list[$headerIconCount - 1];
562
+			$list[$headerIconCount - 1] = $active;
563 563
 			$list[$activeAppIndex] = $lastInHeader;
564 564
 		}
565 565
 
566 566
 		foreach ($list as $index => &$navEntry) {
567 567
 			$navEntry['showInHeader'] = false;
568
-			if($index < $headerIconCount) {
568
+			if ($index < $headerIconCount) {
569 569
 				$navEntry['showInHeader'] = true;
570 570
 			}
571 571
 		}
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 
578 578
 	public static function proceedAppNavigation($entries) {
579 579
 		$headerIconCount = 8;
580
-		if(OC_User::isAdminUser(OC_User::getUser())) {
580
+		if (OC_User::isAdminUser(OC_User::getUser())) {
581 581
 			$headerIconCount--;
582 582
 		}
583 583
 		$activeAppIndex = -1;
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
 			}
594 594
 		}
595 595
 		// move active item to last position
596
-		if($activeAppIndex > ($headerIconCount-1)) {
596
+		if ($activeAppIndex > ($headerIconCount - 1)) {
597 597
 			$active = $list[$activeAppIndex];
598
-			$lastInHeader = $list[$headerIconCount-1];
599
-			$list[$headerIconCount-1] = $active;
598
+			$lastInHeader = $list[$headerIconCount - 1];
599
+			$list[$headerIconCount - 1] = $active;
600 600
 			$list[$activeAppIndex] = $lastInHeader;
601 601
 		}
602 602
 		$list = array_slice($list, 0, $headerIconCount);
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 	 */
634 634
 	public static function findAppInDirectories($appId) {
635 635
 		$sanitizedAppId = self::cleanAppId($appId);
636
-		if($sanitizedAppId !== $appId) {
636
+		if ($sanitizedAppId !== $appId) {
637 637
 			return false;
638 638
 		}
639 639
 		static $app_dir = array();
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 
645 645
 		$possibleApps = array();
646 646
 		foreach (OC::$APPSROOTS as $dir) {
647
-			if (file_exists($dir['path'] . '/' . $appId)) {
647
+			if (file_exists($dir['path'].'/'.$appId)) {
648 648
 				$possibleApps[] = $dir;
649 649
 			}
650 650
 		}
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 		}
686 686
 
687 687
 		if (($dir = self::findAppInDirectories($appId)) != false) {
688
-			return $dir['path'] . '/' . $appId;
688
+			return $dir['path'].'/'.$appId;
689 689
 		}
690 690
 		return false;
691 691
 	}
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 	 */
700 700
 	public static function getAppWebPath($appId) {
701 701
 		if (($dir = self::findAppInDirectories($appId)) != false) {
702
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
702
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
703 703
 		}
704 704
 		return false;
705 705
 	}
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
 	 * @return string
713 713
 	 */
714 714
 	public static function getAppVersion($appId, $useCache = true) {
715
-		if($useCache && isset(self::$appVersion[$appId])) {
715
+		if ($useCache && isset(self::$appVersion[$appId])) {
716 716
 			return self::$appVersion[$appId];
717 717
 		}
718 718
 
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
 	 * @return string
729 729
 	 */
730 730
 	public static function getAppVersionByPath($path) {
731
-		$infoFile = $path . '/appinfo/info.xml';
731
+		$infoFile = $path.'/appinfo/info.xml';
732 732
 		$appData = self::getAppInfo($infoFile, true);
733 733
 		return isset($appData['version']) ? $appData['version'] : '';
734 734
 	}
@@ -751,10 +751,10 @@  discard block
 block discarded – undo
751 751
 				return self::$appInfo[$appId];
752 752
 			}
753 753
 			$appPath = self::getAppPath($appId);
754
-			if($appPath === false) {
754
+			if ($appPath === false) {
755 755
 				return null;
756 756
 			}
757
-			$file = $appPath . '/appinfo/info.xml';
757
+			$file = $appPath.'/appinfo/info.xml';
758 758
 		}
759 759
 
760 760
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
@@ -763,9 +763,9 @@  discard block
 block discarded – undo
763 763
 		if (is_array($data)) {
764 764
 			$data = OC_App::parseAppInfo($data, $lang);
765 765
 		}
766
-		if(isset($data['ocsid'])) {
766
+		if (isset($data['ocsid'])) {
767 767
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
768
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
769 769
 				$data['ocsid'] = $storedId;
770 770
 			}
771 771
 		}
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 	 * @param string $page
862 862
 	 */
863 863
 	public static function registerAdmin($app, $page) {
864
-		self::$adminForms[] = $app . '/' . $page . '.php';
864
+		self::$adminForms[] = $app.'/'.$page.'.php';
865 865
 	}
866 866
 
867 867
 	/**
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 	 * @param string $page
871 871
 	 */
872 872
 	public static function registerPersonal($app, $page) {
873
-		self::$personalForms[] = $app . '/' . $page . '.php';
873
+		self::$personalForms[] = $app.'/'.$page.'.php';
874 874
 	}
875 875
 
876 876
 	/**
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 
900 900
 		foreach (OC::$APPSROOTS as $apps_dir) {
901 901
 			if (!is_readable($apps_dir['path'])) {
902
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
902
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
903 903
 				continue;
904 904
 			}
905 905
 			$dh = opendir($apps_dir['path']);
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
 			if (is_resource($dh)) {
908 908
 				while (($file = readdir($dh)) !== false) {
909 909
 
910
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
910
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
911 911
 
912 912
 						$apps[] = $file;
913 913
 					}
@@ -937,12 +937,12 @@  discard block
 block discarded – undo
937 937
 
938 938
 				$info = OC_App::getAppInfo($app, false, $langCode);
939 939
 				if (!is_array($info)) {
940
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
940
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
941 941
 					continue;
942 942
 				}
943 943
 
944 944
 				if (!isset($info['name'])) {
945
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
945
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
946 946
 					continue;
947 947
 				}
948 948
 
@@ -969,13 +969,13 @@  discard block
 block discarded – undo
969 969
 				}
970 970
 
971 971
 				$appPath = self::getAppPath($app);
972
-				if($appPath !== false) {
973
-					$appIcon = $appPath . '/img/' . $app . '.svg';
972
+				if ($appPath !== false) {
973
+					$appIcon = $appPath.'/img/'.$app.'.svg';
974 974
 					if (file_exists($appIcon)) {
975
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
975
+						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app.'.svg');
976 976
 						$info['previewAsIcon'] = true;
977 977
 					} else {
978
-						$appIcon = $appPath . '/img/app.svg';
978
+						$appIcon = $appPath.'/img/app.svg';
979 979
 						if (file_exists($appIcon)) {
980 980
 							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981 981
 							$info['previewAsIcon'] = true;
@@ -1009,9 +1009,9 @@  discard block
 block discarded – undo
1009 1009
 	 * @return string|false
1010 1010
 	 */
1011 1011
 	public static function getInternalAppIdByOcs($ocsID) {
1012
-		if(is_numeric($ocsID)) {
1012
+		if (is_numeric($ocsID)) {
1013 1013
 			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
-			if(array_search($ocsID, $idArray)) {
1014
+			if (array_search($ocsID, $idArray)) {
1015 1015
 				return array_search($ocsID, $idArray);
1016 1016
 			}
1017 1017
 		}
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
 	public static function getAppVersions() {
1116 1116
 		static $versions;
1117 1117
 
1118
-		if(!$versions) {
1118
+		if (!$versions) {
1119 1119
 			$appConfig = \OC::$server->getAppConfig();
1120 1120
 			$versions = $appConfig->getValues(false, 'installed_version');
1121 1121
 		}
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
 		if ($app !== false) {
1138 1138
 			// check if the app is compatible with this version of ownCloud
1139 1139
 			$info = self::getAppInfo($app);
1140
-			if(!is_array($info)) {
1140
+			if (!is_array($info)) {
1141 1141
 				throw new \Exception(
1142 1142
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143 1143
 						[$info['name']]
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1163 1163
 			}
1164 1164
 
1165
-			if(isset($info['settings']) && is_array($info['settings'])) {
1165
+			if (isset($info['settings']) && is_array($info['settings'])) {
1166 1166
 				$appPath = self::getAppPath($app);
1167 1167
 				self::registerAutoloading($app, $appPath);
1168 1168
 				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -1170,7 +1170,7 @@  discard block
 block discarded – undo
1170 1170
 
1171 1171
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172 1172
 		} else {
1173
-			if(empty($appName) ) {
1173
+			if (empty($appName)) {
1174 1174
 				throw new \Exception($l->t("No app name specified"));
1175 1175
 			} else {
1176 1176
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1188,24 +1188,24 @@  discard block
 block discarded – undo
1188 1188
 	 */
1189 1189
 	public static function updateApp($appId) {
1190 1190
 		$appPath = self::getAppPath($appId);
1191
-		if($appPath === false) {
1191
+		if ($appPath === false) {
1192 1192
 			return false;
1193 1193
 		}
1194 1194
 		$appData = self::getAppInfo($appId);
1195 1195
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1197
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1196
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1197
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1198 1198
 		}
1199 1199
 		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200 1200
 		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201 1201
 		unset(self::$appVersion[$appId]);
1202 1202
 		// run upgrade code
1203
-		if (file_exists($appPath . '/appinfo/update.php')) {
1203
+		if (file_exists($appPath.'/appinfo/update.php')) {
1204 1204
 			self::loadApp($appId);
1205
-			include $appPath . '/appinfo/update.php';
1205
+			include $appPath.'/appinfo/update.php';
1206 1206
 		}
1207 1207
 		self::setupBackgroundJobs($appData['background-jobs']);
1208
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1208
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
1209 1209
 			$appPath = self::getAppPath($appId);
1210 1210
 			self::registerAutoloading($appId, $appPath);
1211 1211
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
@@ -1214,14 +1214,14 @@  discard block
 block discarded – undo
1214 1214
 		//set remote/public handlers
1215 1215
 		if (array_key_exists('ocsid', $appData)) {
1216 1216
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1217
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218 1218
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219 1219
 		}
1220 1220
 		foreach ($appData['remote'] as $name => $path) {
1221
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1221
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1222 1222
 		}
1223 1223
 		foreach ($appData['public'] as $name => $path) {
1224
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1224
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1225 1225
 		}
1226 1226
 
1227 1227
 		self::setAppTypes($appId);
@@ -1291,17 +1291,17 @@  discard block
 block discarded – undo
1291 1291
 	public static function getStorage($appId) {
1292 1292
 		if (OC_App::isEnabled($appId)) { //sanity check
1293 1293
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1294
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1295 1295
 				if (!$view->file_exists($appId)) {
1296 1296
 					$view->mkdir($appId);
1297 1297
 				}
1298
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1298
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1299 1299
 			} else {
1300
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1300
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1301 1301
 				return false;
1302 1302
 			}
1303 1303
 		} else {
1304
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1304
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1305 1305
 			return false;
1306 1306
 		}
1307 1307
 	}
@@ -1333,9 +1333,9 @@  discard block
 block discarded – undo
1333 1333
 
1334 1334
 				if ($attributeLang === $similarLang) {
1335 1335
 					$similarLangFallback = $option['@value'];
1336
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1336
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1337 1337
 					if ($similarLangFallback === false) {
1338
-						$similarLangFallback =  $option['@value'];
1338
+						$similarLangFallback = $option['@value'];
1339 1339
 					}
1340 1340
 				}
1341 1341
 			} else {
@@ -1370,7 +1370,7 @@  discard block
 block discarded – undo
1370 1370
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371 1371
 		} else if (isset($data['description']) && is_string($data['description'])) {
1372 1372
 			$data['description'] = trim($data['description']);
1373
-		} else  {
1373
+		} else {
1374 1374
 			$data['description'] = '';
1375 1375
 		}
1376 1376
 
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -40,391 +40,391 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-		if ($lang === null || !$this->languageExists($app, $lang)) {
103
-			$lang = $this->findLanguage($app);
104
-		}
105
-
106
-		if (!isset($this->instances[$lang][$app])) {
107
-			$this->instances[$lang][$app] = new L10N(
108
-				$this, $app, $lang,
109
-				$this->getL10nFilesForApp($app, $lang)
110
-			);
111
-		}
112
-
113
-		return $this->instances[$lang][$app];
114
-	}
115
-
116
-	/**
117
-	 * Find the best language
118
-	 *
119
-	 * @param string|null $app App id or null for core
120
-	 * @return string language If nothing works it returns 'en'
121
-	 */
122
-	public function findLanguage($app = null) {
123
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
-			return $this->requestLanguage;
125
-		}
126
-
127
-		/**
128
-		 * At this point ownCloud might not yet be installed and thus the lookup
129
-		 * in the preferences table might fail. For this reason we need to check
130
-		 * whether the instance has already been installed
131
-		 *
132
-		 * @link https://github.com/owncloud/core/issues/21955
133
-		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
137
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
-			} else {
139
-				$userLang = null;
140
-			}
141
-		} else {
142
-			$userId = null;
143
-			$userLang = null;
144
-		}
145
-
146
-		if ($userLang) {
147
-			$this->requestLanguage = $userLang;
148
-			if ($this->languageExists($app, $userLang)) {
149
-				return $userLang;
150
-			}
151
-		}
152
-
153
-		try {
154
-			// Try to get the language from the Request
155
-			$lang = $this->getLanguageFromRequest($app);
156
-			if ($userId !== null && $app === null && !$userLang) {
157
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
158
-			}
159
-			return $lang;
160
-		} catch (LanguageNotFoundException $e) {
161
-			// Finding language from request failed fall back to default language
162
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
163
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
-				return $defaultLanguage;
165
-			}
166
-		}
167
-
168
-		// We could not find any language so fall back to english
169
-		return 'en';
170
-	}
171
-
172
-	/**
173
-	 * Find all available languages for an app
174
-	 *
175
-	 * @param string|null $app App id or null for core
176
-	 * @return array an array of available languages
177
-	 */
178
-	public function findAvailableLanguages($app = null) {
179
-		$key = $app;
180
-		if ($key === null) {
181
-			$key = 'null';
182
-		}
183
-
184
-		// also works with null as key
185
-		if (!empty($this->availableLanguages[$key])) {
186
-			return $this->availableLanguages[$key];
187
-		}
188
-
189
-		$available = ['en']; //english is always available
190
-		$dir = $this->findL10nDir($app);
191
-		if (is_dir($dir)) {
192
-			$files = scandir($dir);
193
-			if ($files !== false) {
194
-				foreach ($files as $file) {
195
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
-						$available[] = substr($file, 0, -5);
197
-					}
198
-				}
199
-			}
200
-		}
201
-
202
-		// merge with translations from theme
203
-		$theme = $this->config->getSystemValue('theme');
204
-		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
-
207
-			if (is_dir($themeDir)) {
208
-				$files = scandir($themeDir);
209
-				if ($files !== false) {
210
-					foreach ($files as $file) {
211
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
-							$available[] = substr($file, 0, -5);
213
-						}
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$this->availableLanguages[$key] = $available;
220
-		return $available;
221
-	}
222
-
223
-	/**
224
-	 * @param string|null $app App id or null for core
225
-	 * @param string $lang
226
-	 * @return bool
227
-	 */
228
-	public function languageExists($app, $lang) {
229
-		if ($lang === 'en') {//english is always available
230
-			return true;
231
-		}
232
-
233
-		$languages = $this->findAvailableLanguages($app);
234
-		return array_search($lang, $languages) !== false;
235
-	}
236
-
237
-	/**
238
-	 * @param string|null $app
239
-	 * @return string
240
-	 * @throws LanguageNotFoundException
241
-	 */
242
-	private function getLanguageFromRequest($app) {
243
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
-		if ($header) {
245
-			$available = $this->findAvailableLanguages($app);
246
-
247
-			// E.g. make sure that 'de' is before 'de_DE'.
248
-			sort($available);
249
-
250
-			$preferences = preg_split('/,\s*/', strtolower($header));
251
-			foreach ($preferences as $preference) {
252
-				list($preferred_language) = explode(';', $preference);
253
-				$preferred_language = str_replace('-', '_', $preferred_language);
254
-
255
-				foreach ($available as $available_language) {
256
-					if ($preferred_language === strtolower($available_language)) {
257
-						return $available_language;
258
-					}
259
-				}
260
-
261
-				// Fallback from de_De to de
262
-				foreach ($available as $available_language) {
263
-					if (substr($preferred_language, 0, 2) === $available_language) {
264
-						return $available_language;
265
-					}
266
-				}
267
-			}
268
-		}
269
-
270
-		throw new LanguageNotFoundException();
271
-	}
272
-
273
-	/**
274
-	 * @param string|null $app App id or null for core
275
-	 * @return string
276
-	 */
277
-	public function setLanguageFromRequest($app = null) {
278
-
279
-		try {
280
-			$requestLanguage = $this->getLanguageFromRequest($app);
281
-		} catch (LanguageNotFoundException $e) {
282
-			$requestLanguage = 'en';
283
-		}
284
-
285
-		if ($app === null && !$this->requestLanguage) {
286
-			$this->requestLanguage = $requestLanguage;
287
-		}
288
-		return $requestLanguage;
289
-	}
290
-
291
-	/**
292
-	 * Checks if $sub is a subdirectory of $parent
293
-	 *
294
-	 * @param string $sub
295
-	 * @param string $parent
296
-	 * @return bool
297
-	 */
298
-	private function isSubDirectory($sub, $parent) {
299
-		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
301
-			return false;
302
-		}
303
-
304
-		// Check whether $sub is a subdirectory of $parent
305
-		if (strpos($sub, $parent) === 0) {
306
-			return true;
307
-		}
308
-
309
-		return false;
310
-	}
311
-
312
-	/**
313
-	 * Get a list of language files that should be loaded
314
-	 *
315
-	 * @param string $app
316
-	 * @param string $lang
317
-	 * @return string[]
318
-	 */
319
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
320
-	// FIXME This is also the reason, why it is not in the public interface
321
-	public function getL10nFilesForApp($app, $lang) {
322
-		$languageFiles = [];
323
-
324
-		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
-
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
-			)
332
-			&& file_exists($transFile)) {
333
-			// load the translations file
334
-			$languageFiles[] = $transFile;
335
-		}
336
-
337
-		// merge with translations from theme
338
-		$theme = $this->config->getSystemValue('theme');
339
-		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
-			if (file_exists($transFile)) {
342
-				$languageFiles[] = $transFile;
343
-			}
344
-		}
345
-
346
-		return $languageFiles;
347
-	}
348
-
349
-	/**
350
-	 * find the l10n directory
351
-	 *
352
-	 * @param string $app App id or empty string for core
353
-	 * @return string directory
354
-	 */
355
-	protected function findL10nDir($app = null) {
356
-		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
359
-			}
360
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
361
-			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
363
-		}
364
-		return $this->serverRoot . '/core/l10n/';
365
-	}
366
-
367
-
368
-	/**
369
-	 * Creates a function from the plural string
370
-	 *
371
-	 * Parts of the code is copied from Habari:
372
-	 * https://github.com/habari/system/blob/master/classes/locale.php
373
-	 * @param string $string
374
-	 * @return string
375
-	 */
376
-	public function createPluralFunction($string) {
377
-		if (isset($this->pluralFunctions[$string])) {
378
-			return $this->pluralFunctions[$string];
379
-		}
380
-
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
-			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
-
386
-			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
390
-			);
391
-
392
-			// add parents
393
-			// important since PHP's ternary evaluates from left to right
394
-			$body .= ';';
395
-			$res = '';
396
-			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
398
-				$ch = $body[$i];
399
-				switch ( $ch ) {
400
-					case '?':
401
-						$res .= ' ? (';
402
-						$p++;
403
-						break;
404
-					case ':':
405
-						$res .= ') : (';
406
-						break;
407
-					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
409
-						$p = 0;
410
-						break;
411
-					default:
412
-						$res .= $ch;
413
-				}
414
-			}
415
-
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
-			$function = create_function('$n', $body);
418
-			$this->pluralFunctions[$string] = $function;
419
-			return $function;
420
-		} else {
421
-			// default: one plural form for all cases but n==1 (english)
422
-			$function = create_function(
423
-				'$n',
424
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
-			);
426
-			$this->pluralFunctions[$string] = $function;
427
-			return $function;
428
-		}
429
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+        if ($lang === null || !$this->languageExists($app, $lang)) {
103
+            $lang = $this->findLanguage($app);
104
+        }
105
+
106
+        if (!isset($this->instances[$lang][$app])) {
107
+            $this->instances[$lang][$app] = new L10N(
108
+                $this, $app, $lang,
109
+                $this->getL10nFilesForApp($app, $lang)
110
+            );
111
+        }
112
+
113
+        return $this->instances[$lang][$app];
114
+    }
115
+
116
+    /**
117
+     * Find the best language
118
+     *
119
+     * @param string|null $app App id or null for core
120
+     * @return string language If nothing works it returns 'en'
121
+     */
122
+    public function findLanguage($app = null) {
123
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
+            return $this->requestLanguage;
125
+        }
126
+
127
+        /**
128
+         * At this point ownCloud might not yet be installed and thus the lookup
129
+         * in the preferences table might fail. For this reason we need to check
130
+         * whether the instance has already been installed
131
+         *
132
+         * @link https://github.com/owncloud/core/issues/21955
133
+         */
134
+        if($this->config->getSystemValue('installed', false)) {
135
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
+            if(!is_null($userId)) {
137
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
+            } else {
139
+                $userLang = null;
140
+            }
141
+        } else {
142
+            $userId = null;
143
+            $userLang = null;
144
+        }
145
+
146
+        if ($userLang) {
147
+            $this->requestLanguage = $userLang;
148
+            if ($this->languageExists($app, $userLang)) {
149
+                return $userLang;
150
+            }
151
+        }
152
+
153
+        try {
154
+            // Try to get the language from the Request
155
+            $lang = $this->getLanguageFromRequest($app);
156
+            if ($userId !== null && $app === null && !$userLang) {
157
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
158
+            }
159
+            return $lang;
160
+        } catch (LanguageNotFoundException $e) {
161
+            // Finding language from request failed fall back to default language
162
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
163
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
+                return $defaultLanguage;
165
+            }
166
+        }
167
+
168
+        // We could not find any language so fall back to english
169
+        return 'en';
170
+    }
171
+
172
+    /**
173
+     * Find all available languages for an app
174
+     *
175
+     * @param string|null $app App id or null for core
176
+     * @return array an array of available languages
177
+     */
178
+    public function findAvailableLanguages($app = null) {
179
+        $key = $app;
180
+        if ($key === null) {
181
+            $key = 'null';
182
+        }
183
+
184
+        // also works with null as key
185
+        if (!empty($this->availableLanguages[$key])) {
186
+            return $this->availableLanguages[$key];
187
+        }
188
+
189
+        $available = ['en']; //english is always available
190
+        $dir = $this->findL10nDir($app);
191
+        if (is_dir($dir)) {
192
+            $files = scandir($dir);
193
+            if ($files !== false) {
194
+                foreach ($files as $file) {
195
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
+                        $available[] = substr($file, 0, -5);
197
+                    }
198
+                }
199
+            }
200
+        }
201
+
202
+        // merge with translations from theme
203
+        $theme = $this->config->getSystemValue('theme');
204
+        if (!empty($theme)) {
205
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
+
207
+            if (is_dir($themeDir)) {
208
+                $files = scandir($themeDir);
209
+                if ($files !== false) {
210
+                    foreach ($files as $file) {
211
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
+                            $available[] = substr($file, 0, -5);
213
+                        }
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $this->availableLanguages[$key] = $available;
220
+        return $available;
221
+    }
222
+
223
+    /**
224
+     * @param string|null $app App id or null for core
225
+     * @param string $lang
226
+     * @return bool
227
+     */
228
+    public function languageExists($app, $lang) {
229
+        if ($lang === 'en') {//english is always available
230
+            return true;
231
+        }
232
+
233
+        $languages = $this->findAvailableLanguages($app);
234
+        return array_search($lang, $languages) !== false;
235
+    }
236
+
237
+    /**
238
+     * @param string|null $app
239
+     * @return string
240
+     * @throws LanguageNotFoundException
241
+     */
242
+    private function getLanguageFromRequest($app) {
243
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
+        if ($header) {
245
+            $available = $this->findAvailableLanguages($app);
246
+
247
+            // E.g. make sure that 'de' is before 'de_DE'.
248
+            sort($available);
249
+
250
+            $preferences = preg_split('/,\s*/', strtolower($header));
251
+            foreach ($preferences as $preference) {
252
+                list($preferred_language) = explode(';', $preference);
253
+                $preferred_language = str_replace('-', '_', $preferred_language);
254
+
255
+                foreach ($available as $available_language) {
256
+                    if ($preferred_language === strtolower($available_language)) {
257
+                        return $available_language;
258
+                    }
259
+                }
260
+
261
+                // Fallback from de_De to de
262
+                foreach ($available as $available_language) {
263
+                    if (substr($preferred_language, 0, 2) === $available_language) {
264
+                        return $available_language;
265
+                    }
266
+                }
267
+            }
268
+        }
269
+
270
+        throw new LanguageNotFoundException();
271
+    }
272
+
273
+    /**
274
+     * @param string|null $app App id or null for core
275
+     * @return string
276
+     */
277
+    public function setLanguageFromRequest($app = null) {
278
+
279
+        try {
280
+            $requestLanguage = $this->getLanguageFromRequest($app);
281
+        } catch (LanguageNotFoundException $e) {
282
+            $requestLanguage = 'en';
283
+        }
284
+
285
+        if ($app === null && !$this->requestLanguage) {
286
+            $this->requestLanguage = $requestLanguage;
287
+        }
288
+        return $requestLanguage;
289
+    }
290
+
291
+    /**
292
+     * Checks if $sub is a subdirectory of $parent
293
+     *
294
+     * @param string $sub
295
+     * @param string $parent
296
+     * @return bool
297
+     */
298
+    private function isSubDirectory($sub, $parent) {
299
+        // Check whether $sub contains no ".."
300
+        if(strpos($sub, '..') !== false) {
301
+            return false;
302
+        }
303
+
304
+        // Check whether $sub is a subdirectory of $parent
305
+        if (strpos($sub, $parent) === 0) {
306
+            return true;
307
+        }
308
+
309
+        return false;
310
+    }
311
+
312
+    /**
313
+     * Get a list of language files that should be loaded
314
+     *
315
+     * @param string $app
316
+     * @param string $lang
317
+     * @return string[]
318
+     */
319
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
320
+    // FIXME This is also the reason, why it is not in the public interface
321
+    public function getL10nFilesForApp($app, $lang) {
322
+        $languageFiles = [];
323
+
324
+        $i18nDir = $this->findL10nDir($app);
325
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
+
327
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
+            )
332
+            && file_exists($transFile)) {
333
+            // load the translations file
334
+            $languageFiles[] = $transFile;
335
+        }
336
+
337
+        // merge with translations from theme
338
+        $theme = $this->config->getSystemValue('theme');
339
+        if (!empty($theme)) {
340
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
+            if (file_exists($transFile)) {
342
+                $languageFiles[] = $transFile;
343
+            }
344
+        }
345
+
346
+        return $languageFiles;
347
+    }
348
+
349
+    /**
350
+     * find the l10n directory
351
+     *
352
+     * @param string $app App id or empty string for core
353
+     * @return string directory
354
+     */
355
+    protected function findL10nDir($app = null) {
356
+        if (in_array($app, ['core', 'lib', 'settings'])) {
357
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
+                return $this->serverRoot . '/' . $app . '/l10n/';
359
+            }
360
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
361
+            // Check if the app is in the app folder
362
+            return \OC_App::getAppPath($app) . '/l10n/';
363
+        }
364
+        return $this->serverRoot . '/core/l10n/';
365
+    }
366
+
367
+
368
+    /**
369
+     * Creates a function from the plural string
370
+     *
371
+     * Parts of the code is copied from Habari:
372
+     * https://github.com/habari/system/blob/master/classes/locale.php
373
+     * @param string $string
374
+     * @return string
375
+     */
376
+    public function createPluralFunction($string) {
377
+        if (isset($this->pluralFunctions[$string])) {
378
+            return $this->pluralFunctions[$string];
379
+        }
380
+
381
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
+            // sanitize
383
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
+
386
+            $body = str_replace(
387
+                array( 'plural', 'n', '$n$plurals', ),
388
+                array( '$plural', '$n', '$nplurals', ),
389
+                'nplurals='. $nplurals . '; plural=' . $plural
390
+            );
391
+
392
+            // add parents
393
+            // important since PHP's ternary evaluates from left to right
394
+            $body .= ';';
395
+            $res = '';
396
+            $p = 0;
397
+            for($i = 0; $i < strlen($body); $i++) {
398
+                $ch = $body[$i];
399
+                switch ( $ch ) {
400
+                    case '?':
401
+                        $res .= ' ? (';
402
+                        $p++;
403
+                        break;
404
+                    case ':':
405
+                        $res .= ') : (';
406
+                        break;
407
+                    case ';':
408
+                        $res .= str_repeat( ')', $p ) . ';';
409
+                        $p = 0;
410
+                        break;
411
+                    default:
412
+                        $res .= $ch;
413
+                }
414
+            }
415
+
416
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
+            $function = create_function('$n', $body);
418
+            $this->pluralFunctions[$string] = $function;
419
+            return $function;
420
+        } else {
421
+            // default: one plural form for all cases but n==1 (english)
422
+            $function = create_function(
423
+                '$n',
424
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
+            );
426
+            $this->pluralFunctions[$string] = $function;
427
+            return $function;
428
+        }
429
+    }
430 430
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @link https://github.com/owncloud/core/issues/21955
133 133
 		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
134
+		if ($this->config->getSystemValue('installed', false)) {
135
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
136
+			if (!is_null($userId)) {
137 137
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138 138
 			} else {
139 139
 				$userLang = null;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		// merge with translations from theme
203 203
 		$theme = $this->config->getSystemValue('theme');
204 204
 		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
205
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
206 206
 
207 207
 			if (is_dir($themeDir)) {
208 208
 				$files = scandir($themeDir);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	private function isSubDirectory($sub, $parent) {
299 299
 		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
300
+		if (strpos($sub, '..') !== false) {
301 301
 			return false;
302 302
 		}
303 303
 
@@ -322,12 +322,12 @@  discard block
 block discarded – undo
322 322
 		$languageFiles = [];
323 323
 
324 324
 		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
325
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
326 326
 
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
327
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
328
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
329
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
330
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
331 331
 			)
332 332
 			&& file_exists($transFile)) {
333 333
 			// load the translations file
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		// merge with translations from theme
338 338
 		$theme = $this->config->getSystemValue('theme');
339 339
 		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
340
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
341 341
 			if (file_exists($transFile)) {
342 342
 				$languageFiles[] = $transFile;
343 343
 			}
@@ -354,14 +354,14 @@  discard block
 block discarded – undo
354 354
 	 */
355 355
 	protected function findL10nDir($app = null) {
356 356
 		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
357
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
358
+				return $this->serverRoot.'/'.$app.'/l10n/';
359 359
 			}
360 360
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
361 361
 			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
362
+			return \OC_App::getAppPath($app).'/l10n/';
363 363
 		}
364
-		return $this->serverRoot . '/core/l10n/';
364
+		return $this->serverRoot.'/core/l10n/';
365 365
 	}
366 366
 
367 367
 
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 			return $this->pluralFunctions[$string];
379 379
 		}
380 380
 
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
381
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382 382
 			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
383
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
384
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
385 385
 
386 386
 			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
387
+				array('plural', 'n', '$n$plurals',),
388
+				array('$plural', '$n', '$nplurals',),
389
+				'nplurals='.$nplurals.'; plural='.$plural
390 390
 			);
391 391
 
392 392
 			// add parents
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 			$body .= ';';
395 395
 			$res = '';
396 396
 			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
397
+			for ($i = 0; $i < strlen($body); $i++) {
398 398
 				$ch = $body[$i];
399
-				switch ( $ch ) {
399
+				switch ($ch) {
400 400
 					case '?':
401 401
 						$res .= ' ? (';
402 402
 						$p++;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 						$res .= ') : (';
406 406
 						break;
407 407
 					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
408
+						$res .= str_repeat(')', $p).';';
409 409
 						$p = 0;
410 410
 						break;
411 411
 					default:
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				}
414 414
 			}
415 415
 
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
416
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
417 417
 			$function = create_function('$n', $body);
418 418
 			$this->pluralFunctions[$string] = $function;
419 419
 			return $function;
Please login to merge, or discard this patch.
lib/private/Installer.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,6 @@
 block discarded – undo
45 45
 use OC\App\CodeChecker\CodeChecker;
46 46
 use OC\App\CodeChecker\EmptyCheck;
47 47
 use OC\App\CodeChecker\PrivateCheck;
48
-use OC\Archive\Archive;
49 48
 use OC\Archive\TAR;
50 49
 use OC_App;
51 50
 use OC_DB;
Please login to merge, or discard this patch.
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -60,493 +60,493 @@
 block discarded – undo
60 60
  * This class provides the functionality needed to install, update and remove apps
61 61
  */
62 62
 class Installer {
63
-	/** @var AppFetcher */
64
-	private $appFetcher;
65
-	/** @var IClientService */
66
-	private $clientService;
67
-	/** @var ITempManager */
68
-	private $tempManager;
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/**
73
-	 * @param AppFetcher $appFetcher
74
-	 * @param IClientService $clientService
75
-	 * @param ITempManager $tempManager
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(AppFetcher $appFetcher,
79
-								IClientService $clientService,
80
-								ITempManager $tempManager,
81
-								ILogger $logger) {
82
-		$this->appFetcher = $appFetcher;
83
-		$this->clientService = $clientService;
84
-		$this->tempManager = $tempManager;
85
-		$this->logger = $logger;
86
-	}
87
-
88
-	/**
89
-	 * Installs an app that is located in one of the app folders already
90
-	 *
91
-	 * @param string $appId App to install
92
-	 * @throws \Exception
93
-	 * @return integer
94
-	 */
95
-	public function installApp($appId) {
96
-		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
98
-			throw new \Exception('App not found in any app directory');
99
-		}
100
-
101
-		$basedir = $app['path'].'/'.$appId;
102
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
-
104
-		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
106
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
-			} else {
109
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
-			}
111
-		}
112
-
113
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
114
-
115
-		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
118
-		}
119
-
120
-		$appData = OC_App::getAppInfo($appId);
121
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
-
123
-		//set the installed version
124
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
-
127
-		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
129
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
-		}
131
-		foreach($info['public'] as $name=>$path) {
132
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
-		}
134
-
135
-		OC_App::setAppTypes($info['id']);
136
-
137
-		return $info['id'];
138
-	}
139
-
140
-	/**
141
-	 * @brief checks whether or not an app is installed
142
-	 * @param string $app app
143
-	 * @returns bool
144
-	 *
145
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
146
-	 */
147
-	public static function isInstalled( $app ) {
148
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
-	}
150
-
151
-	/**
152
-	 * Updates the specified app from the appstore
153
-	 *
154
-	 * @param string $appId
155
-	 * @return bool
156
-	 */
157
-	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
-			try {
160
-				$this->downloadApp($appId);
161
-			} catch (\Exception $e) {
162
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
163
-				return false;
164
-			}
165
-			return OC_App::updateApp($appId);
166
-		}
167
-
168
-		return false;
169
-	}
170
-
171
-	/**
172
-	 * Downloads an app and puts it into the app directory
173
-	 *
174
-	 * @param string $appId
175
-	 *
176
-	 * @throws \Exception If the installation was not successful
177
-	 */
178
-	public function downloadApp($appId) {
179
-		$appId = strtolower($appId);
180
-
181
-		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
184
-				// Load the certificate
185
-				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
188
-
189
-				// Verify if the certificate has been revoked
190
-				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
194
-					throw new \Exception('Could not validate CRL signature');
195
-				}
196
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
-				$revoked = $crl->getRevoked($csn);
198
-				if ($revoked !== false) {
199
-					throw new \Exception(
200
-						sprintf(
201
-							'Certificate "%s" has been revoked',
202
-							$csn
203
-						)
204
-					);
205
-				}
206
-
207
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
209
-					throw new \Exception(
210
-						sprintf(
211
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
-							$appId
213
-						)
214
-					);
215
-				}
216
-
217
-				// Verify if the certificate is issued for the requested app id
218
-				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
220
-					throw new \Exception(
221
-						sprintf(
222
-							'App with id %s has a cert with no CN',
223
-							$appId
224
-						)
225
-					);
226
-				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
228
-					throw new \Exception(
229
-						sprintf(
230
-							'App with id %s has a cert issued to %s',
231
-							$appId,
232
-							$certInfo['subject']['CN']
233
-						)
234
-					);
235
-				}
236
-
237
-				// Download the release
238
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
-				$client = $this->clientService->newClient();
240
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
-
242
-				// Check if the signature actually matches the downloaded content
243
-				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
-				openssl_free_key($certificate);
246
-
247
-				if($verified === true) {
248
-					// Seems to match, let's proceed
249
-					$extractDir = $this->tempManager->getTemporaryFolder();
250
-					$archive = new TAR($tempFile);
251
-
252
-					if($archive) {
253
-						$archive->extract($extractDir);
254
-						$allFiles = scandir($extractDir);
255
-						$folders = array_diff($allFiles, ['.', '..']);
256
-						$folders = array_values($folders);
257
-
258
-						if(count($folders) > 1) {
259
-							throw new \Exception(
260
-								sprintf(
261
-									'Extracted app %s has more than 1 folder',
262
-									$appId
263
-								)
264
-							);
265
-						}
266
-
267
-						// Check if appinfo/info.xml has the same app ID as well
268
-						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
-						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
272
-							throw new \Exception(
273
-								sprintf(
274
-									'App for id %s has a wrong app ID in info.xml: %s',
275
-									$appId,
276
-									(string)$xml->id
277
-								)
278
-							);
279
-						}
280
-
281
-						// Check if the version is lower than before
282
-						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
285
-							throw new \Exception(
286
-								sprintf(
287
-									'App for id %s has version %s and tried to update to lower version %s',
288
-									$appId,
289
-									$currentVersion,
290
-									$newVersion
291
-								)
292
-							);
293
-						}
294
-
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
296
-						// Remove old app with the ID if existent
297
-						OC_Helper::rmdirr($baseDir);
298
-						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
301
-							OC_Helper::copyr($extractDir, $baseDir);
302
-						}
303
-						OC_Helper::copyr($extractDir, $baseDir);
304
-						OC_Helper::rmdirr($extractDir);
305
-						return;
306
-					} else {
307
-						throw new \Exception(
308
-							sprintf(
309
-								'Could not extract app with ID %s to %s',
310
-								$appId,
311
-								$extractDir
312
-							)
313
-						);
314
-					}
315
-				} else {
316
-					// Signature does not match
317
-					throw new \Exception(
318
-						sprintf(
319
-							'App with id %s has invalid signature',
320
-							$appId
321
-						)
322
-					);
323
-				}
324
-			}
325
-		}
326
-
327
-		throw new \Exception(
328
-			sprintf(
329
-				'Could not download app %s',
330
-				$appId
331
-			)
332
-		);
333
-	}
334
-
335
-	/**
336
-	 * Check if an update for the app is available
337
-	 *
338
-	 * @param string $appId
339
-	 * @param AppFetcher $appFetcher
340
-	 * @return string|false false or the version number of the update
341
-	 */
342
-	public static function isUpdateAvailable($appId,
343
-									  AppFetcher $appFetcher) {
344
-		static $isInstanceReadyForUpdates = null;
345
-
346
-		if ($isInstanceReadyForUpdates === null) {
347
-			$installPath = OC_App::getInstallPath();
348
-			if ($installPath === false || $installPath === null) {
349
-				$isInstanceReadyForUpdates = false;
350
-			} else {
351
-				$isInstanceReadyForUpdates = true;
352
-			}
353
-		}
354
-
355
-		if ($isInstanceReadyForUpdates === false) {
356
-			return false;
357
-		}
358
-
359
-		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
362
-				$currentVersion = OC_App::getAppVersion($appId);
363
-				$newestVersion = $app['releases'][0]['version'];
364
-				if (version_compare($newestVersion, $currentVersion, '>')) {
365
-					return $newestVersion;
366
-				} else {
367
-					return false;
368
-				}
369
-			}
370
-		}
371
-
372
-		return false;
373
-	}
374
-
375
-	/**
376
-	 * Check if app is already downloaded
377
-	 * @param string $name name of the application to remove
378
-	 * @return boolean
379
-	 *
380
-	 * The function will check if the app is already downloaded in the apps repository
381
-	 */
382
-	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
384
-			$dirToTest  = $dir['path'];
385
-			$dirToTest .= '/';
386
-			$dirToTest .= $name;
387
-			$dirToTest .= '/';
388
-
389
-			if (is_dir($dirToTest)) {
390
-				return true;
391
-			}
392
-		}
393
-
394
-		return false;
395
-	}
396
-
397
-	/**
398
-	 * Removes an app
399
-	 * @param string $appId ID of the application to remove
400
-	 * @return boolean
401
-	 *
402
-	 *
403
-	 * This function works as follows
404
-	 *   -# call uninstall repair steps
405
-	 *   -# removing the files
406
-	 *
407
-	 * The function will not delete preferences, tables and the configuration,
408
-	 * this has to be done by the function oc_app_uninstall().
409
-	 */
410
-	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
413
-			OC_Helper::rmdirr($appDir);
414
-			return true;
415
-		}else{
416
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
-
418
-			return false;
419
-		}
420
-
421
-	}
422
-
423
-	/**
424
-	 * Installs shipped apps
425
-	 *
426
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
-	 *                         working ownCloud at the end instead of an aborted update.
429
-	 * @return array Array of error messages (appid => Exception)
430
-	 */
431
-	public static function installShippedApps($softErrors = false) {
432
-		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
440
-								$enabled = isset($info['default_enable']);
441
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
-									if ($softErrors) {
444
-										try {
445
-											Installer::installShippedApp($filename);
446
-										} catch (HintException $e) {
447
-											if ($e->getPrevious() instanceof TableExistsException) {
448
-												$errors[$filename] = $e;
449
-												continue;
450
-											}
451
-											throw $e;
452
-										}
453
-									} else {
454
-										Installer::installShippedApp($filename);
455
-									}
456
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
-								}
458
-							}
459
-						}
460
-					}
461
-				}
462
-				closedir( $dir );
463
-			}
464
-		}
465
-
466
-		return $errors;
467
-	}
468
-
469
-	/**
470
-	 * install an app already placed in the app folder
471
-	 * @param string $app id of the app to install
472
-	 * @return integer
473
-	 */
474
-	public static function installShippedApp($app) {
475
-		//install the database
476
-		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
478
-			try {
479
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
-			} catch (TableExistsException $e) {
481
-				throw new HintException(
482
-					'Failed to enable app ' . $app,
483
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
-					0, $e
485
-				);
486
-			}
487
-		}
488
-
489
-		//run appinfo/install.php
490
-		\OC_App::registerAutoloading($app, $appPath);
491
-		self::includeAppScript("$appPath/appinfo/install.php");
492
-
493
-		$info = OC_App::getAppInfo($app);
494
-		if (is_null($info)) {
495
-			return false;
496
-		}
497
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
498
-
499
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
-
501
-		$config = \OC::$server->getConfig();
502
-
503
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
-		if (array_key_exists('ocsid', $info)) {
505
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
506
-		}
507
-
508
-		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
510
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
-		}
512
-		foreach($info['public'] as $name=>$path) {
513
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
-		}
515
-
516
-		OC_App::setAppTypes($info['id']);
517
-
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
519
-			// requires that autoloading was registered for the app,
520
-			// as happens before running the install.php some lines above
521
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
-		}
523
-
524
-		return $info['id'];
525
-	}
526
-
527
-	/**
528
-	 * check the code of an app with some static code checks
529
-	 * @param string $folder the folder of the app to check
530
-	 * @return boolean true for app is o.k. and false for app is not o.k.
531
-	 */
532
-	public static function checkCode($folder) {
533
-		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
-			return true;
536
-		}
537
-
538
-		$codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
-		$errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
-
541
-		return empty($errors);
542
-	}
543
-
544
-	/**
545
-	 * @param string $script
546
-	 */
547
-	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
549
-			include $script;
550
-		}
551
-	}
63
+    /** @var AppFetcher */
64
+    private $appFetcher;
65
+    /** @var IClientService */
66
+    private $clientService;
67
+    /** @var ITempManager */
68
+    private $tempManager;
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /**
73
+     * @param AppFetcher $appFetcher
74
+     * @param IClientService $clientService
75
+     * @param ITempManager $tempManager
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(AppFetcher $appFetcher,
79
+                                IClientService $clientService,
80
+                                ITempManager $tempManager,
81
+                                ILogger $logger) {
82
+        $this->appFetcher = $appFetcher;
83
+        $this->clientService = $clientService;
84
+        $this->tempManager = $tempManager;
85
+        $this->logger = $logger;
86
+    }
87
+
88
+    /**
89
+     * Installs an app that is located in one of the app folders already
90
+     *
91
+     * @param string $appId App to install
92
+     * @throws \Exception
93
+     * @return integer
94
+     */
95
+    public function installApp($appId) {
96
+        $app = \OC_App::findAppInDirectories($appId);
97
+        if($app === false) {
98
+            throw new \Exception('App not found in any app directory');
99
+        }
100
+
101
+        $basedir = $app['path'].'/'.$appId;
102
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
+
104
+        //install the database
105
+        if(is_file($basedir.'/appinfo/database.xml')) {
106
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
+            } else {
109
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
+            }
111
+        }
112
+
113
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
114
+
115
+        //run appinfo/install.php
116
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
+            self::includeAppScript($basedir . '/appinfo/install.php');
118
+        }
119
+
120
+        $appData = OC_App::getAppInfo($appId);
121
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
+
123
+        //set the installed version
124
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
+
127
+        //set remote/public handlers
128
+        foreach($info['remote'] as $name=>$path) {
129
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
+        }
131
+        foreach($info['public'] as $name=>$path) {
132
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
+        }
134
+
135
+        OC_App::setAppTypes($info['id']);
136
+
137
+        return $info['id'];
138
+    }
139
+
140
+    /**
141
+     * @brief checks whether or not an app is installed
142
+     * @param string $app app
143
+     * @returns bool
144
+     *
145
+     * Checks whether or not an app is installed, i.e. registered in apps table.
146
+     */
147
+    public static function isInstalled( $app ) {
148
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
+    }
150
+
151
+    /**
152
+     * Updates the specified app from the appstore
153
+     *
154
+     * @param string $appId
155
+     * @return bool
156
+     */
157
+    public function updateAppstoreApp($appId) {
158
+        if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
+            try {
160
+                $this->downloadApp($appId);
161
+            } catch (\Exception $e) {
162
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
163
+                return false;
164
+            }
165
+            return OC_App::updateApp($appId);
166
+        }
167
+
168
+        return false;
169
+    }
170
+
171
+    /**
172
+     * Downloads an app and puts it into the app directory
173
+     *
174
+     * @param string $appId
175
+     *
176
+     * @throws \Exception If the installation was not successful
177
+     */
178
+    public function downloadApp($appId) {
179
+        $appId = strtolower($appId);
180
+
181
+        $apps = $this->appFetcher->get();
182
+        foreach($apps as $app) {
183
+            if($app['id'] === $appId) {
184
+                // Load the certificate
185
+                $certificate = new X509();
186
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
188
+
189
+                // Verify if the certificate has been revoked
190
+                $crl = new X509();
191
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
+                if($crl->validateSignature() !== true) {
194
+                    throw new \Exception('Could not validate CRL signature');
195
+                }
196
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
+                $revoked = $crl->getRevoked($csn);
198
+                if ($revoked !== false) {
199
+                    throw new \Exception(
200
+                        sprintf(
201
+                            'Certificate "%s" has been revoked',
202
+                            $csn
203
+                        )
204
+                    );
205
+                }
206
+
207
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
+                if($certificate->validateSignature() !== true) {
209
+                    throw new \Exception(
210
+                        sprintf(
211
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
+                            $appId
213
+                        )
214
+                    );
215
+                }
216
+
217
+                // Verify if the certificate is issued for the requested app id
218
+                $certInfo = openssl_x509_parse($app['certificate']);
219
+                if(!isset($certInfo['subject']['CN'])) {
220
+                    throw new \Exception(
221
+                        sprintf(
222
+                            'App with id %s has a cert with no CN',
223
+                            $appId
224
+                        )
225
+                    );
226
+                }
227
+                if($certInfo['subject']['CN'] !== $appId) {
228
+                    throw new \Exception(
229
+                        sprintf(
230
+                            'App with id %s has a cert issued to %s',
231
+                            $appId,
232
+                            $certInfo['subject']['CN']
233
+                        )
234
+                    );
235
+                }
236
+
237
+                // Download the release
238
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
+                $client = $this->clientService->newClient();
240
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
+
242
+                // Check if the signature actually matches the downloaded content
243
+                $certificate = openssl_get_publickey($app['certificate']);
244
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
+                openssl_free_key($certificate);
246
+
247
+                if($verified === true) {
248
+                    // Seems to match, let's proceed
249
+                    $extractDir = $this->tempManager->getTemporaryFolder();
250
+                    $archive = new TAR($tempFile);
251
+
252
+                    if($archive) {
253
+                        $archive->extract($extractDir);
254
+                        $allFiles = scandir($extractDir);
255
+                        $folders = array_diff($allFiles, ['.', '..']);
256
+                        $folders = array_values($folders);
257
+
258
+                        if(count($folders) > 1) {
259
+                            throw new \Exception(
260
+                                sprintf(
261
+                                    'Extracted app %s has more than 1 folder',
262
+                                    $appId
263
+                                )
264
+                            );
265
+                        }
266
+
267
+                        // Check if appinfo/info.xml has the same app ID as well
268
+                        $loadEntities = libxml_disable_entity_loader(false);
269
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
+                        libxml_disable_entity_loader($loadEntities);
271
+                        if((string)$xml->id !== $appId) {
272
+                            throw new \Exception(
273
+                                sprintf(
274
+                                    'App for id %s has a wrong app ID in info.xml: %s',
275
+                                    $appId,
276
+                                    (string)$xml->id
277
+                                )
278
+                            );
279
+                        }
280
+
281
+                        // Check if the version is lower than before
282
+                        $currentVersion = OC_App::getAppVersion($appId);
283
+                        $newVersion = (string)$xml->version;
284
+                        if(version_compare($currentVersion, $newVersion) === 1) {
285
+                            throw new \Exception(
286
+                                sprintf(
287
+                                    'App for id %s has version %s and tried to update to lower version %s',
288
+                                    $appId,
289
+                                    $currentVersion,
290
+                                    $newVersion
291
+                                )
292
+                            );
293
+                        }
294
+
295
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
296
+                        // Remove old app with the ID if existent
297
+                        OC_Helper::rmdirr($baseDir);
298
+                        // Move to app folder
299
+                        if(@mkdir($baseDir)) {
300
+                            $extractDir .= '/' . $folders[0];
301
+                            OC_Helper::copyr($extractDir, $baseDir);
302
+                        }
303
+                        OC_Helper::copyr($extractDir, $baseDir);
304
+                        OC_Helper::rmdirr($extractDir);
305
+                        return;
306
+                    } else {
307
+                        throw new \Exception(
308
+                            sprintf(
309
+                                'Could not extract app with ID %s to %s',
310
+                                $appId,
311
+                                $extractDir
312
+                            )
313
+                        );
314
+                    }
315
+                } else {
316
+                    // Signature does not match
317
+                    throw new \Exception(
318
+                        sprintf(
319
+                            'App with id %s has invalid signature',
320
+                            $appId
321
+                        )
322
+                    );
323
+                }
324
+            }
325
+        }
326
+
327
+        throw new \Exception(
328
+            sprintf(
329
+                'Could not download app %s',
330
+                $appId
331
+            )
332
+        );
333
+    }
334
+
335
+    /**
336
+     * Check if an update for the app is available
337
+     *
338
+     * @param string $appId
339
+     * @param AppFetcher $appFetcher
340
+     * @return string|false false or the version number of the update
341
+     */
342
+    public static function isUpdateAvailable($appId,
343
+                                        AppFetcher $appFetcher) {
344
+        static $isInstanceReadyForUpdates = null;
345
+
346
+        if ($isInstanceReadyForUpdates === null) {
347
+            $installPath = OC_App::getInstallPath();
348
+            if ($installPath === false || $installPath === null) {
349
+                $isInstanceReadyForUpdates = false;
350
+            } else {
351
+                $isInstanceReadyForUpdates = true;
352
+            }
353
+        }
354
+
355
+        if ($isInstanceReadyForUpdates === false) {
356
+            return false;
357
+        }
358
+
359
+        $apps = $appFetcher->get();
360
+        foreach($apps as $app) {
361
+            if($app['id'] === $appId) {
362
+                $currentVersion = OC_App::getAppVersion($appId);
363
+                $newestVersion = $app['releases'][0]['version'];
364
+                if (version_compare($newestVersion, $currentVersion, '>')) {
365
+                    return $newestVersion;
366
+                } else {
367
+                    return false;
368
+                }
369
+            }
370
+        }
371
+
372
+        return false;
373
+    }
374
+
375
+    /**
376
+     * Check if app is already downloaded
377
+     * @param string $name name of the application to remove
378
+     * @return boolean
379
+     *
380
+     * The function will check if the app is already downloaded in the apps repository
381
+     */
382
+    public function isDownloaded($name) {
383
+        foreach(\OC::$APPSROOTS as $dir) {
384
+            $dirToTest  = $dir['path'];
385
+            $dirToTest .= '/';
386
+            $dirToTest .= $name;
387
+            $dirToTest .= '/';
388
+
389
+            if (is_dir($dirToTest)) {
390
+                return true;
391
+            }
392
+        }
393
+
394
+        return false;
395
+    }
396
+
397
+    /**
398
+     * Removes an app
399
+     * @param string $appId ID of the application to remove
400
+     * @return boolean
401
+     *
402
+     *
403
+     * This function works as follows
404
+     *   -# call uninstall repair steps
405
+     *   -# removing the files
406
+     *
407
+     * The function will not delete preferences, tables and the configuration,
408
+     * this has to be done by the function oc_app_uninstall().
409
+     */
410
+    public function removeApp($appId) {
411
+        if($this->isDownloaded( $appId )) {
412
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
413
+            OC_Helper::rmdirr($appDir);
414
+            return true;
415
+        }else{
416
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
+
418
+            return false;
419
+        }
420
+
421
+    }
422
+
423
+    /**
424
+     * Installs shipped apps
425
+     *
426
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
+     *                         working ownCloud at the end instead of an aborted update.
429
+     * @return array Array of error messages (appid => Exception)
430
+     */
431
+    public static function installShippedApps($softErrors = false) {
432
+        $errors = [];
433
+        foreach(\OC::$APPSROOTS as $app_dir) {
434
+            if($dir = opendir( $app_dir['path'] )) {
435
+                while( false !== ( $filename = readdir( $dir ))) {
436
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
+                            if(!Installer::isInstalled($filename)) {
439
+                                $info=OC_App::getAppInfo($filename);
440
+                                $enabled = isset($info['default_enable']);
441
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
+                                    if ($softErrors) {
444
+                                        try {
445
+                                            Installer::installShippedApp($filename);
446
+                                        } catch (HintException $e) {
447
+                                            if ($e->getPrevious() instanceof TableExistsException) {
448
+                                                $errors[$filename] = $e;
449
+                                                continue;
450
+                                            }
451
+                                            throw $e;
452
+                                        }
453
+                                    } else {
454
+                                        Installer::installShippedApp($filename);
455
+                                    }
456
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
+                                }
458
+                            }
459
+                        }
460
+                    }
461
+                }
462
+                closedir( $dir );
463
+            }
464
+        }
465
+
466
+        return $errors;
467
+    }
468
+
469
+    /**
470
+     * install an app already placed in the app folder
471
+     * @param string $app id of the app to install
472
+     * @return integer
473
+     */
474
+    public static function installShippedApp($app) {
475
+        //install the database
476
+        $appPath = OC_App::getAppPath($app);
477
+        if(is_file("$appPath/appinfo/database.xml")) {
478
+            try {
479
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
+            } catch (TableExistsException $e) {
481
+                throw new HintException(
482
+                    'Failed to enable app ' . $app,
483
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
+                    0, $e
485
+                );
486
+            }
487
+        }
488
+
489
+        //run appinfo/install.php
490
+        \OC_App::registerAutoloading($app, $appPath);
491
+        self::includeAppScript("$appPath/appinfo/install.php");
492
+
493
+        $info = OC_App::getAppInfo($app);
494
+        if (is_null($info)) {
495
+            return false;
496
+        }
497
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
498
+
499
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
+
501
+        $config = \OC::$server->getConfig();
502
+
503
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
+        if (array_key_exists('ocsid', $info)) {
505
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
506
+        }
507
+
508
+        //set remote/public handlers
509
+        foreach($info['remote'] as $name=>$path) {
510
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
+        }
512
+        foreach($info['public'] as $name=>$path) {
513
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
+        }
515
+
516
+        OC_App::setAppTypes($info['id']);
517
+
518
+        if(isset($info['settings']) && is_array($info['settings'])) {
519
+            // requires that autoloading was registered for the app,
520
+            // as happens before running the install.php some lines above
521
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
+        }
523
+
524
+        return $info['id'];
525
+    }
526
+
527
+    /**
528
+     * check the code of an app with some static code checks
529
+     * @param string $folder the folder of the app to check
530
+     * @return boolean true for app is o.k. and false for app is not o.k.
531
+     */
532
+    public static function checkCode($folder) {
533
+        // is the code checker enabled?
534
+        if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
+            return true;
536
+        }
537
+
538
+        $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
+        $errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
+
541
+        return empty($errors);
542
+    }
543
+
544
+    /**
545
+     * @param string $script
546
+     */
547
+    private static function includeAppScript($script) {
548
+        if ( file_exists($script) ){
549
+            include $script;
550
+        }
551
+    }
552 552
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function installApp($appId) {
96 96
 		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
97
+		if ($app === false) {
98 98
 			throw new \Exception('App not found in any app directory');
99 99
 		}
100 100
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103 103
 
104 104
 		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
105
+		if (is_file($basedir.'/appinfo/database.xml')) {
106 106
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107 107
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108 108
 			} else {
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
114 114
 
115 115
 		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
116
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
117
+			self::includeAppScript($basedir.'/appinfo/install.php');
118 118
 		}
119 119
 
120 120
 		$appData = OC_App::getAppInfo($appId);
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126 126
 
127 127
 		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
128
+		foreach ($info['remote'] as $name=>$path) {
129 129
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130 130
 		}
131
-		foreach($info['public'] as $name=>$path) {
131
+		foreach ($info['public'] as $name=>$path) {
132 132
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133 133
 		}
134 134
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
146 146
 	 */
147
-	public static function isInstalled( $app ) {
147
+	public static function isInstalled($app) {
148 148
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149 149
 	}
150 150
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @return bool
156 156
 	 */
157 157
 	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
158
+		if (self::isUpdateAvailable($appId, $this->appFetcher)) {
159 159
 			try {
160 160
 				$this->downloadApp($appId);
161 161
 			} catch (\Exception $e) {
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
 		$appId = strtolower($appId);
180 180
 
181 181
 		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
182
+		foreach ($apps as $app) {
183
+			if ($app['id'] === $appId) {
184 184
 				// Load the certificate
185 185
 				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
186
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
187 187
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
188 188
 
189 189
 				// Verify if the certificate has been revoked
190 190
 				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
191
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
192
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
193
+				if ($crl->validateSignature() !== true) {
194 194
 					throw new \Exception('Could not validate CRL signature');
195 195
 				}
196 196
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				}
206 206
 
207 207
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
208
+				if ($certificate->validateSignature() !== true) {
209 209
 					throw new \Exception(
210 210
 						sprintf(
211 211
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
 				// Verify if the certificate is issued for the requested app id
218 218
 				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
219
+				if (!isset($certInfo['subject']['CN'])) {
220 220
 					throw new \Exception(
221 221
 						sprintf(
222 222
 							'App with id %s has a cert with no CN',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 						)
225 225
 					);
226 226
 				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
227
+				if ($certInfo['subject']['CN'] !== $appId) {
228 228
 					throw new \Exception(
229 229
 						sprintf(
230 230
 							'App with id %s has a cert issued to %s',
@@ -241,21 +241,21 @@  discard block
 block discarded – undo
241 241
 
242 242
 				// Check if the signature actually matches the downloaded content
243 243
 				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
244
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245 245
 				openssl_free_key($certificate);
246 246
 
247
-				if($verified === true) {
247
+				if ($verified === true) {
248 248
 					// Seems to match, let's proceed
249 249
 					$extractDir = $this->tempManager->getTemporaryFolder();
250 250
 					$archive = new TAR($tempFile);
251 251
 
252
-					if($archive) {
252
+					if ($archive) {
253 253
 						$archive->extract($extractDir);
254 254
 						$allFiles = scandir($extractDir);
255 255
 						$folders = array_diff($allFiles, ['.', '..']);
256 256
 						$folders = array_values($folders);
257 257
 
258
-						if(count($folders) > 1) {
258
+						if (count($folders) > 1) {
259 259
 							throw new \Exception(
260 260
 								sprintf(
261 261
 									'Extracted app %s has more than 1 folder',
@@ -266,22 +266,22 @@  discard block
 block discarded – undo
266 266
 
267 267
 						// Check if appinfo/info.xml has the same app ID as well
268 268
 						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
269
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
270 270
 						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
271
+						if ((string) $xml->id !== $appId) {
272 272
 							throw new \Exception(
273 273
 								sprintf(
274 274
 									'App for id %s has a wrong app ID in info.xml: %s',
275 275
 									$appId,
276
-									(string)$xml->id
276
+									(string) $xml->id
277 277
 								)
278 278
 							);
279 279
 						}
280 280
 
281 281
 						// Check if the version is lower than before
282 282
 						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
283
+						$newVersion = (string) $xml->version;
284
+						if (version_compare($currentVersion, $newVersion) === 1) {
285 285
 							throw new \Exception(
286 286
 								sprintf(
287 287
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -292,12 +292,12 @@  discard block
 block discarded – undo
292 292
 							);
293 293
 						}
294 294
 
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
295
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
296 296
 						// Remove old app with the ID if existent
297 297
 						OC_Helper::rmdirr($baseDir);
298 298
 						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
299
+						if (@mkdir($baseDir)) {
300
+							$extractDir .= '/'.$folders[0];
301 301
 							OC_Helper::copyr($extractDir, $baseDir);
302 302
 						}
303 303
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
360
+		foreach ($apps as $app) {
361
+			if ($app['id'] === $appId) {
362 362
 				$currentVersion = OC_App::getAppVersion($appId);
363 363
 				$newestVersion = $app['releases'][0]['version'];
364 364
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * The function will check if the app is already downloaded in the apps repository
381 381
 	 */
382 382
 	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
383
+		foreach (\OC::$APPSROOTS as $dir) {
384 384
 			$dirToTest  = $dir['path'];
385 385
 			$dirToTest .= '/';
386 386
 			$dirToTest .= $name;
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
 	 * this has to be done by the function oc_app_uninstall().
409 409
 	 */
410 410
 	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
411
+		if ($this->isDownloaded($appId)) {
412
+			$appDir = OC_App::getInstallPath().'/'.$appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else {
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
@@ -430,13 +430,13 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	public static function installShippedApps($softErrors = false) {
432 432
 		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
433
+		foreach (\OC::$APPSROOTS as $app_dir) {
434
+			if ($dir = opendir($app_dir['path'])) {
435
+				while (false !== ($filename = readdir($dir))) {
436
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
437
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
438
+							if (!Installer::isInstalled($filename)) {
439
+								$info = OC_App::getAppInfo($filename);
440 440
 								$enabled = isset($info['default_enable']);
441 441
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442 442
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 						}
460 460
 					}
461 461
 				}
462
-				closedir( $dir );
462
+				closedir($dir);
463 463
 			}
464 464
 		}
465 465
 
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
 	public static function installShippedApp($app) {
475 475
 		//install the database
476 476
 		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
477
+		if (is_file("$appPath/appinfo/database.xml")) {
478 478
 			try {
479 479
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480 480
 			} catch (TableExistsException $e) {
481 481
 				throw new HintException(
482
-					'Failed to enable app ' . $app,
482
+					'Failed to enable app '.$app,
483 483
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484 484
 					0, $e
485 485
 				);
@@ -506,16 +506,16 @@  discard block
 block discarded – undo
506 506
 		}
507 507
 
508 508
 		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
509
+		foreach ($info['remote'] as $name=>$path) {
510 510
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511 511
 		}
512
-		foreach($info['public'] as $name=>$path) {
512
+		foreach ($info['public'] as $name=>$path) {
513 513
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514 514
 		}
515 515
 
516 516
 		OC_App::setAppTypes($info['id']);
517 517
 
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
518
+		if (isset($info['settings']) && is_array($info['settings'])) {
519 519
 			// requires that autoloading was registered for the app,
520 520
 			// as happens before running the install.php some lines above
521 521
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	 */
532 532
 	public static function checkCode($folder) {
533 533
 		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
534
+		if (!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535 535
 			return true;
536 536
 		}
537 537
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @param string $script
546 546
 	 */
547 547
 	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
548
+		if (file_exists($script)) {
549 549
 			include $script;
550 550
 		}
551 551
 	}
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -412,7 +412,7 @@
 block discarded – undo
412 412
 			$appDir = OC_App::getInstallPath() . '/' . $appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else{
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
Please login to merge, or discard this patch.
apps/dav/lib/HookManager.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use OCP\IUserManager;
29 29
 use OCP\Util;
30 30
 use Symfony\Component\EventDispatcher\EventDispatcher;
31
-use Symfony\Component\EventDispatcher\GenericEvent;
32 31
 
33 32
 class HookManager {
34 33
 
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -32,115 +32,115 @@
 block discarded – undo
32 32
 
33 33
 class HookManager {
34 34
 
35
-	/** @var IUserManager */
36
-	private $userManager;
37
-
38
-	/** @var SyncService */
39
-	private $syncService;
40
-
41
-	/** @var IUser[] */
42
-	private $usersToDelete;
43
-
44
-	/** @var CalDavBackend */
45
-	private $calDav;
46
-
47
-	/** @var CardDavBackend */
48
-	private $cardDav;
49
-
50
-	/** @var array */
51
-	private $calendarsToDelete;
52
-
53
-	/** @var array */
54
-	private $addressBooksToDelete;
55
-
56
-	/** @var EventDispatcher */
57
-	private $eventDispatcher;
58
-
59
-	public function __construct(IUserManager $userManager,
60
-								SyncService $syncService,
61
-								CalDavBackend $calDav,
62
-								CardDavBackend $cardDav,
63
-								EventDispatcher $eventDispatcher) {
64
-		$this->userManager = $userManager;
65
-		$this->syncService = $syncService;
66
-		$this->calDav = $calDav;
67
-		$this->cardDav = $cardDav;
68
-		$this->eventDispatcher = $eventDispatcher;
69
-	}
70
-
71
-	public function setup() {
72
-		Util::connectHook('OC_User',
73
-			'post_createUser',
74
-			$this,
75
-			'postCreateUser');
76
-		Util::connectHook('OC_User',
77
-			'pre_deleteUser',
78
-			$this,
79
-			'preDeleteUser');
80
-		Util::connectHook('OC_User',
81
-			'post_deleteUser',
82
-			$this,
83
-			'postDeleteUser');
84
-		Util::connectHook('OC_User',
85
-			'changeUser',
86
-			$this,
87
-			'changeUser');
88
-	}
89
-
90
-	public function postCreateUser($params) {
91
-		$user = $this->userManager->get($params['uid']);
92
-		$this->syncService->updateUser($user);
93
-	}
94
-
95
-	public function preDeleteUser($params) {
96
-		$uid = $params['uid'];
97
-		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
-	}
101
-
102
-	public function postDeleteUser($params) {
103
-		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
105
-			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106
-		}
107
-
108
-		foreach ($this->calendarsToDelete as $calendar) {
109
-			$this->calDav->deleteCalendar($calendar['id']);
110
-		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
-
113
-		foreach ($this->addressBooksToDelete as $addressBook) {
114
-			$this->cardDav->deleteAddressBook($addressBook['id']);
115
-		}
116
-	}
117
-
118
-	public function changeUser($params) {
119
-		$user = $params['user'];
120
-		$this->syncService->updateUser($user);
121
-	}
122
-
123
-	public function firstLogin(IUser $user = null) {
124
-		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
126
-			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
-				try {
128
-					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
-					]);
131
-				} catch (\Exception $ex) {
132
-					\OC::$server->getLogger()->logException($ex);
133
-				}
134
-			}
135
-			if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
-				try {
137
-					$this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
-						'{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
-					]);
140
-				} catch (\Exception $ex) {
141
-					\OC::$server->getLogger()->logException($ex);
142
-				}
143
-			}
144
-		}
145
-	}
35
+    /** @var IUserManager */
36
+    private $userManager;
37
+
38
+    /** @var SyncService */
39
+    private $syncService;
40
+
41
+    /** @var IUser[] */
42
+    private $usersToDelete;
43
+
44
+    /** @var CalDavBackend */
45
+    private $calDav;
46
+
47
+    /** @var CardDavBackend */
48
+    private $cardDav;
49
+
50
+    /** @var array */
51
+    private $calendarsToDelete;
52
+
53
+    /** @var array */
54
+    private $addressBooksToDelete;
55
+
56
+    /** @var EventDispatcher */
57
+    private $eventDispatcher;
58
+
59
+    public function __construct(IUserManager $userManager,
60
+                                SyncService $syncService,
61
+                                CalDavBackend $calDav,
62
+                                CardDavBackend $cardDav,
63
+                                EventDispatcher $eventDispatcher) {
64
+        $this->userManager = $userManager;
65
+        $this->syncService = $syncService;
66
+        $this->calDav = $calDav;
67
+        $this->cardDav = $cardDav;
68
+        $this->eventDispatcher = $eventDispatcher;
69
+    }
70
+
71
+    public function setup() {
72
+        Util::connectHook('OC_User',
73
+            'post_createUser',
74
+            $this,
75
+            'postCreateUser');
76
+        Util::connectHook('OC_User',
77
+            'pre_deleteUser',
78
+            $this,
79
+            'preDeleteUser');
80
+        Util::connectHook('OC_User',
81
+            'post_deleteUser',
82
+            $this,
83
+            'postDeleteUser');
84
+        Util::connectHook('OC_User',
85
+            'changeUser',
86
+            $this,
87
+            'changeUser');
88
+    }
89
+
90
+    public function postCreateUser($params) {
91
+        $user = $this->userManager->get($params['uid']);
92
+        $this->syncService->updateUser($user);
93
+    }
94
+
95
+    public function preDeleteUser($params) {
96
+        $uid = $params['uid'];
97
+        $this->usersToDelete[$uid] = $this->userManager->get($uid);
98
+        $this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
+        $this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
+    }
101
+
102
+    public function postDeleteUser($params) {
103
+        $uid = $params['uid'];
104
+        if (isset($this->usersToDelete[$uid])){
105
+            $this->syncService->deleteUser($this->usersToDelete[$uid]);
106
+        }
107
+
108
+        foreach ($this->calendarsToDelete as $calendar) {
109
+            $this->calDav->deleteCalendar($calendar['id']);
110
+        }
111
+        $this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
+
113
+        foreach ($this->addressBooksToDelete as $addressBook) {
114
+            $this->cardDav->deleteAddressBook($addressBook['id']);
115
+        }
116
+    }
117
+
118
+    public function changeUser($params) {
119
+        $user = $params['user'];
120
+        $this->syncService->updateUser($user);
121
+    }
122
+
123
+    public function firstLogin(IUser $user = null) {
124
+        if (!is_null($user)) {
125
+            $principal = 'principals/users/' . $user->getUID();
126
+            if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
+                try {
128
+                    $this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
+                    ]);
131
+                } catch (\Exception $ex) {
132
+                    \OC::$server->getLogger()->logException($ex);
133
+                }
134
+            }
135
+            if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
+                try {
137
+                    $this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
+                        '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
+                    ]);
140
+                } catch (\Exception $ex) {
141
+                    \OC::$server->getLogger()->logException($ex);
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,20 +95,20 @@  discard block
 block discarded – undo
95 95
 	public function preDeleteUser($params) {
96 96
 		$uid = $params['uid'];
97 97
 		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
98
+		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/'.$uid);
99
+		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/'.$uid);
100 100
 	}
101 101
 
102 102
 	public function postDeleteUser($params) {
103 103
 		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
104
+		if (isset($this->usersToDelete[$uid])) {
105 105
 			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106 106
 		}
107 107
 
108 108
 		foreach ($this->calendarsToDelete as $calendar) {
109 109
 			$this->calDav->deleteCalendar($calendar['id']);
110 110
 		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
111
+		$this->calDav->deleteAllSharesByUser('principals/users/'.$uid);
112 112
 
113 113
 		foreach ($this->addressBooksToDelete as $addressBook) {
114 114
 			$this->cardDav->deleteAddressBook($addressBook['id']);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 
123 123
 	public function firstLogin(IUser $user = null) {
124 124
 		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
125
+			$principal = 'principals/users/'.$user->getUID();
126 126
 			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127 127
 				try {
128 128
 					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
Please login to merge, or discard this patch.
apps/files_sharing/lib/Cache.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -110,6 +110,9 @@
 block discarded – undo
110 110
 		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
111 111
 	}
112 112
 
113
+	/**
114
+	 * @param ICacheEntry $entry
115
+	 */
113 116
 	protected function formatCacheEntry($entry) {
114 117
 		$path = isset($entry['path']) ? $entry['path'] : '';
115 118
 		$entry = parent::formatCacheEntry($entry);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@
 block discarded – undo
29 29
 
30 30
 use OC\Files\Cache\Wrapper\CacheJail;
31 31
 use OCP\Files\Cache\ICacheEntry;
32
-use OCP\Files\Storage\IStorage;
33 32
 
34 33
 /**
35 34
  * Metadata cache for shared files
Please login to merge, or discard this patch.
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -37,103 +37,103 @@
 block discarded – undo
37 37
  * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
38 38
  */
39 39
 class Cache extends CacheJail {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage
42
-	 */
43
-	private $storage;
44
-
45
-	/**
46
-	 * @var ICacheEntry
47
-	 */
48
-	private $sourceRootInfo;
49
-
50
-	private $rootUnchanged = true;
51
-
52
-	private $ownerDisplayName;
53
-
54
-	/**
55
-	 * @param \OCA\Files_Sharing\SharedStorage $storage
56
-	 * @param ICacheEntry $sourceRootInfo
57
-	 */
58
-	public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
-		$this->storage = $storage;
60
-		$this->sourceRootInfo = $sourceRootInfo;
61
-		parent::__construct(
62
-			null,
63
-			$this->sourceRootInfo->getPath()
64
-		);
65
-	}
66
-
67
-	public function getCache() {
68
-		if (is_null($this->cache)) {
69
-			$this->cache = $this->storage->getSourceStorage()->getCache();
70
-		}
71
-		return $this->cache;
72
-	}
73
-
74
-	public function getNumericStorageId() {
75
-		if (isset($this->numericId)) {
76
-			return $this->numericId;
77
-		} else {
78
-			return false;
79
-		}
80
-	}
81
-
82
-	public function get($file) {
83
-		if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
-			return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
-		}
86
-		return parent::get($file);
87
-	}
88
-
89
-	public function update($id, array $data) {
90
-		$this->rootUnchanged = false;
91
-		parent::update($id, $data);
92
-	}
93
-
94
-	public function insert($file, array $data) {
95
-		$this->rootUnchanged = false;
96
-		return parent::insert($file, $data);
97
-	}
98
-
99
-	public function remove($file) {
100
-		$this->rootUnchanged = false;
101
-		parent::remove($file);
102
-	}
103
-
104
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
-		$this->rootUnchanged = false;
106
-		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
-	}
108
-
109
-	protected function formatCacheEntry($entry) {
110
-		$path = isset($entry['path']) ? $entry['path'] : '';
111
-		$entry = parent::formatCacheEntry($entry);
112
-		$sharePermissions = $this->storage->getPermissions($path);
113
-		if (isset($entry['permissions'])) {
114
-			$entry['permissions'] &= $sharePermissions;
115
-		} else {
116
-			$entry['permissions'] = $sharePermissions;
117
-		}
118
-		$entry['uid_owner'] = $this->storage->getOwner($path);
119
-		$entry['displayname_owner'] = $this->getOwnerDisplayName();
120
-		if ($path === '') {
121
-			$entry['is_share_mount_point'] = true;
122
-		}
123
-		return $entry;
124
-	}
125
-
126
-	private function getOwnerDisplayName() {
127
-		if (!$this->ownerDisplayName) {
128
-			$this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
-		}
130
-		return $this->ownerDisplayName;
131
-	}
132
-
133
-	/**
134
-	 * remove all entries for files that are stored on the storage from the cache
135
-	 */
136
-	public function clear() {
137
-		// Not a valid action for Shared Cache
138
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage
42
+     */
43
+    private $storage;
44
+
45
+    /**
46
+     * @var ICacheEntry
47
+     */
48
+    private $sourceRootInfo;
49
+
50
+    private $rootUnchanged = true;
51
+
52
+    private $ownerDisplayName;
53
+
54
+    /**
55
+     * @param \OCA\Files_Sharing\SharedStorage $storage
56
+     * @param ICacheEntry $sourceRootInfo
57
+     */
58
+    public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
+        $this->storage = $storage;
60
+        $this->sourceRootInfo = $sourceRootInfo;
61
+        parent::__construct(
62
+            null,
63
+            $this->sourceRootInfo->getPath()
64
+        );
65
+    }
66
+
67
+    public function getCache() {
68
+        if (is_null($this->cache)) {
69
+            $this->cache = $this->storage->getSourceStorage()->getCache();
70
+        }
71
+        return $this->cache;
72
+    }
73
+
74
+    public function getNumericStorageId() {
75
+        if (isset($this->numericId)) {
76
+            return $this->numericId;
77
+        } else {
78
+            return false;
79
+        }
80
+    }
81
+
82
+    public function get($file) {
83
+        if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
+            return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
+        }
86
+        return parent::get($file);
87
+    }
88
+
89
+    public function update($id, array $data) {
90
+        $this->rootUnchanged = false;
91
+        parent::update($id, $data);
92
+    }
93
+
94
+    public function insert($file, array $data) {
95
+        $this->rootUnchanged = false;
96
+        return parent::insert($file, $data);
97
+    }
98
+
99
+    public function remove($file) {
100
+        $this->rootUnchanged = false;
101
+        parent::remove($file);
102
+    }
103
+
104
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
+        $this->rootUnchanged = false;
106
+        return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
+    }
108
+
109
+    protected function formatCacheEntry($entry) {
110
+        $path = isset($entry['path']) ? $entry['path'] : '';
111
+        $entry = parent::formatCacheEntry($entry);
112
+        $sharePermissions = $this->storage->getPermissions($path);
113
+        if (isset($entry['permissions'])) {
114
+            $entry['permissions'] &= $sharePermissions;
115
+        } else {
116
+            $entry['permissions'] = $sharePermissions;
117
+        }
118
+        $entry['uid_owner'] = $this->storage->getOwner($path);
119
+        $entry['displayname_owner'] = $this->getOwnerDisplayName();
120
+        if ($path === '') {
121
+            $entry['is_share_mount_point'] = true;
122
+        }
123
+        return $entry;
124
+    }
125
+
126
+    private function getOwnerDisplayName() {
127
+        if (!$this->ownerDisplayName) {
128
+            $this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
+        }
130
+        return $this->ownerDisplayName;
131
+    }
132
+
133
+    /**
134
+     * remove all entries for files that are stored on the storage from the cache
135
+     */
136
+    public function clear() {
137
+        // Not a valid action for Shared Cache
138
+    }
139 139
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +9 added lines, -3 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 *
159 159
 	 * By default this excludes the automatically generated birthday calendar
160 160
 	 *
161
-	 * @param $principalUri
161
+	 * @param string $principalUri
162 162
 	 * @param bool $excludeBirthday
163 163
 	 * @return int
164 164
 	 */
@@ -304,6 +304,9 @@  discard block
 block discarded – undo
304 304
 		return array_values($calendars);
305 305
 	}
306 306
 
307
+	/**
308
+	 * @param string $principalUri
309
+	 */
307 310
 	public function getUsersOwnCalendars($principalUri) {
308 311
 		$principalUri = $this->convertPrincipal($principalUri, true);
309 312
 		$fields = array_values($this->propertyMap);
@@ -878,7 +881,7 @@  discard block
 block discarded – undo
878 881
 	 * calendar-data. If the result of a subsequent GET to this object is not
879 882
 	 * the exact same as this request body, you should omit the ETag.
880 883
 	 *
881
-	 * @param mixed $calendarId
884
+	 * @param integer $calendarId
882 885
 	 * @param string $objectUri
883 886
 	 * @param string $calendarData
884 887
 	 * @return string
@@ -1370,7 +1373,7 @@  discard block
 block discarded – undo
1370 1373
 	 * @param string $principalUri
1371 1374
 	 * @param string $uri
1372 1375
 	 * @param array $properties
1373
-	 * @return mixed
1376
+	 * @return integer
1374 1377
 	 */
1375 1378
 	function createSubscription($principalUri, $uri, array $properties) {
1376 1379
 
@@ -1783,6 +1786,9 @@  discard block
 block discarded – undo
1783 1786
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1784 1787
 	}
1785 1788
 
1789
+	/**
1790
+	 * @param boolean $toV2
1791
+	 */
1786 1792
 	private function convertPrincipal($principalUri, $toV2) {
1787 1793
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1788 1794
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Indentation   +1751 added lines, -1751 removed lines patch added patch discarded remove patch
@@ -59,1756 +59,1756 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			if (!isset($calendars[$calendar['id']])) {
252
-				$calendars[$calendar['id']] = $calendar;
253
-			}
254
-		}
255
-
256
-		$stmt->closeCursor();
257
-
258
-		// query for shared calendars
259
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
261
-
262
-		$fields = array_values($this->propertyMap);
263
-		$fields[] = 'a.id';
264
-		$fields[] = 'a.uri';
265
-		$fields[] = 'a.synctoken';
266
-		$fields[] = 'a.components';
267
-		$fields[] = 'a.principaluri';
268
-		$fields[] = 'a.transparent';
269
-		$fields[] = 's.access';
270
-		$query = $this->db->getQueryBuilder();
271
-		$result = $query->select($fields)
272
-			->from('dav_shares', 's')
273
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
-			->setParameter('type', 'calendar')
277
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
-			->execute();
279
-
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
282
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283
-			if (isset($calendars[$row['id']])) {
284
-				if ($readOnly) {
285
-					// New share can not have more permissions then the old one.
286
-					continue;
287
-				}
288
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
289
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
290
-					// Old share is already read-write, no more permissions can be gained
291
-					continue;
292
-				}
293
-			}
294
-
295
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
296
-			$uri = $row['uri'] . '_shared_by_' . $name;
297
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
298
-			$components = [];
299
-			if ($row['components']) {
300
-				$components = explode(',',$row['components']);
301
-			}
302
-			$calendar = [
303
-				'id' => $row['id'],
304
-				'uri' => $uri,
305
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311
-				$readOnlyPropertyName => $readOnly,
312
-			];
313
-
314
-			foreach($this->propertyMap as $xmlName=>$dbName) {
315
-				$calendar[$xmlName] = $row[$dbName];
316
-			}
317
-
318
-			$calendars[$calendar['id']] = $calendar;
319
-		}
320
-		$result->closeCursor();
321
-
322
-		return array_values($calendars);
323
-	}
324
-
325
-	public function getUsersOwnCalendars($principalUri) {
326
-		$principalUri = $this->convertPrincipal($principalUri, true);
327
-		$fields = array_values($this->propertyMap);
328
-		$fields[] = 'id';
329
-		$fields[] = 'uri';
330
-		$fields[] = 'synctoken';
331
-		$fields[] = 'components';
332
-		$fields[] = 'principaluri';
333
-		$fields[] = 'transparent';
334
-		// Making fields a comma-delimited list
335
-		$query = $this->db->getQueryBuilder();
336
-		$query->select($fields)->from('calendars')
337
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
338
-			->orderBy('calendarorder', 'ASC');
339
-		$stmt = $query->execute();
340
-		$calendars = [];
341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342
-			$components = [];
343
-			if ($row['components']) {
344
-				$components = explode(',',$row['components']);
345
-			}
346
-			$calendar = [
347
-				'id' => $row['id'],
348
-				'uri' => $row['uri'],
349
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
-			];
355
-			foreach($this->propertyMap as $xmlName=>$dbName) {
356
-				$calendar[$xmlName] = $row[$dbName];
357
-			}
358
-			if (!isset($calendars[$calendar['id']])) {
359
-				$calendars[$calendar['id']] = $calendar;
360
-			}
361
-		}
362
-		$stmt->closeCursor();
363
-		return array_values($calendars);
364
-	}
365
-
366
-
367
-	private function getUserDisplayName($uid) {
368
-		if (!isset($this->userDisplayNames[$uid])) {
369
-			$user = $this->userManager->get($uid);
370
-
371
-			if ($user instanceof IUser) {
372
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
373
-			} else {
374
-				$this->userDisplayNames[$uid] = $uid;
375
-			}
376
-		}
377
-
378
-		return $this->userDisplayNames[$uid];
379
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            if (!isset($calendars[$calendar['id']])) {
252
+                $calendars[$calendar['id']] = $calendar;
253
+            }
254
+        }
255
+
256
+        $stmt->closeCursor();
257
+
258
+        // query for shared calendars
259
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
+        $principals[]= $principalUri;
261
+
262
+        $fields = array_values($this->propertyMap);
263
+        $fields[] = 'a.id';
264
+        $fields[] = 'a.uri';
265
+        $fields[] = 'a.synctoken';
266
+        $fields[] = 'a.components';
267
+        $fields[] = 'a.principaluri';
268
+        $fields[] = 'a.transparent';
269
+        $fields[] = 's.access';
270
+        $query = $this->db->getQueryBuilder();
271
+        $result = $query->select($fields)
272
+            ->from('dav_shares', 's')
273
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
+            ->setParameter('type', 'calendar')
277
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
+            ->execute();
279
+
280
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
+        while($row = $result->fetch()) {
282
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283
+            if (isset($calendars[$row['id']])) {
284
+                if ($readOnly) {
285
+                    // New share can not have more permissions then the old one.
286
+                    continue;
287
+                }
288
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
289
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
290
+                    // Old share is already read-write, no more permissions can be gained
291
+                    continue;
292
+                }
293
+            }
294
+
295
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
296
+            $uri = $row['uri'] . '_shared_by_' . $name;
297
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
298
+            $components = [];
299
+            if ($row['components']) {
300
+                $components = explode(',',$row['components']);
301
+            }
302
+            $calendar = [
303
+                'id' => $row['id'],
304
+                'uri' => $uri,
305
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311
+                $readOnlyPropertyName => $readOnly,
312
+            ];
313
+
314
+            foreach($this->propertyMap as $xmlName=>$dbName) {
315
+                $calendar[$xmlName] = $row[$dbName];
316
+            }
317
+
318
+            $calendars[$calendar['id']] = $calendar;
319
+        }
320
+        $result->closeCursor();
321
+
322
+        return array_values($calendars);
323
+    }
324
+
325
+    public function getUsersOwnCalendars($principalUri) {
326
+        $principalUri = $this->convertPrincipal($principalUri, true);
327
+        $fields = array_values($this->propertyMap);
328
+        $fields[] = 'id';
329
+        $fields[] = 'uri';
330
+        $fields[] = 'synctoken';
331
+        $fields[] = 'components';
332
+        $fields[] = 'principaluri';
333
+        $fields[] = 'transparent';
334
+        // Making fields a comma-delimited list
335
+        $query = $this->db->getQueryBuilder();
336
+        $query->select($fields)->from('calendars')
337
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
338
+            ->orderBy('calendarorder', 'ASC');
339
+        $stmt = $query->execute();
340
+        $calendars = [];
341
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342
+            $components = [];
343
+            if ($row['components']) {
344
+                $components = explode(',',$row['components']);
345
+            }
346
+            $calendar = [
347
+                'id' => $row['id'],
348
+                'uri' => $row['uri'],
349
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
+            ];
355
+            foreach($this->propertyMap as $xmlName=>$dbName) {
356
+                $calendar[$xmlName] = $row[$dbName];
357
+            }
358
+            if (!isset($calendars[$calendar['id']])) {
359
+                $calendars[$calendar['id']] = $calendar;
360
+            }
361
+        }
362
+        $stmt->closeCursor();
363
+        return array_values($calendars);
364
+    }
365
+
366
+
367
+    private function getUserDisplayName($uid) {
368
+        if (!isset($this->userDisplayNames[$uid])) {
369
+            $user = $this->userManager->get($uid);
370
+
371
+            if ($user instanceof IUser) {
372
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
373
+            } else {
374
+                $this->userDisplayNames[$uid] = $uid;
375
+            }
376
+        }
377
+
378
+        return $this->userDisplayNames[$uid];
379
+    }
380 380
 	
381
-	/**
382
-	 * @return array
383
-	 */
384
-	public function getPublicCalendars() {
385
-		$fields = array_values($this->propertyMap);
386
-		$fields[] = 'a.id';
387
-		$fields[] = 'a.uri';
388
-		$fields[] = 'a.synctoken';
389
-		$fields[] = 'a.components';
390
-		$fields[] = 'a.principaluri';
391
-		$fields[] = 'a.transparent';
392
-		$fields[] = 's.access';
393
-		$fields[] = 's.publicuri';
394
-		$calendars = [];
395
-		$query = $this->db->getQueryBuilder();
396
-		$result = $query->select($fields)
397
-			->from('dav_shares', 's')
398
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
399
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
400
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401
-			->execute();
402
-
403
-		while($row = $result->fetch()) {
404
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
405
-			$row['displayname'] = $row['displayname'] . "($name)";
406
-			$components = [];
407
-			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
409
-			}
410
-			$calendar = [
411
-				'id' => $row['id'],
412
-				'uri' => $row['publicuri'],
413
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
421
-			];
422
-
423
-			foreach($this->propertyMap as $xmlName=>$dbName) {
424
-				$calendar[$xmlName] = $row[$dbName];
425
-			}
426
-
427
-			if (!isset($calendars[$calendar['id']])) {
428
-				$calendars[$calendar['id']] = $calendar;
429
-			}
430
-		}
431
-		$result->closeCursor();
432
-
433
-		return array_values($calendars);
434
-	}
435
-
436
-	/**
437
-	 * @param string $uri
438
-	 * @return array
439
-	 * @throws NotFound
440
-	 */
441
-	public function getPublicCalendar($uri) {
442
-		$fields = array_values($this->propertyMap);
443
-		$fields[] = 'a.id';
444
-		$fields[] = 'a.uri';
445
-		$fields[] = 'a.synctoken';
446
-		$fields[] = 'a.components';
447
-		$fields[] = 'a.principaluri';
448
-		$fields[] = 'a.transparent';
449
-		$fields[] = 's.access';
450
-		$fields[] = 's.publicuri';
451
-		$query = $this->db->getQueryBuilder();
452
-		$result = $query->select($fields)
453
-			->from('dav_shares', 's')
454
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
455
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
456
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
457
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
458
-			->execute();
459
-
460
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
461
-
462
-		$result->closeCursor();
463
-
464
-		if ($row === false) {
465
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
466
-		}
467
-
468
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
469
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
470
-		$components = [];
471
-		if ($row['components']) {
472
-			$components = explode(',',$row['components']);
473
-		}
474
-		$calendar = [
475
-			'id' => $row['id'],
476
-			'uri' => $row['publicuri'],
477
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
-		];
486
-
487
-		foreach($this->propertyMap as $xmlName=>$dbName) {
488
-			$calendar[$xmlName] = $row[$dbName];
489
-		}
490
-
491
-		return $calendar;
492
-
493
-	}
494
-
495
-	/**
496
-	 * @param string $principal
497
-	 * @param string $uri
498
-	 * @return array|null
499
-	 */
500
-	public function getCalendarByUri($principal, $uri) {
501
-		$fields = array_values($this->propertyMap);
502
-		$fields[] = 'id';
503
-		$fields[] = 'uri';
504
-		$fields[] = 'synctoken';
505
-		$fields[] = 'components';
506
-		$fields[] = 'principaluri';
507
-		$fields[] = 'transparent';
508
-
509
-		// Making fields a comma-delimited list
510
-		$query = $this->db->getQueryBuilder();
511
-		$query->select($fields)->from('calendars')
512
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
513
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
514
-			->setMaxResults(1);
515
-		$stmt = $query->execute();
516
-
517
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
518
-		$stmt->closeCursor();
519
-		if ($row === false) {
520
-			return null;
521
-		}
522
-
523
-		$components = [];
524
-		if ($row['components']) {
525
-			$components = explode(',',$row['components']);
526
-		}
527
-
528
-		$calendar = [
529
-			'id' => $row['id'],
530
-			'uri' => $row['uri'],
531
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
-		];
537
-
538
-		foreach($this->propertyMap as $xmlName=>$dbName) {
539
-			$calendar[$xmlName] = $row[$dbName];
540
-		}
541
-
542
-		return $calendar;
543
-	}
544
-
545
-	public function getCalendarById($calendarId) {
546
-		$fields = array_values($this->propertyMap);
547
-		$fields[] = 'id';
548
-		$fields[] = 'uri';
549
-		$fields[] = 'synctoken';
550
-		$fields[] = 'components';
551
-		$fields[] = 'principaluri';
552
-		$fields[] = 'transparent';
553
-
554
-		// Making fields a comma-delimited list
555
-		$query = $this->db->getQueryBuilder();
556
-		$query->select($fields)->from('calendars')
557
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
558
-			->setMaxResults(1);
559
-		$stmt = $query->execute();
560
-
561
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
562
-		$stmt->closeCursor();
563
-		if ($row === false) {
564
-			return null;
565
-		}
566
-
567
-		$components = [];
568
-		if ($row['components']) {
569
-			$components = explode(',',$row['components']);
570
-		}
571
-
572
-		$calendar = [
573
-			'id' => $row['id'],
574
-			'uri' => $row['uri'],
575
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
-		];
581
-
582
-		foreach($this->propertyMap as $xmlName=>$dbName) {
583
-			$calendar[$xmlName] = $row[$dbName];
584
-		}
585
-
586
-		return $calendar;
587
-	}
588
-
589
-	/**
590
-	 * Creates a new calendar for a principal.
591
-	 *
592
-	 * If the creation was a success, an id must be returned that can be used to reference
593
-	 * this calendar in other methods, such as updateCalendar.
594
-	 *
595
-	 * @param string $principalUri
596
-	 * @param string $calendarUri
597
-	 * @param array $properties
598
-	 * @return int
599
-	 */
600
-	function createCalendar($principalUri, $calendarUri, array $properties) {
601
-		$values = [
602
-			'principaluri' => $this->convertPrincipal($principalUri, true),
603
-			'uri'          => $calendarUri,
604
-			'synctoken'    => 1,
605
-			'transparent'  => 0,
606
-			'components'   => 'VEVENT,VTODO',
607
-			'displayname'  => $calendarUri
608
-		];
609
-
610
-		// Default value
611
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612
-		if (isset($properties[$sccs])) {
613
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615
-			}
616
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
617
-		}
618
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
619
-		if (isset($properties[$transp])) {
620
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
621
-		}
622
-
623
-		foreach($this->propertyMap as $xmlName=>$dbName) {
624
-			if (isset($properties[$xmlName])) {
625
-				$values[$dbName] = $properties[$xmlName];
626
-			}
627
-		}
628
-
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->insert('calendars');
631
-		foreach($values as $column => $value) {
632
-			$query->setValue($column, $query->createNamedParameter($value));
633
-		}
634
-		$query->execute();
635
-		$calendarId = $query->getLastInsertId();
636
-
637
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
638
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
639
-			[
640
-				'calendarId' => $calendarId,
641
-				'calendarData' => $this->getCalendarById($calendarId),
642
-		]));
643
-
644
-		return $calendarId;
645
-	}
646
-
647
-	/**
648
-	 * Updates properties for a calendar.
649
-	 *
650
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
651
-	 * To do the actual updates, you must tell this object which properties
652
-	 * you're going to process with the handle() method.
653
-	 *
654
-	 * Calling the handle method is like telling the PropPatch object "I
655
-	 * promise I can handle updating this property".
656
-	 *
657
-	 * Read the PropPatch documentation for more info and examples.
658
-	 *
659
-	 * @param PropPatch $propPatch
660
-	 * @return void
661
-	 */
662
-	function updateCalendar($calendarId, PropPatch $propPatch) {
663
-		$supportedProperties = array_keys($this->propertyMap);
664
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
665
-
666
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667
-			$newValues = [];
668
-			foreach ($mutations as $propertyName => $propertyValue) {
669
-
670
-				switch ($propertyName) {
671
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
672
-						$fieldName = 'transparent';
673
-						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674
-						break;
675
-					default :
676
-						$fieldName = $this->propertyMap[$propertyName];
677
-						$newValues[$fieldName] = $propertyValue;
678
-						break;
679
-				}
680
-
681
-			}
682
-			$query = $this->db->getQueryBuilder();
683
-			$query->update('calendars');
684
-			foreach ($newValues as $fieldName => $value) {
685
-				$query->set($fieldName, $query->createNamedParameter($value));
686
-			}
687
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
688
-			$query->execute();
689
-
690
-			$this->addChange($calendarId, "", 2);
691
-
692
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
693
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
694
-				[
695
-					'calendarId' => $calendarId,
696
-					'calendarData' => $this->getCalendarById($calendarId),
697
-					'shares' => $this->getShares($calendarId),
698
-					'propertyMutations' => $mutations,
699
-			]));
700
-
701
-			return true;
702
-		});
703
-	}
704
-
705
-	/**
706
-	 * Delete a calendar and all it's objects
707
-	 *
708
-	 * @param mixed $calendarId
709
-	 * @return void
710
-	 */
711
-	function deleteCalendar($calendarId) {
712
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
713
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
714
-			[
715
-				'calendarId' => $calendarId,
716
-				'calendarData' => $this->getCalendarById($calendarId),
717
-				'shares' => $this->getShares($calendarId),
718
-		]));
719
-
720
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
721
-		$stmt->execute([$calendarId]);
722
-
723
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
724
-		$stmt->execute([$calendarId]);
725
-
726
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
727
-		$stmt->execute([$calendarId]);
728
-
729
-		$this->sharingBackend->deleteAllShares($calendarId);
730
-	}
731
-
732
-	/**
733
-	 * Delete all of an user's shares
734
-	 *
735
-	 * @param string $principaluri
736
-	 * @return void
737
-	 */
738
-	function deleteAllSharesByUser($principaluri) {
739
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
740
-	}
741
-
742
-	/**
743
-	 * Returns all calendar objects within a calendar.
744
-	 *
745
-	 * Every item contains an array with the following keys:
746
-	 *   * calendardata - The iCalendar-compatible calendar data
747
-	 *   * uri - a unique key which will be used to construct the uri. This can
748
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
749
-	 *     good idea. This is only the basename, or filename, not the full
750
-	 *     path.
751
-	 *   * lastmodified - a timestamp of the last modification time
752
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
753
-	 *   '"abcdef"')
754
-	 *   * size - The size of the calendar objects, in bytes.
755
-	 *   * component - optional, a string containing the type of object, such
756
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
757
-	 *     the Content-Type header.
758
-	 *
759
-	 * Note that the etag is optional, but it's highly encouraged to return for
760
-	 * speed reasons.
761
-	 *
762
-	 * The calendardata is also optional. If it's not returned
763
-	 * 'getCalendarObject' will be called later, which *is* expected to return
764
-	 * calendardata.
765
-	 *
766
-	 * If neither etag or size are specified, the calendardata will be
767
-	 * used/fetched to determine these numbers. If both are specified the
768
-	 * amount of times this is needed is reduced by a great degree.
769
-	 *
770
-	 * @param mixed $calendarId
771
-	 * @return array
772
-	 */
773
-	function getCalendarObjects($calendarId) {
774
-		$query = $this->db->getQueryBuilder();
775
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
776
-			->from('calendarobjects')
777
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
778
-		$stmt = $query->execute();
779
-
780
-		$result = [];
781
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782
-			$result[] = [
783
-					'id'           => $row['id'],
784
-					'uri'          => $row['uri'],
785
-					'lastmodified' => $row['lastmodified'],
786
-					'etag'         => '"' . $row['etag'] . '"',
787
-					'calendarid'   => $row['calendarid'],
788
-					'size'         => (int)$row['size'],
789
-					'component'    => strtolower($row['componenttype']),
790
-					'classification'=> (int)$row['classification']
791
-			];
792
-		}
793
-
794
-		return $result;
795
-	}
796
-
797
-	/**
798
-	 * Returns information from a single calendar object, based on it's object
799
-	 * uri.
800
-	 *
801
-	 * The object uri is only the basename, or filename and not a full path.
802
-	 *
803
-	 * The returned array must have the same keys as getCalendarObjects. The
804
-	 * 'calendardata' object is required here though, while it's not required
805
-	 * for getCalendarObjects.
806
-	 *
807
-	 * This method must return null if the object did not exist.
808
-	 *
809
-	 * @param mixed $calendarId
810
-	 * @param string $objectUri
811
-	 * @return array|null
812
-	 */
813
-	function getCalendarObject($calendarId, $objectUri) {
814
-
815
-		$query = $this->db->getQueryBuilder();
816
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
817
-				->from('calendarobjects')
818
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
819
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
820
-		$stmt = $query->execute();
821
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
822
-
823
-		if(!$row) return null;
824
-
825
-		return [
826
-				'id'            => $row['id'],
827
-				'uri'           => $row['uri'],
828
-				'lastmodified'  => $row['lastmodified'],
829
-				'etag'          => '"' . $row['etag'] . '"',
830
-				'calendarid'    => $row['calendarid'],
831
-				'size'          => (int)$row['size'],
832
-				'calendardata'  => $this->readBlob($row['calendardata']),
833
-				'component'     => strtolower($row['componenttype']),
834
-				'classification'=> (int)$row['classification']
835
-		];
836
-	}
837
-
838
-	/**
839
-	 * Returns a list of calendar objects.
840
-	 *
841
-	 * This method should work identical to getCalendarObject, but instead
842
-	 * return all the calendar objects in the list as an array.
843
-	 *
844
-	 * If the backend supports this, it may allow for some speed-ups.
845
-	 *
846
-	 * @param mixed $calendarId
847
-	 * @param string[] $uris
848
-	 * @return array
849
-	 */
850
-	function getMultipleCalendarObjects($calendarId, array $uris) {
851
-		if (empty($uris)) {
852
-			return [];
853
-		}
854
-
855
-		$chunks = array_chunk($uris, 100);
856
-		$objects = [];
857
-
858
-		$query = $this->db->getQueryBuilder();
859
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
860
-			->from('calendarobjects')
861
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
862
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
863
-
864
-		foreach ($chunks as $uris) {
865
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
866
-			$result = $query->execute();
867
-
868
-			while ($row = $result->fetch()) {
869
-				$objects[] = [
870
-					'id'           => $row['id'],
871
-					'uri'          => $row['uri'],
872
-					'lastmodified' => $row['lastmodified'],
873
-					'etag'         => '"' . $row['etag'] . '"',
874
-					'calendarid'   => $row['calendarid'],
875
-					'size'         => (int)$row['size'],
876
-					'calendardata' => $this->readBlob($row['calendardata']),
877
-					'component'    => strtolower($row['componenttype']),
878
-					'classification' => (int)$row['classification']
879
-				];
880
-			}
881
-			$result->closeCursor();
882
-		}
883
-		return $objects;
884
-	}
885
-
886
-	/**
887
-	 * Creates a new calendar object.
888
-	 *
889
-	 * The object uri is only the basename, or filename and not a full path.
890
-	 *
891
-	 * It is possible return an etag from this function, which will be used in
892
-	 * the response to this PUT request. Note that the ETag must be surrounded
893
-	 * by double-quotes.
894
-	 *
895
-	 * However, you should only really return this ETag if you don't mangle the
896
-	 * calendar-data. If the result of a subsequent GET to this object is not
897
-	 * the exact same as this request body, you should omit the ETag.
898
-	 *
899
-	 * @param mixed $calendarId
900
-	 * @param string $objectUri
901
-	 * @param string $calendarData
902
-	 * @return string
903
-	 */
904
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
905
-		$extraData = $this->getDenormalizedData($calendarData);
906
-
907
-		$query = $this->db->getQueryBuilder();
908
-		$query->insert('calendarobjects')
909
-			->values([
910
-				'calendarid' => $query->createNamedParameter($calendarId),
911
-				'uri' => $query->createNamedParameter($objectUri),
912
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
913
-				'lastmodified' => $query->createNamedParameter(time()),
914
-				'etag' => $query->createNamedParameter($extraData['etag']),
915
-				'size' => $query->createNamedParameter($extraData['size']),
916
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
917
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
918
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
919
-				'classification' => $query->createNamedParameter($extraData['classification']),
920
-				'uid' => $query->createNamedParameter($extraData['uid']),
921
-			])
922
-			->execute();
923
-
924
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
925
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
926
-			[
927
-				'calendarId' => $calendarId,
928
-				'calendarData' => $this->getCalendarById($calendarId),
929
-				'shares' => $this->getShares($calendarId),
930
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
931
-			]
932
-		));
933
-		$this->addChange($calendarId, $objectUri, 1);
934
-
935
-		return '"' . $extraData['etag'] . '"';
936
-	}
937
-
938
-	/**
939
-	 * Updates an existing calendarobject, based on it's uri.
940
-	 *
941
-	 * The object uri is only the basename, or filename and not a full path.
942
-	 *
943
-	 * It is possible return an etag from this function, which will be used in
944
-	 * the response to this PUT request. Note that the ETag must be surrounded
945
-	 * by double-quotes.
946
-	 *
947
-	 * However, you should only really return this ETag if you don't mangle the
948
-	 * calendar-data. If the result of a subsequent GET to this object is not
949
-	 * the exact same as this request body, you should omit the ETag.
950
-	 *
951
-	 * @param mixed $calendarId
952
-	 * @param string $objectUri
953
-	 * @param string $calendarData
954
-	 * @return string
955
-	 */
956
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
957
-		$extraData = $this->getDenormalizedData($calendarData);
958
-
959
-		$query = $this->db->getQueryBuilder();
960
-		$query->update('calendarobjects')
961
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
962
-				->set('lastmodified', $query->createNamedParameter(time()))
963
-				->set('etag', $query->createNamedParameter($extraData['etag']))
964
-				->set('size', $query->createNamedParameter($extraData['size']))
965
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
966
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
967
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
968
-				->set('classification', $query->createNamedParameter($extraData['classification']))
969
-				->set('uid', $query->createNamedParameter($extraData['uid']))
970
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
971
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
972
-			->execute();
973
-
974
-		$data = $this->getCalendarObject($calendarId, $objectUri);
975
-		if (is_array($data)) {
976
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
977
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
978
-				[
979
-					'calendarId' => $calendarId,
980
-					'calendarData' => $this->getCalendarById($calendarId),
981
-					'shares' => $this->getShares($calendarId),
982
-					'objectData' => $data,
983
-				]
984
-			));
985
-		}
986
-		$this->addChange($calendarId, $objectUri, 2);
987
-
988
-		return '"' . $extraData['etag'] . '"';
989
-	}
990
-
991
-	/**
992
-	 * @param int $calendarObjectId
993
-	 * @param int $classification
994
-	 */
995
-	public function setClassification($calendarObjectId, $classification) {
996
-		if (!in_array($classification, [
997
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
998
-		])) {
999
-			throw new \InvalidArgumentException();
1000
-		}
1001
-		$query = $this->db->getQueryBuilder();
1002
-		$query->update('calendarobjects')
1003
-			->set('classification', $query->createNamedParameter($classification))
1004
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1005
-			->execute();
1006
-	}
1007
-
1008
-	/**
1009
-	 * Deletes an existing calendar object.
1010
-	 *
1011
-	 * The object uri is only the basename, or filename and not a full path.
1012
-	 *
1013
-	 * @param mixed $calendarId
1014
-	 * @param string $objectUri
1015
-	 * @return void
1016
-	 */
1017
-	function deleteCalendarObject($calendarId, $objectUri) {
1018
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1019
-		if (is_array($data)) {
1020
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1021
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1022
-				[
1023
-					'calendarId' => $calendarId,
1024
-					'calendarData' => $this->getCalendarById($calendarId),
1025
-					'shares' => $this->getShares($calendarId),
1026
-					'objectData' => $data,
1027
-				]
1028
-			));
1029
-		}
1030
-
1031
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1032
-		$stmt->execute([$calendarId, $objectUri]);
1033
-
1034
-		$this->addChange($calendarId, $objectUri, 3);
1035
-	}
1036
-
1037
-	/**
1038
-	 * Performs a calendar-query on the contents of this calendar.
1039
-	 *
1040
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1041
-	 * calendar-query it is possible for a client to request a specific set of
1042
-	 * object, based on contents of iCalendar properties, date-ranges and
1043
-	 * iCalendar component types (VTODO, VEVENT).
1044
-	 *
1045
-	 * This method should just return a list of (relative) urls that match this
1046
-	 * query.
1047
-	 *
1048
-	 * The list of filters are specified as an array. The exact array is
1049
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1050
-	 *
1051
-	 * Note that it is extremely likely that getCalendarObject for every path
1052
-	 * returned from this method will be called almost immediately after. You
1053
-	 * may want to anticipate this to speed up these requests.
1054
-	 *
1055
-	 * This method provides a default implementation, which parses *all* the
1056
-	 * iCalendar objects in the specified calendar.
1057
-	 *
1058
-	 * This default may well be good enough for personal use, and calendars
1059
-	 * that aren't very large. But if you anticipate high usage, big calendars
1060
-	 * or high loads, you are strongly advised to optimize certain paths.
1061
-	 *
1062
-	 * The best way to do so is override this method and to optimize
1063
-	 * specifically for 'common filters'.
1064
-	 *
1065
-	 * Requests that are extremely common are:
1066
-	 *   * requests for just VEVENTS
1067
-	 *   * requests for just VTODO
1068
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1069
-	 *
1070
-	 * ..and combinations of these requests. It may not be worth it to try to
1071
-	 * handle every possible situation and just rely on the (relatively
1072
-	 * easy to use) CalendarQueryValidator to handle the rest.
1073
-	 *
1074
-	 * Note that especially time-range-filters may be difficult to parse. A
1075
-	 * time-range filter specified on a VEVENT must for instance also handle
1076
-	 * recurrence rules correctly.
1077
-	 * A good example of how to interprete all these filters can also simply
1078
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1079
-	 * as possible, so it gives you a good idea on what type of stuff you need
1080
-	 * to think of.
1081
-	 *
1082
-	 * @param mixed $calendarId
1083
-	 * @param array $filters
1084
-	 * @return array
1085
-	 */
1086
-	function calendarQuery($calendarId, array $filters) {
1087
-		$componentType = null;
1088
-		$requirePostFilter = true;
1089
-		$timeRange = null;
1090
-
1091
-		// if no filters were specified, we don't need to filter after a query
1092
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1093
-			$requirePostFilter = false;
1094
-		}
1095
-
1096
-		// Figuring out if there's a component filter
1097
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1098
-			$componentType = $filters['comp-filters'][0]['name'];
1099
-
1100
-			// Checking if we need post-filters
1101
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1102
-				$requirePostFilter = false;
1103
-			}
1104
-			// There was a time-range filter
1105
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1106
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1107
-
1108
-				// If start time OR the end time is not specified, we can do a
1109
-				// 100% accurate mysql query.
1110
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1111
-					$requirePostFilter = false;
1112
-				}
1113
-			}
1114
-
1115
-		}
1116
-		$columns = ['uri'];
1117
-		if ($requirePostFilter) {
1118
-			$columns = ['uri', 'calendardata'];
1119
-		}
1120
-		$query = $this->db->getQueryBuilder();
1121
-		$query->select($columns)
1122
-			->from('calendarobjects')
1123
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1124
-
1125
-		if ($componentType) {
1126
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1127
-		}
1128
-
1129
-		if ($timeRange && $timeRange['start']) {
1130
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1131
-		}
1132
-		if ($timeRange && $timeRange['end']) {
1133
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1134
-		}
1135
-
1136
-		$stmt = $query->execute();
1137
-
1138
-		$result = [];
1139
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140
-			if ($requirePostFilter) {
1141
-				if (!$this->validateFilterForObject($row, $filters)) {
1142
-					continue;
1143
-				}
1144
-			}
1145
-			$result[] = $row['uri'];
1146
-		}
1147
-
1148
-		return $result;
1149
-	}
1150
-
1151
-	/**
1152
-	 * Searches through all of a users calendars and calendar objects to find
1153
-	 * an object with a specific UID.
1154
-	 *
1155
-	 * This method should return the path to this object, relative to the
1156
-	 * calendar home, so this path usually only contains two parts:
1157
-	 *
1158
-	 * calendarpath/objectpath.ics
1159
-	 *
1160
-	 * If the uid is not found, return null.
1161
-	 *
1162
-	 * This method should only consider * objects that the principal owns, so
1163
-	 * any calendars owned by other principals that also appear in this
1164
-	 * collection should be ignored.
1165
-	 *
1166
-	 * @param string $principalUri
1167
-	 * @param string $uid
1168
-	 * @return string|null
1169
-	 */
1170
-	function getCalendarObjectByUID($principalUri, $uid) {
1171
-
1172
-		$query = $this->db->getQueryBuilder();
1173
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1174
-			->from('calendarobjects', 'co')
1175
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1176
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1177
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1178
-
1179
-		$stmt = $query->execute();
1180
-
1181
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1183
-		}
1184
-
1185
-		return null;
1186
-	}
1187
-
1188
-	/**
1189
-	 * The getChanges method returns all the changes that have happened, since
1190
-	 * the specified syncToken in the specified calendar.
1191
-	 *
1192
-	 * This function should return an array, such as the following:
1193
-	 *
1194
-	 * [
1195
-	 *   'syncToken' => 'The current synctoken',
1196
-	 *   'added'   => [
1197
-	 *      'new.txt',
1198
-	 *   ],
1199
-	 *   'modified'   => [
1200
-	 *      'modified.txt',
1201
-	 *   ],
1202
-	 *   'deleted' => [
1203
-	 *      'foo.php.bak',
1204
-	 *      'old.txt'
1205
-	 *   ]
1206
-	 * );
1207
-	 *
1208
-	 * The returned syncToken property should reflect the *current* syncToken
1209
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1210
-	 * property This is * needed here too, to ensure the operation is atomic.
1211
-	 *
1212
-	 * If the $syncToken argument is specified as null, this is an initial
1213
-	 * sync, and all members should be reported.
1214
-	 *
1215
-	 * The modified property is an array of nodenames that have changed since
1216
-	 * the last token.
1217
-	 *
1218
-	 * The deleted property is an array with nodenames, that have been deleted
1219
-	 * from collection.
1220
-	 *
1221
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1222
-	 * 1, you only have to report changes that happened only directly in
1223
-	 * immediate descendants. If it's 2, it should also include changes from
1224
-	 * the nodes below the child collections. (grandchildren)
1225
-	 *
1226
-	 * The $limit argument allows a client to specify how many results should
1227
-	 * be returned at most. If the limit is not specified, it should be treated
1228
-	 * as infinite.
1229
-	 *
1230
-	 * If the limit (infinite or not) is higher than you're willing to return,
1231
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1232
-	 *
1233
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1234
-	 * return null.
1235
-	 *
1236
-	 * The limit is 'suggestive'. You are free to ignore it.
1237
-	 *
1238
-	 * @param string $calendarId
1239
-	 * @param string $syncToken
1240
-	 * @param int $syncLevel
1241
-	 * @param int $limit
1242
-	 * @return array
1243
-	 */
1244
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245
-		// Current synctoken
1246
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
-		$stmt->execute([ $calendarId ]);
1248
-		$currentToken = $stmt->fetchColumn(0);
1249
-
1250
-		if (is_null($currentToken)) {
1251
-			return null;
1252
-		}
1253
-
1254
-		$result = [
1255
-			'syncToken' => $currentToken,
1256
-			'added'     => [],
1257
-			'modified'  => [],
1258
-			'deleted'   => [],
1259
-		];
1260
-
1261
-		if ($syncToken) {
1262
-
1263
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
-			if ($limit>0) {
1265
-				$query.= " `LIMIT` " . (int)$limit;
1266
-			}
1267
-
1268
-			// Fetching all changes
1269
-			$stmt = $this->db->prepare($query);
1270
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1271
-
1272
-			$changes = [];
1273
-
1274
-			// This loop ensures that any duplicates are overwritten, only the
1275
-			// last change on a node is relevant.
1276
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277
-
1278
-				$changes[$row['uri']] = $row['operation'];
1279
-
1280
-			}
1281
-
1282
-			foreach($changes as $uri => $operation) {
1283
-
1284
-				switch($operation) {
1285
-					case 1 :
1286
-						$result['added'][] = $uri;
1287
-						break;
1288
-					case 2 :
1289
-						$result['modified'][] = $uri;
1290
-						break;
1291
-					case 3 :
1292
-						$result['deleted'][] = $uri;
1293
-						break;
1294
-				}
1295
-
1296
-			}
1297
-		} else {
1298
-			// No synctoken supplied, this is the initial sync.
1299
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1300
-			$stmt = $this->db->prepare($query);
1301
-			$stmt->execute([$calendarId]);
1302
-
1303
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1304
-		}
1305
-		return $result;
1306
-
1307
-	}
1308
-
1309
-	/**
1310
-	 * Returns a list of subscriptions for a principal.
1311
-	 *
1312
-	 * Every subscription is an array with the following keys:
1313
-	 *  * id, a unique id that will be used by other functions to modify the
1314
-	 *    subscription. This can be the same as the uri or a database key.
1315
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1316
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1317
-	 *    principalUri passed to this method.
1318
-	 *
1319
-	 * Furthermore, all the subscription info must be returned too:
1320
-	 *
1321
-	 * 1. {DAV:}displayname
1322
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1323
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1324
-	 *    should not be stripped).
1325
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1326
-	 *    should not be stripped).
1327
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1328
-	 *    attachments should not be stripped).
1329
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1330
-	 *     Sabre\DAV\Property\Href).
1331
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1332
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1333
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1334
-	 *    (should just be an instance of
1335
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1336
-	 *    default components).
1337
-	 *
1338
-	 * @param string $principalUri
1339
-	 * @return array
1340
-	 */
1341
-	function getSubscriptionsForUser($principalUri) {
1342
-		$fields = array_values($this->subscriptionPropertyMap);
1343
-		$fields[] = 'id';
1344
-		$fields[] = 'uri';
1345
-		$fields[] = 'source';
1346
-		$fields[] = 'principaluri';
1347
-		$fields[] = 'lastmodified';
1348
-
1349
-		$query = $this->db->getQueryBuilder();
1350
-		$query->select($fields)
1351
-			->from('calendarsubscriptions')
1352
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353
-			->orderBy('calendarorder', 'asc');
1354
-		$stmt =$query->execute();
1355
-
1356
-		$subscriptions = [];
1357
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358
-
1359
-			$subscription = [
1360
-				'id'           => $row['id'],
1361
-				'uri'          => $row['uri'],
1362
-				'principaluri' => $row['principaluri'],
1363
-				'source'       => $row['source'],
1364
-				'lastmodified' => $row['lastmodified'],
1365
-
1366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367
-			];
1368
-
1369
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370
-				if (!is_null($row[$dbName])) {
1371
-					$subscription[$xmlName] = $row[$dbName];
1372
-				}
1373
-			}
1374
-
1375
-			$subscriptions[] = $subscription;
1376
-
1377
-		}
1378
-
1379
-		return $subscriptions;
1380
-	}
1381
-
1382
-	/**
1383
-	 * Creates a new subscription for a principal.
1384
-	 *
1385
-	 * If the creation was a success, an id must be returned that can be used to reference
1386
-	 * this subscription in other methods, such as updateSubscription.
1387
-	 *
1388
-	 * @param string $principalUri
1389
-	 * @param string $uri
1390
-	 * @param array $properties
1391
-	 * @return mixed
1392
-	 */
1393
-	function createSubscription($principalUri, $uri, array $properties) {
1394
-
1395
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1396
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1397
-		}
1398
-
1399
-		$values = [
1400
-			'principaluri' => $principalUri,
1401
-			'uri'          => $uri,
1402
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1403
-			'lastmodified' => time(),
1404
-		];
1405
-
1406
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407
-
1408
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409
-			if (array_key_exists($xmlName, $properties)) {
1410
-					$values[$dbName] = $properties[$xmlName];
1411
-					if (in_array($dbName, $propertiesBoolean)) {
1412
-						$values[$dbName] = true;
1413
-				}
1414
-			}
1415
-		}
1416
-
1417
-		$valuesToInsert = array();
1418
-
1419
-		$query = $this->db->getQueryBuilder();
1420
-
1421
-		foreach (array_keys($values) as $name) {
1422
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1423
-		}
1424
-
1425
-		$query->insert('calendarsubscriptions')
1426
-			->values($valuesToInsert)
1427
-			->execute();
1428
-
1429
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1430
-	}
1431
-
1432
-	/**
1433
-	 * Updates a subscription
1434
-	 *
1435
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1436
-	 * To do the actual updates, you must tell this object which properties
1437
-	 * you're going to process with the handle() method.
1438
-	 *
1439
-	 * Calling the handle method is like telling the PropPatch object "I
1440
-	 * promise I can handle updating this property".
1441
-	 *
1442
-	 * Read the PropPatch documentation for more info and examples.
1443
-	 *
1444
-	 * @param mixed $subscriptionId
1445
-	 * @param PropPatch $propPatch
1446
-	 * @return void
1447
-	 */
1448
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1449
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1450
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1451
-
1452
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1453
-
1454
-			$newValues = [];
1455
-
1456
-			foreach($mutations as $propertyName=>$propertyValue) {
1457
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458
-					$newValues['source'] = $propertyValue->getHref();
1459
-				} else {
1460
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1461
-					$newValues[$fieldName] = $propertyValue;
1462
-				}
1463
-			}
1464
-
1465
-			$query = $this->db->getQueryBuilder();
1466
-			$query->update('calendarsubscriptions')
1467
-				->set('lastmodified', $query->createNamedParameter(time()));
1468
-			foreach($newValues as $fieldName=>$value) {
1469
-				$query->set($fieldName, $query->createNamedParameter($value));
1470
-			}
1471
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1472
-				->execute();
1473
-
1474
-			return true;
1475
-
1476
-		});
1477
-	}
1478
-
1479
-	/**
1480
-	 * Deletes a subscription.
1481
-	 *
1482
-	 * @param mixed $subscriptionId
1483
-	 * @return void
1484
-	 */
1485
-	function deleteSubscription($subscriptionId) {
1486
-		$query = $this->db->getQueryBuilder();
1487
-		$query->delete('calendarsubscriptions')
1488
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1489
-			->execute();
1490
-	}
1491
-
1492
-	/**
1493
-	 * Returns a single scheduling object for the inbox collection.
1494
-	 *
1495
-	 * The returned array should contain the following elements:
1496
-	 *   * uri - A unique basename for the object. This will be used to
1497
-	 *           construct a full uri.
1498
-	 *   * calendardata - The iCalendar object
1499
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1500
-	 *                    timestamp, or a PHP DateTime object.
1501
-	 *   * etag - A unique token that must change if the object changed.
1502
-	 *   * size - The size of the object, in bytes.
1503
-	 *
1504
-	 * @param string $principalUri
1505
-	 * @param string $objectUri
1506
-	 * @return array
1507
-	 */
1508
-	function getSchedulingObject($principalUri, $objectUri) {
1509
-		$query = $this->db->getQueryBuilder();
1510
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1511
-			->from('schedulingobjects')
1512
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1513
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1514
-			->execute();
1515
-
1516
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517
-
1518
-		if(!$row) {
1519
-			return null;
1520
-		}
1521
-
1522
-		return [
1523
-				'uri'          => $row['uri'],
1524
-				'calendardata' => $row['calendardata'],
1525
-				'lastmodified' => $row['lastmodified'],
1526
-				'etag'         => '"' . $row['etag'] . '"',
1527
-				'size'         => (int)$row['size'],
1528
-		];
1529
-	}
1530
-
1531
-	/**
1532
-	 * Returns all scheduling objects for the inbox collection.
1533
-	 *
1534
-	 * These objects should be returned as an array. Every item in the array
1535
-	 * should follow the same structure as returned from getSchedulingObject.
1536
-	 *
1537
-	 * The main difference is that 'calendardata' is optional.
1538
-	 *
1539
-	 * @param string $principalUri
1540
-	 * @return array
1541
-	 */
1542
-	function getSchedulingObjects($principalUri) {
1543
-		$query = $this->db->getQueryBuilder();
1544
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1545
-				->from('schedulingobjects')
1546
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1547
-				->execute();
1548
-
1549
-		$result = [];
1550
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551
-			$result[] = [
1552
-					'calendardata' => $row['calendardata'],
1553
-					'uri'          => $row['uri'],
1554
-					'lastmodified' => $row['lastmodified'],
1555
-					'etag'         => '"' . $row['etag'] . '"',
1556
-					'size'         => (int)$row['size'],
1557
-			];
1558
-		}
1559
-
1560
-		return $result;
1561
-	}
1562
-
1563
-	/**
1564
-	 * Deletes a scheduling object from the inbox collection.
1565
-	 *
1566
-	 * @param string $principalUri
1567
-	 * @param string $objectUri
1568
-	 * @return void
1569
-	 */
1570
-	function deleteSchedulingObject($principalUri, $objectUri) {
1571
-		$query = $this->db->getQueryBuilder();
1572
-		$query->delete('schedulingobjects')
1573
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1574
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1575
-				->execute();
1576
-	}
1577
-
1578
-	/**
1579
-	 * Creates a new scheduling object. This should land in a users' inbox.
1580
-	 *
1581
-	 * @param string $principalUri
1582
-	 * @param string $objectUri
1583
-	 * @param string $objectData
1584
-	 * @return void
1585
-	 */
1586
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1587
-		$query = $this->db->getQueryBuilder();
1588
-		$query->insert('schedulingobjects')
1589
-			->values([
1590
-				'principaluri' => $query->createNamedParameter($principalUri),
1591
-				'calendardata' => $query->createNamedParameter($objectData),
1592
-				'uri' => $query->createNamedParameter($objectUri),
1593
-				'lastmodified' => $query->createNamedParameter(time()),
1594
-				'etag' => $query->createNamedParameter(md5($objectData)),
1595
-				'size' => $query->createNamedParameter(strlen($objectData))
1596
-			])
1597
-			->execute();
1598
-	}
1599
-
1600
-	/**
1601
-	 * Adds a change record to the calendarchanges table.
1602
-	 *
1603
-	 * @param mixed $calendarId
1604
-	 * @param string $objectUri
1605
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1606
-	 * @return void
1607
-	 */
1608
-	protected function addChange($calendarId, $objectUri, $operation) {
1609
-
1610
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1611
-		$stmt->execute([
1612
-			$objectUri,
1613
-			$calendarId,
1614
-			$operation,
1615
-			$calendarId
1616
-		]);
1617
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1618
-		$stmt->execute([
1619
-			$calendarId
1620
-		]);
1621
-
1622
-	}
1623
-
1624
-	/**
1625
-	 * Parses some information from calendar objects, used for optimized
1626
-	 * calendar-queries.
1627
-	 *
1628
-	 * Returns an array with the following keys:
1629
-	 *   * etag - An md5 checksum of the object without the quotes.
1630
-	 *   * size - Size of the object in bytes
1631
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1632
-	 *   * firstOccurence
1633
-	 *   * lastOccurence
1634
-	 *   * uid - value of the UID property
1635
-	 *
1636
-	 * @param string $calendarData
1637
-	 * @return array
1638
-	 */
1639
-	public function getDenormalizedData($calendarData) {
1640
-
1641
-		$vObject = Reader::read($calendarData);
1642
-		$componentType = null;
1643
-		$component = null;
1644
-		$firstOccurrence = null;
1645
-		$lastOccurrence = null;
1646
-		$uid = null;
1647
-		$classification = self::CLASSIFICATION_PUBLIC;
1648
-		foreach($vObject->getComponents() as $component) {
1649
-			if ($component->name!=='VTIMEZONE') {
1650
-				$componentType = $component->name;
1651
-				$uid = (string)$component->UID;
1652
-				break;
1653
-			}
1654
-		}
1655
-		if (!$componentType) {
1656
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1657
-		}
1658
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1659
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1660
-			// Finding the last occurrence is a bit harder
1661
-			if (!isset($component->RRULE)) {
1662
-				if (isset($component->DTEND)) {
1663
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1664
-				} elseif (isset($component->DURATION)) {
1665
-					$endDate = clone $component->DTSTART->getDateTime();
1666
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1667
-					$lastOccurrence = $endDate->getTimeStamp();
1668
-				} elseif (!$component->DTSTART->hasTime()) {
1669
-					$endDate = clone $component->DTSTART->getDateTime();
1670
-					$endDate->modify('+1 day');
1671
-					$lastOccurrence = $endDate->getTimeStamp();
1672
-				} else {
1673
-					$lastOccurrence = $firstOccurrence;
1674
-				}
1675
-			} else {
1676
-				$it = new EventIterator($vObject, (string)$component->UID);
1677
-				$maxDate = new \DateTime(self::MAX_DATE);
1678
-				if ($it->isInfinite()) {
1679
-					$lastOccurrence = $maxDate->getTimestamp();
1680
-				} else {
1681
-					$end = $it->getDtEnd();
1682
-					while($it->valid() && $end < $maxDate) {
1683
-						$end = $it->getDtEnd();
1684
-						$it->next();
1685
-
1686
-					}
1687
-					$lastOccurrence = $end->getTimestamp();
1688
-				}
1689
-
1690
-			}
1691
-		}
1692
-
1693
-		if ($component->CLASS) {
1694
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1695
-			switch ($component->CLASS->getValue()) {
1696
-				case 'PUBLIC':
1697
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1698
-					break;
1699
-				case 'CONFIDENTIAL':
1700
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1701
-					break;
1702
-			}
1703
-		}
1704
-		return [
1705
-			'etag' => md5($calendarData),
1706
-			'size' => strlen($calendarData),
1707
-			'componentType' => $componentType,
1708
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1709
-			'lastOccurence'  => $lastOccurrence,
1710
-			'uid' => $uid,
1711
-			'classification' => $classification
1712
-		];
1713
-
1714
-	}
1715
-
1716
-	private function readBlob($cardData) {
1717
-		if (is_resource($cardData)) {
1718
-			return stream_get_contents($cardData);
1719
-		}
1720
-
1721
-		return $cardData;
1722
-	}
1723
-
1724
-	/**
1725
-	 * @param IShareable $shareable
1726
-	 * @param array $add
1727
-	 * @param array $remove
1728
-	 */
1729
-	public function updateShares($shareable, $add, $remove) {
1730
-		$calendarId = $shareable->getResourceId();
1731
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1732
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1733
-			[
1734
-				'calendarId' => $calendarId,
1735
-				'calendarData' => $this->getCalendarById($calendarId),
1736
-				'shares' => $this->getShares($calendarId),
1737
-				'add' => $add,
1738
-				'remove' => $remove,
1739
-			]));
1740
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1741
-	}
1742
-
1743
-	/**
1744
-	 * @param int $resourceId
1745
-	 * @return array
1746
-	 */
1747
-	public function getShares($resourceId) {
1748
-		return $this->sharingBackend->getShares($resourceId);
1749
-	}
1750
-
1751
-	/**
1752
-	 * @param boolean $value
1753
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1754
-	 * @return string|null
1755
-	 */
1756
-	public function setPublishStatus($value, $calendar) {
1757
-		$query = $this->db->getQueryBuilder();
1758
-		if ($value) {
1759
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1760
-			$query->insert('dav_shares')
1761
-				->values([
1762
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1763
-					'type' => $query->createNamedParameter('calendar'),
1764
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1765
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1766
-					'publicuri' => $query->createNamedParameter($publicUri)
1767
-				]);
1768
-			$query->execute();
1769
-			return $publicUri;
1770
-		}
1771
-		$query->delete('dav_shares')
1772
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1773
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1774
-		$query->execute();
1775
-		return null;
1776
-	}
1777
-
1778
-	/**
1779
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1780
-	 * @return mixed
1781
-	 */
1782
-	public function getPublishStatus($calendar) {
1783
-		$query = $this->db->getQueryBuilder();
1784
-		$result = $query->select('publicuri')
1785
-			->from('dav_shares')
1786
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1787
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1788
-			->execute();
1789
-
1790
-		$row = $result->fetch();
1791
-		$result->closeCursor();
1792
-		return $row ? reset($row) : false;
1793
-	}
1794
-
1795
-	/**
1796
-	 * @param int $resourceId
1797
-	 * @param array $acl
1798
-	 * @return array
1799
-	 */
1800
-	public function applyShareAcl($resourceId, $acl) {
1801
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1802
-	}
1803
-
1804
-	private function convertPrincipal($principalUri, $toV2) {
1805
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1806
-			list(, $name) = URLUtil::splitPath($principalUri);
1807
-			if ($toV2 === true) {
1808
-				return "principals/users/$name";
1809
-			}
1810
-			return "principals/$name";
1811
-		}
1812
-		return $principalUri;
1813
-	}
381
+    /**
382
+     * @return array
383
+     */
384
+    public function getPublicCalendars() {
385
+        $fields = array_values($this->propertyMap);
386
+        $fields[] = 'a.id';
387
+        $fields[] = 'a.uri';
388
+        $fields[] = 'a.synctoken';
389
+        $fields[] = 'a.components';
390
+        $fields[] = 'a.principaluri';
391
+        $fields[] = 'a.transparent';
392
+        $fields[] = 's.access';
393
+        $fields[] = 's.publicuri';
394
+        $calendars = [];
395
+        $query = $this->db->getQueryBuilder();
396
+        $result = $query->select($fields)
397
+            ->from('dav_shares', 's')
398
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
399
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
400
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401
+            ->execute();
402
+
403
+        while($row = $result->fetch()) {
404
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
405
+            $row['displayname'] = $row['displayname'] . "($name)";
406
+            $components = [];
407
+            if ($row['components']) {
408
+                $components = explode(',',$row['components']);
409
+            }
410
+            $calendar = [
411
+                'id' => $row['id'],
412
+                'uri' => $row['publicuri'],
413
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
421
+            ];
422
+
423
+            foreach($this->propertyMap as $xmlName=>$dbName) {
424
+                $calendar[$xmlName] = $row[$dbName];
425
+            }
426
+
427
+            if (!isset($calendars[$calendar['id']])) {
428
+                $calendars[$calendar['id']] = $calendar;
429
+            }
430
+        }
431
+        $result->closeCursor();
432
+
433
+        return array_values($calendars);
434
+    }
435
+
436
+    /**
437
+     * @param string $uri
438
+     * @return array
439
+     * @throws NotFound
440
+     */
441
+    public function getPublicCalendar($uri) {
442
+        $fields = array_values($this->propertyMap);
443
+        $fields[] = 'a.id';
444
+        $fields[] = 'a.uri';
445
+        $fields[] = 'a.synctoken';
446
+        $fields[] = 'a.components';
447
+        $fields[] = 'a.principaluri';
448
+        $fields[] = 'a.transparent';
449
+        $fields[] = 's.access';
450
+        $fields[] = 's.publicuri';
451
+        $query = $this->db->getQueryBuilder();
452
+        $result = $query->select($fields)
453
+            ->from('dav_shares', 's')
454
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
455
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
456
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
457
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
458
+            ->execute();
459
+
460
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
461
+
462
+        $result->closeCursor();
463
+
464
+        if ($row === false) {
465
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
466
+        }
467
+
468
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
469
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
470
+        $components = [];
471
+        if ($row['components']) {
472
+            $components = explode(',',$row['components']);
473
+        }
474
+        $calendar = [
475
+            'id' => $row['id'],
476
+            'uri' => $row['publicuri'],
477
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+        ];
486
+
487
+        foreach($this->propertyMap as $xmlName=>$dbName) {
488
+            $calendar[$xmlName] = $row[$dbName];
489
+        }
490
+
491
+        return $calendar;
492
+
493
+    }
494
+
495
+    /**
496
+     * @param string $principal
497
+     * @param string $uri
498
+     * @return array|null
499
+     */
500
+    public function getCalendarByUri($principal, $uri) {
501
+        $fields = array_values($this->propertyMap);
502
+        $fields[] = 'id';
503
+        $fields[] = 'uri';
504
+        $fields[] = 'synctoken';
505
+        $fields[] = 'components';
506
+        $fields[] = 'principaluri';
507
+        $fields[] = 'transparent';
508
+
509
+        // Making fields a comma-delimited list
510
+        $query = $this->db->getQueryBuilder();
511
+        $query->select($fields)->from('calendars')
512
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
513
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
514
+            ->setMaxResults(1);
515
+        $stmt = $query->execute();
516
+
517
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
518
+        $stmt->closeCursor();
519
+        if ($row === false) {
520
+            return null;
521
+        }
522
+
523
+        $components = [];
524
+        if ($row['components']) {
525
+            $components = explode(',',$row['components']);
526
+        }
527
+
528
+        $calendar = [
529
+            'id' => $row['id'],
530
+            'uri' => $row['uri'],
531
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
+        ];
537
+
538
+        foreach($this->propertyMap as $xmlName=>$dbName) {
539
+            $calendar[$xmlName] = $row[$dbName];
540
+        }
541
+
542
+        return $calendar;
543
+    }
544
+
545
+    public function getCalendarById($calendarId) {
546
+        $fields = array_values($this->propertyMap);
547
+        $fields[] = 'id';
548
+        $fields[] = 'uri';
549
+        $fields[] = 'synctoken';
550
+        $fields[] = 'components';
551
+        $fields[] = 'principaluri';
552
+        $fields[] = 'transparent';
553
+
554
+        // Making fields a comma-delimited list
555
+        $query = $this->db->getQueryBuilder();
556
+        $query->select($fields)->from('calendars')
557
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
558
+            ->setMaxResults(1);
559
+        $stmt = $query->execute();
560
+
561
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
562
+        $stmt->closeCursor();
563
+        if ($row === false) {
564
+            return null;
565
+        }
566
+
567
+        $components = [];
568
+        if ($row['components']) {
569
+            $components = explode(',',$row['components']);
570
+        }
571
+
572
+        $calendar = [
573
+            'id' => $row['id'],
574
+            'uri' => $row['uri'],
575
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
+        ];
581
+
582
+        foreach($this->propertyMap as $xmlName=>$dbName) {
583
+            $calendar[$xmlName] = $row[$dbName];
584
+        }
585
+
586
+        return $calendar;
587
+    }
588
+
589
+    /**
590
+     * Creates a new calendar for a principal.
591
+     *
592
+     * If the creation was a success, an id must be returned that can be used to reference
593
+     * this calendar in other methods, such as updateCalendar.
594
+     *
595
+     * @param string $principalUri
596
+     * @param string $calendarUri
597
+     * @param array $properties
598
+     * @return int
599
+     */
600
+    function createCalendar($principalUri, $calendarUri, array $properties) {
601
+        $values = [
602
+            'principaluri' => $this->convertPrincipal($principalUri, true),
603
+            'uri'          => $calendarUri,
604
+            'synctoken'    => 1,
605
+            'transparent'  => 0,
606
+            'components'   => 'VEVENT,VTODO',
607
+            'displayname'  => $calendarUri
608
+        ];
609
+
610
+        // Default value
611
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612
+        if (isset($properties[$sccs])) {
613
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615
+            }
616
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
617
+        }
618
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
619
+        if (isset($properties[$transp])) {
620
+            $values['transparent'] = $properties[$transp]->getValue()==='transparent';
621
+        }
622
+
623
+        foreach($this->propertyMap as $xmlName=>$dbName) {
624
+            if (isset($properties[$xmlName])) {
625
+                $values[$dbName] = $properties[$xmlName];
626
+            }
627
+        }
628
+
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->insert('calendars');
631
+        foreach($values as $column => $value) {
632
+            $query->setValue($column, $query->createNamedParameter($value));
633
+        }
634
+        $query->execute();
635
+        $calendarId = $query->getLastInsertId();
636
+
637
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
638
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
639
+            [
640
+                'calendarId' => $calendarId,
641
+                'calendarData' => $this->getCalendarById($calendarId),
642
+        ]));
643
+
644
+        return $calendarId;
645
+    }
646
+
647
+    /**
648
+     * Updates properties for a calendar.
649
+     *
650
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
651
+     * To do the actual updates, you must tell this object which properties
652
+     * you're going to process with the handle() method.
653
+     *
654
+     * Calling the handle method is like telling the PropPatch object "I
655
+     * promise I can handle updating this property".
656
+     *
657
+     * Read the PropPatch documentation for more info and examples.
658
+     *
659
+     * @param PropPatch $propPatch
660
+     * @return void
661
+     */
662
+    function updateCalendar($calendarId, PropPatch $propPatch) {
663
+        $supportedProperties = array_keys($this->propertyMap);
664
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
665
+
666
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667
+            $newValues = [];
668
+            foreach ($mutations as $propertyName => $propertyValue) {
669
+
670
+                switch ($propertyName) {
671
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
672
+                        $fieldName = 'transparent';
673
+                        $newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674
+                        break;
675
+                    default :
676
+                        $fieldName = $this->propertyMap[$propertyName];
677
+                        $newValues[$fieldName] = $propertyValue;
678
+                        break;
679
+                }
680
+
681
+            }
682
+            $query = $this->db->getQueryBuilder();
683
+            $query->update('calendars');
684
+            foreach ($newValues as $fieldName => $value) {
685
+                $query->set($fieldName, $query->createNamedParameter($value));
686
+            }
687
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
688
+            $query->execute();
689
+
690
+            $this->addChange($calendarId, "", 2);
691
+
692
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
693
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
694
+                [
695
+                    'calendarId' => $calendarId,
696
+                    'calendarData' => $this->getCalendarById($calendarId),
697
+                    'shares' => $this->getShares($calendarId),
698
+                    'propertyMutations' => $mutations,
699
+            ]));
700
+
701
+            return true;
702
+        });
703
+    }
704
+
705
+    /**
706
+     * Delete a calendar and all it's objects
707
+     *
708
+     * @param mixed $calendarId
709
+     * @return void
710
+     */
711
+    function deleteCalendar($calendarId) {
712
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
713
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
714
+            [
715
+                'calendarId' => $calendarId,
716
+                'calendarData' => $this->getCalendarById($calendarId),
717
+                'shares' => $this->getShares($calendarId),
718
+        ]));
719
+
720
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
721
+        $stmt->execute([$calendarId]);
722
+
723
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
724
+        $stmt->execute([$calendarId]);
725
+
726
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
727
+        $stmt->execute([$calendarId]);
728
+
729
+        $this->sharingBackend->deleteAllShares($calendarId);
730
+    }
731
+
732
+    /**
733
+     * Delete all of an user's shares
734
+     *
735
+     * @param string $principaluri
736
+     * @return void
737
+     */
738
+    function deleteAllSharesByUser($principaluri) {
739
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
740
+    }
741
+
742
+    /**
743
+     * Returns all calendar objects within a calendar.
744
+     *
745
+     * Every item contains an array with the following keys:
746
+     *   * calendardata - The iCalendar-compatible calendar data
747
+     *   * uri - a unique key which will be used to construct the uri. This can
748
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
749
+     *     good idea. This is only the basename, or filename, not the full
750
+     *     path.
751
+     *   * lastmodified - a timestamp of the last modification time
752
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
753
+     *   '"abcdef"')
754
+     *   * size - The size of the calendar objects, in bytes.
755
+     *   * component - optional, a string containing the type of object, such
756
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
757
+     *     the Content-Type header.
758
+     *
759
+     * Note that the etag is optional, but it's highly encouraged to return for
760
+     * speed reasons.
761
+     *
762
+     * The calendardata is also optional. If it's not returned
763
+     * 'getCalendarObject' will be called later, which *is* expected to return
764
+     * calendardata.
765
+     *
766
+     * If neither etag or size are specified, the calendardata will be
767
+     * used/fetched to determine these numbers. If both are specified the
768
+     * amount of times this is needed is reduced by a great degree.
769
+     *
770
+     * @param mixed $calendarId
771
+     * @return array
772
+     */
773
+    function getCalendarObjects($calendarId) {
774
+        $query = $this->db->getQueryBuilder();
775
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
776
+            ->from('calendarobjects')
777
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
778
+        $stmt = $query->execute();
779
+
780
+        $result = [];
781
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782
+            $result[] = [
783
+                    'id'           => $row['id'],
784
+                    'uri'          => $row['uri'],
785
+                    'lastmodified' => $row['lastmodified'],
786
+                    'etag'         => '"' . $row['etag'] . '"',
787
+                    'calendarid'   => $row['calendarid'],
788
+                    'size'         => (int)$row['size'],
789
+                    'component'    => strtolower($row['componenttype']),
790
+                    'classification'=> (int)$row['classification']
791
+            ];
792
+        }
793
+
794
+        return $result;
795
+    }
796
+
797
+    /**
798
+     * Returns information from a single calendar object, based on it's object
799
+     * uri.
800
+     *
801
+     * The object uri is only the basename, or filename and not a full path.
802
+     *
803
+     * The returned array must have the same keys as getCalendarObjects. The
804
+     * 'calendardata' object is required here though, while it's not required
805
+     * for getCalendarObjects.
806
+     *
807
+     * This method must return null if the object did not exist.
808
+     *
809
+     * @param mixed $calendarId
810
+     * @param string $objectUri
811
+     * @return array|null
812
+     */
813
+    function getCalendarObject($calendarId, $objectUri) {
814
+
815
+        $query = $this->db->getQueryBuilder();
816
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
817
+                ->from('calendarobjects')
818
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
819
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
820
+        $stmt = $query->execute();
821
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
822
+
823
+        if(!$row) return null;
824
+
825
+        return [
826
+                'id'            => $row['id'],
827
+                'uri'           => $row['uri'],
828
+                'lastmodified'  => $row['lastmodified'],
829
+                'etag'          => '"' . $row['etag'] . '"',
830
+                'calendarid'    => $row['calendarid'],
831
+                'size'          => (int)$row['size'],
832
+                'calendardata'  => $this->readBlob($row['calendardata']),
833
+                'component'     => strtolower($row['componenttype']),
834
+                'classification'=> (int)$row['classification']
835
+        ];
836
+    }
837
+
838
+    /**
839
+     * Returns a list of calendar objects.
840
+     *
841
+     * This method should work identical to getCalendarObject, but instead
842
+     * return all the calendar objects in the list as an array.
843
+     *
844
+     * If the backend supports this, it may allow for some speed-ups.
845
+     *
846
+     * @param mixed $calendarId
847
+     * @param string[] $uris
848
+     * @return array
849
+     */
850
+    function getMultipleCalendarObjects($calendarId, array $uris) {
851
+        if (empty($uris)) {
852
+            return [];
853
+        }
854
+
855
+        $chunks = array_chunk($uris, 100);
856
+        $objects = [];
857
+
858
+        $query = $this->db->getQueryBuilder();
859
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
860
+            ->from('calendarobjects')
861
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
862
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
863
+
864
+        foreach ($chunks as $uris) {
865
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
866
+            $result = $query->execute();
867
+
868
+            while ($row = $result->fetch()) {
869
+                $objects[] = [
870
+                    'id'           => $row['id'],
871
+                    'uri'          => $row['uri'],
872
+                    'lastmodified' => $row['lastmodified'],
873
+                    'etag'         => '"' . $row['etag'] . '"',
874
+                    'calendarid'   => $row['calendarid'],
875
+                    'size'         => (int)$row['size'],
876
+                    'calendardata' => $this->readBlob($row['calendardata']),
877
+                    'component'    => strtolower($row['componenttype']),
878
+                    'classification' => (int)$row['classification']
879
+                ];
880
+            }
881
+            $result->closeCursor();
882
+        }
883
+        return $objects;
884
+    }
885
+
886
+    /**
887
+     * Creates a new calendar object.
888
+     *
889
+     * The object uri is only the basename, or filename and not a full path.
890
+     *
891
+     * It is possible return an etag from this function, which will be used in
892
+     * the response to this PUT request. Note that the ETag must be surrounded
893
+     * by double-quotes.
894
+     *
895
+     * However, you should only really return this ETag if you don't mangle the
896
+     * calendar-data. If the result of a subsequent GET to this object is not
897
+     * the exact same as this request body, you should omit the ETag.
898
+     *
899
+     * @param mixed $calendarId
900
+     * @param string $objectUri
901
+     * @param string $calendarData
902
+     * @return string
903
+     */
904
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
905
+        $extraData = $this->getDenormalizedData($calendarData);
906
+
907
+        $query = $this->db->getQueryBuilder();
908
+        $query->insert('calendarobjects')
909
+            ->values([
910
+                'calendarid' => $query->createNamedParameter($calendarId),
911
+                'uri' => $query->createNamedParameter($objectUri),
912
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
913
+                'lastmodified' => $query->createNamedParameter(time()),
914
+                'etag' => $query->createNamedParameter($extraData['etag']),
915
+                'size' => $query->createNamedParameter($extraData['size']),
916
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
917
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
918
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
919
+                'classification' => $query->createNamedParameter($extraData['classification']),
920
+                'uid' => $query->createNamedParameter($extraData['uid']),
921
+            ])
922
+            ->execute();
923
+
924
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
925
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
926
+            [
927
+                'calendarId' => $calendarId,
928
+                'calendarData' => $this->getCalendarById($calendarId),
929
+                'shares' => $this->getShares($calendarId),
930
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
931
+            ]
932
+        ));
933
+        $this->addChange($calendarId, $objectUri, 1);
934
+
935
+        return '"' . $extraData['etag'] . '"';
936
+    }
937
+
938
+    /**
939
+     * Updates an existing calendarobject, based on it's uri.
940
+     *
941
+     * The object uri is only the basename, or filename and not a full path.
942
+     *
943
+     * It is possible return an etag from this function, which will be used in
944
+     * the response to this PUT request. Note that the ETag must be surrounded
945
+     * by double-quotes.
946
+     *
947
+     * However, you should only really return this ETag if you don't mangle the
948
+     * calendar-data. If the result of a subsequent GET to this object is not
949
+     * the exact same as this request body, you should omit the ETag.
950
+     *
951
+     * @param mixed $calendarId
952
+     * @param string $objectUri
953
+     * @param string $calendarData
954
+     * @return string
955
+     */
956
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
957
+        $extraData = $this->getDenormalizedData($calendarData);
958
+
959
+        $query = $this->db->getQueryBuilder();
960
+        $query->update('calendarobjects')
961
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
962
+                ->set('lastmodified', $query->createNamedParameter(time()))
963
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
964
+                ->set('size', $query->createNamedParameter($extraData['size']))
965
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
966
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
967
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
968
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
969
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
970
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
971
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
972
+            ->execute();
973
+
974
+        $data = $this->getCalendarObject($calendarId, $objectUri);
975
+        if (is_array($data)) {
976
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
977
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
978
+                [
979
+                    'calendarId' => $calendarId,
980
+                    'calendarData' => $this->getCalendarById($calendarId),
981
+                    'shares' => $this->getShares($calendarId),
982
+                    'objectData' => $data,
983
+                ]
984
+            ));
985
+        }
986
+        $this->addChange($calendarId, $objectUri, 2);
987
+
988
+        return '"' . $extraData['etag'] . '"';
989
+    }
990
+
991
+    /**
992
+     * @param int $calendarObjectId
993
+     * @param int $classification
994
+     */
995
+    public function setClassification($calendarObjectId, $classification) {
996
+        if (!in_array($classification, [
997
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
998
+        ])) {
999
+            throw new \InvalidArgumentException();
1000
+        }
1001
+        $query = $this->db->getQueryBuilder();
1002
+        $query->update('calendarobjects')
1003
+            ->set('classification', $query->createNamedParameter($classification))
1004
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1005
+            ->execute();
1006
+    }
1007
+
1008
+    /**
1009
+     * Deletes an existing calendar object.
1010
+     *
1011
+     * The object uri is only the basename, or filename and not a full path.
1012
+     *
1013
+     * @param mixed $calendarId
1014
+     * @param string $objectUri
1015
+     * @return void
1016
+     */
1017
+    function deleteCalendarObject($calendarId, $objectUri) {
1018
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1019
+        if (is_array($data)) {
1020
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1021
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1022
+                [
1023
+                    'calendarId' => $calendarId,
1024
+                    'calendarData' => $this->getCalendarById($calendarId),
1025
+                    'shares' => $this->getShares($calendarId),
1026
+                    'objectData' => $data,
1027
+                ]
1028
+            ));
1029
+        }
1030
+
1031
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1032
+        $stmt->execute([$calendarId, $objectUri]);
1033
+
1034
+        $this->addChange($calendarId, $objectUri, 3);
1035
+    }
1036
+
1037
+    /**
1038
+     * Performs a calendar-query on the contents of this calendar.
1039
+     *
1040
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1041
+     * calendar-query it is possible for a client to request a specific set of
1042
+     * object, based on contents of iCalendar properties, date-ranges and
1043
+     * iCalendar component types (VTODO, VEVENT).
1044
+     *
1045
+     * This method should just return a list of (relative) urls that match this
1046
+     * query.
1047
+     *
1048
+     * The list of filters are specified as an array. The exact array is
1049
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1050
+     *
1051
+     * Note that it is extremely likely that getCalendarObject for every path
1052
+     * returned from this method will be called almost immediately after. You
1053
+     * may want to anticipate this to speed up these requests.
1054
+     *
1055
+     * This method provides a default implementation, which parses *all* the
1056
+     * iCalendar objects in the specified calendar.
1057
+     *
1058
+     * This default may well be good enough for personal use, and calendars
1059
+     * that aren't very large. But if you anticipate high usage, big calendars
1060
+     * or high loads, you are strongly advised to optimize certain paths.
1061
+     *
1062
+     * The best way to do so is override this method and to optimize
1063
+     * specifically for 'common filters'.
1064
+     *
1065
+     * Requests that are extremely common are:
1066
+     *   * requests for just VEVENTS
1067
+     *   * requests for just VTODO
1068
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1069
+     *
1070
+     * ..and combinations of these requests. It may not be worth it to try to
1071
+     * handle every possible situation and just rely on the (relatively
1072
+     * easy to use) CalendarQueryValidator to handle the rest.
1073
+     *
1074
+     * Note that especially time-range-filters may be difficult to parse. A
1075
+     * time-range filter specified on a VEVENT must for instance also handle
1076
+     * recurrence rules correctly.
1077
+     * A good example of how to interprete all these filters can also simply
1078
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1079
+     * as possible, so it gives you a good idea on what type of stuff you need
1080
+     * to think of.
1081
+     *
1082
+     * @param mixed $calendarId
1083
+     * @param array $filters
1084
+     * @return array
1085
+     */
1086
+    function calendarQuery($calendarId, array $filters) {
1087
+        $componentType = null;
1088
+        $requirePostFilter = true;
1089
+        $timeRange = null;
1090
+
1091
+        // if no filters were specified, we don't need to filter after a query
1092
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1093
+            $requirePostFilter = false;
1094
+        }
1095
+
1096
+        // Figuring out if there's a component filter
1097
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1098
+            $componentType = $filters['comp-filters'][0]['name'];
1099
+
1100
+            // Checking if we need post-filters
1101
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1102
+                $requirePostFilter = false;
1103
+            }
1104
+            // There was a time-range filter
1105
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1106
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1107
+
1108
+                // If start time OR the end time is not specified, we can do a
1109
+                // 100% accurate mysql query.
1110
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1111
+                    $requirePostFilter = false;
1112
+                }
1113
+            }
1114
+
1115
+        }
1116
+        $columns = ['uri'];
1117
+        if ($requirePostFilter) {
1118
+            $columns = ['uri', 'calendardata'];
1119
+        }
1120
+        $query = $this->db->getQueryBuilder();
1121
+        $query->select($columns)
1122
+            ->from('calendarobjects')
1123
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1124
+
1125
+        if ($componentType) {
1126
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1127
+        }
1128
+
1129
+        if ($timeRange && $timeRange['start']) {
1130
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1131
+        }
1132
+        if ($timeRange && $timeRange['end']) {
1133
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1134
+        }
1135
+
1136
+        $stmt = $query->execute();
1137
+
1138
+        $result = [];
1139
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140
+            if ($requirePostFilter) {
1141
+                if (!$this->validateFilterForObject($row, $filters)) {
1142
+                    continue;
1143
+                }
1144
+            }
1145
+            $result[] = $row['uri'];
1146
+        }
1147
+
1148
+        return $result;
1149
+    }
1150
+
1151
+    /**
1152
+     * Searches through all of a users calendars and calendar objects to find
1153
+     * an object with a specific UID.
1154
+     *
1155
+     * This method should return the path to this object, relative to the
1156
+     * calendar home, so this path usually only contains two parts:
1157
+     *
1158
+     * calendarpath/objectpath.ics
1159
+     *
1160
+     * If the uid is not found, return null.
1161
+     *
1162
+     * This method should only consider * objects that the principal owns, so
1163
+     * any calendars owned by other principals that also appear in this
1164
+     * collection should be ignored.
1165
+     *
1166
+     * @param string $principalUri
1167
+     * @param string $uid
1168
+     * @return string|null
1169
+     */
1170
+    function getCalendarObjectByUID($principalUri, $uid) {
1171
+
1172
+        $query = $this->db->getQueryBuilder();
1173
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1174
+            ->from('calendarobjects', 'co')
1175
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1176
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1177
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1178
+
1179
+        $stmt = $query->execute();
1180
+
1181
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1183
+        }
1184
+
1185
+        return null;
1186
+    }
1187
+
1188
+    /**
1189
+     * The getChanges method returns all the changes that have happened, since
1190
+     * the specified syncToken in the specified calendar.
1191
+     *
1192
+     * This function should return an array, such as the following:
1193
+     *
1194
+     * [
1195
+     *   'syncToken' => 'The current synctoken',
1196
+     *   'added'   => [
1197
+     *      'new.txt',
1198
+     *   ],
1199
+     *   'modified'   => [
1200
+     *      'modified.txt',
1201
+     *   ],
1202
+     *   'deleted' => [
1203
+     *      'foo.php.bak',
1204
+     *      'old.txt'
1205
+     *   ]
1206
+     * );
1207
+     *
1208
+     * The returned syncToken property should reflect the *current* syncToken
1209
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1210
+     * property This is * needed here too, to ensure the operation is atomic.
1211
+     *
1212
+     * If the $syncToken argument is specified as null, this is an initial
1213
+     * sync, and all members should be reported.
1214
+     *
1215
+     * The modified property is an array of nodenames that have changed since
1216
+     * the last token.
1217
+     *
1218
+     * The deleted property is an array with nodenames, that have been deleted
1219
+     * from collection.
1220
+     *
1221
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1222
+     * 1, you only have to report changes that happened only directly in
1223
+     * immediate descendants. If it's 2, it should also include changes from
1224
+     * the nodes below the child collections. (grandchildren)
1225
+     *
1226
+     * The $limit argument allows a client to specify how many results should
1227
+     * be returned at most. If the limit is not specified, it should be treated
1228
+     * as infinite.
1229
+     *
1230
+     * If the limit (infinite or not) is higher than you're willing to return,
1231
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1232
+     *
1233
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1234
+     * return null.
1235
+     *
1236
+     * The limit is 'suggestive'. You are free to ignore it.
1237
+     *
1238
+     * @param string $calendarId
1239
+     * @param string $syncToken
1240
+     * @param int $syncLevel
1241
+     * @param int $limit
1242
+     * @return array
1243
+     */
1244
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245
+        // Current synctoken
1246
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
+        $stmt->execute([ $calendarId ]);
1248
+        $currentToken = $stmt->fetchColumn(0);
1249
+
1250
+        if (is_null($currentToken)) {
1251
+            return null;
1252
+        }
1253
+
1254
+        $result = [
1255
+            'syncToken' => $currentToken,
1256
+            'added'     => [],
1257
+            'modified'  => [],
1258
+            'deleted'   => [],
1259
+        ];
1260
+
1261
+        if ($syncToken) {
1262
+
1263
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
+            if ($limit>0) {
1265
+                $query.= " `LIMIT` " . (int)$limit;
1266
+            }
1267
+
1268
+            // Fetching all changes
1269
+            $stmt = $this->db->prepare($query);
1270
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1271
+
1272
+            $changes = [];
1273
+
1274
+            // This loop ensures that any duplicates are overwritten, only the
1275
+            // last change on a node is relevant.
1276
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277
+
1278
+                $changes[$row['uri']] = $row['operation'];
1279
+
1280
+            }
1281
+
1282
+            foreach($changes as $uri => $operation) {
1283
+
1284
+                switch($operation) {
1285
+                    case 1 :
1286
+                        $result['added'][] = $uri;
1287
+                        break;
1288
+                    case 2 :
1289
+                        $result['modified'][] = $uri;
1290
+                        break;
1291
+                    case 3 :
1292
+                        $result['deleted'][] = $uri;
1293
+                        break;
1294
+                }
1295
+
1296
+            }
1297
+        } else {
1298
+            // No synctoken supplied, this is the initial sync.
1299
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1300
+            $stmt = $this->db->prepare($query);
1301
+            $stmt->execute([$calendarId]);
1302
+
1303
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1304
+        }
1305
+        return $result;
1306
+
1307
+    }
1308
+
1309
+    /**
1310
+     * Returns a list of subscriptions for a principal.
1311
+     *
1312
+     * Every subscription is an array with the following keys:
1313
+     *  * id, a unique id that will be used by other functions to modify the
1314
+     *    subscription. This can be the same as the uri or a database key.
1315
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1316
+     *  * principaluri. The owner of the subscription. Almost always the same as
1317
+     *    principalUri passed to this method.
1318
+     *
1319
+     * Furthermore, all the subscription info must be returned too:
1320
+     *
1321
+     * 1. {DAV:}displayname
1322
+     * 2. {http://apple.com/ns/ical/}refreshrate
1323
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1324
+     *    should not be stripped).
1325
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1326
+     *    should not be stripped).
1327
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1328
+     *    attachments should not be stripped).
1329
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1330
+     *     Sabre\DAV\Property\Href).
1331
+     * 7. {http://apple.com/ns/ical/}calendar-color
1332
+     * 8. {http://apple.com/ns/ical/}calendar-order
1333
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1334
+     *    (should just be an instance of
1335
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1336
+     *    default components).
1337
+     *
1338
+     * @param string $principalUri
1339
+     * @return array
1340
+     */
1341
+    function getSubscriptionsForUser($principalUri) {
1342
+        $fields = array_values($this->subscriptionPropertyMap);
1343
+        $fields[] = 'id';
1344
+        $fields[] = 'uri';
1345
+        $fields[] = 'source';
1346
+        $fields[] = 'principaluri';
1347
+        $fields[] = 'lastmodified';
1348
+
1349
+        $query = $this->db->getQueryBuilder();
1350
+        $query->select($fields)
1351
+            ->from('calendarsubscriptions')
1352
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353
+            ->orderBy('calendarorder', 'asc');
1354
+        $stmt =$query->execute();
1355
+
1356
+        $subscriptions = [];
1357
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358
+
1359
+            $subscription = [
1360
+                'id'           => $row['id'],
1361
+                'uri'          => $row['uri'],
1362
+                'principaluri' => $row['principaluri'],
1363
+                'source'       => $row['source'],
1364
+                'lastmodified' => $row['lastmodified'],
1365
+
1366
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367
+            ];
1368
+
1369
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370
+                if (!is_null($row[$dbName])) {
1371
+                    $subscription[$xmlName] = $row[$dbName];
1372
+                }
1373
+            }
1374
+
1375
+            $subscriptions[] = $subscription;
1376
+
1377
+        }
1378
+
1379
+        return $subscriptions;
1380
+    }
1381
+
1382
+    /**
1383
+     * Creates a new subscription for a principal.
1384
+     *
1385
+     * If the creation was a success, an id must be returned that can be used to reference
1386
+     * this subscription in other methods, such as updateSubscription.
1387
+     *
1388
+     * @param string $principalUri
1389
+     * @param string $uri
1390
+     * @param array $properties
1391
+     * @return mixed
1392
+     */
1393
+    function createSubscription($principalUri, $uri, array $properties) {
1394
+
1395
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1396
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1397
+        }
1398
+
1399
+        $values = [
1400
+            'principaluri' => $principalUri,
1401
+            'uri'          => $uri,
1402
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1403
+            'lastmodified' => time(),
1404
+        ];
1405
+
1406
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407
+
1408
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409
+            if (array_key_exists($xmlName, $properties)) {
1410
+                    $values[$dbName] = $properties[$xmlName];
1411
+                    if (in_array($dbName, $propertiesBoolean)) {
1412
+                        $values[$dbName] = true;
1413
+                }
1414
+            }
1415
+        }
1416
+
1417
+        $valuesToInsert = array();
1418
+
1419
+        $query = $this->db->getQueryBuilder();
1420
+
1421
+        foreach (array_keys($values) as $name) {
1422
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1423
+        }
1424
+
1425
+        $query->insert('calendarsubscriptions')
1426
+            ->values($valuesToInsert)
1427
+            ->execute();
1428
+
1429
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1430
+    }
1431
+
1432
+    /**
1433
+     * Updates a subscription
1434
+     *
1435
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1436
+     * To do the actual updates, you must tell this object which properties
1437
+     * you're going to process with the handle() method.
1438
+     *
1439
+     * Calling the handle method is like telling the PropPatch object "I
1440
+     * promise I can handle updating this property".
1441
+     *
1442
+     * Read the PropPatch documentation for more info and examples.
1443
+     *
1444
+     * @param mixed $subscriptionId
1445
+     * @param PropPatch $propPatch
1446
+     * @return void
1447
+     */
1448
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1449
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1450
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1451
+
1452
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1453
+
1454
+            $newValues = [];
1455
+
1456
+            foreach($mutations as $propertyName=>$propertyValue) {
1457
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458
+                    $newValues['source'] = $propertyValue->getHref();
1459
+                } else {
1460
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1461
+                    $newValues[$fieldName] = $propertyValue;
1462
+                }
1463
+            }
1464
+
1465
+            $query = $this->db->getQueryBuilder();
1466
+            $query->update('calendarsubscriptions')
1467
+                ->set('lastmodified', $query->createNamedParameter(time()));
1468
+            foreach($newValues as $fieldName=>$value) {
1469
+                $query->set($fieldName, $query->createNamedParameter($value));
1470
+            }
1471
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1472
+                ->execute();
1473
+
1474
+            return true;
1475
+
1476
+        });
1477
+    }
1478
+
1479
+    /**
1480
+     * Deletes a subscription.
1481
+     *
1482
+     * @param mixed $subscriptionId
1483
+     * @return void
1484
+     */
1485
+    function deleteSubscription($subscriptionId) {
1486
+        $query = $this->db->getQueryBuilder();
1487
+        $query->delete('calendarsubscriptions')
1488
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1489
+            ->execute();
1490
+    }
1491
+
1492
+    /**
1493
+     * Returns a single scheduling object for the inbox collection.
1494
+     *
1495
+     * The returned array should contain the following elements:
1496
+     *   * uri - A unique basename for the object. This will be used to
1497
+     *           construct a full uri.
1498
+     *   * calendardata - The iCalendar object
1499
+     *   * lastmodified - The last modification date. Can be an int for a unix
1500
+     *                    timestamp, or a PHP DateTime object.
1501
+     *   * etag - A unique token that must change if the object changed.
1502
+     *   * size - The size of the object, in bytes.
1503
+     *
1504
+     * @param string $principalUri
1505
+     * @param string $objectUri
1506
+     * @return array
1507
+     */
1508
+    function getSchedulingObject($principalUri, $objectUri) {
1509
+        $query = $this->db->getQueryBuilder();
1510
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1511
+            ->from('schedulingobjects')
1512
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1513
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1514
+            ->execute();
1515
+
1516
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517
+
1518
+        if(!$row) {
1519
+            return null;
1520
+        }
1521
+
1522
+        return [
1523
+                'uri'          => $row['uri'],
1524
+                'calendardata' => $row['calendardata'],
1525
+                'lastmodified' => $row['lastmodified'],
1526
+                'etag'         => '"' . $row['etag'] . '"',
1527
+                'size'         => (int)$row['size'],
1528
+        ];
1529
+    }
1530
+
1531
+    /**
1532
+     * Returns all scheduling objects for the inbox collection.
1533
+     *
1534
+     * These objects should be returned as an array. Every item in the array
1535
+     * should follow the same structure as returned from getSchedulingObject.
1536
+     *
1537
+     * The main difference is that 'calendardata' is optional.
1538
+     *
1539
+     * @param string $principalUri
1540
+     * @return array
1541
+     */
1542
+    function getSchedulingObjects($principalUri) {
1543
+        $query = $this->db->getQueryBuilder();
1544
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1545
+                ->from('schedulingobjects')
1546
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1547
+                ->execute();
1548
+
1549
+        $result = [];
1550
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551
+            $result[] = [
1552
+                    'calendardata' => $row['calendardata'],
1553
+                    'uri'          => $row['uri'],
1554
+                    'lastmodified' => $row['lastmodified'],
1555
+                    'etag'         => '"' . $row['etag'] . '"',
1556
+                    'size'         => (int)$row['size'],
1557
+            ];
1558
+        }
1559
+
1560
+        return $result;
1561
+    }
1562
+
1563
+    /**
1564
+     * Deletes a scheduling object from the inbox collection.
1565
+     *
1566
+     * @param string $principalUri
1567
+     * @param string $objectUri
1568
+     * @return void
1569
+     */
1570
+    function deleteSchedulingObject($principalUri, $objectUri) {
1571
+        $query = $this->db->getQueryBuilder();
1572
+        $query->delete('schedulingobjects')
1573
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1574
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1575
+                ->execute();
1576
+    }
1577
+
1578
+    /**
1579
+     * Creates a new scheduling object. This should land in a users' inbox.
1580
+     *
1581
+     * @param string $principalUri
1582
+     * @param string $objectUri
1583
+     * @param string $objectData
1584
+     * @return void
1585
+     */
1586
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1587
+        $query = $this->db->getQueryBuilder();
1588
+        $query->insert('schedulingobjects')
1589
+            ->values([
1590
+                'principaluri' => $query->createNamedParameter($principalUri),
1591
+                'calendardata' => $query->createNamedParameter($objectData),
1592
+                'uri' => $query->createNamedParameter($objectUri),
1593
+                'lastmodified' => $query->createNamedParameter(time()),
1594
+                'etag' => $query->createNamedParameter(md5($objectData)),
1595
+                'size' => $query->createNamedParameter(strlen($objectData))
1596
+            ])
1597
+            ->execute();
1598
+    }
1599
+
1600
+    /**
1601
+     * Adds a change record to the calendarchanges table.
1602
+     *
1603
+     * @param mixed $calendarId
1604
+     * @param string $objectUri
1605
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1606
+     * @return void
1607
+     */
1608
+    protected function addChange($calendarId, $objectUri, $operation) {
1609
+
1610
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1611
+        $stmt->execute([
1612
+            $objectUri,
1613
+            $calendarId,
1614
+            $operation,
1615
+            $calendarId
1616
+        ]);
1617
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1618
+        $stmt->execute([
1619
+            $calendarId
1620
+        ]);
1621
+
1622
+    }
1623
+
1624
+    /**
1625
+     * Parses some information from calendar objects, used for optimized
1626
+     * calendar-queries.
1627
+     *
1628
+     * Returns an array with the following keys:
1629
+     *   * etag - An md5 checksum of the object without the quotes.
1630
+     *   * size - Size of the object in bytes
1631
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1632
+     *   * firstOccurence
1633
+     *   * lastOccurence
1634
+     *   * uid - value of the UID property
1635
+     *
1636
+     * @param string $calendarData
1637
+     * @return array
1638
+     */
1639
+    public function getDenormalizedData($calendarData) {
1640
+
1641
+        $vObject = Reader::read($calendarData);
1642
+        $componentType = null;
1643
+        $component = null;
1644
+        $firstOccurrence = null;
1645
+        $lastOccurrence = null;
1646
+        $uid = null;
1647
+        $classification = self::CLASSIFICATION_PUBLIC;
1648
+        foreach($vObject->getComponents() as $component) {
1649
+            if ($component->name!=='VTIMEZONE') {
1650
+                $componentType = $component->name;
1651
+                $uid = (string)$component->UID;
1652
+                break;
1653
+            }
1654
+        }
1655
+        if (!$componentType) {
1656
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1657
+        }
1658
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1659
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1660
+            // Finding the last occurrence is a bit harder
1661
+            if (!isset($component->RRULE)) {
1662
+                if (isset($component->DTEND)) {
1663
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1664
+                } elseif (isset($component->DURATION)) {
1665
+                    $endDate = clone $component->DTSTART->getDateTime();
1666
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1667
+                    $lastOccurrence = $endDate->getTimeStamp();
1668
+                } elseif (!$component->DTSTART->hasTime()) {
1669
+                    $endDate = clone $component->DTSTART->getDateTime();
1670
+                    $endDate->modify('+1 day');
1671
+                    $lastOccurrence = $endDate->getTimeStamp();
1672
+                } else {
1673
+                    $lastOccurrence = $firstOccurrence;
1674
+                }
1675
+            } else {
1676
+                $it = new EventIterator($vObject, (string)$component->UID);
1677
+                $maxDate = new \DateTime(self::MAX_DATE);
1678
+                if ($it->isInfinite()) {
1679
+                    $lastOccurrence = $maxDate->getTimestamp();
1680
+                } else {
1681
+                    $end = $it->getDtEnd();
1682
+                    while($it->valid() && $end < $maxDate) {
1683
+                        $end = $it->getDtEnd();
1684
+                        $it->next();
1685
+
1686
+                    }
1687
+                    $lastOccurrence = $end->getTimestamp();
1688
+                }
1689
+
1690
+            }
1691
+        }
1692
+
1693
+        if ($component->CLASS) {
1694
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1695
+            switch ($component->CLASS->getValue()) {
1696
+                case 'PUBLIC':
1697
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1698
+                    break;
1699
+                case 'CONFIDENTIAL':
1700
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1701
+                    break;
1702
+            }
1703
+        }
1704
+        return [
1705
+            'etag' => md5($calendarData),
1706
+            'size' => strlen($calendarData),
1707
+            'componentType' => $componentType,
1708
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1709
+            'lastOccurence'  => $lastOccurrence,
1710
+            'uid' => $uid,
1711
+            'classification' => $classification
1712
+        ];
1713
+
1714
+    }
1715
+
1716
+    private function readBlob($cardData) {
1717
+        if (is_resource($cardData)) {
1718
+            return stream_get_contents($cardData);
1719
+        }
1720
+
1721
+        return $cardData;
1722
+    }
1723
+
1724
+    /**
1725
+     * @param IShareable $shareable
1726
+     * @param array $add
1727
+     * @param array $remove
1728
+     */
1729
+    public function updateShares($shareable, $add, $remove) {
1730
+        $calendarId = $shareable->getResourceId();
1731
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1732
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1733
+            [
1734
+                'calendarId' => $calendarId,
1735
+                'calendarData' => $this->getCalendarById($calendarId),
1736
+                'shares' => $this->getShares($calendarId),
1737
+                'add' => $add,
1738
+                'remove' => $remove,
1739
+            ]));
1740
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1741
+    }
1742
+
1743
+    /**
1744
+     * @param int $resourceId
1745
+     * @return array
1746
+     */
1747
+    public function getShares($resourceId) {
1748
+        return $this->sharingBackend->getShares($resourceId);
1749
+    }
1750
+
1751
+    /**
1752
+     * @param boolean $value
1753
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1754
+     * @return string|null
1755
+     */
1756
+    public function setPublishStatus($value, $calendar) {
1757
+        $query = $this->db->getQueryBuilder();
1758
+        if ($value) {
1759
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1760
+            $query->insert('dav_shares')
1761
+                ->values([
1762
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1763
+                    'type' => $query->createNamedParameter('calendar'),
1764
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1765
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1766
+                    'publicuri' => $query->createNamedParameter($publicUri)
1767
+                ]);
1768
+            $query->execute();
1769
+            return $publicUri;
1770
+        }
1771
+        $query->delete('dav_shares')
1772
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1773
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1774
+        $query->execute();
1775
+        return null;
1776
+    }
1777
+
1778
+    /**
1779
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1780
+     * @return mixed
1781
+     */
1782
+    public function getPublishStatus($calendar) {
1783
+        $query = $this->db->getQueryBuilder();
1784
+        $result = $query->select('publicuri')
1785
+            ->from('dav_shares')
1786
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1787
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1788
+            ->execute();
1789
+
1790
+        $row = $result->fetch();
1791
+        $result->closeCursor();
1792
+        return $row ? reset($row) : false;
1793
+    }
1794
+
1795
+    /**
1796
+     * @param int $resourceId
1797
+     * @param array $acl
1798
+     * @return array
1799
+     */
1800
+    public function applyShareAcl($resourceId, $acl) {
1801
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1802
+    }
1803
+
1804
+    private function convertPrincipal($principalUri, $toV2) {
1805
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1806
+            list(, $name) = URLUtil::splitPath($principalUri);
1807
+            if ($toV2 === true) {
1808
+                return "principals/users/$name";
1809
+            }
1810
+            return "principals/$name";
1811
+        }
1812
+        return $principalUri;
1813
+    }
1814 1814
 }
Please login to merge, or discard this patch.
Spacing   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180 180
 		}
181 181
 
182
-		return (int)$query->execute()->fetchColumn();
182
+		return (int) $query->execute()->fetchColumn();
183 183
 	}
184 184
 
185 185
 	/**
@@ -226,25 +226,25 @@  discard block
 block discarded – undo
226 226
 		$stmt = $query->execute();
227 227
 
228 228
 		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 
231 231
 			$components = [];
232 232
 			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
233
+				$components = explode(',', $row['components']);
234 234
 			}
235 235
 
236 236
 			$calendar = [
237 237
 				'id' => $row['id'],
238 238
 				'uri' => $row['uri'],
239 239
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
240
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
241
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
242
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
244
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245 245
 			];
246 246
 
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
247
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
248 248
 				$calendar[$xmlName] = $row[$dbName];
249 249
 			}
250 250
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 
258 258
 		// query for shared calendars
259 259
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
260
+		$principals[] = $principalUri;
261 261
 
262 262
 		$fields = array_values($this->propertyMap);
263 263
 		$fields[] = 'a.id';
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278 278
 			->execute();
279 279
 
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
280
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
281
+		while ($row = $result->fetch()) {
282 282
 			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283 283
 			if (isset($calendars[$row['id']])) {
284 284
 				if ($readOnly) {
@@ -293,25 +293,25 @@  discard block
 block discarded – undo
293 293
 			}
294 294
 
295 295
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
296
-			$uri = $row['uri'] . '_shared_by_' . $name;
297
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
296
+			$uri = $row['uri'].'_shared_by_'.$name;
297
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
298 298
 			$components = [];
299 299
 			if ($row['components']) {
300
-				$components = explode(',',$row['components']);
300
+				$components = explode(',', $row['components']);
301 301
 			}
302 302
 			$calendar = [
303 303
 				'id' => $row['id'],
304 304
 				'uri' => $uri,
305 305
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
306
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
307
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
308
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
310
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311 311
 				$readOnlyPropertyName => $readOnly,
312 312
 			];
313 313
 
314
-			foreach($this->propertyMap as $xmlName=>$dbName) {
314
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
315 315
 				$calendar[$xmlName] = $row[$dbName];
316 316
 			}
317 317
 
@@ -338,21 +338,21 @@  discard block
 block discarded – undo
338 338
 			->orderBy('calendarorder', 'ASC');
339 339
 		$stmt = $query->execute();
340 340
 		$calendars = [];
341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
341
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342 342
 			$components = [];
343 343
 			if ($row['components']) {
344
-				$components = explode(',',$row['components']);
344
+				$components = explode(',', $row['components']);
345 345
 			}
346 346
 			$calendar = [
347 347
 				'id' => $row['id'],
348 348
 				'uri' => $row['uri'],
349 349
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
350
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
351
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
352
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
354 354
 			];
355
-			foreach($this->propertyMap as $xmlName=>$dbName) {
355
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
356 356
 				$calendar[$xmlName] = $row[$dbName];
357 357
 			}
358 358
 			if (!isset($calendars[$calendar['id']])) {
@@ -400,27 +400,27 @@  discard block
 block discarded – undo
400 400
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401 401
 			->execute();
402 402
 
403
-		while($row = $result->fetch()) {
403
+		while ($row = $result->fetch()) {
404 404
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
405
-			$row['displayname'] = $row['displayname'] . "($name)";
405
+			$row['displayname'] = $row['displayname']."($name)";
406 406
 			$components = [];
407 407
 			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
408
+				$components = explode(',', $row['components']);
409 409
 			}
410 410
 			$calendar = [
411 411
 				'id' => $row['id'],
412 412
 				'uri' => $row['publicuri'],
413 413
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
414
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
415
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
416
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
418
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
420
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
421 421
 			];
422 422
 
423
-			foreach($this->propertyMap as $xmlName=>$dbName) {
423
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
424 424
 				$calendar[$xmlName] = $row[$dbName];
425 425
 			}
426 426
 
@@ -462,29 +462,29 @@  discard block
 block discarded – undo
462 462
 		$result->closeCursor();
463 463
 
464 464
 		if ($row === false) {
465
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
465
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
466 466
 		}
467 467
 
468 468
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
469
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
469
+		$row['displayname'] = $row['displayname'].' '."($name)";
470 470
 		$components = [];
471 471
 		if ($row['components']) {
472
-			$components = explode(',',$row['components']);
472
+			$components = explode(',', $row['components']);
473 473
 		}
474 474
 		$calendar = [
475 475
 			'id' => $row['id'],
476 476
 			'uri' => $row['publicuri'],
477 477
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
478
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
479
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
480
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
482
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
484
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
485 485
 		];
486 486
 
487
-		foreach($this->propertyMap as $xmlName=>$dbName) {
487
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
488 488
 			$calendar[$xmlName] = $row[$dbName];
489 489
 		}
490 490
 
@@ -522,20 +522,20 @@  discard block
 block discarded – undo
522 522
 
523 523
 		$components = [];
524 524
 		if ($row['components']) {
525
-			$components = explode(',',$row['components']);
525
+			$components = explode(',', $row['components']);
526 526
 		}
527 527
 
528 528
 		$calendar = [
529 529
 			'id' => $row['id'],
530 530
 			'uri' => $row['uri'],
531 531
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
532
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
533
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
534
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
536 536
 		];
537 537
 
538
-		foreach($this->propertyMap as $xmlName=>$dbName) {
538
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
539 539
 			$calendar[$xmlName] = $row[$dbName];
540 540
 		}
541 541
 
@@ -566,20 +566,20 @@  discard block
 block discarded – undo
566 566
 
567 567
 		$components = [];
568 568
 		if ($row['components']) {
569
-			$components = explode(',',$row['components']);
569
+			$components = explode(',', $row['components']);
570 570
 		}
571 571
 
572 572
 		$calendar = [
573 573
 			'id' => $row['id'],
574 574
 			'uri' => $row['uri'],
575 575
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
576
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
577
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
578
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
580 580
 		];
581 581
 
582
-		foreach($this->propertyMap as $xmlName=>$dbName) {
582
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
583 583
 			$calendar[$xmlName] = $row[$dbName];
584 584
 		}
585 585
 
@@ -611,16 +611,16 @@  discard block
 block discarded – undo
611 611
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612 612
 		if (isset($properties[$sccs])) {
613 613
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
614
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615 615
 			}
616
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
616
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
617 617
 		}
618
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
618
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
619 619
 		if (isset($properties[$transp])) {
620
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
620
+			$values['transparent'] = $properties[$transp]->getValue() === 'transparent';
621 621
 		}
622 622
 
623
-		foreach($this->propertyMap as $xmlName=>$dbName) {
623
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
624 624
 			if (isset($properties[$xmlName])) {
625 625
 				$values[$dbName] = $properties[$xmlName];
626 626
 			}
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 
629 629
 		$query = $this->db->getQueryBuilder();
630 630
 		$query->insert('calendars');
631
-		foreach($values as $column => $value) {
631
+		foreach ($values as $column => $value) {
632 632
 			$query->setValue($column, $query->createNamedParameter($value));
633 633
 		}
634 634
 		$query->execute();
@@ -661,14 +661,14 @@  discard block
 block discarded – undo
661 661
 	 */
662 662
 	function updateCalendar($calendarId, PropPatch $propPatch) {
663 663
 		$supportedProperties = array_keys($this->propertyMap);
664
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
664
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
665 665
 
666 666
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667 667
 			$newValues = [];
668 668
 			foreach ($mutations as $propertyName => $propertyValue) {
669 669
 
670 670
 				switch ($propertyName) {
671
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
671
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
672 672
 						$fieldName = 'transparent';
673 673
 						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674 674
 						break;
@@ -778,16 +778,16 @@  discard block
 block discarded – undo
778 778
 		$stmt = $query->execute();
779 779
 
780 780
 		$result = [];
781
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
781
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782 782
 			$result[] = [
783 783
 					'id'           => $row['id'],
784 784
 					'uri'          => $row['uri'],
785 785
 					'lastmodified' => $row['lastmodified'],
786
-					'etag'         => '"' . $row['etag'] . '"',
786
+					'etag'         => '"'.$row['etag'].'"',
787 787
 					'calendarid'   => $row['calendarid'],
788
-					'size'         => (int)$row['size'],
788
+					'size'         => (int) $row['size'],
789 789
 					'component'    => strtolower($row['componenttype']),
790
-					'classification'=> (int)$row['classification']
790
+					'classification'=> (int) $row['classification']
791 791
 			];
792 792
 		}
793 793
 
@@ -820,18 +820,18 @@  discard block
 block discarded – undo
820 820
 		$stmt = $query->execute();
821 821
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
822 822
 
823
-		if(!$row) return null;
823
+		if (!$row) return null;
824 824
 
825 825
 		return [
826 826
 				'id'            => $row['id'],
827 827
 				'uri'           => $row['uri'],
828 828
 				'lastmodified'  => $row['lastmodified'],
829
-				'etag'          => '"' . $row['etag'] . '"',
829
+				'etag'          => '"'.$row['etag'].'"',
830 830
 				'calendarid'    => $row['calendarid'],
831
-				'size'          => (int)$row['size'],
831
+				'size'          => (int) $row['size'],
832 832
 				'calendardata'  => $this->readBlob($row['calendardata']),
833 833
 				'component'     => strtolower($row['componenttype']),
834
-				'classification'=> (int)$row['classification']
834
+				'classification'=> (int) $row['classification']
835 835
 		];
836 836
 	}
837 837
 
@@ -870,12 +870,12 @@  discard block
 block discarded – undo
870 870
 					'id'           => $row['id'],
871 871
 					'uri'          => $row['uri'],
872 872
 					'lastmodified' => $row['lastmodified'],
873
-					'etag'         => '"' . $row['etag'] . '"',
873
+					'etag'         => '"'.$row['etag'].'"',
874 874
 					'calendarid'   => $row['calendarid'],
875
-					'size'         => (int)$row['size'],
875
+					'size'         => (int) $row['size'],
876 876
 					'calendardata' => $this->readBlob($row['calendardata']),
877 877
 					'component'    => strtolower($row['componenttype']),
878
-					'classification' => (int)$row['classification']
878
+					'classification' => (int) $row['classification']
879 879
 				];
880 880
 			}
881 881
 			$result->closeCursor();
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
 		));
933 933
 		$this->addChange($calendarId, $objectUri, 1);
934 934
 
935
-		return '"' . $extraData['etag'] . '"';
935
+		return '"'.$extraData['etag'].'"';
936 936
 	}
937 937
 
938 938
 	/**
@@ -985,7 +985,7 @@  discard block
 block discarded – undo
985 985
 		}
986 986
 		$this->addChange($calendarId, $objectUri, 2);
987 987
 
988
-		return '"' . $extraData['etag'] . '"';
988
+		return '"'.$extraData['etag'].'"';
989 989
 	}
990 990
 
991 991
 	/**
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 		$stmt = $query->execute();
1137 1137
 
1138 1138
 		$result = [];
1139
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1139
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140 1140
 			if ($requirePostFilter) {
1141 1141
 				if (!$this->validateFilterForObject($row, $filters)) {
1142 1142
 					continue;
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 		$stmt = $query->execute();
1180 1180
 
1181 1181
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1182
+			return $row['calendaruri'].'/'.$row['objecturi'];
1183 1183
 		}
1184 1184
 
1185 1185
 		return null;
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245 1245
 		// Current synctoken
1246 1246
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
-		$stmt->execute([ $calendarId ]);
1247
+		$stmt->execute([$calendarId]);
1248 1248
 		$currentToken = $stmt->fetchColumn(0);
1249 1249
 
1250 1250
 		if (is_null($currentToken)) {
@@ -1261,8 +1261,8 @@  discard block
 block discarded – undo
1261 1261
 		if ($syncToken) {
1262 1262
 
1263 1263
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
-			if ($limit>0) {
1265
-				$query.= " `LIMIT` " . (int)$limit;
1264
+			if ($limit > 0) {
1265
+				$query .= " `LIMIT` ".(int) $limit;
1266 1266
 			}
1267 1267
 
1268 1268
 			// Fetching all changes
@@ -1273,15 +1273,15 @@  discard block
 block discarded – undo
1273 1273
 
1274 1274
 			// This loop ensures that any duplicates are overwritten, only the
1275 1275
 			// last change on a node is relevant.
1276
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1276
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277 1277
 
1278 1278
 				$changes[$row['uri']] = $row['operation'];
1279 1279
 
1280 1280
 			}
1281 1281
 
1282
-			foreach($changes as $uri => $operation) {
1282
+			foreach ($changes as $uri => $operation) {
1283 1283
 
1284
-				switch($operation) {
1284
+				switch ($operation) {
1285 1285
 					case 1 :
1286 1286
 						$result['added'][] = $uri;
1287 1287
 						break;
@@ -1351,10 +1351,10 @@  discard block
 block discarded – undo
1351 1351
 			->from('calendarsubscriptions')
1352 1352
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353 1353
 			->orderBy('calendarorder', 'asc');
1354
-		$stmt =$query->execute();
1354
+		$stmt = $query->execute();
1355 1355
 
1356 1356
 		$subscriptions = [];
1357
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1357
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358 1358
 
1359 1359
 			$subscription = [
1360 1360
 				'id'           => $row['id'],
@@ -1363,10 +1363,10 @@  discard block
 block discarded – undo
1363 1363
 				'source'       => $row['source'],
1364 1364
 				'lastmodified' => $row['lastmodified'],
1365 1365
 
1366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1366
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367 1367
 			];
1368 1368
 
1369
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1369
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370 1370
 				if (!is_null($row[$dbName])) {
1371 1371
 					$subscription[$xmlName] = $row[$dbName];
1372 1372
 				}
@@ -1405,7 +1405,7 @@  discard block
 block discarded – undo
1405 1405
 
1406 1406
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407 1407
 
1408
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1408
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409 1409
 			if (array_key_exists($xmlName, $properties)) {
1410 1410
 					$values[$dbName] = $properties[$xmlName];
1411 1411
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
 
1454 1454
 			$newValues = [];
1455 1455
 
1456
-			foreach($mutations as $propertyName=>$propertyValue) {
1456
+			foreach ($mutations as $propertyName=>$propertyValue) {
1457 1457
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458 1458
 					$newValues['source'] = $propertyValue->getHref();
1459 1459
 				} else {
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
 			$query = $this->db->getQueryBuilder();
1466 1466
 			$query->update('calendarsubscriptions')
1467 1467
 				->set('lastmodified', $query->createNamedParameter(time()));
1468
-			foreach($newValues as $fieldName=>$value) {
1468
+			foreach ($newValues as $fieldName=>$value) {
1469 1469
 				$query->set($fieldName, $query->createNamedParameter($value));
1470 1470
 			}
1471 1471
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
 
1516 1516
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517 1517
 
1518
-		if(!$row) {
1518
+		if (!$row) {
1519 1519
 			return null;
1520 1520
 		}
1521 1521
 
@@ -1523,8 +1523,8 @@  discard block
 block discarded – undo
1523 1523
 				'uri'          => $row['uri'],
1524 1524
 				'calendardata' => $row['calendardata'],
1525 1525
 				'lastmodified' => $row['lastmodified'],
1526
-				'etag'         => '"' . $row['etag'] . '"',
1527
-				'size'         => (int)$row['size'],
1526
+				'etag'         => '"'.$row['etag'].'"',
1527
+				'size'         => (int) $row['size'],
1528 1528
 		];
1529 1529
 	}
1530 1530
 
@@ -1547,13 +1547,13 @@  discard block
 block discarded – undo
1547 1547
 				->execute();
1548 1548
 
1549 1549
 		$result = [];
1550
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1550
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551 1551
 			$result[] = [
1552 1552
 					'calendardata' => $row['calendardata'],
1553 1553
 					'uri'          => $row['uri'],
1554 1554
 					'lastmodified' => $row['lastmodified'],
1555
-					'etag'         => '"' . $row['etag'] . '"',
1556
-					'size'         => (int)$row['size'],
1555
+					'etag'         => '"'.$row['etag'].'"',
1556
+					'size'         => (int) $row['size'],
1557 1557
 			];
1558 1558
 		}
1559 1559
 
@@ -1645,10 +1645,10 @@  discard block
 block discarded – undo
1645 1645
 		$lastOccurrence = null;
1646 1646
 		$uid = null;
1647 1647
 		$classification = self::CLASSIFICATION_PUBLIC;
1648
-		foreach($vObject->getComponents() as $component) {
1649
-			if ($component->name!=='VTIMEZONE') {
1648
+		foreach ($vObject->getComponents() as $component) {
1649
+			if ($component->name !== 'VTIMEZONE') {
1650 1650
 				$componentType = $component->name;
1651
-				$uid = (string)$component->UID;
1651
+				$uid = (string) $component->UID;
1652 1652
 				break;
1653 1653
 			}
1654 1654
 		}
@@ -1673,13 +1673,13 @@  discard block
 block discarded – undo
1673 1673
 					$lastOccurrence = $firstOccurrence;
1674 1674
 				}
1675 1675
 			} else {
1676
-				$it = new EventIterator($vObject, (string)$component->UID);
1676
+				$it = new EventIterator($vObject, (string) $component->UID);
1677 1677
 				$maxDate = new \DateTime(self::MAX_DATE);
1678 1678
 				if ($it->isInfinite()) {
1679 1679
 					$lastOccurrence = $maxDate->getTimestamp();
1680 1680
 				} else {
1681 1681
 					$end = $it->getDtEnd();
1682
-					while($it->valid() && $end < $maxDate) {
1682
+					while ($it->valid() && $end < $maxDate) {
1683 1683
 						$end = $it->getDtEnd();
1684 1684
 						$it->next();
1685 1685
 
Please login to merge, or discard this patch.