├── phpstan.neon ├── src ├── class-cursor.php ├── cursor │ ├── interface-cursor.php │ ├── class-memory-cursor.php │ └── class-option-cursor.php ├── progress │ ├── interface-progress.php │ ├── class-null-progress-bar.php │ └── class-php-cli-progress-bar.php ├── trait-bulk-task-side-effects.php └── class-bulk-task.php ├── composer.json └── LICENSE /phpstan.neon: -------------------------------------------------------------------------------- 1 | includes: 2 | - vendor/szepeviktor/phpstan-wordpress/extension.neon 3 | 4 | parameters: 5 | # Level 9 is the highest level 6 | level: max 7 | 8 | paths: 9 | - src/ 10 | 11 | scanFiles: 12 | - vendor/php-stubs/wp-cli-stubs/wp-cli-stubs.php 13 | 14 | -------------------------------------------------------------------------------- /src/class-cursor.php: -------------------------------------------------------------------------------- 1 | cursor; 33 | } 34 | 35 | /** 36 | * Resets the value for the cursor. 37 | * 38 | * @return bool 39 | */ 40 | public function reset(): bool { 41 | $this->cursor = 0; 42 | 43 | return true; 44 | } 45 | 46 | /** 47 | * Sets the value for the cursor. 48 | * 49 | * @param int $value The new value for the cursor. 50 | * @return bool 51 | */ 52 | public function set( int $value ): bool { 53 | $this->cursor = $value; 54 | 55 | return true; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/progress/class-php-cli-progress-bar.php: -------------------------------------------------------------------------------- 1 | tick( $current - $this->_current ); 33 | } 34 | 35 | /** 36 | * Tells the progress tracker that it is finished. 37 | */ 38 | public function set_finished(): void { 39 | $this->finish(); 40 | } 41 | 42 | /** 43 | * Define the finish line for the progress tracker. 44 | * 45 | * @param int $total The total to set. 46 | */ 47 | public function set_total( int $total ): void { 48 | $this->setTotal( $total ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alleyinteractive/wp-bulk-task", 3 | "description": "A library to assist with running performant bulk tasks against WordPress objects.", 4 | "license": "GPL-2.0-or-later", 5 | "authors": [ 6 | { 7 | "name": "Alley", 8 | "email": "info@alley.com" 9 | } 10 | ], 11 | "require": { 12 | "php": ">=8.1", 13 | "alleyinteractive/composer-wordpress-autoloader": "^1.0" 14 | }, 15 | "require-dev": { 16 | "alleyinteractive/alley-coding-standards": "^2.0", 17 | "mantle-framework/testkit": "^1.0", 18 | "php-stubs/wp-cli-stubs": "^2.10", 19 | "szepeviktor/phpstan-wordpress": "^1.3", 20 | "wp-cli/php-cli-tools": "^0.11" 21 | }, 22 | "autoload-dev": { 23 | "psr-4": { 24 | "Alley\\WP_Bulk_Task\\Tests\\": "tests/" 25 | } 26 | }, 27 | "config": { 28 | "allow-plugins": { 29 | "alleyinteractive/composer-wordpress-autoloader": true, 30 | "dealerdirect/phpcodesniffer-composer-installer": true 31 | }, 32 | "sort-packages": true 33 | }, 34 | "extra": { 35 | "wordpress-autoloader": { 36 | "autoload": { 37 | "Alley\\WP_Bulk_Task\\": "src/" 38 | } 39 | } 40 | }, 41 | "scripts": { 42 | "lint": "@phpcs", 43 | "lint:fix": "@phpcbf", 44 | "phpcbf": "phpcbf .", 45 | "phpcs": "phpcs .", 46 | "phpstan": "phpstan --memory-limit=512M", 47 | "phpunit": "phpunit", 48 | "test": [ 49 | "@lint", 50 | "@phpstan", 51 | "@phpunit" 52 | ] 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/cursor/class-option-cursor.php: -------------------------------------------------------------------------------- 1 | option_name = 'bt_' . $key; 34 | } 35 | 36 | /** 37 | * Gets the current value for the cursor. Defaults to 0 if not set. 38 | * 39 | * @return int The current value for the cursor. 40 | */ 41 | public function get(): int { 42 | $cursor_value = get_option( $this->option_name, 0 ); 43 | 44 | if ( ! is_numeric( $cursor_value ) ) { 45 | return 0; 46 | } 47 | 48 | return (int) $cursor_value; 49 | } 50 | 51 | /** 52 | * Resets the value for the cursor. 53 | * 54 | * @return bool True if the value was deleted, false otherwise. 55 | * Will also return false if the cursor did not have a value saved to the database. 56 | */ 57 | public function reset(): bool { 58 | return delete_option( $this->option_name ); 59 | } 60 | 61 | /** 62 | * Sets the value for the cursor. 63 | * 64 | * @param int $value The new value for the cursor. 65 | * @return bool True if the value was successfully set, false otherwise. 66 | */ 67 | public function set( int $value ): bool { 68 | return update_option( $this->option_name, $value, false ); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/trait-bulk-task-side-effects.php: -------------------------------------------------------------------------------- 1 | revert_post_modified_date_closure = $this->revert_post_modified_date( ... ); 33 | 34 | add_filter( 'apple_news_skip_push', '__return_true', 100 ); 35 | add_filter( 'apple_news_should_post_autopublish', '__return_false', 100 ); 36 | add_filter( 'pp_notification_status_change', '__return_false', 100 ); 37 | add_filter( 'pp_notification_editorial_comment', '__return_false', 100 ); 38 | add_filter( 'ef_notification_status_change', '__return_false', 999 ); 39 | add_filter( 'wp_insert_post_data', $this->revert_post_modified_date_closure, 10, 2 ); 40 | } 41 | 42 | /** 43 | * Resume integrations and date changes when updating a post. 44 | */ 45 | protected function resume_side_effects(): void { 46 | remove_filter( 'apple_news_skip_push', '__return_true', 100 ); 47 | remove_filter( 'apple_news_should_post_autopublish', '__return_false', 100 ); 48 | remove_filter( 'pp_notification_status_change', '__return_false', 100 ); 49 | remove_filter( 'pp_notification_editorial_comment', '__return_false', 100 ); 50 | remove_filter( 'ef_notification_status_change', '__return_false', 999 ); 51 | if ( isset( $this->revert_post_modified_date_closure ) ) { 52 | remove_filter( 'wp_insert_post_data', $this->revert_post_modified_date_closure, 10 ); 53 | } 54 | } 55 | 56 | /** 57 | * Revert post modified date to date before post update. 58 | * 59 | * @param array $data An array of slashed, sanitized, and processed post data. 60 | * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data. 61 | * @return array Array of filtered post data. 62 | */ 63 | protected function revert_post_modified_date( $data, $postarr ): array { 64 | if ( empty( $data['post_modified'] ) || empty( $data['post_modified_gmt'] ) || empty( $postarr['post_modified'] ) || empty( $postarr['post_modified_gmt'] ) ) { 65 | return $data; 66 | } 67 | 68 | $data['post_modified'] = $postarr['post_modified']; 69 | $data['post_modified_gmt'] = $postarr['post_modified_gmt']; 70 | 71 | return $data; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | 294 | Copyright (C) 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 | , 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 | -------------------------------------------------------------------------------- /src/class-bulk-task.php: -------------------------------------------------------------------------------- 1 | cursor = $cursor ?? new Cursor\Option_Cursor( $key ); 72 | } 73 | 74 | /** 75 | * Actions to be taken after a batch is processed. Calls the WordPress VIP 76 | * helper functions if they exist, or falls back to a manual implementation if 77 | * not. 78 | * 79 | * @global wpdb $wpdb WordPress database abstraction object. 80 | * @global WP_Object_Cache $wp_object_cache Object cache global instance. 81 | * 82 | * @link https://github.com/Automattic/vip-go-mu-plugins/blob/develop/vip-helpers/vip-caching.php 83 | * @link https://github.com/Automattic/vip-go-mu-plugins/blob/develop/vip-helpers/vip-wp-cli.php 84 | */ 85 | protected function after_batch(): void { 86 | global $wp_object_cache; 87 | 88 | // Update cursor with the new min ID. 89 | $this->cursor->set( $this->min_id ); 90 | 91 | // Reset query cache. 92 | if ( function_exists( 'vip_reset_db_query_log' ) ) { 93 | vip_reset_db_query_log(); 94 | } else { 95 | global $wpdb; 96 | 97 | $wpdb->queries = []; 98 | } 99 | 100 | // Reset object cache. 101 | if ( function_exists( 'vip_reset_local_object_cache' ) ) { 102 | vip_reset_local_object_cache(); 103 | } elseif ( $wp_object_cache instanceof \RedisCachePro\ObjectCaches\ObjectCacheInterface && method_exists( $wp_object_cache, 'flush_runtime' ) ) { // @phpstan-ignore-line 104 | $wp_object_cache->flush_runtime(); // @phpstan-ignore-line 105 | } elseif ( is_object( $wp_object_cache ) ) { 106 | 107 | if ( isset( $wp_object_cache->group_ops ) ) { 108 | $wp_object_cache->group_ops = []; 109 | } 110 | 111 | if ( isset( $wp_object_cache->memcache_debug ) ) { 112 | $wp_object_cache->memcache_debug = []; 113 | } 114 | 115 | if ( isset( $wp_object_cache->cache ) ) { 116 | $wp_object_cache->cache = []; 117 | } 118 | 119 | if ( method_exists( $wp_object_cache, '__remoteset' ) ) { 120 | $wp_object_cache->__remoteset(); 121 | } 122 | } 123 | 124 | // Update progress. 125 | $this->progress?->set_current( $this->min_id ); 126 | } 127 | 128 | /** 129 | * Actions to take after a bulk task is run. 130 | */ 131 | protected function after_run(): void { 132 | if ( function_exists( 'wp_defer_term_counting' ) ) { 133 | wp_defer_term_counting( false ); 134 | } 135 | 136 | $this->progress?->set_finished(); 137 | } 138 | 139 | /** 140 | * Actions to take before a bulk task is run. 141 | */ 142 | protected function before_run(): void { 143 | if ( function_exists( 'wp_defer_term_counting' ) ) { 144 | wp_defer_term_counting( true ); 145 | } 146 | 147 | $this->progress?->set_total( $this->max_id ); 148 | } 149 | 150 | /** 151 | * Manipulate the WHERE clause of a bulk task post query to paginate by ID. 152 | * 153 | * This checks the object hash to ensure that we don't manipulate any other 154 | * queries that might run during a bulk task. 155 | * 156 | * @global wpdb $wpdb WordPress database abstraction object. 157 | * 158 | * @param string $where The WHERE clause of the query. 159 | * @param WP_Query $query The WP_Query instance (passed by reference). 160 | * @return string WHERE clause with our pagination added. 161 | */ 162 | public function filter__posts_where( $where, $query ): string { 163 | if ( spl_object_hash( $query ) === $this->object_hash ) { 164 | global $wpdb; 165 | 166 | return sprintf( 167 | 'AND %s.ID > %d %s', 168 | $wpdb->posts, 169 | $this->min_id, 170 | $where 171 | ); 172 | } 173 | 174 | return $where; 175 | } 176 | 177 | /** 178 | * Manipulate the WHERE clause of a bulk task term query to batch by 179 | * term_taxonomy_id. We're using term_taxonomy_id rather than term_id because 180 | * they're less likely to span very large ranges. 181 | * 182 | * This checks the object hash to ensure that we don't manipulate any other 183 | * queries that might run during a bulk task. 184 | * 185 | * @param array $clauses Associative array of the clauses for the query. 186 | * @return array Associative array of the clauses for the query. 187 | */ 188 | public function filter__terms_where( $clauses ): array { 189 | 190 | // Reset if not an array. 191 | if ( ! is_array( $clauses ) ) { 192 | $clauses = []; 193 | } 194 | 195 | if ( ! empty( $this->query ) && spl_object_hash( $this->query ) === $this->object_hash ) { 196 | $clauses['where'] .= sprintf( 197 | ' AND tt.term_taxonomy_id > %d', 198 | $this->min_id 199 | ); 200 | } 201 | 202 | return $clauses; 203 | } 204 | 205 | /** 206 | * Manipulate the WHERE clause of a bulk task user query to paginate by ID. 207 | * 208 | * @global wpdb $wpdb WordPress database abstraction object. 209 | * 210 | * @param WP_User_Query $query Current instance of WP_User_Query (passed by reference). 211 | */ 212 | public function filter__users_where( $query ): void { 213 | 214 | // Bail early. 215 | if ( spl_object_hash( $query ) !== $this->object_hash ) { 216 | return; 217 | } 218 | 219 | global $wpdb; 220 | 221 | $user_table = $wpdb->users; // phpcs:ignore WordPressVIPMinimum.Variables.RestrictedVariables.user_meta__wpdb__users 222 | 223 | $query->query_where .= sprintf( 224 | ' AND %s.ID > %d', 225 | $user_table, 226 | $this->min_id 227 | ); 228 | } 229 | 230 | /** 231 | * Loop through any number of objects efficiently with a callback, and output 232 | * the progress. 233 | * 234 | * @throws \Exception If method is not found. 235 | * 236 | * @param array $args Array of args to pass to query. 237 | * @param callable $callable Callback function to invoke for each object. 238 | * The callable will be passed an object of the 239 | * specified type. 240 | * @param string $object_type Type of object to query. 241 | */ 242 | public function run( array $args, callable $callable, string $object_type = 'wp_post' ): void { 243 | if ( ! method_exists( $this, "run_{$object_type}_query" ) ) { 244 | return; 245 | } 246 | 247 | $method_callback = [ $this, "run_{$object_type}_query" ]; 248 | 249 | if ( ! is_callable( $method_callback ) ) { 250 | throw new \Exception( 'Invalid method callback.' ); 251 | } 252 | 253 | call_user_func( $method_callback, $args, $callable ); 254 | } 255 | 256 | /** 257 | * Loop through any number of rows in a CSV file efficiently with a callback, and output progress. 258 | * 259 | * @throws Exception If the CSV file does not exist or is not readable. 260 | * 261 | * @param array $args { 262 | * Args for the CSV query. 263 | * @type string $csv Path to the CSV file. 264 | * @type int $number Number of rows to clear cursor in each batch. 265 | * } 266 | * @param callable $callable Callback function to invoke for each row. 267 | * The callable will be passed a row array. 268 | * 269 | * @phpstan-param array $args 270 | */ 271 | public function run_csv_query( array $args, callable $callable ): void { 272 | 273 | // Apply default arguments. 274 | $args = wp_parse_args( 275 | $args, 276 | [ 277 | 'csv' => '', 278 | 'number' => 100, 279 | ], 280 | ); 281 | 282 | // Ensure the CSV file exists and is readable. 283 | if ( empty( $args['csv'] ) || ! is_readable( $args['csv'] ) ) { 284 | throw new Exception( 'The CSV file does not exist or is not readable.' ); 285 | } 286 | 287 | /** 288 | * If the CSV document was created or is read on a Legacy Macintosh computer, 289 | * help PHP detect line ending. 290 | * 291 | * @see https://php.watch/versions/8.1/auto_detect_line_endings-ini-deprecated 292 | */ 293 | if ( version_compare( PHP_VERSION, '8.1.0', '<' ) ) { 294 | if ( ! ini_get( 'auto_detect_line_endings' ) ) { 295 | ini_set( 'auto_detect_line_endings', '1' ); 296 | } 297 | } 298 | 299 | // It assumes that the file is encoded in UTF-8. 300 | try { 301 | $csv = new SplFileObject( $args['csv'], 'r' ); 302 | } catch ( Exception $e ) { 303 | throw new Exception( $e->getMessage() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped 304 | } 305 | 306 | // Set the CSV flags. 307 | $csv->setFlags( SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE ); 308 | 309 | // Set the min ID from the cursor. 310 | $this->min_id = $this->cursor->get(); 311 | 312 | // Set the max ID from CSV file. 313 | $csv->seek( PHP_INT_MAX ); 314 | $this->max_id = $csv->key(); 315 | 316 | // Turn off some automatic behavior that would slow down the process. 317 | $this->before_run(); 318 | 319 | /** 320 | * We do not run rows in batches since the CSV file outputs all rows at once. 321 | * 322 | * But we need it for the cursor, progress to be updated, and resetting 323 | * the object cache. 324 | */ 325 | $batch_size = 0; 326 | 327 | // All systems go. 328 | foreach ( $csv as $row ) { 329 | $line_number = $csv->key(); 330 | 331 | // Skip lines outside of the range. 332 | if ( $line_number < $this->min_id || $line_number > $this->max_id ) { 333 | continue; 334 | } 335 | 336 | if ( $batch_size < $args['number'] ) { 337 | $batch_size++; 338 | } 339 | 340 | $callable( $row, $line_number ); 341 | 342 | // Batch size reached, so update the cursor. 343 | if ( 100 === $batch_size ) { 344 | $batch_size = 0; 345 | 346 | // Update our min ID for the next batch. 347 | $this->min_id = $line_number; 348 | } 349 | 350 | $this->after_batch(); 351 | } 352 | 353 | // Unset the CSV file. Required to close the file stream. 354 | unset( $csv ); 355 | 356 | // Re-enable automatic behavior turned off earlier. 357 | $this->after_run(); 358 | } 359 | 360 | /** 361 | * Loop through any number of terms efficiently with a callback, and output 362 | * the progress. 363 | * 364 | * @global wpdb $wpdb WordPress database abstraction object. 365 | * 366 | * @param array $args { 367 | * WP_Term_Query args. Some have overridden defaults, and some are fixed. 368 | * Anything not mentioned below will operate as normal. 369 | * 370 | * @type string $order Always 'ASC'. 371 | * @type string $orderby Always 'term_id'. 372 | * @type bool $update_term_meta_cache Always false. 373 | * @type int $number Defaults to 0 (all). 374 | * } 375 | * @param callable $callable Callback function to invoke for each post. 376 | * The callable will be passed a post object. 377 | * 378 | * @phpstan-param array $args 379 | */ 380 | public function run_wp_term_query( array $args, callable $callable ): void { 381 | global $wpdb; 382 | 383 | // Apply default arguments. 384 | $args = wp_parse_args( $args, [ 'number' => 0 ] ); 385 | 386 | // Force some arguments and don't let them get overridden. 387 | $args['order'] = 'ASC'; 388 | $args['orderby'] = 'term_id'; 389 | $args['update_term_meta_cache'] = false; 390 | 391 | // Set the min ID from the cursor. 392 | $this->min_id = $this->cursor->get(); 393 | 394 | // Set the max ID from the database. 395 | $this->max_id = (int) $wpdb->get_var( 'SELECT MAX(term_taxonomy_id) FROM ' . $wpdb->term_taxonomy ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 396 | 397 | // Handle batching. 398 | add_filter( 'terms_clauses', [ $this, 'filter__terms_where' ], 9999 ); 399 | 400 | // Turn off some automatic behavior that would slow down the process. 401 | $this->before_run(); 402 | 403 | // All systems go. 404 | while ( $this->min_id < $this->max_id ) { 405 | // Build the query object, but don't run it without the object hash. 406 | $this->query = new WP_Term_Query(); 407 | 408 | // Store the unique object hash to ensure we only filter this query. 409 | $this->object_hash = spl_object_hash( $this->query ); 410 | 411 | // Run the query. 412 | $this->query->query( $args ); 413 | 414 | // Fork for results vs. not. 415 | if ( ! empty( $this->query->terms ) ) { 416 | // Invoke the callable over every term. 417 | array_walk( $this->query->terms, $callable, $this->query ); 418 | 419 | // Update our min ID for the next query. 420 | $this->min_id = end( $this->query->terms )->term_taxonomy_id; 421 | } else { 422 | // No results found in the block of terms, so skip to the end. 423 | $this->min_id = $this->max_id; 424 | } 425 | 426 | // Actions to run after each batch of results. 427 | $this->after_batch(); 428 | } 429 | 430 | // Re-enable automatic behavior turned off earlier. 431 | $this->after_run(); 432 | 433 | // Remove filter after task run. Prevents double filtering the query if you're instantiating the class multiple times. 434 | remove_filter( 'terms_clauses', [ $this, 'filter__terms_where' ], 9999 ); 435 | } 436 | 437 | /** 438 | * Loop through any number of posts efficiently with a callback, and output 439 | * the progress. 440 | * 441 | * @global wpdb $wpdb WordPress database abstraction object. 442 | * 443 | * @param array $args { 444 | * WP_Query args. Some have overridden defaults, and some are fixed. 445 | * Anything not mentioned below will operate as normal. 446 | * 447 | * @type bool $ignore_sticky_posts Always true. 448 | * @type bool $no_found_rows Always true. 449 | * @type string $order Always 'ASC'. 450 | * @type string $orderby Always 'ID'. 451 | * @type int $paged Always 1. 452 | * @type string $post_status Defaults to 'any'. 453 | * @type string $post_type Defaults to 'any'. 454 | * @type int $posts_per_page Defaults to 100. 455 | * @type bool $suppress_filters Always false. 456 | * } 457 | * @param callable $callable Callback function to invoke for each post. 458 | * The callable will be passed a post object. 459 | * 460 | * @phpstan-param array $args 461 | */ 462 | public function run_wp_post_query( array $args, callable $callable ): void { 463 | global $wpdb; 464 | 465 | // Apply default arguments. 466 | $args = wp_parse_args( 467 | $args, 468 | [ 469 | 'post_type' => 'any', 470 | 'post_status' => 'any', 471 | 'posts_per_page' => 100, 472 | ], 473 | ); 474 | 475 | // Force some arguments and don't let them get overridden. 476 | $args['ignore_sticky_posts'] = true; 477 | $args['no_found_rows'] = true; 478 | $args['order'] = 'ASC'; 479 | $args['orderby'] = 'ID'; 480 | $args['paged'] = 1; 481 | $args['suppress_filters'] = false; 482 | 483 | // Set the min ID from the cursor. 484 | $this->min_id = $this->cursor->get(); 485 | 486 | // Set the max ID from the database. 487 | $this->max_id = (int) $wpdb->get_var( 'SELECT MAX(ID) FROM ' . $wpdb->posts ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 488 | 489 | // Disable ElasticPress or VIP Search integration by default. 490 | add_filter( 'ep_skip_query_integration', '__return_true', 100 ); 491 | 492 | // Handle pagination. 493 | add_filter( 'posts_where', [ $this, 'filter__posts_where' ], 9999, 2 ); 494 | 495 | // Turn off some automatic behavior that would slow down the process. 496 | $this->before_run(); 497 | 498 | // All systems go. 499 | while ( $this->min_id < $this->max_id ) { 500 | // Build the query object, but don't run it without the object hash. 501 | $this->query = new WP_Query(); 502 | 503 | // Store the unique object hash to ensure we only filter this query. 504 | $this->object_hash = spl_object_hash( $this->query ); 505 | 506 | // Run the query. 507 | $this->query->query( $args ); 508 | 509 | // Fork for results vs. not. 510 | if ( $this->query->have_posts() ) { 511 | // Invoke the callable over every post. 512 | array_walk( $this->query->posts, $callable, $this->query ); 513 | 514 | // Update our min ID for the next query. 515 | $last_post = end( $this->query->posts ); 516 | $this->min_id = $last_post instanceof WP_Post ? $last_post->ID : 0; 517 | } else { 518 | // No results found in the block of posts, so skip to the end. 519 | $this->min_id = $this->max_id; 520 | } 521 | 522 | // Actions to run after each batch of results. 523 | $this->after_batch(); 524 | } 525 | 526 | // Re-enable automatic behavior turned off earlier. 527 | $this->after_run(); 528 | 529 | // Remove filter after task run. Prevents double filtering the query if you're instantiating the class multiple times. 530 | remove_filter( 'posts_where', [ $this, 'filter__posts_where' ], 9999 ); 531 | 532 | // Remove filter after task run. 533 | remove_filter( 'ep_skip_query_integration', '__return_true', 100 ); 534 | } 535 | 536 | /** 537 | * Loop through any number of users efficiently with a callback, and output 538 | * the progress. 539 | * 540 | * @global wpdb $wpdb WordPress database abstraction object. 541 | * 542 | * @param array $args { 543 | * WP_User_Query args. Some have overridden defaults, and some are fixed. 544 | * Anything not mentioned below will operate as normal. 545 | * 546 | * @type string $order Always 'ASC'. 547 | * @type string $orderby Always 'ID'. 548 | * @type int $paged Always 1. 549 | * @type int $paged Always 1. 550 | * @type int $count_total Always false. 551 | * @type int $has_published_posts Always false. 552 | * @type int $number Defaults to 100. 553 | * } 554 | * @param callable $callable Callback function to invoke for each post. 555 | * The callable will be passed a post object. 556 | * 557 | * @phpstan-param array $args 558 | */ 559 | public function run_wp_user_query( array $args, callable $callable ): void { 560 | global $wpdb; 561 | 562 | // Apply default arguments. 563 | $args = wp_parse_args( $args, [ 'number' => 100 ] ); 564 | 565 | // Force some arguments and don't let them get overridden. 566 | $args['order'] = 'ASC'; 567 | $args['orderby'] = 'ID'; 568 | $args['paged'] = 1; 569 | $args['has_published_posts'] = false; 570 | $args['count_total'] = false; 571 | 572 | // Set the min ID from the cursor. 573 | $this->min_id = $this->cursor->get(); 574 | 575 | // Set the max ID from the database. 576 | $this->max_id = (int) $wpdb->get_var( 'SELECT MAX(ID) FROM ' . $wpdb->users ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPressVIPMinimum.Variables.RestrictedVariables.user_meta__wpdb__users 577 | 578 | // Handle batching. 579 | add_action( 'pre_user_query', [ $this, 'filter__users_where' ], 9999 ); 580 | 581 | // Turn off some automatic behavior that would slow down the process. 582 | $this->before_run(); 583 | 584 | // All systems go. 585 | while ( $this->min_id < $this->max_id ) { 586 | // Build the query object. 587 | $this->query = new WP_User_Query(); 588 | 589 | // Store the unique object hash to ensure we only filter this query. 590 | $this->object_hash = spl_object_hash( $this->query ); 591 | 592 | // Prepare the query. 593 | $this->query->prepare_query( $args ); 594 | 595 | // Run the query. 596 | $this->query->query(); 597 | 598 | // Get the results. 599 | $results = $this->query->get_results(); 600 | 601 | // Fork for results vs. not. 602 | if ( ! empty( $results ) ) { 603 | // Invoke the callable over every term. 604 | array_walk( $results, $callable, $this->query ); 605 | 606 | // Update our min ID for the next query. 607 | $this->min_id = end( $results )->ID; 608 | } else { 609 | // No results found in the block of users, so skip to the end. 610 | $this->min_id = $this->max_id; 611 | } 612 | 613 | // Actions to run after each batch of results. 614 | $this->after_batch(); 615 | } 616 | 617 | // Re-enable automatic behavior turned off earlier. 618 | $this->after_run(); 619 | 620 | // Remove action after task run. Prevents double filtering the query if you're instantiating the class multiple times. 621 | remove_action( 'pre_user_query', [ $this, 'filter__users_where' ], 9999 ); 622 | } 623 | } 624 | --------------------------------------------------------------------------------