├── .gitignore
├── .travis.yml
├── Gruntfile.js
├── LICENSE.md
├── README.md
├── bootstrap.php.dist
├── composer.json
├── dynamic_cdn.php
├── includes
├── classes
│ └── DomainManager.php
└── functions
│ └── core.php
├── package.json
├── phpunit.xml.dist
├── readme.txt
└── tests
└── phpunit
├── Core_Tests.php
├── DomainManagerTests.php
└── test-tools
└── TestCase.php
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | vendor
3 | composer.lock
4 | release
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: php
2 |
3 | php:
4 | - 7.0
5 | - 7.1
6 | - nightly
7 |
8 | matrix:
9 | fast_finish: true
10 | allow_failures:
11 | - php: nightly
12 |
13 | before_script:
14 | - composer install --dev --no-interaction
15 |
16 | after_script:
17 | - travis_retry php vendor/bin/coveralls -v
18 |
19 | script:
20 | - mkdir -p build/logs
21 | - ./vendor/bin/phpunit --coverage-clover build/logs/clover.xml
22 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function( grunt ) {
2 | grunt.initConfig({
3 | wp_readme_to_markdown: {
4 | default: {
5 | files: {
6 | 'readme.md': 'readme.txt'
7 | }
8 | }
9 | }
10 | });
11 |
12 | grunt.loadNpmTasks( 'grunt-wp-readme-to-markdown' );
13 |
14 | grunt.registerTask( 'default', ['wp_readme_to_markdown'] );
15 | };
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Dynamic CDN # [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url]
2 |
3 | **Contributors:** [ericmann](https://profiles.wordpress.org/ericmann), [10up](https://profiles.wordpress.org/10up)
4 | **Donate link:** https://eamann.com
5 | **Tags:** CDN, images, performance
6 | **Requires at least:** 3.8.1
7 | **Tested up to:** 4.5.2
8 | **Stable tag:** 0.4.0
9 | **License:** GPLv2 or later
10 | **License URI:** https://github.com/ericmann/dynamic-cdn/blob/master/LICENSE.md
11 |
12 | Dynamic CDN for front-end assets.
13 |
14 | ## Description ##
15 |
16 | Dynamic solution for rewriting image asset URLs to a hosted content delivery network (CDN) with optional domain sharding for concurrent downloads.
17 |
18 | This plugin is based heavily on the CDN dropin from Mark Jaquith's WP_Stack (https://github.com/markjaquith/WP-Stack).
19 |
20 | ## Installation ##
21 |
22 | ### Manual Installation ###
23 |
24 | 1. Upload the entire `/dynamic-cdn` directory to the `/wp-content/plugins/` directory.
25 | 2. Activate Dynamic CDN through the 'Plugins' menu in WordPress.
26 |
27 | ## Frequently Asked Questions ##
28 |
29 | ### Will this work as a mu-plugin? ###
30 |
31 | Yes. The plugin, as designed, will work just fine in the mu-plugins directory. We highly recommend a second mu-plugin be added to configure the CDN domains used by the system.
32 |
33 | ### How do I add a domain? ###
34 |
35 | In a function wired to `dynamic_cdn_first_loaded`, you'll reference the `->add_domain()` method of the `Dynamic_CDN` object. For example:
36 |
37 | function my_cdn_domains() {
38 | $manager = DomainManager::last();
39 | $manager->add( 'cdn0.mydomain.com' );
40 | $manager->add( 'cdn1.mydomain.com' );
41 | $manager->add( 'cdn2.mydomain.com' );
42 | }
43 | add_action( 'dynamic_cdn_first_loaded', 'my_cdn_domains' );
44 |
45 | ### What if I want to add my domains through wp-config.php? ###
46 |
47 | Simply define a DYNCDN_DOMAINS constant that's a comma-delimited list of your cdn domains. For example:
48 |
49 | define( 'DYNCDN_DOMAINS', 'cdn0.mydomain.com,cdn1.mydomain.com,cdn2.mydomain.com' );
50 |
51 | ### What if I don't add any domains, will this break my images? ###
52 |
53 | Hopefully not. If you haven't added any domains the plugin will not rewrite anything, bypassing your images entirely.
54 |
55 | ## Screenshots ##
56 |
57 | None at this time.
58 |
59 | ## Changelog ##
60 |
61 | ### 0.4.0 ###
62 | * New: Unit tests for core functionality
63 | * Fix: Ensure srcsets don't filter in admin views
64 |
65 | ### 0.3.0 ###
66 | * New: Add support for WordPress 4.4 srcsets
67 |
68 | ### 0.2.0 ###
69 | * New: CDN domains can be added with a constant.
70 | * Fix: Make domain mapping multisite aware. props @trepmal
71 |
72 | ### 0.1.0 ###
73 | * First release
74 |
75 | ## Upgrade Notice ##
76 |
77 | ### 0.4.0 ###
78 | Domain management has moved from a general-purpose class to a purpose-built `DomainManager` object. This object is
79 | instantiated with your current site's domain name, and can be accessed throught the static `DomainManager::last()` helper.
80 | (This method automatically returns the last-instantiated domain manager). If you weren't manipulating CdN domains
81 | programmatically, you won't need to change anything at all.
82 |
83 | ### 0.1.0 ###
84 | First Release
85 |
86 | [travis-image]: https://travis-ci.org/ericmann/dynamic-cdn.svg?branch=master
87 | [travis-url]: https://travis-ci.org/ericmann/dynamic-cdn
88 | [coveralls-image]: https://coveralls.io/repos/ericmann/dynamic-cdn/badge.svg?branch=master&service=github
89 | [coveralls-url]: https://coveralls.io/github/ericmann/dynamic-cdn?branch=master
90 |
--------------------------------------------------------------------------------
/bootstrap.php.dist:
--------------------------------------------------------------------------------
1 | 5.6",
18 | "composer/installers": "~1.0.25"
19 | },
20 | "require-dev": {
21 | "php": ">7.0",
22 | "10up/wp_mock": "0.2.0",
23 | "satooshi/php-coveralls": "^1.0"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/dynamic_cdn.php:
--------------------------------------------------------------------------------
1 |
14 | *
15 | * This program is free software; you can redistribute it and/or modify
16 | * it under the terms of the GNU General Public License, version 2 or, at
17 | * your discretion, any later version, as published by the Free
18 | * Software Foundation.
19 | *
20 | * This program is distributed in the hope that it will be useful,
21 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 | * GNU General Public License for more details.
24 | *
25 | * You should have received a copy of the GNU General Public License
26 | * along with this program; if not, write to the Free Software
27 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28 | */
29 |
30 | // Useful global constants
31 |
32 | define( 'DYNCDN_VERSION', '0.4.0' );
33 | define( 'DYNCDN_URL', plugin_dir_url( __FILE__ ) );
34 | define( 'DYNCDN_PATH', dirname( __FILE__ ) . '/' );
35 | define( 'DYNCDN_INC', DYNCDN_PATH . 'includes/' );
36 |
37 | // Include Files
38 | require_once DYNCDN_INC . 'classes/DomainManager.php';
39 | require_once DYNCDN_INC . 'functions/core.php';
40 |
41 | // Activation/Deactivation
42 | register_activation_hook( __FILE__, '\EAMann\Dynamic_CDN\Core\activate' );
43 | register_deactivation_hook( __FILE__, '\EAMann\Dynamic_CDN\Core\deactivate' );
44 |
45 | // Bootstrap
46 | EAMann\Dynamic_CDN\Core\setup();
47 |
--------------------------------------------------------------------------------
/includes/classes/DomainManager.php:
--------------------------------------------------------------------------------
1 | site_domain = $domain;
78 |
79 | self::$last = $this;
80 | }
81 |
82 | /**
83 | * Add a CDN domain to the collection.
84 | *
85 | * @param string $cdn_domain
86 | *
87 | * @return bool
88 | */
89 | public function add( $cdn_domain ) {
90 | if ( in_array( $cdn_domain, $this->cdn_domains ) ) {
91 | return false;
92 | } else {
93 | $this->cdn_domains[] = $cdn_domain;
94 | $this->has_domains = true;
95 |
96 | return true;
97 | }
98 | }
99 |
100 | /**
101 | * Get a CDN path for a given file, using a reduced checksum to automatically select from an array of available domains.
102 | *
103 | * @param string $file_path
104 | *
105 | * @return string
106 | */
107 | public function cdn_domain( $file_path ) {
108 | // First, get a checksum for the file path to give us the index we'll use from the CDN domain array.
109 | $index = abs( crc32( $file_path ) ) % count( $this->cdn_domains );
110 |
111 | /**
112 | * Return the correct CDN path to the file.
113 | *
114 | * @param string $cdn_domain
115 | * @param string $file_path
116 | */
117 | return apply_filters( 'dynamic_cdn_domain_for_file', $this->cdn_domains[ $index ], $file_path );
118 | }
119 |
120 | /**
121 | * Potentially replace a given file URL with a CDN-ified version
122 | *
123 | * @param string $file_url
124 | *
125 | * @return string
126 | */
127 | public function new_url( $file_url ) {
128 | $domain = $this->cdn_domain( basename( $file_url ) );
129 | $url = explode( '://', $this->site_domain );
130 |
131 | $proto_pattern = '^((https?):)?\/\/';
132 |
133 | if ( count( $url ) > 1 ) array_shift($url);
134 |
135 | // If the CDN domain has an existing protocol use that
136 | preg_match("#{$proto_pattern}#", $domain, $matches);
137 |
138 | /**
139 | * Allows plugins to override the HTTPS protocol
140 | *
141 | * @param string $scheme
142 | */
143 | $scheme = apply_filters(
144 | 'dynamic_cdn_protocol',
145 | ( count($matches) >= 2 ? $matches[2] : ( is_ssl() ? 'https' : 'http' ) )
146 | );
147 |
148 | $domain = esc_url( $scheme . '://' . preg_replace( "#{$proto_pattern}#" , '', $domain ) );
149 |
150 | /**
151 | * Modify the domain we're rewriting, should an aliasing plugin be used (for example)
152 | *
153 | * @param string $site_domain
154 | */
155 | $url = apply_filters( 'dynamic_cdn_site_domain', $url[0] );
156 |
157 | $pattern = "#{$proto_pattern}" . preg_quote($url, '#') . '#';
158 |
159 | return preg_replace( $pattern, $domain, $file_url );
160 | }
161 |
162 | /**
163 | * Verify whether or not the current manager has any registered CDN domains.
164 | *
165 | * @return bool
166 | */
167 | public function has_domains() {
168 | return count( $this->cdn_domains ) > 0;
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/includes/functions/core.php:
--------------------------------------------------------------------------------
1 |
6 | */
7 |
8 | namespace EAMann\Dynamic_CDN\Core;
9 |
10 | use EAMann\Dynamic_CDN\DomainManager;
11 |
12 | /**
13 | * Default setup routine
14 | *
15 | * @uses add_action()
16 | * @uses do_action()
17 | *
18 | * @return void
19 | */
20 | function setup() {
21 | $n = function( $function ) {
22 | return __NAMESPACE__ . "\\$function";
23 | };
24 |
25 | add_action( 'init', $n( 'init' ) );
26 | add_action( 'dynamic_cdn_init', $n( 'initialize_manager' ) );
27 |
28 | /**
29 | * Allow other plugins (i.e. mu-plugins) to hook in and populate the CDN domain array.
30 | */
31 | do_action( 'dynamic_cdn_first_loaded' );
32 | }
33 |
34 | /**
35 | * Get the site's current domain
36 | *
37 | * @return string
38 | */
39 | function get_site_domain() {
40 | $url_parts = parse_url( get_bloginfo( 'url' ) );
41 |
42 | $site_domain = $url_parts['host'] . ( isset( $url_parts['port'] ) ? ':' . $url_parts['port'] : '' );
43 |
44 | /**
45 | * Update the stored site domain, should an aliasing plugin be used (for example)
46 | *
47 | * @param string $site_domain
48 | */
49 | $site_domain = apply_filters( 'dynamic_cdn_site_domain', $site_domain );
50 |
51 | return $site_domain;
52 | }
53 |
54 |
55 | /**
56 | * Initializes the plugin and fires an action other plugins can hook into.
57 | *
58 | * @uses do_action()
59 | *
60 | * @return void
61 | */
62 | function init() {
63 | do_action( 'dynamic_cdn_init' );
64 | }
65 |
66 | /**
67 | * Initialize the CDN domain manager for the current domain.
68 | */
69 | function initialize_manager() {
70 | $site_domain = get_site_domain();
71 |
72 | // Instantiate the domain manager
73 | $manager = \EAMann\Dynamic_CDN\DomainManager( $site_domain );
74 |
75 | /**
76 | * Flag whether to filter all media content or just uploads. Set to `true` to only process uploads from the CDN
77 | *
78 | * @param bool $uploads_only
79 | */
80 | $manager->uploads_only = apply_filters( 'dynamic_cdn_uploads_only', false );
81 |
82 | /**
83 | * Filter the file extensions that will be served from the CDN. Expects an array of RegEx-style strings.
84 | *
85 | * @param array $extensions
86 | */
87 | $manager->extensions = apply_filters( 'dynamic_cdn_extensions', array( 'jpe?g', 'gif', 'png', 'bmp', 'js', 'mp4', 'mp3', 'flac', 'mid', 'midi', 'wav', 'ogg', 'ogv', 'svg', 'svgz', 'pdf', 'doc', 'docx', 'ico' ) );
88 |
89 | if ( ! is_admin() ) {
90 | add_action( 'template_redirect', '\EAMann\Dynamic_CDN\Core\create_buffer' );
91 |
92 | if ( $manager->uploads_only ) {
93 | add_filter( 'the_content'/*'dynamic_cdn_content'*/, '\EAMann\Dynamic_CDN\Core\filter_uploads_only' );
94 | } else {
95 | add_filter( 'dynamic_cdn_content', '\EAMann\Dynamic_CDN\Core\filter' );
96 | }
97 |
98 | add_filter( 'wp_calculate_image_srcset', '\EAMann\Dynamic_CDN\Core\srcsets', 10, 5 );
99 |
100 | add_action( 'rest_api_init', '\EAMann\Dynamic_CDN\Core\create_buffer' );
101 |
102 | $cdn_domains = array();
103 | if ( defined( 'DYNCDN_DOMAINS' ) ) {
104 | $cdn_domains = explode( ',', DYNCDN_DOMAINS );
105 | $cdn_domains = array_map( 'trim', $cdn_domains );
106 | }
107 |
108 | /**
109 | * Programmatically control and/or override any CDN domains as passed in via a hard-coded constant.
110 | *
111 | * @param array $cdn_domains
112 | */
113 | $cdn_domains = apply_filters( 'dynamic_cdn_default_domains', $cdn_domains );
114 |
115 | // Add all domains to the manager
116 | array_map( function( $domain ) use ( $manager ) { $manager->add( $domain ); }, $cdn_domains );
117 | }
118 | }
119 |
120 | /**
121 | * Handles the WP 4.4 srcset Dynamic CDN support
122 | *
123 | * @param array $sources
124 | * @param array $size_array
125 | * @param string $image_src
126 | * @param array $image_meta
127 | * @param int $attachment_id
128 | *
129 | * @return mixed
130 | */
131 | function srcsets( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
132 |
133 | // If we shouldn't process, ABORT!
134 | if( is_admin() || ! defined( 'DYNCDN_DOMAINS' ) ) {
135 | return $sources;
136 | }
137 |
138 | // Iteratively update each srcset
139 | $replacer = srcset_replacer( get_site_domain() );
140 | array_walk( $sources, $replacer );
141 |
142 | return $sources;
143 | }
144 |
145 | /**
146 | * Create a domain-specific srcset replacement function for use in array iterations
147 | *
148 | * @param string $domain
149 | * @return \Closure
150 | */
151 | function srcset_replacer( $domain ) {
152 | $manager = \EAMann\Dynamic_CDN\DomainManager( $domain );
153 |
154 | /**
155 | * Replace the URL for a specific source in a srcset with a CDN'd version
156 | *
157 | * @param array $source
158 | *
159 | * @return array
160 | */
161 | return function( &$source ) use ( $manager ) {
162 | $source['url'] = $manager->new_url( $source['url'] );
163 |
164 | return $source;
165 | };
166 | }
167 |
168 | /**
169 | * Create an output buffer so we can dynamically rewrite any URLs going out.
170 | */
171 | function create_buffer() {
172 | ob_start( '\EAMann\Dynamic_CDN\Core\ob' );
173 | }
174 |
175 | /**
176 | * Callback function for the output buffer that allows us to filter content.
177 | *
178 | * @param $contents
179 | *
180 | * @return mixed|void
181 | */
182 | function ob( $contents ) {
183 | $manager = DomainManager::last();
184 |
185 | /**
186 | * Filter the content from the output buffer
187 | *
188 | * @param string $contents
189 | * @param Dynamic_CDN $this
190 | */
191 | return apply_filters( 'dynamic_cdn_content', $contents, $manager );
192 | }
193 |
194 | /**
195 | * Filter uploaded content (with the given extensions) and rewrite to a CDN.
196 | *
197 | * @param $content
198 | *
199 | * @return mixed
200 | */
201 | function filter_uploads_only( $content ) {
202 | $manager = DomainManager::last();
203 |
204 | if ( ! $manager->has_domains() ) {
205 | return $content;
206 | }
207 |
208 | $upload_dir = wp_upload_dir();
209 | $upload_dir = $upload_dir['baseurl'];
210 | $url_parts = parse_url( $upload_dir );
211 | $domain = $url_parts['host'] . ( isset( $url_parts['port'] ) ? ':' . $url_parts['port'] : '' );
212 | $domain = preg_quote( $domain, '#' );
213 |
214 | $path = ltrim( parse_url( $upload_dir, PHP_URL_PATH ), '/' );
215 | $preg_path = str_replace( '/', '\\\?/', preg_quote( $path, '#' ) );
216 |
217 | // Targeted replace just on uploads URLs
218 | $pattern = "#(\\\?[\"'])" // opening quote
219 | . "(https?:\\\?/\\\?/{$domain})?"// domain (optional)
220 | . "\\\?/($preg_path\\\?/" // uploads path
221 | // . "((?:(?!\\1]).)+)" // look for anything that's not our opening quote
222 | . "[\w\s\\\/\-\,\.]+)" // look for anything that's not our opening quote
223 | . "\.(" . implode( '|', $manager->extensions ) . ")" // extensions
224 | . "(\?((?:(?!\\1).)*))?" // match query strings
225 | . "\\1#"; // closing quote
226 |
227 | return preg_replace_callback( $pattern, 'EAMann\Dynamic_CDN\Core\filter_cb', $content );
228 | }
229 |
230 | /**
231 | * Filter all static content (with the given extensions) and rewrite to a CDN.
232 | *
233 | * @param $content
234 | *
235 | * @return mixed
236 | */
237 | function filter( $content ) {
238 | $manager = DomainManager::last();
239 |
240 | if ( ! $manager->has_domains() ) {
241 | return $content;
242 | }
243 | $url = explode( '://', get_bloginfo( 'url' ) );
244 | array_shift( $url );
245 |
246 | /**
247 | * Modify the domain we're rewriting, should an aliasing plugin be used (for example)
248 | *
249 | * @param string $site_domain
250 | */
251 | $url = apply_filters( 'dynamic_cdn_site_domain', rtrim( implode( '://', $url ), '/' ) );
252 | $url = preg_quote( $url, '#' );
253 |
254 | $pattern = "#(\\\?[\"'])" // opening quote
255 | . "((?:https?:)?\\\?/\\\?/{$url})?\\\?/" // domain (optional)
256 | // . "([^/](?:(?!\\1).)+)" // look for anything that's not our opening quote
257 | . "([^/][\w\s\\\/\-\,\.]+)" // look for anything that's not our opening quote
258 | . "\.(" . implode( '|', $manager->extensions ) . ")" // extensions
259 | . "(\?((?:(?!\\1).)*))?" // match query strings
260 | . "\\1#"; // closing quote
261 |
262 | return preg_replace_callback( $pattern, 'EAMann\Dynamic_CDN\Core\filter_cb', $content );
263 | }
264 |
265 | /**
266 | * Callback function used to automatically parse assets and replace the image src with a CDN version.
267 | *
268 | * @param $matches
269 | *
270 | * @return string
271 | */
272 | function filter_cb( $matches ) {
273 | $manager = DomainManager::last();
274 |
275 | $upload_dir = wp_upload_dir();
276 | $upload_dir = $upload_dir['baseurl'];
277 | $upload_path = parse_url( $upload_dir, PHP_URL_PATH );
278 |
279 | $domain = $manager->cdn_domain( $matches[0] );
280 |
281 | $url = explode( '://', get_bloginfo( 'url' ) );
282 | array_shift( $url );
283 |
284 | /**
285 | * Modify the domain we're rewriting, should an aliasing plugin be used (for example)
286 | *
287 | * @param string $site_domain
288 | */
289 | $url = apply_filters( 'dynamic_cdn_site_domain', rtrim( implode( '://', $url ), '/' ) );
290 | $url = str_replace( $manager->site_domain, $domain, $url );
291 |
292 | // Make sure to use https if the request is over SSL
293 | $scheme = apply_filters( 'dynamic_cdn_protocol', ( is_ssl() ? 'https' : 'http' ) );
294 |
295 | // Append query string, if its available
296 | $query_string = isset( $matches[5] ) ? $matches[5] : '';
297 |
298 | // If backslashes were escaped, then they need to continue being escaped
299 | if( strpos( $matches[0], '\\/' ) !== false ) {
300 | $add_slashes = true;
301 | } else {
302 | $add_slashes = false;
303 | }
304 |
305 | $result = "{$matches[1]}{$scheme}:"
306 | . ( $add_slashes ? addcslashes("//{$url}/", '/') : "//{$url}/" )
307 | . "{$matches[3]}.{$matches[4]}{$query_string}{$matches[1]}";
308 |
309 | return $result;
310 | }
311 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "dynamic-cdn",
3 | "title": "Dynamic CDN",
4 | "description": "Dynamic CDN for front-end assets.",
5 | "version": "0.4.0",
6 | "homepage": "https://jumping-duck.com",
7 | "repository": {
8 | "type": "git",
9 | "url": "https://github.com/ericmann/dynamic-cdn.git"
10 | },
11 | "author": {
12 | "name": "Eric Mann",
13 | "email": "eric@eamann.com",
14 | "url": "https://eamann.com"
15 | },
16 | "devDependencies": {
17 | "grunt": "~1.0.1",
18 | "grunt-wp-readme-to-markdown": "~2.0.0"
19 | },
20 | "keywords": []
21 | }
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 | ./tests/phpunit
9 |
10 |
11 |
12 |
13 | ./includes
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/readme.txt:
--------------------------------------------------------------------------------
1 | === Dynamic CDN ===
2 | Contributors: ericmann, 10up
3 | Donate link: https://eamann.com
4 | Tags: CDN, images, performance
5 | Requires at least: 3.8.1
6 | Tested up to: 4.5.2
7 | Stable tag: 0.4.0
8 | License: GPLv2 or later
9 | License URI: https://github.com/ericmann/dynamic-cdn/blob/master/LICENSE.md
10 |
11 | Dynamic CDN for front-end assets.
12 |
13 | == Description ==
14 |
15 | Dynamic solution for rewriting image asset URLs to a hosted content delivery network (CDN) with optional domain sharding for concurrent downloads.
16 |
17 | This plugin is based heavily on the CDN dropin from Mark Jaquith's WP_Stack (https://github.com/markjaquith/WP-Stack).
18 |
19 | == Installation ==
20 |
21 | = Manual Installation =
22 |
23 | 1. Upload the entire `/dynamic-cdn` directory to the `/wp-content/plugins/` directory.
24 | 2. Activate Dynamic CDN through the 'Plugins' menu in WordPress.
25 |
26 | == Frequently Asked Questions ==
27 |
28 | = Will this work as a mu-plugin? =
29 |
30 | Yes. The plugin, as designed, will work just fine in the mu-plugins directory. We highly recommend a second mu-plugin be added to configure the CDN domains used by the system.
31 |
32 | = How do I add a domain? =
33 |
34 | In a function wired to `dynamic_cdn_first_loaded`, you'll reference the `->add_domain()` method of the `Dynamic_CDN` object. For example:
35 |
36 | function my_cdn_domains() {
37 | $manager = DomainManager::last();
38 | $manager->add( 'cdn0.mydomain.com' );
39 | $manager->add( 'cdn1.mydomain.com' );
40 | $manager->add( 'cdn2.mydomain.com' );
41 | }
42 | add_action( 'dynamic_cdn_first_loaded', 'my_cdn_domains' );
43 |
44 | = What if I want to add my domains through wp-config.php? =
45 |
46 | Simply define a DYNCDN_DOMAINS constant that's a comma-delimited list of your cdn domains. For example:
47 |
48 | define( 'DYNCDN_DOMAINS', 'cdn0.mydomain.com,cdn1.mydomain.com,cdn2.mydomain.com' );
49 |
50 | = What if I don't add any domains, will this break my images? =
51 |
52 | Hopefully not. If you haven't added any domains the plugin will not rewrite anything, bypassing your images entirely.
53 |
54 | == Screenshots ==
55 |
56 | None at this time.
57 |
58 | == Changelog ==
59 |
60 | = 0.4.0 =
61 | * New: Unit tests for core functionality
62 | * Fix: Ensure srcsets don't filter in admin views
63 |
64 | = 0.3.0 =
65 | * New: Add support for WordPress 4.4 srcsets
66 |
67 | = 0.2.0 =
68 | * New: CDN domains can be added with a constant.
69 | * Fix: Make domain mapping multisite aware. props @trepmal
70 |
71 | = 0.1.0 =
72 | * First release
73 |
74 | == Upgrade Notice ==
75 |
76 | = 0.4.0 =
77 | Domain management has moved from a general-purpose class to a purpose-built `DomainManager` object. This object is
78 | instantiated with your current site's domain name, and can be accessed throught the static `DomainManager::last()` helper.
79 | (This method automatically returns the last-instantiated domain manager). If you weren't manipulating CdN domains
80 | programmatically, you won't need to change anything at all.
81 |
82 | = 0.1.0 =
83 | First Release
84 |
--------------------------------------------------------------------------------
/tests/phpunit/Core_Tests.php:
--------------------------------------------------------------------------------
1 | assertConditionsMet();
28 | }
29 |
30 | /**
31 | * Test initialization method.
32 | */
33 | public function test_init() {
34 | // Setup
35 | M::expectAction( 'dynamic_cdn_init' );
36 |
37 | // Act
38 | init();
39 |
40 | // Verify
41 | $this->assertConditionsMet();
42 | }
43 |
44 | public function test_srcset_replacement() {
45 | $manager = Base\DomainManager( 'http://test.com' );
46 | $manager->add( 'https://cdn1.com' );
47 |
48 | // Mocks
49 | M::wpFunction( 'is_ssl', [ 'return' => false ] );
50 | M::wpPassthruFunction( 'esc_url' );
51 |
52 | $source = [
53 | 'url' => 'http://test.com/image.jpg'
54 | ];
55 |
56 | $replacer = srcset_replacer( 'http://test.com' );
57 |
58 | $this->assertEquals( 'https://cdn1.com/image.jpg', $replacer( $source )['url'] );
59 | }
60 |
61 | public function test_srcset_replacement_no_protocol_cdn() {
62 | $manager = Base\DomainManager( 'http://test1.com' );
63 | $manager->add( 'cdn1.com' );
64 |
65 | // Mocks
66 | M::wpFunction( 'is_ssl', [ 'return' => false ] );
67 | M::wpPassthruFunction( 'esc_url' );
68 |
69 | $source = [
70 | 'url' => 'http://test1.com/image.jpg'
71 | ];
72 |
73 | $replacer = srcset_replacer( 'http://test1.com' );
74 |
75 | $this->assertEquals( 'http://cdn1.com/image.jpg', $replacer( $source )['url'] );
76 | }
77 |
78 |
79 | public function test_host_with_port() {
80 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
81 |
82 | \WP_Mock::wpFunction( 'get_bloginfo', array(
83 | 'args' => 'url',
84 | 'return' => 'http://localhost:9001'
85 | ) );
86 | \WP_Mock::wpFunction( 'wp_upload_dir', array(
87 | 'return' => array(
88 | 'baseurl' => 'http://localhost:9001/wp-content/uploads'
89 | )
90 | ) );
91 | $manager = Base\DomainManager( 'localhost:9001' );
92 | $manager->extensions = array( 'jpg' );
93 | $manager->add( 'cdn1.com' );
94 | $content = '
';
95 | $filtered_content = filter( $content );
96 | $expected = '
';
97 |
98 | $this->assertEquals( $expected, $filtered_content );
99 | }
100 |
101 | public function test_query_string() {
102 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
103 |
104 | \WP_Mock::wpFunction( 'get_bloginfo', array(
105 | 'args' => 'url',
106 | 'return' => 'http://localhost'
107 | ) );
108 | \WP_Mock::wpFunction( 'wp_upload_dir', array(
109 | 'return' => array(
110 | 'baseurl' => 'http://localhost/wp-content/uploads'
111 | )
112 | ) );
113 | $manager = Base\DomainManager( 'localhost' );
114 | $manager->extensions = array( 'jpg' );
115 | $manager->add( 'cdn1.com' );
116 | $site_url = 'http://localhost';
117 | $content = '
118 |
119 |
120 |
121 | ';
122 | $filtered_content = filter( $content );
123 | $expected = '
124 |
125 |
126 |
127 | ';
128 |
129 | $this->assertEquals( $expected, $filtered_content );
130 | }
131 |
132 | public function test_escaped_content() {
133 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
134 | \WP_Mock::wpFunction( 'get_bloginfo', array(
135 | 'args' => 'url',
136 | 'return' => 'http://localhost'
137 | ) );
138 | \WP_Mock::wpFunction( 'wp_upload_dir', array(
139 | 'return' => array(
140 | 'baseurl' => 'http://localhost/wp-content/uploads'
141 | )
142 | ) );
143 | $manager = Base\DomainManager( 'localhost' );
144 | $manager->extensions = array( 'jpg' );
145 | $manager->add( 'cdn1.com' );
146 | $site_url = 'http://localhost';
147 | $content = '
148 |
149 |
150 | ';
151 | $filtered_content = filter( $content );
152 | $expected = '
153 |
154 |
155 | ';
156 | $this->assertEquals( $expected, $filtered_content );
157 | }
158 |
159 | public function test_escaped_content_uploads_only() {
160 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
161 | \WP_Mock::wpFunction( 'get_bloginfo', array(
162 | 'args' => 'url',
163 | 'return' => 'http://localhost'
164 | ) );
165 | \WP_Mock::wpFunction( 'wp_upload_dir', array(
166 | 'return' => array(
167 | 'baseurl' => 'http://localhost/wp-content/uploads'
168 | )
169 | ) );
170 | $manager = Base\DomainManager( 'localhost' );
171 | $manager->extensions = array( 'jpg' );
172 | $manager->add( 'cdn1.com' );
173 | $site_url = 'http://localhost';
174 | $content = '
175 |
176 |
177 | ';
178 | $filtered_content = filter_uploads_only( $content );
179 | $expected = '
180 |
181 |
182 | ';
183 | $this->assertEquals( $expected, $filtered_content );
184 | }
185 |
186 | public function test_json_content() {
187 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
188 | \WP_Mock::wpFunction( 'get_bloginfo', array(
189 | 'args' => 'url',
190 | 'return' => 'http://localhost'
191 | ) );
192 | \WP_Mock::wpFunction( 'wp_upload_dir', array(
193 | 'return' => array(
194 | 'baseurl' => 'http://localhost/wp-content/uploads'
195 | )
196 | ) );
197 | $manager = Base\DomainManager( 'localhost' );
198 | $manager->extensions = array( 'jpg' );
199 | $manager->add( 'cdn1.com' );
200 | $site_url = 'http://localhost';
201 | $content = '{"file": "/wp-content/uploads/puppy.jpg"}';
202 | $filtered_content = filter( $content );
203 | $expected = '{"file": "https://cdn1.com/wp-content/uploads/puppy.jpg"}';
204 | $this->assertEquals( $expected, $filtered_content );
205 | }
206 |
207 | }
208 |
--------------------------------------------------------------------------------
/tests/phpunit/DomainManagerTests.php:
--------------------------------------------------------------------------------
1 | assertNotSame( $second, $first );
25 | $this->assertInstanceOf( '\EAMann\Dynamic_CDN\DomainManager', $first );
26 | $this->assertInstanceOf( '\EAMann\Dynamic_CDN\DomainManager', $second );
27 | $this->assertSame( $second, $third );
28 | }
29 |
30 | public function test_adds_domains() {
31 | $manager = DomainManager( 'http://test.com' );
32 |
33 | $this->assertTrue( $manager->add( 'http://cdn1.com' ) );
34 | $this->assertTrue( $manager->add( 'http://cdn2.com' ) );
35 | $this->assertFalse( $manager->add( 'http://cdn1.com' ) );
36 | }
37 |
38 | public function test_cdn_domain_selection() {
39 | $manager = DomainManager( 'http://test.com' );
40 | $manager->add( 'http://cdn1.com' );
41 | $manager->add( 'http://cdn2.com' );
42 | $manager->add( 'http://cdn3.com' );
43 |
44 | $this->assertEquals( $manager->cdn_domain( 'file1.jpg' ), $manager->cdn_domain( 'file1.jpg' ) );
45 | $this->assertNotEquals( $manager->cdn_domain( 'file1.jpg' ), $manager->cdn_domain( 'file2.jpg' ) );
46 | }
47 |
48 | public function test_domain_replacement() {
49 | $manager = DomainManager( 'http://test.com' );
50 | $manager->add( 'http://cdn1.com' );
51 |
52 | $original = 'http://test.com/image.png';
53 | $expected = 'http://cdn1.com/image.png';
54 |
55 | // Mocks
56 | M::wpFunction( 'is_ssl', [ 'return' => false ] );
57 | M::wpPassthruFunction( 'esc_url' );
58 |
59 | // Verify
60 | $this->assertEquals( $expected, $manager->new_url( $original ) );
61 | }
62 |
63 | public function test_domain_replacement_ssl() {
64 | $manager = DomainManager( 'https://test.com' );
65 | $manager->add( 'https://cdn1.com' );
66 |
67 | $original = 'https://test.com/image.png';
68 | $expected = 'https://cdn1.com/image.png';
69 |
70 | // Mocks
71 | M::wpFunction( 'is_ssl', [ 'return' => true ] );
72 | M::wpPassthruFunction( 'esc_url' );
73 |
74 | // Verify
75 | $this->assertEquals( $expected, $manager->new_url( $original ) );
76 | }
77 |
78 | public function test_domain_replacement_mixed() {
79 | $manager = DomainManager( 'http://test.com' );
80 | $manager->add( 'https://cdn1.com' );
81 |
82 | $original = 'http://test.com/image.png';
83 | $expected = 'https://cdn1.com/image.png';
84 |
85 | // Mocks
86 | M::wpFunction( 'is_ssl', [ 'return' => false ] );
87 | M::wpPassthruFunction( 'esc_url' );
88 |
89 | // Verify
90 | $this->assertEquals( $expected, $manager->new_url( $original ) );
91 | }
92 |
93 | public function test_has_domains() {
94 | $manager = DomainManager( 'http://test.com' );
95 | $this->assertFalse( $manager->has_domains() );
96 |
97 | $manager->add( 'https://cdn1.com' );
98 | $this->assertTrue( $manager->has_domains() );
99 | }
100 |
101 | public function test_default_manager() {
102 | M::wpFunction( 'get_bloginfo', [
103 | 'args' => ['url'],
104 | 'return' => 'http://test.com'
105 | ] );
106 |
107 | $manager = DomainManager::current();
108 |
109 | $regular = DomainManager( 'http://test.com' );
110 |
111 | $this->assertSame( $manager, $regular );
112 | }
113 |
114 | public function test_last_manager() {
115 | $manager = DomainManager( 'http://test.com' );
116 |
117 | $last = DomainManager::last();
118 |
119 | $this->assertSame( $manager, $last );
120 | }
121 | }
--------------------------------------------------------------------------------
/tests/phpunit/test-tools/TestCase.php:
--------------------------------------------------------------------------------
1 | setPreserveGlobalState( false );
13 | return parent::run( $result );
14 | }
15 |
16 | protected $testFiles = array();
17 |
18 | public function setUp() {
19 | if ( ! empty( $this->testFiles ) ) {
20 | foreach ( $this->testFiles as $file ) {
21 | if ( file_exists( PROJECT . $file ) ) {
22 | require_once( PROJECT . $file );
23 | }
24 | }
25 | }
26 |
27 | parent::setUp();
28 | }
29 |
30 | public function assertActionsCalled() {
31 | $actions_not_added = $expected_actions = 0;
32 | try {
33 | WP_Mock::assertActionsCalled();
34 | } catch ( \Exception $e ) {
35 | $actions_not_added = 1;
36 | $expected_actions = $e->getMessage();
37 | }
38 | $this->assertEmpty( $actions_not_added, $expected_actions );
39 | }
40 |
41 | public function ns( $function ) {
42 | if ( ! is_string( $function ) || false !== strpos( $function, '\\' ) ) {
43 | return $function;
44 | }
45 |
46 | $thisClassName = trim( get_class( $this ), '\\' );
47 |
48 | if ( ! strpos( $thisClassName, '\\' ) ) {
49 | return $function;
50 | }
51 |
52 | // $thisNamespace is constructed by exploding the current class name on
53 | // namespace separators, running array_slice on that array starting at 0
54 | // and ending one element from the end (chops the class name off) and
55 | // imploding that using namespace separators as the glue.
56 | $thisNamespace = implode( '\\', array_slice( explode( '\\', $thisClassName ), 0, - 1 ) );
57 |
58 | return "$thisNamespace\\$function";
59 | }
60 |
61 | /**
62 | * Define constants after requires/includes
63 | *
64 | * See http://kpayne.me/2012/07/02/phpunit-process-isolation-and-constant-already-defined/
65 | * for more details
66 | *
67 | * @param \Text_Template $template
68 | */
69 | public function prepareTemplate( \Text_Template $template ) {
70 | $template->setVar( [
71 | 'globals' => '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = \'' . $GLOBALS['__PHPUNIT_BOOTSTRAP'] . '\';',
72 | ] );
73 | parent::prepareTemplate( $template );
74 | }
75 | }
--------------------------------------------------------------------------------