├── .gitignore
├── .phpcs.dir.phpcompatibility.xml
├── .phpcs.dir.xml
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── SECURITY.md
├── composer.json
└── src
├── AutoloadFileWriter.php
├── AutoloadGenerator.php
├── AutoloadProcessor.php
├── CustomAutoloaderPlugin.php
├── ManifestGenerator.php
├── autoload.php
├── class-autoloader-handler.php
├── class-autoloader-locator.php
├── class-autoloader.php
├── class-container.php
├── class-hook-manager.php
├── class-latest-autoloader-guard.php
├── class-manifest-reader.php
├── class-path-processor.php
├── class-php-autoloader.php
├── class-plugin-locator.php
├── class-plugins-handler.php
├── class-shutdown-handler.php
├── class-version-loader.php
└── class-version-selector.php
/.gitignore:
--------------------------------------------------------------------------------
1 | tests/php/tmp
2 |
--------------------------------------------------------------------------------
/.phpcs.dir.phpcompatibility.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.phpcs.dir.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7 |
8 | ## [5.0.7] - 2025-04-28
9 | ### Changed
10 | - Internal updates.
11 |
12 | ## [5.0.6] - 2025-03-31
13 | ### Changed
14 | - Internal updates.
15 |
16 | ## [5.0.5] - 2025-03-21
17 | ### Changed
18 | - Internal updates.
19 |
20 | ## [5.0.4] - 2025-03-17
21 | ### Changed
22 | - Internal updates.
23 |
24 | ## [5.0.3] - 2025-03-12
25 | ### Changed
26 | - Internal updates.
27 |
28 | ## [5.0.2] - 2025-02-24
29 | ### Changed
30 | - Internal updates.
31 |
32 | ## [5.0.1] - 2025-01-20
33 | ### Changed
34 | - Code: Use function-style exit() and die() with a default status code of 0. [#41167]
35 |
36 | ## [5.0.0] - 2024-11-25
37 | ### Removed
38 | - Drop support for Composer <2.2. [#40297]
39 | - Remove support for WordPress 6.5 and earlier. [#40200]
40 |
41 | ## [4.0.0] - 2024-11-14
42 | ### Removed
43 | - General: Update minimum PHP version to 7.2. [#40147]
44 |
45 | ## [3.1.3] - 2024-11-04
46 | ### Added
47 | - Enable test coverage. [#39961]
48 |
49 | ## [3.1.2] - 2024-10-15
50 | ### Changed
51 | - Internal updates.
52 |
53 | ## [3.1.1] - 2024-10-10
54 | ### Changed
55 | - Internal updates.
56 |
57 | ## [3.1.0] - 2024-09-06
58 | ### Added
59 | - Add logic for debugging issues caused by conflicting Composer autoloaders, enabled by setting the `JETPACK_AUTOLOAD_DEBUG_CONFLICTING_LOADERS` constant. [#38995]
60 | - Add logic for debugging issues caused by early class loads, enabled by setting the `JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS` constant. [#38995]
61 |
62 | ## [3.0.10] - 2024-08-26
63 | ### Changed
64 | - Updated package dependencies. [#39004]
65 |
66 | ## [3.0.9] - 2024-07-10
67 | ### Fixed
68 | - Avoid a deprecation notice in `Autoloader_Locator::find_latest_autoloader()`. [#38245]
69 |
70 | ## [3.0.8] - 2024-05-29
71 | ### Fixed
72 | - `AutoloadGenerator::__construct` no longer pretends `$io` is nullable. That never worked. [#37608]
73 |
74 | ## [3.0.7] - 2024-05-06
75 | ### Fixed
76 | - Avoid deprecation notices when plugin path is null. [#37174]
77 |
78 | ## [3.0.6] - 2024-04-22
79 | ### Changed
80 | - Internal updates.
81 |
82 | ## [3.0.5] - 2024-04-11
83 | ### Changed
84 | - Internal updates.
85 |
86 | ## [3.0.4] - 2024-03-18
87 | ### Changed
88 | - Internal updates.
89 |
90 | ## [3.0.3] - 2024-03-14
91 | ### Changed
92 | - Internal updates.
93 |
94 | ## [3.0.2] - 2023-11-21
95 |
96 | ## [3.0.1] - 2023-11-21
97 |
98 | ## [3.0.0] - 2023-11-20
99 | ### Changed
100 | - Updated required PHP version to >= 7.0. [#34192]
101 |
102 | ## [2.12.0] - 2023-09-28
103 | ### Added
104 | - Add an `AutoloadGenerator::VERSION` constant, and use that for the autoloader's version in preference to whatever Composer has. [#33156]
105 |
106 | ## [2.11.23] - 2023-09-19
107 |
108 | - Minor internal updates.
109 |
110 | ## [2.11.22] - 2023-08-23
111 | ### Changed
112 | - Updated package dependencies. [#32605]
113 |
114 | ## [2.11.21] - 2023-05-22
115 | ### Added
116 | - Set keywords in `composer.json`. [#30756]
117 |
118 | ## [2.11.20] - 2023-05-11
119 |
120 | - Updated package dependencies
121 |
122 | ## [2.11.19] - 2023-04-25
123 | ### Fixed
124 | - Fix example in README [#30225]
125 |
126 | ## [2.11.18] - 2023-03-28
127 | ### Changed
128 | - Minor internal updates.
129 |
130 | ## [2.11.17] - 2023-03-27
131 | ### Fixed
132 | - Don't error when processing packages specifying missing PSR paths. [#29669]
133 |
134 | ## [2.11.16] - 2023-02-20
135 | ### Changed
136 | - Minor internal updates.
137 |
138 | ## [2.11.15] - 2023-01-11
139 | ### Changed
140 | - Updated package dependencies.
141 |
142 | ## [2.11.14] - 2022-12-19
143 | ### Changed
144 | - Use `Composer\ClassMapGenerator\ClassMapGenerator` when available (i.e. with composer 2.4). [#27812]
145 |
146 | ### Fixed
147 | - Declare fields for PHP 8.2 compatibility. [#27949]
148 |
149 | ## [2.11.13] - 2022-12-02
150 | ### Changed
151 | - Updated package dependencies. [#27688]
152 |
153 | ## [2.11.12] - 2022-11-22
154 | ### Changed
155 | - Updated package dependencies. [#27043]
156 |
157 | ## [2.11.11] - 2022-10-25
158 | ### Changed
159 | - Sort data in generated `vendor/composer/jetpack_autoload_classmap.php` to avoid spurious diffs. [#26929]
160 |
161 | ## [2.11.10] - 2022-10-05
162 |
163 | - Tests: Clear `COMPOSER_AUTH` environment variable when running Composer for tests. [#26404]
164 |
165 | ## [2.11.9] - 2022-09-27
166 | ### Fixed
167 | - Tests: Clear `COMPOSER_AUTH` environment variable when running Composer for tests. [#26404]
168 |
169 | ## [2.11.8] - 2022-09-20
170 | ### Fixed
171 | - Tests: skip test if it requires a version of Composer not compatible with the running version of PHP. [#26143]
172 |
173 | ## [2.11.7] - 2022-07-26
174 | ### Changed
175 | - Updated package dependencies. [#25158]
176 |
177 | ## [2.11.6] - 2022-06-21
178 | ### Changed
179 | - Renaming `master` to `trunk`.
180 |
181 | ## [2.11.5] - 2022-05-18
182 | ### Fixed
183 | - Fix new PHPCS sniffs. [#24366]
184 |
185 | ## [2.11.4] - 2022-04-26
186 | ### Changed
187 | - Updated package dependencies.
188 |
189 | ## [2.11.3] - 2022-04-19
190 | ### Changed
191 | - PHPCS: Fix `WordPress.Security.ValidatedSanitizedInput`
192 |
193 | ## [2.11.2] - 2022-03-29
194 | ### Changed
195 | - Microperformance: Use === null instead of is_null
196 |
197 | ## [2.11.1] - 2022-03-08
198 | ### Removed
199 | - Removed the Upgrade Handler.
200 |
201 | ## [2.11.0] - 2022-03-08
202 | ### Added
203 | - On plugin update, pre-load all (non-PSR-4) classes from the plugin to avoid mid-upgrade fatals.
204 |
205 | ## [2.10.13] - 2022-03-01
206 | ### Fixed
207 | - Fix tests for upstream phpunit change.
208 |
209 | ## [2.10.12] - 2022-01-25
210 | ### Changed
211 | - Updated package dependencies.
212 |
213 | ## [2.10.11] - 2022-01-04
214 | ### Changed
215 | - Switch to pcov for code coverage.
216 | - Updated package dependencies
217 |
218 | ## [2.10.10] - 2021-11-16
219 | ### Added
220 | - Soft return if autoloader chain is not available.
221 |
222 | ## [2.10.9] - 2021-11-02
223 | ### Changed
224 | - Set `convertDeprecationsToExceptions` true in PHPUnit config.
225 |
226 | ## [2.10.8] - 2021-10-13
227 | ### Changed
228 | - Updated package dependencies.
229 |
230 | ## [2.10.7] - 2021-10-07
231 | ### Changed
232 | - Updated package dependencies
233 |
234 | ## [2.10.6] - 2021-09-28
235 | ### Changed
236 | - Updated package dependencies.
237 |
238 | ## [2.10.5] - 2021-08-31
239 | ### Changed
240 | - Run composer update on test-php command instead of phpunit
241 | - Tests: update PHPUnit polyfills dependency (yoast/phpunit-polyfills).
242 |
243 | ## [2.10.4] - 2021-08-10
244 | ### Changed
245 | - Updated package dependencies.
246 |
247 | ## [2.10.3] - 2021-05-25
248 | ### Changed
249 | - Updated package dependencies.
250 |
251 | ## [2.10.2] - 2021-04-27
252 | ### Changed
253 | - Updated package dependencies.
254 |
255 | ## [2.10.1] - 2021-03-30
256 | ### Added
257 | - Composer alias for dev-master, to improve dependencies
258 | - Tests: Added code coverage transformation
259 |
260 | ### Changed
261 | - Update package dependencies.
262 |
263 | ### Fixed
264 | - Fix coverage test
265 | - Fix uninstallation fatal
266 | - Update tests for changed composer 2.0.9 hash.
267 | - Use `composer update` rather than `install` in scripts, as composer.lock isn't checked in.
268 |
269 | ## [2.10.0] - 2021-02-09
270 |
271 | - Autoloader: test suite refactor
272 |
273 | ## [2.9.1] - 2021-02-05
274 |
275 | - CI: Make tests more generic
276 | - Autoloader: stricter type-checking on WP functions
277 | - Autoloader: prevent transitive plugin execution
278 |
279 | ## [2.9.0] - 2021-01-25
280 |
281 | - Autoloader: revised latest autoloader inclusion semantics
282 | - Add mirror-repo information to all current composer packages
283 | - Monorepo: Reorganize all projects
284 | - Autoloader: Don't cache deactivating plugins
285 |
286 | ## [2.8.0] - 2020-12-18
287 |
288 | ## [2.7.1] - 2020-12-18
289 |
290 | - Autoloader: Added realpath resolution to plugin paths
291 |
292 | ## [2.7.0] - 2020-12-08
293 |
294 | - Autoloader: Preemptively load unknown plugins from cache
295 | - Removed unwanted dot
296 | - Pin dependencies
297 | - Packages: Update for PHP 8 testing
298 |
299 | ## [2.6.0] - 2020-11-19
300 |
301 | - Autoloader: AutoloadGenerator no longer extends Composer's AutoloadGenerator class
302 | - Autoloader: Reuse an existing autoloader suffix if available
303 | - Updated PHPCS: Packages and Debugger
304 |
305 | ## [2.5.0] - 2020-10-08
306 |
307 | - Autoloader: remove the defined('JETPACK_AUTOLOAD_DEV') checks from the tests
308 |
309 | ## [2.4.0] - 2020-09-28
310 |
311 | - Autoloader: remove the plugins_loaded bullet point from the README
312 | - Packages: avoid PHPCS warnings
313 | - Autoloader: add PSR-0 support
314 | - Autoloader: Detect filtering of active_plugins
315 | - Autoloader: Support unoptimized PSR-4
316 |
317 | ## [2.3.0] - 2020-08-21
318 |
319 | - Autoloader: remove the plugin update hook
320 |
321 | ## [2.2.0] - 2020-08-14
322 |
323 | - Autoloader: don't reset the autoloader version during plugin update
324 | - CI: Try collect js coverage
325 |
326 | ## [2.1.0] - 2020-07-27
327 |
328 | - Autoloader: convert '\' directory separators to '/' in plugin paths
329 | - Autoloader: Avoid a PHP warning when an empty string is passed to `is_directory_plugin()`.
330 | - Autoloader: Tests: Use a string with define
331 |
332 | ## [2.0.2] - 2020-07-09
333 |
334 | - Autoloader: Avoid a PHP warning when an empty string is passed to `is_directory_plugin()`.
335 |
336 | ## [2.0.1] - 2020-07-02
337 |
338 | - Autoloader: Tests: Use a string with define
339 |
340 | ## [2.0.0] - 2020-06-29
341 |
342 | ## [2.0.0-beta] - 2020-06-29
343 |
344 | - Autoloader: Support Composer v2.0
345 | - Autoloader: use paths to identify plugins instead of the directories
346 | - Autoloader: fix the fatal that occurs during plugin update
347 | - Autoloader: add fallback check for plugin path in mu-plugins
348 | - Autoloader: use JETPACK__PLUGIN_DIR when looking for the jetpack plugin directory.
349 | - Feature Branch: Update the Autoloader
350 | - PHPCS: Clean up the packages
351 | - PHPCS Updates after WPCS 2.3
352 |
353 | ## [1.7.0] - 2020-04-23
354 |
355 | - Jetpack: Move comment notification override back to the constructor
356 |
357 | ## [1.6.0] - 2020-03-26
358 |
359 | - Autoloader: Remove file check to improve performance.
360 |
361 | ## [1.5.0] - 2020-02-25
362 |
363 | - Jetpack: instantiate manager object if it's null
364 |
365 | ## [1.4.1] - 2020-02-14
366 |
367 | - Autoloader: Load only latest version of autoload files to avoid conflicts.
368 |
369 | ## [1.4.0] - 2020-01-23
370 |
371 | - Autoloader: Remove the ignored classes
372 |
373 | ## [1.3.8] - 2020-01-14
374 |
375 | - Trying to add deterministic initialization.
376 | - Autoloader: Remove Manager_Interface and Plugin\Tracking from ignored list
377 | - Autoloader: Remove Jetpack_IXR_Client from ignore list
378 |
379 | ## [1.3.7] - 2019-12-10
380 |
381 | ## [1.3.6] - 2019-12-09
382 |
383 | - Autoloader: Use long-form sytax for array
384 |
385 | ## [1.3.5] - 2019-11-26
386 |
387 | - Fix/php notice status
388 |
389 | ## [1.3.4] - 2019-11-08
390 |
391 | - Deprecate Jetpack::is_development_mode() in favor of the packaged Status()->is_development_mode()
392 |
393 | ## [1.3.3] - 2019-10-28
394 |
395 | - Packages: Add gitattributes files to all packages that need th…
396 |
397 | ## [1.3.2] - 2019-09-24
398 |
399 | - Autoloader: Cover scenarios where composer/autoload_files.php…
400 |
401 | ## [1.3.1] - 2019-09-20
402 |
403 | - Docs: Unify usage of @package phpdoc tags
404 |
405 | ## [1.3.0] - 2019-09-14
406 |
407 | - Fix for empty namespaces. #13459
408 | - Connection: Move the Jetpack IXR client to the package
409 | - Adds full connection cycle capability to the Connection package.
410 | - Jetpack 7.5: Back compatibility package
411 |
412 | ## [1.2.0] - 2019-06-24
413 |
414 | - Jetpack DNA: Add full classmap support to Autoloader
415 | - Move Jetpack_Sync_Main from legacy to PSR-4
416 |
417 | ## [1.1.0] - 2019-06-19
418 |
419 | - Packages: Move autoloader tests to the package
420 | - DNA: Move Jetpack Usage tracking to its own file
421 | - Jetpack DNA: More isolation of Tracks Package
422 | - Autoloader: Ignore XMLRPC_Connector if called too early
423 | - Autoloader: Ignore Jetpack_Signature if called too early
424 |
425 | ## 1.0.0 - 2019-06-11
426 |
427 | - Add Custom Autoloader
428 |
429 | [5.0.7]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.6...v5.0.7
430 | [5.0.6]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.5...v5.0.6
431 | [5.0.5]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.4...v5.0.5
432 | [5.0.4]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.3...v5.0.4
433 | [5.0.3]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.2...v5.0.3
434 | [5.0.2]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.1...v5.0.2
435 | [5.0.1]: https://github.com/Automattic/jetpack-autoloader/compare/v5.0.0...v5.0.1
436 | [5.0.0]: https://github.com/Automattic/jetpack-autoloader/compare/v4.0.0...v5.0.0
437 | [4.0.0]: https://github.com/Automattic/jetpack-autoloader/compare/v3.1.3...v4.0.0
438 | [3.1.3]: https://github.com/Automattic/jetpack-autoloader/compare/v3.1.2...v3.1.3
439 | [3.1.2]: https://github.com/Automattic/jetpack-autoloader/compare/v3.1.1...v3.1.2
440 | [3.1.1]: https://github.com/Automattic/jetpack-autoloader/compare/v3.1.0...v3.1.1
441 | [3.1.0]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.10...v3.1.0
442 | [3.0.10]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.9...v3.0.10
443 | [3.0.9]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.8...v3.0.9
444 | [3.0.8]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.7...v3.0.8
445 | [3.0.7]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.6...v3.0.7
446 | [3.0.6]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.5...v3.0.6
447 | [3.0.5]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.4...v3.0.5
448 | [3.0.4]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.3...v3.0.4
449 | [3.0.3]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.2...v3.0.3
450 | [3.0.2]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.1...v3.0.2
451 | [3.0.1]: https://github.com/Automattic/jetpack-autoloader/compare/v3.0.0...v3.0.1
452 | [3.0.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.12.0...v3.0.0
453 | [2.12.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.23...v2.12.0
454 | [2.11.23]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.22...v2.11.23
455 | [2.11.22]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.21...v2.11.22
456 | [2.11.21]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.20...v2.11.21
457 | [2.11.20]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.19...v2.11.20
458 | [2.11.19]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.18...v2.11.19
459 | [2.11.18]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.17...v2.11.18
460 | [2.11.17]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.16...v2.11.17
461 | [2.11.16]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.15...v2.11.16
462 | [2.11.15]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.14...v2.11.15
463 | [2.11.14]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.13...v2.11.14
464 | [2.11.13]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.12...v2.11.13
465 | [2.11.12]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.11...v2.11.12
466 | [2.11.11]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.10...v2.11.11
467 | [2.11.10]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.9...v2.11.10
468 | [2.11.9]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.8...v2.11.9
469 | [2.11.8]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.7...v2.11.8
470 | [2.11.7]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.6...v2.11.7
471 | [2.11.6]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.5...v2.11.6
472 | [2.11.5]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.4...v2.11.5
473 | [2.11.4]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.3...v2.11.4
474 | [2.11.3]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.2...v2.11.3
475 | [2.11.2]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.1...v2.11.2
476 | [2.11.1]: https://github.com/Automattic/jetpack-autoloader/compare/v2.11.0...v2.11.1
477 | [2.11.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.13...v2.11.0
478 | [2.10.13]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.12...v2.10.13
479 | [2.10.12]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.11...v2.10.12
480 | [2.10.11]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.10...v2.10.11
481 | [2.10.10]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.9...v2.10.10
482 | [2.10.9]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.8...v2.10.9
483 | [2.10.8]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.7...v2.10.8
484 | [2.10.7]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.6...v2.10.7
485 | [2.10.6]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.5...v2.10.6
486 | [2.10.5]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.4...v2.10.5
487 | [2.10.4]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.3...v2.10.4
488 | [2.10.3]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.2...v2.10.3
489 | [2.10.2]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.1...v2.10.2
490 | [2.10.1]: https://github.com/Automattic/jetpack-autoloader/compare/v2.10.0...v2.10.1
491 | [2.10.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.9.1...v2.10.0
492 | [2.9.1]: https://github.com/Automattic/jetpack-autoloader/compare/v2.9.0...v2.9.1
493 | [2.9.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.8.0...v2.9.0
494 | [2.8.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.7.1...v2.8.0
495 | [2.7.1]: https://github.com/Automattic/jetpack-autoloader/compare/v2.7.0...v2.7.1
496 | [2.7.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.6.0...v2.7.0
497 | [2.6.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.5.0...v2.6.0
498 | [2.5.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.4.0...v2.5.0
499 | [2.4.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.3.0...v2.4.0
500 | [2.3.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.2.0...v2.3.0
501 | [2.2.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.1.0...v2.2.0
502 | [2.1.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.0.2...v2.1.0
503 | [2.0.2]: https://github.com/Automattic/jetpack-autoloader/compare/v2.0.1...v2.0.2
504 | [2.0.1]: https://github.com/Automattic/jetpack-autoloader/compare/v2.0.0...v2.0.1
505 | [2.0.0]: https://github.com/Automattic/jetpack-autoloader/compare/v2.0.0-beta...v2.0.0
506 | [2.0.0-beta]: https://github.com/Automattic/jetpack-autoloader/compare/v1.7.0...v2.0.0-beta
507 | [1.7.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.6.0...v1.7.0
508 | [1.6.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.5.0...v1.6.0
509 | [1.5.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.4.1...v1.5.0
510 | [1.4.1]: https://github.com/Automattic/jetpack-autoloader/compare/v1.4.0...v1.4.1
511 | [1.4.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.8...v1.4.0
512 | [1.3.8]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.7...v1.3.8
513 | [1.3.7]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.6...v1.3.7
514 | [1.3.6]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.5...v1.3.6
515 | [1.3.5]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.4...v1.3.5
516 | [1.3.4]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.3...v1.3.4
517 | [1.3.3]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.2...v1.3.3
518 | [1.3.2]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.1...v1.3.2
519 | [1.3.1]: https://github.com/Automattic/jetpack-autoloader/compare/v1.3.0...v1.3.1
520 | [1.3.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.2.0...v1.3.0
521 | [1.2.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.1.0...v1.2.0
522 | [1.1.0]: https://github.com/Automattic/jetpack-autoloader/compare/v1.0.0...v1.1.0
523 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | This program is free software; you can redistribute it and/or modify
2 | it under the terms of the GNU General Public License as published by
3 | the Free Software Foundation; either version 2 of the License, or
4 | (at your option) any later version.
5 |
6 | This program is distributed in the hope that it will be useful,
7 | but WITHOUT ANY WARRANTY; without even the implied warranty of
8 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 | GNU General Public License for more details.
10 |
11 | You should have received a copy of the GNU General Public License
12 | along with this program; if not, write to the Free Software
13 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
14 |
15 |
16 | ===================================
17 |
18 |
19 | GNU GENERAL PUBLIC LICENSE
20 | Version 2, June 1991
21 |
22 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
23 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 | Everyone is permitted to copy and distribute verbatim copies
25 | of this license document, but changing it is not allowed.
26 |
27 | Preamble
28 |
29 | The licenses for most software are designed to take away your
30 | freedom to share and change it. By contrast, the GNU General Public
31 | License is intended to guarantee your freedom to share and change free
32 | software--to make sure the software is free for all its users. This
33 | General Public License applies to most of the Free Software
34 | Foundation's software and to any other program whose authors commit to
35 | using it. (Some other Free Software Foundation software is covered by
36 | the GNU Lesser General Public License instead.) You can apply it to
37 | your programs, too.
38 |
39 | When we speak of free software, we are referring to freedom, not
40 | price. Our General Public Licenses are designed to make sure that you
41 | have the freedom to distribute copies of free software (and charge for
42 | this service if you wish), that you receive source code or can get it
43 | if you want it, that you can change the software or use pieces of it
44 | in new free programs; and that you know you can do these things.
45 |
46 | To protect your rights, we need to make restrictions that forbid
47 | anyone to deny you these rights or to ask you to surrender the rights.
48 | These restrictions translate to certain responsibilities for you if you
49 | distribute copies of the software, or if you modify it.
50 |
51 | For example, if you distribute copies of such a program, whether
52 | gratis or for a fee, you must give the recipients all the rights that
53 | you have. You must make sure that they, too, receive or can get the
54 | source code. And you must show them these terms so they know their
55 | rights.
56 |
57 | We protect your rights with two steps: (1) copyright the software, and
58 | (2) offer you this license which gives you legal permission to copy,
59 | distribute and/or modify the software.
60 |
61 | Also, for each author's protection and ours, we want to make certain
62 | that everyone understands that there is no warranty for this free
63 | software. If the software is modified by someone else and passed on, we
64 | want its recipients to know that what they have is not the original, so
65 | that any problems introduced by others will not reflect on the original
66 | authors' reputations.
67 |
68 | Finally, any free program is threatened constantly by software
69 | patents. We wish to avoid the danger that redistributors of a free
70 | program will individually obtain patent licenses, in effect making the
71 | program proprietary. To prevent this, we have made it clear that any
72 | patent must be licensed for everyone's free use or not licensed at all.
73 |
74 | The precise terms and conditions for copying, distribution and
75 | modification follow.
76 |
77 | GNU GENERAL PUBLIC LICENSE
78 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
79 |
80 | 0. This License applies to any program or other work which contains
81 | a notice placed by the copyright holder saying it may be distributed
82 | under the terms of this General Public License. The "Program", below,
83 | refers to any such program or work, and a "work based on the Program"
84 | means either the Program or any derivative work under copyright law:
85 | that is to say, a work containing the Program or a portion of it,
86 | either verbatim or with modifications and/or translated into another
87 | language. (Hereinafter, translation is included without limitation in
88 | the term "modification".) Each licensee is addressed as "you".
89 |
90 | Activities other than copying, distribution and modification are not
91 | covered by this License; they are outside its scope. The act of
92 | running the Program is not restricted, and the output from the Program
93 | is covered only if its contents constitute a work based on the
94 | Program (independent of having been made by running the Program).
95 | Whether that is true depends on what the Program does.
96 |
97 | 1. You may copy and distribute verbatim copies of the Program's
98 | source code as you receive it, in any medium, provided that you
99 | conspicuously and appropriately publish on each copy an appropriate
100 | copyright notice and disclaimer of warranty; keep intact all the
101 | notices that refer to this License and to the absence of any warranty;
102 | and give any other recipients of the Program a copy of this License
103 | along with the Program.
104 |
105 | You may charge a fee for the physical act of transferring a copy, and
106 | you may at your option offer warranty protection in exchange for a fee.
107 |
108 | 2. You may modify your copy or copies of the Program or any portion
109 | of it, thus forming a work based on the Program, and copy and
110 | distribute such modifications or work under the terms of Section 1
111 | above, provided that you also meet all of these conditions:
112 |
113 | a) You must cause the modified files to carry prominent notices
114 | stating that you changed the files and the date of any change.
115 |
116 | b) You must cause any work that you distribute or publish, that in
117 | whole or in part contains or is derived from the Program or any
118 | part thereof, to be licensed as a whole at no charge to all third
119 | parties under the terms of this License.
120 |
121 | c) If the modified program normally reads commands interactively
122 | when run, you must cause it, when started running for such
123 | interactive use in the most ordinary way, to print or display an
124 | announcement including an appropriate copyright notice and a
125 | notice that there is no warranty (or else, saying that you provide
126 | a warranty) and that users may redistribute the program under
127 | these conditions, and telling the user how to view a copy of this
128 | License. (Exception: if the Program itself is interactive but
129 | does not normally print such an announcement, your work based on
130 | the Program is not required to print an announcement.)
131 |
132 | These requirements apply to the modified work as a whole. If
133 | identifiable sections of that work are not derived from the Program,
134 | and can be reasonably considered independent and separate works in
135 | themselves, then this License, and its terms, do not apply to those
136 | sections when you distribute them as separate works. But when you
137 | distribute the same sections as part of a whole which is a work based
138 | on the Program, the distribution of the whole must be on the terms of
139 | this License, whose permissions for other licensees extend to the
140 | entire whole, and thus to each and every part regardless of who wrote it.
141 |
142 | Thus, it is not the intent of this section to claim rights or contest
143 | your rights to work written entirely by you; rather, the intent is to
144 | exercise the right to control the distribution of derivative or
145 | collective works based on the Program.
146 |
147 | In addition, mere aggregation of another work not based on the Program
148 | with the Program (or with a work based on the Program) on a volume of
149 | a storage or distribution medium does not bring the other work under
150 | the scope of this License.
151 |
152 | 3. You may copy and distribute the Program (or a work based on it,
153 | under Section 2) in object code or executable form under the terms of
154 | Sections 1 and 2 above provided that you also do one of the following:
155 |
156 | a) Accompany it with the complete corresponding machine-readable
157 | source code, which must be distributed under the terms of Sections
158 | 1 and 2 above on a medium customarily used for software interchange; or,
159 |
160 | b) Accompany it with a written offer, valid for at least three
161 | years, to give any third party, for a charge no more than your
162 | cost of physically performing source distribution, a complete
163 | machine-readable copy of the corresponding source code, to be
164 | distributed under the terms of Sections 1 and 2 above on a medium
165 | customarily used for software interchange; or,
166 |
167 | c) Accompany it with the information you received as to the offer
168 | to distribute corresponding source code. (This alternative is
169 | allowed only for noncommercial distribution and only if you
170 | received the program in object code or executable form with such
171 | an offer, in accord with Subsection b above.)
172 |
173 | The source code for a work means the preferred form of the work for
174 | making modifications to it. For an executable work, complete source
175 | code means all the source code for all modules it contains, plus any
176 | associated interface definition files, plus the scripts used to
177 | control compilation and installation of the executable. However, as a
178 | special exception, the source code distributed need not include
179 | anything that is normally distributed (in either source or binary
180 | form) with the major components (compiler, kernel, and so on) of the
181 | operating system on which the executable runs, unless that component
182 | itself accompanies the executable.
183 |
184 | If distribution of executable or object code is made by offering
185 | access to copy from a designated place, then offering equivalent
186 | access to copy the source code from the same place counts as
187 | distribution of the source code, even though third parties are not
188 | compelled to copy the source along with the object code.
189 |
190 | 4. You may not copy, modify, sublicense, or distribute the Program
191 | except as expressly provided under this License. Any attempt
192 | otherwise to copy, modify, sublicense or distribute the Program is
193 | void, and will automatically terminate your rights under this License.
194 | However, parties who have received copies, or rights, from you under
195 | this License will not have their licenses terminated so long as such
196 | parties remain in full compliance.
197 |
198 | 5. You are not required to accept this License, since you have not
199 | signed it. However, nothing else grants you permission to modify or
200 | distribute the Program or its derivative works. These actions are
201 | prohibited by law if you do not accept this License. Therefore, by
202 | modifying or distributing the Program (or any work based on the
203 | Program), you indicate your acceptance of this License to do so, and
204 | all its terms and conditions for copying, distributing or modifying
205 | the Program or works based on it.
206 |
207 | 6. Each time you redistribute the Program (or any work based on the
208 | Program), the recipient automatically receives a license from the
209 | original licensor to copy, distribute or modify the Program subject to
210 | these terms and conditions. You may not impose any further
211 | restrictions on the recipients' exercise of the rights granted herein.
212 | You are not responsible for enforcing compliance by third parties to
213 | this License.
214 |
215 | 7. If, as a consequence of a court judgment or allegation of patent
216 | infringement or for any other reason (not limited to patent issues),
217 | conditions are imposed on you (whether by court order, agreement or
218 | otherwise) that contradict the conditions of this License, they do not
219 | excuse you from the conditions of this License. If you cannot
220 | distribute so as to satisfy simultaneously your obligations under this
221 | License and any other pertinent obligations, then as a consequence you
222 | may not distribute the Program at all. For example, if a patent
223 | license would not permit royalty-free redistribution of the Program by
224 | all those who receive copies directly or indirectly through you, then
225 | the only way you could satisfy both it and this License would be to
226 | refrain entirely from distribution of the Program.
227 |
228 | If any portion of this section is held invalid or unenforceable under
229 | any particular circumstance, the balance of the section is intended to
230 | apply and the section as a whole is intended to apply in other
231 | circumstances.
232 |
233 | It is not the purpose of this section to induce you to infringe any
234 | patents or other property right claims or to contest validity of any
235 | such claims; this section has the sole purpose of protecting the
236 | integrity of the free software distribution system, which is
237 | implemented by public license practices. Many people have made
238 | generous contributions to the wide range of software distributed
239 | through that system in reliance on consistent application of that
240 | system; it is up to the author/donor to decide if he or she is willing
241 | to distribute software through any other system and a licensee cannot
242 | impose that choice.
243 |
244 | This section is intended to make thoroughly clear what is believed to
245 | be a consequence of the rest of this License.
246 |
247 | 8. If the distribution and/or use of the Program is restricted in
248 | certain countries either by patents or by copyrighted interfaces, the
249 | original copyright holder who places the Program under this License
250 | may add an explicit geographical distribution limitation excluding
251 | those countries, so that distribution is permitted only in or among
252 | countries not thus excluded. In such case, this License incorporates
253 | the limitation as if written in the body of this License.
254 |
255 | 9. The Free Software Foundation may publish revised and/or new versions
256 | of the General Public License from time to time. Such new versions will
257 | be similar in spirit to the present version, but may differ in detail to
258 | address new problems or concerns.
259 |
260 | Each version is given a distinguishing version number. If the Program
261 | specifies a version number of this License which applies to it and "any
262 | later version", you have the option of following the terms and conditions
263 | either of that version or of any later version published by the Free
264 | Software Foundation. If the Program does not specify a version number of
265 | this License, you may choose any version ever published by the Free Software
266 | Foundation.
267 |
268 | 10. If you wish to incorporate parts of the Program into other free
269 | programs whose distribution conditions are different, write to the author
270 | to ask for permission. For software which is copyrighted by the Free
271 | Software Foundation, write to the Free Software Foundation; we sometimes
272 | make exceptions for this. Our decision will be guided by the two goals
273 | of preserving the free status of all derivatives of our free software and
274 | of promoting the sharing and reuse of software generally.
275 |
276 | NO WARRANTY
277 |
278 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
279 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
280 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
281 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
282 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
283 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
284 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
285 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
286 | REPAIR OR CORRECTION.
287 |
288 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
289 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
290 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
291 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
292 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
293 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
294 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
295 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
296 | POSSIBILITY OF SUCH DAMAGES.
297 |
298 | END OF TERMS AND CONDITIONS
299 |
300 | How to Apply These Terms to Your New Programs
301 |
302 | If you develop a new program, and you want it to be of the greatest
303 | possible use to the public, the best way to achieve this is to make it
304 | free software which everyone can redistribute and change under these terms.
305 |
306 | To do so, attach the following notices to the program. It is safest
307 | to attach them to the start of each source file to most effectively
308 | convey the exclusion of warranty; and each file should have at least
309 | the "copyright" line and a pointer to where the full notice is found.
310 |
311 |
312 | Copyright (C)
313 |
314 | This program is free software; you can redistribute it and/or modify
315 | it under the terms of the GNU General Public License as published by
316 | the Free Software Foundation; either version 2 of the License, or
317 | (at your option) any later version.
318 |
319 | This program is distributed in the hope that it will be useful,
320 | but WITHOUT ANY WARRANTY; without even the implied warranty of
321 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
322 | GNU General Public License for more details.
323 |
324 | You should have received a copy of the GNU General Public License along
325 | with this program; if not, write to the Free Software Foundation, Inc.,
326 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
327 |
328 | Also add information on how to contact you by electronic and paper mail.
329 |
330 | If the program is interactive, make it output a short notice like this
331 | when it starts in an interactive mode:
332 |
333 | Gnomovision version 69, Copyright (C) year name of author
334 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
335 | This is free software, and you are welcome to redistribute it
336 | under certain conditions; type `show c' for details.
337 |
338 | The hypothetical commands `show w' and `show c' should show the appropriate
339 | parts of the General Public License. Of course, the commands you use may
340 | be called something other than `show w' and `show c'; they could even be
341 | mouse-clicks or menu items--whatever suits your program.
342 |
343 | You should also get your employer (if you work as a programmer) or your
344 | school, if any, to sign a "copyright disclaimer" for the program, if
345 | necessary. Here is a sample; alter the names:
346 |
347 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
348 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
349 |
350 | , 1 April 1989
351 | Ty Coon, President of Vice
352 |
353 | This General Public License does not permit incorporating your program into
354 | proprietary programs. If your program is a subroutine library, you may
355 | consider it more useful to permit linking proprietary applications with the
356 | library. If this is what you want to do, use the GNU Lesser General
357 | Public License instead of this License.
358 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | A custom autoloader for Composer
2 | =====================================
3 |
4 | This is a custom autoloader generator that uses a classmap to always load the latest version of a class.
5 |
6 | The problem this autoloader is trying to solve is conflicts that arise when two or more plugins use the same package, but one of the plugins uses an older version of said package.
7 |
8 | This is solved by keeping an in memory map of all the different classes that can be loaded, and updating the map with the path to the latest version of the package for the autoloader to find when we instantiate the class.
9 |
10 | It diverges from the default Composer autoloader setup in the following ways:
11 |
12 | * It creates `jetpack_autoload_classmap.php` and `jetpack_autoload_filemap.php` files in the `vendor/composer` directory.
13 | * This file includes the version numbers from each package that is used.
14 | * The autoloader will only load the latest version of the package no matter what plugin loads the package. This behavior is guaranteed only when every plugin that uses the package uses this autoloader. If any plugin that requires the package uses a different autoloader, this autoloader may not be able to control which version of the package is loaded.
15 |
16 | Usage
17 | -----
18 |
19 | In your project's `composer.json`, add the following lines:
20 |
21 | ```json
22 | {
23 | "require": {
24 | "automattic/jetpack-autoloader": "^2"
25 | }
26 | }
27 | ```
28 |
29 | Your project must use the default composer vendor directory, `vendor`.
30 |
31 | After the next update/install, you will have a `vendor/autoload_packages.php` file.
32 | Load the file in your plugin via main plugin file.
33 |
34 | In the main plugin you will also need to include the files like this.
35 | ```php
36 | require_once plugin_dir_path( __FILE__ ) . '/vendor/autoload_packages.php';
37 | ```
38 |
39 | Working with Development Versions of Packages
40 | -----
41 |
42 | The autoloader will attempt to use the package with the latest semantic version.
43 |
44 | During development, you can force the autoloader to use development package versions by setting the `JETPACK_AUTOLOAD_DEV` constant to true. When `JETPACK_AUTOLOAD_DEV` is true, the autoloader will prefer the following versions over semantic versions:
45 | - `9999999-dev`
46 | - Versions with a `dev-` prefix.
47 |
48 |
49 | Autoloader Limitations and Caveats
50 | -----
51 |
52 | ### Plugin Updates
53 |
54 | When moving a package class file, renaming a package class file, or changing a package class namespace, make sure that the class will not be loaded after a plugin update.
55 |
56 | The autoloader builds the in memory classmap as soon as the autoloader is loaded. The package class file paths in the map are not updated after a plugin update. If a plugins's package class files are moved during a plugin update and a moved file is autoloaded after the update, an error will occur.
57 |
58 | ### Moving classes to a different package
59 |
60 | Jetpack Autoloader determines the hierarchy of class versions by package version numbers. It can cause problems if a class is moved to a newer package with a lower version number, it will get overshadowed by the old package.
61 |
62 | For instance, if your newer version of a class comes from a new package versioned 0.1.0, and the older version comes from a different package with a greater version number 2.0.1, the newer class will not get loaded.
63 |
64 | ### Jetpack Autoloader uses transient cache
65 |
66 | This is a caveat to be aware of when dealing with issues. The JP Autoloader uses transients to cache a list of available plugins to speed up the lookup process. This can sometimes mask problems that arise when loading code too early. See the [Debugging](#debugging) section for more information on how to detect situations like this.
67 |
68 | Debugging
69 | -----
70 |
71 | A common cause of confusing errors is when a plugin autoloads classes during the plugin load, before the 'plugins_loaded' hook. If that plugin has an older version of the class, that older version may be loaded before a plugin providing the newer version of the class has a chance to register. Even more confusingly, this will likely be intermittent, only showing up when the autoloader's plugin cache is invalidated. To debug this situation, you can set the `JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS` constant to true.
72 |
73 | Another common cause of confusing errors is when a plugin registers its own autoloader at a higher priority than the Jetpack Autoloader, and that autoloader would load packages that should be handled by the Jetpack Autoloader. Setting the `JETPACK_AUTOLOAD_DEBUG_CONFLICTING_LOADERS` constant to true will check for standard Composer autoloaders with such a conflict.
74 |
75 |
76 | Autoloading Standards
77 | ----
78 |
79 | All new Jetpack package development should use classmap autoloading, which allows the class and file names to comply with the WordPress Coding Standards.
80 |
81 | ### Optimized Autoloader
82 |
83 | An optimized autoloader is generated when:
84 | * `composer install` or `composer update` is called with `-o` or `--optimize-autoloader`
85 | * `composer dump-autoload` is called with `-o` or `--optimize`
86 |
87 | PSR-4 and PSR-0 namespaces are converted to classmaps.
88 |
89 | ### Unoptimized Autoloader
90 |
91 | Supports PSR-4 autoloading. PSR-0 namespaces are converted to classmaps.
92 |
93 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | Full details of the Automattic Security Policy can be found on [automattic.com](https://automattic.com/security/).
4 |
5 | ## Supported Versions
6 |
7 | Generally, only the latest version of Jetpack and its associated plugins have continued support. If a critical vulnerability is found in the current version of a plugin, we may opt to backport any patches to previous versions.
8 |
9 | ## Reporting a Vulnerability
10 |
11 | Our HackerOne program covers the below plugin software, as well as a variety of related projects and infrastructure:
12 |
13 | * [Jetpack](https://jetpack.com/)
14 | * Jetpack Backup
15 | * Jetpack Boost
16 | * Jetpack CRM
17 | * Jetpack Protect
18 | * Jetpack Search
19 | * Jetpack Social
20 | * Jetpack VideoPress
21 |
22 | **For responsible disclosure of security issues and to be eligible for our bug bounty program, please submit your report via the [HackerOne](https://hackerone.com/automattic) portal.**
23 |
24 | Our most critical targets are:
25 |
26 | * Jetpack and the Jetpack composer packages (all within this repo)
27 | * Jetpack.com -- the primary marketing site.
28 | * cloud.jetpack.com -- a management site.
29 | * wordpress.com -- the shared management site for both Jetpack and WordPress.com sites.
30 |
31 | For more targets, see the `In Scope` section on [HackerOne](https://hackerone.com/automattic).
32 |
33 | _Please note that the **WordPress software is a separate entity** from Automattic. Please report vulnerabilities for WordPress through [the WordPress Foundation's HackerOne page](https://hackerone.com/wordpress)._
34 |
35 | ## Guidelines
36 |
37 | We're committed to working with security researchers to resolve the vulnerabilities they discover. You can help us by following these guidelines:
38 |
39 | * Follow [HackerOne's disclosure guidelines](https://www.hackerone.com/disclosure-guidelines).
40 | * Pen-testing Production:
41 | * Please **setup a local environment** instead whenever possible. Most of our code is open source (see above).
42 | * If that's not possible, **limit any data access/modification** to the bare minimum necessary to reproduce a PoC.
43 | * **_Don't_ automate form submissions!** That's very annoying for us, because it adds extra work for the volunteers who manage those systems, and reduces the signal/noise ratio in our communication channels.
44 | * To be eligible for a bounty, all of these guidelines must be followed.
45 | * Be Patient - Give us a reasonable time to correct the issue before you disclose the vulnerability.
46 |
47 | We also expect you to comply with all applicable laws. You're responsible to pay any taxes associated with your bounties.
48 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "automattic/jetpack-autoloader",
3 | "description": "Creates a custom autoloader for a plugin or theme.",
4 | "type": "composer-plugin",
5 | "license": "GPL-2.0-or-later",
6 | "keywords": [
7 | "autoload",
8 | "autoloader",
9 | "composer",
10 | "plugin",
11 | "jetpack",
12 | "wordpress"
13 | ],
14 | "require": {
15 | "php": ">=7.2",
16 | "composer-plugin-api": "^2.2"
17 | },
18 | "require-dev": {
19 | "composer/composer": "^2.2",
20 | "yoast/phpunit-polyfills": "^4.0.0",
21 | "automattic/jetpack-changelogger": "^6.0.5",
22 | "automattic/phpunit-select-config": "^1.0.3"
23 | },
24 | "autoload": {
25 | "classmap": [
26 | "src/AutoloadGenerator.php"
27 | ],
28 | "psr-4": {
29 | "Automattic\\Jetpack\\Autoloader\\": "src"
30 | }
31 | },
32 | "scripts": {
33 | "phpunit": [
34 | "phpunit-select-config phpunit.#.xml.dist --colors=always"
35 | ],
36 | "test-coverage": [
37 | "php -dpcov.directory=. ./vendor/bin/phpunit-select-config phpunit.#.xml.dist --coverage-php \"./tests/php/tmp/coverage-report.php\"",
38 | "php ./tests/php/bin/test-coverage.php \"$COVERAGE_DIR/php.cov\""
39 | ],
40 | "test-php": [
41 | "@composer phpunit"
42 | ]
43 | },
44 | "minimum-stability": "dev",
45 | "prefer-stable": true,
46 | "extra": {
47 | "autotagger": true,
48 | "class": "Automattic\\Jetpack\\Autoloader\\CustomAutoloaderPlugin",
49 | "mirror-repo": "Automattic/jetpack-autoloader",
50 | "changelogger": {
51 | "link-template": "https://github.com/Automattic/jetpack-autoloader/compare/v${old}...v${new}"
52 | },
53 | "version-constants": {
54 | "::VERSION": "src/AutoloadGenerator.php"
55 | },
56 | "branch-alias": {
57 | "dev-trunk": "5.0.x-dev"
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/AutoloadFileWriter.php:
--------------------------------------------------------------------------------
1 | '../autoload_packages.php',
39 | );
40 | $ignoreList = array(
41 | 'AutoloadGenerator.php',
42 | 'AutoloadProcessor.php',
43 | 'CustomAutoloaderPlugin.php',
44 | 'ManifestGenerator.php',
45 | 'AutoloadFileWriter.php',
46 | );
47 |
48 | // Copy all of the autoloader files.
49 | $files = scandir( __DIR__ );
50 | foreach ( $files as $file ) {
51 | // Only PHP files will be copied.
52 | if ( substr( $file, -4 ) !== '.php' ) {
53 | continue;
54 | }
55 |
56 | if ( in_array( $file, $ignoreList, true ) ) {
57 | continue;
58 | }
59 |
60 | $newFile = $renameList[ $file ] ?? $file;
61 | $content = self::prepareAutoloaderFile( $file, $suffix );
62 |
63 | $written = file_put_contents( $outDir . '/' . $newFile, $content );
64 | if ( $io ) {
65 | if ( $written ) {
66 | $io->writeError( " Generated: $newFile" );
67 | } else {
68 | $io->writeError( " Error: $newFile" );
69 | }
70 | }
71 | }
72 | }
73 |
74 | /**
75 | * Prepares an autoloader file to be written to the destination.
76 | *
77 | * @param String $filename a file to prepare.
78 | * @param String $suffix Unique suffix used in the namespace.
79 | *
80 | * @return string
81 | */
82 | private static function prepareAutoloaderFile( $filename, $suffix ) {
83 | $header = self::COMMENT;
84 | $header .= PHP_EOL;
85 | if ( $suffix === 'Current' ) {
86 | // Unit testing.
87 | $header .= 'namespace Automattic\Jetpack\Autoloader\jpCurrent;';
88 | } else {
89 | $header .= 'namespace Automattic\Jetpack\Autoloader\jp' . $suffix . '\al' . preg_replace( '/[^0-9a-zA-Z]/', '_', AutoloadGenerator::VERSION ) . ';';
90 | }
91 | $header .= PHP_EOL . PHP_EOL;
92 |
93 | $sourceLoader = fopen( __DIR__ . '/' . $filename, 'r' );
94 | $file_contents = stream_get_contents( $sourceLoader );
95 | return str_replace(
96 | '/* HEADER */',
97 | $header,
98 | $file_contents
99 | );
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/AutoloadGenerator.php:
--------------------------------------------------------------------------------
1 | io = $io;
47 | $this->filesystem = new Filesystem();
48 | }
49 |
50 | /**
51 | * Dump the Jetpack autoloader files.
52 | *
53 | * @param Composer $composer The Composer object.
54 | * @param Config $config Config object.
55 | * @param InstalledRepositoryInterface $localRepo Installed Repository object.
56 | * @param PackageInterface $mainPackage Main Package object.
57 | * @param InstallationManager $installationManager Manager for installing packages.
58 | * @param string $targetDir Path to the current target directory.
59 | * @param bool $scanPsrPackages Whether or not PSR packages should be converted to a classmap.
60 | * @param string $suffix The autoloader suffix.
61 | */
62 | public function dump(
63 | Composer $composer,
64 | Config $config,
65 | InstalledRepositoryInterface $localRepo,
66 | PackageInterface $mainPackage,
67 | InstallationManager $installationManager,
68 | $targetDir,
69 | $scanPsrPackages = false,
70 | $suffix = null
71 | ) {
72 | $this->filesystem->ensureDirectoryExists( $config->get( 'vendor-dir' ) );
73 |
74 | $packageMap = $composer->getAutoloadGenerator()->buildPackageMap( $installationManager, $mainPackage, $localRepo->getCanonicalPackages() );
75 | $autoloads = $this->parseAutoloads( $packageMap, $mainPackage );
76 |
77 | // Convert the autoloads into a format that the manifest generator can consume more easily.
78 | $basePath = $this->filesystem->normalizePath( realpath( getcwd() ) );
79 | $vendorPath = $this->filesystem->normalizePath( realpath( $config->get( 'vendor-dir' ) ) );
80 | $processedAutoloads = $this->processAutoloads( $autoloads, $scanPsrPackages, $vendorPath, $basePath );
81 | unset( $packageMap, $autoloads );
82 |
83 | // Make sure none of the legacy files remain that can lead to problems with the autoloader.
84 | $this->removeLegacyFiles( $vendorPath );
85 |
86 | // Write all of the files now that we're done.
87 | $this->writeAutoloaderFiles( $vendorPath . '/jetpack-autoloader/', $suffix );
88 | $this->writeManifests( $vendorPath . '/' . $targetDir, $processedAutoloads );
89 |
90 | if ( ! $scanPsrPackages ) {
91 | $this->io->writeError( 'You are generating an unoptimized autoloader. If this is a production build, consider using the -o option.' );
92 | }
93 | }
94 |
95 | /**
96 | * Compiles an ordered list of namespace => path mappings
97 | *
98 | * @param array $packageMap Array of array(package, installDir-relative-to-composer.json).
99 | * @param PackageInterface $mainPackage Main package instance.
100 | *
101 | * @return array The list of path mappings.
102 | */
103 | public function parseAutoloads( array $packageMap, PackageInterface $mainPackage ) {
104 | $rootPackageMap = array_shift( $packageMap );
105 |
106 | $sortedPackageMap = $this->sortPackageMap( $packageMap );
107 | $sortedPackageMap[] = $rootPackageMap;
108 | array_unshift( $packageMap, $rootPackageMap );
109 |
110 | $psr0 = $this->parseAutoloadsType( $packageMap, 'psr-0', $mainPackage );
111 | $psr4 = $this->parseAutoloadsType( $packageMap, 'psr-4', $mainPackage );
112 | $classmap = $this->parseAutoloadsType( array_reverse( $sortedPackageMap ), 'classmap', $mainPackage );
113 | $files = $this->parseAutoloadsType( $sortedPackageMap, 'files', $mainPackage );
114 |
115 | krsort( $psr0 );
116 | krsort( $psr4 );
117 |
118 | return array(
119 | 'psr-0' => $psr0,
120 | 'psr-4' => $psr4,
121 | 'classmap' => $classmap,
122 | 'files' => $files,
123 | );
124 | }
125 |
126 | /**
127 | * Sorts packages by dependency weight
128 | *
129 | * Packages of equal weight retain the original order
130 | *
131 | * @param array $packageMap The package map.
132 | *
133 | * @return array
134 | */
135 | protected function sortPackageMap( array $packageMap ) {
136 | $packages = array();
137 | $paths = array();
138 |
139 | foreach ( $packageMap as $item ) {
140 | list( $package, $path ) = $item;
141 | $name = $package->getName();
142 | $packages[ $name ] = $package;
143 | $paths[ $name ] = $path;
144 | }
145 |
146 | $sortedPackages = PackageSorter::sortPackages( $packages );
147 |
148 | $sortedPackageMap = array();
149 |
150 | foreach ( $sortedPackages as $package ) {
151 | $name = $package->getName();
152 | $sortedPackageMap[] = array( $packages[ $name ], $paths[ $name ] );
153 | }
154 |
155 | return $sortedPackageMap;
156 | }
157 |
158 | /**
159 | * Returns the file identifier.
160 | *
161 | * @param PackageInterface $package The package instance.
162 | * @param string $path The path.
163 | */
164 | protected function getFileIdentifier( PackageInterface $package, $path ) {
165 | return md5( $package->getName() . ':' . $path );
166 | }
167 |
168 | /**
169 | * Returns the path code for the given path.
170 | *
171 | * @param Filesystem $filesystem The filesystem instance.
172 | * @param string $basePath The base path.
173 | * @param string $vendorPath The vendor path.
174 | * @param string $path The path.
175 | *
176 | * @return string The path code.
177 | */
178 | protected function getPathCode( Filesystem $filesystem, $basePath, $vendorPath, $path ) {
179 | if ( ! $filesystem->isAbsolutePath( $path ) ) {
180 | $path = $basePath . '/' . $path;
181 | }
182 | $path = $filesystem->normalizePath( $path );
183 |
184 | $baseDir = '';
185 | if ( 0 === strpos( $path . '/', $vendorPath . '/' ) ) {
186 | $path = substr( $path, strlen( $vendorPath ) );
187 | $baseDir = '$vendorDir';
188 |
189 | if ( false !== $path ) {
190 | $baseDir .= ' . ';
191 | }
192 | } else {
193 | $path = $filesystem->normalizePath( $filesystem->findShortestPath( $basePath, $path, true ) );
194 | if ( ! $filesystem->isAbsolutePath( $path ) ) {
195 | $baseDir = '$baseDir . ';
196 | $path = '/' . $path;
197 | }
198 | }
199 |
200 | if ( strpos( $path, '.phar' ) !== false ) {
201 | $baseDir = "'phar://' . " . $baseDir;
202 | }
203 |
204 | // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
205 | return $baseDir . ( ( false !== $path ) ? var_export( $path, true ) : '' );
206 | }
207 |
208 | /**
209 | * This function differs from the composer parseAutoloadsType in that beside returning the path.
210 | * It also return the path and the version of a package.
211 | *
212 | * Supports PSR-4, PSR-0, and classmap parsing.
213 | *
214 | * @param array $packageMap Map of all the packages.
215 | * @param string $type Type of autoloader to use.
216 | * @param PackageInterface $mainPackage Instance of the Package Object.
217 | *
218 | * @return array
219 | */
220 | protected function parseAutoloadsType( array $packageMap, $type, PackageInterface $mainPackage ) {
221 | $autoloads = array();
222 |
223 | foreach ( $packageMap as $item ) {
224 | list($package, $installPath) = $item;
225 | $autoload = $package->getAutoload();
226 | $version = $package->getVersion(); // Version of the class comes from the package - should we try to parse it?
227 |
228 | // Store our own actual package version, not "dev-trunk" or whatever.
229 | if ( $package->getName() === 'automattic/jetpack-autoloader' ) {
230 | $version = self::VERSION;
231 | }
232 |
233 | if ( $package === $mainPackage ) {
234 | $autoload = array_merge_recursive( $autoload, $package->getDevAutoload() );
235 | }
236 |
237 | if ( null !== $package->getTargetDir() && $package !== $mainPackage ) {
238 | $installPath = substr( $installPath, 0, -strlen( '/' . $package->getTargetDir() ) );
239 | }
240 |
241 | if ( in_array( $type, array( 'psr-4', 'psr-0' ), true ) && isset( $autoload[ $type ] ) && is_array( $autoload[ $type ] ) ) {
242 | foreach ( $autoload[ $type ] as $namespace => $paths ) {
243 | $paths = is_array( $paths ) ? $paths : array( $paths );
244 | foreach ( $paths as $path ) {
245 | $relativePath = empty( $installPath ) ? ( empty( $path ) ? '.' : $path ) : $installPath . '/' . $path;
246 | $autoloads[ $namespace ][] = array(
247 | 'path' => $relativePath,
248 | 'version' => $version,
249 | );
250 | }
251 | }
252 | }
253 |
254 | if ( 'classmap' === $type && isset( $autoload['classmap'] ) && is_array( $autoload['classmap'] ) ) {
255 | foreach ( $autoload['classmap'] as $paths ) {
256 | $paths = is_array( $paths ) ? $paths : array( $paths );
257 | foreach ( $paths as $path ) {
258 | $relativePath = empty( $installPath ) ? ( empty( $path ) ? '.' : $path ) : $installPath . '/' . $path;
259 | $autoloads[] = array(
260 | 'path' => $relativePath,
261 | 'version' => $version,
262 | );
263 | }
264 | }
265 | }
266 | if ( 'files' === $type && isset( $autoload['files'] ) && is_array( $autoload['files'] ) ) {
267 | foreach ( $autoload['files'] as $paths ) {
268 | $paths = is_array( $paths ) ? $paths : array( $paths );
269 | foreach ( $paths as $path ) {
270 | $relativePath = empty( $installPath ) ? ( empty( $path ) ? '.' : $path ) : $installPath . '/' . $path;
271 | $autoloads[ $this->getFileIdentifier( $package, $path ) ] = array(
272 | 'path' => $relativePath,
273 | 'version' => $version,
274 | );
275 | }
276 | }
277 | }
278 | }
279 |
280 | return $autoloads;
281 | }
282 |
283 | /**
284 | * Given Composer's autoloads this will convert them to a version that we can use to generate the manifests.
285 | *
286 | * When the $scanPsrPackages argument is true, PSR-4 namespaces are converted to classmaps. When $scanPsrPackages
287 | * is false, PSR-4 namespaces are not converted to classmaps.
288 | *
289 | * PSR-0 namespaces are always converted to classmaps.
290 | *
291 | * @param array $autoloads The autoloads we want to process.
292 | * @param bool $scanPsrPackages Whether or not PSR-4 packages should be converted to a classmap.
293 | * @param string $vendorPath The path to the vendor directory.
294 | * @param string $basePath The path to the current directory.
295 | *
296 | * @return array $processedAutoloads
297 | */
298 | private function processAutoloads( $autoloads, $scanPsrPackages, $vendorPath, $basePath ) {
299 | $processor = new AutoloadProcessor(
300 | function ( $path, $excludedClasses, $namespace ) use ( $basePath ) {
301 | $dir = $this->filesystem->normalizePath(
302 | $this->filesystem->isAbsolutePath( $path ) ? $path : $basePath . '/' . $path
303 | );
304 |
305 | // Composer 2.4 changed the name of the class.
306 | if ( class_exists( \Composer\ClassMapGenerator\ClassMapGenerator::class ) ) {
307 | if ( ! is_dir( $dir ) && ! is_file( $dir ) ) {
308 | return array();
309 | }
310 | $generator = new \Composer\ClassMapGenerator\ClassMapGenerator();
311 | $generator->scanPaths( $dir, $excludedClasses, 'classmap', empty( $namespace ) ? null : $namespace );
312 | return $generator->getClassMap()->getMap();
313 | }
314 |
315 | return \Composer\Autoload\ClassMapGenerator::createMap(
316 | $dir,
317 | $excludedClasses,
318 | null, // Don't pass the IOInterface since the normal autoload generation will have reported already.
319 | empty( $namespace ) ? null : $namespace
320 | );
321 | },
322 | function ( $path ) use ( $basePath, $vendorPath ) {
323 | return $this->getPathCode( $this->filesystem, $basePath, $vendorPath, $path );
324 | }
325 | );
326 |
327 | return array(
328 | 'psr-4' => $processor->processPsr4Packages( $autoloads, $scanPsrPackages ),
329 | 'classmap' => $processor->processClassmap( $autoloads, $scanPsrPackages ),
330 | 'files' => $processor->processFiles( $autoloads ),
331 | );
332 | }
333 |
334 | /**
335 | * Removes all of the legacy autoloader files so they don't cause any problems.
336 | *
337 | * @param string $outDir The directory legacy files are written to.
338 | */
339 | private function removeLegacyFiles( $outDir ) {
340 | $files = array(
341 | 'autoload_functions.php',
342 | 'class-autoloader-handler.php',
343 | 'class-classes-handler.php',
344 | 'class-files-handler.php',
345 | 'class-plugins-handler.php',
346 | 'class-version-selector.php',
347 | );
348 | foreach ( $files as $file ) {
349 | $this->filesystem->remove( $outDir . '/' . $file );
350 | }
351 | }
352 |
353 | /**
354 | * Writes all of the autoloader files to disk.
355 | *
356 | * @param string $outDir The directory to write to.
357 | * @param string $suffix The unique autoloader suffix.
358 | */
359 | private function writeAutoloaderFiles( $outDir, $suffix ) {
360 | $this->io->writeError( "Generating jetpack autoloader ($outDir)" );
361 |
362 | // We will remove all autoloader files to generate this again.
363 | $this->filesystem->emptyDirectory( $outDir );
364 |
365 | // Write the autoloader files.
366 | AutoloadFileWriter::copyAutoloaderFiles( $this->io, $outDir, $suffix );
367 | }
368 |
369 | /**
370 | * Writes all of the manifest files to disk.
371 | *
372 | * @param string $outDir The directory to write to.
373 | * @param array $processedAutoloads The processed autoloads.
374 | */
375 | private function writeManifests( $outDir, $processedAutoloads ) {
376 | $this->io->writeError( "Generating jetpack autoloader manifests ($outDir)" );
377 |
378 | $manifestFiles = array(
379 | 'classmap' => 'jetpack_autoload_classmap.php',
380 | 'psr-4' => 'jetpack_autoload_psr4.php',
381 | 'files' => 'jetpack_autoload_filemap.php',
382 | );
383 |
384 | foreach ( $manifestFiles as $key => $file ) {
385 | // Make sure the file doesn't exist so it isn't there if we don't write it.
386 | $this->filesystem->remove( $outDir . '/' . $file );
387 | if ( empty( $processedAutoloads[ $key ] ) ) {
388 | continue;
389 | }
390 |
391 | $content = ManifestGenerator::buildManifest( $key, $file, $processedAutoloads[ $key ] );
392 | if ( empty( $content ) ) {
393 | continue;
394 | }
395 |
396 | if ( file_put_contents( $outDir . '/' . $file, $content ) ) {
397 | $this->io->writeError( " Generated: $file" );
398 | } else {
399 | $this->io->writeError( " Error: $file" );
400 | }
401 | }
402 | }
403 | }
404 |
--------------------------------------------------------------------------------
/src/AutoloadProcessor.php:
--------------------------------------------------------------------------------
1 | classmapScanner = $classmapScanner;
37 | $this->pathCodeTransformer = $pathCodeTransformer;
38 | }
39 |
40 | /**
41 | * Processes the classmap autoloads into a relative path format including the version for each file.
42 | *
43 | * @param array $autoloads The autoloads we are processing.
44 | * @param bool $scanPsrPackages Whether or not PSR packages should be converted to a classmap.
45 | *
46 | * @return array|null $processed
47 | * @phan-param array{classmap:?array{path:string,version:string}[],psr-4:?array,psr-0:?array} $autoloads
48 | */
49 | public function processClassmap( $autoloads, $scanPsrPackages ) {
50 | // We can't scan PSR packages if we don't actually have any.
51 | if ( empty( $autoloads['psr-4'] ) ) {
52 | $scanPsrPackages = false;
53 | }
54 |
55 | if ( empty( $autoloads['classmap'] ) && ! $scanPsrPackages ) {
56 | return null;
57 | }
58 |
59 | $excludedClasses = null;
60 | if ( ! empty( $autoloads['exclude-from-classmap'] ) ) {
61 | $excludedClasses = '{(' . implode( '|', $autoloads['exclude-from-classmap'] ) . ')}';
62 | }
63 |
64 | $processed = array();
65 |
66 | if ( $scanPsrPackages ) {
67 | foreach ( $autoloads['psr-4'] as $namespace => $sources ) {
68 | $namespace = empty( $namespace ) ? null : $namespace;
69 |
70 | foreach ( $sources as $source ) {
71 | $classmap = call_user_func( $this->classmapScanner, $source['path'], $excludedClasses, $namespace );
72 |
73 | foreach ( $classmap as $class => $path ) {
74 | $processed[ $class ] = array(
75 | 'version' => $source['version'],
76 | 'path' => call_user_func( $this->pathCodeTransformer, $path ),
77 | );
78 | }
79 | }
80 | }
81 | }
82 |
83 | /*
84 | * PSR-0 namespaces are converted to classmaps for both optimized and unoptimized autoloaders because any new
85 | * development should use classmap or PSR-4 autoloading.
86 | */
87 | if ( ! empty( $autoloads['psr-0'] ) ) {
88 | foreach ( $autoloads['psr-0'] as $namespace => $sources ) {
89 | $namespace = empty( $namespace ) ? null : $namespace;
90 |
91 | foreach ( $sources as $source ) {
92 | $classmap = call_user_func( $this->classmapScanner, $source['path'], $excludedClasses, $namespace );
93 | foreach ( $classmap as $class => $path ) {
94 | $processed[ $class ] = array(
95 | 'version' => $source['version'],
96 | 'path' => call_user_func( $this->pathCodeTransformer, $path ),
97 | );
98 | }
99 | }
100 | }
101 | }
102 |
103 | if ( ! empty( $autoloads['classmap'] ) ) {
104 | foreach ( $autoloads['classmap'] as $package ) {
105 | $classmap = call_user_func( $this->classmapScanner, $package['path'], $excludedClasses, null );
106 |
107 | foreach ( $classmap as $class => $path ) {
108 | $processed[ $class ] = array(
109 | 'version' => $package['version'],
110 | 'path' => call_user_func( $this->pathCodeTransformer, $path ),
111 | );
112 | }
113 | }
114 | }
115 |
116 | ksort( $processed );
117 |
118 | return $processed;
119 | }
120 |
121 | /**
122 | * Processes the PSR-4 autoloads into a relative path format including the version for each file.
123 | *
124 | * @param array $autoloads The autoloads we are processing.
125 | * @param bool $scanPsrPackages Whether or not PSR packages should be converted to a classmap.
126 | *
127 | * @return array|null $processed
128 | */
129 | public function processPsr4Packages( $autoloads, $scanPsrPackages ) {
130 | if ( $scanPsrPackages || empty( $autoloads['psr-4'] ) ) {
131 | return null;
132 | }
133 |
134 | $processed = array();
135 |
136 | foreach ( $autoloads['psr-4'] as $namespace => $packages ) {
137 | $namespace = empty( $namespace ) ? null : $namespace;
138 | $paths = array();
139 |
140 | foreach ( $packages as $package ) {
141 | $paths[] = call_user_func( $this->pathCodeTransformer, $package['path'] );
142 | }
143 |
144 | $processed[ $namespace ] = array(
145 | 'version' => $package['version'],
146 | 'path' => $paths,
147 | );
148 | }
149 |
150 | return $processed;
151 | }
152 |
153 | /**
154 | * Processes the file autoloads into a relative format including the version for each file.
155 | *
156 | * @param array $autoloads The autoloads we are processing.
157 | *
158 | * @return array|null $processed
159 | */
160 | public function processFiles( $autoloads ) {
161 | if ( empty( $autoloads['files'] ) ) {
162 | return null;
163 | }
164 |
165 | $processed = array();
166 |
167 | foreach ( $autoloads['files'] as $file_id => $package ) {
168 | $processed[ $file_id ] = array(
169 | 'version' => $package['version'],
170 | 'path' => call_user_func( $this->pathCodeTransformer, $package['path'] ),
171 | );
172 | }
173 |
174 | return $processed;
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/src/CustomAutoloaderPlugin.php:
--------------------------------------------------------------------------------
1 | composer = $composer;
46 | $this->io = $io;
47 | }
48 |
49 | /**
50 | * Do nothing.
51 | * phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
52 | *
53 | * @param Composer $composer Composer object.
54 | * @param IOInterface $io IO object.
55 | */
56 | public function deactivate( Composer $composer, IOInterface $io ) {
57 | /*
58 | * Intentionally left empty. This is a PluginInterface method.
59 | * phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
60 | */
61 | }
62 |
63 | /**
64 | * Do nothing.
65 | * phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
66 | *
67 | * @param Composer $composer Composer object.
68 | * @param IOInterface $io IO object.
69 | */
70 | public function uninstall( Composer $composer, IOInterface $io ) {
71 | /*
72 | * Intentionally left empty. This is a PluginInterface method.
73 | * phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
74 | */
75 | }
76 |
77 | /**
78 | * Tell composer to listen for events and do something with them.
79 | *
80 | * @return array List of subscribed events.
81 | */
82 | public static function getSubscribedEvents() {
83 | return array(
84 | ScriptEvents::POST_AUTOLOAD_DUMP => 'postAutoloadDump',
85 | );
86 | }
87 |
88 | /**
89 | * Generate the custom autolaoder.
90 | *
91 | * @param Event $event Script event object.
92 | */
93 | public function postAutoloadDump( Event $event ) {
94 | // When the autoloader is not required by the root package we don't want to execute it.
95 | // This prevents unwanted transitive execution that generates unused autoloaders or
96 | // at worst throws fatal executions.
97 | if ( ! $this->isRequiredByRoot() ) {
98 | return;
99 | }
100 |
101 | $config = $this->composer->getConfig();
102 |
103 | if ( 'vendor' !== $config->raw()['config']['vendor-dir'] ) {
104 | $this->io->writeError( "\nAn error occurred while generating the autoloader files:", true );
105 | $this->io->writeError( 'The project\'s composer.json or composer environment set a non-default vendor directory.', true );
106 | $this->io->writeError( 'The default composer vendor directory must be used.', true );
107 | exit( 0 );
108 | }
109 |
110 | $installationManager = $this->composer->getInstallationManager();
111 | $repoManager = $this->composer->getRepositoryManager();
112 | $localRepo = $repoManager->getLocalRepository();
113 | $package = $this->composer->getPackage();
114 | $optimize = $event->getFlags()['optimize'];
115 | $suffix = $this->determineSuffix();
116 |
117 | $generator = new AutoloadGenerator( $this->io );
118 | $generator->dump( $this->composer, $config, $localRepo, $package, $installationManager, 'composer', $optimize, $suffix );
119 | }
120 |
121 | /**
122 | * Determine the suffix for the autoloader class.
123 | *
124 | * Reuses an existing suffix from vendor/autoload_packages.php or vendor/autoload.php if possible.
125 | *
126 | * @return string Suffix.
127 | */
128 | private function determineSuffix() {
129 | $config = $this->composer->getConfig();
130 | $vendorPath = $config->get( 'vendor-dir' );
131 |
132 | // Command line.
133 | $suffix = $config->get( 'autoloader-suffix' );
134 | if ( $suffix ) {
135 | return $suffix;
136 | }
137 |
138 | // Reuse our own suffix, if any.
139 | if ( is_readable( $vendorPath . '/autoload_packages.php' ) ) {
140 | $content = file_get_contents( $vendorPath . '/autoload_packages.php' );
141 | if ( preg_match( '/^namespace Automattic\\\\Jetpack\\\\Autoloader\\\\jp([^;\s]+?)(?:\\\\al[^;\s]+)?;/m', $content, $match ) ) {
142 | return $match[1];
143 | }
144 | }
145 |
146 | // Reuse Composer's suffix, if any.
147 | if ( is_readable( $vendorPath . '/autoload.php' ) ) {
148 | $content = file_get_contents( $vendorPath . '/autoload.php' );
149 | if ( preg_match( '{ComposerAutoloaderInit([^:\s]+)::}', $content, $match ) ) {
150 | return $match[1];
151 | }
152 | }
153 |
154 | // Generate a random suffix.
155 | return md5( uniqid( '', true ) );
156 | }
157 |
158 | /**
159 | * Checks to see whether or not the root package is the one that required the autoloader.
160 | *
161 | * @return bool
162 | */
163 | private function isRequiredByRoot() {
164 | $package = $this->composer->getPackage();
165 | $requires = $package->getRequires();
166 | if ( ! is_array( $requires ) ) { // @phan-suppress-current-line PhanRedundantCondition -- Earlier Composer versions may not have guaranteed this.
167 | $requires = array();
168 | }
169 | $devRequires = $package->getDevRequires();
170 | if ( ! is_array( $devRequires ) ) { // @phan-suppress-current-line PhanRedundantCondition -- Earlier Composer versions may not have guaranteed this.
171 | $devRequires = array();
172 | }
173 | $requires = array_merge( $requires, $devRequires );
174 |
175 | if ( empty( $requires ) ) {
176 | $this->io->writeError( "\nThe package is not required and this should never happen?", true );
177 | exit( 0 );
178 | }
179 |
180 | foreach ( $requires as $require ) {
181 | if ( 'automattic/jetpack-autoloader' === $require->getTarget() ) {
182 | return true;
183 | }
184 | }
185 |
186 | return false;
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/src/ManifestGenerator.php:
--------------------------------------------------------------------------------
1 | $data ) {
54 | $key = var_export( $key, true );
55 | $versionCode = var_export( $data['version'], true );
56 | $fileContent .= << array(
58 | 'version' => $versionCode,
59 | 'path' => {$data['path']}
60 | ),
61 | MANIFEST_CODE;
62 | $fileContent .= PHP_EOL;
63 | }
64 |
65 | return self::buildFile( $fileName, $fileContent );
66 | }
67 |
68 | /**
69 | * Builds the contents for the PSR-4 manifest file.
70 | *
71 | * @param string $fileName The filename we are building.
72 | * @param array $namespaces The formatted PSR-4 data for the manifest.
73 | *
74 | * @return string|null $manifestFile
75 | */
76 | private static function buildPsr4Manifest( $fileName, $namespaces ) {
77 | $fileContent = PHP_EOL;
78 | foreach ( $namespaces as $namespace => $data ) {
79 | $namespaceCode = var_export( $namespace, true );
80 | $versionCode = var_export( $data['version'], true );
81 | $pathCode = 'array( ' . implode( ', ', $data['path'] ) . ' )';
82 | $fileContent .= << array(
84 | 'version' => $versionCode,
85 | 'path' => $pathCode
86 | ),
87 | MANIFEST_CODE;
88 | $fileContent .= PHP_EOL;
89 | }
90 |
91 | return self::buildFile( $fileName, $fileContent );
92 | }
93 |
94 | /**
95 | * Generate the PHP that will be used in the file.
96 | *
97 | * @param string $fileName The filename we are building.
98 | * @param string $content The content to be written into the file.
99 | *
100 | * @return string $fileContent
101 | */
102 | private static function buildFile( $fileName, $content ) {
103 | return <<php_autoloader = $php_autoloader;
49 | $this->hook_manager = $hook_manager;
50 | $this->manifest_reader = $manifest_reader;
51 | $this->version_selector = $version_selector;
52 | }
53 |
54 | /**
55 | * Checks to see whether or not an autoloader is currently in the process of initializing.
56 | *
57 | * @return bool
58 | */
59 | public function is_initializing() {
60 | // If no version has been set it means that no autoloader has started initializing yet.
61 | global $jetpack_autoloader_latest_version;
62 | if ( ! isset( $jetpack_autoloader_latest_version ) ) {
63 | return false;
64 | }
65 |
66 | // When the version is set but the classmap is not it ALWAYS means that this is the
67 | // latest autoloader and is being included by an older one.
68 | global $jetpack_packages_classmap;
69 | if ( empty( $jetpack_packages_classmap ) ) {
70 | return true;
71 | }
72 |
73 | // Version 2.4.0 added a new global and altered the reset semantics. We need to check
74 | // the other global as well since it may also point at initialization.
75 | // Note: We don't need to check for the class first because every autoloader that
76 | // will set the latest version global requires this class in the classmap.
77 | $replacing_version = $jetpack_packages_classmap[ AutoloadGenerator::class ]['version'];
78 | if ( $this->version_selector->is_dev_version( $replacing_version ) || version_compare( $replacing_version, '2.4.0.0', '>=' ) ) {
79 | global $jetpack_autoloader_loader;
80 | if ( ! isset( $jetpack_autoloader_loader ) ) {
81 | return true;
82 | }
83 | }
84 |
85 | return false;
86 | }
87 |
88 | /**
89 | * Activates an autoloader using the given plugins and activates it.
90 | *
91 | * @param string[] $plugins The plugins to initialize the autoloader for.
92 | */
93 | public function activate_autoloader( $plugins ) {
94 | global $jetpack_packages_psr4;
95 | $jetpack_packages_psr4 = array();
96 | $this->manifest_reader->read_manifests( $plugins, 'vendor/composer/jetpack_autoload_psr4.php', $jetpack_packages_psr4 );
97 |
98 | global $jetpack_packages_classmap;
99 | $jetpack_packages_classmap = array();
100 | $this->manifest_reader->read_manifests( $plugins, 'vendor/composer/jetpack_autoload_classmap.php', $jetpack_packages_classmap );
101 |
102 | global $jetpack_packages_filemap;
103 | $jetpack_packages_filemap = array();
104 | $this->manifest_reader->read_manifests( $plugins, 'vendor/composer/jetpack_autoload_filemap.php', $jetpack_packages_filemap );
105 |
106 | $loader = new Version_Loader(
107 | $this->version_selector,
108 | $jetpack_packages_classmap,
109 | $jetpack_packages_psr4,
110 | $jetpack_packages_filemap
111 | );
112 |
113 | $this->php_autoloader->register_autoloader( $loader );
114 |
115 | // Now that the autoloader is active we can load the filemap.
116 | $loader->load_filemap();
117 | }
118 |
119 | /**
120 | * Resets the active autoloader and all related global state.
121 | */
122 | public function reset_autoloader() {
123 | $this->php_autoloader->unregister_autoloader();
124 | $this->hook_manager->reset();
125 |
126 | // Clear all of the autoloader globals so that older autoloaders don't do anything strange.
127 | global $jetpack_autoloader_latest_version;
128 | $jetpack_autoloader_latest_version = null;
129 |
130 | global $jetpack_packages_classmap;
131 | $jetpack_packages_classmap = array(); // Must be array to avoid exceptions in old autoloaders!
132 |
133 | global $jetpack_packages_psr4;
134 | $jetpack_packages_psr4 = array(); // Must be array to avoid exceptions in old autoloaders!
135 |
136 | global $jetpack_packages_filemap;
137 | $jetpack_packages_filemap = array(); // Must be array to avoid exceptions in old autoloaders!
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/class-autoloader-locator.php:
--------------------------------------------------------------------------------
1 | version_selector = $version_selector;
25 | }
26 |
27 | /**
28 | * Finds the path to the plugin with the latest autoloader.
29 | *
30 | * @param array $plugin_paths An array of plugin paths.
31 | * @param string $latest_version The latest version reference. @phan-output-reference.
32 | *
33 | * @return string|null
34 | */
35 | public function find_latest_autoloader( $plugin_paths, &$latest_version ) {
36 | $latest_plugin = null;
37 |
38 | foreach ( $plugin_paths as $plugin_path ) {
39 | $version = $this->get_autoloader_version( $plugin_path );
40 | if ( ! $version || ! $this->version_selector->is_version_update_required( $latest_version, $version ) ) {
41 | continue;
42 | }
43 |
44 | $latest_version = $version;
45 | $latest_plugin = $plugin_path;
46 | }
47 |
48 | return $latest_plugin;
49 | }
50 |
51 | /**
52 | * Gets the path to the autoloader.
53 | *
54 | * @param string $plugin_path The path to the plugin.
55 | *
56 | * @return string
57 | */
58 | public function get_autoloader_path( $plugin_path ) {
59 | return trailingslashit( $plugin_path ) . 'vendor/autoload_packages.php';
60 | }
61 |
62 | /**
63 | * Gets the version for the autoloader.
64 | *
65 | * @param string $plugin_path The path to the plugin.
66 | *
67 | * @return string|null
68 | */
69 | public function get_autoloader_version( $plugin_path ) {
70 | $classmap = trailingslashit( $plugin_path ) . 'vendor/composer/jetpack_autoload_classmap.php';
71 | if ( ! file_exists( $classmap ) ) {
72 | return null;
73 | }
74 |
75 | $classmap = require $classmap;
76 | if ( isset( $classmap[ AutoloadGenerator::class ] ) ) {
77 | return $classmap[ AutoloadGenerator::class ]['version'];
78 | }
79 |
80 | return null;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/class-autoloader.php:
--------------------------------------------------------------------------------
1 | get( Autoloader_Handler::class );
27 |
28 | // If the autoloader is already initializing it means that it has included us as the latest.
29 | $was_included_by_autoloader = $autoloader_handler->is_initializing();
30 |
31 | /** @var Plugin_Locator $plugin_locator */
32 | $plugin_locator = $container->get( Plugin_Locator::class );
33 |
34 | /** @var Plugins_Handler $plugins_handler */
35 | $plugins_handler = $container->get( Plugins_Handler::class );
36 |
37 | // The current plugin is the one that we are attempting to initialize here.
38 | $current_plugin = $plugin_locator->find_current_plugin();
39 |
40 | // The active plugins are those that we were able to discover on the site. This list will not
41 | // include mu-plugins, those activated by code, or those who are hidden by filtering. We also
42 | // want to take care to not consider the current plugin unknown if it was included by an
43 | // autoloader. This avoids the case where a plugin will be marked "active" while deactivated
44 | // due to it having the latest autoloader.
45 | $active_plugins = $plugins_handler->get_active_plugins( true, ! $was_included_by_autoloader );
46 |
47 | // The cached plugins are all of those that were active or discovered by the autoloader during a previous request.
48 | // Note that it's possible this list will include plugins that have since been deactivated, but after a request
49 | // the cache should be updated and the deactivated plugins will be removed.
50 | $cached_plugins = $plugins_handler->get_cached_plugins();
51 |
52 | // We combine the active list and cached list to preemptively load classes for plugins that are
53 | // presently unknown but will be loaded during the request. While this may result in us considering packages in
54 | // deactivated plugins there shouldn't be any problems as a result and the eventual consistency is sufficient.
55 | $all_plugins = array_merge( $active_plugins, $cached_plugins );
56 |
57 | // In particular we also include the current plugin to address the case where it is the latest autoloader
58 | // but also unknown (and not cached). We don't want it in the active list because we don't know that it
59 | // is active but we need it in the all plugins list so that it is considered by the autoloader.
60 | $all_plugins[] = $current_plugin;
61 |
62 | // We require uniqueness in the array to avoid processing the same plugin more than once.
63 | $all_plugins = array_values( array_unique( $all_plugins ) );
64 |
65 | /** @var Latest_Autoloader_Guard $guard */
66 | $guard = $container->get( Latest_Autoloader_Guard::class );
67 | if ( $guard->should_stop_init( $current_plugin, $all_plugins, $was_included_by_autoloader ) ) {
68 | return;
69 | }
70 |
71 | // Initialize the autoloader using the handler now that we're ready.
72 | $autoloader_handler->activate_autoloader( $all_plugins );
73 |
74 | /** @var Hook_Manager $hook_manager */
75 | $hook_manager = $container->get( Hook_Manager::class );
76 |
77 | // Register a shutdown handler to clean up the autoloader.
78 | $hook_manager->add_action( 'shutdown', new Shutdown_Handler( $plugins_handler, $cached_plugins, $was_included_by_autoloader ) );
79 |
80 | // Register a plugins_loaded handler to check for conflicting autoloaders.
81 | $hook_manager->add_action( 'plugins_loaded', array( $guard, 'check_for_conflicting_autoloaders' ), 1 );
82 |
83 | // phpcs:enable Generic.Commenting.DocComment.MissingShort
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/class-container.php:
--------------------------------------------------------------------------------
1 | 'Hook_Manager',
17 | );
18 |
19 | /**
20 | * A map of all the dependencies we've registered with the container and created.
21 | *
22 | * @var array
23 | */
24 | protected $dependencies;
25 |
26 | /**
27 | * The constructor.
28 | */
29 | public function __construct() {
30 | $this->dependencies = array();
31 |
32 | $this->register_shared_dependencies();
33 | $this->register_dependencies();
34 | $this->initialize_globals();
35 | }
36 |
37 | /**
38 | * Gets a dependency out of the container.
39 | *
40 | * @param string $class The class to fetch.
41 | *
42 | * @return mixed
43 | * @throws \InvalidArgumentException When a class that isn't registered with the container is fetched.
44 | */
45 | public function get( $class ) {
46 | if ( ! isset( $this->dependencies[ $class ] ) ) {
47 | throw new \InvalidArgumentException( "Class '$class' is not registered with the container." );
48 | }
49 |
50 | return $this->dependencies[ $class ];
51 | }
52 |
53 | /**
54 | * Registers all of the dependencies that are shared between all instances of the autoloader.
55 | */
56 | private function register_shared_dependencies() {
57 | global $jetpack_autoloader_container_shared;
58 | if ( ! isset( $jetpack_autoloader_container_shared ) ) {
59 | $jetpack_autoloader_container_shared = array();
60 | }
61 |
62 | $key = self::SHARED_DEPENDENCY_KEYS[ Hook_Manager::class ];
63 | if ( ! isset( $jetpack_autoloader_container_shared[ $key ] ) ) {
64 | require_once __DIR__ . '/class-hook-manager.php';
65 | $jetpack_autoloader_container_shared[ $key ] = new Hook_Manager();
66 | }
67 | $this->dependencies[ Hook_Manager::class ] = &$jetpack_autoloader_container_shared[ $key ];
68 | }
69 |
70 | /**
71 | * Registers all of the dependencies with the container.
72 | */
73 | private function register_dependencies() {
74 | require_once __DIR__ . '/class-path-processor.php';
75 | $this->dependencies[ Path_Processor::class ] = new Path_Processor();
76 |
77 | require_once __DIR__ . '/class-plugin-locator.php';
78 | $this->dependencies[ Plugin_Locator::class ] = new Plugin_Locator(
79 | $this->get( Path_Processor::class )
80 | );
81 |
82 | require_once __DIR__ . '/class-version-selector.php';
83 | $this->dependencies[ Version_Selector::class ] = new Version_Selector();
84 |
85 | require_once __DIR__ . '/class-autoloader-locator.php';
86 | $this->dependencies[ Autoloader_Locator::class ] = new Autoloader_Locator(
87 | $this->get( Version_Selector::class )
88 | );
89 |
90 | require_once __DIR__ . '/class-php-autoloader.php';
91 | $this->dependencies[ PHP_Autoloader::class ] = new PHP_Autoloader();
92 |
93 | require_once __DIR__ . '/class-manifest-reader.php';
94 | $this->dependencies[ Manifest_Reader::class ] = new Manifest_Reader(
95 | $this->get( Version_Selector::class )
96 | );
97 |
98 | require_once __DIR__ . '/class-plugins-handler.php';
99 | $this->dependencies[ Plugins_Handler::class ] = new Plugins_Handler(
100 | $this->get( Plugin_Locator::class ),
101 | $this->get( Path_Processor::class )
102 | );
103 |
104 | require_once __DIR__ . '/class-autoloader-handler.php';
105 | $this->dependencies[ Autoloader_Handler::class ] = new Autoloader_Handler(
106 | $this->get( PHP_Autoloader::class ),
107 | $this->get( Hook_Manager::class ),
108 | $this->get( Manifest_Reader::class ),
109 | $this->get( Version_Selector::class )
110 | );
111 |
112 | require_once __DIR__ . '/class-latest-autoloader-guard.php';
113 | $this->dependencies[ Latest_Autoloader_Guard::class ] = new Latest_Autoloader_Guard(
114 | $this->get( Plugins_Handler::class ),
115 | $this->get( Autoloader_Handler::class ),
116 | $this->get( Autoloader_Locator::class )
117 | );
118 |
119 | // Register any classes that we will use elsewhere.
120 | require_once __DIR__ . '/class-version-loader.php';
121 | require_once __DIR__ . '/class-shutdown-handler.php';
122 | }
123 |
124 | /**
125 | * Initializes any of the globals needed by the autoloader.
126 | */
127 | private function initialize_globals() {
128 | /*
129 | * This global was retired in version 2.9. The value is set to 'false' to maintain
130 | * compatibility with older versions of the autoloader.
131 | */
132 | global $jetpack_autoloader_including_latest;
133 | $jetpack_autoloader_including_latest = false;
134 |
135 | // Not all plugins can be found using the locator. In cases where a plugin loads the autoloader
136 | // but was not discoverable, we will record them in this array to track them as "active".
137 | global $jetpack_autoloader_activating_plugins_paths;
138 | if ( ! isset( $jetpack_autoloader_activating_plugins_paths ) ) {
139 | $jetpack_autoloader_activating_plugins_paths = array();
140 | }
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/src/class-hook-manager.php:
--------------------------------------------------------------------------------
1 | registered_hooks = array();
21 | }
22 |
23 | /**
24 | * Adds an action to WordPress and registers it internally.
25 | *
26 | * @param string $tag The name of the action which is hooked.
27 | * @param callable $callable The function to call.
28 | * @param int $priority Used to specify the priority of the action.
29 | * @param int $accepted_args Used to specify the number of arguments the callable accepts.
30 | */
31 | public function add_action( $tag, $callable, $priority = 10, $accepted_args = 1 ) {
32 | $this->registered_hooks[ $tag ][] = array(
33 | 'priority' => $priority,
34 | 'callable' => $callable,
35 | );
36 |
37 | add_action( $tag, $callable, $priority, $accepted_args );
38 | }
39 |
40 | /**
41 | * Adds a filter to WordPress and registers it internally.
42 | *
43 | * @param string $tag The name of the filter which is hooked.
44 | * @param callable $callable The function to call.
45 | * @param int $priority Used to specify the priority of the filter.
46 | * @param int $accepted_args Used to specify the number of arguments the callable accepts.
47 | */
48 | public function add_filter( $tag, $callable, $priority = 10, $accepted_args = 1 ) {
49 | $this->registered_hooks[ $tag ][] = array(
50 | 'priority' => $priority,
51 | 'callable' => $callable,
52 | );
53 |
54 | add_filter( $tag, $callable, $priority, $accepted_args );
55 | }
56 |
57 | /**
58 | * Removes all of the registered hooks.
59 | */
60 | public function reset() {
61 | foreach ( $this->registered_hooks as $tag => $hooks ) {
62 | foreach ( $hooks as $hook ) {
63 | remove_filter( $tag, $hook['callable'], $hook['priority'] );
64 | }
65 | }
66 | $this->registered_hooks = array();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/class-latest-autoloader-guard.php:
--------------------------------------------------------------------------------
1 | plugins_handler = $plugins_handler;
39 | $this->autoloader_handler = $autoloader_handler;
40 | $this->autoloader_locator = $autoloader_locator;
41 | }
42 |
43 | /**
44 | * Indicates whether or not the autoloader should be initialized. Note that this function
45 | * has the side-effect of actually loading the latest autoloader in the event that this
46 | * is not it.
47 | *
48 | * @param string $current_plugin The current plugin we're checking.
49 | * @param string[] $plugins The active plugins to check for autoloaders in.
50 | * @param bool $was_included_by_autoloader Indicates whether or not this autoloader was included by another.
51 | *
52 | * @return bool True if we should stop initialization, otherwise false.
53 | */
54 | public function should_stop_init( $current_plugin, $plugins, $was_included_by_autoloader ) {
55 | global $jetpack_autoloader_latest_version;
56 |
57 | // We need to reset the autoloader when the plugins change because
58 | // that means the autoloader was generated with a different list.
59 | if ( $this->plugins_handler->have_plugins_changed( $plugins ) ) {
60 | $this->autoloader_handler->reset_autoloader();
61 | }
62 |
63 | // When the latest autoloader has already been found we don't need to search for it again.
64 | // We should take care however because this will also trigger if the autoloader has been
65 | // included by an older one.
66 | if ( isset( $jetpack_autoloader_latest_version ) && ! $was_included_by_autoloader ) {
67 | return true;
68 | }
69 |
70 | $latest_plugin = $this->autoloader_locator->find_latest_autoloader( $plugins, $jetpack_autoloader_latest_version );
71 | if ( isset( $latest_plugin ) && $latest_plugin !== $current_plugin ) {
72 | require $this->autoloader_locator->get_autoloader_path( $latest_plugin );
73 | return true;
74 | }
75 |
76 | return false;
77 | }
78 |
79 | /**
80 | * Check for conflicting autoloaders.
81 | *
82 | * A common source of strange and confusing problems is when another plugin
83 | * registers a Composer autoloader at a higher priority that us. If enabled,
84 | * check for this problem and warn about it.
85 | *
86 | * Called from the plugins_loaded hook.
87 | *
88 | * @since 3.1.0
89 | * @return void
90 | */
91 | public function check_for_conflicting_autoloaders() {
92 | if ( ! defined( 'JETPACK_AUTOLOAD_DEBUG_CONFLICTING_LOADERS' ) || ! JETPACK_AUTOLOAD_DEBUG_CONFLICTING_LOADERS ) {
93 | return;
94 | }
95 |
96 | global $jetpack_autoloader_loader;
97 | if ( ! isset( $jetpack_autoloader_loader ) ) {
98 | return;
99 | }
100 | $prefixes = array();
101 | foreach ( ( $jetpack_autoloader_loader->get_class_map() ?? array() ) as $classname => $data ) {
102 | $parts = explode( '\\', trim( $classname, '\\' ) );
103 | array_pop( $parts );
104 | while ( $parts ) {
105 | $prefixes[ implode( '\\', $parts ) . '\\' ] = true;
106 | array_pop( $parts );
107 | }
108 | }
109 | foreach ( ( $jetpack_autoloader_loader->get_psr4_map() ?? array() ) as $prefix => $data ) {
110 | $parts = explode( '\\', trim( $prefix, '\\' ) );
111 | while ( $parts ) {
112 | $prefixes[ implode( '\\', $parts ) . '\\' ] = true;
113 | array_pop( $parts );
114 | }
115 | }
116 |
117 | $autoload_chain = spl_autoload_functions();
118 | if ( ! $autoload_chain ) {
119 | return;
120 | }
121 |
122 | foreach ( $autoload_chain as $autoloader ) {
123 | // No need to check anything after us.
124 | if ( is_array( $autoloader ) && is_string( $autoloader[0] ) && substr( $autoloader[0], 0, strlen( __NAMESPACE__ ) + 1 ) === __NAMESPACE__ . '\\' ) {
125 | break;
126 | }
127 |
128 | // We can check Composer autoloaders easily enough.
129 | if ( is_array( $autoloader ) && $autoloader[0] instanceof \Composer\Autoload\ClassLoader && is_callable( array( $autoloader[0], 'getPrefixesPsr4' ) ) ) {
130 | $composer_autoloader = $autoloader[0];
131 | foreach ( $composer_autoloader->getClassMap() as $classname => $path ) {
132 | if ( $jetpack_autoloader_loader->find_class_file( $classname ) ) {
133 | $msg = "A Composer autoloader is registered with a higher priority than the Jetpack Autoloader and would also handle some of the classes we handle (e.g. $classname => $path). This may cause strange and confusing problems.";
134 | wp_trigger_error( '', $msg );
135 | continue 2;
136 | }
137 | }
138 | foreach ( $composer_autoloader->getPrefixesPsr4() as $prefix => $paths ) {
139 | if ( isset( $prefixes[ $prefix ] ) ) {
140 | $path = array_pop( $paths );
141 | $msg = "A Composer autoloader is registered with a higher priority than the Jetpack Autoloader and would also handle some of the namespaces we handle (e.g. $prefix => $path). This may cause strange and confusing problems.";
142 | wp_trigger_error( '', $msg );
143 | continue 2;
144 | }
145 | }
146 | foreach ( $composer_autoloader->getPrefixes() as $prefix => $paths ) {
147 | if ( isset( $prefixes[ $prefix ] ) ) {
148 | $path = array_pop( $paths );
149 | $msg = "A Composer autoloader is registered with a higher priority than the Jetpack Autoloader and would also handle some of the namespaces we handle (e.g. $prefix => $path). This may cause strange and confusing problems.";
150 | wp_trigger_error( '', $msg );
151 | continue 2;
152 | }
153 | }
154 | }
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/class-manifest-reader.php:
--------------------------------------------------------------------------------
1 | version_selector = $version_selector;
23 | }
24 |
25 | /**
26 | * Reads all of the manifests in the given plugin paths.
27 | *
28 | * @param array $plugin_paths The paths to the plugins we're loading the manifest in.
29 | * @param string $manifest_path The path that we're loading the manifest from in each plugin.
30 | * @param array $path_map The path map to add the contents of the manifests to.
31 | *
32 | * @return array $path_map The path map we've built using the manifests in each plugin.
33 | */
34 | public function read_manifests( $plugin_paths, $manifest_path, &$path_map ) {
35 | $file_paths = array_map(
36 | function ( $path ) use ( $manifest_path ) {
37 | return trailingslashit( $path ) . $manifest_path;
38 | },
39 | $plugin_paths
40 | );
41 |
42 | foreach ( $file_paths as $path ) {
43 | $this->register_manifest( $path, $path_map );
44 | }
45 |
46 | return $path_map;
47 | }
48 |
49 | /**
50 | * Registers a plugin's manifest file with the path map.
51 | *
52 | * @param string $manifest_path The absolute path to the manifest that we're loading.
53 | * @param array $path_map The path map to add the contents of the manifest to.
54 | */
55 | protected function register_manifest( $manifest_path, &$path_map ) {
56 | if ( ! is_readable( $manifest_path ) ) {
57 | return;
58 | }
59 |
60 | $manifest = require $manifest_path;
61 | if ( ! is_array( $manifest ) ) {
62 | return;
63 | }
64 |
65 | foreach ( $manifest as $key => $data ) {
66 | $this->register_record( $key, $data, $path_map );
67 | }
68 | }
69 |
70 | /**
71 | * Registers an entry from the manifest in the path map.
72 | *
73 | * @param string $key The identifier for the entry we're registering.
74 | * @param array $data The data for the entry we're registering.
75 | * @param array $path_map The path map to add the contents of the manifest to.
76 | */
77 | protected function register_record( $key, $data, &$path_map ) {
78 | if ( isset( $path_map[ $key ]['version'] ) ) {
79 | $selected_version = $path_map[ $key ]['version'];
80 | } else {
81 | $selected_version = null;
82 | }
83 |
84 | if ( $this->version_selector->is_version_update_required( $selected_version, $data['version'] ) ) {
85 | $path_map[ $key ] = array(
86 | 'version' => $data['version'],
87 | 'path' => $data['path'],
88 | );
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/class-path-processor.php:
--------------------------------------------------------------------------------
1 | get_normalized_constants();
19 | foreach ( $constants as $constant => $constant_path ) {
20 | $len = strlen( $constant_path );
21 | if ( substr( $path, 0, $len ) !== $constant_path ) {
22 | continue;
23 | }
24 |
25 | return substr_replace( $path, '{{' . $constant . '}}', 0, $len );
26 | }
27 |
28 | return $path;
29 | }
30 |
31 | /**
32 | * Given a path this will replace any of the path constant tokens with the expanded path.
33 | *
34 | * @param string $tokenized_path The path we want to process.
35 | *
36 | * @return string The expanded path.
37 | */
38 | public function untokenize_path_constants( $tokenized_path ) {
39 | $tokenized_path = wp_normalize_path( $tokenized_path );
40 |
41 | $constants = $this->get_normalized_constants();
42 | foreach ( $constants as $constant => $constant_path ) {
43 | $constant = '{{' . $constant . '}}';
44 |
45 | $len = strlen( $constant );
46 | if ( substr( $tokenized_path, 0, $len ) !== $constant ) {
47 | continue;
48 | }
49 |
50 | return $this->get_real_path( substr_replace( $tokenized_path, $constant_path, 0, $len ) );
51 | }
52 |
53 | return $tokenized_path;
54 | }
55 |
56 | /**
57 | * Given a file and an array of places it might be, this will find the absolute path and return it.
58 | *
59 | * @param string $file The plugin or theme file to resolve.
60 | * @param array $directories_to_check The directories we should check for the file if it isn't an absolute path.
61 | *
62 | * @return string|false Returns the absolute path to the directory, otherwise false.
63 | */
64 | public function find_directory_with_autoloader( $file, $directories_to_check ) {
65 | $file = wp_normalize_path( $file );
66 |
67 | if ( ! $this->is_absolute_path( $file ) ) {
68 | $file = $this->find_absolute_plugin_path( $file, $directories_to_check );
69 | if ( ! isset( $file ) ) {
70 | return false;
71 | }
72 | }
73 |
74 | // We need the real path for consistency with __DIR__ paths.
75 | $file = $this->get_real_path( $file );
76 |
77 | // phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
78 | $directory = @is_file( $file ) ? dirname( $file ) : $file;
79 | if ( ! @is_file( $directory . '/vendor/composer/jetpack_autoload_classmap.php' ) ) {
80 | return false;
81 | }
82 | // phpcs:enable WordPress.PHP.NoSilencedErrors.Discouraged
83 |
84 | return $directory;
85 | }
86 |
87 | /**
88 | * Fetches an array of normalized paths keyed by the constant they came from.
89 | *
90 | * @return string[] The normalized paths keyed by the constant.
91 | */
92 | private function get_normalized_constants() {
93 | $raw_constants = array(
94 | // Order the constants from most-specific to least-specific.
95 | 'WP_PLUGIN_DIR',
96 | 'WPMU_PLUGIN_DIR',
97 | 'WP_CONTENT_DIR',
98 | 'ABSPATH',
99 | );
100 |
101 | $constants = array();
102 | foreach ( $raw_constants as $raw ) {
103 | if ( ! defined( $raw ) ) {
104 | continue;
105 | }
106 |
107 | $path = wp_normalize_path( constant( $raw ) );
108 | if ( isset( $path ) ) {
109 | $constants[ $raw ] = $path;
110 | }
111 | }
112 |
113 | return $constants;
114 | }
115 |
116 | /**
117 | * Indicates whether or not a path is absolute.
118 | *
119 | * @param string $path The path to check.
120 | *
121 | * @return bool True if the path is absolute, otherwise false.
122 | */
123 | private function is_absolute_path( $path ) {
124 | if ( empty( $path ) || 0 === strlen( $path ) || '.' === $path[0] ) {
125 | return false;
126 | }
127 |
128 | // Absolute paths on Windows may begin with a drive letter.
129 | if ( preg_match( '/^[a-zA-Z]:[\/\\\\]/', $path ) ) {
130 | return true;
131 | }
132 |
133 | // A path starting with / or \ is absolute; anything else is relative.
134 | return ( '/' === $path[0] || '\\' === $path[0] );
135 | }
136 |
137 | /**
138 | * Given a file and a list of directories to check, this method will try to figure out
139 | * the absolute path to the file in question.
140 | *
141 | * @param string $normalized_path The normalized path to the plugin or theme file to resolve.
142 | * @param array $directories_to_check The directories we should check for the file if it isn't an absolute path.
143 | *
144 | * @return string|null The absolute path to the plugin file, otherwise null.
145 | */
146 | private function find_absolute_plugin_path( $normalized_path, $directories_to_check ) {
147 | // We're only able to find the absolute path for plugin/theme PHP files.
148 | if ( ! is_string( $normalized_path ) || '.php' !== substr( $normalized_path, -4 ) ) {
149 | return null;
150 | }
151 |
152 | foreach ( $directories_to_check as $directory ) {
153 | $normalized_check = wp_normalize_path( trailingslashit( $directory ) ) . $normalized_path;
154 | // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
155 | if ( @is_file( $normalized_check ) ) {
156 | return $normalized_check;
157 | }
158 | }
159 |
160 | return null;
161 | }
162 |
163 | /**
164 | * Given a path this will figure out the real path that we should be using.
165 | *
166 | * @param string $path The path to resolve.
167 | *
168 | * @return string The resolved path.
169 | */
170 | private function get_real_path( $path ) {
171 | // We want to resolve symbolic links for consistency with __DIR__ paths.
172 | // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
173 | $real_path = @realpath( $path );
174 | if ( false === $real_path ) {
175 | // Let the autoloader deal with paths that don't exist.
176 | $real_path = $path;
177 | }
178 |
179 | // Using realpath will make it platform-specific so we must normalize it after.
180 | if ( $path !== $real_path ) {
181 | $real_path = wp_normalize_path( $real_path );
182 | }
183 |
184 | return $real_path;
185 | }
186 | }
187 |
--------------------------------------------------------------------------------
/src/class-php-autoloader.php:
--------------------------------------------------------------------------------
1 | unregister_autoloader();
17 |
18 | // Set the global so that it can be used to load classes.
19 | global $jetpack_autoloader_loader;
20 | $jetpack_autoloader_loader = $version_loader;
21 |
22 | // Ensure that the autoloader is first to avoid contention with others.
23 | spl_autoload_register( array( self::class, 'load_class' ), true, true );
24 | }
25 |
26 | /**
27 | * Unregisters the active autoloader so that it will no longer autoload classes.
28 | */
29 | public function unregister_autoloader() {
30 | // Remove any v2 autoloader that we've already registered.
31 | $autoload_chain = spl_autoload_functions();
32 | if ( ! $autoload_chain ) {
33 | return;
34 | }
35 | foreach ( $autoload_chain as $autoloader ) {
36 | // We can identify a v2 autoloader using the namespace.
37 | $namespace_check = null;
38 |
39 | // Functions are recorded as strings.
40 | if ( is_string( $autoloader ) ) {
41 | $namespace_check = $autoloader;
42 | } elseif ( is_array( $autoloader ) && is_string( $autoloader[0] ) ) {
43 | // Static method calls have the class as the first array element.
44 | $namespace_check = $autoloader[0];
45 | } else {
46 | // Since the autoloader has only ever been a function or a static method we don't currently need to check anything else.
47 | continue;
48 | }
49 |
50 | // Check for the namespace without the generated suffix.
51 | if ( 'Automattic\\Jetpack\\Autoloader\\jp' === substr( $namespace_check, 0, 32 ) ) {
52 | spl_autoload_unregister( $autoloader );
53 | }
54 | }
55 |
56 | // Clear the global now that the autoloader has been unregistered.
57 | global $jetpack_autoloader_loader;
58 | $jetpack_autoloader_loader = null;
59 | }
60 |
61 | /**
62 | * Loads a class file if one could be found.
63 | *
64 | * Note: This function is static so that the autoloader can be easily unregistered. If
65 | * it was a class method we would have to unwrap the object to check the namespace.
66 | *
67 | * @param string $class_name The name of the class to autoload.
68 | *
69 | * @return bool Indicates whether or not a class file was loaded.
70 | */
71 | public static function load_class( $class_name ) {
72 | global $jetpack_autoloader_loader;
73 | if ( ! isset( $jetpack_autoloader_loader ) ) {
74 | return false;
75 | }
76 |
77 | $file = $jetpack_autoloader_loader->find_class_file( $class_name );
78 | if ( ! isset( $file ) ) {
79 | return false;
80 | }
81 |
82 | // A common source of strange and confusing problems is when a vendor
83 | // file is autoloaded before all plugins have had a chance to register
84 | // with the autoloader. Detect that, if a development constant is set.
85 | if ( defined( 'JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS' ) && JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS &&
86 | ( strpos( $file, '/vendor/' ) !== false || strpos( $file, '/jetpack_vendor/' ) !== false ) &&
87 | is_callable( 'did_action' ) && ! did_action( 'plugins_loaded' )
88 | ) {
89 | // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_wp_debug_backtrace_summary -- This is a debug log message.
90 | $msg = "Jetpack Autoloader: Autoloading `$class_name` before the plugins_loaded hook may cause strange and confusing problems. " . wp_debug_backtrace_summary( '', 1 );
91 | wp_trigger_error( '', $msg );
92 | }
93 |
94 | require $file;
95 | return true;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/class-plugin-locator.php:
--------------------------------------------------------------------------------
1 | path_processor = $path_processor;
23 | }
24 |
25 | /**
26 | * Finds the path to the current plugin.
27 | *
28 | * @return string $path The path to the current plugin.
29 | *
30 | * @throws \RuntimeException If the current plugin does not have an autoloader.
31 | */
32 | public function find_current_plugin() {
33 | // Escape from `vendor/__DIR__` to root plugin directory.
34 | $plugin_directory = dirname( __DIR__, 2 );
35 |
36 | // Use the path processor to ensure that this is an autoloader we're referencing.
37 | $path = $this->path_processor->find_directory_with_autoloader( $plugin_directory, array() );
38 | if ( false === $path ) {
39 | throw new \RuntimeException( 'Failed to locate plugin ' . $plugin_directory );
40 | }
41 |
42 | return $path;
43 | }
44 |
45 | /**
46 | * Checks a given option for plugin paths.
47 | *
48 | * @param string $option_name The option that we want to check for plugin information.
49 | * @param bool $site_option Indicates whether or not we want to check the site option.
50 | *
51 | * @return array $plugin_paths The list of absolute paths we've found.
52 | */
53 | public function find_using_option( $option_name, $site_option = false ) {
54 | $raw = $site_option ? get_site_option( $option_name ) : get_option( $option_name );
55 | if ( false === $raw ) {
56 | return array();
57 | }
58 |
59 | return $this->convert_plugins_to_paths( $raw );
60 | }
61 |
62 | /**
63 | * Checks for plugins in the `action` request parameter.
64 | *
65 | * @param string[] $allowed_actions The actions that we're allowed to return plugins for.
66 | *
67 | * @return array $plugin_paths The list of absolute paths we've found.
68 | */
69 | public function find_using_request_action( $allowed_actions ) {
70 | /**
71 | * Note: we're not actually checking the nonce here because it's too early
72 | * in the execution. The pluggable functions are not yet loaded to give
73 | * plugins a chance to plug their versions. Therefore we're doing the bare
74 | * minimum: checking whether the nonce exists and it's in the right place.
75 | * The request will fail later if the nonce doesn't pass the check.
76 | */
77 | if ( empty( $_REQUEST['_wpnonce'] ) ) {
78 | return array();
79 | }
80 |
81 | // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated just below.
82 | $action = isset( $_REQUEST['action'] ) ? wp_unslash( $_REQUEST['action'] ) : false;
83 | if ( ! in_array( $action, $allowed_actions, true ) ) {
84 | return array();
85 | }
86 |
87 | $plugin_slugs = array();
88 | switch ( $action ) {
89 | case 'activate':
90 | case 'deactivate':
91 | if ( empty( $_REQUEST['plugin'] ) ) {
92 | break;
93 | }
94 |
95 | // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated by convert_plugins_to_paths.
96 | $plugin_slugs[] = wp_unslash( $_REQUEST['plugin'] );
97 | break;
98 |
99 | case 'activate-selected':
100 | case 'deactivate-selected':
101 | if ( empty( $_REQUEST['checked'] ) ) {
102 | break;
103 | }
104 |
105 | // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated by convert_plugins_to_paths.
106 | $plugin_slugs = wp_unslash( $_REQUEST['checked'] );
107 | break;
108 | }
109 |
110 | return $this->convert_plugins_to_paths( $plugin_slugs );
111 | }
112 |
113 | /**
114 | * Given an array of plugin slugs or paths, this will convert them to absolute paths and filter
115 | * out the plugins that are not directory plugins. Note that array keys will also be included
116 | * if they are plugin paths!
117 | *
118 | * @param string[] $plugins Plugin paths or slugs to filter.
119 | *
120 | * @return string[]
121 | */
122 | private function convert_plugins_to_paths( $plugins ) {
123 | if ( ! is_array( $plugins ) || empty( $plugins ) ) {
124 | return array();
125 | }
126 |
127 | // We're going to look for plugins in the standard directories.
128 | $path_constants = array( WP_PLUGIN_DIR, WPMU_PLUGIN_DIR );
129 |
130 | $plugin_paths = array();
131 | foreach ( $plugins as $key => $value ) {
132 | $path = $this->path_processor->find_directory_with_autoloader( $key, $path_constants );
133 | if ( $path ) {
134 | $plugin_paths[] = $path;
135 | }
136 |
137 | $path = $this->path_processor->find_directory_with_autoloader( $value, $path_constants );
138 | if ( $path ) {
139 | $plugin_paths[] = $path;
140 | }
141 | }
142 |
143 | return $plugin_paths;
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/src/class-plugins-handler.php:
--------------------------------------------------------------------------------
1 | plugin_locator = $plugin_locator;
35 | $this->path_processor = $path_processor;
36 | }
37 |
38 | /**
39 | * Gets all of the active plugins we can find.
40 | *
41 | * @param bool $include_deactivating When true, plugins deactivating this request will be considered active.
42 | * @param bool $record_unknown When true, the current plugin will be marked as active and recorded when unknown.
43 | *
44 | * @return string[]
45 | */
46 | public function get_active_plugins( $include_deactivating, $record_unknown ) {
47 | global $jetpack_autoloader_activating_plugins_paths;
48 |
49 | // We're going to build a unique list of plugins from a few different sources
50 | // to find all of our "active" plugins. While we need to return an integer
51 | // array, we're going to use an associative array internally to reduce
52 | // the amount of time that we're going to spend checking uniqueness
53 | // and merging different arrays together to form the output.
54 | $active_plugins = array();
55 |
56 | // Make sure that plugins which have activated this request are considered as "active" even though
57 | // they probably won't be present in any option.
58 | if ( is_array( $jetpack_autoloader_activating_plugins_paths ) ) {
59 | foreach ( $jetpack_autoloader_activating_plugins_paths as $path ) {
60 | $active_plugins[ $path ] = $path;
61 | }
62 | }
63 |
64 | // This option contains all of the plugins that have been activated.
65 | $plugins = $this->plugin_locator->find_using_option( 'active_plugins' );
66 | foreach ( $plugins as $path ) {
67 | $active_plugins[ $path ] = $path;
68 | }
69 |
70 | // This option contains all of the multisite plugins that have been activated.
71 | if ( is_multisite() ) {
72 | $plugins = $this->plugin_locator->find_using_option( 'active_sitewide_plugins', true );
73 | foreach ( $plugins as $path ) {
74 | $active_plugins[ $path ] = $path;
75 | }
76 | }
77 |
78 | // These actions contain plugins that are being activated/deactivated during this request.
79 | $plugins = $this->plugin_locator->find_using_request_action( array( 'activate', 'activate-selected', 'deactivate', 'deactivate-selected' ) );
80 | foreach ( $plugins as $path ) {
81 | $active_plugins[ $path ] = $path;
82 | }
83 |
84 | // When the current plugin isn't considered "active" there's a problem.
85 | // Since we're here, the plugin is active and currently being loaded.
86 | // We can support this case (mu-plugins and non-standard activation)
87 | // by adding the current plugin to the active list and marking it
88 | // as an unknown (activating) plugin. This also has the benefit
89 | // of causing a reset because the active plugins list has
90 | // been changed since it was saved in the global.
91 | $current_plugin = $this->plugin_locator->find_current_plugin();
92 | if ( $record_unknown && ! in_array( $current_plugin, $active_plugins, true ) ) {
93 | $active_plugins[ $current_plugin ] = $current_plugin;
94 | $jetpack_autoloader_activating_plugins_paths[] = $current_plugin;
95 | }
96 |
97 | // When deactivating plugins aren't desired we should entirely remove them from the active list.
98 | if ( ! $include_deactivating ) {
99 | // These actions contain plugins that are being deactivated during this request.
100 | $plugins = $this->plugin_locator->find_using_request_action( array( 'deactivate', 'deactivate-selected' ) );
101 | foreach ( $plugins as $path ) {
102 | unset( $active_plugins[ $path ] );
103 | }
104 | }
105 |
106 | // Transform the array so that we don't have to worry about the keys interacting with other array types later.
107 | return array_values( $active_plugins );
108 | }
109 |
110 | /**
111 | * Gets all of the cached plugins if there are any.
112 | *
113 | * @return string[]
114 | */
115 | public function get_cached_plugins() {
116 | $cached = get_transient( self::TRANSIENT_KEY );
117 | if ( ! is_array( $cached ) || empty( $cached ) ) {
118 | return array();
119 | }
120 |
121 | // We need to expand the tokens to an absolute path for this webserver.
122 | return array_map( array( $this->path_processor, 'untokenize_path_constants' ), $cached );
123 | }
124 |
125 | /**
126 | * Saves the plugin list to the cache.
127 | *
128 | * @param array $plugins The plugin list to save to the cache.
129 | */
130 | public function cache_plugins( $plugins ) {
131 | // We store the paths in a tokenized form so that that webservers with different absolute paths don't break.
132 | $plugins = array_map( array( $this->path_processor, 'tokenize_path_constants' ), $plugins );
133 |
134 | set_transient( self::TRANSIENT_KEY, $plugins );
135 | }
136 |
137 | /**
138 | * Checks to see whether or not the plugin list given has changed when compared to the
139 | * shared `$jetpack_autoloader_cached_plugin_paths` global. This allows us to deal
140 | * with cases where the active list may change due to filtering..
141 | *
142 | * @param string[] $plugins The plugins list to check against the global cache.
143 | *
144 | * @return bool True if the plugins have changed, otherwise false.
145 | */
146 | public function have_plugins_changed( $plugins ) {
147 | global $jetpack_autoloader_cached_plugin_paths;
148 |
149 | if ( $jetpack_autoloader_cached_plugin_paths !== $plugins ) {
150 | $jetpack_autoloader_cached_plugin_paths = $plugins;
151 | return true;
152 | }
153 |
154 | return false;
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/src/class-shutdown-handler.php:
--------------------------------------------------------------------------------
1 | plugins_handler = $plugins_handler;
39 | $this->cached_plugins = $cached_plugins;
40 | $this->was_included_by_autoloader = $was_included_by_autoloader;
41 | }
42 |
43 | /**
44 | * Handles the shutdown of the autoloader.
45 | */
46 | public function __invoke() {
47 | // Don't save a broken cache if an error happens during some plugin's initialization.
48 | if ( ! did_action( 'plugins_loaded' ) ) {
49 | // Ensure that the cache is emptied to prevent consecutive failures if the cache is to blame.
50 | if ( ! empty( $this->cached_plugins ) ) {
51 | $this->plugins_handler->cache_plugins( array() );
52 | }
53 |
54 | return;
55 | }
56 |
57 | // Load the active plugins fresh since the list we pulled earlier might not contain
58 | // plugins that were activated but did not reset the autoloader. This happens
59 | // when a plugin is in the cache but not "active" when the autoloader loads.
60 | // We also want to make sure that plugins which are deactivating are not
61 | // considered "active" so that they will be removed from the cache now.
62 | try {
63 | $active_plugins = $this->plugins_handler->get_active_plugins( false, ! $this->was_included_by_autoloader );
64 | } catch ( \Exception $ex ) {
65 | // When the package is deleted before shutdown it will throw an exception.
66 | // In the event this happens we should erase the cache.
67 | if ( ! empty( $this->cached_plugins ) ) {
68 | $this->plugins_handler->cache_plugins( array() );
69 | }
70 | return;
71 | }
72 |
73 | // The paths should be sorted for easy comparisons with those loaded from the cache.
74 | // Note we don't need to sort the cached entries because they're already sorted.
75 | sort( $active_plugins );
76 |
77 | // We don't want to waste time saving a cache that hasn't changed.
78 | if ( $this->cached_plugins === $active_plugins ) {
79 | return;
80 | }
81 |
82 | $this->plugins_handler->cache_plugins( $active_plugins );
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/class-version-loader.php:
--------------------------------------------------------------------------------
1 | version_selector = $version_selector;
47 | $this->classmap = $classmap;
48 | $this->psr4_map = $psr4_map;
49 | $this->filemap = $filemap;
50 | }
51 |
52 | /**
53 | * Fetch the classmap.
54 | *
55 | * @since 3.1.0
56 | * @return array
57 | */
58 | public function get_class_map() {
59 | return $this->classmap;
60 | }
61 |
62 | /**
63 | * Fetch the psr-4 mappings.
64 | *
65 | * @since 3.1.0
66 | * @return array
67 | */
68 | public function get_psr4_map() {
69 | return $this->psr4_map;
70 | }
71 |
72 | /**
73 | * Finds the file path for the given class.
74 | *
75 | * @param string $class_name The class to find.
76 | *
77 | * @return string|null $file_path The path to the file if found, null if no class was found.
78 | */
79 | public function find_class_file( $class_name ) {
80 | $data = $this->select_newest_file(
81 | $this->classmap[ $class_name ] ?? null,
82 | $this->find_psr4_file( $class_name )
83 | );
84 | if ( ! isset( $data ) ) {
85 | return null;
86 | }
87 |
88 | return $data['path'];
89 | }
90 |
91 | /**
92 | * Load all of the files in the filemap.
93 | */
94 | public function load_filemap() {
95 | if ( empty( $this->filemap ) ) {
96 | return;
97 | }
98 |
99 | foreach ( $this->filemap as $file_identifier => $file_data ) {
100 | if ( empty( $GLOBALS['__composer_autoload_files'][ $file_identifier ] ) ) {
101 | require_once $file_data['path'];
102 |
103 | $GLOBALS['__composer_autoload_files'][ $file_identifier ] = true;
104 | }
105 | }
106 | }
107 |
108 | /**
109 | * Compares different class sources and returns the newest.
110 | *
111 | * @param array|null $classmap_data The classmap class data.
112 | * @param array|null $psr4_data The PSR-4 class data.
113 | *
114 | * @return array|null $data
115 | */
116 | private function select_newest_file( $classmap_data, $psr4_data ) {
117 | if ( ! isset( $classmap_data ) ) {
118 | return $psr4_data;
119 | } elseif ( ! isset( $psr4_data ) ) {
120 | return $classmap_data;
121 | }
122 |
123 | if ( $this->version_selector->is_version_update_required( $classmap_data['version'], $psr4_data['version'] ) ) {
124 | return $psr4_data;
125 | }
126 |
127 | return $classmap_data;
128 | }
129 |
130 | /**
131 | * Finds the file for a given class in a PSR-4 namespace.
132 | *
133 | * @param string $class_name The class to find.
134 | *
135 | * @return array|null $data The version and path path to the file if found, null otherwise.
136 | */
137 | private function find_psr4_file( $class_name ) {
138 | if ( empty( $this->psr4_map ) ) {
139 | return null;
140 | }
141 |
142 | // Don't bother with classes that have no namespace.
143 | $class_index = strrpos( $class_name, '\\' );
144 | if ( ! $class_index ) {
145 | return null;
146 | }
147 | $class_for_path = str_replace( '\\', '/', $class_name );
148 |
149 | // Search for the namespace by iteratively cutting off the last segment until
150 | // we find a match. This allows us to check the most-specific namespaces
151 | // first as well as minimize the amount of time spent looking.
152 | for (
153 | $class_namespace = substr( $class_name, 0, $class_index );
154 | ! empty( $class_namespace );
155 | $class_namespace = substr( $class_namespace, 0, strrpos( $class_namespace, '\\' ) )
156 | ) {
157 | $namespace = $class_namespace . '\\';
158 | if ( ! isset( $this->psr4_map[ $namespace ] ) ) {
159 | continue;
160 | }
161 | $data = $this->psr4_map[ $namespace ];
162 |
163 | foreach ( $data['path'] as $path ) {
164 | $path .= '/' . substr( $class_for_path, strlen( $namespace ) ) . '.php';
165 | if ( file_exists( $path ) ) {
166 | return array(
167 | 'version' => $data['version'],
168 | 'path' => $path,
169 | );
170 | }
171 | }
172 | }
173 |
174 | return null;
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/src/class-version-selector.php:
--------------------------------------------------------------------------------
1 | is_dev_version( $selected_version ) ) {
29 | return false;
30 | }
31 |
32 | if ( $this->is_dev_version( $compare_version ) ) {
33 | if ( $use_dev_versions ) {
34 | return true;
35 | } else {
36 | return false;
37 | }
38 | }
39 |
40 | if ( version_compare( $selected_version, $compare_version, '<' ) ) {
41 | return true;
42 | }
43 |
44 | return false;
45 | }
46 |
47 | /**
48 | * Checks whether the given package version is a development version.
49 | *
50 | * @param String $version The package version.
51 | *
52 | * @return bool True if the version is a dev version, else false.
53 | */
54 | public function is_dev_version( $version ) {
55 | if ( 'dev-' === substr( $version, 0, 4 ) || '9999999-dev' === $version ) {
56 | return true;
57 | }
58 |
59 | return false;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------