Completed
Push — master ( 94ab2e...2cd79a )
by Lukas
12:30
created

TemplateLayout::findJavascriptFiles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 14
nc 1
nop 1
dl 0
loc 19
rs 9.4285
c 2
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Christopher Schäpers <[email protected]>
7
 * @author Clark Tomlinson <[email protected]>
8
 * @author Hendrik Leppelsack <[email protected]>
9
 * @author Joas Schilling <[email protected]>
10
 * @author Jörn Friedrich Dreyer <[email protected]>
11
 * @author Lukas Reschke <[email protected]>
12
 * @author Michael Gapczynski <[email protected]>
13
 * @author Morris Jobke <[email protected]>
14
 * @author Remco Brenninkmeijer <[email protected]>
15
 * @author Robin Appelman <[email protected]>
16
 * @author Robin McCorkell <[email protected]>
17
 * @author Roeland Jago Douma <[email protected]>
18
 * @author Thomas Müller <[email protected]>
19
 * @author Victor Dubiniuk <[email protected]>
20
 *
21
 * @license AGPL-3.0
22
 *
23
 * This code is free software: you can redistribute it and/or modify
24
 * it under the terms of the GNU Affero General Public License, version 3,
25
 * as published by the Free Software Foundation.
26
 *
27
 * This program is distributed in the hope that it will be useful,
28
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30
 * GNU Affero General Public License for more details.
31
 *
32
 * You should have received a copy of the GNU Affero General Public License, version 3,
33
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
34
 *
35
 */
36
namespace OC;
37
38
use OC\Template\JSCombiner;
39
use OC\Template\JSConfigHelper;
40
use OC\Template\SCSSCacher;
41
42
class TemplateLayout extends \OC_Template {
43
44
	private static $versionHash = '';
45
46
	/**
47
	 * @var \OCP\IConfig
48
	 */
49
	private $config;
50
51
	/**
52
	 * @param string $renderAs
53
	 * @param string $appId application id
54
	 */
55
	public function __construct( $renderAs, $appId = '' ) {
56
57
		// yes - should be injected ....
58
		$this->config = \OC::$server->getConfig();
59
60
		// Decide which page we show
61
		if($renderAs == 'user') {
62
			parent::__construct( 'core', 'layout.user' );
63
			if(in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
64
				$this->assign('bodyid', 'body-settings');
65
			}else{
66
				$this->assign('bodyid', 'body-user');
67
			}
68
69
			// Code integrity notification
70
			$integrityChecker = \OC::$server->getIntegrityCodeChecker();
71
			if(\OC_User::isAdminUser(\OC_User::getUser()) && $integrityChecker->isCodeCheckEnforced() && !$integrityChecker->hasPassedCheck()) {
72
				\OCP\Util::addScript('core', 'integritycheck-failed-notification');
73
			}
74
75
			// Add navigation entry
76
			$this->assign( 'application', '');
77
			$this->assign( 'appid', $appId );
78
			$navigation = \OC_App::getNavigation();
79
			$this->assign( 'navigation', $navigation);
80
			$navigation = \OC_App::getHeaderNavigation();
81
			$this->assign( 'headernavigation', $navigation);
82
			$settingsNavigation = \OC_App::getSettingsNavigation();
83
			$this->assign( 'settingsnavigation', $settingsNavigation);
84
			foreach($navigation as $entry) {
85
				if ($entry['active']) {
86
					$this->assign( 'application', $entry['name'] );
87
					break;
88
				}
89
			}
90
			
91
			foreach($settingsNavigation as $entry) {
92
				if ($entry['active']) {
93
					$this->assign( 'application', $entry['name'] );
94
					break;
95
				}
96
			}
97
			$userDisplayName = \OC_User::getDisplayName();
98
			$appsMgmtActive = strpos(\OC::$server->getRequest()->getRequestUri(), \OC::$server->getURLGenerator()->linkToRoute('settings.AppSettings.viewApps')) === 0;
99
			if ($appsMgmtActive) {
100
				$l = \OC::$server->getL10N('lib');
101
				$this->assign('application', $l->t('Apps'));
102
			}
103
			$this->assign('user_displayname', $userDisplayName);
104
			$this->assign('user_uid', \OC_User::getUser());
105
			$this->assign('appsmanagement_active', $appsMgmtActive);
106
107
			if (\OC_User::getUser() === false) {
108
				$this->assign('userAvatarSet', false);
109
			} else {
110
				$this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
111
				$this->assign('userAvatarVersion', \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
112
			}
113
114
		} else if ($renderAs == 'error') {
115
			parent::__construct('core', 'layout.guest', '', false);
116
			$this->assign('bodyid', 'body-login');
117
		} else if ($renderAs == 'guest') {
118
			parent::__construct('core', 'layout.guest');
119
			$this->assign('bodyid', 'body-login');
120
		} else {
121
			parent::__construct('core', 'layout.base');
122
123
		}
124
		// Send the language to our layouts
125
		$this->assign('language', \OC::$server->getL10NFactory()->findLanguage());
126
127
		if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
128
			if (empty(self::$versionHash)) {
129
				$v = \OC_App::getAppVersions();
130
				$v['core'] = implode('.', \OCP\Util::getVersion());
131
				self::$versionHash = md5(implode(',', $v));
132
			}
133
		} else {
134
			self::$versionHash = md5('not installed');
135
		}
136
137
		// Add the js files
138
		$jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
139
		$this->assign('jsfiles', array());
140
		if ($this->config->getSystemValue('installed', false) && $renderAs != 'error') {
141
			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
142
				$jsConfigHelper = new JSConfigHelper(
143
					\OC::$server->getL10N('core'),
144
					\OC::$server->getThemingDefaults(),
145
					\OC::$server->getAppManager(),
146
					\OC::$server->getSession(),
147
					\OC::$server->getUserSession()->getUser(),
148
					\OC::$server->getConfig(),
149
					\OC::$server->getGroupManager(),
150
					\OC::$server->getIniWrapper(),
151
					\OC::$server->getURLGenerator()
152
				);
153
				$this->assign('inline_ocjs', $jsConfigHelper->getConfig());
154
			} else {
155
				$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
156
			}
157
		}
158
		foreach($jsFiles as $info) {
159
			$web = $info[1];
160
			$file = $info[2];
161
			$this->append( 'jsfiles', $web.'/'.$file . $this->getVersionHashSuffix() );
162
		}
163
164
		try {
165
			$pathInfo = \OC::$server->getRequest()->getPathInfo();
166
		} catch (\Exception $e) {
167
			$pathInfo = '';
168
		}
169
170
		// Do not initialise scss appdata until we have a fully installed instance
171
		// Do not load scss for update, errors, installation or login page
172
		if(\OC::$server->getSystemConfig()->getValue('installed', false)
173
			&& !\OCP\Util::needUpgrade()
174
			&& $pathInfo !== ''
175
			&& !preg_match('/^\/login/', $pathInfo)) {
176
			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
177
		} else {
178
			// If we ignore the scss compiler,
179
			// we need to load the guest css fallback
180
			\OC_Util::addStyle('guest');
181
			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
182
		}
183
184
		$this->assign('cssfiles', array());
185
		$this->assign('printcssfiles', []);
186
		$this->assign('versionHash', self::$versionHash);
187
		foreach($cssFiles as $info) {
188
			$web = $info[1];
189
			$file = $info[2];
190
191
			if (substr($file, -strlen('print.css')) === 'print.css') {
192
				$this->append( 'printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix() );
193
			} else {
194
				$this->append( 'cssfiles', $web.'/'.$file . $this->getVersionHashSuffix()  );
195
			}
196
		}
197
	}
198
199
	protected function getVersionHashSuffix() {
200
		if(\OC::$server->getConfig()->getSystemValue('debug', false)) {
201
			// allows chrome workspace mapping in debug mode
202
			return "";
203
		}
204
205
		return '?v=' . self::$versionHash;
206
	}
207
208
	/**
209
	 * @param array $styles
210
	 * @return array
211
	 */
212
	static public function findStylesheetFiles($styles, $compileScss = true) {
213
		// Read the selected theme from the config file
214
		$theme = \OC_Util::getTheme();
215
216
		if($compileScss) {
217
			/** @var \OC\Memcache\Factory $cache */
218
			$cache = \OC::$server->query('MemCacheFactory');
219
			$SCSSCacher = new SCSSCacher(
220
				\OC::$server->getLogger(),
221
				\OC::$server->getAppDataDir('css'),
222
				\OC::$server->getURLGenerator(),
223
				\OC::$server->getConfig(),
224
				\OC::$SERVERROOT,
225
				$cache->createLocal('SCSS')
226
			);
227
		} else {
228
			$SCSSCacher = null;
229
		}
230
231
		$locator = new \OC\Template\CSSResourceLocator(
232
			\OC::$server->getLogger(),
233
			$theme,
234
			array( \OC::$SERVERROOT => \OC::$WEBROOT ),
235
			array( \OC::$SERVERROOT => \OC::$WEBROOT ),
236
			$SCSSCacher);
0 ignored issues
show
Bug introduced by
It seems like $SCSSCacher defined by null on line 228 can be null; however, OC\Template\CSSResourceLocator::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
237
		$locator->find($styles);
238
		return $locator->getResources();
239
	}
240
241
	/**
242
	 * @param array $scripts
243
	 * @return array
244
	 */
245
	static public function findJavascriptFiles($scripts) {
246
		// Read the selected theme from the config file
247
		$theme = \OC_Util::getTheme();
248
249
		$locator = new \OC\Template\JSResourceLocator(
250
			\OC::$server->getLogger(),
251
			$theme,
252
			array( \OC::$SERVERROOT => \OC::$WEBROOT ),
253
			array( \OC::$SERVERROOT => \OC::$WEBROOT ),
254
			new JSCombiner(
255
				\OC::$server->getAppDataDir('js'),
256
				\OC::$server->getURLGenerator(),
257
				\OC::$server->getMemCacheFactory()->create('JS'),
258
				\OC::$server->getSystemConfig()
259
			)
260
			);
261
		$locator->find($scripts);
262
		return $locator->getResources();
263
	}
264
265
	/**
266
	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
267
	 * @param string $filePath Absolute path
268
	 * @return string Relative path
269
	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
270
	 */
271
	public static function convertToRelativePath($filePath) {
272
		$relativePath = explode(\OC::$SERVERROOT, $filePath);
273
		if(count($relativePath) !== 2) {
274
			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
275
		}
276
277
		return $relativePath[1];
278
	}
279
}
280