Completed
Pull Request — stable8.2 (#24656)
by Joas
12:22
created

OC_TemplateLayout::findStylesheetFiles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 12
loc 12
ccs 0
cts 10
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @author Adam Williamson <[email protected]>
4
 * @author Bart Visscher <[email protected]>
5
 * @author Bernhard Posselt <[email protected]>
6
 * @author Christopher Schäpers <[email protected]>
7
 * @author Clark Tomlinson <[email protected]>
8
 * @author Joas Schilling <[email protected]>
9
 * @author Jörn Friedrich Dreyer <[email protected]>
10
 * @author Lukas Reschke <[email protected]>
11
 * @author Michael Gapczynski <[email protected]>
12
 * @author Morris Jobke <[email protected]>
13
 * @author Remco Brenninkmeijer <[email protected]>
14
 * @author Robin Appelman <[email protected]>
15
 * @author Robin McCorkell <[email protected]>
16
 * @author Thomas Müller <[email protected]>
17
 * @author Victor Dubiniuk <[email protected]>
18
 *
19
 * @copyright Copyright (c) 2015, ownCloud, Inc.
20
 * @license AGPL-3.0
21
 *
22
 * This code is free software: you can redistribute it and/or modify
23
 * it under the terms of the GNU Affero General Public License, version 3,
24
 * as published by the Free Software Foundation.
25
 *
26
 * This program is distributed in the hope that it will be useful,
27
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29
 * GNU Affero General Public License for more details.
30
 *
31
 * You should have received a copy of the GNU Affero General Public License, version 3,
32
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
33
 *
34
 */
35
use Assetic\Asset\AssetCollection;
36
use Assetic\Asset\FileAsset;
37
use Assetic\AssetWriter;
38
use Assetic\Filter\CssImportFilter;
39
use Assetic\Filter\CssMinFilter;
40
use Assetic\Filter\CssRewriteFilter;
41
use Assetic\Filter\JSqueezeFilter;
42
use Assetic\Filter\SeparatorFilter;
43
44
/**
45
 * Copyright (c) 2012 Bart Visscher <[email protected]>
46
 * This file is licensed under the Affero General Public License version 3 or
47
 * later.
48
 * See the COPYING-README file.
49
 */
50
51
class OC_TemplateLayout extends OC_Template {
52
53
	private static $versionHash = '';
54
55
	/**
56
	 * @var \OCP\IConfig
57
	 */
58
	private $config;
59
60
	/**
61
	 * @param string $renderAs
62
	 * @param string $appId application id
63
	 */
64
	public function __construct( $renderAs, $appId = '' ) {
65
66
		// yes - should be injected ....
67
		$this->config = \OC::$server->getConfig();
68
69
		// Decide which page we show
70
		if($renderAs == 'user') {
71
			parent::__construct( 'core', 'layout.user' );
72
			if(in_array(OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
73
				$this->assign('bodyid', 'body-settings');
74
			}else{
75
				$this->assign('bodyid', 'body-user');
76
			}
77
78
			// Update notification
79
			if($this->config->getSystemValue('updatechecker', true) === true &&
80
				OC_User::isAdminUser(OC_User::getUser())) {
81
				$updater = new \OC\Updater(\OC::$server->getHTTPHelper(),
82
					\OC::$server->getConfig(), \OC::$server->getLogger());
83
				$data = $updater->check();
84
85
				if(isset($data['version']) && $data['version'] != '' and $data['version'] !== Array()) {
86
					$this->assign('updateAvailable', true);
87
					$this->assign('updateVersion', $data['versionstring']);
88
					$this->assign('updateLink', $data['web']);
89
					\OCP\Util::addScript('core', 'update-notification');
90
				} else {
91
					$this->assign('updateAvailable', false); // No update available or not an admin user
92
				}
93
			} else {
94
				$this->assign('updateAvailable', false); // Update check is disabled
95
			}
96
97
			// Add navigation entry
98
99
			$this->assign( 'application', '');
100
			$this->assign( 'appid', $appId );
101
			$navigation = OC_App::getNavigation();
102
			$this->assign( 'navigation', $navigation);
103
			$settingsNavigation = OC_App::getSettingsNavigation();
104
			$this->assign( 'settingsnavigation', $settingsNavigation);
105
			foreach($navigation as $entry) {
106
				if ($entry['active']) {
107
					$this->assign( 'application', $entry['name'] );
108
					break;
109
				}
110
			}
111
			
112
			foreach($settingsNavigation as $entry) {
113
				if ($entry['active']) {
114
					$this->assign( 'application', $entry['name'] );
115
					break;
116
				}
117
			}
118
			$userDisplayName = OC_User::getDisplayName();
119
			$appsMgmtActive = strpos(\OC::$server->getRequest()->getRequestUri(), \OC::$server->getURLGenerator()->linkToRoute('settings.AppSettings.viewApps')) === 0;
120
			if ($appsMgmtActive) {
121
				$l = \OC::$server->getL10N('lib');
122
				$this->assign('application', $l->t('Apps'));
123
			}
124
			$this->assign('user_displayname', $userDisplayName);
125
			$this->assign('user_uid', OC_User::getUser());
126
			$this->assign('appsmanagement_active', $appsMgmtActive);
127
			$this->assign('enableAvatars', $this->config->getSystemValue('enable_avatars', true) === true);
128
			$this->assign('userAvatarSet', \OC_Helper::userAvatarSet(OC_User::getUser()));
129
		} else if ($renderAs == 'error') {
130
			parent::__construct('core', 'layout.guest', '', false);
131
			$this->assign('bodyid', 'body-login');
132
		} else if ($renderAs == 'guest') {
133
			parent::__construct('core', 'layout.guest');
134
			$this->assign('bodyid', 'body-login');
135
		} else {
136
			parent::__construct('core', 'layout.base');
137
138
		}
139
		// Send the language to our layouts
140
		$this->assign('language', OC_L10N::findLanguage());
141
142
143
		if(empty(self::$versionHash)) {
144
			$v = OC_App::getAppVersions();
145
			$v['core'] = implode('.', \OC_Util::getVersion());
146
			self::$versionHash = md5(implode(',', $v));
147
		}
148
149
		$useAssetPipeline = self::isAssetPipelineEnabled();
150
		if ($useAssetPipeline) {
151
			$this->append( 'jsfiles', OC_Helper::linkToRoute('js_config', array('v' => self::$versionHash)));
152
			$this->generateAssets();
153
		} else {
154
			// Add the js files
155
			$jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
156
			$this->assign('jsfiles', array());
157
			if ($this->config->getSystemValue('installed', false) && $renderAs != 'error') {
158
				$this->append( 'jsfiles', OC_Helper::linkToRoute('js_config', array('v' => self::$versionHash)));
159
			}
160
			foreach($jsFiles as $info) {
161
				$web = $info[1];
162
				$file = $info[2];
163
				$this->append( 'jsfiles', $web.'/'.$file . '?v=' . self::$versionHash);
164
			}
165
166
			// Add the css files
167
			$cssFiles = self::findStylesheetFiles(OC_Util::$styles);
168
			$this->assign('cssfiles', array());
169
			foreach($cssFiles as $info) {
170
				$web = $info[1];
171
				$file = $info[2];
172
173
				$this->append( 'cssfiles', $web.'/'.$file . '?v=' . self::$versionHash);
174
			}
175
		}
176
	}
177
178
	/**
179
	 * @param array $styles
180
	 * @return array
181
	 */
182 View Code Duplication
	static public function findStylesheetFiles($styles) {
183
		// Read the selected theme from the config file
184
		$theme = OC_Util::getTheme();
185
186
		$locator = new \OC\Template\CSSResourceLocator(
187
			OC::$server->getLogger(),
188
			$theme,
189
			array( OC::$SERVERROOT => OC::$WEBROOT ),
190
			array( OC::$THIRDPARTYROOT => OC::$THIRDPARTYWEBROOT ));
191
		$locator->find($styles);
192
		return $locator->getResources();
193
	}
194
195
	/**
196
	 * @param array $scripts
197
	 * @return array
198
	 */
199 View Code Duplication
	static public function findJavascriptFiles($scripts) {
200
		// Read the selected theme from the config file
201
		$theme = OC_Util::getTheme();
202
203
		$locator = new \OC\Template\JSResourceLocator(
204
			OC::$server->getLogger(),
205
			$theme,
206
			array( OC::$SERVERROOT => OC::$WEBROOT ),
207
			array( OC::$THIRDPARTYROOT => OC::$THIRDPARTYWEBROOT ));
208
		$locator->find($scripts);
209
		return $locator->getResources();
210
	}
211
212
	public function generateAssets() {
213
		$assetDir = \OC::$server->getConfig()->getSystemValue('assetdirectory', \OC::$SERVERROOT);
214
		$jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
215
		$jsHash = self::hashFileNames($jsFiles);
216
217
		if (!file_exists("$assetDir/assets/$jsHash.js")) {
218
			$jsFiles = array_map(function ($item) {
219
				$root = $item[0];
220
				$file = $item[2];
221
				// no need to minifiy minified files
222
				if (substr($file, -strlen('.min.js')) === '.min.js') {
223
					return new FileAsset($root . '/' . $file, array(
224
						new SeparatorFilter(';')
225
					), $root, $file);
226
				}
227
				return new FileAsset($root . '/' . $file, array(
228
					new JSqueezeFilter(),
229
					new SeparatorFilter(';')
230
				), $root, $file);
231
			}, $jsFiles);
232
			$jsCollection = new AssetCollection($jsFiles);
233
			$jsCollection->setTargetPath("assets/$jsHash.js");
234
235
			$writer = new AssetWriter($assetDir);
236
			$writer->writeAsset($jsCollection);
237
		}
238
239
		$cssFiles = self::findStylesheetFiles(OC_Util::$styles);
240
		$cssHash = self::hashFileNames($cssFiles);
241
242
		if (!file_exists("$assetDir/assets/$cssHash.css")) {
243
			$cssFiles = array_map(function ($item) {
244
				$root = $item[0];
245
				$file = $item[2];
246
				$assetPath = $root . '/' . $file;
247
				$sourceRoot =  \OC::$SERVERROOT;
248
				$sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
249
				return new FileAsset(
250
					$assetPath,
251
					array(
252
						new CssRewriteFilter(),
253
						new CssMinFilter(),
254
						new CssImportFilter()
255
					),
256
					$sourceRoot,
257
					$sourcePath
258
				);
259
			}, $cssFiles);
260
			$cssCollection = new AssetCollection($cssFiles);
261
			$cssCollection->setTargetPath("assets/$cssHash.css");
262
263
			$writer = new AssetWriter($assetDir);
264
			$writer->writeAsset($cssCollection);
265
		}
266
267
		$this->append('jsfiles', OC_Helper::linkTo('assets', "$jsHash.js"));
268
		$this->append('cssfiles', OC_Helper::linkTo('assets', "$cssHash.css"));
269
	}
270
271
	/**
272
	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
273
	 * @param string $filePath Absolute path
274
	 * @return string Relative path
275
	 * @throws Exception If $filePath is not under \OC::$SERVERROOT
276
	 */
277
	public static function convertToRelativePath($filePath) {
278
		$relativePath = explode(\OC::$SERVERROOT, $filePath);
279
		if(count($relativePath) !== 2) {
280
			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
281
		}
282
283
		return $relativePath[1];
284
	}
285
286
	/**
287
	 * @param array $files
288
	 * @return string
289
	 */
290
291
	private static function hashFileNames($files) {
292
		foreach($files as $i => $file) {
293
			try {
294
				$files[$i] = self::convertToRelativePath($file[0]).'/'.$file[2];
295
			} catch (\Exception $e) {
296
				$files[$i] = $file[0].'/'.$file[2];
297
			}
298
		}
299
300
		sort($files);
301
		// include the apps' versions hash to invalidate the cached assets
302
		$files[] = self::$versionHash;
303
		return hash('md5', implode('', $files));
304
	}
305
}
306