-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathless.php
354 lines (299 loc) · 9.75 KB
/
less.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
<?php
/**
* @package System Plugin - automatic Less compiler - for Joomla 2.5 and 3.x
* @version 0.8.1 Stable
* @author Andreas Tasch
* @copyright (C) 2012-2015 - Andreas Tasch and contributors
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
// no direct access
defined('_JEXEC') or die();
/**
* Plugin checks and compiles updated .less files on page load. No need to manually compile your .less files again.
* Less compiler lessphp; see http://leafo.net/lessphp/
*/
class plgSystemLess extends JPlugin
{
/**
* @var $app
*/
protected $app;
/**
* override constructor to load classes as soon as possible
* @param $subject
* @param $config
*/
public function __construct(&$subject, $config)
{
// trigger parent constructor first so params get set
parent::__construct($subject, $config);
// set app
$this->app = JFactory::getApplication();
// check if lessc already exists but bypass autoloader
if (class_exists('lessc', false))
{
// the lessc class already exists, so we cannot load our own version
JDEBUG ? $this->app->enqueueMessage('[DEBUG] class "lessc" already exists, using version ' . lessc::$VERSION) : null;
}
// load the appropriate class
else
{
// determine the name of the file to load based on application
$name = false;
if ($this->app->isSite())
{
$name = $this->params->get('sitelessc', 'lessc-0.3.9');
}
else if ($this->app->isAdmin())
{
$name = $this->params->get('adminlessc', 'lessc-0.3.9');
}
$name && JDEBUG ? $this->app->enqueueMessage("[DEBUG] loading $name") : null;
// confirm that the named file exists
if ($name && file_exists($file = dirname(__FILE__) . '/lessc/' . $name . '.php'))
{
require_once $file;
}
}
// trigger autoload in case the file wasn't found while checking for debug
class_exists('lessc') && JDEBUG ? $this->app->enqueueMessage("[DEBUG] lessc " . lessc::$VERSION) : null;
}
/**
* Compile .less files on change
*/
function onBeforeRender()
{
//path to less file
$lessFile = '';
// 0 = frontend only
// 1 = backend only
// 2 = front + backend
$mode = $this->params->get('mode', 0);
//only execute frontend
if ($this->app->isSite() && ($mode == 0 || $mode == 2))
{
$templatePath = JPATH_BASE . DIRECTORY_SEPARATOR . 'templates/' . $this->app->getTemplate() . DIRECTORY_SEPARATOR;
//entrypoint for main .less file, default is less/template.less
$lessFile = $templatePath . $this->params->get('lessfile', 'less/template.less');
//destination .css file, default css/template.css
$cssFile = $templatePath . $this->params->get('cssfile', 'css/template.css');
}
//execute backend
if ($this->app->isAdmin() && ($mode == 1 || $mode == 2))
{
$templatePath = JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'templates/' . $this->app->getTemplate() . DIRECTORY_SEPARATOR;
//entrypoint for main .less file, default is less/template.less
$lessFile = $templatePath . $this->params->get('admin_lessfile', 'less/template.less');
//destination .css file, default css/template.css
$cssFile = $templatePath . $this->params->get('admin_cssfile', 'css/template.css');
}
//check if .less file exists and is readable
if (is_readable($lessFile))
{
if ((bool) $this->params->get('clientside_enable', 0))
{
$this->clientsideLess();
}
else
{
//initialse less compiler
try
{
$this->autoCompileLess($lessFile, $cssFile);
}
catch (Exception $e)
{
echo "lessphp error: " . $e->getMessage();
}
}
}
return false;
}
/**
* Checks if .less file has been updated and stores it in cache for quick comparison.
*
* This function is taken and modified from documentation of lessphp
*
* @param String $inputFile
* @param String $outputFile
*/
function autoCompileLess($inputFile, $outputFile)
{
// load config file
$config = JFactory::getConfig();
//path to temp folder
$tmpPath = $config->get('tmp_path');
//load chached file
$cacheFile = $tmpPath . DIRECTORY_SEPARATOR . $this->app->getTemplate() . "_" . basename($inputFile) . ".cache";
if (file_exists($cacheFile))
{
$tmpCache = unserialize(file_get_contents($cacheFile));
if ($tmpCache['root'] === $inputFile)
{
$cache = $tmpCache;
}
else
{
$cache = $inputFile;
unlink($cacheFile);
}
}
else
{
$cache = $inputFile;
}
//instantiate less compiler
$less = new lessc;
//set less options
//option: force recompilation regardless of change
$force = (boolean) $this->params->get('less_force', 0);
//option: preserve comments
if ($this->params->get('less_comments', 0))
{
$less->setPreserveComments(true);
}
//option: compression
if ($this->params->get('less_compress', 0))
{
$less->setFormatter("compressed");
}
else
{
$less->setFormatter("classic");
}
//compile cache file
$newCache = $less->cachedCompile($cache, $force);
if (!is_array($cache) || $newCache["updated"] > $cache["updated"])
{
file_put_contents($cacheFile, serialize($newCache));
file_put_contents($outputFile, $newCache['compiled']);
}
}
/**
* Configure and add Client-side Less library
* @author piotr-cz
* @return void
*
* @see LESS: Ussage http://lesscss.org/#usage
*/
function clientsideLess()
{
// Initialise variables
$doc = JFactory::getDocument();
// Early exit
if ($doc->getType() !== 'html')
{
return;
}
// Get asset paths
$templateRel = 'templates/' . $doc->template . '/';
$templateUri = JUri::base() . $templateRel;
// Determine which param to use (admin/ site)
$mode = $this->params->get('mode', 0);
$lessKey = 'lessfile';
$cssKey = 'cssfile';
if ($this->app->isAdmin() && ($mode == 1 || $mode == 2))
{
$lessKey = 'admin_' . $lessKey;
$cssKey = 'admin_' . $cssKey;
}
// Get template css filenames
$lessUri = $templateRel . $this->params->get($lessKey, 'less/template.less');
$cssUri = $templateRel . $this->params->get($cssKey, 'css/template.css');
// Add less file to document
$doc->addHeadLink($lessUri, 'stylesheet/less', 'rel', array('type' => 'text/css'));
/*
* Configure Less options
* async : false,
* fileAsync : false,
* poll : 1500,
* relativeUrls : false,
* rootpath : $templateUrl
*/
$options = array(
'env' => 'development',
'dumpLineNumbers' => 'mediaquery', // default: 'comments'
);
$doc->addScriptDeclaration('
// Less options
var less = ' . json_encode($options, JSON_FORCE_OBJECT | (defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : false)) . ';
');
// Load less.js (pick latest version in media folder)
// Joomla adds JS code after libraries in head. We need it other way around
$mediaJsDestination = '/media/plg_less/js/';
$mediaPath = JPATH_SITE . $mediaJsDestination;
$mediaUri = JUri::root(true) . $mediaJsDestination;
$lessVersions = glob($mediaPath . 'less-*.js');
if (!empty($lessVersions))
{
rsort($lessVersions);
// Load at the end of head
$doc->addCustomTag('<script src="' . $mediaUri . basename($lessVersions[0]) . '" type="text/javascript"></script>');
// Load after options (experimental, cannot use in XHTML documents)
/*
$doc->addScriptDeclaration('
// Less library
document.write( unescape( \'%3Cscript src="' . $mediaUri . basename($lessVersions[0]) . '" type="text/javascript"%3E%3C/script%3E\' ) );
');
*/
}
// Cannot find client-side parser
else
{
return;
}
/*
* Remove template.css from document head
*
* Note: Css file must be added either using `JFactory::getDocument->addStylesheet($cssFile)` or `JHtml::_('stylesheet', $cssFile)`
* Note: Cannot rely on removing stylesheet using JDocumentHTML methods.
* Note: Passes ignore cache trick (template.css?1234567890123)
* Note: Template.css may be added to $doc['stylesheets'] using following keys:
* - relative : `templates/...`
* - semi JUri::base(true) : `/[path-to-root]/templates/...`
* - absolute JUri::base() : `http://[host]/[path-to-root]/templates/...`
* - or outside $doc->_styleSheets
*/
$lookups = array($cssUri, JUri::base(true) . '/' . $cssUri, JUri::base() . $cssUri);
// Loop trough all registered document stylesheets...
foreach ($doc->_styleSheets as $stylesSheetUri => $styleSheetInfo)
{
// ...and compare to every lookup...
foreach ($lookups as $lookup)
{
// ...that starts like a lookup
if (strpos($stylesSheetUri, $lookup) === 0)
{
unset($doc->_styleSheets[$stylesSheetUri]);
return;
}
}
}
// Didn't find a css file in JDocument instance, register event to remove in from rendered html body.
$this->app->registerEvent('onAfterRender', array($this, 'removeCss'));
return;
}
/**
* Remove template.css from document html
* Stylesheet href may include query string, ie template.css?1234567890123
* @author piotr-cz
*
* @return void
*/
public function removeCss()
{
// Initialise variables
$doc = JFactory::getDocument();
$body = JResponse::getBody();
// Get Uri to template stylesheet file
$templateUri = JUri::base(true) . '/templates/' . $doc->template . '/';
$cssUri = $templateUri . $this->params->get('cssfile', 'css/template.css');
// Replace line with link element and path to stylesheet file
$replaced = preg_replace( '~(\s*?<link.* href=".*?' . preg_quote($cssUri) . '(?:\?.*)?".*/>)~', '', $body, -1, $count);
if ($count)
{
JResponse::setBody($replaced);
}
return;
}
}