loader.php
22.3 KB
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<?php
/**
* @package Joomla.Platform
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
/**
* Static class to handle loading of libraries.
*
* @package Joomla.Platform
* @since 1.7.0
*/
abstract class JLoader
{
/**
* Container for already imported library paths.
*
* @var array
* @since 1.7.0
*/
protected static $classes = array();
/**
* Container for already imported library paths.
*
* @var array
* @since 1.7.0
*/
protected static $imported = array();
/**
* Container for registered library class prefixes and path lookups.
*
* @var array
* @since 3.0.0
*/
protected static $prefixes = array();
/**
* Holds proxy classes and the class names the proxy.
*
* @var array
* @since 3.2
*/
protected static $classAliases = array();
/**
* Holds the inverse lookup for proxy classes and the class names the proxy.
*
* @var array
* @since 3.4
*/
protected static $classAliasesInverse = array();
/**
* Container for namespace => path map.
*
* @var array
* @since 3.1.4
*/
protected static $namespaces = array('psr0' => array(), 'psr4' => array());
/**
* Holds a reference for all deprecated aliases (mainly for use by a logging platform).
*
* @var array
* @since 3.6.3
*/
protected static $deprecatedAliases = array();
/**
* Method to discover classes of a given type in a given path.
*
* @param string $classPrefix The class name prefix to use for discovery.
* @param string $parentPath Full path to the parent folder for the classes to discover.
* @param boolean $force True to overwrite the autoload path value for the class if it already exists.
* @param boolean $recurse Recurse through all child directories as well as the parent path.
*
* @return void
*
* @since 1.7.0
*/
public static function discover($classPrefix, $parentPath, $force = true, $recurse = false)
{
try
{
if ($recurse)
{
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($parentPath),
RecursiveIteratorIterator::SELF_FIRST
);
}
else
{
$iterator = new DirectoryIterator($parentPath);
}
/** @type $file DirectoryIterator */
foreach ($iterator as $file)
{
$fileName = $file->getFilename();
// Only load for php files.
if ($file->isFile() && $file->getExtension() === 'php')
{
// Get the class name and full path for each file.
$class = strtolower($classPrefix . preg_replace('#\.php$#', '', $fileName));
// Register the class with the autoloader if not already registered or the force flag is set.
if ($force || empty(self::$classes[$class]))
{
self::register($class, $file->getPath() . '/' . $fileName);
}
}
}
}
catch (UnexpectedValueException $e)
{
// Exception will be thrown if the path is not a directory. Ignore it.
}
}
/**
* Method to get the list of registered classes and their respective file paths for the autoloader.
*
* @return array The array of class => path values for the autoloader.
*
* @since 1.7.0
*/
public static function getClassList()
{
return self::$classes;
}
/**
* Method to get the list of deprecated class aliases.
*
* @return array An associative array with deprecated class alias data.
*
* @since 3.6.3
*/
public static function getDeprecatedAliases()
{
return self::$deprecatedAliases;
}
/**
* Method to get the list of registered namespaces.
*
* @param string $type Defines the type of namespace, can be prs0 or psr4.
*
* @return array The array of namespace => path values for the autoloader.
*
* @since 3.1.4
*/
public static function getNamespaces($type = 'psr0')
{
if ($type !== 'psr0' && $type !== 'psr4')
{
throw new InvalidArgumentException('Type needs to be prs0 or psr4!');
}
return self::$namespaces[$type];
}
/**
* Loads a class from specified directories.
*
* @param string $key The class name to look for (dot notation).
* @param string $base Search this directory for the class.
*
* @return boolean True on success.
*
* @since 1.7.0
*/
public static function import($key, $base = null)
{
// Only import the library if not already attempted.
if (!isset(self::$imported[$key]))
{
// Setup some variables.
$success = false;
$parts = explode('.', $key);
$class = array_pop($parts);
$base = (!empty($base)) ? $base : __DIR__;
$path = str_replace('.', DIRECTORY_SEPARATOR, $key);
// Handle special case for helper classes.
if ($class === 'helper')
{
$class = ucfirst(array_pop($parts)) . ucfirst($class);
}
// Standard class.
else
{
$class = ucfirst($class);
}
// If we are importing a library from the Joomla namespace set the class to autoload.
if (strpos($path, 'joomla') === 0)
{
// Since we are in the Joomla namespace prepend the classname with J.
$class = 'J' . $class;
// Only register the class for autoloading if the file exists.
if (is_file($base . '/' . $path . '.php'))
{
self::$classes[strtolower($class)] = $base . '/' . $path . '.php';
$success = true;
}
}
/*
* If we are not importing a library from the Joomla namespace directly include the
* file since we cannot assert the file/folder naming conventions.
*/
else
{
// If the file exists attempt to include it.
if (is_file($base . '/' . $path . '.php'))
{
$success = (bool) include_once $base . '/' . $path . '.php';
}
}
// Add the import key to the memory cache container.
self::$imported[$key] = $success;
}
return self::$imported[$key];
}
/**
* Load the file for a class.
*
* @param string $class The class to be loaded.
*
* @return boolean True on success
*
* @since 1.7.0
*/
public static function load($class)
{
// Sanitize class name.
$key = strtolower($class);
// If the class already exists do nothing.
if (class_exists($class, false))
{
return true;
}
// If the class is registered include the file.
if (isset(self::$classes[$key]))
{
$found = (bool) include_once self::$classes[$key];
if ($found)
{
self::loadAliasFor($class);
}
// If the class doesn't exists, we probably have a class alias available
if (!class_exists($class, false))
{
// Search the alias class, first none namespaced and then namespaced
$original = array_search($class, self::$classAliases) ? : array_search('\\' . $class, self::$classAliases);
// When we have an original and the class exists an alias should be created
if ($original && class_exists($original, false))
{
class_alias($original, $class);
}
}
return true;
}
return false;
}
/**
* Directly register a class to the autoload list.
*
* @param string $class The class name to register.
* @param string $path Full path to the file that holds the class to register.
* @param boolean $force True to overwrite the autoload path value for the class if it already exists.
*
* @return void
*
* @since 1.7.0
*/
public static function register($class, $path, $force = true)
{
// When an alias exists, register it as well
if (key_exists(strtolower($class), self::$classAliases))
{
self::register(self::stripFirstBackslash(self::$classAliases[strtolower($class)]), $path, $force);
}
// Sanitize class name.
$class = strtolower($class);
// Only attempt to register the class if the name and file exist.
if (!empty($class) && is_file($path))
{
// Register the class with the autoloader if not already registered or the force flag is set.
if ($force || empty(self::$classes[$class]))
{
self::$classes[$class] = $path;
}
}
}
/**
* Register a class prefix with lookup path. This will allow developers to register library
* packages with different class prefixes to the system autoloader. More than one lookup path
* may be registered for the same class prefix, but if this method is called with the reset flag
* set to true then any registered lookups for the given prefix will be overwritten with the current
* lookup path. When loaded, prefix paths are searched in a "last in, first out" order.
*
* @param string $prefix The class prefix to register.
* @param string $path Absolute file path to the library root where classes with the given prefix can be found.
* @param boolean $reset True to reset the prefix with only the given lookup path.
* @param boolean $prepend If true, push the path to the beginning of the prefix lookup paths array.
*
* @return void
*
* @throws RuntimeException
*
* @since 3.0.0
*/
public static function registerPrefix($prefix, $path, $reset = false, $prepend = false)
{
// Verify the library path exists.
if (!file_exists($path))
{
$path = (str_replace(JPATH_ROOT, '', $path) == $path) ? basename($path) : str_replace(JPATH_ROOT, '', $path);
throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500);
}
// If the prefix is not yet registered or we have an explicit reset flag then set set the path.
if ($reset || !isset(self::$prefixes[$prefix]))
{
self::$prefixes[$prefix] = array($path);
}
// Otherwise we want to simply add the path to the prefix.
else
{
if ($prepend)
{
array_unshift(self::$prefixes[$prefix], $path);
}
else
{
self::$prefixes[$prefix][] = $path;
}
}
}
/**
* Offers the ability for "just in time" usage of `class_alias()`.
* You cannot overwrite an existing alias.
*
* @param string $alias The alias name to register.
* @param string $original The original class to alias.
* @param string|boolean $version The version in which the alias will no longer be present.
*
* @return boolean True if registration was successful. False if the alias already exists.
*
* @since 3.2
*/
public static function registerAlias($alias, $original, $version = false)
{
// PHP is case insensitive so support all kind of alias combination
$lowercasedAlias = strtolower($alias);
if (!isset(self::$classAliases[$lowercasedAlias]))
{
self::$classAliases[$lowercasedAlias] = $original;
$original = self::stripFirstBackslash($original);
if (!isset(self::$classAliasesInverse[$original]))
{
self::$classAliasesInverse[$original] = array($lowercasedAlias);
}
else
{
self::$classAliasesInverse[$original][] = $lowercasedAlias;
}
// If given a version, log this alias as deprecated
if ($version)
{
self::$deprecatedAliases[] = array('old' => $alias, 'new' => $original, 'version' => $version);
}
return true;
}
return false;
}
/**
* Register a namespace to the autoloader. When loaded, namespace paths are searched in a "last in, first out" order.
*
* @param string $namespace A case sensitive Namespace to register.
* @param string $path A case sensitive absolute file path to the library root where classes of the given namespace can be found.
* @param boolean $reset True to reset the namespace with only the given lookup path.
* @param boolean $prepend If true, push the path to the beginning of the namespace lookup paths array.
* @param string $type Defines the type of namespace, can be prs0 or psr4.
*
* @return void
*
* @throws RuntimeException
*
* @note The default argument of $type will be changed in J4 to be 'psr4'
* @since 3.1.4
*/
public static function registerNamespace($namespace, $path, $reset = false, $prepend = false, $type = 'psr0')
{
if ($type !== 'psr0' && $type !== 'psr4')
{
throw new InvalidArgumentException('Type needs to be prs0 or psr4!');
}
// Verify the library path exists.
if (!file_exists($path))
{
$path = (str_replace(JPATH_ROOT, '', $path) == $path) ? basename($path) : str_replace(JPATH_ROOT, '', $path);
throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500);
}
// Trim leading and trailing backslashes from namespace, allowing "\Parent\Child", "Parent\Child\" and "\Parent\Child\" to be treated the same way.
$namespace = trim($namespace, '\\');
// If the namespace is not yet registered or we have an explicit reset flag then set the path.
if ($reset || !isset(self::$namespaces[$type][$namespace]))
{
self::$namespaces[$type][$namespace] = array($path);
}
// Otherwise we want to simply add the path to the namespace.
else
{
if ($prepend)
{
array_unshift(self::$namespaces[$type][$namespace], $path);
}
else
{
self::$namespaces[$type][$namespace][] = $path;
}
}
}
/**
* Method to setup the autoloaders for the Joomla Platform.
* Since the SPL autoloaders are called in a queue we will add our explicit
* class-registration based loader first, then fall back on the autoloader based on conventions.
* This will allow people to register a class in a specific location and override platform libraries
* as was previously possible.
*
* @param boolean $enablePsr True to enable autoloading based on PSR-0.
* @param boolean $enablePrefixes True to enable prefix based class loading (needed to auto load the Joomla core).
* @param boolean $enableClasses True to enable class map based class loading (needed to auto load the Joomla core).
*
* @return void
*
* @since 3.1.4
*/
public static function setup($enablePsr = true, $enablePrefixes = true, $enableClasses = true)
{
if ($enableClasses)
{
// Register the class map based autoloader.
spl_autoload_register(array('JLoader', 'load'));
}
if ($enablePrefixes)
{
// Register the J prefix and base path for Joomla platform libraries.
self::registerPrefix('J', JPATH_PLATFORM . '/joomla');
// Register the prefix autoloader.
spl_autoload_register(array('JLoader', '_autoload'));
}
if ($enablePsr)
{
// Register the PSR based autoloader.
spl_autoload_register(array('JLoader', 'loadByPsr0'));
spl_autoload_register(array('JLoader', 'loadByPsr4'));
spl_autoload_register(array('JLoader', 'loadByAlias'));
}
}
/**
* Method to autoload classes that are namespaced to the PSR-4 standard.
*
* @param string $class The fully qualified class name to autoload.
*
* @return boolean True on success, false otherwise.
*
* @since 3.7.0
*/
public static function loadByPsr4($class)
{
$class = self::stripFirstBackslash($class);
// Find the location of the last NS separator.
$pos = strrpos($class, '\\');
// If one is found, we're dealing with a NS'd class.
if ($pos !== false)
{
$classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
$className = substr($class, $pos + 1);
}
// If not, no need to parse path.
else
{
$classPath = null;
$className = $class;
}
$classPath .= $className . '.php';
// Loop through registered namespaces until we find a match.
foreach (self::$namespaces['psr4'] as $ns => $paths)
{
if (strpos($class, "{$ns}\\") === 0)
{
$nsPath = trim(str_replace('\\', DIRECTORY_SEPARATOR, $ns), DIRECTORY_SEPARATOR);
// Loop through paths registered to this namespace until we find a match.
foreach ($paths as $path)
{
$classFilePath = realpath($path . DIRECTORY_SEPARATOR . substr_replace($classPath, '', 0, strlen($nsPath) + 1));
// We do not allow files outside the namespace root to be loaded
if (strpos($classFilePath, realpath($path)) !== 0)
{
continue;
}
// We check for class_exists to handle case-sensitive file systems
if (file_exists($classFilePath) && !class_exists($class, false))
{
$found = (bool) include_once $classFilePath;
if ($found)
{
self::loadAliasFor($class);
}
return $found;
}
}
}
}
return false;
}
/**
* Method to autoload classes that are namespaced to the PSR-0 standard.
*
* @param string $class The fully qualified class name to autoload.
*
* @return boolean True on success, false otherwise.
*
* @since 3.2.0
*
* @deprecated 4.0 this method will be removed
*/
public static function loadByPsr0($class)
{
$class = self::stripFirstBackslash($class);
// Find the location of the last NS separator.
$pos = strrpos($class, '\\');
// If one is found, we're dealing with a NS'd class.
if ($pos !== false)
{
$classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
$className = substr($class, $pos + 1);
}
// If not, no need to parse path.
else
{
$classPath = null;
$className = $class;
}
$classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
// Loop through registered namespaces until we find a match.
foreach (self::$namespaces['psr0'] as $ns => $paths)
{
if (strpos($class, $ns) === 0)
{
// Loop through paths registered to this namespace until we find a match.
foreach ($paths as $path)
{
$classFilePath = realpath($path . DIRECTORY_SEPARATOR . $classPath);
// We do not allow files outside the namespace root to be loaded
if (strpos($classFilePath, realpath($path)) !== 0)
{
continue;
}
// We check for class_exists to handle case-sensitive file systems
if (file_exists($classFilePath) && !class_exists($class, false))
{
$found = (bool) include_once $classFilePath;
if ($found)
{
self::loadAliasFor($class);
}
return $found;
}
}
}
}
return false;
}
/**
* Method to autoload classes that have been aliased using the registerAlias method.
*
* @param string $class The fully qualified class name to autoload.
*
* @return boolean True on success, false otherwise.
*
* @since 3.2
*/
public static function loadByAlias($class)
{
$class = strtolower(self::stripFirstBackslash($class));
if (isset(self::$classAliases[$class]))
{
// Force auto-load of the regular class
class_exists(self::$classAliases[$class], true);
// Normally this shouldn't execute as the autoloader will execute applyAliasFor when the regular class is
// auto-loaded above.
if (!class_exists($class, false) && !interface_exists($class, false))
{
class_alias(self::$classAliases[$class], $class);
}
}
}
/**
* Applies a class alias for an already loaded class, if a class alias was created for it.
*
* @param string $class We'll look for and register aliases for this (real) class name
*
* @return void
*
* @since 3.4
*/
public static function applyAliasFor($class)
{
$class = self::stripFirstBackslash($class);
if (isset(self::$classAliasesInverse[$class]))
{
foreach (self::$classAliasesInverse[$class] as $alias)
{
class_alias($class, $alias);
}
}
}
/**
* Autoload a class based on name.
*
* @param string $class The class to be loaded.
*
* @return boolean True if the class was loaded, false otherwise.
*
* @since 1.7.3
*/
public static function _autoload($class)
{
foreach (self::$prefixes as $prefix => $lookup)
{
$chr = strlen($prefix) < strlen($class) ? $class[strlen($prefix)] : 0;
if (strpos($class, $prefix) === 0 && ($chr === strtoupper($chr)))
{
return self::_load(substr($class, strlen($prefix)), $lookup);
}
}
return false;
}
/**
* Load a class based on name and lookup array.
*
* @param string $class The class to be loaded (without prefix).
* @param array $lookup The array of base paths to use for finding the class file.
*
* @return boolean True if the class was loaded, false otherwise.
*
* @since 3.0.0
*/
private static function _load($class, $lookup)
{
// Split the class name into parts separated by camelCase.
$parts = preg_split('/(?<=[a-z0-9])(?=[A-Z])/x', $class);
$partsCount = count($parts);
foreach ($lookup as $base)
{
// Generate the path based on the class name parts.
$path = realpath($base . '/' . implode('/', array_map('strtolower', $parts)) . '.php');
// Load the file if it exists and is in the lookup path.
if (strpos($path, realpath($base)) === 0 && file_exists($path))
{
$found = (bool) include_once $path;
if ($found)
{
self::loadAliasFor($class);
}
return $found;
}
// Backwards compatibility patch
// If there is only one part we want to duplicate that part for generating the path.
if ($partsCount === 1)
{
// Generate the path based on the class name parts.
$path = realpath($base . '/' . implode('/', array_map('strtolower', array($parts[0], $parts[0]))) . '.php');
// Load the file if it exists and is in the lookup path.
if (strpos($path, realpath($base)) === 0 && file_exists($path))
{
$found = (bool) include_once $path;
if ($found)
{
self::loadAliasFor($class);
}
return $found;
}
}
}
return false;
}
/**
* Loads the aliases for the given class.
*
* @param string $class The class.
*
* @return void
*
* @since 3.8.0
*/
private static function loadAliasFor($class)
{
if (!key_exists($class, self::$classAliasesInverse))
{
return;
}
foreach (self::$classAliasesInverse[$class] as $alias)
{
// Force auto-load of the alias class
class_exists($alias, true);
}
}
/**
* Strips the first backslash from the given class if present.
*
* @param string $class The class to strip the first prefix from.
*
* @return string The striped class name.
*
* @since 3.8.0
*/
private static function stripFirstBackslash($class)
{
return $class && $class[0] === '\\' ? substr($class, 1) : $class;
}
}
// Check if jexit is defined first (our unit tests mock this)
if (!function_exists('jexit'))
{
/**
* Global application exit.
*
* This function provides a single exit point for the platform.
*
* @param mixed $message Exit code or string. Defaults to zero.
*
* @return void
*
* @codeCoverageIgnore
* @since 1.7.0
*/
function jexit($message = 0)
{
exit($message);
}
}
/**
* Intelligent file importer.
*
* @param string $path A dot syntax path.
* @param string $base Search this directory for the class.
*
* @return boolean True on success.
*
* @since 1.7.0
*/
function jimport($path, $base = null)
{
return JLoader::import($path, $base);
}