diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c08daf6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# See http://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[{*.php,*.html}] +indent_style = space +indent_size = 4 + +[*.js] +indent_style = space +indent_size = 2 + +[{*.css,*.scss}] +indent_style = space +indent_size = 4 + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4105a06 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,58 @@ +name: Tests + +on: + push: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + tests: + runs-on: ubuntu-latest + + services: + mysql: + image: mysql:5.7 + env: + MYSQL_DATABASE: testdb + MYSQL_USER: user + MYSQL_PASSWORD: password + MYSQL_ROOT_PASSWORD: rootpassword + ports: + - 3306:3306 + options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 + + strategy: + fail-fast: true + matrix: + php: ['7.4', '8.2'] + + name: PHP ${{ matrix.php }} + steps: + - uses: actions/checkout@v2 + + - uses: actions/setup-node@v2 + with: + node-version: 16.x + + - name: Install PHP + uses: shivammathur/setup-php@master + with: + php-version: ${{ matrix.php }} + + - name: Report PHP version + run: php -v + + - name: Install dependencies + run: composer install --no-interaction + + - name: Test Syntax + run: ./test/test_for_syntax_errors.sh + + - name: Test Installation + run: ./test/test_installation.sh + + - name: Test phpcs + run: ./test/test_phpcs.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..897e6aa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,47 @@ +name: Release + +on: + push: + tags: + - '*.*' # Push events to matching v*, i.e. v1.0, v20.15.10 + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" + # Docs: https://getcomposer.org/doc/articles/scripts.md + + # - name: Run test suite + # run: composer run-script test + # cp -r disciple-tools-migration.php includes languages spinner.svg version-control.json LICENSE SECURITY.md disciple-tools-migration/ + # Below borrowed from https://github.com/actions/upload-release-asset + - name: Build project + run: | + mkdir disciple-tools-migration + cp -r disciple-tools-migration.php admin charts languages magic-link post-type rest-api site-link tile workflows spinner.svg version-control.json LICENSE SECURITY.md disciple-tools-migration/ + zip -r disciple-tools-migration.zip disciple-tools-migration + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + draft: false + prerelease: false + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./disciple-tools-migration.zip + asset_name: disciple-tools-migration.zip + asset_content_type: application/zip diff --git a/.github/workflows/translations.yml b/.github/workflows/translations.yml new file mode 100644 index 0000000..6678a3f --- /dev/null +++ b/.github/workflows/translations.yml @@ -0,0 +1,63 @@ +name: translation-workflow +run-name: Regenerating pot file + +on: + workflow_run: + workflows: ["Release"] + types: [requested] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + update-pot-file: + runs-on: ubuntu-latest + steps: + - name: Checkout master branch + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install PHP + uses: shivammathur/setup-php@master + with: + php-version: "7.4" + + - name: Setup WP-CLI + uses: godaddy-wordpress/setup-wp-cli@1 + + ####################### + ### MAKE EDITS HERE ### + ####################### + # edit .pot location + # remove/edit --subtract option + # add any files or folders for excluding if necessary with --exclude options + ####################### + - name: Generate new pot file + run: > + wp i18n make-pot . languages/default.pot --skip-audit --subtract="languages/terms_to_exclude.pot" + --exclude="admin" + ####################### + + - name: Check diff output + run: git diff | wc -l + + - name: Add changes + run: git add -A + + - name: Check status + run: git status + + - name: push changes + uses: github-actions-x/commit@master + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + push-branch: master + commit-message: 'Update .pot translation file' + name: ${{ github.actor }} + email: ${{github.actor}}@users.noreply.github.com + + - name: Check git config + run: git config --list --show-origin diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1a3bf87 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +vendor/* +composer.lock +.idea +.phpunit.result.cache diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..754bd20 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at info@disciple.tools. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..f341e74 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,31 @@ +Thank you for joining us in contributing to Disciple.Tools! These are the guidelines we expect you to follow in writing code that will be used in or with D.T. + +### Translations +D.T is already being used in multiple languages. Please help us make D.T translable by taking full advantage of Wordpress’ translatable strings. Any string that will be read by the user must be marked as translatable. Ex: +`` + +Make sure you look for these in PHP, HTML and JavaScript code. + +### PHPCS +We use [PHPCS](https://github.com/squizlabs/PHP_CodeSniffer) and [PHPCS WordPress Coding Standards](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards) to test for syntax errors, security vulnerabilities and some styling rules. We expect your commits to pass these tests. + +In the theme you can run `./tests/test_phpcs.sh` or create a pull request to our repo and Github Actions CI will run the tests for you. + +If you are working on a plugin based off our starter plugin run `./includes/admin/test/test_phpcs.sh` + +You might need to run `composer install` first. + +Note: rules for PHPCS are located in the `phpcs.xml` file. We sometimes update the rule list as PHPCS updates. We’ll update the [starter plugin](https://github.com/DiscipleTools/disciple-tools-migration) `phpcs.xml`, you might want to look there to get the latest version. + +### GitHub and Commits +For new plugins copy our [starter plugin](https://github.com/DiscipleTools/disciple-tools-migration). + +To commit to the theme or an existing plugin start by creating a fork of the repository. When you are ready, create a pull request into our repo. + +Note: Depending on your context you may wish to use an anonymous GitHub account. + +### `WP_DEBUG` +Enable `WP_DEBUG` in your `wp-config.php`: `define('WP_DEBUG', true);` +Checking out a PR and seeing the orange debug table is disappointing. + +We look forward to hearing from you! diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..692e761 --- /dev/null +++ b/LICENSE @@ -0,0 +1,366 @@ +Disciple.Tools - Migrations + +Copyright (C) 2018 by various contributors + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +This program incoporates these works: + +- "jquery" by jQuery Foundation and other contributors, licensed under the MIT +license. You can find the required copyright notice and permission notice at +dependencies/jquery/LICENSE.txt + + +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..aefa44e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,10 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a security vulnerability in these WordPress plugins and/or themes, or in the website https://disciple.tools , please send an email to supportXXXXdisciple.tools , replacing XXXX with the @ symbol. We ask that you give us a reasonable amount of time to correct the issue before you make the vulnerability public. Please do not submit a GitHub issue or a GitHub pull request, as these are public. + +## Supported Versions + +Our development is forward focused. Although we are writing with backward compatibility in mind, due to resources and time, our security patching and upgrades +are focused on the most currently released version. All plugin users are strongly encouraged to upgrade when new releases or published. diff --git a/admin/admin-menu-and-tabs.php b/admin/admin-menu-and-tabs.php new file mode 100644 index 0000000..3cfccdf --- /dev/null +++ b/admin/admin-menu-and-tabs.php @@ -0,0 +1,242 @@ +page_title = __( 'Migration', 'disciple-tools-migration' ); + } // End __construct() + + /** + * Returns the current migration settings from the options table. + * + * @return array + */ + public static function get_settings(): array { + $defaults = [ + 'enabled' => false, + 'mode' => 'api', + 'allowed_items' => [ + 'general_settings' => true, + 'custom_lists' => true, + 'tiles' => true, + 'fields' => true, + 'roles' => true, + 'workflows' => true, + 'records' => [ + 'contacts' => true, + 'groups' => true, + ], + ], + 'api' => [ + 'connection_type' => 'site_link', + 'site_link_id' => 0, + 'remote_base_url' => '', + 'auth_token' => '', + 'jwt_token' => '', + 'jwt_token_set_at' => 0, + ], + 'file' => [ + 'compression' => 'zip', + ], + ]; + + $current = get_option( 'dt_migration_settings', [] ); + if ( ! is_array( $current ) ) { + $current = []; + } + + return wp_parse_args( $current, $defaults ); + } + + /** + * Persists migration settings to the options table. + * + * @param array $settings + * + * @return void + */ + public static function update_settings( array $settings ): void { + update_option( 'dt_migration_settings', $settings ); + } + + /** + * Registers the top-level Migration admin menu. + * + * @since 0.1.0 + */ + public function register_menu() { + $this->page_title = __( 'Migration', 'disciple-tools-migration' ); + + $parent_slug = $this->token; + + // Top-level menu. + add_menu_page( + $this->page_title, + $this->page_title, + 'manage_dt', + $parent_slug, + [ $this, 'content' ], + 'dashicons-migrate', + 57 + ); + + // Submenu entries so the left-hand menu shows a fly-out similar to Site Links. + add_submenu_page( + $parent_slug, + __( 'Settings', 'disciple-tools-migration' ), + __( 'Settings', 'disciple-tools-migration' ), + 'manage_dt', + $parent_slug, + [ $this, 'content' ] + ); + + add_submenu_page( + $parent_slug, + __( 'Export', 'disciple-tools-migration' ), + __( 'Export', 'disciple-tools-migration' ), + 'manage_dt', + $parent_slug . '_export', + [ $this, 'content' ] + ); + + add_submenu_page( + $parent_slug, + __( 'Import', 'disciple-tools-migration' ), + __( 'Import', 'disciple-tools-migration' ), + 'manage_dt', + $parent_slug . '_import', + [ $this, 'content' ] + ); + } + + /** + * Builds the Migration page contents and tab navigation. + * + * @since 0.1.0 + */ + public function content() { + if ( ! current_user_can( 'manage_dt' ) ) { // manage_dt is Disciple.Tools specific permission. + wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'disciple-tools-migration' ) ); + } + + $tab = 'settings'; + $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : $this->token; + + // Allow explicit tab override via query parameter for flexibility. + if ( isset( $_GET['tab'] ) ) { + $tab = sanitize_key( wp_unslash( $_GET['tab'] ) ); + } else { + // Map submenu page slugs back to logical tabs. + if ( $page === $this->token . '_export' ) { + $tab = 'export'; + } elseif ( $page === $this->token . '_import' ) { + $tab = 'import'; + } else { + $tab = 'settings'; + } + } + + $link = 'admin.php?page=' . $this->token . '&tab='; + + ?> +
+

page_title ); ?>

+ + + content(); + break; + case 'export': + $object = new Disciple_Tools_Migration_Tab_Export(); + $object->content(); + break; + case 'import': + $object = new Disciple_Tools_Migration_Tab_Import(); + $object->content(); + break; + default: + /** + * Allow extensions to hook custom tabs. + * + * @param string $tab Current tab slug. + */ + do_action( 'dt_migration_tab_content', $tab ); + break; + } + ?> + +
+ + $enabled ) { + if ( ! $enabled ) { + continue; + } + $mode = isset( $export_by[ $post_type ] ) && $export_by[ $post_type ] === 'limit' ? 'limit' : 'range'; + $limit = $mode === 'limit' ? absint( $limits[ $post_type ] ?? 0 ) : 0; + $min_id = $mode === 'range' ? absint( $min_ids[ $post_type ] ?? 0 ) : 0; + $max_id = $mode === 'range' ? absint( $max_ids[ $post_type ] ?? 0 ) : 0; + if ( $limit > 0 || $min_id > 0 || $max_id > 0 ) { + $record_options[ $post_type ] = [ + 'limit' => $limit, + 'min_id' => $min_id, + 'max_id' => $max_id, + ]; + } + } + + $payload = Disciple_Tools_Migration_Export_File::build_export( $record_options ); + + if ( isset( $payload['error'] ) ) { + wp_die( esc_html( $payload['error'] ) ); + } + + $filename = 'dt-migration-export-' . gmdate( 'Y-m-d-His' ) . '.json'; + header( 'Content-Type: application/json; charset=utf-8' ); + header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' ); + header( 'Cache-Control: no-cache, must-revalidate' ); + header( 'Pragma: no-cache' ); + + echo wp_json_encode( $payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ); + exit; + } +} diff --git a/admin/class-dt-migration-import-ajax.php b/admin/class-dt-migration-import-ajax.php new file mode 100644 index 0000000..660f3ff --- /dev/null +++ b/admin/class-dt-migration-import-ajax.php @@ -0,0 +1,335 @@ + admin_url( 'admin-ajax.php' ), + 'nonce' => wp_create_nonce( 'dt_migration_import' ), + ] + ); + wp_add_inline_style( 'wp-admin', $this->get_modal_css() ); + } + + /** + * Returns inline CSS for the modal and progress UI. + * + * @return string + */ + private function get_modal_css() : string { + return ' + .dt-migration-modal { position: fixed; inset: 0; z-index: 100000; display: flex; align-items: center; justify-content: center; } + .dt-migration-modal-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); } + .dt-migration-modal-content { position: relative; background: #fff; padding: 24px; max-width: 500px; width: 90%; box-shadow: 0 4px 20px rgba(0,0,0,0.2); border-radius: 4px; } + .dt-migration-modal-body { margin-top: 16px; } + .dt-migration-modal-warning { color: #b32d2e; font-weight: 600; } + .dt-migration-modal-summary { margin: 12px 0; padding: 12px; background: #f0f0f1; border-radius: 4px; font-size: 13px; } + .dt-migration-confirm-input { width: 100%; margin: 8px 0 16px; padding: 8px; } + .dt-migration-modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; } + .dt-migration-progress-panel { margin-top: 20px; padding: 20px; background: #f6f7f7; border: 1px solid #c3c4c7; border-radius: 4px; } + .dt-migration-progress-bar-wrap { display: flex; align-items: center; gap: 12px; } + .dt-migration-progress-bar { flex: 1; height: 24px; background: #ddd; border-radius: 4px; overflow: hidden; } + .dt-migration-progress-fill { display: block; height: 100%; background: #2271b1; width: 0%; transition: width 0.2s; } + .dt-migration-step-list { margin: 16px 0; padding-left: 24px; } + .dt-migration-step-list .done { color: #00a32a; } + .dt-migration-step-list .active { font-weight: 600; } + .dt-migration-current-phase { margin-top: 8px; font-style: italic; color: #50575e; } + .dt-migration-error-details { margin-top: 16px; padding: 12px; background: #fcf0f1; border: 1px solid #d63638; border-radius: 4px; } + .dt-migration-error-details strong { display: block; margin-bottom: 8px; color: #b32d2e; } + .dt-migration-error-scroll { max-height: 200px; overflow-y: auto; padding: 8px; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; white-space: pre-wrap; font-size: 12px; line-height: 1.4; } + '; + } + + /** + * Handles the import batch AJAX request. + * + * Supports both API mode (fetch from remote) and file mode (use transient payload). + */ + public function handle_import_batch() : void { + check_ajax_referer( 'dt_migration_import', 'nonce' ); + + if ( ! current_user_can( 'manage_dt' ) ) { + wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'disciple-tools-migration' ) ] ); + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + if ( empty( $settings['enabled'] ) ) { + wp_send_json_error( [ 'message' => __( 'Migration is not enabled.', 'disciple-tools-migration' ) ] ); + } + + $mode = $settings['mode'] ?? 'api'; + $step = isset( $_POST['step'] ) ? sanitize_key( wp_unslash( $_POST['step'] ) ) : ''; + + if ( $mode === 'file' ) { + $this->handle_file_mode_batch( $step, $settings ); + return; + } + + if ( $mode !== 'api' ) { + wp_send_json_error( [ 'message' => __( 'Migration mode not supported for import.', 'disciple-tools-migration' ) ] ); + } + + $remote_url = $settings['api']['remote_base_url'] ?? ''; + $jwt = $settings['api']['jwt_token'] ?? ''; + $token_at = (int) ( $settings['api']['jwt_token_set_at'] ?? 0 ); + + if ( empty( $remote_url ) || empty( $jwt ) ) { + wp_send_json_error( [ 'message' => __( 'Not connected to Server A. Run Test Connection first.', 'disciple-tools-migration' ) ] ); + } + + if ( $token_at < ( time() - HOUR_IN_SECONDS ) ) { + wp_send_json_error( [ 'message' => __( 'JWT token expired. Please re-run Test Connection.', 'disciple-tools-migration' ) ] ); + } + + $base = rtrim( $remote_url, '/' ); + + if ( $step === 'settings' ) { + $selected = isset( $_POST['settings_selected'] ) && is_array( $_POST['settings_selected'] ) + ? array_map( 'sanitize_key', wp_unslash( $_POST['settings_selected'] ) ) + : []; + + $export_res = wp_remote_post( + $base . '/wp-json/dt-migration/v1/export', + [ + 'timeout' => 60, + 'headers' => [ + 'Authorization' => 'Bearer ' . $jwt, + 'Content-Type' => 'application/json', + ], + 'body' => wp_json_encode( [ 'settings_only' => true ] ), + ] + ); + + if ( is_wp_error( $export_res ) ) { + wp_send_json_error( [ 'message' => $export_res->get_error_message() ] ); + } + + $code = wp_remote_retrieve_response_code( $export_res ); + $body = json_decode( (string) wp_remote_retrieve_body( $export_res ), true ); + if ( $code < 200 || $code >= 300 || ! is_array( $body ) ) { + wp_send_json_error( [ 'message' => __( 'Failed to fetch export from Server A.', 'disciple-tools-migration' ) ] ); + } + + $selected_map = array_fill_keys( $selected, true ); + $result = Disciple_Tools_Migration_Import_Engine::import_settings( $body, $selected_map ); + + if ( ! empty( $result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $result['errors'] ), + 'applied' => $result['applied'] ?? [], + ] ); + } + + wp_send_json_success( [ + 'done' => true, + 'phase' => 'settings', + 'applied' => $result['applied'] ?? [], + ] ); + } + + if ( $step === 'records' ) { + $post_type = isset( $_POST['post_type'] ) ? sanitize_key( wp_unslash( $_POST['post_type'] ) ) : ''; + $offset = isset( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 0; + $limit = 50; + + if ( empty( $post_type ) ) { + wp_send_json_error( [ 'message' => __( 'Post type required.', 'disciple-tools-migration' ) ] ); + } + + $records_url = add_query_arg( + [ 'offset' => $offset, 'limit' => $limit ], + $base . '/wp-json/dt-migration/v1/records/' . $post_type + ); + + $records_res = wp_remote_get( + $records_url, + [ + 'timeout' => 60, + 'headers' => [ 'Authorization' => 'Bearer ' . $jwt ], + ] + ); + + if ( is_wp_error( $records_res ) ) { + wp_send_json_error( [ 'message' => $records_res->get_error_message() ] ); + } + + $code = wp_remote_retrieve_response_code( $records_res ); + $rbody = json_decode( (string) wp_remote_retrieve_body( $records_res ), true ); + $recs = $rbody['records'] ?? []; + $total = (int) ( $rbody['total'] ?? 0 ); + $has_more = ! empty( $rbody['has_more'] ); + + $batch_result = Disciple_Tools_Migration_Import_Engine::import_records_batch( $post_type, $recs, $offset ); + + if ( ! empty( $batch_result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $batch_result['errors'] ), + 'imported' => $batch_result['imported'] ?? 0, + ] ); + } + + if ( $post_type === 'groups' && ! $has_more ) { + $conn_result = Disciple_Tools_Migration_Import_Engine::apply_deferred_group_connections(); + if ( ! empty( $conn_result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $conn_result['errors'] ), + 'imported' => $batch_result['imported'] ?? 0, + ] ); + } + } + + wp_send_json_success( [ + 'done' => ! $has_more, + 'phase' => 'records', + 'post_type' => $post_type, + 'imported' => $batch_result['imported'], + 'offset' => $offset, + 'total' => $total, + 'has_more' => $has_more, + 'next_offset' => $offset + count( $recs ), + ] ); + } + + wp_send_json_error( [ 'message' => __( 'Invalid step.', 'disciple-tools-migration' ) ] ); + } + + /** + * Handles import batch requests for file mode (payload in transient). + * + * @param string $step 'settings' or 'records' + * @param array $settings Migration settings. + */ + private function handle_file_mode_batch( string $step, array $settings ) : void { + $transient_key = 'dt_migration_file_payload_' . get_current_user_id(); + $payload = get_transient( $transient_key ); + + if ( ! is_array( $payload ) || empty( $payload['export']['dt_settings'] ) ) { + wp_send_json_error( [ + 'message' => __( 'No migration file loaded or payload expired. Please upload the file again.', 'disciple-tools-migration' ), + ] ); + } + + if ( $step === 'settings' ) { + $selected = isset( $_POST['settings_selected'] ) && is_array( $_POST['settings_selected'] ) + ? array_map( 'sanitize_key', wp_unslash( $_POST['settings_selected'] ) ) + : []; + + $selected_map = array_fill_keys( $selected, true ); + $result = Disciple_Tools_Migration_Import_Engine::import_settings( $payload, $selected_map ); + + if ( ! empty( $result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $result['errors'] ), + 'applied' => $result['applied'] ?? [], + ] ); + } + + wp_send_json_success( [ + 'done' => true, + 'phase' => 'settings', + 'applied' => $result['applied'] ?? [], + ] ); + } + + if ( $step === 'records' ) { + $post_type = isset( $_POST['post_type'] ) ? sanitize_key( wp_unslash( $_POST['post_type'] ) ) : ''; + $offset = isset( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 0; + $limit = 50; + + if ( empty( $post_type ) ) { + wp_send_json_error( [ 'message' => __( 'Post type required.', 'disciple-tools-migration' ) ] ); + } + + $records_all = $payload['records'][ $post_type ] ?? []; + if ( ! is_array( $records_all ) ) { + $records_all = []; + } + + $total = count( $records_all ); + $slice = array_slice( $records_all, $offset, $limit ); + $has_more = ( $offset + count( $slice ) ) < $total; + + try { + $batch_result = Disciple_Tools_Migration_Import_Engine::import_records_batch( $post_type, $slice, $offset ); + } catch ( Throwable $e ) { + wp_send_json_error( [ + 'message' => sprintf( + /* translators: 1: error message, 2: file and line */ + __( 'Import failed: %1$s (%2$s)', 'disciple-tools-migration' ), + $e->getMessage(), + $e->getFile() . ':' . $e->getLine() + ), + ] ); + } + + if ( ! empty( $batch_result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $batch_result['errors'] ), + 'imported' => $batch_result['imported'] ?? 0, + ] ); + } + + if ( $post_type === 'groups' && ! $has_more ) { + $conn_result = Disciple_Tools_Migration_Import_Engine::apply_deferred_group_connections(); + if ( ! empty( $conn_result['errors'] ) ) { + wp_send_json_error( [ + 'message' => implode( "\n", $conn_result['errors'] ), + 'imported' => $batch_result['imported'] ?? 0, + ] ); + } + } + + wp_send_json_success( [ + 'done' => ! $has_more, + 'phase' => 'records', + 'post_type' => $post_type, + 'imported' => $batch_result['imported'], + 'offset' => $offset, + 'total' => $total, + 'has_more' => $has_more, + 'next_offset' => $offset + count( $slice ), + ] ); + } + + wp_send_json_error( [ 'message' => __( 'Invalid step.', 'disciple-tools-migration' ) ] ); + } +} diff --git a/admin/class-dt-migration-tab-export.php b/admin/class-dt-migration-tab-export.php new file mode 100644 index 0000000..c9ebb4d --- /dev/null +++ b/admin/class-dt-migration-tab-export.php @@ -0,0 +1,341 @@ + +
+
+
+
+ main_column( $settings ); ?> +
+
+ right_column( $settings ); ?> +
+
+
+
+
+
+ + + + + + + + + + + + + +
+ +

+ +

+ + +

+ +

+ get_api_export_preview( $allowed ); + $records_preview = $this->get_api_records_preview( $allowed ); + $post_type_count = is_array( $records_preview ) ? count( $records_preview ) : 0; + ?> + +

+

+ +

+ + + + + + + + + + [ 'label' => __( 'General Settings', 'disciple-tools-migration' ), 'notes' => '' ], + 'custom_lists' => [ 'label' => __( 'Custom Lists', 'disciple-tools-migration' ), 'notes' => '' ], + 'tiles' => [ 'label' => __( 'Tiles', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['tiles'] ) ? sprintf( esc_html__( 'Tiles defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'fields' => [ 'label' => __( 'Fields', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['fields'] ) ? sprintf( esc_html__( 'Fields defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'roles' => [ 'label' => __( 'Roles', 'disciple-tools-migration' ), 'notes' => '' ], + 'workflows' => [ 'label' => __( 'Workflows', 'disciple-tools-migration' ), 'notes' => '' ], + ]; + foreach ( $settings_rows as $key => $row ) : + $is_enabled = ! empty( $allowed[ $key ] ); + ?> + + + + + + + +
+ + + + + + + + + + + + $data ) : + $summary = $settings_preview[ $post_type ] ?? [ 'tiles' => 0, 'fields' => 0 ]; + $count = isset( $data['count'] ) ? (int) $data['count'] : 0; + ?> + + + + + + + + +
+ +

+ +

+ + +

+ +

+ + +

+ +

+

+ +

+ +
+ + + + + + + + + + + + + + + + $stat ) : ?> + + + + + + + + + + + +
+ + + + + + + +
+

+ +

+
+ + +

+ +

+ + + +
+
+ + + */ + private function get_api_export_preview( array $allowed ) : array { + $preview = []; + if ( ! class_exists( 'DT_Posts' ) || ( empty( $allowed['tiles'] ) && empty( $allowed['fields'] ) && empty( $allowed['records'] ) ) ) { + return $preview; + } + $post_types = DT_Posts::get_post_types(); + $tiles_all = []; + $fields_all = []; + if ( ! empty( $allowed['tiles'] ) ) { + foreach ( $post_types as $pt ) { + $tiles_all[ $pt ] = DT_Posts::get_post_tiles( $pt, false ); + } + } + if ( ! empty( $allowed['fields'] ) ) { + foreach ( $post_types as $pt ) { + $fields_all[ $pt ] = DT_Posts::get_post_field_settings( $pt, false, true ); + } + } + $allowed_records = $allowed['records'] ?? []; + foreach ( $allowed_records as $post_type => $enabled ) { + if ( ! $enabled ) { + continue; + } + $preview[ $post_type ] = [ + 'tiles' => isset( $tiles_all[ $post_type ] ) ? count( (array) $tiles_all[ $post_type ] ) : 0, + 'fields' => isset( $fields_all[ $post_type ] ) ? count( (array) $fields_all[ $post_type ] ) : 0, + ]; + } + return $preview; + } + + /** + * Builds records preview (count per post type) for API export. + * + * @param array $allowed Allowed items from migration settings. + * @return array + */ + private function get_api_records_preview( array $allowed ) : array { + if ( ! class_exists( 'Disciple_Tools_Migration_Export_File' ) ) { + return []; + } + $stats = Disciple_Tools_Migration_Export_File::get_record_stats(); + $allowed = $allowed['records'] ?? []; + $result = []; + foreach ( $allowed as $post_type => $enabled ) { + if ( $enabled && isset( $stats[ $post_type ] ) ) { + $result[ $post_type ] = [ 'count' => (int) $stats[ $post_type ]['count'] ]; + } + } + return $result; + } + + /** + * Renders the Export information column. + * + * @param array $settings + */ + public function right_column( array $settings ) { + $site_url = get_site_url(); + $wp_theme = wp_get_theme(); + $dt_version = $wp_theme->version; + ?> + + + + + + + + + + + + +
+

+ +

+

+ +

+

+ +

+
+
+ + process_form_fields( $settings ); + $settings = Disciple_Tools_Migration_Menu::get_settings(); + + ?> +
+
+
+
+ main_column( $settings ); ?> +
+
+ right_column( $settings ); ?> +
+
+
+
+
+
+ + + + + + + + + + + + + +
+ +

+ +

+ + +

+ +

+

+ +

+

+ +

+
+

+

+ +

+
+ + + + + + + + + + + + + + + + + + + + +
+ + + +

+ +

+
+ + + +

+ +

+
+ + + +

+ +

+
+ +
+
+ connection_error ) ) : ?> +
+

connection_error ); ?>

+
+ connection_result ) ) : ?> +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
connection_result['site_meta']['site_url'] ?? '' ); ?>
connection_result['site_meta']['dt_version'] ?? '' ); ?>
connection_result['enabled'] ) ? esc_html__( 'Yes', 'disciple-tools-migration' ) : esc_html__( 'No', 'disciple-tools-migration' ); ?>
connection_result['mode'] ?? '' ); ?>
+ connection_result['allowed_items'] ?? []; + $labels = []; + if ( ! empty( $allowed['general_settings'] ) ) { + $labels[] = esc_html__( 'General Settings', 'disciple-tools-migration' ); + } + if ( ! empty( $allowed['custom_lists'] ) ) { + $labels[] = esc_html__( 'Custom Lists', 'disciple-tools-migration' ); + } + if ( ! empty( $allowed['tiles'] ) ) { + $labels[] = esc_html__( 'Tiles', 'disciple-tools-migration' ); + } + if ( ! empty( $allowed['fields'] ) ) { + $labels[] = esc_html__( 'Fields', 'disciple-tools-migration' ); + } + if ( ! empty( $allowed['roles'] ) ) { + $labels[] = esc_html__( 'Roles', 'disciple-tools-migration' ); + } + if ( ! empty( $allowed['workflows'] ) ) { + $labels[] = esc_html__( 'Workflows', 'disciple-tools-migration' ); + } + echo esc_html( implode( ', ', $labels ) ); + ?> +
+ connection_result['allowed_items']['records'] ?? []; + $recordLabels = []; + if ( ! empty( $records['contacts'] ) ) { + $recordLabels[] = esc_html__( 'Contacts', 'disciple-tools-migration' ); + } + if ( ! empty( $records['groups'] ) ) { + $recordLabels[] = esc_html__( 'Groups', 'disciple-tools-migration' ); + } + echo esc_html( implode( ', ', $recordLabels ) ); + ?> +
+ + +
+ + +
+ + settings_preview ) ) : ?> +

+ + export_allowed_items ?? $this->connection_result['allowed_items'] ?? []; + $dt_settings = $this->settings_preview; + $records_preview = $this->records_preview ?? []; + $post_type_count = is_array( $records_preview ) ? count( $records_preview ) : ( is_array( $dt_settings ) ? count( $dt_settings ) : 0 ); + ?> + + + + + + + + + + + + + [ 'label' => __( 'General Settings', 'disciple-tools-migration' ), 'notes' => '' ], + 'custom_lists' => [ 'label' => __( 'Custom Lists', 'disciple-tools-migration' ), 'notes' => '' ], + 'tiles' => [ 'label' => __( 'Tiles', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['tiles'] ) ? sprintf( esc_html__( 'Tiles defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'fields' => [ 'label' => __( 'Fields', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['fields'] ) ? sprintf( esc_html__( 'Fields defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'roles' => [ 'label' => __( 'Roles', 'disciple-tools-migration' ), 'notes' => '' ], + 'workflows' => [ 'label' => __( 'Workflows', 'disciple-tools-migration' ), 'notes' => '' ], + ]; + foreach ( $settings_rows as $key => $row ) : + $is_enabled = ! empty( $allowed[ $key ] ); + ?> + + + + + + + + +
+ +
+ + data-setting-type=""> +
+ + + + + + + + + + + + + + records_preview ?? []; + $dt_preview = $this->settings_preview ?? []; + foreach ( $records_counts as $post_type => $record_data ) { + $summary = $dt_preview[ $post_type ] ?? [ 'tiles' => 0, 'fields' => 0 ]; + $record_count = isset( $record_data['count'] ) ? (int) $record_data['count'] : 0; + ?> + + + + + + + + + +
+ +
+ +
+ +

+ +

+ render_import_modal_and_progress(); + ?> + + +

+ +

+

+ +

+ connection_error ) ) : ?> +
+

connection_error ); ?>

+
+ +
+ + + + + + + + + + + + +
+ +

+ +

+
+ +
+
+ settings_preview ) ) : ?> +

+ export_allowed_items ?? []; + $dt_settings = $this->settings_preview; + $records_preview = $this->records_preview ?? []; + $post_type_count = is_array( $records_preview ) ? count( $records_preview ) : 0; + ?> + + + + + + + + + + + [ 'label' => __( 'General Settings', 'disciple-tools-migration' ), 'notes' => '' ], + 'custom_lists' => [ 'label' => __( 'Custom Lists', 'disciple-tools-migration' ), 'notes' => '' ], + 'tiles' => [ 'label' => __( 'Tiles', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['tiles'] ) ? sprintf( esc_html__( 'Tiles defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'fields' => [ 'label' => __( 'Fields', 'disciple-tools-migration' ), 'notes' => ! empty( $allowed['fields'] ) ? sprintf( esc_html__( 'Fields defined for %d post types.', 'disciple-tools-migration' ), $post_type_count ) : '' ], + 'roles' => [ 'label' => __( 'Roles', 'disciple-tools-migration' ), 'notes' => '' ], + 'workflows' => [ 'label' => __( 'Workflows', 'disciple-tools-migration' ), 'notes' => '' ], + ]; + foreach ( $settings_rows as $key => $row ) : + $is_enabled = ! empty( $allowed[ $key ] ); + ?> + + + + + + + + +
+ data-setting-type=""> +
+ + + + + + + + + + + + records_preview ?? []; + $dt_preview = $this->settings_preview ?? []; + foreach ( $records_counts as $post_type => $record_data ) { + $summary = $dt_preview[ $post_type ] ?? [ 'tiles' => 0, 'fields' => 0 ]; + $record_count = isset( $record_data['count'] ) ? (int) $record_data['count'] : 0; + ?> + + + + + + + + + +
+ +
+

+ +

+ render_import_modal_and_progress(); ?> + + + +
+
+ + + + + + + + + + + + + + +
+

+ +

+

+ +

+
+
+ + settings_preview ) ) { + return; + } + $nonce = wp_create_nonce( 'dt_migration_import' ); + ?> + + + + process_file_upload( $settings ); + return; + } + + if ( $settings['mode'] !== 'api' ) { + return; + } + + if ( ! isset( $_POST['dt_migration_import_connection_form_nonce'] ) ) { + return; + } + + if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['dt_migration_import_connection_form_nonce'] ) ), 'dt_migration_import_connection_form' ) ) { + return; + } + + $post_vars = dt_recursive_sanitize_array( $_POST ); + + $remote_base_url = isset( $post_vars['dt_migration_api_remote_base_url'] ) ? trim( (string) $post_vars['dt_migration_api_remote_base_url'] ) : ''; + $username = isset( $post_vars['dt_migration_api_username'] ) ? (string) $post_vars['dt_migration_api_username'] : ''; + $password = isset( $post_vars['dt_migration_api_password'] ) ? (string) $post_vars['dt_migration_api_password'] : ''; + + $action = isset( $post_vars['dt_migration_action'] ) ? (string) $post_vars['dt_migration_action'] : 'test_connection'; + + // If user clicked "Fetch Settings Export Preview", use stored URL + JWT. + if ( $action === 'settings_preview' ) { + $remote_base_url = $settings['api']['remote_base_url'] ?? ''; + $jwt_token = $settings['api']['jwt_token'] ?? ''; + $token_set_at = (int) ( $settings['api']['jwt_token_set_at'] ?? 0 ); + + if ( empty( $remote_base_url ) || empty( $jwt_token ) ) { + $this->connection_error = esc_html__( 'JWT token not available. Please run "Test Connection & Fetch Capabilities" first.', 'disciple-tools-migration' ); + return; + } + + if ( $token_set_at < ( time() - HOUR_IN_SECONDS ) ) { + $this->connection_error = esc_html__( 'JWT token appears to be expired. Please re-run "Test Connection & Fetch Capabilities".', 'disciple-tools-migration' ); + return; + } + + $base = rtrim( $remote_base_url, '/' ); + $export_url = $base . '/wp-json/dt-migration/v1/export'; + $export_res = wp_remote_post( + $export_url, + [ + 'timeout' => 30, + 'headers' => [ + 'Authorization' => 'Bearer ' . $jwt_token, + 'Content-Type' => 'application/json', + ], + 'body' => wp_json_encode( [ 'settings_only' => true ] ), + ] + ); + + if ( is_wp_error( $export_res ) ) { + $this->connection_error = sprintf( + esc_html__( 'Unable to fetch settings export from Server A: %s', 'disciple-tools-migration' ), + $export_res->get_error_message() + ); + return; + } + + $export_code = wp_remote_retrieve_response_code( $export_res ); + $export_body = json_decode( (string) wp_remote_retrieve_body( $export_res ), true ); + + if ( $export_code < 200 || $export_code >= 300 || ! is_array( $export_body ) ) { + $this->connection_error = esc_html__( 'Unexpected response when fetching settings export from Server A.', 'disciple-tools-migration' ); + return; + } + + $dt_settings = $export_body['export']['dt_settings'] ?? []; + $post_types = $dt_settings['dt_post_types_settings']['values'] ?? []; + $tiles_all = $dt_settings['dt_tiles_settings']['values'] ?? []; + $fields_all = $dt_settings['dt_fields_settings']['values'] ?? []; + + // Store allowed_items from export response for use in preview tables. + $this->export_allowed_items = $export_body['settings']['allowed_items'] ?? []; + + $preview = []; + foreach ( $post_types as $post_type => $config ) { + $preview[ $post_type ] = [ + 'tiles' => isset( $tiles_all[ $post_type ] ) ? count( (array) $tiles_all[ $post_type ] ) : 0, + 'fields' => isset( $fields_all[ $post_type ] ) ? count( (array) $fields_all[ $post_type ] ) : 0, + ]; + } + + $this->settings_preview = $preview; + + // Also fetch non-destructive record counts (only returns allowed record types). + $preview_records = []; + + $records_url = $base . '/wp-json/dt-migration/v1/records-preview'; + $records_res = wp_remote_get( + $records_url, + [ + 'timeout' => 20, + 'headers' => [ + 'Authorization' => 'Bearer ' . $jwt_token, + ], + ] + ); + + if ( ! is_wp_error( $records_res ) ) { + $records_code = wp_remote_retrieve_response_code( $records_res ); + $records_body = json_decode( (string) wp_remote_retrieve_body( $records_res ), true ); + if ( $records_code >= 200 && $records_code < 300 && is_array( $records_body ) ) { + $preview_records = $records_body['records'] ?? []; + } + } + + $this->records_preview = $preview_records; + + return; + } + + if ( empty( $remote_base_url ) || empty( $username ) || empty( $password ) ) { + $this->connection_error = esc_html__( 'Please provide the Server A base URL, username and password.', 'disciple-tools-migration' ); + return; + } + + // Persist the remote base URL in settings for convenience. + $settings['api']['remote_base_url'] = $remote_base_url; + Disciple_Tools_Migration_Menu::update_settings( $settings ); + + $base = rtrim( $remote_base_url, '/' ); + + // Step 1: obtain JWT token from Server A. + $token_url = $base . '/wp-json/jwt-auth/v1/token'; + $response = wp_remote_post( + $token_url, + [ + 'timeout' => 15, + 'body' => [ + 'username' => $username, + 'password' => $password, + ], + ] + ); + + if ( is_wp_error( $response ) ) { + $this->connection_error = sprintf( + /* translators: %s: WP error message */ + esc_html__( 'Unable to contact Server A token endpoint: %s', 'disciple-tools-migration' ), + $response->get_error_message() + ); + return; + } + + $code = wp_remote_retrieve_response_code( $response ); + $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); + + if ( $code < 200 || $code >= 300 || empty( $body['token'] ) ) { + $this->connection_error = esc_html__( 'Server A did not return a valid JWT token. Please check credentials and URL.', 'disciple-tools-migration' ); + return; + } + + $token = (string) $body['token']; + + // Persist connection details and JWT for later preview use. + $settings['api']['remote_base_url'] = $remote_base_url; + $settings['api']['jwt_token'] = $token; + $settings['api']['jwt_token_set_at'] = time(); + Disciple_Tools_Migration_Menu::update_settings( $settings ); + + // Optional: validate the token. + $validate_url = $base . '/wp-json/jwt-auth/v1/token/validate'; + $validate = wp_remote_post( + $validate_url, + [ + 'timeout' => 15, + 'headers' => [ + 'Authorization' => 'Bearer ' . $token, + ], + ] + ); + + if ( is_wp_error( $validate ) ) { + $this->connection_error = sprintf( + /* translators: %s: WP error message */ + esc_html__( 'Unable to validate JWT token on Server A: %s', 'disciple-tools-migration' ), + $validate->get_error_message() + ); + return; + } + + // Always clear previous preview when re-submitting the form. + $this->settings_preview = null; + + // Default action: fetch capabilities only. + $capabilities_url = $base . '/wp-json/dt-migration/v1/capabilities'; + $caps_response = wp_remote_get( + $capabilities_url, + [ + 'timeout' => 20, + 'headers' => [ + 'Authorization' => 'Bearer ' . $token, + ], + ] + ); + + if ( is_wp_error( $caps_response ) ) { + $this->connection_error = sprintf( + /* translators: %s: WP error message */ + esc_html__( 'Unable to fetch migration capabilities from Server A: %s', 'disciple-tools-migration' ), + $caps_response->get_error_message() + ); + return; + } + + $caps_code = wp_remote_retrieve_response_code( $caps_response ); + $caps_body = json_decode( (string) wp_remote_retrieve_body( $caps_response ), true ); + + if ( $caps_code < 200 || $caps_code >= 300 || ! is_array( $caps_body ) ) { + $this->connection_error = esc_html__( 'Unexpected response when fetching migration capabilities from Server A.', 'disciple-tools-migration' ); + return; + } + + $this->connection_result = $caps_body; + } + + /** + * Processes file upload for file mode import. + * + * @param array $settings + */ + private function process_file_upload( array $settings ) : void { + if ( ! isset( $_POST['dt_migration_file_upload_nonce'] ) ) { + return; + } + + if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['dt_migration_file_upload_nonce'] ) ), 'dt_migration_file_upload' ) ) { + $this->connection_error = esc_html__( 'Security check failed.', 'disciple-tools-migration' ); + return; + } + + if ( empty( $_FILES['dt_migration_import_file']['tmp_name'] ) ) { + $this->connection_error = esc_html__( 'Please select a JSON file to upload.', 'disciple-tools-migration' ); + return; + } + + $content = file_get_contents( sanitize_text_field( wp_unslash( $_FILES['dt_migration_import_file']['tmp_name'] ) ) ); + if ( $content === false ) { + $this->connection_error = esc_html__( 'Could not read the uploaded file.', 'disciple-tools-migration' ); + return; + } + + $payload = json_decode( $content, true ); + if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $payload ) ) { + $this->connection_error = esc_html__( 'Invalid JSON file.', 'disciple-tools-migration' ); + return; + } + + if ( empty( $payload['export']['dt_settings'] ) ) { + $this->connection_error = esc_html__( 'The file does not contain a valid migration export.', 'disciple-tools-migration' ); + return; + } + + $transient_key = 'dt_migration_file_payload_' . get_current_user_id(); + set_transient( $transient_key, $payload, 15 * MINUTE_IN_SECONDS ); + + $dt_settings = $payload['export']['dt_settings'] ?? []; + $post_types = $dt_settings['dt_post_types_settings']['values'] ?? []; + $tiles_all = $dt_settings['dt_tiles_settings']['values'] ?? []; + $fields_all = $dt_settings['dt_fields_settings']['values'] ?? []; + $this->export_allowed_items = $payload['settings']['allowed_items'] ?? []; + + $preview = []; + foreach ( $post_types as $post_type => $config ) { + $preview[ $post_type ] = [ + 'tiles' => isset( $tiles_all[ $post_type ] ) ? count( (array) $tiles_all[ $post_type ] ) : 0, + 'fields' => isset( $fields_all[ $post_type ] ) ? count( (array) $fields_all[ $post_type ] ) : 0, + ]; + } + $this->settings_preview = $preview; + + $records_raw = $payload['records'] ?? []; + $this->records_preview = []; + foreach ( $records_raw as $post_type => $recs ) { + $this->records_preview[ $post_type ] = [ 'count' => is_array( $recs ) ? count( $recs ) : 0 ]; + } + } +} \ No newline at end of file diff --git a/admin/class-dt-migration-tab-settings.php b/admin/class-dt-migration-tab-settings.php new file mode 100644 index 0000000..e3ca2a3 --- /dev/null +++ b/admin/class-dt-migration-tab-settings.php @@ -0,0 +1,239 @@ +process_form_fields(); + $settings = Disciple_Tools_Migration_Menu::get_settings(); + + ?> +
+
+
+
+ main_column( $settings ); ?> +
+
+ right_column( $settings ); ?> +
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Settings
+ + + +

+ +

+
+ + +
+ +
+ +

+ +

+
+
+ + +
+ +
+ +
+ +
+ +
+ +
+ +

+ +

+
+
+ + +
+ +
+ +

+ +

+
+
+ +
+
+
+ true, + 'groups' => true, + ]; + } + + $settings['allowed_items']['records']['contacts'] = ! empty( $allowed['records']['contacts'] ); + $settings['allowed_items']['records']['groups'] = ! empty( $allowed['records']['groups'] ); + + Disciple_Tools_Migration_Menu::update_settings( $settings ); + } + + /** + * Renders the right-hand information column. + * + * @param array $settings + */ + public function right_column( array $settings ) { + ?> + + + + + + + + + + + + +
Information
+

+ +

+

+ +

+

+ +

+
+
+ + 'REST API Console', // The plugin name. +// 'slug' => 'rest-api-console', // The plugin slug (typically the folder name). +// 'source' => dirname( __FILE__ ) . '/lib/plugins/rest-api-console.zip', // The plugin source. +// 'required' => true, // If false, the plugin is only 'recommended' instead of required. +// 'version' => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher. If the plugin version is higher than the plugin version installed, the user will be notified to update the plugin. +// 'force_activation' => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch. +// 'force_deactivation' => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins. +// 'external_url' => '', // If set, overrides default API URL and points to an external URL. +// 'is_callable' => '', // If set, this callable will be be checked for availability to determine if a plugin is active. +// ), +// + */ + +add_action( 'tgmpa_register', function() { + /* + * Array of plugin arrays. Required keys are name and slug. + * If the source is NOT from the .org repo, then source is also required. + */ + $plugins = []; + // a wordpress plugin: + // $plugins[] = [ + // 'name' => 'iThemes Security', + // 'slug' => 'better-wp-security', + // 'required' => false, + // 'version' => '7.2.0', + // ]; + + // a D.T plugin + // $plugins[] = [ + // 'name' => 'Disciple.Tools Dashboard', + // 'slug' => 'disciple-tools-dashboard', + // 'source' => 'https://github.com/DiscipleTools/disciple-tools-dashboard/releases/latest/download/disciple-tools-dashboard.zip', + // 'required' => false + // ]; + + /* + * Array of configuration settings. Amend each line as needed. + * + * Only uncomment the strings in the config array if you want to customize the strings. + */ + $config = array( + 'id' => 'disciple_tools', // Unique ID for hashing notices for multiple instances of TGMPA. + 'default_path' => '/includes/plugins/', // Default absolute path to bundled plugins. + 'menu' => 'tgmpa-install-plugins', // Menu slug. + 'parent_slug' => 'plugins.php', // Parent menu slug. + 'capability' => 'manage_options', // Capability needed to view plugin install page, should be a capability associated with the parent menu used. + 'has_notices' => true, // Show admin notices or not. + 'dismissable' => true, // If false, a user cannot dismiss the nag message. + 'dismiss_msg' => 'These are recommended plugins to complement your Disciple.Tools system.', // If 'dismissable' is false, this message will be output at top of nag. + 'is_automatic' => true, // Automatically activate plugins after installation or not. + 'message' => '', // Message to output right before the plugins table. + ); + + tgmpa( $plugins, $config ); +} ); diff --git a/admin/js/import.js b/admin/js/import.js new file mode 100644 index 0000000..f20fa35 --- /dev/null +++ b/admin/js/import.js @@ -0,0 +1,331 @@ +/** + * Disciple.Tools Migration - Import flow (AJAX, progress, confirmation) + */ +( function( $ ) { + 'use strict'; + + let $modal, $progress, $confirmInput, $confirmBtn, $cancelBtn, $summary; + let $progressBar, $progressText, $stepList, $currentPhase, $cancelImport; + let $errorDetails, $errorScroll; + + let cancelled = false; + let phases = []; + let currentPhaseIndex = 0; + let totalSteps = 0; + let completedSteps = 0; + + const CONFIRM_WORD = 'IMPORT'; + + function getSelectedSettings() { + const out = []; + $( '.dt-migration-setting-checkbox:checked:not(:disabled)' ).each( function() { + out.push( $( this ).val() ); + } ); + return out; + } + + function getSelectedRecords() { + const out = {}; + $( '.dt-migration-record-checkbox:checked' ).each( function() { + const pt = $( this ).data( 'post-type' ); + const count = $( this ).data( 'record-count' ) || 0; + out[ pt ] = { count }; + } ); + return out; + } + + function buildSummary( settings, records ) { + const parts = []; + if ( settings.length ) { + const labels = { + general_settings: 'General Settings', + custom_lists: 'Custom Lists', + tiles: 'Tiles', + fields: 'Fields', + roles: 'Roles', + workflows: 'Workflows' + }; + const names = settings.map( s => labels[ s ] || s ); + parts.push( 'Settings: ' + names.join( ', ' ) ); + } + if ( Object.keys( records ).length ) { + const recParts = Object.keys( records ).map( pt => pt + ' (' + ( records[ pt ].count || 0 ) + ' records)' ); + parts.push( 'Records: ' + recParts.join( ', ' ) ); + } + return parts.join( '. ' ); + } + + function buildPhases() { + const settings = getSelectedSettings(); + const records = getSelectedRecords(); + const phases = []; + + if ( settings.length ) { + phases.push( { + type: 'settings', + label: 'Import settings (' + settings.join( ', ' ) + ')', + settings: settings, + records: null + } ); + } + const order = [ 'peoplegroups', 'contacts', 'groups', 'trainings' ]; + const rest = Object.keys( records ).filter( pt => ! order.includes( pt ) ); + const ordered = order.filter( pt => records[ pt ] ).concat( rest ); + ordered.forEach( pt => { + if ( records[ pt ] ) { + phases.push( { + type: 'records', + post_type: pt, + label: 'Import ' + pt + ' (' + ( records[ pt ].count || 0 ) + ' records)', + records: records + } ); + } + } ); + return phases; + } + + function getPhaseConfirmMessage( phase ) { + if ( phase.type === 'settings' ) { + return 'This will overwrite the selected settings on this site.'; + } + return 'This will delete existing ' + phase.post_type + ' and replace them with records from Server A. Record IDs will be preserved for relationships.'; + } + + function setProgress( percent ) { + const n = ( typeof percent === 'number' && ! isNaN( percent ) ) ? Math.round( percent ) : 0; + $progressBar.css( 'width', n + '%' ); + $progressText.text( n + '%' ); + } + + function addStep( label, status ) { + const cls = status === 'done' ? 'done' : ( status === 'active' ? 'active' : '' ); + $stepList.append( '
  • ' + label + '
  • ' ); + } + + function markStepDone( index ) { + $stepList.find( 'li' ).eq( index ).addClass( 'done' ).removeClass( 'active' ); + } + + function markStepActive( index ) { + $stepList.find( 'li' ).removeClass( 'active' ); + $stepList.find( 'li' ).eq( index ).addClass( 'active' ); + } + + function showModal( phase ) { + $summary.text( getPhaseConfirmMessage( phase ) ); + $confirmInput.val( '' ).prop( 'disabled', false ); + $confirmBtn.prop( 'disabled', true ); + cancelled = false; + $modal.show(); + } + + function hideModal() { + $modal.hide(); + } + + function showProgress() { + $progress.show(); + $errorDetails.hide(); + $errorScroll.text( '' ); + phases.forEach( ( p, i ) => addStep( p.label, i === 0 ? 'active' : '' ) ); + } + + function showError( message ) { + $errorScroll.text( message || '' ); + $errorDetails.toggle( !! message ); + } + + function runPhase( phase ) { + return new Promise( ( resolve, reject ) => { + if ( cancelled ) { + resolve( { cancelled: true } ); + return; + } + $currentPhase.text( phase.label + '...' ); + + if ( phase.type === 'settings' ) { + $.post( dtMigrationImport.ajaxUrl, { + action: 'dt_migration_import_batch', + nonce: dtMigrationImport.nonce, + step: 'settings', + settings_selected: phase.settings + } ).done( function( r ) { + if ( r.success ) { + resolve( r.data ); + } else { + reject( r.data && r.data.message ? r.data.message : 'Settings import failed' ); + } + } ).fail( function( xhr ) { + reject( xhr.statusText || 'Request failed' ); + } ); + return; + } + + if ( phase.type === 'records' ) { + let offset = 0; + let totalImported = 0; + const totalExpected = phase.records[ phase.post_type ] ? phase.records[ phase.post_type ].count : 0; + + function fetchBatch() { + if ( cancelled ) { + resolve( { cancelled: true } ); + return; + } + $.post( dtMigrationImport.ajaxUrl, { + action: 'dt_migration_import_batch', + nonce: dtMigrationImport.nonce, + step: 'records', + post_type: phase.post_type, + offset: offset + } ).done( function( r ) { + if ( r.success ) { + const d = r.data; + totalImported += d.imported || 0; + const pct = totalExpected ? ( totalImported / totalExpected ) * 100 : 100; + const phasePct = totalSteps ? ( currentPhaseIndex / totalSteps ) * 100 + ( pct / totalSteps ) : 0; + setProgress( Math.min( 100, phasePct ) ); + + if ( d.has_more ) { + offset = d.next_offset || ( offset + 50 ); + fetchBatch(); + } else { + resolve( { imported: totalImported } ); + } + } else { + reject( r.data && r.data.message ? r.data.message : 'Records import failed' ); + } + } ).fail( function( xhr ) { + reject( xhr.statusText || 'Request failed' ); + } ); + } + fetchBatch(); + } + } ); + } + + + function startNextPhase() { + if ( currentPhaseIndex >= phases.length ) { + setProgress( 100 ); + $currentPhase.text( 'Import complete.' ); + $cancelImport.hide(); + return; + } + const phase = phases[ currentPhaseIndex ]; + showModal( phase ); + $confirmInput.val( '' ); + $confirmBtn.prop( 'disabled', true ); + } + + function runCurrentPhase() { + if ( currentPhaseIndex >= phases.length ) { + return; + } + const phase = phases[ currentPhaseIndex ]; + hideModal(); + if ( ! $progress.is( ':visible' ) ) { + showProgress(); + setProgress( 0 ); + $cancelImport.show(); + } + markStepActive( currentPhaseIndex ); + runPhase( phase ).then( function( result ) { + if ( result && result.cancelled ) { + $currentPhase.text( 'Import cancelled.' ); + $cancelImport.hide(); + return; + } + markStepDone( currentPhaseIndex ); + completedSteps++; + currentPhaseIndex++; + startNextPhase(); + } ).catch( function( err ) { + $currentPhase.text( 'Import failed.' ); + showError( err ); + $cancelImport.hide(); + } ); + } + + function onConfirmClick() { + const val = $confirmInput.val().trim().toUpperCase(); + if ( val === CONFIRM_WORD ) { + runCurrentPhase(); + } + } + + function init() { + $modal = $( '#dt-migration-import-modal' ); + $progress = $( '#dt-migration-progress-panel' ); + $confirmInput = $( '#dt-migration-confirm-input' ); + $confirmBtn = $( '.dt-migration-modal-confirm' ); + $cancelBtn = $( '.dt-migration-modal-cancel' ); + $summary = $( '.dt-migration-modal-summary' ); + $progressBar = $( '.dt-migration-progress-fill' ); + $progressText = $( '.dt-migration-progress-text' ); + $stepList = $( '.dt-migration-step-list' ); + $currentPhase = $( '.dt-migration-current-phase' ); + $cancelImport = $( '.dt-migration-cancel-import' ); + $errorDetails = $( '#dt-migration-error-details' ); + $errorScroll = $( '.dt-migration-error-scroll' ); + + if ( ! $modal.length || ! $( '.dt-migration-start-import' ).length ) { + return; + } + + $confirmInput.on( 'input', function() { + const val = $( this ).val().trim().toUpperCase(); + $confirmBtn.prop( 'disabled', val !== CONFIRM_WORD ); + } ); + + $confirmInput.on( 'keydown', function( e ) { + if ( e.key === 'Enter' ) { + onConfirmClick(); + } + } ); + + $confirmBtn.on( 'click', onConfirmClick ); + + $cancelBtn.on( 'click', function() { + hideModal(); + } ); + + $( '.dt-migration-modal-overlay' ).on( 'click', function() { + hideModal(); + } ); + + $cancelImport.on( 'click', function() { + cancelled = true; + $( this ).prop( 'disabled', true ).text( 'Cancelling...' ); + } ); + + $( '.dt-migration-start-import' ).on( 'click', function() { + const settings = getSelectedSettings(); + const records = getSelectedRecords(); + if ( ! settings.length && ! Object.keys( records ).length ) { + alert( 'Please select at least one setting type or record type to import.' ); + return; + } + phases = buildPhases(); + if ( ! phases.length ) { + return; + } + totalSteps = phases.length; + currentPhaseIndex = 0; + $summary.text( buildSummary( settings, records ) ); + showModal( phases[ 0 ] ); + } ); + + $( '.dt-migration-select-all-settings' ).on( 'change', function() { + const checked = $( this ).prop( 'checked' ); + $( '.dt-migration-setting-checkbox:not(:disabled)' ).prop( 'checked', checked ); + } ); + + $( '.dt-migration-select-all-records' ).on( 'change', function() { + const checked = $( this ).prop( 'checked' ); + $( '.dt-migration-record-checkbox' ).prop( 'checked', checked ); + } ); + } + + $( document ).ready( init ); + +} )( jQuery ); diff --git a/charts/charts-base.js b/charts/charts-base.js new file mode 100644 index 0000000..9ebd375 --- /dev/null +++ b/charts/charts-base.js @@ -0,0 +1,9 @@ +(function() { + "use strict"; + + jQuery(document).ready(function() { + jQuery('#metrics-sidemenu').foundation('down', jQuery(`#${window.wpApiBase.slug}`)); + + }) +})(); + diff --git a/charts/charts-loader.php b/charts/charts-loader.php new file mode 100644 index 0000000..f0f9962 --- /dev/null +++ b/charts/charts-loader.php @@ -0,0 +1,24 @@ +${localizedObject.translations.title} + +
    + +
    + +
    + + +
    + `) + + // Create chart instance + var chart = am4core.create("chartdiv", am4charts.PieChart); + + // Add data + chart.data = [{ + "country": "Lithuania", + "litres": 501.9 + }, { + "country": "Czech Republic", + "litres": 301.9 + }, { + "country": "Ireland", + "litres": 201.1 + }, { + "country": "Germany", + "litres": 165.8 + }, { + "country": "Australia", + "litres": 139.9 + }, { + "country": "Austria", + "litres": 128.3 + }, { + "country": "UK", + "litres": 99 + }, { + "country": "Belgium", + "litres": 60 + }, { + "country": "The Netherlands", + "litres": 50 + }]; + + // Add and configure Series + var pieSeries = chart.series.push(new am4charts.PieSeries()); + pieSeries.dataFields.value = "litres"; + pieSeries.dataFields.category = "country"; + } + + window.sample_api_call = function sample_api_call( button_data ) { + + + let localizedObject = window.wp_js_object // change this object to the one named in ui-menu-and-enqueue.php + + let button = jQuery('#sample_button') + + $('#sample_spinner').addClass("active") + + let data = { "button_data": button_data }; + return jQuery.ajax({ + type: "POST", + data: JSON.stringify(data), + contentType: "application/json; charset=utf-8", + dataType: "json", + url: `${localizedObject.rest_endpoints_base}/sample`, + beforeSend: function(xhr) { + xhr.setRequestHeader('X-WP-Nonce', localizedObject.nonce); + }, + }) + .done(function (data) { + $('#sample_spinner').removeClass("active") + button.empty().append(data) + console.log( 'success' ) + console.log( data ) + }) + .fail(function (err) { + $('#sample_spinner').removeClass("active") + button.empty().append("error. Something went wrong") + console.log("error"); + console.log(err); + }) + } +})(); diff --git a/charts/one-page-chart-template.php b/charts/one-page-chart-template.php new file mode 100644 index 0000000..0f181ed --- /dev/null +++ b/charts/one-page-chart-template.php @@ -0,0 +1,97 @@ +has_permission() ){ + return; + } + $url_path = dt_get_url_path(); + + // only load scripts if exact url + if ( "metrics/$this->base_slug/$this->slug" === $url_path ) { + + add_action( 'wp_enqueue_scripts', [ $this, 'scripts' ], 99 ); + } + } + + + /** + * Load scripts for the plugin + */ + public function scripts() { + + wp_register_script( 'amcharts-core', 'https://www.amcharts.com/lib/4/core.js', false, '4' ); + wp_register_script( 'amcharts-charts', 'https://www.amcharts.com/lib/4/charts.js', false, '4' ); + + wp_enqueue_script( 'dt_'.$this->slug.'_script', trailingslashit( plugin_dir_url( __FILE__ ) ) . $this->js_file_name, [ + 'jquery', + 'amcharts-core', + 'amcharts-charts' + ], filemtime( plugin_dir_path( __FILE__ ) .$this->js_file_name ), true ); + + // Localize script with array data + wp_localize_script( + 'dt_'.$this->slug.'_script', $this->js_object_name, [ + 'rest_endpoints_base' => esc_url_raw( rest_url() ) . "$this->base_slug/$this->slug", + 'base_slug' => $this->base_slug, + 'slug' => $this->slug, + 'root' => esc_url_raw( rest_url() ), + 'plugin_uri' => plugin_dir_url( __DIR__ ), + 'nonce' => wp_create_nonce( 'wp_rest' ), + 'current_user_login' => wp_get_current_user()->user_login, + 'current_user_id' => get_current_user_id(), + 'stats' => [ + // add preload stats data into arrays here + ], + 'translations' => [ + 'title' => $this->title, + 'Sample API Call' => __( 'Sample API Call', 'disciple-tools-migration' ) + ] + ] + ); + } + + public function add_api_routes() { + $namespace = "$this->base_slug/$this->slug"; + register_rest_route( + $namespace, '/sample', [ + 'methods' => 'POST', + 'callback' => [ $this, 'sample' ], + 'permission_callback' => function( WP_REST_Request $request ) { + return $this->has_permission(); + }, + ] + ); + } + + public function sample( WP_REST_Request $request ) { + $params = $request->get_params(); + if ( isset( $params['button_data'] ) ) { + // Do something + $results = $params['button_data']; + return $results; + } else { + return new WP_Error( __METHOD__, 'Missing parameters.' ); + } + } +} diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..cd83935 --- /dev/null +++ b/composer.json @@ -0,0 +1,11 @@ +{ + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "1.*", + "wp-coding-standards/wpcs": "3.1.*" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/disciple-tools-migration.php b/disciple-tools-migration.php new file mode 100755 index 0000000..9d0c7da --- /dev/null +++ b/disciple-tools-migration.php @@ -0,0 +1,397 @@ +version; + + /* + * Check if the Disciple.Tools theme is loaded and is the latest required version + */ + $is_theme_dt = class_exists( 'Disciple_Tools' ); + if ( $is_theme_dt && version_compare( $version, $disciple_tools_migration_required_dt_theme_version, '<' ) ) { + add_action( 'admin_notices', 'disciple_tools_migration_hook_admin_notice' ); + add_action( 'wp_ajax_dismissed_notice_handler', 'dt_hook_ajax_notice_handler' ); + return false; + } + if ( !$is_theme_dt ){ + return false; + } + /** + * Load useful function from the theme + */ + if ( !defined( 'DT_FUNCTIONS_READY' ) ){ + require_once get_template_directory() . '/dt-core/global-functions.php'; + } + + return Disciple_Tools_Migration_Plugin::instance(); +} +add_action( 'after_setup_theme', 'disciple_tools_migration', 20 ); + +//register the D.T Plugin +add_filter( 'dt_plugins', function ( $plugins ){ + $plugin_data = get_file_data( __FILE__, [ 'Version' => 'Version', 'Plugin Name' => 'Plugin Name' ], false ); + $plugins['disciple-tools-migration'] = [ + 'plugin_url' => trailingslashit( plugin_dir_url( __FILE__ ) ), + 'version' => $plugin_data['Version'] ?? null, + 'name' => $plugin_data['Plugin Name'] ?? null, + ]; + return $plugins; +}); + +/** + * Singleton class for setting up the plugin. + * + * @since 0.1 + * @access public + */ +class Disciple_Tools_Migration_Plugin { + + private static $_instance = null; + public static function instance() { + if ( is_null( self::$_instance ) ) { + self::$_instance = new self(); + } + return self::$_instance; + } + + private function __construct() { + $is_rest = dt_is_rest(); + /** + * Load the migration REST API endpoints. + * + * Originally this was only loaded when the URL path contained "disciple-tools-migration". + * For the dedicated dt-migration REST namespace, we also want to load it for + * /wp-json/dt-migration/... requests. The overhead is small, so we simply load it + * for all REST requests handled by this plugin. + */ + if ( $is_rest ) { + require_once( 'rest-api/rest-api.php' ); + } + + /** + * @todo Decide if you want to create a new post type + * To remove: delete the line below and remove the folder named /post-type + */ + require_once( 'post-type/loader.php' ); // add starter post type extension to Disciple.Tools system + + /** + * @todo Decide if you want to create a custom site-to-site link + * To remove: delete the line below and remove the folder named /site-link + */ + require_once( 'site-link/custom-site-to-site-links.php' ); // add site to site link class and capabilities + + /** + * @todo Decide if you want to add new charts to the metrics section + * To remove: delete the line below and remove the folder named /charts + */ + if ( strpos( dt_get_url_path(), 'metrics' ) !== false || ( $is_rest && strpos( dt_get_url_path(), 'disciple-tools-migration-metrics' ) !== false ) ){ + require_once( 'charts/charts-loader.php' ); // add custom charts to the metrics area + } + + /** + * @todo Decide if you want to add a custom tile or settings page tile + * To remove: delete the lines below and remove the folder named /tile + */ + require_once( 'tile/custom-tile.php' ); // add custom tile + if ( 'settings' === dt_get_url_path() && ! $is_rest ) { + require_once( 'tile/profile-settings-tile.php' ); // add custom settings page tile + } + + /** + * @todo Decide if you want to create a magic link + * To remove: delete the line below and remove the folder named /magic-link + */ + require_once( 'magic-link/post-type-magic-link/magic-link-post-type.php' ); + require_once( 'magic-link/magic-link-user-app.php' ); + require_once( 'magic-link/magic-link-login-user-app.php' ); + require_once( 'magic-link/magic-link-non-object.php' ); + require_once( 'magic-link/magic-link-map.php' ); + require_once( 'magic-link/templates/starter-template.php' ); +// require_once( 'magic-link/magic-link-home.php' ); + + /** + * Load the admin menu and shared settings helpers. + * + * The admin menu UI is only relevant in wp-admin, but the settings helper + * methods (e.g. Disciple_Tools_Migration_Menu::get_settings()) are also + * required by the REST API endpoints. We therefore load this file for both + * admin and REST requests. + */ + if ( is_admin() || $is_rest ) { + require_once( 'admin/admin-menu-and-tabs.php' ); // adds admin page and exposes settings helpers + } + + /** + * Load the import engine (shared logic for settings + records). + */ + if ( is_admin() || $is_rest ) { + require_once( 'includes/class-dt-migration-import-engine.php' ); + } + + /** + * Load the export file generator and download handler (Downloadable File mode). + */ + if ( is_admin() ) { + require_once( 'includes/class-dt-migration-export-file.php' ); + require_once( 'admin/class-dt-migration-export-download.php' ); + new Disciple_Tools_Migration_Export_Download(); + } + + /** + * Load the import AJAX handlers (admin only). + */ + if ( is_admin() ) { + require_once( 'admin/class-dt-migration-import-ajax.php' ); + new Disciple_Tools_Migration_Import_Ajax(); + } + + /** + * @todo Decide if you want to support localization of your plugin + * To remove: delete the line below and remove the folder named /languages + */ + $this->i18n(); + + /** + * @todo Decide if you want to customize links for your plugin in the plugin admin area + * To remove: delete the lines below and remove the function named "plugin_description_links" + */ + if ( is_admin() ) { // adds links to the plugin description area in the plugin admin list. + add_filter( 'plugin_row_meta', [ $this, 'plugin_description_links' ], 10, 4 ); + } + + /** + * @todo Decide if you want to create default workflows + * To remove: delete the line below and remove the folder named /workflows + */ + require_once( 'workflows/workflows.php' ); + } + + /** + * Filters the array of row meta for each/specific plugin in the Plugins list table. + * Appends additional links below each/specific plugin on the plugins page. + */ + public function plugin_description_links( $links_array, $plugin_file_name, $plugin_data, $status ) { + if ( strpos( $plugin_file_name, basename( __FILE__ ) ) ) { + // You can still use `array_unshift()` to add links at the beginning. + + $links_array[] = 'Disciple.Tools Community'; // @todo replace with your links. + // @todo add other links here + } + + return $links_array; + } + + /** + * Method that runs only when the plugin is activated. + * + * @since 0.1 + * @access public + * @return void + */ + public static function activation() { + // add elements here that need to fire on activation + } + + /** + * Method that runs only when the plugin is deactivated. + * + * @since 0.1 + * @access public + * @return void + */ + public static function deactivation() { + // add functions here that need to happen on deactivation + delete_option( 'dismissed-disciple-tools-migration' ); + } + + /** + * Loads the translation files. + * + * @since 0.1 + * @access public + * @return void + */ + public function i18n() { + $domain = 'disciple-tools-migration'; + load_plugin_textdomain( $domain, false, trailingslashit( dirname( plugin_basename( __FILE__ ) ) ). 'languages' ); + } + + /** + * Magic method to output a string if trying to use the object as a string. + * + * @since 0.1 + * @access public + * @return string + */ + public function __toString() { + return 'disciple-tools-migration'; + } + + /** + * Magic method to keep the object from being cloned. + * + * @since 0.1 + * @access public + * @return void + */ + public function __clone() { + _doing_it_wrong( __FUNCTION__, 'Whoah, partner!', '0.1' ); + } + + /** + * Magic method to keep the object from being unserialized. + * + * @since 0.1 + * @access public + * @return void + */ + public function __wakeup() { + _doing_it_wrong( __FUNCTION__, 'Whoah, partner!', '0.1' ); + } + + /** + * Magic method to prevent a fatal error when calling a method that doesn't exist. + * + * @param string $method + * @param array $args + * @return null + * @since 0.1 + * @access public + */ + public function __call( $method = '', $args = array() ) { + _doing_it_wrong( 'disciple_tools_migration::' . esc_html( $method ), 'Method does not exist.', '0.1' ); + unset( $method, $args ); + return null; + } +} + + +// Register activation hook. +register_activation_hook( __FILE__, [ 'Disciple_Tools_Migration_Plugin', 'activation' ] ); +register_deactivation_hook( __FILE__, [ 'Disciple_Tools_Migration_Plugin', 'deactivation' ] ); + + +if ( ! function_exists( 'disciple_tools_migration_hook_admin_notice' ) ) { + function disciple_tools_migration_hook_admin_notice() { + global $disciple_tools_migration_required_dt_theme_version; + $wp_theme = wp_get_theme(); + $current_version = $wp_theme->version; + $message = "'Disciple.Tools - Migrations' plugin requires 'Disciple.Tools' theme to work. Please activate 'Disciple.Tools' theme or make sure it is latest version."; + if ( $wp_theme->get_template() === 'disciple-tools-theme' ){ + $message .= ' ' . sprintf( esc_html( 'Current Disciple.Tools version: %1$s, required version: %2$s' ), esc_html( $current_version ), esc_html( $disciple_tools_migration_required_dt_theme_version ) ); + } + // Check if it's been dismissed... + if ( ! get_option( 'dismissed-disciple-tools-migration', false ) ) { ?> +
    +

    +
    + + [ 'limit' => 50, 'min_id' => 1, 'max_id' => 500 ], ... ]. + * @return array Export structure for JSON encoding. + */ + public static function build_export( array $record_options = [] ) : array { + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) || ! class_exists( 'DT_Posts' ) ) { + return [ 'error' => __( 'Migration or DT_Posts not available.', 'disciple-tools-migration' ) ]; + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + $allowed = $settings['allowed_items'] ?? []; + $site_meta = self::get_site_meta(); + + $settings_export = self::build_settings_export( $allowed ); + + $records = []; + $allowed_records = $allowed['records'] ?? []; + if ( ! empty( $allowed_records ) && is_array( $allowed_records ) ) { + foreach ( $allowed_records as $post_type => $enabled ) { + if ( ! $enabled ) { + continue; + } + $opts = $record_options[ $post_type ] ?? []; + $limit = isset( $opts['limit'] ) ? absint( $opts['limit'] ) : 0; + $min_id = isset( $opts['min_id'] ) ? absint( $opts['min_id'] ) : 0; + $max_id = isset( $opts['max_id'] ) ? absint( $opts['max_id'] ) : 0; + + $records[ $post_type ] = self::fetch_records( $post_type, $limit, $min_id, $max_id ); + } + } + + return [ + 'version' => self::EXPORT_VERSION, + 'type' => 'file', + 'site_meta' => $site_meta, + 'settings' => [ + 'enabled' => ! empty( $settings['enabled'] ), + 'mode' => 'file', + 'allowed_items' => $allowed, + ], + 'export' => [ + 'dt_settings' => $settings_export, + ], + 'records' => $records, + ]; + } + + /** + * Fetches records for a post type with optional limit and ID range. + * Always orders by ID ASC for deterministic batching. + * + * @param string $post_type + * @param int $limit 0 = no limit. + * @param int $min_id 0 = no minimum. + * @param int $max_id 0 = no maximum. + * @return array + */ + public static function fetch_records( string $post_type, int $limit = 0, int $min_id = 0, int $max_id = 0 ) : array { + $ids = self::get_record_ids( $post_type, $limit, $min_id, $max_id ); + $records = []; + foreach ( $ids as $post_id ) { + $post = DT_Posts::get_post( $post_type, $post_id, true, false ); + if ( ! is_wp_error( $post ) && is_array( $post ) ) { + $records[] = $post; + } + } + return $records; + } + + /** + * Gets post IDs for a post type with optional limit and ID range. + * Always ORDER BY ID ASC. + * + * @param string $post_type + * @param int $limit + * @param int $min_id + * @param int $max_id + * @return int[] + */ + private static function get_record_ids( string $post_type, int $limit, int $min_id, int $max_id ) : array { + global $wpdb; + $pt = $wpdb->prepare( '%s', $post_type ); + $where = $wpdb->prepare( "post_type = %s AND post_status != 'trash'", $post_type ); + if ( $min_id > 0 ) { + $where .= $wpdb->prepare( ' AND ID >= %d', $min_id ); + } + if ( $max_id > 0 ) { + $where .= $wpdb->prepare( ' AND ID <= %d', $max_id ); + } + $limit_sql = $limit > 0 ? $wpdb->prepare( ' LIMIT %d', $limit ) : ''; + $ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE $where ORDER BY ID ASC $limit_sql" ); + return array_map( 'intval', (array) $ids ); + } + + /** + * Returns record stats (count, min_id, max_id) per post type. + * + * @return array + */ + public static function get_record_stats() : array { + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) ) { + return []; + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + $allowed = $settings['allowed_items']['records'] ?? []; + if ( empty( $allowed ) || ! is_array( $allowed ) ) { + return []; + } + + global $wpdb; + $stats = []; + foreach ( $allowed as $post_type => $enabled ) { + if ( ! $enabled ) { + continue; + } + $pt = esc_sql( $post_type ); + $row = $wpdb->get_row( + $wpdb->prepare( + "SELECT COUNT(*) as cnt, MIN(ID) as min_id, MAX(ID) as max_id FROM $wpdb->posts WHERE post_type = %s AND post_status != 'trash'", + $post_type + ), + ARRAY_A + ); + $stats[ $post_type ] = [ + 'count' => (int) ( $row['cnt'] ?? 0 ), + 'min_id' => (int) ( $row['min_id'] ?? 0 ), + 'max_id' => (int) ( $row['max_id'] ?? 0 ), + ]; + } + return $stats; + } + + /** + * Builds settings export (mirrors REST API export logic). + * + * @param array $allowed + * @return array + */ + private static function build_settings_export( array $allowed ) : array { + $settings_export = [ + 'type' => 'file', + 'dt_tiles_settings' => [ 'values' => [] ], + 'dt_tiles_custom_settings' => [ 'values' => [] ], + 'dt_fields_settings' => [ 'values' => [] ], + 'dt_fields_custom_settings' => [ 'values' => [] ], + 'dt_post_types_settings' => [ 'values' => [] ], + 'dt_post_types_custom_settings' => [ 'values' => [] ], + 'dt_workflows_post_types' => [ 'values' => [] ], + 'dt_workflows_defaults' => [ 'values' => [] ], + ]; + + if ( ! empty( $allowed['tiles'] ) || ! empty( $allowed['fields'] ) || ! empty( $allowed['records'] ) ) { + $post_types = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $post_types[ $post_type ] ) ) { + $post_type_settings = DT_Posts::get_post_settings( $post_type, false ); + unset( $post_type_settings['tiles'], $post_type_settings['fields'] ); + $post_types[ $post_type ] = $post_type_settings; + } + } + $settings_export['dt_post_types_settings']['values'] = $post_types; + $settings_export['dt_post_types_custom_settings']['values'] = get_option( 'dt_custom_post_types', [] ); + } + + if ( ! empty( $allowed['tiles'] ) ) { + $tiles = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $tiles[ $post_type ] ) ) { + $tiles[ $post_type ] = DT_Posts::get_post_tiles( $post_type, false ); + } + } + $settings_export['dt_tiles_settings']['values'] = $tiles; + $settings_export['dt_tiles_custom_settings']['values'] = dt_get_option( 'dt_custom_tiles' ); + } + + if ( ! empty( $allowed['fields'] ) ) { + $fields = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $fields[ $post_type ] ) ) { + $fields[ $post_type ] = DT_Posts::get_post_field_settings( $post_type, false, true ); + } + } + $settings_export['dt_fields_settings']['values'] = $fields; + $settings_export['dt_fields_custom_settings']['values'] = dt_get_option( 'dt_field_customizations' ); + } + + if ( ! empty( $allowed['workflows'] ) ) { + $post_types_raw = get_option( 'dt_workflows_post_types', '' ); + $defaults_raw = get_option( 'dt_workflows_defaults', '' ); + $settings_export['dt_workflows_post_types']['values'] = ! empty( $post_types_raw ) + ? json_decode( $post_types_raw, true ) + : []; + $settings_export['dt_workflows_defaults']['values'] = ! empty( $defaults_raw ) + ? json_decode( $defaults_raw, true ) + : []; + } + + return $settings_export; + } + + /** + * @return array + */ + private static function get_site_meta() : array { + $wp_theme = wp_get_theme(); + return [ + 'timestamp' => time(), + 'site_url' => get_site_url(), + 'wp_version' => get_bloginfo( 'version' ), + 'php_version' => phpversion(), + 'server' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '', + 'dt_version' => $wp_theme->version, + 'multisite' => is_multisite(), + ]; + } +} diff --git a/includes/class-dt-migration-import-engine.php b/includes/class-dt-migration-import-engine.php new file mode 100644 index 0000000..e5eb6bf --- /dev/null +++ b/includes/class-dt-migration-import-engine.php @@ -0,0 +1,866 @@ + true, + 'applied' => [], + 'errors' => [], + ]; + + $dt_settings = $export_payload['export']['dt_settings'] ?? []; + if ( empty( $dt_settings ) ) { + return $result; + } + + if ( ! empty( $selected['general_settings'] ) ) { + $general = self::apply_general_settings( $export_payload ); + if ( ! empty( $general['error'] ) ) { + $result['errors'][] = $general['error']; + $result['success'] = false; + } else { + $result['applied']['general_settings'] = true; + } + } + + if ( ! empty( $selected['custom_lists'] ) ) { + $custom_lists = self::apply_custom_lists( $dt_settings ); + if ( ! empty( $custom_lists['error'] ) ) { + $result['errors'][] = $custom_lists['error']; + $result['success'] = false; + } else { + $result['applied']['custom_lists'] = true; + } + } + + if ( ! empty( $selected['tiles'] ) ) { + $tiles = self::apply_tiles( $dt_settings ); + if ( ! empty( $tiles['error'] ) ) { + $result['errors'][] = $tiles['error']; + $result['success'] = false; + } else { + $result['applied']['tiles'] = true; + } + } + + if ( ! empty( $selected['fields'] ) ) { + $fields = self::apply_fields( $dt_settings ); + if ( ! empty( $fields['error'] ) ) { + $result['errors'][] = $fields['error']; + $result['success'] = false; + } else { + $result['applied']['fields'] = true; + } + } + + if ( ! empty( $selected['roles'] ) ) { + $roles = self::apply_roles( $export_payload ); + if ( ! empty( $roles['error'] ) ) { + $result['errors'][] = $roles['error']; + $result['success'] = false; + } else { + $result['applied']['roles'] = true; + } + } + + if ( ! empty( $selected['workflows'] ) ) { + $workflows = self::apply_workflows( $export_payload ); + if ( ! empty( $workflows['error'] ) ) { + $result['errors'][] = $workflows['error']; + $result['success'] = false; + } else { + $result['applied']['workflows'] = true; + } + } + + return $result; + } + + /** + * Applies general site settings. + * + * @param array $export_payload + * + * @return array + */ + private static function apply_general_settings( array $export_payload ) : array { + // General settings may be in export payload; for now we skip if not present. + return []; + } + + /** + * Applies custom lists. + * + * @param array $dt_settings + * + * @return array + */ + private static function apply_custom_lists( array $dt_settings ) : array { + $custom_lists = $dt_settings['dt_site_custom_lists'] ?? null; + if ( empty( $custom_lists ) || ! isset( $custom_lists['values'] ) ) { + return []; + } + if ( function_exists( 'dt_get_option' ) ) { + $existing = dt_get_option( 'dt_site_custom_lists' ); + $merged = is_array( $existing ) ? array_merge( $existing, $custom_lists['values'] ) : $custom_lists['values']; + update_option( 'dt_site_custom_lists', $merged, true ); + } + return []; + } + + /** + * Applies tile settings from export. + * + * @param array $dt_settings + * + * @return array + */ + private static function apply_tiles( array $dt_settings ) : array { + $tiles_settings = $dt_settings['dt_tiles_settings']['values'] ?? []; + $custom_tiles = $dt_settings['dt_tiles_custom_settings']['values'] ?? []; + if ( empty( $tiles_settings ) && empty( $custom_tiles ) ) { + return []; + } + $existing = get_option( 'dt_custom_tiles', [] ); + if ( ! is_array( $existing ) ) { + $existing = []; + } + foreach ( $tiles_settings as $post_type => $tiles ) { + if ( ! isset( $existing[ $post_type ] ) ) { + $existing[ $post_type ] = []; + } + foreach ( (array) $tiles as $tile_key => $tile_config ) { + $existing[ $post_type ][ $tile_key ] = $tile_config; + } + } + if ( ! empty( $custom_tiles ) ) { + $existing = array_merge( $existing, $custom_tiles ); + } + update_option( 'dt_custom_tiles', $existing, true ); + return []; + } + + /** + * Applies field settings from export. + * + * @param array $dt_settings + * + * @return array + */ + private static function apply_fields( array $dt_settings ) : array { + $fields_settings = $dt_settings['dt_fields_settings']['values'] ?? []; + $custom_fields = $dt_settings['dt_fields_custom_settings']['values'] ?? []; + if ( empty( $fields_settings ) && empty( $custom_fields ) ) { + return []; + } + $existing = get_option( 'dt_field_customizations', [] ); + if ( ! is_array( $existing ) ) { + $existing = []; + } + foreach ( $fields_settings as $post_type => $fields ) { + if ( ! isset( $existing[ $post_type ] ) ) { + $existing[ $post_type ] = []; + } + foreach ( (array) $fields as $field_key => $field_config ) { + $existing[ $post_type ][ $field_key ] = $field_config; + } + } + if ( ! empty( $custom_fields ) ) { + $existing = array_merge( $existing, $custom_fields ); + } + update_option( 'dt_field_customizations', $existing, true ); + return []; + } + + /** + * Applies roles from export. + * + * @param array $export_payload + * + * @return array + */ + private static function apply_roles( array $export_payload ) : array { + // Roles export/import structure may differ; placeholder. + return []; + } + + /** + * Applies workflows from export. + * + * Restores dt_workflows_post_types and dt_workflows_defaults from the export payload. + * + * @param array $export_payload + * + * @return array + */ + private static function apply_workflows( array $export_payload ) : array { + $dt_settings = $export_payload['export']['dt_settings'] ?? []; + + $post_types_values = $dt_settings['dt_workflows_post_types']['values'] ?? []; + if ( ! empty( $post_types_values ) && is_array( $post_types_values ) ) { + update_option( 'dt_workflows_post_types', wp_json_encode( $post_types_values ), true ); + } + + $defaults_values = $dt_settings['dt_workflows_defaults']['values'] ?? []; + if ( ! empty( $defaults_values ) && is_array( $defaults_values ) ) { + update_option( 'dt_workflows_defaults', wp_json_encode( $defaults_values ), true ); + } + + return []; + } + + /** + * Imports a batch of records for a post type. + * + * Preserves post IDs using import_id. Deletes existing records first when offset=0. + * + * @param string $post_type Post type. + * @param array $records Array of post data from DT_Posts::get_post. + * @param int $offset Batch offset (0 = first batch, delete existing first). + * + * @return array{ imported: int, errors: array } + */ + public static function import_records_batch( string $post_type, array $records, int $offset = 0 ) : array { + $result = [ + 'imported' => 0, + 'errors' => [], + ]; + + if ( ! class_exists( 'DT_Posts' ) ) { + $result['errors'][] = __( 'DT_Posts not available.', 'disciple-tools-migration' ); + return $result; + } + + // On first batch, delete existing posts of this type (destructive). + if ( $offset === 0 ) { + $deleted = self::delete_posts_by_type( $post_type ); + if ( $deleted < 0 ) { + $result['errors'][] = __( 'Failed to clear existing records.', 'disciple-tools-migration' ); + return $result; + } + if ( $post_type === 'groups' ) { + delete_transient( 'dt_migration_deferred_group_connections' ); + } + } + + $group_conn_keys = [ 'parent_groups', 'child_groups', 'peer_groups' ]; + + $records = self::sort_records_by_connection_deps( $post_type, $records ); + + $deferred_connections = ( $post_type === 'groups' ) + ? ( array ) ( get_transient( 'dt_migration_deferred_group_connections' ) ?: [] ) + : []; + + foreach ( $records as $record ) { + $post_id = isset( $record['ID'] ) ? (int) $record['ID'] : 0; + if ( ! $post_id ) { + continue; + } + $fields = self::prepare_record_fields_for_import( $record, $post_type ); + $fields = self::filter_fields_for_target( $post_type, $fields ); + + if ( $post_type === 'groups' ) { + $deferred = []; + foreach ( $group_conn_keys as $key ) { + if ( isset( $fields[ $key ] ) && is_array( $fields[ $key ] ) && ! empty( $fields[ $key ]['values'] ) ) { + $deferred[ $key ] = $fields[ $key ]; + unset( $fields[ $key ] ); + } + } + if ( ! empty( $deferred ) ) { + $deferred_connections[ $post_id ] = $deferred; + } + } + + $err = self::insert_or_update_post( $post_type, $post_id, $fields ); + if ( is_wp_error( $err ) ) { + $result['errors'][] = sprintf( + /* translators: 1: post type, 2: post ID, 3: error message */ + __( 'Failed to import %1$s #%2$d: %3$s', 'disciple-tools-migration' ), + $post_type, + $post_id, + $err->get_error_message() + ); + } else { + ++$result['imported']; + } + } + + if ( $post_type === 'groups' && ! empty( $deferred_connections ) ) { + set_transient( 'dt_migration_deferred_group_connections', $deferred_connections, HOUR_IN_SECONDS ); + } + + return $result; + } + + /** + * Filters connection field values to only include target IDs that exist. + * + * Prevents "Error adding connection" when the target post was not imported + * (e.g. filtered out of export, failed import, or different batch). + * + * @param array $conn_fields Connection fields: { parent_groups: [...], child_groups: [...], ... }. + * @param string $post_type Expected post type of target (e.g. 'groups'). + * @return array Filtered connection fields with invalid targets removed. + */ + private static function filter_connection_values_to_existing_posts( array $conn_fields, string $post_type ) : array { + $filtered = []; + foreach ( $conn_fields as $field_key => $field_data ) { + if ( ! is_array( $field_data ) || empty( $field_data['values'] ) ) { + continue; + } + $valid = []; + foreach ( $field_data['values'] as $item ) { + $target_id = isset( $item['value'] ) ? (int) $item['value'] : 0; + if ( $target_id <= 0 ) { + continue; + } + if ( get_post_type( $target_id ) === $post_type ) { + $valid[] = $item; + } + } + if ( ! empty( $valid ) ) { + $filtered[ $field_key ] = array_merge( $field_data, [ 'values' => $valid ] ); + } + } + return $filtered; + } + + /** + * Applies deferred group-to-group connections after all groups have been imported. + * + * Called when the last batch of groups completes. All groups exist, so connections + * can be added without order dependencies. + * + * @return array{ applied: int, errors: array } + */ + public static function apply_deferred_group_connections() : array { + $stored = get_transient( 'dt_migration_deferred_group_connections' ); + if ( ! is_array( $stored ) || empty( $stored ) ) { + return [ 'applied' => 0, 'errors' => [] ]; + } + delete_transient( 'dt_migration_deferred_group_connections' ); + + $result = [ 'applied' => 0, 'errors' => [] ]; + if ( ! class_exists( 'DT_Posts' ) ) { + $result['errors'][] = __( 'DT_Posts not available.', 'disciple-tools-migration' ); + return $result; + } + + foreach ( $stored as $post_id => $conn_fields ) { + $post_id = (int) $post_id; + if ( $post_id <= 0 || get_post_type( $post_id ) !== 'groups' ) { + continue; + } + $conn_fields = self::filter_connection_values_to_existing_posts( $conn_fields, 'groups' ); + if ( empty( $conn_fields ) ) { + continue; + } + $err = DT_Posts::update_post( 'groups', $post_id, $conn_fields, true, false ); + if ( is_wp_error( $err ) ) { + $result['errors'][] = sprintf( + /* translators: 1: group ID, 2: error message */ + __( 'Failed to apply connections for group #%1$d: %2$s', 'disciple-tools-migration' ), + $post_id, + $err->get_error_message() + ); + } else { + ++$result['applied']; + } + } + return $result; + } + + /** + * Deletes all posts of a given post type. + * + * @param string $post_type + * + * @return int Number deleted, or -1 on error. + */ + public static function delete_posts_by_type( string $post_type ) : int { + $query = new WP_Query( + [ + 'post_type' => $post_type, + 'post_status' => 'any', + 'posts_per_page' => -1, + 'fields' => 'ids', + ] + ); + $ids = $query->posts ?? []; + $n = 0; + foreach ( $ids as $id ) { + $deleted = wp_delete_post( (int) $id, true ); + if ( $deleted ) { + ++$n; + } + } + return $n; + } + + /** + * Sorts records so connection dependencies are satisfied (e.g. parent before child for groups). + * + * For groups, parent_groups and child_groups require the connected group to exist first. + * Uses topological sort so parents and children are imported before the group that references them. + * + * @param string $post_type Post type. + * @param array $records Array of records from export. + * @return array Sorted records. + */ + private static function sort_records_by_connection_deps( string $post_type, array $records ) : array { + if ( $post_type !== 'groups' || empty( $records ) ) { + return $records; + } + + $id_to_record = []; + $batch_ids = []; + foreach ( $records as $r ) { + $id = isset( $r['ID'] ) ? (int) $r['ID'] : 0; + if ( $id > 0 ) { + $id_to_record[ $id ] = $r; + $batch_ids[] = $id; + } + } + $batch_ids = array_unique( $batch_ids ); + + $blocks = []; // blocks[dep_id] = list of ids that must wait for dep_id + foreach ( $records as $r ) { + $id = isset( $r['ID'] ) ? (int) $r['ID'] : 0; + $deps = []; + foreach ( [ 'parent_groups', 'child_groups' ] as $conn_key ) { + if ( empty( $r[ $conn_key ] ) || ! is_array( $r[ $conn_key ] ) ) { + continue; + } + foreach ( $r[ $conn_key ] as $item ) { + $oid = self::extract_post_id_from_connection_item( $item ); + if ( $oid > 0 && in_array( $oid, $batch_ids, true ) && $oid !== $id ) { + $deps[] = $oid; + } + } + } + foreach ( array_unique( $deps ) as $dep ) { + $blocks[ $dep ] = $blocks[ $dep ] ?? []; + $blocks[ $dep ][] = $id; + } + } + + $in_degree = array_fill_keys( $batch_ids, 0 ); + foreach ( $records as $r ) { + $id = isset( $r['ID'] ) ? (int) $r['ID'] : 0; + $deps = []; + foreach ( [ 'parent_groups', 'child_groups' ] as $conn_key ) { + if ( empty( $r[ $conn_key ] ) || ! is_array( $r[ $conn_key ] ) ) { + continue; + } + foreach ( $r[ $conn_key ] as $item ) { + $oid = self::extract_post_id_from_connection_item( $item ); + if ( $oid > 0 && in_array( $oid, $batch_ids, true ) && $oid !== $id ) { + $deps[] = $oid; + } + } + } + $in_degree[ $id ] = count( array_unique( $deps ) ); + } + + $ready = array_keys( array_filter( $in_degree, function ( $d ) { return $d === 0; } ) ); + $out = []; + $done = []; + while ( ! empty( $ready ) ) { + $nid = array_shift( $ready ); + if ( isset( $done[ $nid ] ) ) { + continue; + } + $done[ $nid ] = true; + if ( isset( $id_to_record[ $nid ] ) ) { + $out[] = $id_to_record[ $nid ]; + } + foreach ( $blocks[ $nid ] ?? [] as $waiting ) { + $in_degree[ $waiting ] = isset( $in_degree[ $waiting ] ) ? $in_degree[ $waiting ] - 1 : 0; + if ( $in_degree[ $waiting ] <= 0 && empty( $done[ $waiting ] ) ) { + $ready[] = $waiting; + } + } + } + foreach ( $batch_ids as $bid ) { + if ( ! in_array( $bid, array_column( $out, 'ID' ), true ) && isset( $id_to_record[ $bid ] ) ) { + $out[] = $id_to_record[ $bid ]; + } + } + return $out; + } + + /** + * Filters record fields to only those that exist on the target site. + * + * Skips unknown fields so records can still migrate with ID, name, and valid fields. + * + * @param string $post_type + * @param array $fields Prepared fields from prepare_record_fields_for_import. + * + * @return array Filtered fields safe for DT_Posts::update_post. + */ + private static function filter_fields_for_target( string $post_type, array $fields ) : array { + if ( ! class_exists( 'DT_Posts' ) || empty( $fields ) ) { + return $fields; + } + + try { + $post_settings = DT_Posts::get_post_settings( $post_type, false ); + if ( empty( $post_settings['fields'] ) ) { + return $fields; + } + + // Ensure keys expected by check_for_invalid_post_fields / is_post_key_contact_method_or_connection exist. + $post_settings = array_merge( + [ 'channels' => [], 'connection_types' => [] ], + $post_settings + ); + + $allowed_fields = apply_filters( 'dt_post_update_allow_fields', [], $post_type ); + $bad_fields = DT_Posts::check_for_invalid_post_fields( $post_settings, $fields, $allowed_fields ); + + foreach ( (array) $bad_fields as $bad ) { + unset( $fields[ $bad ] ); + } + } catch ( Throwable $e ) { + // If filtering fails, return fields unchanged; DT_Posts may still accept them or return a clearer error. + return $fields; + } + + return $fields; + } + + /** + * Normalizes a field value from export format to DT_Posts update format. + * + * Export returns key_select as { key, label }; DT expects the key string. + * Export returns user_select as { assigned-to, id, display }; DT expects assigned-to value. + * + * @param mixed $value + * @return mixed + */ + private static function normalize_field_value_for_import( $value ) { + if ( is_array( $value ) && isset( $value['key'] ) ) { + return (string) $value['key']; + } + if ( is_array( $value ) && isset( $value['assigned-to'] ) ) { + return (string) $value['assigned-to']; + } + if ( is_array( $value ) && isset( $value['timestamp'] ) ) { + return $value['timestamp']; + } + return $value; + } + + /** + * Normalizes a connection field from export format to DT_Posts update format. + * + * Export returns connections as an array of objects (e.g. [ ['ID' => 123, ... ], ... ]). + * DT_Posts::update_post expects { values: [ ['value' => id], ... ], force_values?: true }. + * + * @param mixed $value Connection data from export. + * @return array{ values: array, force_values: bool } + */ + private static function normalize_connection_for_import( $value ) : array { + $values = []; + if ( is_array( $value ) && isset( $value['values'] ) ) { + foreach ( (array) $value['values'] as $item ) { + $id = self::extract_post_id_from_connection_item( $item ); + if ( $id > 0 ) { + $values[] = [ 'value' => $id ]; + } + } + return [ + 'values' => $values, + 'force_values' => ! empty( $value['force_values'] ), + ]; + } + if ( is_array( $value ) ) { + foreach ( $value as $item ) { + $id = self::extract_post_id_from_connection_item( $item ); + if ( $id > 0 ) { + $values[] = [ 'value' => $id ]; + } + } + } + return [ 'values' => $values, 'force_values' => true ]; + } + + /** + * Normalizes a multi_select/tags field from export format to DT_Posts update format. + * + * Export may return plain arrays (e.g. ['web','facebook']) or mixed formats. + * DT_Posts::update_post expects { values: [ ['value' => key], ... ], force_values?: true }. + * + * @param mixed $value Multi-select data from export. + * @return array{ values: array, force_values: bool } + */ + private static function normalize_multi_select_for_import( $value ) : array { + $values = []; + if ( is_array( $value ) && isset( $value['values'] ) ) { + foreach ( (array) $value['values'] as $item ) { + $v = self::extract_multi_select_value( $item ); + if ( $v !== '' && $v !== null ) { + $values[] = [ 'value' => $v ]; + } + } + return [ + 'values' => $values, + 'force_values' => ! empty( $value['force_values'] ), + ]; + } + if ( is_array( $value ) ) { + foreach ( $value as $item ) { + $v = self::extract_multi_select_value( $item ); + if ( $v !== '' && $v !== null ) { + $values[] = [ 'value' => $v ]; + } + } + } + return [ 'values' => $values, 'force_values' => true ]; + } + + /** + * Extracts the value from a multi-select, location, or tags item. + * + * Handles: plain values, arrays with value/key (multi_select), grid_id/id (location). + * + * @param mixed $item + * @return string|int|null + */ + private static function extract_multi_select_value( $item ) { + if ( is_string( $item ) || is_numeric( $item ) ) { + return is_numeric( $item ) ? (int) $item : (string) $item; + } + if ( is_array( $item ) ) { + if ( isset( $item['value'] ) ) { + return is_numeric( $item['value'] ) ? (int) $item['value'] : (string) $item['value']; + } + if ( isset( $item['key'] ) ) { + return (string) $item['key']; + } + if ( isset( $item['grid_id'] ) ) { + return (int) $item['grid_id']; + } + if ( isset( $item['id'] ) ) { + return is_numeric( $item['id'] ) ? (int) $item['id'] : (string) $item['id']; + } + } + return null; + } + + /** + * Extracts post ID from a connection item (object or array). + * + * @param mixed $item Connection item: object with ID, or array with ID/value. + * @return int + */ + private static function extract_post_id_from_connection_item( $item ) : int { + if ( is_numeric( $item ) ) { + return (int) $item; + } + if ( is_object( $item ) && isset( $item->ID ) ) { + return (int) $item->ID; + } + if ( is_array( $item ) ) { + if ( isset( $item['ID'] ) ) { + return (int) $item['ID']; + } + if ( isset( $item['value'] ) && is_numeric( $item['value'] ) ) { + return (int) $item['value']; + } + } + return 0; + } + + /** + * Prepares record fields for import (strips IDs, formats for create/update). + * + * @param array $record Full post from DT_Posts::get_post. + * @param string $post_type Post type for connection field detection. + * + * @return array + */ + private static function prepare_record_fields_for_import( array $record, string $post_type ) : array { + $exclude = [ + 'ID', + 'post_type', + 'post_date', + 'post_date_gmt', + 'permalink', + 'post_date_formatted', + 'post_author', + 'post_author_display_name', + ]; + $connection_types = []; + $multi_select_types = []; + if ( class_exists( 'DT_Posts' ) ) { + $post_settings = DT_Posts::get_post_settings( $post_type, false ); + $connection_types = (array) ( $post_settings['connection_types'] ?? [] ); + $field_settings = (array) ( $post_settings['fields'] ?? [] ); + $values_based_types = [ 'multi_select', 'tags', 'location', 'location_meta' ]; + foreach ( $field_settings as $fk => $fs ) { + if ( isset( $fs['type'] ) && in_array( $fs['type'], $values_based_types, true ) ) { + $multi_select_types[] = $fk; + } + } + } + $fields = []; + foreach ( $record as $key => $value ) { + if ( in_array( $key, $exclude, true ) ) { + continue; + } + if ( in_array( $key, $connection_types, true ) ) { + $fields[ $key ] = self::normalize_connection_for_import( $value ); + } elseif ( in_array( $key, $multi_select_types, true ) ) { + $fields[ $key ] = self::normalize_multi_select_for_import( $value ); + } else { + $fields[ $key ] = self::normalize_field_value_for_import( $value ); + } + } + if ( isset( $fields['name'] ) && ! isset( $fields['title'] ) ) { + $fields['title'] = $fields['name']; + } + return $fields; + } + + /** + * get_post_metadata filter: return [] for *_details keys during record import. + * + * The theme's update_post_contact_method expects get_post_meta(..., '_details', true) + * to return an array. When the meta does not exist (or is corrupt as ''), the theme + * does $details[$key] = $value and triggers "Cannot access offset of type string on string". + * Short-circuiting with [] fixes this without modifying the theme. + * + * @param mixed $value Value from previous filter or null. + * @param int $object_id Post ID. + * @param string $meta_key Meta key. + * @param bool $single Whether a single value is requested. + * @param string $meta_type Meta type ('post'). + * @return mixed + */ + public static function filter_details_meta_during_import( $value, $object_id, $meta_key, $single, $meta_type ) { + if ( ! self::$during_record_import || $meta_type !== 'post' ) { + return $value; + } + if ( substr( $meta_key, -8 ) !== '_details' ) { + return $value; + } + return [ [] ]; + } + + /** + * Inserts a post with a specific ID (preserves relationships). + * + * Uses wp_insert_post with import_id for the base post, then DT_Posts::update_post + * to apply all field values, connections, and meta. + * + * @param string $post_type + * @param int $post_id Desired post ID. + * @param array $fields Prepared fields from prepare_record_fields_for_import. + * + * @return true|WP_Error + */ + private static function insert_or_update_post( string $post_type, int $post_id, array $fields ) { + $existing = get_post( $post_id ); + $run_update = function () use ( $post_type, $post_id, $fields ) { + return DT_Posts::update_post( $post_type, $post_id, $fields, true, false ); + }; + + if ( $existing && get_post_type( $post_id ) === $post_type ) { + self::$during_record_import = true; + add_filter( 'get_post_metadata', [ self::class, 'filter_details_meta_during_import' ], 10, 5 ); + try { + return $run_update(); + } finally { + remove_filter( 'get_post_metadata', [ self::class, 'filter_details_meta_during_import' ], 10 ); + self::$during_record_import = false; + } + } + + $title = $fields['title'] ?? $fields['name'] ?? ''; + if ( empty( $title ) ) { + return new WP_Error( 'missing_title', __( 'Record has no title/name.', 'disciple-tools-migration' ) ); + } + + $post_arr = [ + 'import_id' => $post_id, + 'post_title' => $title, + 'post_type' => $post_type, + 'post_status' => $fields['post_status'] ?? 'publish', + ]; + + $inserted_id = wp_insert_post( $post_arr, true ); + if ( is_wp_error( $inserted_id ) ) { + return $inserted_id; + } + if ( $inserted_id !== $post_id ) { + return new WP_Error( 'id_mismatch', __( 'Could not preserve post ID.', 'disciple-tools-migration' ) ); + } + + self::$during_record_import = true; + add_filter( 'get_post_metadata', [ self::class, 'filter_details_meta_during_import' ], 10, 5 ); + try { + return $run_update(); + } finally { + remove_filter( 'get_post_metadata', [ self::class, 'filter_details_meta_during_import' ], 10 ); + self::$during_record_import = false; + } + } + + /** + * Returns post types to import in dependency order. + * + * @param array $selected Selected post type keys. + * + * @return string[] + */ + public static function ordered_post_types( array $selected ) : array { + $ordered = []; + foreach ( self::POST_TYPE_ORDER as $pt ) { + if ( ! empty( $selected[ $pt ] ) ) { + $ordered[] = $pt; + } + } + foreach ( array_keys( $selected ) as $pt ) { + if ( ! in_array( $pt, $ordered, true ) && ! empty( $selected[ $pt ] ) ) { + $ordered[] = $pt; + } + } + return $ordered; + } +} diff --git a/languages/Readme.md b/languages/Readme.md new file mode 100644 index 0000000..59baa77 --- /dev/null +++ b/languages/Readme.md @@ -0,0 +1,5 @@ +.po and .mo files must be in this format: +{translation-domain}-{localisation}.po + +ex: +disciple-tools-migration-fr_FR.po diff --git a/languages/default.pot b/languages/default.pot new file mode 100644 index 0000000..0e58dd8 --- /dev/null +++ b/languages/default.pot @@ -0,0 +1,298 @@ +# Copyright (C) 2022 +# This file is distributed under the same license as the Disciple.Tools - Migrations plugin. +msgid "" +msgstr "" +"Project-Id-Version: Disciple.Tools - Migrations 0.1\n" +"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/disciple-tools-migration\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"POT-Creation-Date: 2022-10-27T10:12:56+00:00\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"X-Generator: WP-CLI 2.7.1\n" +"X-Domain: disciple-tools-migration\n" + +#: charts/one-page-chart-template.php:68 +msgid "Sample API Call" +msgstr "" + +#: magic-link/magic-link-map.php:99 +#: magic-link/magic-link-non-object.php:117 +#: magic-link/magic-link-user-app.php:167 +#: magic-link/post-type-magic-link/magic-link-post-type.php:102 +msgid "Add Magic" +msgstr "" + +#: magic-link/post-type-magic-link/magic-link-post-type.php:128 +msgid "Magic Url" +msgstr "" + +#: post-type/loader.php:22 +#: post-type/module-base.php:63 +#: post-type/module-base.php:79 +msgid "Starter" +msgstr "" + +#: post-type/loader.php:27 +msgid "Default starter functionality" +msgstr "" + +#: post-type/module-base.php:64 +#: post-type/module-base.php:80 +msgid "Starters" +msgstr "" + +#: post-type/module-base.php:95 +msgid "Multiplier" +msgstr "" + +#: post-type/module-base.php:137 +msgid "Status" +msgstr "" + +#: post-type/module-base.php:138 +msgid "Set the current status." +msgstr "" + +#: post-type/module-base.php:142 +msgid "Inactive" +msgstr "" + +#: post-type/module-base.php:143 +msgid "No longer active." +msgstr "" + +#: post-type/module-base.php:147 +msgid "Active" +msgstr "" + +#: post-type/module-base.php:148 +msgid "Is active." +msgstr "" + +#: post-type/module-base.php:158 +msgid "Assigned To" +msgstr "" + +#: post-type/module-base.php:159 +msgid "Select the main person who is responsible for reporting on this record." +msgstr "" + +#: post-type/module-base.php:173 +msgid "Start Date" +msgstr "" + +#: post-type/module-base.php:181 +msgid "End Date" +msgstr "" + +#: post-type/module-base.php:189 +msgid "Multi-Select" +msgstr "" + +#: post-type/module-base.php:190 +msgid "Multi Select Field" +msgstr "" + +#: post-type/module-base.php:194 +msgid "Item 1" +msgstr "" + +#: post-type/module-base.php:195 +msgid "Item 1." +msgstr "" + +#: post-type/module-base.php:198 +msgid "Item 2" +msgstr "" + +#: post-type/module-base.php:199 +msgid "Item 2." +msgstr "" + +#: post-type/module-base.php:202 +msgid "Item 3" +msgstr "" + +#: post-type/module-base.php:203 +msgid "Item 3." +msgstr "" + +#: post-type/module-base.php:217 +#: post-type/module-base.php:226 +msgid "Locations" +msgstr "" + +#: post-type/module-base.php:218 +msgid "The general location where this contact is located." +msgstr "" + +#: post-type/module-base.php:227 +msgid "The general location where this record is located." +msgstr "" + +#: post-type/module-base.php:235 +msgid "Address" +msgstr "" + +#: post-type/module-base.php:258 +msgid "Parents" +msgstr "" + +#: post-type/module-base.php:269 +msgid "Peers" +msgstr "" + +#: post-type/module-base.php:280 +msgid "Children" +msgstr "" + +#: post-type/module-base.php:297 +msgid "People Groups" +msgstr "" + +#: post-type/module-base.php:298 +msgid "The people groups connected to this record." +msgstr "" + +#: post-type/module-base.php:308 +msgid "Contacts" +msgstr "" + +#: post-type/module-base.php:365 +msgid "Connections" +msgstr "" + +#: post-type/module-base.php:366 +msgid "Other" +msgstr "" + +#: post-type/module-base.php:383 +msgid "Custom Section Contact" +msgstr "" + +#: post-type/module-base.php:539 +msgid "Assigned to me" +msgstr "" + +#: post-type/module-base.php:547 +#: post-type/module-base.php:604 +#: post-type/module-base.php:612 +msgid "All" +msgstr "" + +#: tile/custom-tile.php:32 +msgid "Migrations" +msgstr "" + +#: tile/custom-tile.php:33 +msgid "A Beautiful Tile" +msgstr "" + +#: tile/custom-tile.php:63 +#: tile/custom-tile.php:132 +#: tile/custom-tile.php:138 +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:64 +msgctxt "Optional Documentation" +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:74 +msgid "Multiselect" +msgstr "" + +#: tile/custom-tile.php:76 +msgid "One" +msgstr "" + +#: tile/custom-tile.php:77 +msgid "Two" +msgstr "" + +#: tile/custom-tile.php:78 +msgid "Three" +msgstr "" + +#: tile/custom-tile.php:79 +msgid "Four" +msgstr "" + +#: tile/custom-tile.php:95 +msgctxt "Key Select Label" +msgid "First" +msgstr "" + +#: tile/custom-tile.php:96 +msgctxt "Training Status field description" +msgid "First Key Description" +msgstr "" + +#: tile/custom-tile.php:100 +msgctxt "Key Select Label" +msgid "Second" +msgstr "" + +#: tile/custom-tile.php:101 +msgctxt "Training Status field description" +msgid "Second Key Description" +msgstr "" + +#: tile/custom-tile.php:105 +msgctxt "Key Select Label" +msgid "Third" +msgstr "" + +#: tile/custom-tile.php:106 +msgctxt "Training Status field description" +msgid "Third Key Description" +msgstr "" + +#: tile/custom-tile.php:117 +msgid "Number field" +msgstr "" + +#: tile/custom-tile.php:124 +msgid "Number field private" +msgstr "" + +#: tile/custom-tile.php:145 +msgid "Communication Channel" +msgstr "" + +#: tile/custom-tile.php:152 +msgid "User Select" +msgstr "" + +#: tile/custom-tile.php:157 +msgid "Array" +msgstr "" + +#: tile/custom-tile.php:167 +#: tile/custom-tile.php:174 +msgid " Date Field" +msgstr "" + +#: tile/custom-tile.php:182 +#: tile/custom-tile.php:187 +msgid "Boolean" +msgstr "" + +#: tile/settings-tile.php:43 +#: tile/settings-tile.php:61 +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:77 +msgctxt "Optional Documentation" +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:78 +msgctxt "Optional Documentation" +msgid "Add your own help information into this modal." +msgstr "" diff --git a/languages/disciple-tools-plugin-starter-template-es_ES.mo b/languages/disciple-tools-plugin-starter-template-es_ES.mo new file mode 100644 index 0000000..6969af0 Binary files /dev/null and b/languages/disciple-tools-plugin-starter-template-es_ES.mo differ diff --git a/languages/disciple-tools-plugin-starter-template-es_ES.po b/languages/disciple-tools-plugin-starter-template-es_ES.po new file mode 100644 index 0000000..e6850cb --- /dev/null +++ b/languages/disciple-tools-plugin-starter-template-es_ES.po @@ -0,0 +1,292 @@ +# Copyright (C) 2022 +# This file is distributed under the same license as the Disciple.Tools - Migrations plugin. +msgid "" +msgstr "" +"Project-Id-Version: Disciple.Tools - Migrations 0.1\n" +"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/disciple-tools-" +"plugin-starter-template\n" +"POT-Creation-Date: 2022-10-27T10:12:56+00:00\n" +"PO-Revision-Date: 2022-10-27 10:11+0000\n" +"Last-Translator: Corsacca \n" +"Language-Team: Spanish \n" +"Language: es_ES\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 4.14.1\n" +"X-Domain: disciple-tools-migration\n" + +#: charts/one-page-chart-template.php:68 +msgid "Sample API Call" +msgstr "Sample API Call" + +#: magic-link/magic-link-map.php:99 magic-link/magic-link-non-object.php:117 +#: magic-link/magic-link-user-app.php:167 +#: magic-link/post-type-magic-link/magic-link-post-type.php:102 +msgid "Add Magic" +msgstr "" + +#: magic-link/post-type-magic-link/magic-link-post-type.php:128 +msgid "Magic Url" +msgstr "" + +#: post-type/loader.php:22 post-type/module-base.php:63 +#: post-type/module-base.php:79 +msgid "Starter" +msgstr "" + +#: post-type/loader.php:27 +msgid "Default starter functionality" +msgstr "" + +#: post-type/module-base.php:64 post-type/module-base.php:80 +msgid "Starters" +msgstr "" + +#: post-type/module-base.php:95 +msgid "Multiplier" +msgstr "" + +#: post-type/module-base.php:137 +msgid "Status" +msgstr "" + +#: post-type/module-base.php:138 +msgid "Set the current status." +msgstr "" + +#: post-type/module-base.php:142 +msgid "Inactive" +msgstr "" + +#: post-type/module-base.php:143 +msgid "No longer active." +msgstr "" + +#: post-type/module-base.php:147 +msgid "Active" +msgstr "" + +#: post-type/module-base.php:148 +msgid "Is active." +msgstr "" + +#: post-type/module-base.php:158 +msgid "Assigned To" +msgstr "" + +#: post-type/module-base.php:159 +msgid "Select the main person who is responsible for reporting on this record." +msgstr "" + +#: post-type/module-base.php:173 +msgid "Start Date" +msgstr "" + +#: post-type/module-base.php:181 +msgid "End Date" +msgstr "" + +#: post-type/module-base.php:189 +msgid "Multi-Select" +msgstr "" + +#: post-type/module-base.php:190 +msgid "Multi Select Field" +msgstr "" + +#: post-type/module-base.php:194 +msgid "Item 1" +msgstr "" + +#: post-type/module-base.php:195 +msgid "Item 1." +msgstr "" + +#: post-type/module-base.php:198 +msgid "Item 2" +msgstr "" + +#: post-type/module-base.php:199 +msgid "Item 2." +msgstr "" + +#: post-type/module-base.php:202 +msgid "Item 3" +msgstr "" + +#: post-type/module-base.php:203 +msgid "Item 3." +msgstr "" + +#: post-type/module-base.php:217 post-type/module-base.php:226 +msgid "Locations" +msgstr "" + +#: post-type/module-base.php:218 +msgid "The general location where this contact is located." +msgstr "" + +#: post-type/module-base.php:227 +msgid "The general location where this record is located." +msgstr "" + +#: post-type/module-base.php:235 +msgid "Address" +msgstr "" + +#: post-type/module-base.php:258 +msgid "Parents" +msgstr "" + +#: post-type/module-base.php:269 +msgid "Peers" +msgstr "" + +#: post-type/module-base.php:280 +msgid "Children" +msgstr "" + +#: post-type/module-base.php:297 +msgid "People Groups" +msgstr "" + +#: post-type/module-base.php:298 +msgid "The people groups connected to this record." +msgstr "" + +#: post-type/module-base.php:308 +msgid "Contacts" +msgstr "" + +#: post-type/module-base.php:365 +msgid "Connections" +msgstr "" + +#: post-type/module-base.php:366 +msgid "Other" +msgstr "" + +#: post-type/module-base.php:383 +msgid "Custom Section Contact" +msgstr "" + +#: post-type/module-base.php:539 +msgid "Assigned to me" +msgstr "" + +#: post-type/module-base.php:547 post-type/module-base.php:604 +#: post-type/module-base.php:612 +msgid "All" +msgstr "" + +#: tile/custom-tile.php:32 +msgid "Migrations" +msgstr "" + +#: tile/custom-tile.php:33 +msgid "A Beautiful Tile" +msgstr "" + +#: tile/custom-tile.php:63 tile/custom-tile.php:132 tile/custom-tile.php:138 +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:64 +msgctxt "Optional Documentation" +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:74 +msgid "Multiselect" +msgstr "" + +#: tile/custom-tile.php:76 +msgid "One" +msgstr "" + +#: tile/custom-tile.php:77 +msgid "Two" +msgstr "" + +#: tile/custom-tile.php:78 +msgid "Three" +msgstr "" + +#: tile/custom-tile.php:79 +msgid "Four" +msgstr "" + +#: tile/custom-tile.php:95 +msgctxt "Key Select Label" +msgid "First" +msgstr "" + +#: tile/custom-tile.php:96 +msgctxt "Training Status field description" +msgid "First Key Description" +msgstr "" + +#: tile/custom-tile.php:100 +msgctxt "Key Select Label" +msgid "Second" +msgstr "" + +#: tile/custom-tile.php:101 +msgctxt "Training Status field description" +msgid "Second Key Description" +msgstr "" + +#: tile/custom-tile.php:105 +msgctxt "Key Select Label" +msgid "Third" +msgstr "" + +#: tile/custom-tile.php:106 +msgctxt "Training Status field description" +msgid "Third Key Description" +msgstr "" + +#: tile/custom-tile.php:117 +msgid "Number field" +msgstr "" + +#: tile/custom-tile.php:124 +msgid "Number field private" +msgstr "" + +#: tile/custom-tile.php:145 +msgid "Communication Channel" +msgstr "" + +#: tile/custom-tile.php:152 +msgid "User Select" +msgstr "" + +#: tile/custom-tile.php:157 +msgid "Array" +msgstr "" + +#: tile/custom-tile.php:167 tile/custom-tile.php:174 +msgid " Date Field" +msgstr "" + +#: tile/custom-tile.php:182 tile/custom-tile.php:187 +msgid "Boolean" +msgstr "" + +#: tile/settings-tile.php:43 tile/settings-tile.php:61 +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:77 +msgctxt "Optional Documentation" +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:78 +msgctxt "Optional Documentation" +msgid "Add your own help information into this modal." +msgstr "" diff --git a/languages/disciple-tools-plugin-starter-template-fr_FR.mo b/languages/disciple-tools-plugin-starter-template-fr_FR.mo new file mode 100644 index 0000000..afefc54 Binary files /dev/null and b/languages/disciple-tools-plugin-starter-template-fr_FR.mo differ diff --git a/languages/disciple-tools-plugin-starter-template-fr_FR.po b/languages/disciple-tools-plugin-starter-template-fr_FR.po new file mode 100644 index 0000000..8024759 --- /dev/null +++ b/languages/disciple-tools-plugin-starter-template-fr_FR.po @@ -0,0 +1,299 @@ +msgid "" +msgstr "" +"Project-Id-Version: Disciple Tools - Migrations\n" +"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/disciple-tools-" +"plugin-starter-template\n" +"POT-Creation-Date: 2022-10-27T10:12:56+00:00\n" +"PO-Revision-Date: 2022-10-27 10:10+0000\n" +"Last-Translator: Corsacca \n" +"Language-Team: French \n" +"Language: fr_FR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=n > 1;\n" +"X-Generator: Weblate 4.14.1\n" +"X-Poedit-Basepath: ..\n" +"X-Poedit-Flags-xgettext: --add-comments=translators:\n" +"X-Poedit-WPHeader: disciple-tools-migration.php\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;esc_attr__;" +"esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c;_n_noop:1,2;" +"_nx_noop:3c,1,2;__ngettext_noop:1,2\n" +"X-Poedit-SearchPath-0: .\n" +"X-Poedit-SearchPathExcluded-0: *.js\n" +"X-Poedit-SearchPathExcluded-1: */libraries/*\n" + +#: charts/one-page-chart-template.php:68 +msgid "Sample API Call" +msgstr "Sample API Call" + +#: magic-link/magic-link-map.php:99 magic-link/magic-link-non-object.php:117 +#: magic-link/magic-link-user-app.php:167 +#: magic-link/post-type-magic-link/magic-link-post-type.php:102 +msgid "Add Magic" +msgstr "Ajouter magie" + +#: magic-link/post-type-magic-link/magic-link-post-type.php:128 +msgid "Magic Url" +msgstr "Url Magic" + +#: post-type/loader.php:22 post-type/module-base.php:63 +#: post-type/module-base.php:79 +msgid "Starter" +msgstr "Starter" + +#: post-type/loader.php:27 +msgid "Default starter functionality" +msgstr "" + +#: post-type/module-base.php:64 post-type/module-base.php:80 +msgid "Starters" +msgstr "" + +#: post-type/module-base.php:95 +msgid "Multiplier" +msgstr "Multiplicateur" + +#: post-type/module-base.php:137 +msgid "Status" +msgstr "" + +#: post-type/module-base.php:138 +msgid "Set the current status." +msgstr "" + +#: post-type/module-base.php:142 +msgid "Inactive" +msgstr "" + +#: post-type/module-base.php:143 +msgid "No longer active." +msgstr "" + +#: post-type/module-base.php:147 +msgid "Active" +msgstr "" + +#: post-type/module-base.php:148 +msgid "Is active." +msgstr "" + +#: post-type/module-base.php:158 +msgid "Assigned To" +msgstr "" + +#: post-type/module-base.php:159 +msgid "Select the main person who is responsible for reporting on this record." +msgstr "" + +#: post-type/module-base.php:173 +msgid "Start Date" +msgstr "" + +#: post-type/module-base.php:181 +msgid "End Date" +msgstr "" + +#: post-type/module-base.php:189 +msgid "Multi-Select" +msgstr "" + +#: post-type/module-base.php:190 +msgid "Multi Select Field" +msgstr "" + +#: post-type/module-base.php:194 +msgid "Item 1" +msgstr "" + +#: post-type/module-base.php:195 +msgid "Item 1." +msgstr "" + +#: post-type/module-base.php:198 +msgid "Item 2" +msgstr "" + +#: post-type/module-base.php:199 +msgid "Item 2." +msgstr "" + +#: post-type/module-base.php:202 +msgid "Item 3" +msgstr "" + +#: post-type/module-base.php:203 +msgid "Item 3." +msgstr "" + +#: post-type/module-base.php:217 post-type/module-base.php:226 +msgid "Locations" +msgstr "" + +#: post-type/module-base.php:218 +msgid "The general location where this contact is located." +msgstr "" + +#: post-type/module-base.php:227 +msgid "The general location where this record is located." +msgstr "" + +#: post-type/module-base.php:235 +msgid "Address" +msgstr "" + +#: post-type/module-base.php:258 +msgid "Parents" +msgstr "" + +#: post-type/module-base.php:269 +msgid "Peers" +msgstr "" + +#: post-type/module-base.php:280 +msgid "Children" +msgstr "" + +#: post-type/module-base.php:297 +msgid "People Groups" +msgstr "" + +#: post-type/module-base.php:298 +msgid "The people groups connected to this record." +msgstr "" + +#: post-type/module-base.php:308 +msgid "Contacts" +msgstr "" + +#: post-type/module-base.php:365 +msgid "Connections" +msgstr "" + +#: post-type/module-base.php:366 +msgid "Other" +msgstr "" + +#: post-type/module-base.php:383 +msgid "Custom Section Contact" +msgstr "" + +#: post-type/module-base.php:539 +msgid "Assigned to me" +msgstr "" + +#: post-type/module-base.php:547 post-type/module-base.php:604 +#: post-type/module-base.php:612 +msgid "All" +msgstr "" + +#: tile/custom-tile.php:32 +msgid "Migrations" +msgstr "" + +#: tile/custom-tile.php:33 +msgid "A Beautiful Tile" +msgstr "" + +#: tile/custom-tile.php:63 tile/custom-tile.php:132 tile/custom-tile.php:138 +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:64 +msgctxt "Optional Documentation" +msgid "Text" +msgstr "" + +#: tile/custom-tile.php:74 +msgid "Multiselect" +msgstr "" + +#: tile/custom-tile.php:76 +msgid "One" +msgstr "" + +#: tile/custom-tile.php:77 +msgid "Two" +msgstr "" + +#: tile/custom-tile.php:78 +msgid "Three" +msgstr "" + +#: tile/custom-tile.php:79 +msgid "Four" +msgstr "" + +#: tile/custom-tile.php:95 +msgctxt "Key Select Label" +msgid "First" +msgstr "" + +#: tile/custom-tile.php:96 +msgctxt "Training Status field description" +msgid "First Key Description" +msgstr "" + +#: tile/custom-tile.php:100 +msgctxt "Key Select Label" +msgid "Second" +msgstr "" + +#: tile/custom-tile.php:101 +msgctxt "Training Status field description" +msgid "Second Key Description" +msgstr "" + +#: tile/custom-tile.php:105 +msgctxt "Key Select Label" +msgid "Third" +msgstr "" + +#: tile/custom-tile.php:106 +msgctxt "Training Status field description" +msgid "Third Key Description" +msgstr "" + +#: tile/custom-tile.php:117 +msgid "Number field" +msgstr "" + +#: tile/custom-tile.php:124 +msgid "Number field private" +msgstr "" + +#: tile/custom-tile.php:145 +msgid "Communication Channel" +msgstr "" + +#: tile/custom-tile.php:152 +msgid "User Select" +msgstr "" + +#: tile/custom-tile.php:157 +msgid "Array" +msgstr "" + +#: tile/custom-tile.php:167 tile/custom-tile.php:174 +msgid " Date Field" +msgstr "" + +#: tile/custom-tile.php:182 tile/custom-tile.php:187 +msgid "Boolean" +msgstr "" + +#: tile/settings-tile.php:43 tile/settings-tile.php:61 +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:77 +msgctxt "Optional Documentation" +msgid "Custom Settings Section" +msgstr "" + +#: tile/settings-tile.php:78 +msgctxt "Optional Documentation" +msgid "Add your own help information into this modal." +msgstr "" diff --git a/languages/terms_to_exclude.pot b/languages/terms_to_exclude.pot new file mode 100644 index 0000000..370ce45 --- /dev/null +++ b/languages/terms_to_exclude.pot @@ -0,0 +1,15 @@ +#. Plugin Name of the plugin +msgid "Disciple.Tools - Migrations" +msgstr "" + +#. Description of the plugin +msgid "Disciple.Tools - Migrations is intended to help developers and integrator jumpstart their extension of the Disciple.Tools system." +msgstr "" + +# Author URI of the plugin +msgid "https://github.com/DiscipleTools" +msgstr "" + +#. Plugin URI of the plugin +msgid "https://github.com/DiscipleTools/disciple-tools-migration" +msgstr "" diff --git a/magic-link/magic-link-home.php b/magic-link/magic-link-home.php new file mode 100644 index 0000000..4b54d21 --- /dev/null +++ b/magic-link/magic-link-home.php @@ -0,0 +1,95 @@ + + + +
    Insert Your Home Page Here
    + meta = [ + 'app_type' => 'magic_link', + 'post_type' => $this->post_type, + 'contacts_only' => false, + 'fields' => [ + [ + 'id' => 'name', + 'label' => 'Name' + ] + ], + 'icon' => 'mdi mdi-cog-outline', + 'show_in_home_apps' => false + ]; + + $this->meta_key = $this->root . '_' . $this->type . '_magic_key'; + parent::__construct(); + + /** + * user_app and module section + */ + add_filter( 'dt_settings_apps_list', [ $this, 'dt_settings_apps_list' ], 10, 1 ); + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + + /** + * tests if other URL + */ + $url = dt_get_url_path(); + if ( strpos( $url, $this->root . '/' . $this->type ) === false ) { + return; + } + /** + * tests magic link parts are registered and have valid elements + */ + if ( !$this->check_parts_match() ){ + return; + } + + if ( !is_user_logged_in() ) { + /* redirect user to login page with a redirect_to back to here */ + wp_redirect( dt_login_url( 'login', '?redirect_to=' . rawurlencode( site_url( dt_get_url_path() ) ) . '&hide-nav' ) ); + exit; + } + + // load if valid url + add_action( 'dt_blank_body', [ $this, 'body' ] ); + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + // @todo add or remove js files with this filter + return $allowed_js; + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + // @todo add or remove js files with this filter + return $allowed_css; + } + + /** + * Builds magic link type settings payload: + * - key: Unique magic link type key; which is usually composed of root, type and _magic_key suffix. + * - url_base: URL path information to map with parent magic link type. + * - label: Magic link type name. + * - description: Magic link type description. + * - settings_display: Boolean flag which determines if magic link type is to be listed within frontend user profile settings. + * + * @param $apps_list + * + * @return mixed + */ + public function dt_settings_apps_list( $apps_list ) { + $apps_list[ $this->meta_key ] = [ + 'key' => $this->meta_key, + 'url_base' => $this->root . '/' . $this->type, + 'label' => $this->page_title, + 'description' => $this->page_description, + 'settings_display' => true + ]; + + return $apps_list; + } + + /** + * Writes custom styles to header + * + * @see DT_Magic_Url_Base()->header_style() for default state + * @todo remove if not needed + */ + public function header_style(){ + ?> + + header_javascript() for default state + * @todo remove if not needed + */ + public function header_javascript(){ + ?> + + footer_javascript() for default state + * @todo remove if not needed + */ + public function footer_javascript(){ + ?> + + parts['post_id']; + $app_owner = get_user_by( 'ID', $app_owner_id ); + $app_owner_display_name = dt_get_user_display_name( $app_owner_id ); + + // @todo Create an app here that interacts with both the logged in user and the user who owns the app + + ?> +
    +
    +
    +
    +

    Hello there

    +
    +
    +
    +
    +

    This app belongs to

    +
    + + +
    + +
    +
    +
    +

    Form

    +
    + +
    +
    + +
    + root . '/v1'; + register_rest_route( + $namespace, '/'.$this->type, [ + [ + 'methods' => 'GET', + 'callback' => [ $this, 'endpoint_get' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/'.$this->type, [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'update_record' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + } + + public function update_record( WP_REST_Request $request ) { + $params = $request->get_params(); + $params = dt_recursive_sanitize_array( $params ); + + $post_id = $params['parts']['post_id']; //has been verified in verify_rest_endpoint_permissions_on_post() + + $args = []; + if ( !is_user_logged_in() ){ + $global_name = apply_filters( 'dt_magic_link_global_name', __( 'Magic Link', 'disciple-tools-migration' ) ); + $args['comment_author'] = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + wp_set_current_user( 0 ); + $current_user = wp_get_current_user(); + $current_user->add_cap( 'magic_link' ); + $current_user->display_name = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + } + + if ( isset( $params['update']['comment'] ) && !empty( $params['update']['comment'] ) ){ + $update = DT_Posts::add_post_comment( $this->post_type, $post_id, $params['update']['comment'], 'comment', $args, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + if ( isset( $params['update']['start_date'] ) && !empty( $params['update']['start_date'] ) ){ + $update = DT_Posts::update_post( $this->post_type, $post_id, [ 'start_date' => $params['update']['start_date'] ], false, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + return true; + } + + public function endpoint_get( WP_REST_Request $request ) { + $params = $request->get_params(); + if ( ! isset( $params['parts'], $params['action'] ) ) { + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + $data = []; + + $data[] = [ 'name' => 'List item' ]; // @todo remove example + $data[] = [ 'name' => 'List item' ]; // @todo remove example + + return $data; + } +} +Disciple_Tools_Migration_Magic_Login_User_App::instance(); diff --git a/magic-link/magic-link-map.php b/magic-link/magic-link-map.php new file mode 100644 index 0000000..3ae0545 --- /dev/null +++ b/magic-link/magic-link-map.php @@ -0,0 +1,315 @@ +root . '/' . $this->type ) === $url ) { + + $this->magic = new DT_Magic_URL( $this->root ); + $this->parts = $this->magic->parse_url_parts(); + + + // register url and access + add_action( 'template_redirect', [ $this, 'theme_redirect' ] ); + add_filter( 'dt_blank_access', function (){ return true; + }, 100, 1 ); + add_filter( 'dt_allow_non_login_access', function (){ return true; + }, 100, 1 ); + add_filter( 'dt_override_header_meta', function (){ return true; + }, 100, 1 ); + + // header content + add_filter( 'dt_blank_title', [ $this, 'page_tab_title' ] ); // adds basic title to browser tab + add_action( 'wp_print_scripts', [ $this, 'print_scripts' ], 1500 ); // authorizes scripts + add_action( 'wp_print_styles', [ $this, 'print_styles' ], 1500 ); // authorizes styles + + + // page content + add_action( 'dt_blank_head', [ $this, '_header' ] ); + add_action( 'dt_blank_footer', [ $this, '_footer' ] ); + add_action( 'dt_blank_body', [ $this, 'body' ] ); // body for no post key + + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + add_action( 'wp_enqueue_scripts', [ $this, '_wp_enqueue_scripts' ], 100 ); + } + + if ( dt_is_rest() ) { + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + add_filter( 'dt_allow_rest_access', [ $this, 'authorize_url' ], 10, 1 ); + } + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + $allowed_js[] = 'jquery-touch-punch'; + $allowed_js[] = 'mapbox-gl'; + $allowed_js[] = 'jquery-cookie'; + $allowed_js[] = 'mapbox-cookie'; + $allowed_js[] = 'heatmap-js'; + return $allowed_js; + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + $allowed_css[] = 'mapbox-gl-css'; + $allowed_css[] = 'introjs-css'; + $allowed_css[] = 'heatmap-css'; + $allowed_css[] = 'site-css'; + return $allowed_css; + } + + public function header_javascript(){ + ?> + + + + + +
    +
    +
    + root . '/v1'; + register_rest_route( + $namespace, + '/'.$this->type, + [ + [ + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'endpoint' ], + 'permission_callback' => '__return_true', + ], + ] + ); + } + + public function endpoint( WP_REST_Request $request ) { + $params = $request->get_params(); + + if ( ! isset( $params['parts'], $params['action'] ) ) { + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + $params = dt_recursive_sanitize_array( $params ); + + switch ( $params['action'] ) { + case 'geojson': + return $this->endpoint_geojson( $params['parts'] ); + default: + return new WP_Error( __METHOD__, 'Missing valid action parameters', [ 'status' => 400 ] ); + } + } + + public function endpoint_geojson( $parts ) { + global $wpdb; + + $results = $wpdb->get_results( + "SELECT * FROM $wpdb->dt_location_grid WHERE level = 0", ARRAY_A ); + + if ( empty( $results ) ) { + return $this->_empty_geojson(); + } + + $features = []; + foreach ( $results as $result ) { + $features[] = array( + 'type' => 'Feature', + 'properties' => array( + 'grid_id' => $result['grid_id'], + 'name' => $result['name'], + 'value' => rand( 1, 10 ) // random value + ), + 'geometry' => array( + 'type' => 'Point', + 'coordinates' => array( + (float) $result['longitude'], + (float) $result['latitude'], + 1 + ), + ), + ); + } + + $geojson = array( + 'type' => 'FeatureCollection', + 'features' => $features, + ); + + return $geojson; + } + + private function _empty_geojson() { + return array( + 'type' => 'FeatureCollection', + 'features' => array() + ); + } +} +Disciple_Tools_Migration_Magic_Map_App::instance(); diff --git a/magic-link/magic-link-non-object.php b/magic-link/magic-link-non-object.php new file mode 100644 index 0000000..21b920f --- /dev/null +++ b/magic-link/magic-link-non-object.php @@ -0,0 +1,192 @@ +root . '/' . $this->type ) === $url ) { + + $this->magic = new DT_Magic_URL( $this->root ); + $this->parts = $this->magic->parse_url_parts(); + + + // register url and access + add_filter( 'dt_override_header_meta', '__return_true', 100, 1 ); + + // page content + add_action( 'dt_blank_body', [ $this, 'body' ] ); // body for no post key + + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + add_action( 'wp_enqueue_scripts', [ $this, '_wp_enqueue_scripts' ], 100 ); + } + + if ( dt_is_rest() ) { + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + } + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + return $allowed_js; + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + return $allowed_css; + } + + public function header_style(){ + ?> + + +
    + + + root . '/v1'; + register_rest_route( + $namespace, + '/'.$this->type, + [ + [ + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'endpoint' ], + 'permission_callback' => '__return_true', + ], + ] + ); + } + + public function endpoint( WP_REST_Request $request ) { + $params = $request->get_params(); + + if ( ! isset( $params['parts'], $params['action'] ) ) { + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + $params = dt_recursive_sanitize_array( $params ); + + switch ( $params['action'] ) { + case 'get': + // do something + return true; + case 'excited': + // do something else + default: + return true; + } + } +} +Disciple_Tools_Migration_Magic_Non_Object_App::instance(); diff --git a/magic-link/magic-link-user-app.php b/magic-link/magic-link-user-app.php new file mode 100644 index 0000000..3fecd70 --- /dev/null +++ b/magic-link/magic-link-user-app.php @@ -0,0 +1,362 @@ +meta = [ + 'app_type' => 'magic_link', + 'post_type' => $this->post_type, + 'contacts_only' => false, + 'fields' => [ + [ + 'id' => 'name', + 'label' => 'Name' + ] + ], + 'icon' => 'mdi mdi-cog-outline', + 'show_in_home_apps' => false + ]; + + $this->meta_key = $this->root . '_' . $this->type . '_magic_key'; + parent::__construct(); + + /** + * user_app and module section + */ + add_filter( 'dt_settings_apps_list', [ $this, 'dt_settings_apps_list' ], 10, 1 ); + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + + /** + * tests if other URL + */ + $url = dt_get_url_path(); + if ( strpos( $url, $this->root . '/' . $this->type ) === false ) { + return; + } + /** + * tests magic link parts are registered and have valid elements + */ + if ( !$this->check_parts_match() ){ + return; + } + + // load if valid url + add_action( 'dt_blank_body', [ $this, 'body' ] ); + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + // @todo add or remove js files with this filter + return $allowed_js; + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + // @todo add or remove js files with this filter + return $allowed_css; + } + + /** + * Builds magic link type settings payload: + * - key: Unique magic link type key; which is usually composed of root, type and _magic_key suffix. + * - url_base: URL path information to map with parent magic link type. + * - label: Magic link type name. + * - description: Magic link type description. + * - settings_display: Boolean flag which determines if magic link type is to be listed within frontend user profile settings. + * + * @param $apps_list + * + * @return mixed + */ + public function dt_settings_apps_list( $apps_list ) { + $apps_list[ $this->meta_key ] = [ + 'key' => $this->meta_key, + 'url_base' => $this->root . '/' . $this->type, + 'label' => $this->page_title, + 'description' => $this->page_description, + 'settings_display' => true + ]; + + return $apps_list; + } + + /** + * Writes custom styles to header + * + * @see DT_Magic_Url_Base()->header_style() for default state + * @todo remove if not needed + */ + public function header_style(){ + ?> + + header_javascript() for default state + * @todo remove if not needed + */ + public function header_javascript(){ + ?> + + footer_javascript() for default state + * @todo remove if not needed + */ + public function footer_javascript(){ + ?> + + +
    +
    +
    +
    +

    Title

    +
    +
    +
    +
    +

    List From API

    +
    + + +
    + +
    +
    +
    +

    Form

    +
    + +
    +
    + +
    + root . '/v1'; + register_rest_route( + $namespace, '/'.$this->type, [ + [ + 'methods' => 'GET', + 'callback' => [ $this, 'endpoint_get' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/'.$this->type, [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'update_record' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + } + + public function update_record( WP_REST_Request $request ) { + $params = $request->get_params(); + $params = dt_recursive_sanitize_array( $params ); + + $post_id = $params['parts']['post_id']; //has been verified in verify_rest_endpoint_permissions_on_post() + + $args = []; + if ( !is_user_logged_in() ){ + $global_name = apply_filters( 'dt_magic_link_global_name', __( 'Magic Link', 'disciple-tools-migration' ) ); + $args['comment_author'] = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + wp_set_current_user( 0 ); + $current_user = wp_get_current_user(); + $current_user->add_cap( 'magic_link' ); + $current_user->display_name = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + } + + if ( isset( $params['update']['comment'] ) && !empty( $params['update']['comment'] ) ){ + $update = DT_Posts::add_post_comment( $this->post_type, $post_id, $params['update']['comment'], 'comment', $args, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + if ( isset( $params['update']['start_date'] ) && !empty( $params['update']['start_date'] ) ){ + $update = DT_Posts::update_post( $this->post_type, $post_id, [ 'start_date' => $params['update']['start_date'] ], false, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + return true; + } + + public function endpoint_get( WP_REST_Request $request ) { + $params = $request->get_params(); + if ( ! isset( $params['parts'], $params['action'] ) ) { + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + $data = []; + + $data[] = [ 'name' => 'List item' ]; // @todo remove example + $data[] = [ 'name' => 'List item' ]; // @todo remove example + + return $data; + } +} +Disciple_Tools_Migration_Magic_User_App::instance(); diff --git a/magic-link/post-type-magic-link/magic-link-post-type.php b/magic-link/post-type-magic-link/magic-link-post-type.php new file mode 100644 index 0000000..527c560 --- /dev/null +++ b/magic-link/post-type-magic-link/magic-link-post-type.php @@ -0,0 +1,277 @@ +meta = [ + 'app_type' => 'magic_link', + 'post_type' => $this->post_type, + 'contacts_only' => true, + 'fields' => [ + [ + 'id' => 'name', + 'label' => 'Name' + ] + ], + 'icon' => 'mdi mdi-cog-outline', + 'show_in_home_apps' => false + ]; + + $this->meta_key = $this->root . '_' . $this->type . '_magic_key'; + parent::__construct(); + + /** + * post type and module section + */ +// add_action( 'dt_details_additional_section', [ $this, 'dt_details_additional_section' ], 30, 2 ); +// add_filter( 'dt_details_additional_tiles', [ $this, 'dt_details_additional_tiles' ], 10, 2 ); + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + + + /** + * tests if other URL + */ + $url = dt_get_url_path(); + if ( strpos( $url, $this->root . '/' . $this->type ) === false ) { + return; + } + /** + * tests magic link parts are registered and have valid elements + */ + if ( !$this->check_parts_match() ){ + return; + } + + // load if valid url + add_action( 'dt_blank_body', [ $this, 'body' ] ); // body for no post key + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + add_action( 'wp_enqueue_scripts', [ $this, 'wp_enqueue_scripts' ], 100 ); + } + + public function wp_enqueue_scripts(){ + wp_enqueue_script( 'magic_link_scripts', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'magic-link.js', [ + 'jquery', + 'lodash', + ], filemtime( plugin_dir_path( __FILE__ ) . 'magic-link.js' ), true ); + wp_localize_script( + 'magic_link_scripts', 'jsObject', [ + 'map_key' => DT_Mapbox_API::get_key(), + 'rest_base' => esc_url( rest_url() ), + 'nonce' => wp_create_nonce( 'wp_rest' ), + 'parts' => $this->parts, + 'translations' => [ + 'add' => __( 'Add Magic', 'disciple-tools-migration' ), + ], + 'rest_namespace' => $this->root . '/v1/' . $this->type, + ] + ); + wp_enqueue_style( 'magic_link_css', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'magic-link.css', [], filemtime( plugin_dir_path( __FILE__ ) . 'magic-link.css' ) ); + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + // @todo add or remove js files with this filter + $allowed_js[] = 'magic_link_scripts'; + return $allowed_js; + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + // @todo add or remove js files with this filter + $allowed_css[] = 'magic_link_css'; + return $allowed_css; + } + + /** + * Post Type Tile Examples + */ + public function dt_details_additional_tiles( $tiles, $post_type = '' ) { + if ( $post_type === $this->post_type ){ + $tiles['dt_migrations_magic_url'] = [ + 'label' => __( 'Magic Url', 'disciple-tools-migration' ), + 'description' => 'The Magic URL sets up a page accessible without authentication, only the link is needed. Useful for small applications liked to this record, like quick surveys or updates.' + ]; + } + return $tiles; + } + public function dt_details_additional_section( $section, $post_type ) { + // test if campaigns post type and campaigns_app_module enabled + if ( $post_type === $this->post_type ) { + if ( 'dt_migrations_magic_url' === $section ) { + $link = DT_Magic_URL::get_link_url_for_post( $post_type, get_the_ID(), $this->root, $this->type ) + ?> +

    See help for description.

    + Open magic link + + + root . '/v1'; + register_rest_route( + $namespace, '/' . $this->type, [ + [ + 'methods' => 'GET', + 'callback' => [ $this, 'endpoint_get' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/' . $this->type, [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'update_record' ], + 'permission_callback' => function( WP_REST_Request $request ){ + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + } + + public function update_record( WP_REST_Request $request ) { + $params = $request->get_params(); + $params = dt_recursive_sanitize_array( $params ); + + $post_id = $params['parts']['post_id']; //has been verified in verify_rest_endpoint_permissions_on_post() + + $args = []; + if ( !is_user_logged_in() ){ + $global_name = apply_filters( 'dt_magic_link_global_name', __( 'Magic Link', 'disciple-tools-migration' ) ); + $args['comment_author'] = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + wp_set_current_user( 0 ); + $current_user = wp_get_current_user(); + $current_user->add_cap( 'magic_link' ); + $current_user->display_name = sprintf( __( '%s Submission', 'disciple-tools-migration' ), $global_name ); + } + + if ( isset( $params['update']['comment'] ) && !empty( $params['update']['comment'] ) ){ + $update = DT_Posts::add_post_comment( $this->post_type, $post_id, $params['update']['comment'], 'comment', $args, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + if ( isset( $params['update']['start_date'] ) && !empty( $params['update']['start_date'] ) ){ + $update = DT_Posts::update_post( $this->post_type, $post_id, [ 'start_date' => $params['update']['start_date'] ], false, false ); + if ( is_wp_error( $update ) ){ + return $update; + } + } + + return true; + } + + public function endpoint_get( WP_REST_Request $request ) { + $params = $request->get_params(); + if ( ! isset( $params['parts'], $params['action'] ) ) { + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + $data = []; + + $data[] = [ 'name' => 'List item' ]; // @todo remove example + $data[] = [ 'name' => 'List item' ]; // @todo remove example + + return $data; + } +} +Disciple_Tools_Migration_Magic_Link::instance(); diff --git a/magic-link/post-type-magic-link/magic-link.css b/magic-link/post-type-magic-link/magic-link.css new file mode 100644 index 0000000..ef408c0 --- /dev/null +++ b/magic-link/post-type-magic-link/magic-link.css @@ -0,0 +1,6 @@ +body { + background-color: white !important; +} +#magic-link-wrapper { + padding: 1em; +} diff --git a/magic-link/post-type-magic-link/magic-link.js b/magic-link/post-type-magic-link/magic-link.js new file mode 100644 index 0000000..5a0e84b --- /dev/null +++ b/magic-link/post-type-magic-link/magic-link.js @@ -0,0 +1,61 @@ +window.get_magic = () => { + window.makeRequest( "GET", '/', { action: 'get', parts: jsObject.parts }, jsObject.rest_namespace ) + .done(function(data){ + window.load_magic( data ) + }) + .fail(function(e) { + console.log(e) + jQuery('#error').html(e) + }) +} +window.get_magic() + +window.load_magic = ( data ) => { + let content = jQuery('#api-content') + let spinner = jQuery('.loading-spinner') + + content.empty() + let html = `` + data.forEach(v=>{ + html += ` +
    + ${window.lodash.escape(v.name)} +
    + ` + }) + content.html(html) + + spinner.removeClass('active') + +} + +$('.dt_date_picker').datepicker({ + constrainInput: false, + dateFormat: 'yy-mm-dd', + changeMonth: true, + changeYear: true, + yearRange: "1900:2050", +}).each(function() { + if (this.value && moment.unix(this.value).isValid()) { + this.value = window.SHAREDFUNCTIONS.formatDate(this.value); + } +}) + + +$('#submit-form').on("click", function (){ + $(this).addClass("loading") + let start_date = $('#start_date').val() + let comment = $('#comment-input').val() + let update = { + start_date, + comment + } + + window.makeRequest( "POST", '/', { parts: jsObject.parts, update }, jsObject.rest_namespace ).done(function(data){ + window.location.reload() + }) + .fail(function(e) { + console.log(e) + jQuery('#error').html(e) + }) +}) diff --git a/magic-link/templates/starter-template.php b/magic-link/templates/starter-template.php new file mode 100644 index 0000000..655cbd3 --- /dev/null +++ b/magic-link/templates/starter-template.php @@ -0,0 +1,443 @@ + 'migrations-template', + 'text' => 'Migrations Template', + ]; + $types['default-options'][] = [ + 'value' => 'migrations-template', + 'text' => 'Migrations Template', + ]; + return $types; +}); + +add_action('dt_magic_link_template_load', function ( $template ) { + if ( isset( $template['type'] ) && $template['type'] === 'migrations-template' ) { + new Disciple_Tools_Magic_Links_Template_Migrations_Template( $template ); + } +} ); + +/** + * Class Disciple_Tools_Magic_Links_Templates + */ +class Disciple_Tools_Magic_Links_Template_Migrations_Template extends DT_Magic_Url_Base { + + protected $template_type = 'migrations-template'; + public $page_title = 'Migrations Template'; + public $page_description = 'Edit all connections to a given post'; + public $root = 'templates'; // @todo define the root of the url {yoursite}/root/type/key/action + public $type = 'template_id'; // Placeholder to be replaced with actual template ids + public $type_name = ''; + public $post_type = 'contacts'; // Main post type that the ML is linked to. + public $record_post_type = 'groups'; // Child post type determined by the connection field selected + private $post = null; + private $items = []; + private $meta_key = ''; + + public $show_bulk_send = true; + public $show_app_tile = true; + + private static $_instance = null; + public $meta = []; // Allows for instance specific data. + public $translatable = [ + 'query', + 'user', + 'contact' + ]; // Order of translatable flags to be checked. Translate on first hit..! + + private $template = null; + private $link_obj = null; + private $layout = null; + + public function __construct( $template = null ) { + + // only handle this template type + if ( empty( $template ) || $template['type'] !== $this->template_type ) { + return; + } + + $this->template = $template; + $this->post_type = $template['post_type']; + $this->type = array_map( 'sanitize_key', wp_unslash( explode( '_', $template['id'] ) ) )[1]; + $this->type_name = $template['name']; + $this->page_title = $template['name']; + $this->page_description = ''; + + if ( !isset( $this->template['record_type'] ) ) { + $this->template['record_type'] = $this->record_post_type; + } + + /** + * Specify metadata structure, specific to the processing of current + * magic link class type. + * + * - meta: Magic link plugin related data. + * - app_type: Flag indicating type to be processed by magic link plugin. + * - class_type: Flag indicating template class type. + */ + + $show_in_apps = false; + + if ( $template['post_type'] == 'contacts' ) { + $show_in_apps = true; + } + + $this->meta = [ + 'app_type' => 'magic_link', + 'class_type' => 'template', + 'show_in_home_apps' => $show_in_apps, + 'icon' => 'mdi mdi-account-network', + ]; + + /** + * Once adjustments have been made, proceed with parent instantiation! + */ + + $this->meta_key = $this->root . '_' . $this->type; + parent::__construct(); + add_action( 'rest_api_init', [ $this, 'add_endpoints' ] ); + + /** + * Test magic link parts are registered and have valid elements. + */ + + if ( ! $this->check_parts_match() ) { + return; + } + + /** + * Attempt to load sooner, rather than later; corresponding post record details. + */ + + $this->post = DT_Posts::get_post( $this->post_type, $this->parts['post_id'], true, false ); + + // @todo remove example and replace with DT_Posts::list_posts() + $data = []; + $data[] = [ + 'ID' => '123', + 'name' => 'List item 1', + 'last_modified' => [ + 'timestamp' => 1735678800, + ], + ]; + $data[] = [ + 'ID' => '124', + 'name' => 'List item 2', + 'last_modified' => [ + 'timestamp' => 1735678800, + ], + ]; + $this->items = [ + 'posts' => $data + ]; + + /** + * Attempt to load corresponding link object, if a valid incoming id has been detected. + */ + + $this->link_obj = Disciple_Tools_Bulk_Magic_Link_Sender_API::fetch_option_link_obj( $this->fetch_incoming_link_param( 'id' ) ); + + // Revert back to dt translations + $this->hard_switch_to_default_dt_text_domain(); + + // Initialize layout front-end + $this->layout = new Disciple_Tools_Magic_Links_Layout_List_Detail( + $this->template, + $this->post, + $this->link_obj + ); + + /** + * Load if valid url + */ + + add_action( 'dt_blank_body', [ $this, 'body' ] ); + add_filter( 'dt_magic_url_base_allowed_css', [ $this, 'dt_magic_url_base_allowed_css' ], 10, 1 ); + add_filter( 'dt_magic_url_base_allowed_js', [ $this, 'dt_magic_url_base_allowed_js' ], 10, 1 ); + add_action( 'wp_enqueue_scripts', [ $this, 'wp_enqueue_scripts' ], 100 ); + add_filter( 'dt_can_update_permission', [ $this, 'can_update_permission_filter' ], 10, 3 ); + } + + // Ensure template fields remain editable + public function can_update_permission_filter( $has_permission, $post_id, $post_type ) { + return true; + } + + public function wp_enqueue_scripts() { + $this->layout->wp_enqueue_scripts(); + + Disciple_Tools_Bulk_Magic_Link_Sender_API::enqueue_magic_link_utilities_script(); + } + + public function dt_magic_url_base_allowed_js( $allowed_js ) { + $allowed_js[] = Disciple_Tools_Bulk_Magic_Link_Sender_API::get_magic_link_utilities_script_handle(); + + return $this->layout->allowed_js( $allowed_js ); + } + + public function dt_magic_url_base_allowed_css( $allowed_css ) { + return $this->layout->allowed_css( $allowed_css ); + } + + /** + * Writes javascript to the footer + * + * @see DT_Magic_Url_Base()->footer_javascript() for default state + */ + public function footer_javascript() { + $this->layout->footer_javascript( $this->parts, $this->items ); + } + + public function body() { + $this->layout->body(); + } + + /** + * Register REST Endpoints + * @link https://github.com/DiscipleTools/disciple-tools-theme/wiki/Site-to-Site-Link for outside of wordpress authentication + */ + public function add_endpoints() { + $namespace = $this->root . '/v1'; + register_rest_route( + $namespace, '/' . $this->type . '/post', [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'get_post' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + $magic = new DT_Magic_URL( $this->root ); + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/' . $this->type . '/update', [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'update_record' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + $magic = new DT_Magic_URL( $this->root ); + + $params = $request->get_params(); + + $permissions = $this->check_permissions( $params['parts']['post_id'], $params['post_id'] ); + if ( !$permissions ) { + return false; + } + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/' . $this->type . '/comment', [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'new_comment' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + $magic = new DT_Magic_URL( $this->root ); + + $params = $request->get_params(); + + $permissions = $this->check_permissions( $params['parts']['post_id'], $params['post_id'] ); + if ( !$permissions ) { + return false; + } + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + register_rest_route( + $namespace, '/' . $this->type . '/sort_post', [ + [ + 'methods' => 'POST', + 'callback' => [ $this, 'sorted_list_posts' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + $magic = new DT_Magic_URL( $this->root ); + + $params = $request->get_params(); + + $permissions = $this->check_permissions( $params['parts']['post_id'], $params['post_id'] ); + if ( !$permissions ) { + return false; + } + + return $magic->verify_rest_endpoint_permissions_on_post( $request ); + }, + ], + ] + ); + } + + public function check_permissions( $post_id, $connection_id ) { + + // if connection is actually the main post id, we're good + if ( strval( $post_id ) === strval( $connection_id ) ) { + return true; + } + + //set query fields to search for our post_id + $query_fields = []; + //todo: based on list of posts that are accessible, verify current user + // has permission to edit the given connection_id + + //get related records that have our query fields + $this->items = DT_Posts::list_posts( $this->record_post_type, [ + 'limit' => 1000, + 'fields' => [ + $query_fields + ] + ], false ); + + //return true if the post_id in the request is in the list + foreach ( $this->items['posts'] as $item ) { + if ( strval( $connection_id ) === strval( $item['ID'] ) ) { + return true; + } + } + return false; + } + + public function get_post( WP_REST_Request $request ){ + $params = $request->get_params(); + if ( !isset( $params['post_type'], $params['post_id'], $params['parts'], $params['action'], $params['comment_count'] ) ){ + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + // Sanitize and fetch user/post id + $params = dt_recursive_sanitize_array( $params ); + + // Update logged-in user state if required accordingly, based on their sys_type + if ( !is_user_logged_in() ) { + DT_ML_Helper::update_user_logged_in_state(); + } + + return [ + 'success' => true, + 'post' => $this->items['posts'][0], + 'comments' => [], + ]; + } + + public function update_record( WP_REST_Request $request ){ + $params = $request->get_params(); + if ( !isset( $params['post_id'], $params['post_type'], $params['parts'], $params['action'], $params['fields'] ) ){ + return new WP_Error( __METHOD__, 'Missing core parameters', [ 'status' => 400 ] ); + } + + // Sanitize and fetch user id + $params = dt_recursive_sanitize_array( $params ); + + // Update logged-in user state, if required + if ( !is_user_logged_in() ){ + DT_ML_Helper::update_user_logged_in_state(); + } + + $updates = []; + + //todo: handle all input fields + /* + foreach ( $params['fields']['dt'] ?? [] as $field ) { + } + */ + + // Update specified post record + if ( empty( $params['post_id'] ) ) { + // if ID is empty ("0", 0, or generally falsy), create a new post + $updates['type'] = 'access'; + + $updated_post = DT_Posts::create_post( $params['post_type'], $updates, false, false ); + } else { + // dt_write_log( json_encode( $updates ) ); + $updated_post = DT_Posts::update_post( $params['post_type'], $params['post_id'], $updates, false, false ); + } + + if ( empty( $updated_post ) || is_wp_error( $updated_post ) ) { + dt_write_log( $updated_post ); + return [ + 'success' => false, + 'message' => 'Unable to update/create contact record details!' + ]; + } + + // Next, any identified custom fields, are to be added as comments + foreach ( $params['fields']['custom'] ?? [] as $field ) { + $field = dt_recursive_sanitize_array( $field ); + if ( ! empty( $field['value'] ) ) { + $updated_comment = DT_Posts::add_post_comment( $updated_post['post_type'], $updated_post['ID'], $field['value'], 'comment', [], false ); + if ( empty( $updated_comment ) || is_wp_error( $updated_comment ) ) { + return [ + 'success' => false, + 'message' => 'Unable to add comment to record details!' + ]; + } + } + } + + // Next, dispatch submission notification, accordingly; always send by default. + if ( isset( $params['send_submission_notifications'] ) && $params['send_submission_notifications'] && isset( $updated_post['assigned_to'], $updated_post['assigned_to']['id'], $updated_post['assigned_to']['display'] ) ) { + $default_comment = sprintf( __( '%s Updates Submitted', 'disciple_tools' ), $params['template_name'] ); + $submission_comment = '@[' . $updated_post['assigned_to']['display'] . '](' . $updated_post['assigned_to']['id'] . ') ' . $default_comment; + DT_Posts::add_post_comment( $updated_post['post_type'], $updated_post['ID'], $submission_comment, 'comment', [], false ); + } + + // Finally, return successful response + return [ + 'success' => true, + 'message' => '', + 'post' => $updated_post, + ]; + } + + public function new_comment( WP_REST_Request $request ){ + $params = $request->get_params(); + if ( !isset( $params['post_type'], $params['post_id'], $params['parts'], $params['action'] ) ){ + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + // Sanitize and fetch user id + $params = dt_recursive_sanitize_array( $params ); + + // Update logged-in user state, if required + if ( !is_user_logged_in() ){ + DT_ML_Helper::update_user_logged_in_state(); + } + + $post = DT_Posts::get_post( $params['post_type'], $params['post_id'], false, false ); + //$params['comment'] + DT_Posts::add_post_comment( $post['post_type'], $post['ID'], $params['comment'], 'comment', [], false ); + + return [ + 'success' => true, + 'message' => '', + 'post' => $post, + ]; + } + + public function sorted_list_posts( WP_REST_Request $request ){ + $params = $request->get_params(); + if ( !isset( $params['post_type'], $params['post_id'], $params['parts'], $params['action'] ) ){ + return new WP_Error( __METHOD__, 'Missing parameters', [ 'status' => 400 ] ); + } + + // Sanitize and fetch user id + $params = dt_recursive_sanitize_array( $params ); + + // Update logged-in user state, if required + if ( !is_user_logged_in() ){ + DT_ML_Helper::update_user_logged_in_state(); + } + + //todo: get sorted items using DT_Posts::list_posts() + + return $this->items; + } +} diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..32dec0c --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,251 @@ + + + The coding standard for disciple-tools theme + + + + + + . + + vendor/* + includes/admin/libraries/plugin-update-checker/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..54626a4 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + ./test/ + ./test/after-unit-tests.php + ./test/unit-test-sample.php + + + diff --git a/post-type/loader.php b/post-type/loader.php new file mode 100644 index 0000000..1908513 --- /dev/null +++ b/post-type/loader.php @@ -0,0 +1,38 @@ + __( 'Migration', 'disciple-tools-migration' ), + 'enabled' => true, + 'locked' => true, + 'prerequisites' => [ 'contacts_base' ], + 'post_type' => 'migrations', + 'description' => __( 'Default migration functionality', 'disciple-tools-migration' ) + ]; + + return $modules; +}, 20, 1 ); + +require_once 'module-base.php'; +Disciple_Tools_Migration_Base::instance(); + +/** + * @todo require_once and load additional modules + */ diff --git a/post-type/module-base.php b/post-type/module-base.php new file mode 100644 index 0000000..5ccd133 --- /dev/null +++ b/post-type/module-base.php @@ -0,0 +1,583 @@ +single_name = __( 'Migration', 'disciple-tools-migration' ); + $this->plural_name = __( 'Migrations', 'disciple-tools-migration' ); + + if ( class_exists( 'Disciple_Tools_Post_Type_Template' ) ) { + new Disciple_Tools_Post_Type_Template( $this->post_type, $this->single_name, $this->plural_name ); + } + } + + /** + * Set the singular and plural translations for this post types settings + * The add_filter is set onto a higher priority than the one in Disciple_tools_Post_Type_Template + * so as to enable localisation changes. Otherwise the system translation passed in to the custom post type + * will prevail. + */ + public function dt_get_post_type_settings( $settings, $post_type ){ + if ( $post_type === $this->post_type ){ + $settings['label_singular'] = __( 'Migration', 'disciple-tools-migration' ); + $settings['label_plural'] = __( 'Migrations', 'disciple-tools-migration' ); + } + return $settings; + } + + /** + * @todo define the permissions for the roles + * Documentation + * @link https://github.com/DiscipleTools/Documentation/blob/master/Theme-Core/roles-permissions.md#rolesd + */ + public function dt_set_roles_and_permissions( $expected_roles ){ + + if ( !isset( $expected_roles['my_migration_role'] ) ){ + $expected_roles['my_migration_role'] = [ + + 'label' => __( 'My Migration Role', 'disciple-tools-migration' ), + 'description' => 'Does something Cool', + 'permissions' => [ + 'access_contacts' => true, + // @todo more capabilities + ] + ]; + } + + // if the user can access contact they also can access this post type + foreach ( $expected_roles as $role => $role_value ){ + if ( isset( $expected_roles[$role]['permissions']['access_contacts'] ) && $expected_roles[$role]['permissions']['access_contacts'] ){ + $expected_roles[$role]['permissions']['access_' . $this->post_type ] = true; + $expected_roles[$role]['permissions']['create_' . $this->post_type] = true; + $expected_roles[$role]['permissions']['update_' . $this->post_type] = true; + } + } + + if ( isset( $expected_roles['dt_admin'] ) ){ + $expected_roles['dt_admin']['permissions']['view_any_'.$this->post_type ] = true; + $expected_roles['dt_admin']['permissions']['update_any_'.$this->post_type ] = true; + } + if ( isset( $expected_roles['administrator'] ) ){ + $expected_roles['administrator']['permissions']['view_any_'.$this->post_type ] = true; + $expected_roles['administrator']['permissions']['update_any_'.$this->post_type ] = true; + $expected_roles['administrator']['permissions']['delete_any_'.$this->post_type ] = true; + } + + return $expected_roles; + } + + /** + * @todo define fields + * Documentation + * @link https://github.com/DiscipleTools/Documentation/blob/master/Theme-Core/fields.md + */ + public function dt_custom_fields_settings( $fields, $post_type ){ + if ( $post_type === $this->post_type ){ + + + + /** + * @todo configure status appropriate to your post type + * @todo modify strings and add elements to default array + */ + $fields['status'] = [ + 'name' => __( 'Status', 'disciple-tools-migration' ), + 'description' => __( 'Set the current status.', 'disciple-tools-migration' ), + 'type' => 'key_select', + 'default' => [ + 'inactive' => [ + 'label' => __( 'Inactive', 'disciple-tools-migration' ), + 'description' => __( 'No longer active.', 'disciple-tools-migration' ), + 'color' => '#F43636' + ], + 'active' => [ + 'label' => __( 'Active', 'disciple-tools-migration' ), + 'description' => __( 'Is active.', 'disciple-tools-migration' ), + 'color' => '#4CAF50' + ], + ], + 'tile' => 'status', + 'icon' => get_template_directory_uri() . '/dt-assets/images/status.svg', + 'default_color' => '#366184', + 'show_in_table' => 10, + ]; + $fields['assigned_to'] = [ + 'name' => __( 'Assigned To', 'disciple-tools-migration' ), + 'description' => __( 'Select the main person who is responsible for reporting on this record.', 'disciple-tools-migration' ), + 'type' => 'user_select', + 'default' => '', + 'tile' => 'status', + 'icon' => get_template_directory_uri() . '/dt-assets/images/assigned-to.svg', + 'show_in_table' => 16, + ]; + + + + /** + * Common and recommended fields + */ + $fields['start_date'] = [ + 'name' => __( 'Start Date', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'date', + 'default' => time(), + 'tile' => 'details', + 'icon' => get_template_directory_uri() . '/dt-assets/images/date-start.svg', + ]; + $fields['end_date'] = [ + 'name' => __( 'End Date', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'date', + 'default' => '', + 'tile' => 'details', + 'icon' => get_template_directory_uri() . '/dt-assets/images/date-end.svg', + ]; + $fields['multi_select'] = [ + 'name' => __( 'Multi-Select', 'disciple-tools-migration' ), + 'description' => __( 'Multi Select Field', 'disciple-tools-migration' ), + 'type' => 'multi_select', + 'default' => [ + 'item_1' => [ + 'label' => __( 'Item 1', 'disciple-tools-migration' ), + 'description' => __( 'Item 1.', 'disciple-tools-migration' ), + ], + 'item_2' => [ + 'label' => __( 'Item 2', 'disciple-tools-migration' ), + 'description' => __( 'Item 2.', 'disciple-tools-migration' ), + ], + 'item_3' => [ + 'label' => __( 'Item 3', 'disciple-tools-migration' ), + 'description' => __( 'Item 3.', 'disciple-tools-migration' ), + ], + ], + 'tile' => 'details', + 'in_create_form' => true, + 'icon' => get_template_directory_uri() . '/dt-assets/images/languages.svg?v=2', + ]; + + $fields['contact_address'] = [ + 'name' => __( 'Address', 'disciple-tools-migration' ), + 'icon' => get_template_directory_uri() . '/dt-assets/images/house.svg', + 'type' => 'communication_channel', + 'tile' => 'details', + 'mapbox' => false, + 'customizable' => false + ]; + if ( DT_Mapbox_API::get_key() ){ + $fields['contact_address']['custom_display'] = true; + $fields['contact_address']['mapbox'] = true; + unset( $fields['contact_address']['tile'] ); + } + // end locations + + /** + * @todo this adds generational support to this post type. remove if not needed. + * generation and peer connection fields + */ + $fields['parents'] = [ + 'name' => __( 'Parents', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'connection', + 'post_type' => $this->post_type, + 'p2p_direction' => 'from', + 'p2p_key' => $this->post_type.'_to_'.$this->post_type, + 'tile' => 'connections', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-parent.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-group.svg', + ]; + $fields['peers'] = [ + 'name' => __( 'Peers', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'connection', + 'post_type' => $this->post_type, + 'p2p_direction' => 'any', + 'p2p_key' => $this->post_type.'_to_peers', + 'tile' => 'connections', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-peer.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-group.svg', + ]; + $fields['children'] = [ + 'name' => __( 'Children', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'connection', + 'post_type' => $this->post_type, + 'p2p_direction' => 'to', + 'p2p_key' => $this->post_type.'_to_'.$this->post_type, + 'tile' => 'connections', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-child.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-group.svg', + ]; + // end generations + + /** + * @todo this adds people groups support to this post type. remove if not needed. + * Connections to other post types + */ + $fields['peoplegroups'] = [ + 'name' => __( 'People Groups', 'disciple-tools-migration' ), + 'description' => __( 'The people groups connected to this record.', 'disciple-tools-migration' ), + 'type' => 'connection', + 'tile' => 'details', + 'post_type' => 'peoplegroups', + 'p2p_direction' => 'to', + 'p2p_key' => $this->post_type.'_to_peoplegroups', + 'icon' => get_template_directory_uri() . '/dt-assets/images/people-group.svg', + ]; + + $fields['contacts'] = [ + 'name' => __( 'Contacts', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'connection', + 'post_type' => 'contacts', + 'p2p_direction' => 'to', + 'p2p_key' => $this->post_type.'_to_contacts', + 'tile' => 'status', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-type.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-contact.svg', + 'show_in_table' => 35 + ]; + } + + /** + * @todo this adds connection to contacts. remove if not needed. + */ + if ( $post_type === 'contacts' ){ + $fields[$this->post_type] = [ + 'name' => $this->plural_name, + 'description' => '', + 'type' => 'connection', + 'post_type' => $this->post_type, + 'p2p_direction' => 'from', + 'p2p_key' => $this->post_type.'_to_contacts', + 'tile' => 'other', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-type.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-group.svg', + 'show_in_table' => 35 + ]; + } + + /** + * @todo this adds connection to groups. remove if not needed. + */ + if ( $post_type === 'groups' ){ + $fields[$this->post_type] = [ + 'name' => $this->plural_name, + 'description' => '', + 'type' => 'connection', + 'post_type' => $this->post_type, + 'p2p_direction' => 'from', + 'p2p_key' => $this->post_type.'_to_groups', + 'tile' => 'other', + 'icon' => get_template_directory_uri() . '/dt-assets/images/group-type.svg', + 'create-icon' => get_template_directory_uri() . '/dt-assets/images/add-group.svg', + 'show_in_table' => 35 + ]; + } + return $fields; + } + + /** + * @todo define tiles + * @link https://github.com/DiscipleTools/Documentation/blob/master/Theme-Core/field-and-tiles.md + */ + public function dt_details_additional_tiles( $tiles, $post_type = '' ){ + if ( $post_type === $this->post_type ){ + $tiles['connections'] = [ 'label' => __( 'Connections', 'disciple-tools-migration' ) ]; + $tiles['other'] = [ 'label' => __( 'Other', 'disciple-tools-migration' ) ]; + } + return $tiles; + } + + /** + * @todo define additional section content + * Documentation + * @link https://github.com/DiscipleTools/Documentation/blob/master/Theme-Core/field-and-tiles.md#add-custom-content + */ + public function dt_details_additional_section( $section, $post_type ){ + + if ( $post_type === $this->post_type && $section === 'other' ) { + $fields = DT_Posts::get_post_field_settings( $post_type ); + $post = DT_Posts::get_post( $this->post_type, get_the_ID() ); + ?> +
    + +
    +
    +

    Add information or custom fields here

    +
    + + post_type ){ +// if ( $field_key === "members" ){ +// // @todo change 'members' +// // execute your code here, if field key match +// } +// if ( $field_key === "coaches" ){ +// // @todo change 'coaches' +// // execute your code here, if field key match +// } +// } +// if ( $post_type === "contacts" && $field_key === $this->post_type ){ +// // execute your code here, if a change is made in contacts and a field key is matched +// } + } + + //action when a post connection is removed during create or update + public function post_connection_removed( $post_type, $post_id, $field_key, $value ){ +// if ( $post_type === $this->post_type ){ +// // execute your code here, if connection removed +// } + } + + //filter at the start of post update + public function dt_post_update_fields( $fields, $post_type, $post_id ){ +// if ( $post_type === $this->post_type ){ +// // execute your code here +// } + return $fields; + } + + + //filter when a comment is created + public function dt_comment_created( $post_type, $post_id, $comment_id, $type ){ + } + + // filter at the start of post creation + public function dt_post_create_fields( $fields, $post_type ){ + if ( $post_type === $this->post_type ){ + $post_fields = DT_Posts::get_post_field_settings( $post_type ); + if ( isset( $post_fields['status'] ) && !isset( $fields['status'] ) ){ + $fields['status'] = 'active'; + } + } + return $fields; + } + + //action when a post has been created + public function dt_post_created( $post_type, $post_id, $initial_fields ){ + } + + //list page filters function + + /** + * @todo adjust queries to support list counts + * Documentation + * @link https://github.com/DiscipleTools/Documentation/blob/master/Theme-Core/list-query.md + */ + private static function count_records_assigned_to_me_by_status(){ + global $wpdb; + $post_type = self::post_type(); + $current_user = get_current_user_id(); + + $results = $wpdb->get_results( $wpdb->prepare( " + SELECT status.meta_value as status, count(pm.post_id) as count + FROM $wpdb->postmeta pm + INNER JOIN $wpdb->posts a ON( a.ID = pm.post_id AND a.post_type = %s and a.post_status = 'publish' ) + INNER JOIN $wpdb->postmeta status ON ( status.post_id = pm.post_id AND status.meta_key = 'status' ) + WHERE pm.meta_key = 'assigned_to' + AND pm.meta_value = CONCAT( 'user-', %s ) + GROUP BY status.meta_value + ", $post_type, $current_user ), ARRAY_A); + + return $results; + } + + //list page filters function + private static function count_records_by_status(){ + global $wpdb; + $results = $wpdb->get_results($wpdb->prepare( " + SELECT status.meta_value as status, count(status.post_id) as count + FROM $wpdb->postmeta status + INNER JOIN $wpdb->posts a ON( a.ID = status.post_id AND a.post_type = %s and a.post_status = 'publish' ) + WHERE status.meta_key = 'status' + GROUP BY status.meta_value + ", self::post_type() ), ARRAY_A ); + + return $results; + } + + //build list page filters + public static function dt_user_list_filters( $filters, $post_type ){ + /** + * @todo process and build filter lists + */ + if ( $post_type === self::post_type() ){ + $records_assigned_to_me_by_status_counts = self::count_records_assigned_to_me_by_status(); + $fields = DT_Posts::get_post_field_settings( $post_type ); + /** + * Setup my filters + */ + $active_counts = []; + $status_counts = []; + $total_my = 0; + foreach ( $records_assigned_to_me_by_status_counts as $count ){ + $total_my += $count['count']; + dt_increment( $status_counts[$count['status']], $count['count'] ); + } + + // add assigned to me tab + $filters['tabs'][] = [ + 'key' => 'assigned_to_me', + 'label' => __( 'Assigned to me', 'disciple-tools-migration' ), + 'count' => $total_my, + 'order' => 20 + ]; + // add assigned to me filters + $filters['filters'][] = [ + 'ID' => 'my_all', + 'tab' => 'assigned_to_me', + 'name' => __( 'All', 'disciple-tools-migration' ), + 'query' => [ + 'assigned_to' => [ 'me' ], + 'sort' => 'status' + ], + 'count' => $total_my, + ]; + //add a filter for each status + foreach ( $fields['status']['default'] as $status_key => $status_value ) { + if ( isset( $status_counts[$status_key] ) ){ + $filters['filters'][] = [ + 'ID' => 'my_' . $status_key, + 'tab' => 'assigned_to_me', + 'name' => $status_value['label'], + 'query' => [ + 'assigned_to' => [ 'me' ], + 'status' => [ $status_key ], + 'sort' => '-post_date' + ], + 'count' => $status_counts[$status_key] + ]; + } + } + + if ( DT_Posts::can_view_all( self::post_type() ) ){ + $records_by_status_counts = self::count_records_by_status(); + $status_counts = []; + $total_all = 0; + foreach ( $records_by_status_counts as $count ){ + $total_all += $count['count']; + dt_increment( $status_counts[$count['status']], $count['count'] ); + } + + // add by Status Tab + $filters['tabs'][] = [ + 'key' => 'by_status', + 'label' => __( 'All By Status', 'disciple-tools-migration' ), + 'count' => $total_all, + 'order' => 30 + ]; + // add assigned to me filters + $filters['filters'][] = [ + 'ID' => 'all_status', + 'tab' => 'by_status', + 'name' => __( 'All', 'disciple-tools-migration' ), + 'query' => [ + 'sort' => '-post_date' + ], + 'count' => $total_all + ]; + + foreach ( $fields['status']['default'] as $status_key => $status_value ) { + if ( isset( $status_counts[$status_key] ) ){ + $filters['filters'][] = [ + 'ID' => 'all_' . $status_key, + 'tab' => 'by_status', + 'name' => $status_value['label'], + 'query' => [ + 'status' => [ $status_key ], + 'sort' => '-post_date' + ], + 'count' => $status_counts[$status_key] + ]; + } + } + } + } + return $filters; + } + + // access permission + public static function dt_filter_access_permissions( $permissions, $post_type ){ + if ( $post_type === self::post_type() ){ + if ( DT_Posts::can_view_all( $post_type ) ){ + $permissions = []; + } + } + return $permissions; + } + + // scripts + public function scripts(){ + if ( is_singular( $this->post_type ) && get_the_ID() && DT_Posts::can_view( $this->post_type, get_the_ID() ) ){ + $test = ''; + // @todo add enqueue scripts + } + } +} + + diff --git a/rest-api/rest-api.php b/rest-api/rest-api.php new file mode 100644 index 0000000..fbb3c3f --- /dev/null +++ b/rest-api/rest-api.php @@ -0,0 +1,453 @@ + WP_REST_Server::READABLE, + 'callback' => [ $this, 'capabilities' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + return $this->has_permission( $request ); + }, + ] + ); + + register_rest_route( + $namespace, + '/export', + [ + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => [ $this, 'export' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + return $this->has_permission( $request ); + }, + ] + ); + + register_rest_route( + $namespace, + '/records-preview', + [ + 'methods' => WP_REST_Server::READABLE, + 'callback' => [ $this, 'records_preview' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + return $this->has_permission( $request ); + }, + ] + ); + + register_rest_route( + $namespace, + '/records/(?P[a-zA-Z0-9_-]+)', + [ + 'methods' => WP_REST_Server::READABLE, + 'callback' => [ $this, 'records_batch' ], + 'permission_callback' => function ( WP_REST_Request $request ) { + return $this->has_permission( $request ); + }, + 'args' => [ + 'post_type' => [ + 'required' => true, + 'type' => 'string', + 'validate_callback' => function ( $param ) { + return is_string( $param ) && in_array( $param, array_keys( $this->get_allowed_record_types() ), true ); + }, + ], + 'offset' => [ + 'default' => 0, + 'sanitize_callback' => 'absint', + ], + 'limit' => [ + 'default' => 50, + 'sanitize_callback' => function ( $param ) { + $val = absint( $param ); + return min( max( 1, $val ), 100 ); + }, + ], + ], + ] + ); + } + + /** + * Returns a summary of what this site is configured to export. + * + * @param WP_REST_Request $request + * + * @return WP_REST_Response + */ + public function capabilities( WP_REST_Request $request ) : WP_REST_Response { + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) ) { + return new WP_REST_Response( + [ + 'enabled' => false, + 'message' => __( 'Migration admin menu is not available on this site.', 'disciple-tools-migration' ), + 'site_meta' => $this->get_site_meta(), + ], + 200 + ); + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + + $response = [ + 'enabled' => ! empty( $settings['enabled'] ), + 'mode' => $settings['mode'] ?? 'api', + 'allowed_items' => $settings['allowed_items'] ?? [], + 'site_meta' => $this->get_site_meta(), + 'plugin_capabilities' => [ + 'supports_api_mode' => true, + 'supports_file_mode' => true, + 'supports_records' => [ + 'contacts' => ! empty( $settings['allowed_items']['records']['contacts'] ), + 'groups' => ! empty( $settings['allowed_items']['records']['groups'] ), + ], + ], + ]; + + return new WP_REST_Response( $response, 200 ); + } + + /** + * Settings export endpoint (non-destructive). + * + * Builds a settings-only export payload similar to the downloadable exports, + * respecting the migration settings flags. Records are not included yet. + * + * @param WP_REST_Request $request + * + * @return WP_REST_Response + */ + public function export( WP_REST_Request $request ) : WP_REST_Response { + $body = $request->get_json_params(); + if ( ! is_array( $body ) ) { + $body = []; + } + + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) ) { + return new WP_REST_Response( + [ + 'message' => __( 'Migration admin menu is not available on this site.', 'disciple-tools-migration' ), + 'site_meta' => $this->get_site_meta(), + 'request' => $body, + ], + 200 + ); + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + $allowed = $settings['allowed_items'] ?? []; + $site_meta = $this->get_site_meta(); + $settings_export = [ + 'type' => 'api', + 'dt_tiles_settings' => [ 'values' => [] ], + 'dt_tiles_custom_settings' => [ 'values' => [] ], + 'dt_fields_settings' => [ 'values' => [] ], + 'dt_fields_custom_settings' => [ 'values' => [] ], + 'dt_post_types_settings' => [ 'values' => [] ], + 'dt_post_types_custom_settings' => [ 'values' => [] ], + 'dt_workflows_post_types' => [ 'values' => [] ], + 'dt_workflows_defaults' => [ 'values' => [] ], + ]; + + // Base post types configuration (without tiles/fields) when any structure-related export is enabled. + if ( ! empty( $allowed['tiles'] ) || ! empty( $allowed['fields'] ) || ! empty( $allowed['records'] ) ) { + $post_types = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $post_types[ $post_type ] ) ) { + $post_type_settings = DT_Posts::get_post_settings( $post_type, false ); + unset( $post_type_settings['tiles'], $post_type_settings['fields'] ); + $post_types[ $post_type ] = $post_type_settings; + } + } + $settings_export['dt_post_types_settings']['values'] = $post_types; + $settings_export['dt_post_types_custom_settings']['values'] = get_option( 'dt_custom_post_types', [] ); + } + + if ( ! empty( $allowed['tiles'] ) ) { + $tiles = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $tiles[ $post_type ] ) ) { + $tiles[ $post_type ] = DT_Posts::get_post_tiles( $post_type, false ); + } + } + $settings_export['dt_tiles_settings']['values'] = $tiles; + $settings_export['dt_tiles_custom_settings']['values'] = dt_get_option( 'dt_custom_tiles' ); + } + + if ( ! empty( $allowed['fields'] ) ) { + $fields = []; + foreach ( DT_Posts::get_post_types() as $post_type ) { + if ( ! isset( $fields[ $post_type ] ) ) { + $fields[ $post_type ] = DT_Posts::get_post_field_settings( $post_type, false, true ); + } + } + $settings_export['dt_fields_settings']['values'] = $fields; + $settings_export['dt_fields_custom_settings']['values'] = dt_get_option( 'dt_field_customizations' ); + } + + if ( ! empty( $allowed['workflows'] ) ) { + $post_types_raw = get_option( 'dt_workflows_post_types', '' ); + $defaults_raw = get_option( 'dt_workflows_defaults', '' ); + $settings_export['dt_workflows_post_types']['values'] = ! empty( $post_types_raw ) + ? json_decode( $post_types_raw, true ) + : []; + $settings_export['dt_workflows_defaults']['values'] = ! empty( $defaults_raw ) + ? json_decode( $defaults_raw, true ) + : []; + } + + $response = [ + 'site_meta' => $site_meta, + 'settings' => [ + 'enabled' => ! empty( $settings['enabled'] ), + 'mode' => $settings['mode'] ?? 'api', + 'allowed_items' => $allowed, + ], + 'export' => [ + 'dt_settings' => $settings_export, + ], + 'request' => $body, + 'note' => __( 'This is a non-destructive settings export payload. Records are not included yet and nothing is applied automatically.', 'disciple-tools-migration' ), + ]; + + return new WP_REST_Response( $response, 200 ); + } + + /** + * Records preview endpoint (non-destructive). + * + * Returns record counts for each enabled record post type. + * + * @param WP_REST_Request $request + * + * @return WP_REST_Response + */ + public function records_preview( WP_REST_Request $request ) : WP_REST_Response { + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) ) { + return new WP_REST_Response( + [ + 'message' => __( 'Migration admin menu is not available on this site.', 'disciple-tools-migration' ), + 'site_meta' => $this->get_site_meta(), + ], + 200 + ); + } + + $settings = Disciple_Tools_Migration_Menu::get_settings(); + $allowed = $settings['allowed_items']['records'] ?? []; + + $records = []; + + if ( ! empty( $allowed ) && is_array( $allowed ) ) { + foreach ( $allowed as $post_type => $enabled ) { + if ( ! $enabled ) { + continue; + } + + // Count posts for this post type (non-destructive). + $query = new WP_Query( + [ + 'post_type' => $post_type, + 'post_status' => 'any', + 'posts_per_page' => 1, + 'fields' => 'ids', + ] + ); + + $records[ $post_type ] = [ + 'count' => (int) ( $query->found_posts ?? 0 ), + ]; + } + } + + $response = [ + 'site_meta' => $this->get_site_meta(), + 'records' => $records, + 'note' => __( 'Non-destructive records preview; counts only.', 'disciple-tools-migration' ), + ]; + + return new WP_REST_Response( $response, 200 ); + } + + /** + * Returns post types allowed for record export based on migration settings. + * + * @return array + */ + protected function get_allowed_record_types() : array { + if ( ! class_exists( 'Disciple_Tools_Migration_Menu' ) ) { + return []; + } + $settings = Disciple_Tools_Migration_Menu::get_settings(); + $allowed = $settings['allowed_items']['records'] ?? []; + + return is_array( $allowed ) ? $allowed : []; + } + + /** + * Records batch endpoint (Server A). + * + * Returns a batch of full record data for the given post type. + * Used by Server B during import to pull records in chunks. + * + * @param WP_REST_Request $request + * + * @return WP_REST_Response + */ + public function records_batch( WP_REST_Request $request ) : WP_REST_Response { + $post_type = $request->get_param( 'post_type' ); + $offset = (int) $request->get_param( 'offset' ); + $limit = (int) $request->get_param( 'limit' ); + + $allowed = $this->get_allowed_record_types(); + if ( empty( $allowed[ $post_type ] ) ) { + return new WP_REST_Response( + [ + 'message' => __( 'Post type not allowed for migration.', 'disciple-tools-migration' ), + 'records' => [], + 'total' => 0, + 'offset' => $offset, + 'limit' => $limit, + 'has_more' => false, + ], + 403 + ); + } + + if ( ! class_exists( 'DT_Posts' ) ) { + return new WP_REST_Response( + [ 'message' => __( 'DT_Posts not available.', 'disciple-tools-migration' ), 'records' => [] ], + 500 + ); + } + + $query = [ + 'post_type' => $post_type, + 'post_status' => 'any', + 'posts_per_page' => $limit, + 'offset' => $offset, + 'orderby' => 'ID', + 'order' => 'ASC', + 'fields' => 'ids', + ]; + + $wp_query = new WP_Query( $query ); + $ids = $wp_query->posts ?? []; + $total = (int) ( $wp_query->found_posts ?? 0 ); + + $records = []; + foreach ( $ids as $post_id ) { + $post = DT_Posts::get_post( $post_type, (int) $post_id, true, false ); + if ( ! is_wp_error( $post ) && is_array( $post ) ) { + $records[] = $post; + } + } + + return new WP_REST_Response( + [ + 'records' => $records, + 'total' => $total, + 'offset' => $offset, + 'limit' => $limit, + 'has_more' => ( $offset + count( $records ) ) < $total, + ], + 200 + ); + } + + /** + * Builds a meta summary of the current site. + * + * @return array + */ + protected function get_site_meta() : array { + $wp_theme = wp_get_theme(); + + return [ + 'timestamp' => time(), + 'site_url' => get_site_url(), + 'wp_version' => get_bloginfo( 'version' ), + 'php_version' => phpversion(), + 'server' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '', + 'dt_version' => $wp_theme->version, + 'multisite' => is_multisite(), + ]; + } + + /** + * Permission callback for REST routes. + * + * For now this only allows authenticated users with appropriate capabilities. + * Site-to-site token-based access will be layered on in a later phase. + * + * @param WP_REST_Request $request + * + * @return bool + */ + public function has_permission( WP_REST_Request $request ) : bool { + $pass = false; + + foreach ( $this->permissions as $permission ) { + if ( current_user_can( $permission ) ) { + $pass = true; + break; + } + } + + return $pass; + } + + /** + * Singleton instance. + * + * @var Disciple_Tools_Migration_Endpoints|null + */ + private static $_instance = null; + + /** + * Returns the singleton instance. + * + * @return Disciple_Tools_Migration_Endpoints + */ + public static function instance() { + if ( is_null( self::$_instance ) ) { + self::$_instance = new self(); + } + return self::$_instance; + } // End instance() + + /** + * Constructor. + */ + public function __construct() { + add_action( 'rest_api_init', [ $this, 'add_api_routes' ] ); + } +} + +Disciple_Tools_Migration_Endpoints::instance(); diff --git a/site-link/custom-site-to-site-links.php b/site-link/custom-site-to-site-links.php new file mode 100644 index 0000000..8cfeec2 --- /dev/null +++ b/site-link/custom-site-to-site-links.php @@ -0,0 +1,40 @@ +type === $args['connection_type'] ) { + $args['capabilities'][] = 'create_' . $this->type; + $args['capabilities'][] = 'update_any_' . $this->type; + // @todo add other capabilities here + } + return $args; + } + + public function site_link_type( $type ) { + $type[$this->type] = __( 'Migrations' ); + return $type; + } +} +Disciple_Tools_Migration_Site_Links::instance(); diff --git a/spinner.svg b/spinner.svg new file mode 100644 index 0000000..5c09396 --- /dev/null +++ b/spinner.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/after-unit-tests.php b/test/after-unit-tests.php new file mode 100644 index 0000000..1f3d205 --- /dev/null +++ b/test/after-unit-tests.php @@ -0,0 +1,19 @@ +assertTrue( true ); + } + + public static function tearDownAfterClass(){ + global $wpdb; + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_activity_log" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_location_grid" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_notifications" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_reports" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_reportmeta" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_share" ); + $wpdb->query( "DROP TABLE IF EXISTS $wpdb->dt_post_user_meta" ); + } +} diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100755 index 0000000..1937d3a --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,51 @@ + [db-host] [wp-version] [skip-database-creation]" + exit 1 +fi + +DB_NAME=$1 +DB_USER=$2 +DB_PASS=$3 +DB_HOST=${4-localhost} +WP_VERSION=${5-latest} +SKIP_DB_CREATE=${6-false} + +PLUGIN_DIR=$(pwd ../.) +TMPDIR=${TMPDIR-/tmp} +TMPDIR=$(echo $TMPDIR | sed -e "s/\/$//") +WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib} +WP_CORE_DIR=${WP_CORE_DIR-$TMPDIR/wordpress} +WP_THEME_DIR=${WP_THEME_DIR-$TMPDIR/wordpress/wp-content/themes} +WP_PLUGINS_DIR=${WP_PLUGINS_DIR-$TMPDIR/wordpress/wp-content/plugins} + +download() { + if [ `which curl` ]; then + curl -s "$1" > "$2"; + elif [ `which wget` ]; then + wget -nv -O "$2" "$1" + fi +} + +if [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+\-(beta|RC)[0-9]+$ ]]; then + WP_BRANCH=${WP_VERSION%\-*} + WP_TESTS_TAG="branches/$WP_BRANCH" + +elif [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+$ ]]; then + WP_TESTS_TAG="branches/$WP_VERSION" +elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then + if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then + # version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x + WP_TESTS_TAG="tags/${WP_VERSION%??}" + else + WP_TESTS_TAG="tags/$WP_VERSION" + fi +elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then + WP_TESTS_TAG="trunk" +else + # http serves a single offer, whereas https serves multiple. we only want one + download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json + grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json + LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//') + if [[ -z "$LATEST_VERSION" ]]; then + echo "Latest WordPress version could not be found" + exit 1 + fi + WP_TESTS_TAG="tags/$LATEST_VERSION" +fi +set -ex + +install_wp() { + if [ -d $WP_CORE_DIR ]; then + return; + fi + + mkdir -p $WP_CORE_DIR + + if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then + mkdir -p $TMPDIR/wordpress-nightly + download https://wordpress.org/nightly-builds/wordpress-latest.zip $TMPDIR/wordpress-nightly/wordpress-nightly.zip + unzip -q $TMPDIR/wordpress-nightly/wordpress-nightly.zip -d $TMPDIR/wordpress-nightly/ + mv $TMPDIR/wordpress-nightly/wordpress/* $WP_CORE_DIR + else + if [ $WP_VERSION == 'latest' ]; then + local ARCHIVE_NAME='latest' + elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+ ]]; then + # https serves multiple offers, whereas http serves single. + download https://api.wordpress.org/core/version-check/1.7/ $TMPDIR/wp-latest.json + if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then + # version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x + LATEST_VERSION=${WP_VERSION%??} + else + # otherwise, scan the releases and get the most up to date minor version of the major release + local VERSION_ESCAPED=`echo $WP_VERSION | sed 's/\./\\\\./g'` + LATEST_VERSION=$(grep -o '"version":"'$VERSION_ESCAPED'[^"]*' $TMPDIR/wp-latest.json | sed 's/"version":"//' | head -1) + fi + if [[ -z "$LATEST_VERSION" ]]; then + local ARCHIVE_NAME="wordpress-$WP_VERSION" + else + local ARCHIVE_NAME="wordpress-$LATEST_VERSION" + fi + else + local ARCHIVE_NAME="wordpress-$WP_VERSION" + fi + download https://wordpress.org/${ARCHIVE_NAME}.tar.gz $TMPDIR/wordpress.tar.gz + tar --strip-components=1 -zxmf $TMPDIR/wordpress.tar.gz -C $WP_CORE_DIR + fi + + download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php +} + +install_test_suite() { + # portable in-place argument for both GNU sed and Mac OSX sed + if [[ $(uname -s) == 'Darwin' ]]; then + local ioption='-i.bak' + else + local ioption='-i' + fi + + # set up testing suite if it doesn't yet exist + if [ ! -d $WP_TESTS_DIR ]; then + # set up testing suite + mkdir -p $WP_TESTS_DIR + svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes + svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data + fi + + if [ ! -f wp-tests-config.php ]; then + download https://develop.svn.wordpress.org/${WP_TESTS_TAG}/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php + # remove all forward slashes in the end + WP_CORE_DIR=$(echo $WP_CORE_DIR | sed "s:/\+$::") + sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php + fi +} + +install_db() { + if [ ${SKIP_DB_CREATE} = "true" ]; then + return 0 + fi + + # parse DB_HOST for port or socket references + local PARTS=(${DB_HOST//\:/ }) + local DB_HOSTNAME=${PARTS[0]}; + local DB_SOCK_OR_PORT=${PARTS[1]}; + local EXTRA="" + + if ! [ -z $DB_HOSTNAME ] ; then + if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then + EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp" + elif ! [ -z $DB_SOCK_OR_PORT ] ; then + EXTRA=" --socket=$DB_SOCK_OR_PORT" + elif ! [ -z $DB_HOSTNAME ] ; then + EXTRA=" --host=$DB_HOSTNAME --protocol=tcp" + fi + fi + + # create database + mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA +} + +install_theme() { + DOWNLOAD_URL=$(curl -sL https://api.github.com/repos/DiscipleTools/disciple-tools-theme/releases/latest | jq -r '.assets[].browser_download_url') + curl -s -L --create-dirs "$DOWNLOAD_URL" -o disciple-tools-theme.zip + rm -rf $WP_THEME_DIR/disciple-tools-theme + unzip disciple-tools-theme -d $WP_THEME_DIR + rm disciple-tools-theme.zip +} + +install_plugin() { + ln -sf $PLUGIN_DIR $WP_PLUGINS_DIR/. +} + +install_wp +install_test_suite +install_theme +install_plugin +install_db + diff --git a/test/test_for_syntax_errors.sh b/test/test_for_syntax_errors.sh new file mode 100755 index 0000000..cd6220d --- /dev/null +++ b/test/test_for_syntax_errors.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +cd "$(dirname "${BASH_SOURCE[0]}")/../" + +if [ "$(php -r 'echo version_compare( phpversion(), "7.0", ">=" ) ? 1 : 0;')" != 1 ] ; then + php -l ../disciple-tools-migration.php + exit +fi + +found_error=0 + +while read -d '' filename ; do + + # php -l checks the file for syntax errors + php -l "$filename" || found_error=1 + +done < <(find . -path ./vendor -prune -o -name "*.php" -print0) + +exit $found_error diff --git a/test/test_installation.sh b/test/test_installation.sh new file mode 100755 index 0000000..86cdadb --- /dev/null +++ b/test/test_installation.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +# Test installing this plugin using the Wordpress CLI, with a command like this +# one: +# +# wp plugin install --activate (github link)/archive/master.zip +# +# If this fails, we know we have an issue that we need to fix to make the plugin +# installable again + + +set -x +set -e + +if [ "$GITHUB_REPOSITORY" = "" ] ; then + echo "GITHUB_REPOSITORY env variable not set" >&2 + exit 1 +fi + +tmpdir=$(mktemp -d) + +cd "$tmpdir" + +curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar +php wp-cli.phar --info +chmod +x wp-cli.phar + +# Set up basic Wordpress installation: +./wp-cli.phar core download +./wp-cli.phar config create --force --dbname=testdb --dbuser=user --dbhost=127.0.0.0 --dbpass=password +./wp-cli.phar core install --url=localhost --title=test --admin_user=admin --admin_email=example@example.com + +# Install plugin +./wp-cli.phar plugin install --activate "https://github.com/$GITHUB_REPOSITORY/archive/$GITHUB_SHA.zip" diff --git a/test/test_phpcs.sh b/test/test_phpcs.sh new file mode 100755 index 0000000..026ae56 --- /dev/null +++ b/test/test_phpcs.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +set -e + +cd "$(dirname "${BASH_SOURCE[0]}")/../" + +if [ "$(php -r 'echo version_compare( phpversion(), "7.0", ">=" ) ? 1 : 0;')" != 1 ] ; then + vendor/bin/phpcs disciple-tools-migration.php + exit +fi + +eval vendor/bin/phpcs diff --git a/test/testcase.php b/test/testcase.php new file mode 100644 index 0000000..49076a8 --- /dev/null +++ b/test/testcase.php @@ -0,0 +1,15 @@ +query( 'START TRANSACTION' ); + parent::setUp(); + } + + public function tearDown() { + global $wpdb; + $wpdb->query( 'ROLLBACK' ); + parent::tearDown(); + } +} diff --git a/test/unit-test-plugin.php b/test/unit-test-plugin.php new file mode 100644 index 0000000..9f8e66a --- /dev/null +++ b/test/unit-test-plugin.php @@ -0,0 +1,13 @@ +assertContains( + 'disciple-tools-migration/disciple-tools-migration.php', + get_option( 'active_plugins' ) + ); + } +} diff --git a/tile/custom-tile.php b/tile/custom-tile.php new file mode 100644 index 0000000..148f79b --- /dev/null +++ b/tile/custom-tile.php @@ -0,0 +1,300 @@ + __( 'Migrations', 'disciple-tools-migration' ) ]; + $tiles['a_beautiful_tile'] = [ 'label' => __( 'A Beautiful Tile', 'disciple-tools-migration' ) ]; + } + return $tiles; + } + + /** + * @param array $fields + * @param string $post_type + * @return array + */ + public function dt_custom_fields( array $fields, string $post_type = '' ) { + /** + * @todo set the post type + */ + if ( $post_type === 'contacts' || $post_type === 'migrations' ){ + /** + * @todo Add the fields that you want to include in your tile. + * + * Examples for creating the $fields array + * Contacts + * @link https://github.com/DiscipleTools/disciple-tools-theme/blob/256c9d8510998e77694a824accb75522c9b6ed06/dt-contacts/base-setup.php#L108 + * + * Groups + * @link https://github.com/DiscipleTools/disciple-tools-theme/blob/256c9d8510998e77694a824accb75522c9b6ed06/dt-groups/base-setup.php#L83 + */ + + /** + * This is an example of a text field + */ + $fields['disciple_tools_migration_text'] = [ + 'name' => __( 'Text', 'disciple-tools-migration' ), + 'description' => _x( 'Text', 'Optional Documentation', 'disciple-tools-migration' ), + 'type' => 'text', + 'default' => '', + 'tile' => 'disciple_tools_migration', + 'icon' => get_template_directory_uri() . '/dt-assets/images/edit.svg', + ]; + /** + * This is an example of a multiselect field + */ + $fields['disciple_tools_migration_multiselect'] = [ + 'name' => __( 'Multiselect', 'disciple-tools-migration' ), + 'default' => [ + 'one' => [ 'label' => __( 'One', 'disciple-tools-migration' ) ], + 'two' => [ 'label' => __( 'Two', 'disciple-tools-migration' ) ], + 'three' => [ 'label' => __( 'Three', 'disciple-tools-migration' ) ], + 'four' => [ 'label' => __( 'Four', 'disciple-tools-migration' ) ], + ], + 'tile' => 'disciple_tools_migration', + 'type' => 'multi_select', + 'hidden' => false, + 'icon' => get_template_directory_uri() . '/dt-assets/images/edit.svg', + ]; + /** + * This is an example of a key select field + */ + $fields['disciple_tools_migration_keyselect'] = [ + 'name' => 'Key Select', + 'type' => 'key_select', + 'tile' => 'disciple_tools_migration', + 'default' => [ + 'first' => [ + 'label' => _x( 'First', 'Key Select Label', 'disciple-tools-migration' ), + 'description' => _x( 'First Key Description', 'Training Status field description', 'disciple-tools-migration' ), + 'color' => '#ff9800' + ], + 'second' => [ + 'label' => _x( 'Second', 'Key Select Label', 'disciple-tools-migration' ), + 'description' => _x( 'Second Key Description', 'Training Status field description', 'disciple-tools-migration' ), + 'color' => '#4CAF50' + ], + 'third' => [ + 'label' => _x( 'Third', 'Key Select Label', 'disciple-tools-migration' ), + 'description' => _x( 'Third Key Description', 'Training Status field description', 'disciple-tools-migration' ), + 'color' => '#366184' + ], + ], + 'icon' => get_template_directory_uri() . '/dt-assets/images/edit.svg', + 'default_color' => '#366184', + 'select_cannot_be_empty' => true + ]; + + //test fields + $fields['number_test'] = [ + 'name' => __( 'Number field', 'disciple-tools-migration' ), + 'type' => 'number', + 'default' => 0, + 'tile' => 'a_beautiful_tile', + 'min_option' => '5', + ]; + $fields['number_test_private'] = [ + 'name' => __( 'Number field private', 'disciple-tools-migration' ), + 'type' => 'number', + 'default' => 0, + 'tile' => 'a_beautiful_tile', + 'private' => true, + 'max_option' => '200', + ]; + $fields['text_test'] = [ + 'name' => __( 'Text', 'disciple-tools-migration' ), + 'type' => 'text', + 'default' => 0, + 'tile' => 'a_beautiful_tile', + ]; + $fields['text_test_private'] = [ + 'name' => __( 'Text', 'disciple-tools-migration' ), + 'type' => 'text', + 'default' => 0, + 'tile' => 'a_beautiful_tile', + 'private' => true + ]; + $fields['contact_communication_channel_test'] = [ + 'name' => __( 'Communication Channel', 'disciple-tools-migration' ), + 'type' => 'communication_channel', + 'default' => 0, + 'tile' => 'a_beautiful_tile', + ]; + + $fields['user_select_test'] = [ + 'name' => __( 'User Select', 'disciple-tools-migration' ), + 'type' => 'user_select', + 'tile' => 'a_beautiful_tile' + ]; + $fields['array_test'] = [ + 'name' => __( 'Array', 'disciple-tools-migration' ), + 'type' => 'array', + 'tile' => 'a_beautiful_tile' + ]; + $fields['location_test'] = [ + 'name' => 'location field', + 'type' => 'location', + 'tile' => 'a_beautiful_tile' + ]; + $fields['date_test'] = [ + 'name' => __( ' Date Field', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'date', + 'default' => '', + 'tile' => 'a_beautiful_tile' + ]; + $fields['date_test_private'] = [ + 'name' => __( ' Date Field', 'disciple-tools-migration' ), + 'description' => '', + 'type' => 'date', + 'default' => '', + 'tile' => 'a_beautiful_tile', + 'private' => true + ]; + $fields['boolean_test'] = [ + 'name' => __( 'Boolean', 'disciple-tools-migration' ), + 'type' => 'boolean', + 'default' => false, + ]; + $fields['boolean_test_private'] = [ + 'name' => __( 'Boolean', 'disciple-tools-migration' ), + 'type' => 'boolean', + 'default' => false, + 'private' => true + ]; + $fields['multi_select_test'] = [ + 'name' => 'Random Options Multiselect', + 'type' => 'multi_select', + 'default' => [ + 'one' => [ 'label' => 'option 1' ], + 'two' => [ 'label' => 'option 2' ], + 'three' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + ]; + $fields['multi_select_test_private'] = [ + 'name' => 'Random Private Options', + 'type' => 'multi_select', + 'default' => [ + 'one_private' => [ 'label' => 'option 1' ], + 'two_private' => [ 'label' => 'option 2' ], + 'three_private' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + 'private' => true + ]; + $fields['key_select_test'] = [ + 'name' => 'Random Options Key Select', + 'type' => 'key_select', + 'default' => [ + 'one' => [ 'label' => 'option 1' ], + 'two' => [ 'label' => 'option 2' ], + 'three' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + ]; + $fields['key_select_test_private'] = [ + 'name' => 'Random Private Key Select Options', + 'type' => 'key_select', + 'default' => [ + 'one_private' => [ 'label' => 'option 1' ], + 'two_private' => [ 'label' => 'option 2' ], + 'three_private' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + 'private' => true + ]; + $fields['tags_test'] = [ + 'name' => 'Random Tags', + 'type' => 'tags', + 'default' => [ + 'one' => [ 'label' => 'option 1' ], + 'two' => [ 'label' => 'option 2' ], + 'three' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + ]; + $fields['tags_test_private'] = [ + 'name' => 'Random Tags Private', + 'type' => 'tags', + 'default' => [ + 'one' => [ 'label' => 'option 1' ], + 'two' => [ 'label' => 'option 2' ], + 'three' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + 'private' => true + ]; + + $fields['links_test'] = [ + 'name' => 'Links', + 'type' => 'link', + 'default' => [ + 'default' => [ 'label' => 'Default', ], + 'one' => [ 'label' => 'option 1' ], + 'two' => [ 'label' => 'option 2' ], + 'three' => [ 'label' => 'option 3' ], + ], + 'tile' => 'a_beautiful_tile', + ]; + } + return $fields; + } + + public function dt_add_section( $section, $post_type ) { + /** + * @todo set the post type and the section key that you created in the dt_details_additional_tiles() function + */ + if ( ( $post_type === 'contacts' || $post_type === 'migrations' ) && $section === 'disciple_tools_migration' ){ + /** + * These are two sets of key data: + * $this_post is the details for this specific post + * $post_type_fields is the list of the default fields for the post type + * + * You can pull any query data into this section and display it. + */ + $this_post = DT_Posts::get_post( $post_type, get_the_ID() ); + $post_type_fields = DT_Posts::get_post_field_settings( $post_type ); + ?> + + + +
    + + You can do a number of customizations here.

    + See post types and field keys and values: click here +
    + + +
  • + +
    + + +
    + + +

    Replace with your custom content

    + +
    + + + build_default_workflows_contacts( $workflows ); + break; + case 'groups': + $this->build_default_workflows_groups( $workflows ); + break; + case 'migrations': + $this->build_default_workflows_migration( $workflows ); + break; + } + + return $workflows; + } + + private function build_default_workflows_contacts( &$workflows ) { + } + + private function build_default_workflows_groups( &$workflows ) { + } + + private function build_default_workflows_migration( &$workflows ) { + $dt_fields = DT_Posts::get_post_field_settings( 'migrations' ); + + $workflows[] = (object) [ + 'id' => 'migration_00001', + 'name' => 'Migration Template Add Text On Creation', + 'enabled' => false, // Can be enabled via admin view + 'trigger' => Disciple_Tools_Workflows_Defaults::$trigger_created['id'], + 'conditions' => [ + Disciple_Tools_Workflows_Defaults::new_condition( Disciple_Tools_Workflows_Defaults::$condition_is_set, + [ + 'id' => 'name', + 'label' => $dt_fields['name']['name'] + ], [ + 'id' => '', + 'label' => '' + ] + ) + ], + 'actions' => [ + Disciple_Tools_Workflows_Defaults::new_action( Disciple_Tools_Workflows_Defaults::$action_update, + [ + 'id' => 'disciple_tools_migration_text', + 'label' => $dt_fields['disciple_tools_migration_text']['name'] + ], [ + 'id' => 'Auto Filled By Workflow Engine', + 'label' => 'Auto Filled By Workflow Engine' + ] + ) + ] + ]; + } +} + +Disciple_Tools_Migration_Workflows::instance();