-
Notifications
You must be signed in to change notification settings - Fork 988
/
LSYii_ClientScript.php
569 lines (507 loc) · 21.5 KB
/
LSYii_ClientScript.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
*/
/*
* NOTE 1 : To refresh the assets, the base directory of the template must be updated.
* NOTE 2: By default, Asset Manager is off when debug mode is on.
*
* Developers should then think about :
* 1. refreshing their brower's cache (ctrl + F5) to see their changes
* 2. update the config.xml last_update before pushing, to be sure that end users will have the new version
*
*
* For more detail, see :
* http://www.yiiframework.com/doc/api/1.1/CClientScript#addPackage-detail
* http://www.yiiframework.com/doc/api/1.1/YiiBase#setPathOfAlias-detail
*/
class LSYii_ClientScript extends CClientScript
{
const POS_POSTSCRIPT = 5;
/**
* cssFiles is protected on CClientScript. It can be useful to access it for debugin purpose
* @return array
*/
public function getCssFiles()
{
return $this->cssFiles;
}
public function getScriptFiles()
{
return $this->scriptFiles;
}
/**
* cssFicoreScripts is protected on CClientScript. It can be useful to access it for debugin purpose
* @return array
*/
public function getCoreScripts()
{
return $this->coreScripts;
}
/**
* Remove a package from coreScript.
* It can be useful when mixing backend/frontend rendering (see: template editor)
*
* @var string $sName of the package to remove
*/
public function unregisterPackage($sName)
{
if (!empty($this->coreScripts[$sName])) {
unset($this->coreScripts[$sName]);
}
}
public function unregisterScriptFile($sName)
{
if (!empty($this->scriptFiles[0]["$sName"])) {
unset($this->scriptFiles[0]["$sName"]);
}
}
/**
* Check if a file is in a given package
* @var $sPackageName string name of the package
* @var $sType string css/js
* @var $sFileName string name of the file to remove
* @return boolean
*/
public function IsFileInPackage($sPackageName, $sType, $sFileName)
{
if (!empty(Yii::app()->clientScript->packages[$sPackageName])) {
if (!empty(Yii::app()->clientScript->packages[$sPackageName][$sType])) {
$key = array_search($sFileName, Yii::app()->clientScript->packages[$sPackageName][$sType]);
return $key !== false;
}
}
return false;
}
/**
* Add a file to a given package
*
* @var $sPackageName string name of the package
* @var $sType string css/js
* @var $sFileName string name of the file to add
*/
public function addFileToPackage($sPackageName, $sType, $sFileName)
{
if (!empty(Yii::app()->clientScript->packages[$sPackageName])) {
if (!empty(Yii::app()->clientScript->packages[$sPackageName][$sType])) {
Yii::app()->clientScript->packages[$sPackageName][$sType][] = $sFileName;
}
}
}
/**
* Remove a file from a given package
*
* @var $sPackageName string name of the package
* @var $sType string css/js
* @var $sFileName string name of the file to remove
*/
public function removeFileFromPackage($sPackageName, $sType, $sFileName)
{
if (!empty(Yii::app()->clientScript->packages[$sPackageName])) {
if (!empty(Yii::app()->clientScript->packages[$sPackageName][$sType])) {
$key = array_search($sFileName, Yii::app()->clientScript->packages[$sPackageName][$sType]);
unset(Yii::app()->clientScript->packages[$sPackageName][$sType][$key]);
}
}
}
/**
* In LimeSurvey, if debug mode is OFF we use the asset manager (so participants never needs to update their webbrowser cache).
* If debug mode is ON, we don't use the asset manager, so developpers just have to refresh their browser cache to reload the new scripts.
* To make developper life easier, if they want to register a single script file, they can use App()->getClientScript()->registerScriptFile({url to script file})
* if the file exist in local file system and debug mode is off, it will find the path to the file, and it will publish it via the asset manager
* @param string $url
* @param string $position
* @param array $htmlOptions
* @return void|static
*/
public function registerScriptFile($url, $position = null, array $htmlOptions = array())
{
// If possible, we publish the asset: it moves the file to the tmp/asset directory and return the url to access it
if ((!YII_DEBUG || Yii::app()->getConfig('use_asset_manager'))) {
$aUrlDatas = $this->analyzeUrl($url);
if ($aUrlDatas['toPublish']) {
$url = App()->getAssetManager()->publish($aUrlDatas['sPathToFile']);
}
}
parent::registerScriptFile($url, $position, $htmlOptions); // We publish the script
}
public function registerCssFile($url, $media = '')
{
// If possible, we publish the asset: it moves the file to the tmp/asset directory and return the url to access it
if ((!YII_DEBUG || Yii::app()->getConfig('use_asset_manager'))) {
$aUrlDatas = $this->analyzeUrl($url);
if ($aUrlDatas['toPublish']) {
$url = App()->getAssetManager()->publish($aUrlDatas['sPathToFile']);
}
}
parent::registerCssFile($url, $media); // We publish the script
}
/**
* The method will first check if a devbaseUrl parameter is provided,
* so when debug mode is on, it doens't use the asset manager
* @param string $name
* @return void|static
*/
public function registerPackage($name)
{
if (!YII_DEBUG || Yii::app()->getConfig('use_asset_manager')) {
parent::registerPackage($name);
} else {
// We first convert the current package to devBaseUrl
$this->convertDevBaseUrl($name);
// Then we do the same for all its dependencies
$aDepends = $this->getRecursiveDependencies($name);
foreach ($aDepends as $package) {
$this->convertDevBaseUrl($package);
}
parent::registerPackage($name);
}
}
/**
* Return a list of all the recursive dependencies of a packages
* eg: If a package A depends on B, and B depends on C, getRecursiveDependencies('A') will return {B,C}
* @param string $sPackageName
*/
public function getRecursiveDependencies($sPackageName)
{
$aPackages = Yii::app()->clientScript->packages;
if (array_key_exists('depends', $aPackages[$sPackageName])) {
$aDependencies = $aPackages[$sPackageName]['depends'];
foreach ($aDependencies as $sDpackageName) {
if ($aPackages[$sPackageName]['depends']) {
$aRDependencies = $this->getRecursiveDependencies($sDpackageName); // Recursive call
if (is_array($aRDependencies)) {
$aDependencies = array_unique(array_merge($aDependencies, $aRDependencies));
}
}
}
return $aDependencies;
}
return array();
}
/**
* Convert one package to baseUrl
* Overwrite the package definition using a base url instead of a base path
* The package must have a devBaseUrl, else it will remain unchanged (for core/external package); so third party package are not concerned
* @param string $package
*/
private function convertDevBaseUrl($package)
{
// We retreive the old package
$aOldPackageDefinition = Yii::app()->clientScript->packages[$package];
// If it has an entry 'devBaseUrl', we use it to replace basePath (it will turn off asset manager for this package)
if (is_array($aOldPackageDefinition) && array_key_exists('devBaseUrl', $aOldPackageDefinition)) {
$aNewPackageDefinition = array();
// Take all the values of the oldPackage to add it to the new one
foreach ($aOldPackageDefinition as $key => $value) {
// Remove basePath
if ($key != 'basePath') {
// Convert devBaseUrl
if ($key == 'devBaseUrl') {
$aNewPackageDefinition['baseUrl'] = $value;
} else {
$aNewPackageDefinition[$key] = $value;
}
}
}
Yii::app()->clientScript->addPackage($package, $aNewPackageDefinition);
}
}
/**
* This function will analyze the url of a file (css/js) to register
* It will check if it can be published via the asset manager and if so will retreive its path
* @param $sUrl
* @return array
*/
private function analyzeUrl($sUrl)
{
$sCleanUrl = str_replace(Yii::app()->baseUrl, '', $sUrl); // we remove the base url to be sure that the first parameter is the one we want
$aUrlParams = explode('/', $sCleanUrl);
$sFilePath = Yii::app()->getConfig('rootdir').$sCleanUrl;
$sPath = '';
// TODO: check if tmp directory can be named differently via config
if ($aUrlParams[1] == 'tmp') {
$sType = 'published';
} else {
if (file_exists($sFilePath)) {
$sType = 'toPublish';
$sPath = $sFilePath;
} else {
$sType = 'cantPublish';
}
}
return array('toPublish'=>($sType == 'toPublish'), 'sPathToFile' => $sPath);
}
/**
* Registers a script package that is listed in {@link packages}.
* @param string $name the name of the script package.
* @return static the CClientScript object itself (to support method chaining, available since version 1.1.5).
* @see renderCoreScript
* @throws CException
*/
public function registerPackageScriptOnPosition($name, $position)
{
if (isset($this->coreScripts[$name])) {
$this->coreScripts[$name]['position'] = $position;
return $this;
}
if (isset($this->packages[$name])) {
$package = $this->packages[$name];
} else {
if ($this->corePackages === null) {
$this->corePackages = require(YII_PATH.'/web/js/packages.php');
}
if (isset($this->corePackages[$name])) {
$package = $this->corePackages[$name];
}
}
if (isset($package)) {
$package['position'] = $position;
if (!empty($package['depends'])) {
foreach ($package['depends'] as $p) {
$this->registerPackageScriptOnPosition($p, $position);
}
}
$this->coreScripts[$name] = $package;
$this->hasScripts = true;
$params = func_get_args();
$this->recordCachingAction('clientScript', 'registerPackageScriptOnPosition', $params);
} elseif (YII_DEBUG) {
throw new CException('There is no LSYii_ClientScript package: '.$name);
} else {
Yii::log('There is no LSYii_ClientScript package: '.$name, CLogger::LEVEL_WARNING, 'system.web.LSYii_ClientScript');
}
return $this;
}
/**
* Renders the specified core javascript library.
*/
public function renderCoreScripts()
{
if ($this->coreScripts === null) {
return;
}
$cssFiles = array();
$jsFiles = array();
$jsFilesPositioned = array();
foreach ($this->coreScripts as $name=>$package) {
$baseUrl = $this->getPackageBaseUrl($name);
if (!empty($package['js'])) {
foreach ($package['js'] as $js) {
if (isset($package['position'])) {
$jsFilesPositioned[$package['position']][$baseUrl.'/'.$js] = $baseUrl.'/'.$js;
} else {
$jsFiles[$baseUrl.'/'.$js] = $baseUrl.'/'.$js;
}
}
}
if (!empty($package['css'])) {
foreach ($package['css'] as $css) {
$cssFiles[$baseUrl.'/'.$css] = '';
}
}
}
// merge in place
if ($cssFiles !== array()) {
foreach ($this->cssFiles as $cssFile=>$media) {
$cssFiles[$cssFile] = $media;
}
$this->cssFiles = $cssFiles;
}
if ($jsFiles !== array()) {
if (isset($this->scriptFiles[$this->coreScriptPosition])) {
foreach ($this->scriptFiles[$this->coreScriptPosition] as $url => $value) {
$jsFiles[$url] = $value;
}
}
$this->scriptFiles[$this->coreScriptPosition] = $jsFiles;
}
if ($jsFilesPositioned !== array()) {
foreach ($jsFilesPositioned as $position=>$fileArray) {
if (isset($this->scriptFiles[$position])) {
foreach ($this->scriptFiles[$position] as $url => $value) {
$fileArray[$url] = $value;
}
}
$this->scriptFiles[$position] = $fileArray;
}
}
}
/**
* Inserts the scripts in the head section.
* @param string $output the output to be inserted with scripts.
*/
public function renderHead(&$output)
{
$html = '';
foreach ($this->metaTags as $meta) {
$html .= CHtml::metaTag($meta['content'], null, null, $meta)."\n";
}
foreach ($this->linkTags as $link) {
$html .= CHtml::linkTag(null, null, null, null, $link)."\n";
}
foreach ($this->cssFiles as $url=>$media) {
$html .= CHtml::cssFile($url, $media)."\n";
}
if ($this->enableJavaScript) {
if (isset($this->scriptFiles[self::POS_HEAD])) {
foreach ($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue) {
if (is_array($scriptFileValue)) {
$scriptFileValue['class'] = isset($scriptFileValue['class']) ? $scriptFileValue['class']." headScriptTag" : "headScriptTag";
$html .= CHtml::scriptFile($scriptFileValueUrl, $scriptFileValue)."\n";
} else {
$html .= CHtml::scriptFile($scriptFileValueUrl, array('class' => 'headScriptTag'))."\n";
}
}
}
//############################################################################################
//###### This has to correctly resolved by either updateing jquery ui or removing it! ######
//############################################################################################
$html .= "<script> jQuery.migrateMute = true; </script>";
if (isset($this->scripts[self::POS_HEAD])) {
$html .= $this->renderScriptBatch($this->scripts[self::POS_HEAD]);
}
}
if ($html !== '') {
$count = 0;
$output = preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is', '<###head###>$1', $output, 1, $count);
if ($count) {
$output = str_replace('<###head###>', $html, $output);
} else {
$output = $html.$output;
}
}
}
/**
* Inserts the scripts at the beginning of the body section.
* This is overwriting the core method and is exactly the same except the marked parts
* @param string $output the output to be inserted with scripts.
*/
public function renderBodyBegin(&$output)
{
$html = '';
if (isset($this->scriptFiles[self::POS_BEGIN])) {
foreach ($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue) {
if (is_array($scriptFileValue)) {
$html .= CHtml::scriptFile($scriptFileUrl, $scriptFileValue)."\n";
} else {
$html .= CHtml::scriptFile($scriptFileUrl)."\n";
}
}
}
if (isset($this->scripts[self::POS_BEGIN])) {
$html .= $this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
}
if ($html !== '') {
$count = 0;
if (preg_match('/<###begin###>/', $output)) {
$count = 1;
} else {
$output = preg_replace('/(<body\b[^>]*>)/is', '$1<###begin###>', $output, 1, $count);
}
if ($count) {
$output = str_replace('<###begin###>', $html, $output);
} else {
$output = $html.$output;
}
} else {
$output = preg_replace('/<###begin###>/', '', $output, 1);
}
}
/**
* Inserts the scripts at the end of the body section.
* This is overwriting the core method and is exactly the same except the marked parts
* @param string $output the output to be inserted with scripts.
*/
public function renderBodyEnd(&$output)
{
if (!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END]) && !isset($this->scripts[self::POS_READY])
&& !isset($this->scripts[self::POS_LOAD]) && !isset($this->scripts[self::POS_POSTSCRIPT])) {
str_replace('<###end###>', '', $output);
return;
}
$fullPage = 0;
if (preg_match('/<###end###>/', $output)) {
$fullPage = 1;
} else {
$output = preg_replace('/(<\\/body\s*>)/is', '<###end###>$1', $output, 1, $fullPage);
}
$html = '';
if (isset($this->scriptFiles[self::POS_END])) {
foreach ($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue) {
if (is_array($scriptFileValue)) {
$html .= CHtml::scriptFile($scriptFileUrl, $scriptFileValue)."\n";
} else {
$html .= CHtml::scriptFile($scriptFileUrl)."\n";
}
}
}
$scripts = isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
if (isset($this->scripts[self::POS_READY])) {
if ($fullPage) {
$scripts[] = "jQuery(function($) {\n".implode("\n", $this->scripts[self::POS_READY])."\n});";
} else {
$scripts[] = implode("\n", $this->scripts[self::POS_READY]);
}
}
if (isset($this->scripts[self::POS_LOAD])) {
if ($fullPage) {
//This part is different to reflect the changes needed in the backend by the pjax loading of pages
$scripts[] = "jQuery(document).on('ready pjax:complete',function() {\n".implode("\n", $this->scripts[self::POS_LOAD])."\n});";
} else {
$scripts[] = implode("\n", $this->scripts[self::POS_LOAD]);
}
}
if (isset($this->scripts[self::POS_POSTSCRIPT])) {
if ($fullPage) {
//This part is different to reflect the changes needed in the backend by the pjax loading of pages
$scripts[] = "jQuery(document).off('pjax:scriptcomplete.mainBottom').on('ready pjax:scriptcomplete.mainBottom', function() {\n".implode("\n", $this->scripts[self::POS_POSTSCRIPT])."\n});";
} else {
$scripts[] = implode("\n", $this->scripts[self::POS_POSTSCRIPT]);
}
}
//All scripts are wrapped into a section to be able to reload them accordingly
if (!empty($scripts)) {
$html .= $this->renderScriptBatch($scripts);
}
if ($fullPage) {
$output = preg_replace('/<###end###>/', $html, $output, 1);
} else {
$output = $output.$html;
}
}
/**
* Renders the registered scripts.
* This method is called in {@link CController::render} when it finishes
* rendering content. CClientScript thus gets a chance to insert script tags
* at <code>head</code> and <code>body</code> sections in the HTML output.
* @param string $output the existing output that needs to be inserted with script tags
*/
public function render(&$output)
{
if (!$this->hasScripts) {
return;
}
$this->renderCoreScripts();
if (!empty($this->scriptMap)) {
$this->remapScripts();
}
$this->unifyScripts();
$this->renderHead($output);
if ($this->enableJavaScript) {
$this->renderBodyBegin($output);
$this->renderBodyEnd($output);
}
}
}