Passed
Push — master ( bbb39c...5026d2 )
by Christoph
27:34 queued 12:27
created
lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -34,62 +34,62 @@
 block discarded – undo
34 34
 use OCP\Share\IShare;
35 35
 
36 36
 class RemoteGroupPlugin implements ISearchPlugin {
37
-	protected $shareeEnumeration;
37
+    protected $shareeEnumeration;
38 38
 
39
-	/** @var ICloudIdManager */
40
-	private $cloudIdManager;
41
-	/** @var bool */
42
-	private $enabled = false;
39
+    /** @var ICloudIdManager */
40
+    private $cloudIdManager;
41
+    /** @var bool */
42
+    private $enabled = false;
43 43
 
44
-	public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
45
-		try {
46
-			$fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
47
-			$supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
48
-			if (in_array('group', $supportedShareTypes)) {
49
-				$this->enabled = true;
50
-			}
51
-		} catch (\Exception $e) {
52
-			// do nothing, just don't enable federated group shares
53
-		}
54
-		$this->cloudIdManager = $cloudIdManager;
55
-	}
44
+    public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
45
+        try {
46
+            $fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
47
+            $supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
48
+            if (in_array('group', $supportedShareTypes)) {
49
+                $this->enabled = true;
50
+            }
51
+        } catch (\Exception $e) {
52
+            // do nothing, just don't enable federated group shares
53
+        }
54
+        $this->cloudIdManager = $cloudIdManager;
55
+    }
56 56
 
57
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
58
-		$result = ['wide' => [], 'exact' => []];
59
-		$resultType = new SearchResultType('remote_groups');
57
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
58
+        $result = ['wide' => [], 'exact' => []];
59
+        $resultType = new SearchResultType('remote_groups');
60 60
 
61
-		if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
62
-			[$remoteGroup, $serverUrl] = $this->splitGroupRemote($search);
63
-			$result['exact'][] = [
64
-				'label' => $remoteGroup . " ($serverUrl)",
65
-				'guid' => $remoteGroup,
66
-				'name' => $remoteGroup,
67
-				'value' => [
68
-					'shareType' => IShare::TYPE_REMOTE_GROUP,
69
-					'shareWith' => $search,
70
-					'server' => $serverUrl,
71
-				],
72
-			];
73
-		}
61
+        if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
62
+            [$remoteGroup, $serverUrl] = $this->splitGroupRemote($search);
63
+            $result['exact'][] = [
64
+                'label' => $remoteGroup . " ($serverUrl)",
65
+                'guid' => $remoteGroup,
66
+                'name' => $remoteGroup,
67
+                'value' => [
68
+                    'shareType' => IShare::TYPE_REMOTE_GROUP,
69
+                    'shareWith' => $search,
70
+                    'server' => $serverUrl,
71
+                ],
72
+            ];
73
+        }
74 74
 
75
-		$searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
75
+        $searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
76 76
 
77
-		return true;
78
-	}
77
+        return true;
78
+    }
79 79
 
80
-	/**
81
-	 * split group and remote from federated cloud id
82
-	 *
83
-	 * @param string $address federated share address
84
-	 * @return array [user, remoteURL]
85
-	 * @throws \InvalidArgumentException
86
-	 */
87
-	public function splitGroupRemote($address) {
88
-		try {
89
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
90
-			return [$cloudId->getUser(), $cloudId->getRemote()];
91
-		} catch (\InvalidArgumentException $e) {
92
-			throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
93
-		}
94
-	}
80
+    /**
81
+     * split group and remote from federated cloud id
82
+     *
83
+     * @param string $address federated share address
84
+     * @return array [user, remoteURL]
85
+     * @throws \InvalidArgumentException
86
+     */
87
+    public function splitGroupRemote($address) {
88
+        try {
89
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
90
+            return [$cloudId->getUser(), $cloudId->getRemote()];
91
+        } catch (\InvalidArgumentException $e) {
92
+            throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
93
+        }
94
+    }
95 95
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 		if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
62 62
 			[$remoteGroup, $serverUrl] = $this->splitGroupRemote($search);
63 63
 			$result['exact'][] = [
64
-				'label' => $remoteGroup . " ($serverUrl)",
64
+				'label' => $remoteGroup." ($serverUrl)",
65 65
 				'guid' => $remoteGroup,
66 66
 				'name' => $remoteGroup,
67 67
 				'value' => [
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/RemotePlugin.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -38,155 +38,155 @@
 block discarded – undo
38 38
 use OCP\Share\IShare;
39 39
 
40 40
 class RemotePlugin implements ISearchPlugin {
41
-	protected $shareeEnumeration;
41
+    protected $shareeEnumeration;
42 42
 
43
-	/** @var IManager */
44
-	private $contactsManager;
45
-	/** @var ICloudIdManager */
46
-	private $cloudIdManager;
47
-	/** @var IConfig */
48
-	private $config;
49
-	/** @var IUserManager */
50
-	private $userManager;
51
-	/** @var string */
52
-	private $userId = '';
43
+    /** @var IManager */
44
+    private $contactsManager;
45
+    /** @var ICloudIdManager */
46
+    private $cloudIdManager;
47
+    /** @var IConfig */
48
+    private $config;
49
+    /** @var IUserManager */
50
+    private $userManager;
51
+    /** @var string */
52
+    private $userId = '';
53 53
 
54
-	public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IUserManager $userManager, IUserSession $userSession) {
55
-		$this->contactsManager = $contactsManager;
56
-		$this->cloudIdManager = $cloudIdManager;
57
-		$this->config = $config;
58
-		$this->userManager = $userManager;
59
-		$user = $userSession->getUser();
60
-		if ($user !== null) {
61
-			$this->userId = $user->getUID();
62
-		}
63
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
64
-	}
54
+    public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IUserManager $userManager, IUserSession $userSession) {
55
+        $this->contactsManager = $contactsManager;
56
+        $this->cloudIdManager = $cloudIdManager;
57
+        $this->config = $config;
58
+        $this->userManager = $userManager;
59
+        $user = $userSession->getUser();
60
+        if ($user !== null) {
61
+            $this->userId = $user->getUID();
62
+        }
63
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
64
+    }
65 65
 
66
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
67
-		$result = ['wide' => [], 'exact' => []];
68
-		$resultType = new SearchResultType('remotes');
66
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
67
+        $result = ['wide' => [], 'exact' => []];
68
+        $resultType = new SearchResultType('remotes');
69 69
 
70
-		// Search in contacts
71
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN'], ['limit' => $limit, 'offset' => $offset]);
72
-		foreach ($addressBookContacts as $contact) {
73
-			if (isset($contact['isLocalSystemBook'])) {
74
-				continue;
75
-			}
76
-			if (isset($contact['CLOUD'])) {
77
-				$cloudIds = $contact['CLOUD'];
78
-				if (is_string($cloudIds)) {
79
-					$cloudIds = [$cloudIds];
80
-				}
81
-				$lowerSearch = strtolower($search);
82
-				foreach ($cloudIds as $cloudId) {
83
-					$cloudIdType = '';
84
-					if (\is_array($cloudId)) {
85
-						$cloudIdData = $cloudId;
86
-						$cloudId = $cloudIdData['value'];
87
-						$cloudIdType = $cloudIdData['type'];
88
-					}
89
-					try {
90
-						[$remoteUser, $serverUrl] = $this->splitUserRemote($cloudId);
91
-					} catch (\InvalidArgumentException $e) {
92
-						continue;
93
-					}
70
+        // Search in contacts
71
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN'], ['limit' => $limit, 'offset' => $offset]);
72
+        foreach ($addressBookContacts as $contact) {
73
+            if (isset($contact['isLocalSystemBook'])) {
74
+                continue;
75
+            }
76
+            if (isset($contact['CLOUD'])) {
77
+                $cloudIds = $contact['CLOUD'];
78
+                if (is_string($cloudIds)) {
79
+                    $cloudIds = [$cloudIds];
80
+                }
81
+                $lowerSearch = strtolower($search);
82
+                foreach ($cloudIds as $cloudId) {
83
+                    $cloudIdType = '';
84
+                    if (\is_array($cloudId)) {
85
+                        $cloudIdData = $cloudId;
86
+                        $cloudId = $cloudIdData['value'];
87
+                        $cloudIdType = $cloudIdData['type'];
88
+                    }
89
+                    try {
90
+                        [$remoteUser, $serverUrl] = $this->splitUserRemote($cloudId);
91
+                    } catch (\InvalidArgumentException $e) {
92
+                        continue;
93
+                    }
94 94
 
95
-					$localUser = $this->userManager->get($remoteUser);
96
-					/**
97
-					 * Add local share if remote cloud id matches a local user ones
98
-					 */
99
-					if ($localUser !== null && $remoteUser !== $this->userId && $cloudId === $localUser->getCloudId()) {
100
-						$result['wide'][] = [
101
-							'label' => $contact['FN'],
102
-							'uuid' => $contact['UID'],
103
-							'value' => [
104
-								'shareType' => IShare::TYPE_USER,
105
-								'shareWith' => $remoteUser
106
-							],
107
-							'shareWithDisplayNameUnique' => $contact['EMAIL'] !== null && $contact['EMAIL'] !== '' ? $contact['EMAIL'] : $contact['UID'],
108
-						];
109
-					}
95
+                    $localUser = $this->userManager->get($remoteUser);
96
+                    /**
97
+                     * Add local share if remote cloud id matches a local user ones
98
+                     */
99
+                    if ($localUser !== null && $remoteUser !== $this->userId && $cloudId === $localUser->getCloudId()) {
100
+                        $result['wide'][] = [
101
+                            'label' => $contact['FN'],
102
+                            'uuid' => $contact['UID'],
103
+                            'value' => [
104
+                                'shareType' => IShare::TYPE_USER,
105
+                                'shareWith' => $remoteUser
106
+                            ],
107
+                            'shareWithDisplayNameUnique' => $contact['EMAIL'] !== null && $contact['EMAIL'] !== '' ? $contact['EMAIL'] : $contact['UID'],
108
+                        ];
109
+                    }
110 110
 
111
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
112
-						if (strtolower($cloudId) === $lowerSearch) {
113
-							$searchResult->markExactIdMatch($resultType);
114
-						}
115
-						$result['exact'][] = [
116
-							'label' => $contact['FN'] . " ($cloudId)",
117
-							'uuid' => $contact['UID'],
118
-							'name' => $contact['FN'],
119
-							'type' => $cloudIdType,
120
-							'value' => [
121
-								'shareType' => IShare::TYPE_REMOTE,
122
-								'shareWith' => $cloudId,
123
-								'server' => $serverUrl,
124
-							],
125
-						];
126
-					} else {
127
-						$result['wide'][] = [
128
-							'label' => $contact['FN'] . " ($cloudId)",
129
-							'uuid' => $contact['UID'],
130
-							'name' => $contact['FN'],
131
-							'type' => $cloudIdType,
132
-							'value' => [
133
-								'shareType' => IShare::TYPE_REMOTE,
134
-								'shareWith' => $cloudId,
135
-								'server' => $serverUrl,
136
-							],
137
-						];
138
-					}
139
-				}
140
-			}
141
-		}
111
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
112
+                        if (strtolower($cloudId) === $lowerSearch) {
113
+                            $searchResult->markExactIdMatch($resultType);
114
+                        }
115
+                        $result['exact'][] = [
116
+                            'label' => $contact['FN'] . " ($cloudId)",
117
+                            'uuid' => $contact['UID'],
118
+                            'name' => $contact['FN'],
119
+                            'type' => $cloudIdType,
120
+                            'value' => [
121
+                                'shareType' => IShare::TYPE_REMOTE,
122
+                                'shareWith' => $cloudId,
123
+                                'server' => $serverUrl,
124
+                            ],
125
+                        ];
126
+                    } else {
127
+                        $result['wide'][] = [
128
+                            'label' => $contact['FN'] . " ($cloudId)",
129
+                            'uuid' => $contact['UID'],
130
+                            'name' => $contact['FN'],
131
+                            'type' => $cloudIdType,
132
+                            'value' => [
133
+                                'shareType' => IShare::TYPE_REMOTE,
134
+                                'shareWith' => $cloudId,
135
+                                'server' => $serverUrl,
136
+                            ],
137
+                        ];
138
+                    }
139
+                }
140
+            }
141
+        }
142 142
 
143
-		if (!$this->shareeEnumeration) {
144
-			$result['wide'] = [];
145
-		} else {
146
-			$result['wide'] = array_slice($result['wide'], $offset, $limit);
147
-		}
143
+        if (!$this->shareeEnumeration) {
144
+            $result['wide'] = [];
145
+        } else {
146
+            $result['wide'] = array_slice($result['wide'], $offset, $limit);
147
+        }
148 148
 
149
-		/**
150
-		 * Add generic share with remote item for valid cloud ids that are not users of the local instance
151
-		 */
152
-		if (!$searchResult->hasExactIdMatch($resultType) && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
153
-			try {
154
-				[$remoteUser, $serverUrl] = $this->splitUserRemote($search);
155
-				$localUser = $this->userManager->get($remoteUser);
156
-				if ($localUser === null || $search !== $localUser->getCloudId()) {
157
-					$result['exact'][] = [
158
-						'label' => $remoteUser . " ($serverUrl)",
159
-						'uuid' => $remoteUser,
160
-						'name' => $remoteUser,
161
-						'value' => [
162
-							'shareType' => IShare::TYPE_REMOTE,
163
-							'shareWith' => $search,
164
-							'server' => $serverUrl,
165
-						],
166
-					];
167
-				}
168
-			} catch (\InvalidArgumentException $e) {
169
-			}
170
-		}
149
+        /**
150
+         * Add generic share with remote item for valid cloud ids that are not users of the local instance
151
+         */
152
+        if (!$searchResult->hasExactIdMatch($resultType) && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
153
+            try {
154
+                [$remoteUser, $serverUrl] = $this->splitUserRemote($search);
155
+                $localUser = $this->userManager->get($remoteUser);
156
+                if ($localUser === null || $search !== $localUser->getCloudId()) {
157
+                    $result['exact'][] = [
158
+                        'label' => $remoteUser . " ($serverUrl)",
159
+                        'uuid' => $remoteUser,
160
+                        'name' => $remoteUser,
161
+                        'value' => [
162
+                            'shareType' => IShare::TYPE_REMOTE,
163
+                            'shareWith' => $search,
164
+                            'server' => $serverUrl,
165
+                        ],
166
+                    ];
167
+                }
168
+            } catch (\InvalidArgumentException $e) {
169
+            }
170
+        }
171 171
 
172
-		$searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
172
+        $searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
173 173
 
174
-		return true;
175
-	}
174
+        return true;
175
+    }
176 176
 
177
-	/**
178
-	 * split user and remote from federated cloud id
179
-	 *
180
-	 * @param string $address federated share address
181
-	 * @return array [user, remoteURL]
182
-	 * @throws \InvalidArgumentException
183
-	 */
184
-	public function splitUserRemote($address) {
185
-		try {
186
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
187
-			return [$cloudId->getUser(), $cloudId->getRemote()];
188
-		} catch (\InvalidArgumentException $e) {
189
-			throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
190
-		}
191
-	}
177
+    /**
178
+     * split user and remote from federated cloud id
179
+     *
180
+     * @param string $address federated share address
181
+     * @return array [user, remoteURL]
182
+     * @throws \InvalidArgumentException
183
+     */
184
+    public function splitUserRemote($address) {
185
+        try {
186
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
187
+            return [$cloudId->getUser(), $cloudId->getRemote()];
188
+        } catch (\InvalidArgumentException $e) {
189
+            throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
190
+        }
191
+    }
192 192
 }
Please login to merge, or discard this patch.
lib/private/Template/IconsCacher.php 2 patches
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -42,226 +42,226 @@
 block discarded – undo
42 42
 
43 43
 class IconsCacher {
44 44
 
45
-	/** @var ILogger */
46
-	protected $logger;
47
-
48
-	/** @var IAppData */
49
-	protected $appData;
50
-
51
-	/** @var ISimpleFolder */
52
-	private $folder;
53
-
54
-	/** @var IURLGenerator */
55
-	protected $urlGenerator;
56
-
57
-	/** @var ITimeFactory */
58
-	protected $timeFactory;
59
-
60
-	/** @var string */
61
-	private $iconVarRE = '/--(icon-[a-zA-Z0-9-]+):\s?url\(["\']?([a-zA-Z0-9-_\~\/\.\?\&\=\:\;\+\,]+)[^;]+;/m';
62
-
63
-	/** @var string */
64
-	private $fileName = 'icons-vars.css';
65
-
66
-	private $iconList = 'icons-list.template';
67
-
68
-	private $cachedCss;
69
-	private $cachedList;
70
-
71
-	/**
72
-	 * @param ILogger $logger
73
-	 * @param Factory $appDataFactory
74
-	 * @param IURLGenerator $urlGenerator
75
-	 * @param ITimeFactory $timeFactory
76
-	 * @throws \OCP\Files\NotPermittedException
77
-	 */
78
-	public function __construct(ILogger $logger,
79
-								Factory $appDataFactory,
80
-								IURLGenerator $urlGenerator,
81
-								ITimeFactory $timeFactory) {
82
-		$this->logger = $logger;
83
-		$this->appData = $appDataFactory->get('css');
84
-		$this->urlGenerator = $urlGenerator;
85
-		$this->timeFactory = $timeFactory;
86
-
87
-		try {
88
-			$this->folder = $this->appData->getFolder('icons');
89
-		} catch (NotFoundException $e) {
90
-			$this->folder = $this->appData->newFolder('icons');
91
-		}
92
-	}
93
-
94
-	private function getIconsFromCss(string $css): array {
95
-		preg_match_all($this->iconVarRE, $css, $matches, PREG_SET_ORDER);
96
-		$icons = [];
97
-		foreach ($matches as $icon) {
98
-			$icons[$icon[1]] = $icon[2];
99
-		}
100
-
101
-		return $icons;
102
-	}
103
-
104
-	/**
105
-	 * @param string $css
106
-	 * @return string
107
-	 * @throws NotFoundException
108
-	 * @throws \OCP\Files\NotPermittedException
109
-	 */
110
-	public function setIconsCss(string $css): string {
111
-		$cachedFile = $this->getCachedList();
112
-		if (!$cachedFile) {
113
-			$currentData = '';
114
-			$cachedFile = $this->folder->newFile($this->iconList);
115
-		} else {
116
-			$currentData = $cachedFile->getContent();
117
-		}
118
-
119
-		$cachedVarsCssFile = $this->getCachedCSS();
120
-		if (!$cachedVarsCssFile) {
121
-			$cachedVarsCssFile = $this->folder->newFile($this->fileName);
122
-		}
123
-
124
-		$icons = $this->getIconsFromCss($currentData . $css);
125
-
126
-		$data = '';
127
-		$list = '';
128
-		foreach ($icons as $icon => $url) {
129
-			$list .= "--$icon: url('$url');";
130
-			[$location,$color] = $this->parseUrl($url);
131
-			$svg = false;
132
-			if ($location !== '' && \file_exists($location)) {
133
-				$svg = \file_get_contents($location);
134
-			}
135
-			if ($svg === false) {
136
-				$this->logger->debug('Failed to get icon file ' . $location);
137
-				$data .= "--$icon: url('$url');";
138
-				continue;
139
-			}
140
-			$encode = base64_encode($this->colorizeSvg($svg, $color));
141
-			$data .= '--' . $icon . ': url(data:image/svg+xml;base64,' . $encode . ');';
142
-		}
143
-
144
-		if (\strlen($data) > 0 && \strlen($list) > 0) {
145
-			$data = ":root {\n$data\n}";
146
-			$cachedVarsCssFile->putContent($data);
147
-			$list = ":root {\n$list\n}";
148
-			$cachedFile->putContent($list);
149
-			$this->cachedList = null;
150
-			$this->cachedCss = null;
151
-		}
152
-
153
-		return preg_replace($this->iconVarRE, '', $css);
154
-	}
155
-
156
-	/**
157
-	 * @param $url
158
-	 * @return array
159
-	 */
160
-	private function parseUrl($url): array {
161
-		$location = '';
162
-		$color = '';
163
-		$base = $this->getRoutePrefix() . '/svg/';
164
-		$cleanUrl = \substr($url, \strlen($base));
165
-		if (\strpos($url, $base . 'core') === 0) {
166
-			$cleanUrl = \substr($cleanUrl, \strlen('core'));
167
-			if (\preg_match('/\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
168
-				[,$cleanUrl,$color] = $matches;
169
-				$location = \OC::$SERVERROOT . '/core/img/' . $cleanUrl . '.svg';
170
-			}
171
-		} elseif (\strpos($url, $base) === 0) {
172
-			if (\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
173
-				[,$app,$cleanUrl, $color] = $matches;
174
-				$location = \OC_App::getAppPath($app) . '/img/' . $cleanUrl . '.svg';
175
-				if ($app === 'settings') {
176
-					$location = \OC::$SERVERROOT . '/settings/img/' . $cleanUrl . '.svg';
177
-				}
178
-			}
179
-		}
180
-		return [
181
-			$location,
182
-			$color
183
-		];
184
-	}
185
-
186
-	/**
187
-	 * @param $svg
188
-	 * @param $color
189
-	 * @return string
190
-	 */
191
-	public function colorizeSvg($svg, $color): string {
192
-		if (!preg_match('/^[0-9a-f]{3,6}$/i', $color)) {
193
-			// Prevent not-sane colors from being written into the SVG
194
-			$color = '000';
195
-		}
196
-
197
-		// add fill (fill is not present on black elements)
198
-		$fillRe = '/<((circle|rect|path)((?!fill)[a-z0-9 =".\-#():;,])+)\/>/mi';
199
-		$svg = preg_replace($fillRe, '<$1 fill="#' . $color . '"/>', $svg);
200
-
201
-		// replace any fill or stroke colors
202
-		$svg = preg_replace('/stroke="#([a-z0-9]{3,6})"/mi', 'stroke="#' . $color . '"', $svg);
203
-		$svg = preg_replace('/fill="#([a-z0-9]{3,6})"/mi', 'fill="#' . $color . '"', $svg);
204
-		return $svg;
205
-	}
206
-
207
-	private function getRoutePrefix() {
208
-		$frontControllerActive = (\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
209
-		$prefix = \OC::$WEBROOT . '/index.php';
210
-		if ($frontControllerActive) {
211
-			$prefix = \OC::$WEBROOT;
212
-		}
213
-		return $prefix;
214
-	}
215
-
216
-	/**
217
-	 * Get icons css file
218
-	 * @return ISimpleFile|boolean
219
-	 */
220
-	public function getCachedCSS() {
221
-		try {
222
-			if (!$this->cachedCss) {
223
-				$this->cachedCss = $this->folder->getFile($this->fileName);
224
-			}
225
-			return $this->cachedCss;
226
-		} catch (NotFoundException $e) {
227
-			return false;
228
-		}
229
-	}
230
-
231
-	/**
232
-	 * Get icon-vars list template
233
-	 * @return ISimpleFile|boolean
234
-	 */
235
-	public function getCachedList() {
236
-		try {
237
-			if (!$this->cachedList) {
238
-				$this->cachedList = $this->folder->getFile($this->iconList);
239
-			}
240
-			return $this->cachedList;
241
-		} catch (NotFoundException $e) {
242
-			return false;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Add the icons cache css into the header
248
-	 */
249
-	public function injectCss() {
250
-		$mtime = $this->timeFactory->getTime();
251
-		$file = $this->getCachedList();
252
-		if ($file) {
253
-			$mtime = $file->getMTime();
254
-		}
255
-		// Only inject once
256
-		foreach (\OC_Util::$headers as $header) {
257
-			if (
258
-				array_key_exists('attributes', $header) &&
259
-				array_key_exists('href', $header['attributes']) &&
260
-				strpos($header['attributes']['href'], $this->fileName) !== false) {
261
-				return;
262
-			}
263
-		}
264
-		$linkToCSS = $this->urlGenerator->linkToRoute('core.Css.getCss', ['appName' => 'icons', 'fileName' => $this->fileName, 'v' => $mtime]);
265
-		\OC_Util::addHeader('link', ['rel' => 'stylesheet', 'href' => $linkToCSS], null, true);
266
-	}
45
+    /** @var ILogger */
46
+    protected $logger;
47
+
48
+    /** @var IAppData */
49
+    protected $appData;
50
+
51
+    /** @var ISimpleFolder */
52
+    private $folder;
53
+
54
+    /** @var IURLGenerator */
55
+    protected $urlGenerator;
56
+
57
+    /** @var ITimeFactory */
58
+    protected $timeFactory;
59
+
60
+    /** @var string */
61
+    private $iconVarRE = '/--(icon-[a-zA-Z0-9-]+):\s?url\(["\']?([a-zA-Z0-9-_\~\/\.\?\&\=\:\;\+\,]+)[^;]+;/m';
62
+
63
+    /** @var string */
64
+    private $fileName = 'icons-vars.css';
65
+
66
+    private $iconList = 'icons-list.template';
67
+
68
+    private $cachedCss;
69
+    private $cachedList;
70
+
71
+    /**
72
+     * @param ILogger $logger
73
+     * @param Factory $appDataFactory
74
+     * @param IURLGenerator $urlGenerator
75
+     * @param ITimeFactory $timeFactory
76
+     * @throws \OCP\Files\NotPermittedException
77
+     */
78
+    public function __construct(ILogger $logger,
79
+                                Factory $appDataFactory,
80
+                                IURLGenerator $urlGenerator,
81
+                                ITimeFactory $timeFactory) {
82
+        $this->logger = $logger;
83
+        $this->appData = $appDataFactory->get('css');
84
+        $this->urlGenerator = $urlGenerator;
85
+        $this->timeFactory = $timeFactory;
86
+
87
+        try {
88
+            $this->folder = $this->appData->getFolder('icons');
89
+        } catch (NotFoundException $e) {
90
+            $this->folder = $this->appData->newFolder('icons');
91
+        }
92
+    }
93
+
94
+    private function getIconsFromCss(string $css): array {
95
+        preg_match_all($this->iconVarRE, $css, $matches, PREG_SET_ORDER);
96
+        $icons = [];
97
+        foreach ($matches as $icon) {
98
+            $icons[$icon[1]] = $icon[2];
99
+        }
100
+
101
+        return $icons;
102
+    }
103
+
104
+    /**
105
+     * @param string $css
106
+     * @return string
107
+     * @throws NotFoundException
108
+     * @throws \OCP\Files\NotPermittedException
109
+     */
110
+    public function setIconsCss(string $css): string {
111
+        $cachedFile = $this->getCachedList();
112
+        if (!$cachedFile) {
113
+            $currentData = '';
114
+            $cachedFile = $this->folder->newFile($this->iconList);
115
+        } else {
116
+            $currentData = $cachedFile->getContent();
117
+        }
118
+
119
+        $cachedVarsCssFile = $this->getCachedCSS();
120
+        if (!$cachedVarsCssFile) {
121
+            $cachedVarsCssFile = $this->folder->newFile($this->fileName);
122
+        }
123
+
124
+        $icons = $this->getIconsFromCss($currentData . $css);
125
+
126
+        $data = '';
127
+        $list = '';
128
+        foreach ($icons as $icon => $url) {
129
+            $list .= "--$icon: url('$url');";
130
+            [$location,$color] = $this->parseUrl($url);
131
+            $svg = false;
132
+            if ($location !== '' && \file_exists($location)) {
133
+                $svg = \file_get_contents($location);
134
+            }
135
+            if ($svg === false) {
136
+                $this->logger->debug('Failed to get icon file ' . $location);
137
+                $data .= "--$icon: url('$url');";
138
+                continue;
139
+            }
140
+            $encode = base64_encode($this->colorizeSvg($svg, $color));
141
+            $data .= '--' . $icon . ': url(data:image/svg+xml;base64,' . $encode . ');';
142
+        }
143
+
144
+        if (\strlen($data) > 0 && \strlen($list) > 0) {
145
+            $data = ":root {\n$data\n}";
146
+            $cachedVarsCssFile->putContent($data);
147
+            $list = ":root {\n$list\n}";
148
+            $cachedFile->putContent($list);
149
+            $this->cachedList = null;
150
+            $this->cachedCss = null;
151
+        }
152
+
153
+        return preg_replace($this->iconVarRE, '', $css);
154
+    }
155
+
156
+    /**
157
+     * @param $url
158
+     * @return array
159
+     */
160
+    private function parseUrl($url): array {
161
+        $location = '';
162
+        $color = '';
163
+        $base = $this->getRoutePrefix() . '/svg/';
164
+        $cleanUrl = \substr($url, \strlen($base));
165
+        if (\strpos($url, $base . 'core') === 0) {
166
+            $cleanUrl = \substr($cleanUrl, \strlen('core'));
167
+            if (\preg_match('/\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
168
+                [,$cleanUrl,$color] = $matches;
169
+                $location = \OC::$SERVERROOT . '/core/img/' . $cleanUrl . '.svg';
170
+            }
171
+        } elseif (\strpos($url, $base) === 0) {
172
+            if (\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
173
+                [,$app,$cleanUrl, $color] = $matches;
174
+                $location = \OC_App::getAppPath($app) . '/img/' . $cleanUrl . '.svg';
175
+                if ($app === 'settings') {
176
+                    $location = \OC::$SERVERROOT . '/settings/img/' . $cleanUrl . '.svg';
177
+                }
178
+            }
179
+        }
180
+        return [
181
+            $location,
182
+            $color
183
+        ];
184
+    }
185
+
186
+    /**
187
+     * @param $svg
188
+     * @param $color
189
+     * @return string
190
+     */
191
+    public function colorizeSvg($svg, $color): string {
192
+        if (!preg_match('/^[0-9a-f]{3,6}$/i', $color)) {
193
+            // Prevent not-sane colors from being written into the SVG
194
+            $color = '000';
195
+        }
196
+
197
+        // add fill (fill is not present on black elements)
198
+        $fillRe = '/<((circle|rect|path)((?!fill)[a-z0-9 =".\-#():;,])+)\/>/mi';
199
+        $svg = preg_replace($fillRe, '<$1 fill="#' . $color . '"/>', $svg);
200
+
201
+        // replace any fill or stroke colors
202
+        $svg = preg_replace('/stroke="#([a-z0-9]{3,6})"/mi', 'stroke="#' . $color . '"', $svg);
203
+        $svg = preg_replace('/fill="#([a-z0-9]{3,6})"/mi', 'fill="#' . $color . '"', $svg);
204
+        return $svg;
205
+    }
206
+
207
+    private function getRoutePrefix() {
208
+        $frontControllerActive = (\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
209
+        $prefix = \OC::$WEBROOT . '/index.php';
210
+        if ($frontControllerActive) {
211
+            $prefix = \OC::$WEBROOT;
212
+        }
213
+        return $prefix;
214
+    }
215
+
216
+    /**
217
+     * Get icons css file
218
+     * @return ISimpleFile|boolean
219
+     */
220
+    public function getCachedCSS() {
221
+        try {
222
+            if (!$this->cachedCss) {
223
+                $this->cachedCss = $this->folder->getFile($this->fileName);
224
+            }
225
+            return $this->cachedCss;
226
+        } catch (NotFoundException $e) {
227
+            return false;
228
+        }
229
+    }
230
+
231
+    /**
232
+     * Get icon-vars list template
233
+     * @return ISimpleFile|boolean
234
+     */
235
+    public function getCachedList() {
236
+        try {
237
+            if (!$this->cachedList) {
238
+                $this->cachedList = $this->folder->getFile($this->iconList);
239
+            }
240
+            return $this->cachedList;
241
+        } catch (NotFoundException $e) {
242
+            return false;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Add the icons cache css into the header
248
+     */
249
+    public function injectCss() {
250
+        $mtime = $this->timeFactory->getTime();
251
+        $file = $this->getCachedList();
252
+        if ($file) {
253
+            $mtime = $file->getMTime();
254
+        }
255
+        // Only inject once
256
+        foreach (\OC_Util::$headers as $header) {
257
+            if (
258
+                array_key_exists('attributes', $header) &&
259
+                array_key_exists('href', $header['attributes']) &&
260
+                strpos($header['attributes']['href'], $this->fileName) !== false) {
261
+                return;
262
+            }
263
+        }
264
+        $linkToCSS = $this->urlGenerator->linkToRoute('core.Css.getCss', ['appName' => 'icons', 'fileName' => $this->fileName, 'v' => $mtime]);
265
+        \OC_Util::addHeader('link', ['rel' => 'stylesheet', 'href' => $linkToCSS], null, true);
266
+    }
267 267
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -121,24 +121,24 @@  discard block
 block discarded – undo
121 121
 			$cachedVarsCssFile = $this->folder->newFile($this->fileName);
122 122
 		}
123 123
 
124
-		$icons = $this->getIconsFromCss($currentData . $css);
124
+		$icons = $this->getIconsFromCss($currentData.$css);
125 125
 
126 126
 		$data = '';
127 127
 		$list = '';
128 128
 		foreach ($icons as $icon => $url) {
129 129
 			$list .= "--$icon: url('$url');";
130
-			[$location,$color] = $this->parseUrl($url);
130
+			[$location, $color] = $this->parseUrl($url);
131 131
 			$svg = false;
132 132
 			if ($location !== '' && \file_exists($location)) {
133 133
 				$svg = \file_get_contents($location);
134 134
 			}
135 135
 			if ($svg === false) {
136
-				$this->logger->debug('Failed to get icon file ' . $location);
136
+				$this->logger->debug('Failed to get icon file '.$location);
137 137
 				$data .= "--$icon: url('$url');";
138 138
 				continue;
139 139
 			}
140 140
 			$encode = base64_encode($this->colorizeSvg($svg, $color));
141
-			$data .= '--' . $icon . ': url(data:image/svg+xml;base64,' . $encode . ');';
141
+			$data .= '--'.$icon.': url(data:image/svg+xml;base64,'.$encode.');';
142 142
 		}
143 143
 
144 144
 		if (\strlen($data) > 0 && \strlen($list) > 0) {
@@ -160,20 +160,20 @@  discard block
 block discarded – undo
160 160
 	private function parseUrl($url): array {
161 161
 		$location = '';
162 162
 		$color = '';
163
-		$base = $this->getRoutePrefix() . '/svg/';
163
+		$base = $this->getRoutePrefix().'/svg/';
164 164
 		$cleanUrl = \substr($url, \strlen($base));
165
-		if (\strpos($url, $base . 'core') === 0) {
165
+		if (\strpos($url, $base.'core') === 0) {
166 166
 			$cleanUrl = \substr($cleanUrl, \strlen('core'));
167 167
 			if (\preg_match('/\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
168
-				[,$cleanUrl,$color] = $matches;
169
-				$location = \OC::$SERVERROOT . '/core/img/' . $cleanUrl . '.svg';
168
+				[,$cleanUrl, $color] = $matches;
169
+				$location = \OC::$SERVERROOT.'/core/img/'.$cleanUrl.'.svg';
170 170
 			}
171 171
 		} elseif (\strpos($url, $base) === 0) {
172 172
 			if (\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) {
173
-				[,$app,$cleanUrl, $color] = $matches;
174
-				$location = \OC_App::getAppPath($app) . '/img/' . $cleanUrl . '.svg';
173
+				[,$app, $cleanUrl, $color] = $matches;
174
+				$location = \OC_App::getAppPath($app).'/img/'.$cleanUrl.'.svg';
175 175
 				if ($app === 'settings') {
176
-					$location = \OC::$SERVERROOT . '/settings/img/' . $cleanUrl . '.svg';
176
+					$location = \OC::$SERVERROOT.'/settings/img/'.$cleanUrl.'.svg';
177 177
 				}
178 178
 			}
179 179
 		}
@@ -196,17 +196,17 @@  discard block
 block discarded – undo
196 196
 
197 197
 		// add fill (fill is not present on black elements)
198 198
 		$fillRe = '/<((circle|rect|path)((?!fill)[a-z0-9 =".\-#():;,])+)\/>/mi';
199
-		$svg = preg_replace($fillRe, '<$1 fill="#' . $color . '"/>', $svg);
199
+		$svg = preg_replace($fillRe, '<$1 fill="#'.$color.'"/>', $svg);
200 200
 
201 201
 		// replace any fill or stroke colors
202
-		$svg = preg_replace('/stroke="#([a-z0-9]{3,6})"/mi', 'stroke="#' . $color . '"', $svg);
203
-		$svg = preg_replace('/fill="#([a-z0-9]{3,6})"/mi', 'fill="#' . $color . '"', $svg);
202
+		$svg = preg_replace('/stroke="#([a-z0-9]{3,6})"/mi', 'stroke="#'.$color.'"', $svg);
203
+		$svg = preg_replace('/fill="#([a-z0-9]{3,6})"/mi', 'fill="#'.$color.'"', $svg);
204 204
 		return $svg;
205 205
 	}
206 206
 
207 207
 	private function getRoutePrefix() {
208 208
 		$frontControllerActive = (\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
209
-		$prefix = \OC::$WEBROOT . '/index.php';
209
+		$prefix = \OC::$WEBROOT.'/index.php';
210 210
 		if ($frontControllerActive) {
211 211
 			$prefix = \OC::$WEBROOT;
212 212
 		}
Please login to merge, or discard this patch.
lib/private/Activity/EventMerger.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -31,231 +31,231 @@
 block discarded – undo
31 31
 
32 32
 class EventMerger implements IEventMerger {
33 33
 
34
-	/** @var IL10N */
35
-	protected $l10n;
34
+    /** @var IL10N */
35
+    protected $l10n;
36 36
 
37
-	/**
38
-	 * @param IL10N $l10n
39
-	 */
40
-	public function __construct(IL10N $l10n) {
41
-		$this->l10n = $l10n;
42
-	}
37
+    /**
38
+     * @param IL10N $l10n
39
+     */
40
+    public function __construct(IL10N $l10n) {
41
+        $this->l10n = $l10n;
42
+    }
43 43
 
44
-	/**
45
-	 * Combines two events when possible to have grouping:
46
-	 *
47
-	 * Example1: Two events with subject '{user} created {file}' and
48
-	 * $mergeParameter file with different file and same user will be merged
49
-	 * to '{user} created {file1} and {file2}' and the childEvent on the return
50
-	 * will be set, if the events have been merged.
51
-	 *
52
-	 * Example2: Two events with subject '{user} created {file}' and
53
-	 * $mergeParameter file with same file and same user will be merged to
54
-	 * '{user} created {file1}' and the childEvent on the return will be set, if
55
-	 * the events have been merged.
56
-	 *
57
-	 * The following requirements have to be met, in order to be merged:
58
-	 * - Both events need to have the same `getApp()`
59
-	 * - Both events must not have a message `getMessage()`
60
-	 * - Both events need to have the same subject `getSubject()`
61
-	 * - Both events need to have the same object type `getObjectType()`
62
-	 * - The time difference between both events must not be bigger then 3 hours
63
-	 * - Only up to 5 events can be merged.
64
-	 * - All parameters apart from such starting with $mergeParameter must be
65
-	 *   the same for both events.
66
-	 *
67
-	 * @param string $mergeParameter
68
-	 * @param IEvent $event
69
-	 * @param IEvent|null $previousEvent
70
-	 * @return IEvent
71
-	 */
72
-	public function mergeEvents($mergeParameter, IEvent $event, IEvent $previousEvent = null) {
73
-		// No second event => can not combine
74
-		if (!$previousEvent instanceof IEvent) {
75
-			return $event;
76
-		}
44
+    /**
45
+     * Combines two events when possible to have grouping:
46
+     *
47
+     * Example1: Two events with subject '{user} created {file}' and
48
+     * $mergeParameter file with different file and same user will be merged
49
+     * to '{user} created {file1} and {file2}' and the childEvent on the return
50
+     * will be set, if the events have been merged.
51
+     *
52
+     * Example2: Two events with subject '{user} created {file}' and
53
+     * $mergeParameter file with same file and same user will be merged to
54
+     * '{user} created {file1}' and the childEvent on the return will be set, if
55
+     * the events have been merged.
56
+     *
57
+     * The following requirements have to be met, in order to be merged:
58
+     * - Both events need to have the same `getApp()`
59
+     * - Both events must not have a message `getMessage()`
60
+     * - Both events need to have the same subject `getSubject()`
61
+     * - Both events need to have the same object type `getObjectType()`
62
+     * - The time difference between both events must not be bigger then 3 hours
63
+     * - Only up to 5 events can be merged.
64
+     * - All parameters apart from such starting with $mergeParameter must be
65
+     *   the same for both events.
66
+     *
67
+     * @param string $mergeParameter
68
+     * @param IEvent $event
69
+     * @param IEvent|null $previousEvent
70
+     * @return IEvent
71
+     */
72
+    public function mergeEvents($mergeParameter, IEvent $event, IEvent $previousEvent = null) {
73
+        // No second event => can not combine
74
+        if (!$previousEvent instanceof IEvent) {
75
+            return $event;
76
+        }
77 77
 
78
-		// Different app => can not combine
79
-		if ($event->getApp() !== $previousEvent->getApp()) {
80
-			return $event;
81
-		}
78
+        // Different app => can not combine
79
+        if ($event->getApp() !== $previousEvent->getApp()) {
80
+            return $event;
81
+        }
82 82
 
83
-		// Message is set => can not combine
84
-		if ($event->getMessage() !== '' || $previousEvent->getMessage() !== '') {
85
-			return $event;
86
-		}
83
+        // Message is set => can not combine
84
+        if ($event->getMessage() !== '' || $previousEvent->getMessage() !== '') {
85
+            return $event;
86
+        }
87 87
 
88
-		// Different subject => can not combine
89
-		if ($event->getSubject() !== $previousEvent->getSubject()) {
90
-			return $event;
91
-		}
88
+        // Different subject => can not combine
89
+        if ($event->getSubject() !== $previousEvent->getSubject()) {
90
+            return $event;
91
+        }
92 92
 
93
-		// Different object type => can not combine
94
-		if ($event->getObjectType() !== $previousEvent->getObjectType()) {
95
-			return $event;
96
-		}
93
+        // Different object type => can not combine
94
+        if ($event->getObjectType() !== $previousEvent->getObjectType()) {
95
+            return $event;
96
+        }
97 97
 
98
-		// More than 3 hours difference => can not combine
99
-		if (abs($event->getTimestamp() - $previousEvent->getTimestamp()) > 3 * 60 * 60) {
100
-			return $event;
101
-		}
98
+        // More than 3 hours difference => can not combine
99
+        if (abs($event->getTimestamp() - $previousEvent->getTimestamp()) > 3 * 60 * 60) {
100
+            return $event;
101
+        }
102 102
 
103
-		// Other parameters are not the same => can not combine
104
-		try {
105
-			[$combined, $parameters] = $this->combineParameters($mergeParameter, $event, $previousEvent);
106
-		} catch (\UnexpectedValueException $e) {
107
-			return $event;
108
-		}
103
+        // Other parameters are not the same => can not combine
104
+        try {
105
+            [$combined, $parameters] = $this->combineParameters($mergeParameter, $event, $previousEvent);
106
+        } catch (\UnexpectedValueException $e) {
107
+            return $event;
108
+        }
109 109
 
110
-		try {
111
-			$newSubject = $this->getExtendedSubject($event->getRichSubject(), $mergeParameter, $combined);
112
-			$parsedSubject = $this->generateParsedSubject($newSubject, $parameters);
110
+        try {
111
+            $newSubject = $this->getExtendedSubject($event->getRichSubject(), $mergeParameter, $combined);
112
+            $parsedSubject = $this->generateParsedSubject($newSubject, $parameters);
113 113
 
114
-			$event->setRichSubject($newSubject, $parameters)
115
-				->setParsedSubject($parsedSubject)
116
-				->setChildEvent($previousEvent)
117
-				->setTimestamp(max($event->getTimestamp(), $previousEvent->getTimestamp()));
118
-		} catch (\UnexpectedValueException $e) {
119
-			return $event;
120
-		}
114
+            $event->setRichSubject($newSubject, $parameters)
115
+                ->setParsedSubject($parsedSubject)
116
+                ->setChildEvent($previousEvent)
117
+                ->setTimestamp(max($event->getTimestamp(), $previousEvent->getTimestamp()));
118
+        } catch (\UnexpectedValueException $e) {
119
+            return $event;
120
+        }
121 121
 
122
-		return $event;
123
-	}
122
+        return $event;
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $mergeParameter
127
-	 * @param IEvent $event
128
-	 * @param IEvent $previousEvent
129
-	 * @return array
130
-	 * @throws \UnexpectedValueException
131
-	 */
132
-	protected function combineParameters($mergeParameter, IEvent $event, IEvent $previousEvent) {
133
-		$params1 = $event->getRichSubjectParameters();
134
-		$params2 = $previousEvent->getRichSubjectParameters();
135
-		$params = [];
125
+    /**
126
+     * @param string $mergeParameter
127
+     * @param IEvent $event
128
+     * @param IEvent $previousEvent
129
+     * @return array
130
+     * @throws \UnexpectedValueException
131
+     */
132
+    protected function combineParameters($mergeParameter, IEvent $event, IEvent $previousEvent) {
133
+        $params1 = $event->getRichSubjectParameters();
134
+        $params2 = $previousEvent->getRichSubjectParameters();
135
+        $params = [];
136 136
 
137
-		$combined = 0;
137
+        $combined = 0;
138 138
 
139
-		// Check that all parameters from $event exist in $previousEvent
140
-		foreach ($params1 as $key => $parameter) {
141
-			if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
142
-				if (!$this->checkParameterAlreadyExits($params, $mergeParameter, $parameter)) {
143
-					$combined++;
144
-					$params[$mergeParameter . $combined] = $parameter;
145
-				}
146
-				continue;
147
-			}
139
+        // Check that all parameters from $event exist in $previousEvent
140
+        foreach ($params1 as $key => $parameter) {
141
+            if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
142
+                if (!$this->checkParameterAlreadyExits($params, $mergeParameter, $parameter)) {
143
+                    $combined++;
144
+                    $params[$mergeParameter . $combined] = $parameter;
145
+                }
146
+                continue;
147
+            }
148 148
 
149
-			if (!isset($params2[$key]) || $params2[$key] !== $parameter) {
150
-				// Parameter missing on $previousEvent or different => can not combine
151
-				throw new \UnexpectedValueException();
152
-			}
149
+            if (!isset($params2[$key]) || $params2[$key] !== $parameter) {
150
+                // Parameter missing on $previousEvent or different => can not combine
151
+                throw new \UnexpectedValueException();
152
+            }
153 153
 
154
-			$params[$key] = $parameter;
155
-		}
154
+            $params[$key] = $parameter;
155
+        }
156 156
 
157
-		// Check that all parameters from $previousEvent exist in $event
158
-		foreach ($params2 as $key => $parameter) {
159
-			if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
160
-				if (!$this->checkParameterAlreadyExits($params, $mergeParameter, $parameter)) {
161
-					$combined++;
162
-					$params[$mergeParameter . $combined] = $parameter;
163
-				}
164
-				continue;
165
-			}
157
+        // Check that all parameters from $previousEvent exist in $event
158
+        foreach ($params2 as $key => $parameter) {
159
+            if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
160
+                if (!$this->checkParameterAlreadyExits($params, $mergeParameter, $parameter)) {
161
+                    $combined++;
162
+                    $params[$mergeParameter . $combined] = $parameter;
163
+                }
164
+                continue;
165
+            }
166 166
 
167
-			if (!isset($params1[$key]) || $params1[$key] !== $parameter) {
168
-				// Parameter missing on $event or different => can not combine
169
-				throw new \UnexpectedValueException();
170
-			}
167
+            if (!isset($params1[$key]) || $params1[$key] !== $parameter) {
168
+                // Parameter missing on $event or different => can not combine
169
+                throw new \UnexpectedValueException();
170
+            }
171 171
 
172
-			$params[$key] = $parameter;
173
-		}
172
+            $params[$key] = $parameter;
173
+        }
174 174
 
175
-		return [$combined, $params];
176
-	}
175
+        return [$combined, $params];
176
+    }
177 177
 
178
-	/**
179
-	 * @param array[] $parameters
180
-	 * @param string $mergeParameter
181
-	 * @param array $parameter
182
-	 * @return bool
183
-	 */
184
-	protected function checkParameterAlreadyExits($parameters, $mergeParameter, $parameter) {
185
-		foreach ($parameters as $key => $param) {
186
-			if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
187
-				if ($param === $parameter) {
188
-					return true;
189
-				}
190
-			}
191
-		}
192
-		return false;
193
-	}
178
+    /**
179
+     * @param array[] $parameters
180
+     * @param string $mergeParameter
181
+     * @param array $parameter
182
+     * @return bool
183
+     */
184
+    protected function checkParameterAlreadyExits($parameters, $mergeParameter, $parameter) {
185
+        foreach ($parameters as $key => $param) {
186
+            if (preg_match('/^' . $mergeParameter . '(\d+)?$/', $key)) {
187
+                if ($param === $parameter) {
188
+                    return true;
189
+                }
190
+            }
191
+        }
192
+        return false;
193
+    }
194 194
 
195
-	/**
196
-	 * @param string $subject
197
-	 * @param string $parameter
198
-	 * @param int $counter
199
-	 * @return mixed
200
-	 */
201
-	protected function getExtendedSubject($subject, $parameter, $counter) {
202
-		switch ($counter) {
203
-			case 1:
204
-				$replacement = '{' . $parameter . '1}';
205
-				break;
206
-			case 2:
207
-				$replacement = $this->l10n->t(
208
-					'%1$s and %2$s',
209
-					['{' . $parameter . '2}', '{' . $parameter . '1}']
210
-				);
211
-				break;
212
-			case 3:
213
-				$replacement = $this->l10n->t(
214
-					'%1$s, %2$s and %3$s',
215
-					['{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
216
-				);
217
-				break;
218
-			case 4:
219
-				$replacement = $this->l10n->t(
220
-					'%1$s, %2$s, %3$s and %4$s',
221
-					['{' . $parameter . '4}', '{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
222
-				);
223
-				break;
224
-			case 5:
225
-				$replacement = $this->l10n->t(
226
-					'%1$s, %2$s, %3$s, %4$s and %5$s',
227
-					['{' . $parameter . '5}', '{' . $parameter . '4}', '{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
228
-				);
229
-				break;
230
-			default:
231
-				throw new \UnexpectedValueException();
232
-		}
195
+    /**
196
+     * @param string $subject
197
+     * @param string $parameter
198
+     * @param int $counter
199
+     * @return mixed
200
+     */
201
+    protected function getExtendedSubject($subject, $parameter, $counter) {
202
+        switch ($counter) {
203
+            case 1:
204
+                $replacement = '{' . $parameter . '1}';
205
+                break;
206
+            case 2:
207
+                $replacement = $this->l10n->t(
208
+                    '%1$s and %2$s',
209
+                    ['{' . $parameter . '2}', '{' . $parameter . '1}']
210
+                );
211
+                break;
212
+            case 3:
213
+                $replacement = $this->l10n->t(
214
+                    '%1$s, %2$s and %3$s',
215
+                    ['{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
216
+                );
217
+                break;
218
+            case 4:
219
+                $replacement = $this->l10n->t(
220
+                    '%1$s, %2$s, %3$s and %4$s',
221
+                    ['{' . $parameter . '4}', '{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
222
+                );
223
+                break;
224
+            case 5:
225
+                $replacement = $this->l10n->t(
226
+                    '%1$s, %2$s, %3$s, %4$s and %5$s',
227
+                    ['{' . $parameter . '5}', '{' . $parameter . '4}', '{' . $parameter . '3}', '{' . $parameter . '2}', '{' . $parameter . '1}']
228
+                );
229
+                break;
230
+            default:
231
+                throw new \UnexpectedValueException();
232
+        }
233 233
 
234
-		return str_replace(
235
-			'{' . $parameter . '}',
236
-			$replacement,
237
-			$subject
238
-		);
239
-	}
234
+        return str_replace(
235
+            '{' . $parameter . '}',
236
+            $replacement,
237
+            $subject
238
+        );
239
+    }
240 240
 
241
-	/**
242
-	 * @param string $subject
243
-	 * @param array[] $parameters
244
-	 * @return string
245
-	 */
246
-	protected function generateParsedSubject($subject, $parameters) {
247
-		$placeholders = $replacements = [];
248
-		foreach ($parameters as $placeholder => $parameter) {
249
-			$placeholders[] = '{' . $placeholder . '}';
250
-			if ($parameter['type'] === 'file') {
251
-				$replacements[] = trim($parameter['path'], '/');
252
-			} elseif (isset($parameter['name'])) {
253
-				$replacements[] = $parameter['name'];
254
-			} else {
255
-				$replacements[] = $parameter['id'];
256
-			}
257
-		}
241
+    /**
242
+     * @param string $subject
243
+     * @param array[] $parameters
244
+     * @return string
245
+     */
246
+    protected function generateParsedSubject($subject, $parameters) {
247
+        $placeholders = $replacements = [];
248
+        foreach ($parameters as $placeholder => $parameter) {
249
+            $placeholders[] = '{' . $placeholder . '}';
250
+            if ($parameter['type'] === 'file') {
251
+                $replacements[] = trim($parameter['path'], '/');
252
+            } elseif (isset($parameter['name'])) {
253
+                $replacements[] = $parameter['name'];
254
+            } else {
255
+                $replacements[] = $parameter['id'];
256
+            }
257
+        }
258 258
 
259
-		return str_replace($placeholders, $replacements, $subject);
260
-	}
259
+        return str_replace($placeholders, $replacements, $subject);
260
+    }
261 261
 }
Please login to merge, or discard this patch.
lib/private/Preview/HEIC.php 1 patch
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -40,106 +40,106 @@
 block discarded – undo
40 40
  * @package OC\Preview
41 41
  */
42 42
 class HEIC extends ProviderV2 {
43
-	/**
44
-	 * {@inheritDoc}
45
-	 */
46
-	public function getMimeType(): string {
47
-		return '/image\/hei(f|c)/';
48
-	}
49
-
50
-	/**
51
-	 * {@inheritDoc}
52
-	 */
53
-	public function isAvailable(\OCP\Files\FileInfo $file): bool {
54
-		return in_array('HEIC', \Imagick::queryFormats("HEI*"));
55
-	}
56
-
57
-	/**
58
-	 * {@inheritDoc}
59
-	 */
60
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
61
-		$tmpPath = $this->getLocalFile($file);
62
-
63
-		// Creates \Imagick object from the heic file
64
-		try {
65
-			$bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
66
-			$bp->setFormat('jpg');
67
-		} catch (\Exception $e) {
68
-			\OC::$server->getLogger()->logException($e, [
69
-				'message' => 'File: ' . $file->getPath() . ' Imagick says:',
70
-				'level' => ILogger::ERROR,
71
-				'app' => 'core',
72
-			]);
73
-			return null;
74
-		}
75
-
76
-		$this->cleanTmpFiles();
77
-
78
-		//new bitmap image object
79
-		$image = new \OC_Image();
80
-		$image->loadFromData($bp);
81
-		//check if image object is valid
82
-		return $image->valid() ? $image : null;
83
-	}
84
-
85
-	/**
86
-	 * Returns a preview of maxX times maxY dimensions in JPG format
87
-	 *
88
-	 *    * The default resolution is already 72dpi, no need to change it for a bitmap output
89
-	 *    * It's possible to have proper colour conversion using profileimage().
90
-	 *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
91
-	 *    * It's possible to Gamma-correct an image via gammaImage()
92
-	 *
93
-	 * @param string $tmpPath the location of the file to convert
94
-	 * @param int $maxX
95
-	 * @param int $maxY
96
-	 *
97
-	 * @return \Imagick
98
-	 */
99
-	private function getResizedPreview($tmpPath, $maxX, $maxY) {
100
-		$bp = new \Imagick();
101
-
102
-		// Layer 0 contains either the bitmap or a flat representation of all vector layers
103
-		$bp->readImage($tmpPath . '[0]');
104
-
105
-		$bp->setImageFormat('jpg');
106
-
107
-		$bp = $this->resize($bp, $maxX, $maxY);
43
+    /**
44
+     * {@inheritDoc}
45
+     */
46
+    public function getMimeType(): string {
47
+        return '/image\/hei(f|c)/';
48
+    }
49
+
50
+    /**
51
+     * {@inheritDoc}
52
+     */
53
+    public function isAvailable(\OCP\Files\FileInfo $file): bool {
54
+        return in_array('HEIC', \Imagick::queryFormats("HEI*"));
55
+    }
56
+
57
+    /**
58
+     * {@inheritDoc}
59
+     */
60
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
61
+        $tmpPath = $this->getLocalFile($file);
62
+
63
+        // Creates \Imagick object from the heic file
64
+        try {
65
+            $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
66
+            $bp->setFormat('jpg');
67
+        } catch (\Exception $e) {
68
+            \OC::$server->getLogger()->logException($e, [
69
+                'message' => 'File: ' . $file->getPath() . ' Imagick says:',
70
+                'level' => ILogger::ERROR,
71
+                'app' => 'core',
72
+            ]);
73
+            return null;
74
+        }
75
+
76
+        $this->cleanTmpFiles();
77
+
78
+        //new bitmap image object
79
+        $image = new \OC_Image();
80
+        $image->loadFromData($bp);
81
+        //check if image object is valid
82
+        return $image->valid() ? $image : null;
83
+    }
84
+
85
+    /**
86
+     * Returns a preview of maxX times maxY dimensions in JPG format
87
+     *
88
+     *    * The default resolution is already 72dpi, no need to change it for a bitmap output
89
+     *    * It's possible to have proper colour conversion using profileimage().
90
+     *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
91
+     *    * It's possible to Gamma-correct an image via gammaImage()
92
+     *
93
+     * @param string $tmpPath the location of the file to convert
94
+     * @param int $maxX
95
+     * @param int $maxY
96
+     *
97
+     * @return \Imagick
98
+     */
99
+    private function getResizedPreview($tmpPath, $maxX, $maxY) {
100
+        $bp = new \Imagick();
101
+
102
+        // Layer 0 contains either the bitmap or a flat representation of all vector layers
103
+        $bp->readImage($tmpPath . '[0]');
104
+
105
+        $bp->setImageFormat('jpg');
106
+
107
+        $bp = $this->resize($bp, $maxX, $maxY);
108 108
 		
109
-		return $bp;
110
-	}
111
-
112
-	/**
113
-	 * Returns a resized \Imagick object
114
-	 *
115
-	 * If you want to know more on the various methods available to resize an
116
-	 * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
117
-	 *
118
-	 * @param \Imagick $bp
119
-	 * @param int $maxX
120
-	 * @param int $maxY
121
-	 *
122
-	 * @return \Imagick
123
-	 */
124
-	private function resize($bp, $maxX, $maxY) {
125
-		[$previewWidth, $previewHeight] = array_values($bp->getImageGeometry());
126
-
127
-		// We only need to resize a preview which doesn't fit in the maximum dimensions
128
-		if ($previewWidth > $maxX || $previewHeight > $maxY) {
129
-			// If we want a small image (thumbnail) let's be most space- and time-efficient
130
-			if ($maxX <= 500 && $maxY <= 500) {
131
-				$bp->thumbnailImage($maxY, $maxX, true);
132
-				$bp->stripImage();
133
-			} else {
134
-				// A bigger image calls for some better resizing algorithm
135
-				// According to http://www.imagemagick.org/Usage/filter/#lanczos
136
-				// the catrom filter is almost identical to Lanczos2, but according
137
-				// to https://www.php.net/manual/en/imagick.resizeimage.php it is
138
-				// significantly faster
139
-				$bp->resizeImage($maxX, $maxY, \Imagick::FILTER_CATROM, 1, true);
140
-			}
141
-		}
142
-
143
-		return $bp;
144
-	}
109
+        return $bp;
110
+    }
111
+
112
+    /**
113
+     * Returns a resized \Imagick object
114
+     *
115
+     * If you want to know more on the various methods available to resize an
116
+     * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
117
+     *
118
+     * @param \Imagick $bp
119
+     * @param int $maxX
120
+     * @param int $maxY
121
+     *
122
+     * @return \Imagick
123
+     */
124
+    private function resize($bp, $maxX, $maxY) {
125
+        [$previewWidth, $previewHeight] = array_values($bp->getImageGeometry());
126
+
127
+        // We only need to resize a preview which doesn't fit in the maximum dimensions
128
+        if ($previewWidth > $maxX || $previewHeight > $maxY) {
129
+            // If we want a small image (thumbnail) let's be most space- and time-efficient
130
+            if ($maxX <= 500 && $maxY <= 500) {
131
+                $bp->thumbnailImage($maxY, $maxX, true);
132
+                $bp->stripImage();
133
+            } else {
134
+                // A bigger image calls for some better resizing algorithm
135
+                // According to http://www.imagemagick.org/Usage/filter/#lanczos
136
+                // the catrom filter is almost identical to Lanczos2, but according
137
+                // to https://www.php.net/manual/en/imagick.resizeimage.php it is
138
+                // significantly faster
139
+                $bp->resizeImage($maxX, $maxY, \Imagick::FILTER_CATROM, 1, true);
140
+            }
141
+        }
142
+
143
+        return $bp;
144
+    }
145 145
 }
Please login to merge, or discard this patch.
lib/private/Preview/MarkDown.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -28,117 +28,117 @@
 block discarded – undo
28 28
 use OCP\IImage;
29 29
 
30 30
 class MarkDown extends TXT {
31
-	/**
32
-	 * {@inheritDoc}
33
-	 */
34
-	public function getMimeType(): string {
35
-		return '/text\/(x-)?markdown/';
36
-	}
37
-
38
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
39
-		$content = $file->fopen('r');
40
-
41
-		if ($content === false) {
42
-			return null;
43
-		}
44
-
45
-		$content = stream_get_contents($content,3000);
46
-
47
-		//don't create previews of empty text files
48
-		if (trim($content) === '') {
49
-			return null;
50
-		}
51
-
52
-		// Merge text paragraph lines that might belong together
53
-		$content = preg_replace('/^(\s*)\*\s/mU', '$1- ', $content);
54
-
55
-		$content = preg_replace('/((?!^(\s*-|#)).*)(\w|\\|\.)(\r\n|\n|\r)(\w|\*)/mU', '$1 $3', $content);
56
-
57
-		// Remove markdown symbols that we cannot easily represent in rendered text in the preview
58
-		$content = preg_replace('/\*\*(.*)\*\*/U', '$1', $content);
59
-		$content = preg_replace('/\*(.*)\*/U', '$1', $content);
60
-		$content = preg_replace('/\_\_(.*)\_\_/U', '$1', $content);
61
-		$content = preg_replace('/\_(.*)\_/U', '$1', $content);
62
-		$content = preg_replace('/\~\~(.*)\~\~/U', '$1', $content);
63
-
64
-		$content = preg_replace('/\!?\[((.|\n)*)\]\((.*)\)/mU', '$1 ($3)', $content);
65
-		$content = preg_replace('/\n\n+/', "\n", $content);
66
-
67
-		$content = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $content);
68
-
69
-		$lines = preg_split("/\r\n|\n|\r/", $content);
70
-
71
-		// Define text size of text file preview
72
-		$fontSize = $maxX ? (int) ((1 / ($maxX >= 512 ? 60 : 40) * $maxX)) : 10;
73
-
74
-		$image = imagecreate($maxX, $maxY);
75
-		imagecolorallocate($image, 255, 255, 255);
76
-		$textColor = imagecolorallocate($image, 0, 0, 0);
77
-
78
-		$fontFile = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
79
-		$fontFileBold = __DIR__ . '/../../../core/fonts/NotoSans-Bold.ttf';
80
-
81
-		$canUseTTF = function_exists('imagettftext');
82
-
83
-		$textOffset = (int)min($maxX * 0.05, $maxY * 0.05);
84
-		$nextLineStart = 0;
85
-		$y = $textOffset;
86
-		foreach ($lines as $line) {
87
-			$actualFontSize = $fontSize;
88
-			if (mb_strpos($line, '# ') === 0) {
89
-				$actualFontSize *= 2;
90
-			}
91
-			if (mb_strpos($line, '## ') === 0) {
92
-				$actualFontSize *= 1.8;
93
-			}
94
-			if (mb_strpos($line, '### ') === 0) {
95
-				$actualFontSize *= 1.6;
96
-			}
97
-			if (mb_strpos($line, '#### ') === 0) {
98
-				$actualFontSize *= 1.4;
99
-			}
100
-			if (mb_strpos($line, '##### ') === 0) {
101
-				$actualFontSize *= 1.2;
102
-			}
103
-			if (mb_strpos($line, '###### ') === 0) {
104
-				$actualFontSize *= 1.1;
105
-			}
106
-
107
-			// Add spacing before headlines
108
-			if ($actualFontSize !== $fontSize && $y !== $textOffset) {
109
-				$y += (int)($actualFontSize * 2);
110
-			}
111
-
112
-			$x = $textOffset;
113
-			$y += (int)($nextLineStart + $actualFontSize);
114
-
115
-			if ($canUseTTF === true) {
116
-				$wordWrap = (int)((1 / $actualFontSize * 1.3) * $maxX);
117
-
118
-				// Get rid of markdown symbols that we still needed for the font size
119
-				$line = preg_replace('/^#*\s/', '', $line);
120
-
121
-				$wrappedText = wordwrap($line, $wordWrap,"\n");
122
-				$linesWrapped = count(explode("\n", $wrappedText));
123
-				imagettftext($image, $actualFontSize, 0, $x, $y, $textColor, $actualFontSize === $fontSize ? $fontFile : $fontFileBold, $wrappedText);
124
-				$nextLineStart = (int)($linesWrapped * ceil($actualFontSize * 2));
125
-				if ($actualFontSize !== $fontSize && $y !== $textOffset) {
126
-					$nextLineStart -= $actualFontSize;
127
-				}
128
-			} else {
129
-				$y -= $fontSize;
130
-				imagestring($image, 1, $x, $y, $line, $textColor);
131
-				$nextLineStart = $fontSize;
132
-			}
133
-
134
-			if ($y >= $maxY) {
135
-				break;
136
-			}
137
-		}
138
-
139
-		$imageObject = new \OC_Image();
140
-		$imageObject->setResource($image);
141
-
142
-		return $imageObject->valid() ? $imageObject : null;
143
-	}
31
+    /**
32
+     * {@inheritDoc}
33
+     */
34
+    public function getMimeType(): string {
35
+        return '/text\/(x-)?markdown/';
36
+    }
37
+
38
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
39
+        $content = $file->fopen('r');
40
+
41
+        if ($content === false) {
42
+            return null;
43
+        }
44
+
45
+        $content = stream_get_contents($content,3000);
46
+
47
+        //don't create previews of empty text files
48
+        if (trim($content) === '') {
49
+            return null;
50
+        }
51
+
52
+        // Merge text paragraph lines that might belong together
53
+        $content = preg_replace('/^(\s*)\*\s/mU', '$1- ', $content);
54
+
55
+        $content = preg_replace('/((?!^(\s*-|#)).*)(\w|\\|\.)(\r\n|\n|\r)(\w|\*)/mU', '$1 $3', $content);
56
+
57
+        // Remove markdown symbols that we cannot easily represent in rendered text in the preview
58
+        $content = preg_replace('/\*\*(.*)\*\*/U', '$1', $content);
59
+        $content = preg_replace('/\*(.*)\*/U', '$1', $content);
60
+        $content = preg_replace('/\_\_(.*)\_\_/U', '$1', $content);
61
+        $content = preg_replace('/\_(.*)\_/U', '$1', $content);
62
+        $content = preg_replace('/\~\~(.*)\~\~/U', '$1', $content);
63
+
64
+        $content = preg_replace('/\!?\[((.|\n)*)\]\((.*)\)/mU', '$1 ($3)', $content);
65
+        $content = preg_replace('/\n\n+/', "\n", $content);
66
+
67
+        $content = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $content);
68
+
69
+        $lines = preg_split("/\r\n|\n|\r/", $content);
70
+
71
+        // Define text size of text file preview
72
+        $fontSize = $maxX ? (int) ((1 / ($maxX >= 512 ? 60 : 40) * $maxX)) : 10;
73
+
74
+        $image = imagecreate($maxX, $maxY);
75
+        imagecolorallocate($image, 255, 255, 255);
76
+        $textColor = imagecolorallocate($image, 0, 0, 0);
77
+
78
+        $fontFile = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
79
+        $fontFileBold = __DIR__ . '/../../../core/fonts/NotoSans-Bold.ttf';
80
+
81
+        $canUseTTF = function_exists('imagettftext');
82
+
83
+        $textOffset = (int)min($maxX * 0.05, $maxY * 0.05);
84
+        $nextLineStart = 0;
85
+        $y = $textOffset;
86
+        foreach ($lines as $line) {
87
+            $actualFontSize = $fontSize;
88
+            if (mb_strpos($line, '# ') === 0) {
89
+                $actualFontSize *= 2;
90
+            }
91
+            if (mb_strpos($line, '## ') === 0) {
92
+                $actualFontSize *= 1.8;
93
+            }
94
+            if (mb_strpos($line, '### ') === 0) {
95
+                $actualFontSize *= 1.6;
96
+            }
97
+            if (mb_strpos($line, '#### ') === 0) {
98
+                $actualFontSize *= 1.4;
99
+            }
100
+            if (mb_strpos($line, '##### ') === 0) {
101
+                $actualFontSize *= 1.2;
102
+            }
103
+            if (mb_strpos($line, '###### ') === 0) {
104
+                $actualFontSize *= 1.1;
105
+            }
106
+
107
+            // Add spacing before headlines
108
+            if ($actualFontSize !== $fontSize && $y !== $textOffset) {
109
+                $y += (int)($actualFontSize * 2);
110
+            }
111
+
112
+            $x = $textOffset;
113
+            $y += (int)($nextLineStart + $actualFontSize);
114
+
115
+            if ($canUseTTF === true) {
116
+                $wordWrap = (int)((1 / $actualFontSize * 1.3) * $maxX);
117
+
118
+                // Get rid of markdown symbols that we still needed for the font size
119
+                $line = preg_replace('/^#*\s/', '', $line);
120
+
121
+                $wrappedText = wordwrap($line, $wordWrap,"\n");
122
+                $linesWrapped = count(explode("\n", $wrappedText));
123
+                imagettftext($image, $actualFontSize, 0, $x, $y, $textColor, $actualFontSize === $fontSize ? $fontFile : $fontFileBold, $wrappedText);
124
+                $nextLineStart = (int)($linesWrapped * ceil($actualFontSize * 2));
125
+                if ($actualFontSize !== $fontSize && $y !== $textOffset) {
126
+                    $nextLineStart -= $actualFontSize;
127
+                }
128
+            } else {
129
+                $y -= $fontSize;
130
+                imagestring($image, 1, $x, $y, $line, $textColor);
131
+                $nextLineStart = $fontSize;
132
+            }
133
+
134
+            if ($y >= $maxY) {
135
+                break;
136
+            }
137
+        }
138
+
139
+        $imageObject = new \OC_Image();
140
+        $imageObject->setResource($image);
141
+
142
+        return $imageObject->valid() ? $imageObject : null;
143
+    }
144 144
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 			return null;
43 43
 		}
44 44
 
45
-		$content = stream_get_contents($content,3000);
45
+		$content = stream_get_contents($content, 3000);
46 46
 
47 47
 		//don't create previews of empty text files
48 48
 		if (trim($content) === '') {
@@ -75,12 +75,12 @@  discard block
 block discarded – undo
75 75
 		imagecolorallocate($image, 255, 255, 255);
76 76
 		$textColor = imagecolorallocate($image, 0, 0, 0);
77 77
 
78
-		$fontFile = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
79
-		$fontFileBold = __DIR__ . '/../../../core/fonts/NotoSans-Bold.ttf';
78
+		$fontFile = __DIR__.'/../../../core/fonts/NotoSans-Regular.ttf';
79
+		$fontFileBold = __DIR__.'/../../../core/fonts/NotoSans-Bold.ttf';
80 80
 
81 81
 		$canUseTTF = function_exists('imagettftext');
82 82
 
83
-		$textOffset = (int)min($maxX * 0.05, $maxY * 0.05);
83
+		$textOffset = (int) min($maxX * 0.05, $maxY * 0.05);
84 84
 		$nextLineStart = 0;
85 85
 		$y = $textOffset;
86 86
 		foreach ($lines as $line) {
@@ -106,22 +106,22 @@  discard block
 block discarded – undo
106 106
 
107 107
 			// Add spacing before headlines
108 108
 			if ($actualFontSize !== $fontSize && $y !== $textOffset) {
109
-				$y += (int)($actualFontSize * 2);
109
+				$y += (int) ($actualFontSize * 2);
110 110
 			}
111 111
 
112 112
 			$x = $textOffset;
113
-			$y += (int)($nextLineStart + $actualFontSize);
113
+			$y += (int) ($nextLineStart + $actualFontSize);
114 114
 
115 115
 			if ($canUseTTF === true) {
116
-				$wordWrap = (int)((1 / $actualFontSize * 1.3) * $maxX);
116
+				$wordWrap = (int) ((1 / $actualFontSize * 1.3) * $maxX);
117 117
 
118 118
 				// Get rid of markdown symbols that we still needed for the font size
119 119
 				$line = preg_replace('/^#*\s/', '', $line);
120 120
 
121
-				$wrappedText = wordwrap($line, $wordWrap,"\n");
121
+				$wrappedText = wordwrap($line, $wordWrap, "\n");
122 122
 				$linesWrapped = count(explode("\n", $wrappedText));
123 123
 				imagettftext($image, $actualFontSize, 0, $x, $y, $textColor, $actualFontSize === $fontSize ? $fontFile : $fontFileBold, $wrappedText);
124
-				$nextLineStart = (int)($linesWrapped * ceil($actualFontSize * 2));
124
+				$nextLineStart = (int) ($linesWrapped * ceil($actualFontSize * 2));
125 125
 				if ($actualFontSize !== $fontSize && $y !== $textOffset) {
126 126
 					$nextLineStart -= $actualFontSize;
127 127
 				}
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 2 patches
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -34,82 +34,82 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 abstract class Office extends ProviderV2 {
37
-	private $cmd;
38
-
39
-	/**
40
-	 * {@inheritDoc}
41
-	 */
42
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
43
-		$this->initCmd();
44
-		if (is_null($this->cmd)) {
45
-			return null;
46
-		}
47
-
48
-		$absPath = $this->getLocalFile($file);
49
-
50
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
51
-
52
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
53
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
54
-
55
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
56
-
57
-		shell_exec($exec);
58
-
59
-		//create imagick object from png
60
-		$pngPreview = null;
61
-		try {
62
-			[$dirname, , , $filename] = array_values(pathinfo($absPath));
63
-			$pngPreview = $tmpDir . '/' . $filename . '.png';
64
-
65
-			$png = new \imagick($pngPreview . '[0]');
66
-			$png->setImageFormat('jpg');
67
-		} catch (\Exception $e) {
68
-			$this->cleanTmpFiles();
69
-			unlink($pngPreview);
70
-			\OC::$server->getLogger()->logException($e, [
71
-				'level' => ILogger::ERROR,
72
-				'app' => 'core',
73
-			]);
74
-			return null;
75
-		}
76
-
77
-		$image = new \OC_Image();
78
-		$image->loadFromData($png);
79
-
80
-		$this->cleanTmpFiles();
81
-		unlink($pngPreview);
82
-
83
-		if ($image->valid()) {
84
-			$image->scaleDownToFit($maxX, $maxY);
85
-
86
-			return $image;
87
-		}
88
-		return null;
89
-	}
90
-
91
-	private function initCmd() {
92
-		$cmd = '';
93
-
94
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
95
-		if (is_string($libreOfficePath)) {
96
-			$cmd = $libreOfficePath;
97
-		}
98
-
99
-		$whichLibreOffice = shell_exec('command -v libreoffice');
100
-		if ($cmd === '' && !empty($whichLibreOffice)) {
101
-			$cmd = 'libreoffice';
102
-		}
103
-
104
-		$whichOpenOffice = shell_exec('command -v openoffice');
105
-		if ($cmd === '' && !empty($whichOpenOffice)) {
106
-			$cmd = 'openoffice';
107
-		}
108
-
109
-		if ($cmd === '') {
110
-			$cmd = null;
111
-		}
112
-
113
-		$this->cmd = $cmd;
114
-	}
37
+    private $cmd;
38
+
39
+    /**
40
+     * {@inheritDoc}
41
+     */
42
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
43
+        $this->initCmd();
44
+        if (is_null($this->cmd)) {
45
+            return null;
46
+        }
47
+
48
+        $absPath = $this->getLocalFile($file);
49
+
50
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
51
+
52
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
53
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
54
+
55
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
56
+
57
+        shell_exec($exec);
58
+
59
+        //create imagick object from png
60
+        $pngPreview = null;
61
+        try {
62
+            [$dirname, , , $filename] = array_values(pathinfo($absPath));
63
+            $pngPreview = $tmpDir . '/' . $filename . '.png';
64
+
65
+            $png = new \imagick($pngPreview . '[0]');
66
+            $png->setImageFormat('jpg');
67
+        } catch (\Exception $e) {
68
+            $this->cleanTmpFiles();
69
+            unlink($pngPreview);
70
+            \OC::$server->getLogger()->logException($e, [
71
+                'level' => ILogger::ERROR,
72
+                'app' => 'core',
73
+            ]);
74
+            return null;
75
+        }
76
+
77
+        $image = new \OC_Image();
78
+        $image->loadFromData($png);
79
+
80
+        $this->cleanTmpFiles();
81
+        unlink($pngPreview);
82
+
83
+        if ($image->valid()) {
84
+            $image->scaleDownToFit($maxX, $maxY);
85
+
86
+            return $image;
87
+        }
88
+        return null;
89
+    }
90
+
91
+    private function initCmd() {
92
+        $cmd = '';
93
+
94
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
95
+        if (is_string($libreOfficePath)) {
96
+            $cmd = $libreOfficePath;
97
+        }
98
+
99
+        $whichLibreOffice = shell_exec('command -v libreoffice');
100
+        if ($cmd === '' && !empty($whichLibreOffice)) {
101
+            $cmd = 'libreoffice';
102
+        }
103
+
104
+        $whichOpenOffice = shell_exec('command -v openoffice');
105
+        if ($cmd === '' && !empty($whichOpenOffice)) {
106
+            $cmd = 'openoffice';
107
+        }
108
+
109
+        if ($cmd === '') {
110
+            $cmd = null;
111
+        }
112
+
113
+        $this->cmd = $cmd;
114
+    }
115 115
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -49,20 +49,20 @@
 block discarded – undo
49 49
 
50 50
 		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
51 51
 
52
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
52
+		$defaultParameters = ' -env:UserInstallation=file://'.escapeshellarg($tmpDir.'/owncloud-'.\OC_Util::getInstanceId().'/').' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
53 53
 		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
54 54
 
55
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
55
+		$exec = $this->cmd.$clParameters.escapeshellarg($tmpDir).' '.escapeshellarg($absPath);
56 56
 
57 57
 		shell_exec($exec);
58 58
 
59 59
 		//create imagick object from png
60 60
 		$pngPreview = null;
61 61
 		try {
62
-			[$dirname, , , $filename] = array_values(pathinfo($absPath));
63
-			$pngPreview = $tmpDir . '/' . $filename . '.png';
62
+			[$dirname,,, $filename] = array_values(pathinfo($absPath));
63
+			$pngPreview = $tmpDir.'/'.$filename.'.png';
64 64
 
65
-			$png = new \imagick($pngPreview . '[0]');
65
+			$png = new \imagick($pngPreview.'[0]');
66 66
 			$png->setImageFormat('jpg');
67 67
 		} catch (\Exception $e) {
68 68
 			$this->cleanTmpFiles();
Please login to merge, or discard this patch.
lib/private/Preview/Bitmap.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -39,81 +39,81 @@
 block discarded – undo
39 39
  */
40 40
 abstract class Bitmap extends ProviderV2 {
41 41
 
42
-	/**
43
-	 * {@inheritDoc}
44
-	 */
45
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
46
-		$tmpPath = $this->getLocalFile($file);
42
+    /**
43
+     * {@inheritDoc}
44
+     */
45
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
46
+        $tmpPath = $this->getLocalFile($file);
47 47
 
48
-		// Creates \Imagick object from bitmap or vector file
49
-		try {
50
-			$bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
-		} catch (\Exception $e) {
52
-			\OC::$server->getLogger()->logException($e, [
53
-				'message' => 'File: ' . $file->getPath() . ' Imagick says:',
54
-				'level' => ILogger::ERROR,
55
-				'app' => 'core',
56
-			]);
57
-			return null;
58
-		}
48
+        // Creates \Imagick object from bitmap or vector file
49
+        try {
50
+            $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
+        } catch (\Exception $e) {
52
+            \OC::$server->getLogger()->logException($e, [
53
+                'message' => 'File: ' . $file->getPath() . ' Imagick says:',
54
+                'level' => ILogger::ERROR,
55
+                'app' => 'core',
56
+            ]);
57
+            return null;
58
+        }
59 59
 
60
-		$this->cleanTmpFiles();
60
+        $this->cleanTmpFiles();
61 61
 
62
-		//new bitmap image object
63
-		$image = new \OC_Image();
64
-		$image->loadFromData($bp);
65
-		//check if image object is valid
66
-		return $image->valid() ? $image : null;
67
-	}
62
+        //new bitmap image object
63
+        $image = new \OC_Image();
64
+        $image->loadFromData($bp);
65
+        //check if image object is valid
66
+        return $image->valid() ? $image : null;
67
+    }
68 68
 
69
-	/**
70
-	 * Returns a preview of maxX times maxY dimensions in PNG format
71
-	 *
72
-	 *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
-	 *    * It's possible to have proper colour conversion using profileimage().
74
-	 *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
-	 *    * It's possible to Gamma-correct an image via gammaImage()
76
-	 *
77
-	 * @param string $tmpPath the location of the file to convert
78
-	 * @param int $maxX
79
-	 * @param int $maxY
80
-	 *
81
-	 * @return \Imagick
82
-	 */
83
-	private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
-		$bp = new Imagick();
69
+    /**
70
+     * Returns a preview of maxX times maxY dimensions in PNG format
71
+     *
72
+     *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
+     *    * It's possible to have proper colour conversion using profileimage().
74
+     *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
+     *    * It's possible to Gamma-correct an image via gammaImage()
76
+     *
77
+     * @param string $tmpPath the location of the file to convert
78
+     * @param int $maxX
79
+     * @param int $maxY
80
+     *
81
+     * @return \Imagick
82
+     */
83
+    private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
+        $bp = new Imagick();
85 85
 
86
-		// Layer 0 contains either the bitmap or a flat representation of all vector layers
87
-		$bp->readImage($tmpPath . '[0]');
86
+        // Layer 0 contains either the bitmap or a flat representation of all vector layers
87
+        $bp->readImage($tmpPath . '[0]');
88 88
 
89
-		$bp = $this->resize($bp, $maxX, $maxY);
89
+        $bp = $this->resize($bp, $maxX, $maxY);
90 90
 
91
-		$bp->setImageFormat('png');
91
+        $bp->setImageFormat('png');
92 92
 
93
-		return $bp;
94
-	}
93
+        return $bp;
94
+    }
95 95
 
96
-	/**
97
-	 * Returns a resized \Imagick object
98
-	 *
99
-	 * If you want to know more on the various methods available to resize an
100
-	 * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
-	 *
102
-	 * @param \Imagick $bp
103
-	 * @param int $maxX
104
-	 * @param int $maxY
105
-	 *
106
-	 * @return \Imagick
107
-	 */
108
-	private function resize($bp, $maxX, $maxY) {
109
-		[$previewWidth, $previewHeight] = array_values($bp->getImageGeometry());
96
+    /**
97
+     * Returns a resized \Imagick object
98
+     *
99
+     * If you want to know more on the various methods available to resize an
100
+     * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
+     *
102
+     * @param \Imagick $bp
103
+     * @param int $maxX
104
+     * @param int $maxY
105
+     *
106
+     * @return \Imagick
107
+     */
108
+    private function resize($bp, $maxX, $maxY) {
109
+        [$previewWidth, $previewHeight] = array_values($bp->getImageGeometry());
110 110
 
111
-		// We only need to resize a preview which doesn't fit in the maximum dimensions
112
-		if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
-			// TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
-			$bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
-		}
111
+        // We only need to resize a preview which doesn't fit in the maximum dimensions
112
+        if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
+            // TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
+            $bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
+        }
116 116
 
117
-		return $bp;
118
-	}
117
+        return $bp;
118
+    }
119 119
 }
Please login to merge, or discard this patch.
lib/private/Preview/ProviderV1Adapter.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,30 +35,30 @@
 block discarded – undo
35 35
 use OCP\Preview\IProviderV2;
36 36
 
37 37
 class ProviderV1Adapter implements IProviderV2 {
38
-	private $providerV1;
38
+    private $providerV1;
39 39
 
40
-	public function __construct(IProvider $providerV1) {
41
-		$this->providerV1 = $providerV1;
42
-	}
40
+    public function __construct(IProvider $providerV1) {
41
+        $this->providerV1 = $providerV1;
42
+    }
43 43
 
44
-	public function getMimeType(): string {
45
-		return (string)$this->providerV1->getMimeType();
46
-	}
44
+    public function getMimeType(): string {
45
+        return (string)$this->providerV1->getMimeType();
46
+    }
47 47
 
48
-	public function isAvailable(FileInfo $file): bool {
49
-		return (bool)$this->providerV1->isAvailable($file);
50
-	}
48
+    public function isAvailable(FileInfo $file): bool {
49
+        return (bool)$this->providerV1->isAvailable($file);
50
+    }
51 51
 
52
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
53
-		[$view, $path] = $this->getViewAndPath($file);
54
-		$thumbnail = $this->providerV1->getThumbnail($path, $maxX, $maxY, false, $view);
55
-		return $thumbnail === false ? null: $thumbnail;
56
-	}
52
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
53
+        [$view, $path] = $this->getViewAndPath($file);
54
+        $thumbnail = $this->providerV1->getThumbnail($path, $maxX, $maxY, false, $view);
55
+        return $thumbnail === false ? null: $thumbnail;
56
+    }
57 57
 
58
-	private function getViewAndPath(File $file) {
59
-		$view = new View($file->getParent()->getPath());
60
-		$path = $file->getName();
58
+    private function getViewAndPath(File $file) {
59
+        $view = new View($file->getParent()->getPath());
60
+        $path = $file->getName();
61 61
 
62
-		return [$view, $path];
63
-	}
62
+        return [$view, $path];
63
+    }
64 64
 }
Please login to merge, or discard this patch.