From 36b80696e3111f5b80910b9e549773fd382543f2 Mon Sep 17 00:00:00 2001 From: Michel Velis Date: Mon, 1 Jul 2019 14:50:31 -0400 Subject: [PATCH] ## Features - added: support for email reminder, user will receive an email when license has expired - fixed: a bug where email will be send-out - added: custom fields to woocommece order - added: product type (license) for woocommerce - rebuilt my licenses in my account page - added: until version and current version to api - ui: change styles to match more wp interface --- CHANGELOG.md | 11 +- README.md | 18 +- admin/includes/cronjobs/slm-tasks.php | 30 +- .../plugin-update-checker/.editorconfig | 15 + .../plugin-update-checker/Puc/v4/Factory.php | 6 + .../Puc/v4p6/Autoloader.php | 49 + .../Puc/v4p6/DebugBar/Extension.php | 177 ++ .../Puc/v4p6/DebugBar/Panel.php | 165 ++ .../Puc/v4p6/DebugBar/PluginExtension.php | 33 + .../Puc/v4p6/DebugBar/PluginPanel.php | 38 + .../Puc/v4p6/DebugBar/ThemePanel.php | 21 + .../Puc/v4p6/Factory.php | 297 ++++ .../Puc/v4p6/InstalledPackage.php | 103 ++ .../Puc/v4p6/Metadata.php | 132 ++ .../Puc/v4p6/OAuthSignature.php | 100 ++ .../Puc/v4p6/Plugin/Info.php | 130 ++ .../Puc/v4p6/Plugin/Package.php | 184 ++ .../Puc/v4p6/Plugin/Ui.php | 277 +++ .../Puc/v4p6/Plugin/Update.php | 110 ++ .../Puc/v4p6/Plugin/UpdateChecker.php | 396 +++++ .../Puc/v4p6/Scheduler.php | 231 +++ .../Puc/v4p6/StateStore.php | 207 +++ .../Puc/v4p6/Theme/Package.php | 65 + .../Puc/v4p6/Theme/Update.php | 84 + .../Puc/v4p6/Theme/UpdateChecker.php | 142 ++ .../plugin-update-checker/Puc/v4p6/Update.php | 34 + .../Puc/v4p6/UpdateChecker.php | 926 ++++++++++ .../Puc/v4p6/UpgraderStatus.php | 199 +++ .../plugin-update-checker/Puc/v4p6/Utils.php | 69 + .../Puc/v4p6/Vcs/Api.php | 302 ++++ .../Puc/v4p6/Vcs/BaseChecker.php | 27 + .../Puc/v4p6/Vcs/BitBucketApi.php | 265 +++ .../Puc/v4p6/Vcs/GitHubApi.php | 413 +++++ .../Puc/v4p6/Vcs/GitLabApi.php | 297 ++++ .../Puc/v4p6/Vcs/PluginUpdateChecker.php | 213 +++ .../Puc/v4p6/Vcs/Reference.php | 49 + .../Puc/v4p6/Vcs/ThemeUpdateChecker.php | 118 ++ .../css/puc-debug-bar.css | 70 + .../plugin-update-checker/js/debug-bar.js | 52 + .../languages/plugin-update-checker-cs_CZ.mo | Bin 0 -> 1077 bytes .../languages/plugin-update-checker-cs_CZ.po | 45 + .../languages/plugin-update-checker-da_DK.mo | Bin 0 -> 1010 bytes .../languages/plugin-update-checker-da_DK.po | 42 + .../languages/plugin-update-checker-de_DE.mo | Bin 0 -> 980 bytes .../languages/plugin-update-checker-de_DE.po | 38 + .../languages/plugin-update-checker-fa_IR.mo | Bin 0 -> 1128 bytes .../languages/plugin-update-checker-fa_IR.po | 38 + .../languages/plugin-update-checker-fr_CA.mo | Bin 0 -> 1208 bytes .../languages/plugin-update-checker-fr_CA.po | 48 + .../languages/plugin-update-checker-fr_FR.mo | Bin 0 -> 1066 bytes .../languages/plugin-update-checker-fr_FR.po | 42 + .../languages/plugin-update-checker-hu_HU.mo | Bin 0 -> 982 bytes .../languages/plugin-update-checker-hu_HU.po | 41 + .../languages/plugin-update-checker-it_IT.mo | Bin 0 -> 989 bytes .../languages/plugin-update-checker-it_IT.po | 38 + .../languages/plugin-update-checker-ja.mo | Bin 0 -> 1105 bytes .../languages/plugin-update-checker-ja.po | 42 + .../languages/plugin-update-checker-nl_BE.mo | Bin 0 -> 1211 bytes .../languages/plugin-update-checker-nl_BE.po | 48 + .../languages/plugin-update-checker-nl_NL.mo | Bin 0 -> 1211 bytes .../languages/plugin-update-checker-nl_NL.po | 48 + .../languages/plugin-update-checker-pt_BR.mo | Bin 0 -> 1014 bytes .../languages/plugin-update-checker-pt_BR.po | 48 + .../languages/plugin-update-checker-sv_SE.mo | Bin 0 -> 1006 bytes .../languages/plugin-update-checker-sv_SE.po | 42 + .../languages/plugin-update-checker.pot | 49 + .../plugin-update-checker/license.txt | 7 + .../plugin-update-checker.php | 34 + .../vendor/Parsedown.php | 1538 +++++++++++++++++ .../vendor/ParsedownLegacy.php | 1535 ++++++++++++++++ .../vendor/readme-parser.php | 341 ++++ admin/includes/wpestores/slm-wpestores.php | 2 +- admin/slm-add-licenses.php | 27 +- admin/slm-admin-functions.php | 6 +- admin/slm-admin-init.php | 7 - admin/slm-integration-help-page.php | 174 +- admin/slm-lic-settings.php | 300 ++-- admin/slm-list-licenses-class.php | 72 +- admin/slm-manage-licenses.php | 20 +- admin/slm-subscribers.php | 14 +- includes/class-slm-installer.php | 21 +- includes/mails/expired.php | 251 +++ includes/slm-meta-boxes.php | 104 +- includes/slm-plugin-core.php | 44 +- includes/slm-scripts.php | 5 +- includes/slm-utility.php | 112 +- includes/slm-wizard.php | 2 + includes/wp-mail-class.php | 437 +++++ languages/softwarelicensemanager-es_ES.mo | Bin 0 -> 11210 bytes languages/softwarelicensemanager-es_ES.po | 495 ++++++ languages/softwarelicensemanager-es_US.mo | Bin 0 -> 11213 bytes languages/softwarelicensemanager-es_US.po | 495 ++++++ languages/softwarelicensemanager.pot | 454 +++++ nbproject/project.properties | 7 + nbproject/project.xml | 9 + public/assets/css/slm-front-end.css | 29 +- public/assets/js/wplm-custom-admin.js | 17 +- public/slm-add-menu-frontend.php | 228 +-- software-license-manager.php | 17 +- software-license-manager/addons/loader.php | 4 + .../addons/woocommerce/includes/emails.php | 55 + .../addons/woocommerce/includes/helper.php | 23 + .../addons/woocommerce/includes/purchase.php | 385 +++++ .../addons/woocommerce/includes/settings.php | 64 + .../addons/woocommerce/loader.php | 103 ++ .../client-side-examples/index.html | 0 .../sample-php-scripts/create-license.php | 27 + .../sample-plugin/slm-sample-plugin.php | 144 ++ software-license-manager/css/jquery-ui.css | 1225 +++++++++++++ .../includes/slm-api-listener.php | 350 ++++ .../includes/slm-api-utility.php | 57 + .../includes/slm-error-codes.php | 20 + .../includes/slm-init-time-tasks.php | 46 + .../includes/slm-meta-boxes.php | 64 + .../includes/slm-third-party-integration.php | 301 ++++ .../includes/slm-utility.php | 73 + software-license-manager/index.html | 0 software-license-manager/js/index.html | 0 .../js/wplm-custom-admin.js | 11 + .../menu/includes/index.html | 0 .../menu/includes/slm-list-table-class.php | 907 ++++++++++ software-license-manager/menu/index.html | 0 .../menu/slm-add-licenses.php | 394 +++++ .../menu/slm-admin-functions.php | 50 + .../menu/slm-admin-init.php | 25 + .../menu/slm-integration-help-page.php | 118 ++ .../menu/slm-lic-settings.php | 143 ++ .../menu/slm-list-licenses-class.php | 157 ++ .../menu/slm-manage-licenses.php | 49 + software-license-manager/slm_bootstrap.php | 51 + software-license-manager/slm_installer.php | 75 + software-license-manager/slm_plugin_core.php | 81 + .../emails/customer-completed-order.php | 27 - woocommerce/includes/class.php | 73 - woocommerce/includes/purchase.php | 47 +- woocommerce/includes/wc-slm.php | 4 +- 136 files changed, 17950 insertions(+), 671 deletions(-) create mode 100755 admin/includes/plugin-update-checker/.editorconfig create mode 100755 admin/includes/plugin-update-checker/Puc/v4/Factory.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Autoloader.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Extension.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Panel.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginExtension.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginPanel.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/ThemePanel.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Factory.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/InstalledPackage.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Metadata.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/OAuthSignature.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Info.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Package.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Ui.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Update.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Plugin/UpdateChecker.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Scheduler.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/StateStore.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Theme/Package.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Theme/Update.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Theme/UpdateChecker.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Update.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/UpdateChecker.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/UpgraderStatus.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Utils.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Api.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/BaseChecker.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/BitBucketApi.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitHubApi.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitLabApi.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/PluginUpdateChecker.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Reference.php create mode 100755 admin/includes/plugin-update-checker/Puc/v4p6/Vcs/ThemeUpdateChecker.php create mode 100755 admin/includes/plugin-update-checker/css/puc-debug-bar.css create mode 100755 admin/includes/plugin-update-checker/js/debug-bar.js create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-cs_CZ.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-cs_CZ.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-de_DE.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-de_DE.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_CA.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_CA.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-hu_HU.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-hu_HU.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-it_IT.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-it_IT.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.mo create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.po create mode 100755 admin/includes/plugin-update-checker/languages/plugin-update-checker.pot create mode 100755 admin/includes/plugin-update-checker/license.txt create mode 100755 admin/includes/plugin-update-checker/plugin-update-checker.php create mode 100755 admin/includes/plugin-update-checker/vendor/Parsedown.php create mode 100755 admin/includes/plugin-update-checker/vendor/ParsedownLegacy.php create mode 100755 admin/includes/plugin-update-checker/vendor/readme-parser.php create mode 100644 includes/mails/expired.php create mode 100644 includes/slm-wizard.php create mode 100644 includes/wp-mail-class.php create mode 100644 languages/softwarelicensemanager-es_ES.mo create mode 100644 languages/softwarelicensemanager-es_ES.po create mode 100644 languages/softwarelicensemanager-es_US.mo create mode 100644 languages/softwarelicensemanager-es_US.po create mode 100644 languages/softwarelicensemanager.pot create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml create mode 100644 software-license-manager/addons/loader.php create mode 100644 software-license-manager/addons/woocommerce/includes/emails.php create mode 100644 software-license-manager/addons/woocommerce/includes/helper.php create mode 100644 software-license-manager/addons/woocommerce/includes/purchase.php create mode 100644 software-license-manager/addons/woocommerce/includes/settings.php create mode 100644 software-license-manager/addons/woocommerce/loader.php create mode 100644 software-license-manager/client-side-examples/index.html create mode 100644 software-license-manager/client-side-examples/sample-php-scripts/create-license.php create mode 100644 software-license-manager/client-side-examples/sample-plugin/slm-sample-plugin.php create mode 100644 software-license-manager/css/jquery-ui.css create mode 100644 software-license-manager/includes/slm-api-listener.php create mode 100644 software-license-manager/includes/slm-api-utility.php create mode 100644 software-license-manager/includes/slm-error-codes.php create mode 100644 software-license-manager/includes/slm-init-time-tasks.php create mode 100644 software-license-manager/includes/slm-meta-boxes.php create mode 100644 software-license-manager/includes/slm-third-party-integration.php create mode 100644 software-license-manager/includes/slm-utility.php create mode 100644 software-license-manager/index.html create mode 100644 software-license-manager/js/index.html create mode 100644 software-license-manager/js/wplm-custom-admin.js create mode 100644 software-license-manager/menu/includes/index.html create mode 100644 software-license-manager/menu/includes/slm-list-table-class.php create mode 100644 software-license-manager/menu/index.html create mode 100644 software-license-manager/menu/slm-add-licenses.php create mode 100644 software-license-manager/menu/slm-admin-functions.php create mode 100644 software-license-manager/menu/slm-admin-init.php create mode 100644 software-license-manager/menu/slm-integration-help-page.php create mode 100644 software-license-manager/menu/slm-lic-settings.php create mode 100644 software-license-manager/menu/slm-list-licenses-class.php create mode 100644 software-license-manager/menu/slm-manage-licenses.php create mode 100644 software-license-manager/slm_bootstrap.php create mode 100644 software-license-manager/slm_installer.php create mode 100644 software-license-manager/slm_plugin_core.php delete mode 100644 woocommerce/emails/customer-completed-order.php delete mode 100644 woocommerce/includes/class.php diff --git a/CHANGELOG.md b/CHANGELOG.md index b0832ac..9949cc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,22 +7,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). -## [4.12.1](https://github.com/michelve/software-license-manager/compare/4.11.2...4.12.1) - 2019-06-17 - -### Commits - -- ### 4.12.1 [`4b3adc2`](https://github.com/michelve/software-license-manager/commit/4b3adc2a2687f008362fb864eb39a759fc3a22c3) -- ### 4.12.1 [`89acaa5`](https://github.com/michelve/software-license-manager/commit/89acaa5718721cfdce40fcab70036367d2592c11) -- added change-log and updated readme file [`123564f`](https://github.com/michelve/software-license-manager/commit/123564f08ba7877da99fb6f826b03dbfceed0795) -- security.md [`3d225ce`](https://github.com/michelve/software-license-manager/commit/3d225ceffe5a5e65049112098656198335d066f1) - ## [4.11.2](https://github.com/michelve/software-license-manager/compare/4.10.3...4.11.2) - 2019-06-12 ### Commits - upgraded jQuery ui version [`27fe73f`](https://github.com/michelve/software-license-manager/commit/27fe73fe555c4a9b5b3044042be7c8b66cd0f2bd) -## [4.10.4](https://github.com/michelve/software-license-manager/compare/4.12.1...4.10.4) - 2019-06-17 +## [4.10.4](https://github.com/michelve/software-license-manager/compare/4.11.2...4.10.4) - 2019-06-12 ## [4.10.3](https://github.com/michelve/software-license-manager/compare/3.6.2...4.10.3) - 2019-05-14 diff --git a/README.md b/README.md index f97bb61..531b57e 100755 --- a/README.md +++ b/README.md @@ -53,20 +53,20 @@ Changelog: [View changelog](https://github.com/michelve/software-license-manager ## Screenshots -Software License Manager +Software License Manager -Software License Manager +Software License Manager -Software License Manager +Software License Manager -Software License Manager +Software License Manager -Software License Manager +Software License Manager - + -Software License Manager +Software License Manager -Software License Manager +Software License Manager -Software License Manager +Software License Manager diff --git a/admin/includes/cronjobs/slm-tasks.php b/admin/includes/cronjobs/slm-tasks.php index c36bd08..6797753 100644 --- a/admin/includes/cronjobs/slm-tasks.php +++ b/admin/includes/cronjobs/slm-tasks.php @@ -1,28 +1,24 @@ 1*60, - 'display' => __('Every 1 minute'), +add_filter('cron_schedules', 'slm_check_expiration_daily'); +add_action('slm_expired_send_email_reminder', 'slm_run_lic_check'); + +// for dev +function slm_check_expiration_daily($schedules){ + $schedules['slm_daily'] = array( + 'interval' => 21600*4, + 'display' => __('Every day'), ); return $schedules; } - // send automatic scheduled email if (!wp_next_scheduled('slm_expired_send_email_reminder')) { - wp_schedule_event(time(), 'every_minute', 'slm_expired_send_email_reminder'); + wp_schedule_event(time(), 'slm_daily', 'slm_expired_send_email_reminder'); } -add_action('slm_expired_send_email_reminder', 'run_slm_lic_check'); - -function run_slm_lic_check(){ +function slm_run_lic_check(){ SLM_Utility::check_for_expired_lic(); -} \ No newline at end of file +} + + diff --git a/admin/includes/plugin-update-checker/.editorconfig b/admin/includes/plugin-update-checker/.editorconfig new file mode 100755 index 0000000..1b51cad --- /dev/null +++ b/admin/includes/plugin-update-checker/.editorconfig @@ -0,0 +1,15 @@ +[*] +charset=utf-8 +end_of_line=lf +insert_final_newline=false +indent_style=tab +tab_width=4 + +[{phpunit.xml.dist,*.jhm,*.xslt,*.xul,*.rng,*.xsl,*.xsd,*.ant,*.tld,*.fxml,*.jrxml,*.xml,*.jnlp,*.wsdl}] +indent_style=space +indent_size=4 + +[*.svg] +indent_style=space +indent_size=4 + diff --git a/admin/includes/plugin-update-checker/Puc/v4/Factory.php b/admin/includes/plugin-update-checker/Puc/v4/Factory.php new file mode 100755 index 0000000..1fd3f0f --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4/Factory.php @@ -0,0 +1,6 @@ +rootDir = dirname(__FILE__) . '/'; + $nameParts = explode('_', __CLASS__, 3); + $this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_'; + + $this->libraryDir = realpath($this->rootDir . '../..') . '/'; + $this->staticMap = array( + 'PucReadmeParser' => 'vendor/readme-parser.php', + 'Parsedown' => 'vendor/ParsedownLegacy.php', + ); + if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) { + $this->staticMap['Parsedown'] = 'vendor/Parsedown.php'; + } + + spl_autoload_register(array($this, 'autoload')); + } + + public function autoload($className) { + if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) { + /** @noinspection PhpIncludeInspection */ + include ($this->libraryDir . $this->staticMap[$className]); + return; + } + + if (strpos($className, $this->prefix) === 0) { + $path = substr($className, strlen($this->prefix)); + $path = str_replace('_', '/', $path); + $path = $this->rootDir . $path . '.php'; + + if (file_exists($path)) { + /** @noinspection PhpIncludeInspection */ + include $path; + } + } + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Extension.php b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Extension.php new file mode 100755 index 0000000..06f81c5 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Extension.php @@ -0,0 +1,177 @@ +updateChecker = $updateChecker; + if ( isset($panelClass) ) { + $this->panelClass = $panelClass; + } + + add_filter('debug_bar_panels', array($this, 'addDebugBarPanel')); + add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies')); + + add_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow')); + } + + /** + * Register the PUC Debug Bar panel. + * + * @param array $panels + * @return array + */ + public function addDebugBarPanel($panels) { + if ( $this->updateChecker->userCanInstallUpdates() ) { + $panels[] = new $this->panelClass($this->updateChecker); + } + return $panels; + } + + /** + * Enqueue our Debug Bar scripts and styles. + */ + public function enqueuePanelDependencies() { + wp_enqueue_style( + 'puc-debug-bar-style-v4', + $this->getLibraryUrl("/css/puc-debug-bar.css"), + array('debug-bar'), + '20171124' + ); + + wp_enqueue_script( + 'puc-debug-bar-js-v4', + $this->getLibraryUrl("/js/debug-bar.js"), + array('jquery'), + '20170516' + ); + } + + /** + * Run an update check and output the result. Useful for making sure that + * the update checking process works as expected. + */ + public function ajaxCheckNow() { + if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) { + return; + } + $this->preAjaxRequest(); + $update = $this->updateChecker->checkForUpdates(); + if ( $update !== null ) { + echo "An update is available:"; + echo '
', htmlentities(print_r($update, true)), '
'; + } else { + echo 'No updates found.'; + } + + $errors = $this->updateChecker->getLastRequestApiErrors(); + if ( !empty($errors) ) { + printf('

The update checker encountered %d API error%s.

', count($errors), (count($errors) > 1) ? 's' : ''); + + foreach (array_values($errors) as $num => $item) { + $wpError = $item['error']; + /** @var WP_Error $wpError */ + printf('

%d) %s

', $num + 1, esc_html($wpError->get_error_message())); + + echo '
'; + printf('
Error code:
%s
', esc_html($wpError->get_error_code())); + + if ( isset($item['url']) ) { + printf('
Requested URL:
%s
', esc_html($item['url'])); + } + + if ( isset($item['httpResponse']) ) { + if ( is_wp_error($item['httpResponse']) ) { + $httpError = $item['httpResponse']; + /** @var WP_Error $httpError */ + printf( + '
WordPress HTTP API error:
%s (%s)
', + esc_html($httpError->get_error_message()), + esc_html($httpError->get_error_code()) + ); + } else { + //Status code. + printf( + '
HTTP status:
%d %s
', + wp_remote_retrieve_response_code($item['httpResponse']), + wp_remote_retrieve_response_message($item['httpResponse']) + ); + + //Headers. + echo '
Response headers:
';
+							foreach (wp_remote_retrieve_headers($item['httpResponse']) as $name => $value) {
+								printf("%s: %s\n", esc_html($name), esc_html($value));
+							}
+							echo '
'; + + //Body. + $body = wp_remote_retrieve_body($item['httpResponse']); + if ( $body === '' ) { + $body = '(Empty response.)'; + } else if ( strlen($body) > self::RESPONSE_BODY_LENGTH_LIMIT ) { + $length = strlen($body); + $body = substr($body, 0, self::RESPONSE_BODY_LENGTH_LIMIT) + . sprintf("\n(Long string truncated. Total length: %d bytes.)", $length); + } + + printf('
Response body:
%s
', esc_html($body)); + } + } + echo '
'; + } + } + + exit; + } + + /** + * Check access permissions and enable error display (for debugging). + */ + protected function preAjaxRequest() { + if ( !$this->updateChecker->userCanInstallUpdates() ) { + die('Access denied'); + } + check_ajax_referer('puc-ajax'); + + error_reporting(E_ALL); + @ini_set('display_errors', 'On'); + } + + /** + * @param string $filePath + * @return string + */ + private function getLibraryUrl($filePath) { + $absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/')); + + //Where is the library located inside the WordPress directory structure? + $absolutePath = Puc_v4p6_Factory::normalizePath($absolutePath); + + $pluginDir = Puc_v4p6_Factory::normalizePath(WP_PLUGIN_DIR); + $muPluginDir = Puc_v4p6_Factory::normalizePath(WPMU_PLUGIN_DIR); + $themeDir = Puc_v4p6_Factory::normalizePath(get_theme_root()); + + if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) { + //It's part of a plugin. + return plugins_url(basename($absolutePath), $absolutePath); + } else if ( strpos($absolutePath, $themeDir) === 0 ) { + //It's part of a theme. + $relativePath = substr($absolutePath, strlen($themeDir) + 1); + $template = substr($relativePath, 0, strpos($relativePath, '/')); + $baseUrl = get_theme_root_uri($template); + + if ( !empty($baseUrl) && $relativePath ) { + return $baseUrl . '/' . $relativePath; + } + } + + return ''; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Panel.php b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Panel.php new file mode 100755 index 0000000..06a218d --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/Panel.php @@ -0,0 +1,165 @@ +'; + + public function __construct($updateChecker) { + $this->updateChecker = $updateChecker; + $title = sprintf( + 'PUC (%s)', + esc_attr($this->updateChecker->getUniqueName('uid')), + $this->updateChecker->slug + ); + parent::__construct($title); + } + + public function render() { + printf( + '
', + esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')), + esc_attr($this->updateChecker->slug), + esc_attr($this->updateChecker->getUniqueName('uid')), + esc_attr(wp_create_nonce('puc-ajax')) + ); + + $this->displayConfiguration(); + $this->displayStatus(); + $this->displayCurrentUpdate(); + + echo '
'; + } + + private function displayConfiguration() { + echo '

Configuration

'; + echo ''; + $this->displayConfigHeader(); + $this->row('Slug', htmlentities($this->updateChecker->slug)); + $this->row('DB option', htmlentities($this->updateChecker->optionName)); + + $requestInfoButton = $this->getMetadataButton(); + $this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox); + + $scheduler = $this->updateChecker->scheduler; + if ( $scheduler->checkPeriod > 0 ) { + $this->row('Automatic checks', 'Every ' . $scheduler->checkPeriod . ' hours'); + } else { + $this->row('Automatic checks', 'Disabled'); + } + + if ( isset($scheduler->throttleRedundantChecks) ) { + if ( $scheduler->throttleRedundantChecks && ($scheduler->checkPeriod > 0) ) { + $this->row( + 'Throttling', + sprintf( + 'Enabled. If an update is already available, check for updates every %1$d hours instead of every %2$d hours.', + $scheduler->throttledCheckPeriod, + $scheduler->checkPeriod + ) + ); + } else { + $this->row('Throttling', 'Disabled'); + } + } + + $this->updateChecker->onDisplayConfiguration($this); + + echo '
'; + } + + protected function displayConfigHeader() { + //Do nothing. This should be implemented in subclasses. + } + + protected function getMetadataButton() { + return ''; + } + + private function displayStatus() { + echo '

Status

'; + echo ''; + $state = $this->updateChecker->getUpdateState(); + $checkNowButton = ''; + if ( function_exists('get_submit_button') ) { + $checkNowButton = get_submit_button( + 'Check Now', + 'secondary', + 'puc-check-now-button', + false, + array('id' => $this->updateChecker->getUniqueName('check-now-button')) + ); + } + + if ( $state->getLastCheck() > 0 ) { + $this->row('Last check', $this->formatTimeWithDelta($state->getLastCheck()) . ' ' . $checkNowButton . $this->responseBox); + } else { + $this->row('Last check', 'Never'); + } + + $nextCheck = wp_next_scheduled($this->updateChecker->scheduler->getCronHookName()); + $this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck)); + + if ( $state->getCheckedVersion() !== '' ) { + $this->row('Checked version', htmlentities($state->getCheckedVersion())); + $this->row('Cached update', $state->getUpdate()); + } + $this->row('Update checker class', htmlentities(get_class($this->updateChecker))); + echo '
'; + } + + private function displayCurrentUpdate() { + $update = $this->updateChecker->getUpdate(); + if ( $update !== null ) { + echo '

An Update Is Available

'; + echo ''; + $fields = $this->getUpdateFields(); + foreach($fields as $field) { + if ( property_exists($update, $field) ) { + $this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field)); + } + } + echo '
'; + } else { + echo '

No updates currently available

'; + } + } + + protected function getUpdateFields() { + return array('version', 'download_url', 'slug',); + } + + private function formatTimeWithDelta($unixTime) { + if ( empty($unixTime) ) { + return 'Never'; + } + + $delta = time() - $unixTime; + $result = human_time_diff(time(), $unixTime); + if ( $delta < 0 ) { + $result = 'after ' . $result; + } else { + $result = $result . ' ago'; + } + $result .= ' (' . $this->formatTimestamp($unixTime) . ')'; + return $result; + } + + private function formatTimestamp($unixTime) { + return gmdate('Y-m-d H:i:s', $unixTime + (get_option('gmt_offset') * 3600)); + } + + public function row($name, $value) { + if ( is_object($value) || is_array($value) ) { + $value = '
' . htmlentities(print_r($value, true)) . '
'; + } else if ($value === null) { + $value = 'null'; + } + printf('%1$s %2$s', $name, $value); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginExtension.php b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginExtension.php new file mode 100755 index 0000000..c9462ec --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginExtension.php @@ -0,0 +1,33 @@ +updateChecker->getUniqueName('uid') ) { + return; + } + $this->preAjaxRequest(); + $info = $this->updateChecker->requestInfo(); + if ( $info !== null ) { + echo 'Successfully retrieved plugin info from the metadata URL:'; + echo '
', htmlentities(print_r($info, true)), '
'; + } else { + echo 'Failed to retrieve plugin info from the metadata URL.'; + } + exit; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginPanel.php b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginPanel.php new file mode 100755 index 0000000..47a106e --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/PluginPanel.php @@ -0,0 +1,38 @@ +row('Plugin file', htmlentities($this->updateChecker->pluginFile)); + parent::displayConfigHeader(); + } + + protected function getMetadataButton() { + $requestInfoButton = ''; + if ( function_exists('get_submit_button') ) { + $requestInfoButton = get_submit_button( + 'Request Info', + 'secondary', + 'puc-request-info-button', + false, + array('id' => $this->updateChecker->getUniqueName('request-info-button')) + ); + } + return $requestInfoButton; + } + + protected function getUpdateFields() { + return array_merge( + parent::getUpdateFields(), + array('homepage', 'upgrade_notice', 'tested',) + ); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/ThemePanel.php b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/ThemePanel.php new file mode 100755 index 0000000..ed2734f --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/DebugBar/ThemePanel.php @@ -0,0 +1,21 @@ +row('Theme directory', htmlentities($this->updateChecker->directoryName)); + parent::displayConfigHeader(); + } + + protected function getUpdateFields() { + return array_merge(parent::getUpdateFields(), array('details_url')); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Factory.php b/admin/includes/plugin-update-checker/Puc/v4p6/Factory.php new file mode 100755 index 0000000..712035d --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Factory.php @@ -0,0 +1,297 @@ + 'Plugin Name'), 'plugin'); + return !empty($headers['Name']); + } + + return false; + } + + /** + * Get the name of the theme's directory from a full path to a file inside that directory. + * E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo". + * + * Note that subdirectories are currently not supported. For example, + * "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL. + * + * @param string $absolutePath Normalized path. + * @return string|null Directory name, or NULL if the path doesn't point to a theme. + */ + protected static function getThemeDirectoryName($absolutePath) { + if ( is_file($absolutePath) ) { + $absolutePath = dirname($absolutePath); + } + + if ( file_exists($absolutePath . '/style.css') ) { + return basename($absolutePath); + } + return null; + } + + /** + * Get the name of the hosting service that the URL points to. + * + * @param string $metadataUrl + * @return string|null + */ + private static function getVcsService($metadataUrl) { + $service = null; + + //Which hosting service does the URL point to? + $host = parse_url($metadataUrl, PHP_URL_HOST); + $path = parse_url($metadataUrl, PHP_URL_PATH); + + //Check if the path looks like "/user-name/repository". + //For GitLab.com it can also be "/user/group1/group2/.../repository". + $repoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@'; + if ( $host === 'gitlab.com' ) { + $repoRegex = '@^/?(?:[^/#?&]++/){1,20}(?:[^/#?&]++)/?$@'; + } + if ( preg_match($repoRegex, $path) ) { + $knownServices = array( + 'github.com' => 'GitHub', + 'bitbucket.org' => 'BitBucket', + 'gitlab.com' => 'GitLab', + ); + if ( isset($knownServices[$host]) ) { + $service = $knownServices[$host]; + } + } + + return apply_filters('puc_get_vcs_service', $service, $host, $path, $metadataUrl); + } + + /** + * Get the latest version of the specified class that has the same major version number + * as this factory class. + * + * @param string $class Partial class name. + * @return string|null Full class name. + */ + protected static function getCompatibleClassVersion($class) { + if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) { + return self::$classVersions[$class][self::$latestCompatibleVersion]; + } + return null; + } + + /** + * Get the specific class name for the latest available version of a class. + * + * @param string $class + * @return null|string + */ + public static function getLatestClassVersion($class) { + if ( !self::$sorted ) { + self::sortVersions(); + } + + if ( isset(self::$classVersions[$class]) ) { + return reset(self::$classVersions[$class]); + } else { + return null; + } + } + + /** + * Sort available class versions in descending order (i.e. newest first). + */ + protected static function sortVersions() { + foreach ( self::$classVersions as $class => $versions ) { + uksort($versions, array(__CLASS__, 'compareVersions')); + self::$classVersions[$class] = $versions; + } + self::$sorted = true; + } + + protected static function compareVersions($a, $b) { + return -version_compare($a, $b); + } + + /** + * Register a version of a class. + * + * @access private This method is only for internal use by the library. + * + * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'. + * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'. + * @param string $version Version number, e.g. '1.2'. + */ + public static function addVersion($generalClass, $versionedClass, $version) { + if ( empty(self::$myMajorVersion) ) { + $nameParts = explode('_', __CLASS__, 3); + self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1); + } + + //Store the greatest version number that matches our major version. + $components = explode('.', $version); + if ( $components[0] === self::$myMajorVersion ) { + + if ( + empty(self::$latestCompatibleVersion) + || version_compare($version, self::$latestCompatibleVersion, '>') + ) { + self::$latestCompatibleVersion = $version; + } + + } + + if ( !isset(self::$classVersions[$generalClass]) ) { + self::$classVersions[$generalClass] = array(); + } + self::$classVersions[$generalClass][$version] = $versionedClass; + self::$sorted = false; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/InstalledPackage.php b/admin/includes/plugin-update-checker/Puc/v4p6/InstalledPackage.php new file mode 100755 index 0000000..da7b17b --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/InstalledPackage.php @@ -0,0 +1,103 @@ +updateChecker = $updateChecker; + } + + /** + * Get the currently installed version of the plugin or theme. + * + * @return string|null Version number. + */ + abstract public function getInstalledVersion(); + + /** + * Get the full path of the plugin or theme directory (without a trailing slash). + * + * @return string + */ + abstract public function getAbsoluteDirectoryPath(); + + /** + * Check whether a regular file exists in the package's directory. + * + * @param string $relativeFileName File name relative to the package directory. + * @return bool + */ + public function fileExists($relativeFileName) { + return is_file( + $this->getAbsoluteDirectoryPath() + . DIRECTORY_SEPARATOR + . ltrim($relativeFileName, '/\\') + ); + } + + /* ------------------------------------------------------------------- + * File header parsing + * ------------------------------------------------------------------- + */ + + /** + * Parse plugin or theme metadata from the header comment. + * + * This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php. + * It's intended as a utility for subclasses that detect updates by parsing files in a VCS. + * + * @param string|null $content File contents. + * @return string[] + */ + public function getFileHeader($content) { + $content = (string)$content; + + //WordPress only looks at the first 8 KiB of the file, so we do the same. + $content = substr($content, 0, 8192); + //Normalize line endings. + $content = str_replace("\r", "\n", $content); + + $headers = $this->getHeaderNames(); + $results = array(); + foreach ($headers as $field => $name) { + $success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches); + + if ( ($success === 1) && $matches[1] ) { + $value = $matches[1]; + if ( function_exists('_cleanup_header_comment') ) { + $value = _cleanup_header_comment($value); + } + $results[$field] = $value; + } else { + $results[$field] = ''; + } + } + + return $results; + } + + /** + * @return array Format: ['HeaderKey' => 'Header Name'] + */ + abstract protected function getHeaderNames(); + + /** + * Get the value of a specific plugin or theme header. + * + * @param string $headerName + * @return string Either the value of the header, or an empty string if the header doesn't exist. + */ + abstract public function getHeaderValue($headerName); + + } +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Metadata.php b/admin/includes/plugin-update-checker/Puc/v4p6/Metadata.php new file mode 100755 index 0000000..4940f4a --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Metadata.php @@ -0,0 +1,132 @@ +validateMetadata($apiResponse); + if ( is_wp_error($valid) ){ + do_action('puc_api_error', $valid); + trigger_error($valid->get_error_message(), E_USER_NOTICE); + return false; + } + + foreach(get_object_vars($apiResponse) as $key => $value){ + $target->$key = $value; + } + + return true; + } + + /** + * No validation by default! Subclasses should check that the required fields are present. + * + * @param StdClass $apiResponse + * @return bool|WP_Error + */ + protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) { + return true; + } + + /** + * Create a new instance by copying the necessary fields from another object. + * + * @abstract + * @param StdClass|self $object The source object. + * @return self The new copy. + */ + public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) { + throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses'); + } + + /** + * Create an instance of StdClass that can later be converted back to an + * update or info container. Useful for serialization and caching, as it + * avoids the "incomplete object" problem if the cached value is loaded + * before this class. + * + * @return StdClass + */ + public function toStdClass() { + $object = new stdClass(); + $this->copyFields($this, $object); + return $object; + } + + /** + * Transform the metadata into the format used by WordPress core. + * + * @return object + */ + abstract public function toWpFormat(); + + /** + * Copy known fields from one object to another. + * + * @param StdClass|self $from + * @param StdClass|self $to + */ + protected function copyFields($from, $to) { + $fields = $this->getFieldNames(); + + if ( property_exists($from, 'slug') && !empty($from->slug) ) { + //Let plugins add extra fields without having to create subclasses. + $fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields); + } + + foreach ($fields as $field) { + if ( property_exists($from, $field) ) { + $to->$field = $from->$field; + } + } + } + + /** + * @return string[] + */ + protected function getFieldNames() { + return array(); + } + + /** + * @param string $tag + * @return string + */ + protected function getPrefixedFilter($tag) { + return 'puc_' . $tag; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/OAuthSignature.php b/admin/includes/plugin-update-checker/Puc/v4p6/OAuthSignature.php new file mode 100755 index 0000000..e6ffd48 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/OAuthSignature.php @@ -0,0 +1,100 @@ +consumerKey = $consumerKey; + $this->consumerSecret = $consumerSecret; + } + + /** + * Sign a URL using OAuth 1.0. + * + * @param string $url The URL to be signed. It may contain query parameters. + * @param string $method HTTP method such as "GET", "POST" and so on. + * @return string The signed URL. + */ + public function sign($url, $method = 'GET') { + $parameters = array(); + + //Parse query parameters. + $query = parse_url($url, PHP_URL_QUERY); + if ( !empty($query) ) { + parse_str($query, $parsedParams); + if ( is_array($parameters) ) { + $parameters = $parsedParams; + } + //Remove the query string from the URL. We'll replace it later. + $url = substr($url, 0, strpos($url, '?')); + } + + $parameters = array_merge( + $parameters, + array( + 'oauth_consumer_key' => $this->consumerKey, + 'oauth_nonce' => $this->nonce(), + 'oauth_signature_method' => 'HMAC-SHA1', + 'oauth_timestamp' => time(), + 'oauth_version' => '1.0', + ) + ); + unset($parameters['oauth_signature']); + + //Parameters must be sorted alphabetically before signing. + ksort($parameters); + + //The most complicated part of the request - generating the signature. + //The string to sign contains the HTTP method, the URL path, and all of + //our query parameters. Everything is URL encoded. Then we concatenate + //them with ampersands into a single string to hash. + $encodedVerb = urlencode($method); + $encodedUrl = urlencode($url); + $encodedParams = urlencode(http_build_query($parameters, '', '&')); + + $stringToSign = $encodedVerb . '&' . $encodedUrl . '&' . $encodedParams; + + //Since we only have one OAuth token (the consumer secret) we only have + //to use it as our HMAC key. However, we still have to append an & to it + //as if we were using it with additional tokens. + $secret = urlencode($this->consumerSecret) . '&'; + + //The signature is a hash of the consumer key and the base string. Note + //that we have to get the raw output from hash_hmac and base64 encode + //the binary data result. + $parameters['oauth_signature'] = base64_encode(hash_hmac('sha1', $stringToSign, $secret, true)); + + return ($url . '?' . http_build_query($parameters)); + } + + /** + * Generate a random nonce. + * + * @return string + */ + private function nonce() { + $mt = microtime(); + + $rand = null; + if ( is_callable('random_bytes') ) { + try { + $rand = random_bytes(16); + } catch (Exception $ex) { + //Fall back to mt_rand (below). + } + } + if ( $rand === null ) { + $rand = mt_rand(); + } + + return md5($mt . '_' . $rand); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Info.php b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Info.php new file mode 100755 index 0000000..2c97475 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Info.php @@ -0,0 +1,130 @@ +sections = (array)$instance->sections; + $instance->icons = (array)$instance->icons; + + return $instance; + } + + /** + * Very, very basic validation. + * + * @param StdClass $apiResponse + * @return bool|WP_Error + */ + protected function validateMetadata($apiResponse) { + if ( + !isset($apiResponse->name, $apiResponse->version) + || empty($apiResponse->name) + || empty($apiResponse->version) + ) { + return new WP_Error( + 'puc-invalid-metadata', + "The plugin metadata file does not contain the required 'name' and/or 'version' keys." + ); + } + return true; + } + + + /** + * Transform plugin info into the format used by the native WordPress.org API + * + * @return object + */ + public function toWpFormat(){ + $info = new stdClass; + + //The custom update API is built so that many fields have the same name and format + //as those returned by the native WordPress.org API. These can be assigned directly. + $sameFormat = array( + 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', + 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated', + ); + foreach($sameFormat as $field){ + if ( isset($this->$field) ) { + $info->$field = $this->$field; + } else { + $info->$field = null; + } + } + + //Other fields need to be renamed and/or transformed. + $info->download_link = $this->download_url; + $info->author = $this->getFormattedAuthor(); + $info->sections = array_merge(array('description' => ''), $this->sections); + + if ( !empty($this->banners) ) { + //WP expects an array with two keys: "high" and "low". Both are optional. + //Docs: https://wordpress.org/plugins/about/faq/#banners + $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners; + $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true)); + } + + return $info; + } + + protected function getFormattedAuthor() { + if ( !empty($this->author_homepage) ){ + /** @noinspection HtmlUnknownTarget */ + return sprintf('%s', $this->author_homepage, $this->author); + } + return $this->author; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Package.php b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Package.php new file mode 100755 index 0000000..e880a9f --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Package.php @@ -0,0 +1,184 @@ +pluginAbsolutePath = $pluginAbsolutePath; + $this->pluginFile = plugin_basename($this->pluginAbsolutePath); + + parent::__construct($updateChecker); + + //Clear the version number cache when something - anything - is upgraded or WP clears the update cache. + add_filter('upgrader_post_install', array($this, 'clearCachedVersion')); + add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion')); + } + + public function getInstalledVersion() { + if ( isset($this->cachedInstalledVersion) ) { + return $this->cachedInstalledVersion; + } + + $pluginHeader = $this->getPluginHeader(); + if ( isset($pluginHeader['Version']) ) { + $this->cachedInstalledVersion = $pluginHeader['Version']; + return $pluginHeader['Version']; + } else { + //This can happen if the filename points to something that is not a plugin. + $this->updateChecker->triggerError( + sprintf( + "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", + $this->updateChecker->pluginFile + ), + E_USER_WARNING + ); + return null; + } + } + + /** + * Clear the cached plugin version. This method can be set up as a filter (hook) and will + * return the filter argument unmodified. + * + * @param mixed $filterArgument + * @return mixed + */ + public function clearCachedVersion($filterArgument = null) { + $this->cachedInstalledVersion = null; + return $filterArgument; + } + + public function getAbsoluteDirectoryPath() { + return dirname($this->pluginAbsolutePath); + } + + /** + * Get the value of a specific plugin or theme header. + * + * @param string $headerName + * @param string $defaultValue + * @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty. + */ + public function getHeaderValue($headerName, $defaultValue = '') { + $headers = $this->getPluginHeader(); + if ( isset($headers[$headerName]) && ($headers[$headerName] !== '') ) { + return $headers[$headerName]; + } + return $defaultValue; + } + + protected function getHeaderNames() { + return array( + 'Name' => 'Plugin Name', + 'PluginURI' => 'Plugin URI', + 'Version' => 'Version', + 'Description' => 'Description', + 'Author' => 'Author', + 'AuthorURI' => 'Author URI', + 'TextDomain' => 'Text Domain', + 'DomainPath' => 'Domain Path', + 'Network' => 'Network', + + //The newest WordPress version that this plugin requires or has been tested with. + //We support several different formats for compatibility with other libraries. + 'Tested WP' => 'Tested WP', + 'Requires WP' => 'Requires WP', + 'Tested up to' => 'Tested up to', + 'Requires at least' => 'Requires at least', + ); + } + + /** + * Get the translated plugin title. + * + * @return string + */ + public function getPluginTitle() { + $title = ''; + $header = $this->getPluginHeader(); + if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) { + $title = translate($header['Name'], $header['TextDomain']); + } + return $title; + } + + /** + * Get plugin's metadata from its file header. + * + * @return array + */ + public function getPluginHeader() { + if ( !is_file($this->pluginAbsolutePath) ) { + //This can happen if the plugin filename is wrong. + $this->updateChecker->triggerError( + sprintf( + "Can't to read the plugin header for '%s'. The file does not exist.", + $this->updateChecker->pluginFile + ), + E_USER_WARNING + ); + return array(); + } + + if ( !function_exists('get_plugin_data') ) { + /** @noinspection PhpIncludeInspection */ + require_once(ABSPATH . '/wp-admin/includes/plugin.php'); + } + return get_plugin_data($this->pluginAbsolutePath, false, false); + } + + public function removeHooks() { + remove_filter('upgrader_post_install', array($this, 'clearCachedVersion')); + remove_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion')); + } + + /** + * Check if the plugin file is inside the mu-plugins directory. + * + * @return bool + */ + public function isMuPlugin() { + static $cachedResult = null; + + if ( $cachedResult === null ) { + if ( !defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR) ) { + $cachedResult = false; + return $cachedResult; + } + + //Convert both paths to the canonical form before comparison. + $muPluginDir = realpath(WPMU_PLUGIN_DIR); + $pluginPath = realpath($this->pluginAbsolutePath); + //If realpath() fails, just normalize the syntax instead. + if (($muPluginDir === false) || ($pluginPath === false)) { + $muPluginDir = Puc_v4p6_Factory::normalizePath(WPMU_PLUGIN_DIR); + $pluginPath = Puc_v4p6_Factory::normalizePath($this->pluginAbsolutePath); + } + + $cachedResult = (strpos($pluginPath, $muPluginDir) === 0); + } + + return $cachedResult; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Ui.php b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Ui.php new file mode 100755 index 0000000..93c22aa --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Ui.php @@ -0,0 +1,277 @@ +updateChecker = $updateChecker; + $this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors'); + + add_action('admin_init', array($this, 'onAdminInit')); + } + + public function onAdminInit() { + if ( $this->updateChecker->userCanInstallUpdates() ) { + $this->handleManualCheck(); + + add_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10, 3); + add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2); + add_action('all_admin_notices', array($this, 'displayManualCheckResult')); + } + } + + /** + * Add a "View Details" link to the plugin row in the "Plugins" page. By default, + * the new link will appear before the "Visit plugin site" link (if present). + * + * You can change the link text by using the "puc_view_details_link-$slug" filter. + * Returning an empty string from the filter will disable the link. + * + * You can change the position of the link using the + * "puc_view_details_link_position-$slug" filter. + * Returning 'before' or 'after' will place the link immediately before/after + * the "Visit plugin site" link. + * Returning 'append' places the link after any existing links at the time of the hook. + * Returning 'replace' replaces the "Visit plugin site" link. + * Returning anything else disables the link when there is a "Visit plugin site" link. + * + * If there is no "Visit plugin site" link 'append' is always used! + * + * @param array $pluginMeta Array of meta links. + * @param string $pluginFile + * @param array $pluginData Array of plugin header data. + * @return array + */ + public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = array()) { + if ( $this->isMyPluginFile($pluginFile) && !isset($pluginData['slug']) ) { + $linkText = apply_filters($this->updateChecker->getUniqueName('view_details_link'), __('View details')); + if ( !empty($linkText) ) { + $viewDetailsLinkPosition = 'append'; + + //Find the "Visit plugin site" link (if present). + $visitPluginSiteLinkIndex = count($pluginMeta) - 1; + if ( $pluginData['PluginURI'] ) { + $escapedPluginUri = esc_url($pluginData['PluginURI']); + foreach ($pluginMeta as $linkIndex => $existingLink) { + if ( strpos($existingLink, $escapedPluginUri) !== false ) { + $visitPluginSiteLinkIndex = $linkIndex; + $viewDetailsLinkPosition = apply_filters( + $this->updateChecker->getUniqueName('view_details_link_position'), + 'before' + ); + break; + } + } + } + + $viewDetailsLink = sprintf('%s', + esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->slug) . + '&TB_iframe=true&width=600&height=550')), + esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])), + esc_attr($pluginData['Name']), + $linkText + ); + switch ($viewDetailsLinkPosition) { + case 'before': + array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink); + break; + case 'after': + array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink); + break; + case 'replace': + $pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink; + break; + case 'append': + default: + $pluginMeta[] = $viewDetailsLink; + break; + } + } + } + return $pluginMeta; + } + + /** + * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default, + * the new link will appear after the "Visit plugin site" link if present, otherwise + * after the "View plugin details" link. + * + * You can change the link text by using the "puc_manual_check_link-$slug" filter. + * Returning an empty string from the filter will disable the link. + * + * @param array $pluginMeta Array of meta links. + * @param string $pluginFile + * @return array + */ + public function addCheckForUpdatesLink($pluginMeta, $pluginFile) { + if ( $this->isMyPluginFile($pluginFile) ) { + $linkUrl = wp_nonce_url( + add_query_arg( + array( + 'puc_check_for_updates' => 1, + 'puc_slug' => $this->updateChecker->slug, + ), + self_admin_url('plugins.php') + ), + 'puc_check_for_updates' + ); + + $linkText = apply_filters( + $this->updateChecker->getUniqueName('manual_check_link'), + __('Check for updates', 'plugin-update-checker') + ); + if ( !empty($linkText) ) { + /** @noinspection HtmlUnknownTarget */ + $pluginMeta[] = sprintf('%s', esc_attr($linkUrl), $linkText); + } + } + return $pluginMeta; + } + + protected function isMyPluginFile($pluginFile) { + return ($pluginFile == $this->updateChecker->pluginFile) + || (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile)); + } + + /** + * Check for updates when the user clicks the "Check for updates" link. + * + * @see self::addCheckForUpdatesLink() + * + * @return void + */ + public function handleManualCheck() { + $shouldCheck = + isset($_GET['puc_check_for_updates'], $_GET['puc_slug']) + && $_GET['puc_slug'] == $this->updateChecker->slug + && check_admin_referer('puc_check_for_updates'); + + if ( $shouldCheck ) { + $update = $this->updateChecker->checkForUpdates(); + $status = ($update === null) ? 'no_update' : 'update_available'; + + if ( ($update === null) && !empty($this->lastRequestApiErrors) ) { + //Some errors are not critical. For example, if PUC tries to retrieve the readme.txt + //file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates + //from working. Maybe the plugin simply doesn't have a readme. + //Let's only show important errors. + $foundCriticalErrors = false; + $questionableErrorCodes = array( + 'puc-github-http-error', + 'puc-gitlab-http-error', + 'puc-bitbucket-http-error', + ); + + foreach ($this->lastRequestApiErrors as $item) { + $wpError = $item['error']; + /** @var WP_Error $wpError */ + if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) { + $foundCriticalErrors = true; + break; + } + } + + if ( $foundCriticalErrors ) { + $status = 'error'; + set_site_transient($this->manualCheckErrorTransient, $this->lastRequestApiErrors, 60); + } + } + + wp_redirect(add_query_arg( + array( + 'puc_update_check_result' => $status, + 'puc_slug' => $this->updateChecker->slug, + ), + self_admin_url('plugins.php') + )); + exit; + } + } + + /** + * Display the results of a manual update check. + * + * @see self::handleManualCheck() + * + * You can change the result message by using the "puc_manual_check_message-$slug" filter. + */ + public function displayManualCheckResult() { + if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) { + $status = strval($_GET['puc_update_check_result']); + $title = $this->updateChecker->getInstalledPackage()->getPluginTitle(); + $noticeClass = 'updated notice-success'; + $details = ''; + + if ( $status == 'no_update' ) { + $message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title); + } else if ( $status == 'update_available' ) { + $message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title); + } else if ( $status === 'error' ) { + $message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title); + $noticeClass = 'error notice-error'; + + $details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient)); + delete_site_transient($this->manualCheckErrorTransient); + } else { + $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status)); + $noticeClass = 'error notice-error'; + } + printf( + '

%s

%s
', + $noticeClass, + apply_filters($this->updateChecker->getUniqueName('manual_check_message'), $message, $status), + $details + ); + } + } + + /** + * Format the list of errors that were thrown during an update check. + * + * @param array $errors + * @return string + */ + protected function formatManualCheckErrors($errors) { + if ( empty($errors) ) { + return ''; + } + $output = ''; + + $showAsList = count($errors) > 1; + if ( $showAsList ) { + $output .= '
    '; + $formatString = '
  1. %1$s %2$s
  2. '; + } else { + $formatString = '

    %1$s %2$s

    '; + } + foreach ($errors as $item) { + $wpError = $item['error']; + /** @var WP_Error $wpError */ + $output .= sprintf( + $formatString, + $wpError->get_error_message(), + $wpError->get_error_code() + ); + } + if ( $showAsList ) { + $output .= '
'; + } + + return $output; + } + + public function removeHooks() { + remove_action('admin_init', array($this, 'onAdminInit')); + remove_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10); + remove_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10); + remove_action('all_admin_notices', array($this, 'displayManualCheckResult')); + } + } +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Update.php b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Update.php new file mode 100755 index 0000000..5939656 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/Update.php @@ -0,0 +1,110 @@ +copyFields($object, $update); + return $update; + } + + /** + * @return string[] + */ + protected function getFieldNames() { + return array_merge(parent::getFieldNames(), self::$extraFields); + } + + /** + * Transform the update into the format used by WordPress native plugin API. + * + * @return object + */ + public function toWpFormat() { + $update = parent::toWpFormat(); + + $update->id = $this->id; + $update->url = $this->homepage; + $update->tested = $this->tested; + $update->plugin = $this->filename; + + if ( !empty($this->upgrade_notice) ) { + $update->upgrade_notice = $this->upgrade_notice; + } + + if ( !empty($this->icons) && is_array($this->icons) ) { + //This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'. + //Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons + $icons = array_intersect_key( + $this->icons, + array('svg' => true, '1x' => true, '2x' => true, 'default' => true) + ); + if ( !empty($icons) ) { + $update->icons = $icons; + + //It appears that the 'default' icon isn't used anywhere in WordPress 4.9, + //but lets set it just in case a future release needs it. + if ( !isset($update->icons['default']) ) { + $update->icons['default'] = current($update->icons); + } + } + } + + return $update; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/UpdateChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/UpdateChecker.php new file mode 100755 index 0000000..1cbe7c6 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Plugin/UpdateChecker.php @@ -0,0 +1,396 @@ +pluginAbsolutePath = $pluginFile; + $this->pluginFile = plugin_basename($this->pluginAbsolutePath); + $this->muPluginFile = $muPluginFile; + + //If no slug is specified, use the name of the main plugin file as the slug. + //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'. + if ( empty($slug) ){ + $slug = basename($this->pluginFile, '.php'); + } + + //Plugin slugs must be unique. + $slugCheckFilter = 'puc_is_slug_in_use-' . $slug; + $slugUsedBy = apply_filters($slugCheckFilter, false); + if ( $slugUsedBy ) { + $this->triggerError(sprintf( + 'Plugin slug "%s" is already in use by %s. Slugs must be unique.', + htmlentities($slug), + htmlentities($slugUsedBy) + ), E_USER_ERROR); + } + add_filter($slugCheckFilter, array($this, 'getAbsolutePath')); + + //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume + //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir). + if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) { + $this->muPluginFile = $this->pluginFile; + } + + //To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin. + //Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964 + add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks')); + + parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName); + + $this->extraUi = new Puc_v4p6_Plugin_Ui($this); + } + + /** + * Create an instance of the scheduler. + * + * @param int $checkPeriod + * @return Puc_v4p6_Scheduler + */ + protected function createScheduler($checkPeriod) { + $scheduler = new Puc_v4p6_Scheduler($this, $checkPeriod, array('load-plugins.php')); + register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron')); + return $scheduler; + } + + /** + * Install the hooks required to run periodic update checks and inject update info + * into WP data structures. + * + * @return void + */ + protected function installHooks(){ + //Override requests for plugin information + add_filter('plugins_api', array($this, 'injectInfo'), 20, 3); + + parent::installHooks(); + } + + /** + * Remove update checker hooks. + * + * The intent is to prevent a fatal error that can happen if the plugin has an uninstall + * hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance), + * the uninstall hook runs, WP deletes the plugin files and then updates some transients. + * If PUC hooks are still around at this time, they could throw an error while trying to + * autoload classes from files that no longer exist. + * + * The "site_transient_{$transient}" filter is the main problem here, but let's also remove + * most other PUC hooks to be safe. + * + * @internal + */ + public function removeHooks() { + parent::removeHooks(); + $this->extraUi->removeHooks(); + $this->package->removeHooks(); + + remove_filter('plugins_api', array($this, 'injectInfo'), 20); + } + + /** + * Retrieve plugin info from the configured API endpoint. + * + * @uses wp_remote_get() + * + * @param array $queryArgs Additional query arguments to append to the request. Optional. + * @return Puc_v4p6_Plugin_Info + */ + public function requestInfo($queryArgs = array()) { + list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p6_Plugin_Info', 'request_info', $queryArgs); + + if ( $pluginInfo !== null ) { + /** @var Puc_v4p6_Plugin_Info $pluginInfo */ + $pluginInfo->filename = $this->pluginFile; + $pluginInfo->slug = $this->slug; + } + + $pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result); + return $pluginInfo; + } + + /** + * Retrieve the latest update (if any) from the configured API endpoint. + * + * @uses PluginUpdateChecker::requestInfo() + * + * @return Puc_v4p6_Update|null An instance of Plugin_Update, or NULL when no updates are available. + */ + public function requestUpdate() { + //For the sake of simplicity, this function just calls requestInfo() + //and transforms the result accordingly. + $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1')); + if ( $pluginInfo === null ){ + return null; + } + $update = Puc_v4p6_Plugin_Update::fromPluginInfo($pluginInfo); + + $update = $this->filterUpdateResult($update); + + return $update; + } + + /** + * Intercept plugins_api() calls that request information about our plugin and + * use the configured API endpoint to satisfy them. + * + * @see plugins_api() + * + * @param mixed $result + * @param string $action + * @param array|object $args + * @return mixed + */ + public function injectInfo($result, $action = null, $args = null){ + $relevant = ($action == 'plugin_information') && isset($args->slug) && ( + ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile)) + ); + if ( !$relevant ) { + return $result; + } + + $pluginInfo = $this->requestInfo(); + $pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo); + if ( $pluginInfo ) { + return $pluginInfo->toWpFormat(); + } + + return $result; + } + + protected function shouldShowUpdates() { + //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file + //is usually different from the main plugin file so the update wouldn't show up properly anyway. + return !$this->isUnknownMuPlugin(); + } + + /** + * @param stdClass|null $updates + * @param stdClass $updateToAdd + * @return stdClass + */ + protected function addUpdateToList($updates, $updateToAdd) { + if ( $this->package->isMuPlugin() ) { + //WP does not support automatic update installation for mu-plugins, but we can + //still display a notice. + $updateToAdd->package = null; + } + return parent::addUpdateToList($updates, $updateToAdd); + } + + /** + * @param stdClass|null $updates + * @return stdClass|null + */ + protected function removeUpdateFromList($updates) { + $updates = parent::removeUpdateFromList($updates); + if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) { + unset($updates->response[$this->muPluginFile]); + } + return $updates; + } + + /** + * For plugins, the update array is indexed by the plugin filename relative to the "plugins" + * directory. Example: "plugin-name/plugin.php". + * + * @return string + */ + protected function getUpdateListKey() { + if ( $this->package->isMuPlugin() ) { + return $this->muPluginFile; + } + return $this->pluginFile; + } + + /** + * Alias for isBeingUpgraded(). + * + * @deprecated + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + public function isPluginBeingUpgraded($upgrader = null) { + return $this->isBeingUpgraded($upgrader); + } + + /** + * Is there an update being installed for this plugin, right now? + * + * @param WP_Upgrader|null $upgrader + * @return bool + */ + public function isBeingUpgraded($upgrader = null) { + return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader); + } + + /** + * Get the details of the currently available update, if any. + * + * If no updates are available, or if the last known update version is below or equal + * to the currently installed version, this method will return NULL. + * + * Uses cached update data. To retrieve update information straight from + * the metadata URL, call requestUpdate() instead. + * + * @return Puc_v4p6_Plugin_Update|null + */ + public function getUpdate() { + $update = parent::getUpdate(); + if ( isset($update) ) { + /** @var Puc_v4p6_Plugin_Update $update */ + $update->filename = $this->pluginFile; + } + return $update; + } + + /** + * Get the translated plugin title. + * + * @deprecated + * @return string + */ + public function getPluginTitle() { + return $this->package->getPluginTitle(); + } + + /** + * Check if the current user has the required permissions to install updates. + * + * @return bool + */ + public function userCanInstallUpdates() { + return current_user_can('update_plugins'); + } + + /** + * Check if the plugin file is inside the mu-plugins directory. + * + * @deprecated + * @return bool + */ + protected function isMuPlugin() { + return $this->package->isMuPlugin(); + } + + /** + * MU plugins are partially supported, but only when we know which file in mu-plugins + * corresponds to this plugin. + * + * @return bool + */ + protected function isUnknownMuPlugin() { + return empty($this->muPluginFile) && $this->package->isMuPlugin(); + } + + /** + * Get absolute path to the main plugin file. + * + * @return string + */ + public function getAbsolutePath() { + return $this->pluginAbsolutePath; + } + + /** + * Register a callback for filtering query arguments. + * + * The callback function should take one argument - an associative array of query arguments. + * It should return a modified array of query arguments. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addQueryArgFilter($callback){ + $this->addFilter('request_info_query_args', $callback); + } + + /** + * Register a callback for filtering arguments passed to wp_remote_get(). + * + * The callback function should take one argument - an associative array of arguments - + * and return a modified array or arguments. See the WP documentation on wp_remote_get() + * for details on what arguments are available and how they work. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addHttpRequestArgFilter($callback) { + $this->addFilter('request_info_options', $callback); + } + + /** + * Register a callback for filtering the plugin info retrieved from the external API. + * + * The callback function should take two arguments. If the plugin info was retrieved + * successfully, the first argument passed will be an instance of PluginInfo. Otherwise, + * it will be NULL. The second argument will be the corresponding return value of + * wp_remote_get (see WP docs for details). + * + * The callback function should return a new or modified instance of PluginInfo or NULL. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addResultFilter($callback) { + $this->addFilter('request_info_result', $callback, 10, 2); + } + + protected function createDebugBarExtension() { + return new Puc_v4p6_DebugBar_PluginExtension($this); + } + + /** + * Create a package instance that represents this plugin or theme. + * + * @return Puc_v4p6_InstalledPackage + */ + protected function createInstalledPackage() { + return new Puc_v4p6_Plugin_Package($this->pluginAbsolutePath, $this); + } + + /** + * @return Puc_v4p6_Plugin_Package + */ + public function getInstalledPackage() { + return $this->package; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Scheduler.php b/admin/includes/plugin-update-checker/Puc/v4p6/Scheduler.php new file mode 100755 index 0000000..cf1d6b3 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Scheduler.php @@ -0,0 +1,231 @@ +updateChecker = $updateChecker; + $this->checkPeriod = $checkPeriod; + + //Set up the periodic update checks + $this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates'); + if ( $this->checkPeriod > 0 ){ + + //Trigger the check via Cron. + //Try to use one of the default schedules if possible as it's less likely to conflict + //with other plugins and their custom schedules. + $defaultSchedules = array( + 1 => 'hourly', + 12 => 'twicedaily', + 24 => 'daily', + ); + if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) { + $scheduleName = $defaultSchedules[$this->checkPeriod]; + } else { + //Use a custom cron schedule. + $scheduleName = 'every' . $this->checkPeriod . 'hours'; + add_filter('cron_schedules', array($this, '_addCustomSchedule')); + } + + if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { + wp_schedule_event(time(), $scheduleName, $this->cronHook); + } + add_action($this->cronHook, array($this, 'maybeCheckForUpdates')); + + //In case Cron is disabled or unreliable, we also manually trigger + //the periodic checks while the user is browsing the Dashboard. + add_action( 'admin_init', array($this, 'maybeCheckForUpdates') ); + + //Like WordPress itself, we check more often on certain pages. + /** @see wp_update_plugins */ + add_action('load-update-core.php', array($this, 'maybeCheckForUpdates')); + //"load-update.php" and "load-plugins.php" or "load-themes.php". + $this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks); + foreach($this->hourlyCheckHooks as $hook) { + add_action($hook, array($this, 'maybeCheckForUpdates')); + } + //This hook fires after a bulk update is complete. + add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2); + + } else { + //Periodic checks are disabled. + wp_clear_scheduled_hook($this->cronHook); + } + } + + /** + * Runs upon the WP action upgrader_process_complete. + * + * We look at the parameters to decide whether to call maybeCheckForUpdates() or not. + * + * @param WP_Upgrader $upgrader WP_Upgrader instance + * @param array $upgradeInfo extra information about the upgrade + */ + public function upgraderProcessComplete( + /** @noinspection PhpUnusedParameterInspection */ + $upgrader, $upgradeInfo + ) { + + //Sanity check and limitation to relevant types. + if ( + !is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action']) + || 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme')) + ) { + return; + } + + //Filter out notifications of upgrades that should have no bearing upon whether or not our + //current info is up-to-date. + if ( is_a($this->updateChecker, 'Puc_v4p6_Theme_UpdateChecker') ) { + if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) { + return; + } + + //Letting too many things going through for checks is not a real problem, so we compare widely. + if ( !in_array( + strtolower($this->updateChecker->directoryName), + array_map('strtolower', $upgradeInfo['themes']) + ) ) { + return; + } + } + + if ( is_a($this->updateChecker, 'Puc_v4p6_Plugin_UpdateChecker') ) { + if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) { + return; + } + + //Themes pass in directory names in the information array, but plugins use the relative plugin path. + if ( !in_array( + strtolower($this->updateChecker->directoryName), + array_map('dirname', array_map('strtolower', $upgradeInfo['plugins'])) + ) ) { + return; + } + } + + $this->maybeCheckForUpdates(); + } + + /** + * Check for updates if the configured check interval has already elapsed. + * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron. + * + * You can override the default behaviour by using the "puc_check_now-$slug" filter. + * The filter callback will be passed three parameters: + * - Current decision. TRUE = check updates now, FALSE = don't check now. + * - Last check time as a Unix timestamp. + * - Configured check period in hours. + * Return TRUE to check for updates immediately, or FALSE to cancel. + * + * This method is declared public because it's a hook callback. Calling it directly is not recommended. + */ + public function maybeCheckForUpdates() { + if ( empty($this->checkPeriod) ){ + return; + } + + $state = $this->updateChecker->getUpdateState(); + $shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod()); + + //Let plugin authors substitute their own algorithm. + $shouldCheck = apply_filters( + $this->updateChecker->getUniqueName('check_now'), + $shouldCheck, + $state->getLastCheck(), + $this->checkPeriod + ); + + if ( $shouldCheck ) { + $this->updateChecker->checkForUpdates(); + } + } + + /** + * Calculate the actual check period based on the current status and environment. + * + * @return int Check period in seconds. + */ + protected function getEffectiveCheckPeriod() { + $currentFilter = current_filter(); + if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) { + //Check more often when the user visits "Dashboard -> Updates" or does a bulk update. + $period = 60; + } else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) { + //Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page. + $period = 3600; + } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) { + //Check less frequently if it's already known that an update is available. + $period = $this->throttledCheckPeriod * 3600; + } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) { + //WordPress cron schedules are not exact, so lets do an update check even + //if slightly less than $checkPeriod hours have elapsed since the last check. + $cronFuzziness = 20 * 60; + $period = $this->checkPeriod * 3600 - $cronFuzziness; + } else { + $period = $this->checkPeriod * 3600; + } + + return $period; + } + + /** + * Add our custom schedule to the array of Cron schedules used by WP. + * + * @param array $schedules + * @return array + */ + public function _addCustomSchedule($schedules) { + if ( $this->checkPeriod && ($this->checkPeriod > 0) ){ + $scheduleName = 'every' . $this->checkPeriod . 'hours'; + $schedules[$scheduleName] = array( + 'interval' => $this->checkPeriod * 3600, + 'display' => sprintf('Every %d hours', $this->checkPeriod), + ); + } + return $schedules; + } + + /** + * Remove the scheduled cron event that the library uses to check for updates. + * + * @return void + */ + public function removeUpdaterCron() { + wp_clear_scheduled_hook($this->cronHook); + } + + /** + * Get the name of the update checker's WP-cron hook. Mostly useful for debugging. + * + * @return string + */ + public function getCronHookName() { + return $this->cronHook; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/StateStore.php b/admin/includes/plugin-update-checker/Puc/v4p6/StateStore.php new file mode 100755 index 0000000..23f984e --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/StateStore.php @@ -0,0 +1,207 @@ +optionName = $optionName; + } + + /** + * Get time elapsed since the last update check. + * + * If there are no recorded update checks, this method returns a large arbitrary number + * (i.e. time since the Unix epoch). + * + * @return int Elapsed time in seconds. + */ + public function timeSinceLastCheck() { + $this->lazyLoad(); + return time() - $this->lastCheck; + } + + /** + * @return int + */ + public function getLastCheck() { + $this->lazyLoad(); + return $this->lastCheck; + } + + /** + * Set the time of the last update check to the current timestamp. + * + * @return $this + */ + public function setLastCheckToNow() { + $this->lazyLoad(); + $this->lastCheck = time(); + return $this; + } + + /** + * @return null|Puc_v4p6_Update + */ + public function getUpdate() { + $this->lazyLoad(); + return $this->update; + } + + /** + * @param Puc_v4p6_Update|null $update + * @return $this + */ + public function setUpdate(Puc_v4p6_Update $update = null) { + $this->lazyLoad(); + $this->update = $update; + return $this; + } + + /** + * @return string + */ + public function getCheckedVersion() { + $this->lazyLoad(); + return $this->checkedVersion; + } + + /** + * @param string $version + * @return $this + */ + public function setCheckedVersion($version) { + $this->lazyLoad(); + $this->checkedVersion = strval($version); + return $this; + } + + /** + * Get translation updates. + * + * @return array + */ + public function getTranslations() { + $this->lazyLoad(); + if ( isset($this->update, $this->update->translations) ) { + return $this->update->translations; + } + return array(); + } + + /** + * Set translation updates. + * + * @param array $translationUpdates + */ + public function setTranslations($translationUpdates) { + $this->lazyLoad(); + if ( isset($this->update) ) { + $this->update->translations = $translationUpdates; + $this->save(); + } + } + + public function save() { + $state = new stdClass(); + + $state->lastCheck = $this->lastCheck; + $state->checkedVersion = $this->checkedVersion; + + if ( isset($this->update)) { + $state->update = $this->update->toStdClass(); + + $updateClass = get_class($this->update); + $state->updateClass = $updateClass; + $prefix = $this->getLibPrefix(); + if ( Puc_v4p6_Utils::startsWith($updateClass, $prefix) ) { + $state->updateBaseClass = substr($updateClass, strlen($prefix)); + } + } + + update_site_option($this->optionName, $state); + $this->isLoaded = true; + } + + /** + * @return $this + */ + public function lazyLoad() { + if ( !$this->isLoaded ) { + $this->load(); + } + return $this; + } + + protected function load() { + $this->isLoaded = true; + + $state = get_site_option($this->optionName, null); + + if ( !is_object($state) ) { + $this->lastCheck = 0; + $this->checkedVersion = ''; + $this->update = null; + return; + } + + $this->lastCheck = intval(Puc_v4p6_Utils::get($state, 'lastCheck', 0)); + $this->checkedVersion = Puc_v4p6_Utils::get($state, 'checkedVersion', ''); + $this->update = null; + + if ( isset($state->update) ) { + //This mess is due to the fact that the want the update class from this version + //of the library, not the version that saved the update. + + $updateClass = null; + if ( isset($state->updateBaseClass) ) { + $updateClass = $this->getLibPrefix() . $state->updateBaseClass; + } else if ( isset($state->updateClass) && class_exists($state->updateClass) ) { + $updateClass = $state->updateClass; + } + + if ( $updateClass !== null ) { + $this->update = call_user_func(array($updateClass, 'fromObject'), $state->update); + } + } + } + + public function delete() { + delete_site_option($this->optionName); + + $this->lastCheck = 0; + $this->checkedVersion = ''; + $this->update = null; + } + + private function getLibPrefix() { + $parts = explode('_', __CLASS__, 3); + return $parts[0] . '_' . $parts[1] . '_'; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Package.php b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Package.php new file mode 100755 index 0000000..d4a6dcc --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Package.php @@ -0,0 +1,65 @@ +stylesheet = $stylesheet; + $this->theme = wp_get_theme($this->stylesheet); + + parent::__construct($updateChecker); + } + + public function getInstalledVersion() { + return $this->theme->get('Version'); + } + + public function getAbsoluteDirectoryPath() { + if ( method_exists($this->theme, 'get_stylesheet_directory') ) { + return $this->theme->get_stylesheet_directory(); //Available since WP 3.4. + } + return get_theme_root($this->stylesheet) . '/' . $this->stylesheet; + } + + /** + * Get the value of a specific plugin or theme header. + * + * @param string $headerName + * @param string $defaultValue + * @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty. + */ + public function getHeaderValue($headerName, $defaultValue = '') { + $value = $this->theme->get($headerName); + if ( ($headerName === false) || ($headerName === '') ) { + return $defaultValue; + } + return $value; + } + + protected function getHeaderNames() { + return array( + 'Name' => 'Theme Name', + 'ThemeURI' => 'Theme URI', + 'Description' => 'Description', + 'Author' => 'Author', + 'AuthorURI' => 'Author URI', + 'Version' => 'Version', + 'Template' => 'Template', + 'Status' => 'Status', + 'Tags' => 'Tags', + 'TextDomain' => 'Text Domain', + 'DomainPath' => 'Domain Path', + ); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Update.php b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Update.php new file mode 100755 index 0000000..f1a8f67 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/Update.php @@ -0,0 +1,84 @@ + $this->slug, + 'new_version' => $this->version, + 'url' => $this->details_url, + ); + + if ( !empty($this->download_url) ) { + $update['package'] = $this->download_url; + } + + return $update; + } + + /** + * Create a new instance of Theme_Update from its JSON-encoded representation. + * + * @param string $json Valid JSON string representing a theme information object. + * @return self New instance of ThemeUpdate, or NULL on error. + */ + public static function fromJson($json) { + $instance = new self(); + if ( !parent::createFromJson($json, $instance) ) { + return null; + } + return $instance; + } + + /** + * Create a new instance by copying the necessary fields from another object. + * + * @param StdClass|Puc_v4p6_Theme_Update $object The source object. + * @return Puc_v4p6_Theme_Update The new copy. + */ + public static function fromObject($object) { + $update = new self(); + $update->copyFields($object, $update); + return $update; + } + + /** + * Basic validation. + * + * @param StdClass $apiResponse + * @return bool|WP_Error + */ + protected function validateMetadata($apiResponse) { + $required = array('version', 'details_url'); + foreach($required as $key) { + if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) { + return new WP_Error( + 'tuc-invalid-metadata', + sprintf('The theme metadata is missing the required "%s" key.', $key) + ); + } + } + return true; + } + + protected function getFieldNames() { + return array_merge(parent::getFieldNames(), self::$extraFields); + } + + protected function getPrefixedFilter($tag) { + return parent::getPrefixedFilter($tag) . '_theme'; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Theme/UpdateChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/UpdateChecker.php new file mode 100755 index 0000000..12848a9 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Theme/UpdateChecker.php @@ -0,0 +1,142 @@ +stylesheet = $stylesheet; + + parent::__construct( + $metadataUrl, + $stylesheet, + $customSlug ? $customSlug : $stylesheet, + $checkPeriod, + $optionName + ); + } + + /** + * For themes, the update array is indexed by theme directory name. + * + * @return string + */ + protected function getUpdateListKey() { + return $this->directoryName; + } + + /** + * Retrieve the latest update (if any) from the configured API endpoint. + * + * @return Puc_v4p6_Update|null An instance of Update, or NULL when no updates are available. + */ + public function requestUpdate() { + list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p6_Theme_Update', 'request_update'); + + if ( $themeUpdate !== null ) { + /** @var Puc_v4p6_Theme_Update $themeUpdate */ + $themeUpdate->slug = $this->slug; + } + + $themeUpdate = $this->filterUpdateResult($themeUpdate, $result); + return $themeUpdate; + } + + public function userCanInstallUpdates() { + return current_user_can('update_themes'); + } + + /** + * Create an instance of the scheduler. + * + * @param int $checkPeriod + * @return Puc_v4p6_Scheduler + */ + protected function createScheduler($checkPeriod) { + return new Puc_v4p6_Scheduler($this, $checkPeriod, array('load-themes.php')); + } + + /** + * Is there an update being installed right now for this theme? + * + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + public function isBeingUpgraded($upgrader = null) { + return $this->upgraderStatus->isThemeBeingUpgraded($this->stylesheet, $upgrader); + } + + protected function createDebugBarExtension() { + return new Puc_v4p6_DebugBar_Extension($this, 'Puc_v4p6_DebugBar_ThemePanel'); + } + + /** + * Register a callback for filtering query arguments. + * + * The callback function should take one argument - an associative array of query arguments. + * It should return a modified array of query arguments. + * + * @param callable $callback + * @return void + */ + public function addQueryArgFilter($callback){ + $this->addFilter('request_update_query_args', $callback); + } + + /** + * Register a callback for filtering arguments passed to wp_remote_get(). + * + * The callback function should take one argument - an associative array of arguments - + * and return a modified array or arguments. See the WP documentation on wp_remote_get() + * for details on what arguments are available and how they work. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addHttpRequestArgFilter($callback) { + $this->addFilter('request_update_options', $callback); + } + + /** + * Register a callback for filtering theme updates retrieved from the external API. + * + * The callback function should take two arguments. If the theme update was retrieved + * successfully, the first argument passed will be an instance of Theme_Update. Otherwise, + * it will be NULL. The second argument will be the corresponding return value of + * wp_remote_get (see WP docs for details). + * + * The callback function should return a new or modified instance of Theme_Update or NULL. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addResultFilter($callback) { + $this->addFilter('request_update_result', $callback, 10, 2); + } + + /** + * Create a package instance that represents this plugin or theme. + * + * @return Puc_v4p6_InstalledPackage + */ + protected function createInstalledPackage() { + return new Puc_v4p6_Theme_Package($this->stylesheet, $this); + } + } + +endif; \ No newline at end of file diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Update.php b/admin/includes/plugin-update-checker/Puc/v4p6/Update.php new file mode 100755 index 0000000..5369e8a --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Update.php @@ -0,0 +1,34 @@ +slug = $this->slug; + $update->new_version = $this->version; + $update->package = $this->download_url; + + return $update; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/UpdateChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/UpdateChecker.php new file mode 100755 index 0000000..00c916e --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/UpdateChecker.php @@ -0,0 +1,926 @@ +debugMode = (bool)(constant('WP_DEBUG')); + $this->metadataUrl = $metadataUrl; + $this->directoryName = $directoryName; + $this->slug = !empty($slug) ? $slug : $this->directoryName; + + $this->optionName = $optionName; + if ( empty($this->optionName) ) { + //BC: Initially the library only supported plugin updates and didn't use type prefixes + //in the option name. Lets use the same prefix-less name when possible. + if ( $this->filterSuffix === '' ) { + $this->optionName = 'external_updates-' . $this->slug; + } else { + $this->optionName = $this->getUniqueName('external_updates'); + } + } + + $this->package = $this->createInstalledPackage(); + $this->scheduler = $this->createScheduler($checkPeriod); + $this->upgraderStatus = new Puc_v4p6_UpgraderStatus(); + $this->updateState = new Puc_v4p6_StateStore($this->optionName); + + if ( did_action('init') ) { + $this->loadTextDomain(); + } else { + add_action('init', array($this, 'loadTextDomain')); + } + + $this->installHooks(); + } + + /** + * @internal + */ + public function loadTextDomain() { + //We're not using load_plugin_textdomain() or its siblings because figuring out where + //the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy. + $domain = 'plugin-update-checker'; + $locale = apply_filters( + 'plugin_locale', + (is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(), + $domain + ); + + $moFile = $domain . '-' . $locale . '.mo'; + $path = realpath(dirname(__FILE__) . '/../../languages'); + + if ($path && file_exists($path)) { + load_textdomain($domain, $path . '/' . $moFile); + } + } + + protected function installHooks() { + //Insert our update info into the update array maintained by WP. + add_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate')); + + //Insert translation updates into the update list. + add_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates')); + + //Clear translation updates when WP clears the update cache. + //This needs to be done directly because the library doesn't actually remove obsolete plugin updates, + //it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O. + add_action( + 'delete_site_transient_' . $this->updateTransient, + array($this, 'clearCachedTranslationUpdates') + ); + + //Rename the update directory to be the same as the existing directory. + if ( $this->directoryName !== '.' ) { + add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3); + } + + //Allow HTTP requests to the metadata URL even if it's on a local host. + add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2); + + //DebugBar integration. + if ( did_action('plugins_loaded') ) { + $this->maybeInitDebugBar(); + } else { + add_action('plugins_loaded', array($this, 'maybeInitDebugBar')); + } + } + + /** + * Remove hooks that were added by this update checker instance. + */ + protected function removeHooks() { + remove_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate')); + remove_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates')); + remove_action( + 'delete_site_transient_' . $this->updateTransient, + array($this, 'clearCachedTranslationUpdates') + ); + + remove_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10); + remove_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10); + remove_action('plugins_loaded', array($this, 'maybeInitDebugBar')); + + remove_action('init', array($this, 'loadTextDomain')); + } + + /** + * Check if the current user has the required permissions to install updates. + * + * @return bool + */ + abstract public function userCanInstallUpdates(); + + /** + * Explicitly allow HTTP requests to the metadata URL. + * + * WordPress has a security feature where the HTTP API will reject all requests that are sent to + * another site hosted on the same server as the current site (IP match), a local host, or a local + * IP, unless the host exactly matches the current site. + * + * This feature is opt-in (at least in WP 4.4). Apparently some people enable it. + * + * That can be a problem when you're developing your plugin and you decide to host the update information + * on the same server as your test site. Update requests will mysteriously fail. + * + * We fix that by adding an exception for the metadata host. + * + * @param bool $allow + * @param string $host + * @return bool + */ + public function allowMetadataHost($allow, $host) { + static $metadataHost = 0; //Using 0 instead of NULL because parse_url can return NULL. + if ( $metadataHost === 0 ) { + $metadataHost = parse_url($this->metadataUrl, PHP_URL_HOST); + } + + if ( is_string($metadataHost) && (strtolower($host) === strtolower($metadataHost)) ) { + return true; + } + return $allow; + } + + /** + * Create a package instance that represents this plugin or theme. + * + * @return Puc_v4p6_InstalledPackage + */ + abstract protected function createInstalledPackage(); + + /** + * @return Puc_v4p6_InstalledPackage + */ + public function getInstalledPackage() { + return $this->package; + } + + /** + * Create an instance of the scheduler. + * + * This is implemented as a method to make it possible for plugins to subclass the update checker + * and substitute their own scheduler. + * + * @param int $checkPeriod + * @return Puc_v4p6_Scheduler + */ + abstract protected function createScheduler($checkPeriod); + + /** + * Check for updates. The results are stored in the DB option specified in $optionName. + * + * @return Puc_v4p6_Update|null + */ + public function checkForUpdates() { + $installedVersion = $this->getInstalledVersion(); + //Fail silently if we can't find the plugin/theme or read its header. + if ( $installedVersion === null ) { + $this->triggerError( + sprintf('Skipping update check for %s - installed version unknown.', $this->slug), + E_USER_WARNING + ); + return null; + } + + //Start collecting API errors. + $this->lastRequestApiErrors = array(); + add_action('puc_api_error', array($this, 'collectApiErrors'), 10, 4); + + $state = $this->updateState; + $state->setLastCheckToNow() + ->setCheckedVersion($installedVersion) + ->save(); //Save before checking in case something goes wrong + + $state->setUpdate($this->requestUpdate()); + $state->save(); + + //Stop collecting API errors. + remove_action('puc_api_error', array($this, 'collectApiErrors'), 10); + + return $this->getUpdate(); + } + + /** + * Load the update checker state from the DB. + * + * @return Puc_v4p6_StateStore + */ + public function getUpdateState() { + return $this->updateState->lazyLoad(); + } + + /** + * Reset update checker state - i.e. last check time, cached update data and so on. + * + * Call this when your plugin is being uninstalled, or if you want to + * clear the update cache. + */ + public function resetUpdateState() { + $this->updateState->delete(); + } + + /** + * Get the details of the currently available update, if any. + * + * If no updates are available, or if the last known update version is below or equal + * to the currently installed version, this method will return NULL. + * + * Uses cached update data. To retrieve update information straight from + * the metadata URL, call requestUpdate() instead. + * + * @return Puc_v4p6_Update|null + */ + public function getUpdate() { + $update = $this->updateState->getUpdate(); + + //Is there an update available? + if ( isset($update) ) { + //Check if the update is actually newer than the currently installed version. + $installedVersion = $this->getInstalledVersion(); + if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){ + return $update; + } + } + return null; + } + + /** + * Retrieve the latest update (if any) from the configured API endpoint. + * + * Subclasses should run the update through filterUpdateResult before returning it. + * + * @return Puc_v4p6_Update An instance of Update, or NULL when no updates are available. + */ + abstract public function requestUpdate(); + + /** + * Filter the result of a requestUpdate() call. + * + * @param Puc_v4p6_Update|null $update + * @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any. + * @return Puc_v4p6_Update + */ + protected function filterUpdateResult($update, $httpResult = null) { + //Let plugins/themes modify the update. + $update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult); + + $this->fixSupportedWordpressVersion($update); + + if ( isset($update, $update->translations) ) { + //Keep only those translation updates that apply to this site. + $update->translations = $this->filterApplicableTranslations($update->translations); + } + + return $update; + } + + /** + * The "Tested up to" field in the plugin metadata is supposed to be in the form of "major.minor", + * while WordPress core's list_plugin_updates() expects the $update->tested field to be an exact + * version, e.g. "major.minor.patch", to say it's compatible. In other case it shows + * "Compatibility: Unknown". + * The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to". + * + * @param Puc_v4p6_Update|null $update + */ + protected function fixSupportedWordpressVersion(Puc_v4p6_Update $update = null) { + if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) { + return; + } + + $actualWpVersions = array(); + + $wpVersion = $GLOBALS['wp_version']; + + if ( function_exists('get_preferred_from_update_core') ) { + $coreUpdate = get_preferred_from_update_core(); + if ( isset($coreUpdate->current) && version_compare($coreUpdate->current, $wpVersion, '>') ) { + $actualWpVersions[] = $coreUpdate->current; + } + } + + $actualWpVersions[] = $wpVersion; + + $actualWpPatchNumber = "999"; + foreach ($actualWpVersions as $version) { + if ( preg_match('/^(?P\d++\.\d++)\.(?P\d++)/', $version, $versionParts) ) { + if ( $versionParts['majorMinor'] === $update->tested ) { + $actualWpPatchNumber = $versionParts['patch']; + break; + } + } + } + + $update->tested .= '.' . $actualWpPatchNumber; + } + + /** + * Get the currently installed version of the plugin or theme. + * + * @return string|null Version number. + */ + public function getInstalledVersion() { + return $this->package->getInstalledVersion(); + } + + /** + * Get the full path of the plugin or theme directory. + * + * @return string + */ + public function getAbsoluteDirectoryPath() { + return $this->package->getAbsoluteDirectoryPath(); + } + + /** + * Trigger a PHP error, but only when $debugMode is enabled. + * + * @param string $message + * @param int $errorType + */ + public function triggerError($message, $errorType) { + if ( $this->isDebugModeEnabled() ) { + trigger_error($message, $errorType); + } + } + + /** + * @return bool + */ + protected function isDebugModeEnabled() { + if ( $this->debugMode === null ) { + $this->debugMode = (bool)(constant('WP_DEBUG')); + } + return $this->debugMode; + } + + /** + * Get the full name of an update checker filter, action or DB entry. + * + * This method adds the "puc_" prefix and the "-$slug" suffix to the filter name. + * For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug". + * + * @param string $baseTag + * @return string + */ + public function getUniqueName($baseTag) { + $name = 'puc_' . $baseTag; + if ( $this->filterSuffix !== '' ) { + $name .= '_' . $this->filterSuffix; + } + return $name . '-' . $this->slug; + } + + /** + * Store API errors that are generated when checking for updates. + * + * @internal + * @param WP_Error $error + * @param array|null $httpResponse + * @param string|null $url + * @param string|null $slug + */ + public function collectApiErrors($error, $httpResponse = null, $url = null, $slug = null) { + if ( isset($slug) && ($slug !== $this->slug) ) { + return; + } + + $this->lastRequestApiErrors[] = array( + 'error' => $error, + 'httpResponse' => $httpResponse, + 'url' => $url, + ); + } + + /** + * @return array + */ + public function getLastRequestApiErrors() { + return $this->lastRequestApiErrors; + } + + /* ------------------------------------------------------------------- + * PUC filters and filter utilities + * ------------------------------------------------------------------- + */ + + /** + * Register a callback for one of the update checker filters. + * + * Identical to add_filter(), except it automatically adds the "puc_" prefix + * and the "-$slug" suffix to the filter name. For example, "request_info_result" + * becomes "puc_request_info_result-your_plugin_slug". + * + * @param string $tag + * @param callable $callback + * @param int $priority + * @param int $acceptedArgs + */ + public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) { + add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs); + } + + /* ------------------------------------------------------------------- + * Inject updates + * ------------------------------------------------------------------- + */ + + /** + * Insert the latest update (if any) into the update list maintained by WP. + * + * @param stdClass $updates Update list. + * @return stdClass Modified update list. + */ + public function injectUpdate($updates) { + //Is there an update to insert? + $update = $this->getUpdate(); + + if ( !$this->shouldShowUpdates() ) { + $update = null; + } + + if ( !empty($update) ) { + //Let plugins filter the update info before it's passed on to WordPress. + $update = apply_filters($this->getUniqueName('pre_inject_update'), $update); + $updates = $this->addUpdateToList($updates, $update->toWpFormat()); + } else { + //Clean up any stale update info. + $updates = $this->removeUpdateFromList($updates); + } + + return $updates; + } + + /** + * @param stdClass|null $updates + * @param stdClass|array $updateToAdd + * @return stdClass + */ + protected function addUpdateToList($updates, $updateToAdd) { + if ( !is_object($updates) ) { + $updates = new stdClass(); + $updates->response = array(); + } + + $updates->response[$this->getUpdateListKey()] = $updateToAdd; + return $updates; + } + + /** + * @param stdClass|null $updates + * @return stdClass|null + */ + protected function removeUpdateFromList($updates) { + if ( isset($updates, $updates->response) ) { + unset($updates->response[$this->getUpdateListKey()]); + } + return $updates; + } + + /** + * Get the key that will be used when adding updates to the update list that's maintained + * by the WordPress core. The list is always an associative array, but the key is different + * for plugins and themes. + * + * @return string + */ + abstract protected function getUpdateListKey(); + + /** + * Should we show available updates? + * + * Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't + * support automatic updates installation for mu-plugins, so PUC usually won't show update + * notifications in that case. See the plugin-specific subclass for details. + * + * Note: This method only applies to updates that are displayed (or not) in the WordPress + * admin. It doesn't affect APIs like requestUpdate and getUpdate. + * + * @return bool + */ + protected function shouldShowUpdates() { + return true; + } + + /* ------------------------------------------------------------------- + * JSON-based update API + * ------------------------------------------------------------------- + */ + + /** + * Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl. + * + * @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method. + * @param string $filterRoot + * @param array $queryArgs Additional query arguments. + * @return array [Puc_v4p6_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get(). + */ + protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) { + //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). + $queryArgs = array_merge( + array( + 'installed_version' => strval($this->getInstalledVersion()), + 'php' => phpversion(), + 'locale' => get_locale(), + ), + $queryArgs + ); + $queryArgs = apply_filters($this->getUniqueName($filterRoot . '_query_args'), $queryArgs); + + //Various options for the wp_remote_get() call. Plugins can filter these, too. + $options = array( + 'timeout' => 10, //seconds + 'headers' => array( + 'Accept' => 'application/json', + ), + ); + $options = apply_filters($this->getUniqueName($filterRoot . '_options'), $options); + + //The metadata file should be at 'http://your-api.com/url/here/$slug/info.json' + $url = $this->metadataUrl; + if ( !empty($queryArgs) ){ + $url = add_query_arg($queryArgs, $url); + } + + $result = wp_remote_get($url, $options); + + $result = apply_filters($this->getUniqueName('request_metadata_http_result'), $result, $url, $options); + + //Try to parse the response + $status = $this->validateApiResponse($result); + $metadata = null; + if ( !is_wp_error($status) ){ + $metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']); + } else { + do_action('puc_api_error', $status, $result, $url, $this->slug); + $this->triggerError( + sprintf('The URL %s does not point to a valid metadata file. ', $url) + . $status->get_error_message(), + E_USER_WARNING + ); + } + + return array($metadata, $result); + } + + /** + * Check if $result is a successful update API response. + * + * @param array|WP_Error $result + * @return true|WP_Error + */ + protected function validateApiResponse($result) { + if ( is_wp_error($result) ) { /** @var WP_Error $result */ + return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message()); + } + + if ( !isset($result['response']['code']) ) { + return new WP_Error( + 'puc_no_response_code', + 'wp_remote_get() returned an unexpected result.' + ); + } + + if ( $result['response']['code'] !== 200 ) { + return new WP_Error( + 'puc_unexpected_response_code', + 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)' + ); + } + + if ( empty($result['body']) ) { + return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.'); + } + + return true; + } + + /* ------------------------------------------------------------------- + * Language packs / Translation updates + * ------------------------------------------------------------------- + */ + + /** + * Filter a list of translation updates and return a new list that contains only updates + * that apply to the current site. + * + * @param array $translations + * @return array + */ + protected function filterApplicableTranslations($translations) { + $languages = array_flip(array_values(get_available_languages())); + $installedTranslations = $this->getInstalledTranslations(); + + $applicableTranslations = array(); + foreach ($translations as $translation) { + //Does it match one of the available core languages? + $isApplicable = array_key_exists($translation->language, $languages); + //Is it more recent than an already-installed translation? + if ( isset($installedTranslations[$translation->language]) ) { + $updateTimestamp = strtotime($translation->updated); + $installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']); + $isApplicable = $updateTimestamp > $installedTimestamp; + } + + if ( $isApplicable ) { + $applicableTranslations[] = $translation; + } + } + + return $applicableTranslations; + } + + /** + * Get a list of installed translations for this plugin or theme. + * + * @return array + */ + protected function getInstalledTranslations() { + if ( !function_exists('wp_get_installed_translations') ) { + return array(); + } + $installedTranslations = wp_get_installed_translations($this->translationType . 's'); + if ( isset($installedTranslations[$this->directoryName]) ) { + $installedTranslations = $installedTranslations[$this->directoryName]; + } else { + $installedTranslations = array(); + } + return $installedTranslations; + } + + /** + * Insert translation updates into the list maintained by WordPress. + * + * @param stdClass $updates + * @return stdClass + */ + public function injectTranslationUpdates($updates) { + $translationUpdates = $this->getTranslationUpdates(); + if ( empty($translationUpdates) ) { + return $updates; + } + + //Being defensive. + if ( !is_object($updates) ) { + $updates = new stdClass(); + } + if ( !isset($updates->translations) ) { + $updates->translations = array(); + } + + //In case there's a name collision with a plugin or theme hosted on wordpress.org, + //remove any preexisting updates that match our thing. + $updates->translations = array_values(array_filter( + $updates->translations, + array($this, 'isNotMyTranslation') + )); + + //Add our updates to the list. + foreach($translationUpdates as $update) { + $convertedUpdate = array_merge( + array( + 'type' => $this->translationType, + 'slug' => $this->directoryName, + 'autoupdate' => 0, + //AFAICT, WordPress doesn't actually use the "version" field for anything. + //But lets make sure it's there, just in case. + 'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)), + ), + (array)$update + ); + + $updates->translations[] = $convertedUpdate; + } + + return $updates; + } + + /** + * Get a list of available translation updates. + * + * This method will return an empty array if there are no updates. + * Uses cached update data. + * + * @return array + */ + public function getTranslationUpdates() { + return $this->updateState->getTranslations(); + } + + /** + * Remove all cached translation updates. + * + * @see wp_clean_update_cache + */ + public function clearCachedTranslationUpdates() { + $this->updateState->setTranslations(array()); + } + + /** + * Filter callback. Keeps only translations that *don't* match this plugin or theme. + * + * @param array $translation + * @return bool + */ + protected function isNotMyTranslation($translation) { + $isMatch = isset($translation['type'], $translation['slug']) + && ($translation['type'] === $this->translationType) + && ($translation['slug'] === $this->directoryName); + + return !$isMatch; + } + + /* ------------------------------------------------------------------- + * Fix directory name when installing updates + * ------------------------------------------------------------------- + */ + + /** + * Rename the update directory to match the existing plugin/theme directory. + * + * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain + * exactly one directory, and that the directory name will be the same as the directory where + * the plugin or theme is currently installed. + * + * GitHub and other repositories provide ZIP downloads, but they often use directory names like + * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder. + * + * This is a hook callback. Don't call it from a plugin. + * + * @access protected + * + * @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource. + * @param string $remoteSource WordPress has extracted the update to this directory. + * @param WP_Upgrader $upgrader + * @return string|WP_Error + */ + public function fixDirectoryName($source, $remoteSource, $upgrader) { + global $wp_filesystem; + /** @var WP_Filesystem_Base $wp_filesystem */ + + //Basic sanity checks. + if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { + return $source; + } + + //If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged. + if ( !$this->isBeingUpgraded($upgrader) ) { + return $source; + } + + //Rename the source to match the existing directory. + $correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/'; + if ( $source !== $correctedSource ) { + //The update archive should contain a single directory that contains the rest of plugin/theme files. + //Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource). + //We can't rename $remoteSource because that would break WordPress code that cleans up temporary files + //after update. + if ( $this->isBadDirectoryStructure($remoteSource) ) { + return new WP_Error( + 'puc-incorrect-directory-structure', + sprintf( + 'The directory structure of the update is incorrect. All files should be inside ' . + 'a directory named %s, not at the root of the ZIP archive.', + htmlentities($this->slug) + ) + ); + } + + /** @var WP_Upgrader_Skin $upgrader ->skin */ + $upgrader->skin->feedback(sprintf( + 'Renaming %s to %s…', + '' . basename($source) . '', + '' . $this->directoryName . '' + )); + + if ( $wp_filesystem->move($source, $correctedSource, true) ) { + $upgrader->skin->feedback('Directory successfully renamed.'); + return $correctedSource; + } else { + return new WP_Error( + 'puc-rename-failed', + 'Unable to rename the update to match the existing directory.' + ); + } + } + + return $source; + } + + /** + * Is there an update being installed right now, for this plugin or theme? + * + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + abstract public function isBeingUpgraded($upgrader = null); + + /** + * Check for incorrect update directory structure. An update must contain a single directory, + * all other files should be inside that directory. + * + * @param string $remoteSource Directory path. + * @return bool + */ + protected function isBadDirectoryStructure($remoteSource) { + global $wp_filesystem; + /** @var WP_Filesystem_Base $wp_filesystem */ + + $sourceFiles = $wp_filesystem->dirlist($remoteSource); + if ( is_array($sourceFiles) ) { + $sourceFiles = array_keys($sourceFiles); + $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0]; + return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)); + } + + //Assume it's fine. + return false; + } + + /* ------------------------------------------------------------------- + * DebugBar integration + * ------------------------------------------------------------------- + */ + + /** + * Initialize the update checker Debug Bar plugin/add-on thingy. + */ + public function maybeInitDebugBar() { + if ( class_exists('Debug_Bar', false) && file_exists(dirname(__FILE__) . '/DebugBar') ) { + $this->createDebugBarExtension(); + } + } + + protected function createDebugBarExtension() { + return new Puc_v4p6_DebugBar_Extension($this); + } + + /** + * Display additional configuration details in the Debug Bar panel. + * + * @param Puc_v4p6_DebugBar_Panel $panel + */ + public function onDisplayConfiguration($panel) { + //Do nothing. Subclasses can use this to add additional info to the panel. + } + + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/UpgraderStatus.php b/admin/includes/plugin-update-checker/Puc/v4p6/UpgraderStatus.php new file mode 100755 index 0000000..89f9161 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/UpgraderStatus.php @@ -0,0 +1,199 @@ +isBeingUpgraded('plugin', $pluginFile, $upgrader); + } + + /** + * Is there an update being installed for a specific theme? + * + * @param string $stylesheet Theme directory name. + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + public function isThemeBeingUpgraded($stylesheet, $upgrader = null) { + return $this->isBeingUpgraded('theme', $stylesheet, $upgrader); + } + + /** + * Check if a specific theme or plugin is being upgraded. + * + * @param string $type + * @param string $id + * @param Plugin_Upgrader|WP_Upgrader|null $upgrader + * @return bool + */ + protected function isBeingUpgraded($type, $id, $upgrader = null) { + if ( isset($upgrader) ) { + list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader); + if ( $currentType !== null ) { + $this->currentType = $currentType; + $this->currentId = $currentId; + } + } + return ($this->currentType === $type) && ($this->currentId === $id); + } + + /** + * Figure out which theme or plugin is being upgraded by a WP_Upgrader instance. + * + * Returns an array with two items. The first item is the type of the thing that's being + * upgraded: "plugin" or "theme". The second item is either the plugin basename or + * the theme directory name. If we can't determine what the upgrader is doing, both items + * will be NULL. + * + * Examples: + * ['plugin', 'plugin-dir-name/plugin.php'] + * ['theme', 'theme-dir-name'] + * + * @param Plugin_Upgrader|WP_Upgrader $upgrader + * @return array + */ + private function getThingBeingUpgradedBy($upgrader) { + if ( !isset($upgrader, $upgrader->skin) ) { + return array(null, null); + } + + //Figure out which plugin or theme is being upgraded. + $pluginFile = null; + $themeDirectoryName = null; + + $skin = $upgrader->skin; + if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) { + $themeDirectoryName = $skin->theme_info->get_stylesheet(); + } elseif ( $skin instanceof Plugin_Upgrader_Skin ) { + if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { + $pluginFile = $skin->plugin; + } + } elseif ( $skin instanceof Theme_Upgrader_Skin ) { + if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) { + $themeDirectoryName = $skin->theme; + } + } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) { + //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin + //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can + //do is compare those headers to the headers of installed plugins. + $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info); + } + + if ( $pluginFile !== null ) { + return array('plugin', $pluginFile); + } elseif ( $themeDirectoryName !== null ) { + return array('theme', $themeDirectoryName); + } + return array(null, null); + } + + /** + * Identify an installed plugin based on its headers. + * + * @param array $searchHeaders The plugin file header to look for. + * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin. + */ + private function identifyPluginByHeaders($searchHeaders) { + if ( !function_exists('get_plugins') ){ + /** @noinspection PhpIncludeInspection */ + require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); + } + + $installedPlugins = get_plugins(); + $matches = array(); + foreach($installedPlugins as $pluginBasename => $headers) { + $diff1 = array_diff_assoc($headers, $searchHeaders); + $diff2 = array_diff_assoc($searchHeaders, $headers); + if ( empty($diff1) && empty($diff2) ) { + $matches[] = $pluginBasename; + } + } + + //It's possible (though very unlikely) that there could be two plugins with identical + //headers. In that case, we can't unambiguously identify the plugin that's being upgraded. + if ( count($matches) !== 1 ) { + return null; + } + + return reset($matches); + } + + /** + * @access private + * + * @param mixed $input + * @param array $hookExtra + * @return mixed Returns $input unaltered. + */ + public function setUpgradedThing($input, $hookExtra) { + if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) { + $this->currentId = $hookExtra['plugin']; + $this->currentType = 'plugin'; + } elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) { + $this->currentId = $hookExtra['theme']; + $this->currentType = 'theme'; + } else { + $this->currentType = null; + $this->currentId = null; + } + return $input; + } + + /** + * @access private + * + * @param array $options + * @return array + */ + public function setUpgradedPluginFromOptions($options) { + if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) { + $this->currentType = 'plugin'; + $this->currentId = $options['hook_extra']['plugin']; + } else { + $this->currentType = null; + $this->currentId = null; + } + return $options; + } + + /** + * @access private + * + * @param mixed $input + * @return mixed Returns $input unaltered. + */ + public function clearUpgradedThing($input = null) { + $this->currentId = null; + $this->currentType = null; + return $input; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Utils.php b/admin/includes/plugin-update-checker/Puc/v4p6/Utils.php new file mode 100755 index 0000000..6c4f0a9 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Utils.php @@ -0,0 +1,69 @@ +$node) ) { + $currentValue = $currentValue->$node; + } else { + return $default; + } + } + + return $currentValue; + } + + /** + * Get the first array element that is not empty. + * + * @param array $values + * @param mixed|null $default Returns this value if there are no non-empty elements. + * @return mixed|null + */ + public static function findNotEmpty($values, $default = null) { + if ( empty($values) ) { + return $default; + } + + foreach ($values as $value) { + if ( !empty($value) ) { + return $value; + } + } + + return $default; + } + + /** + * Check if the input string starts with the specified prefix. + * + * @param string $input + * @param string $prefix + * @return bool + */ + public static function startsWith($input, $prefix) { + $length = strlen($prefix); + return (substr($input, 0, $length) === $prefix); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Api.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Api.php new file mode 100755 index 0000000..9f27cd2 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Api.php @@ -0,0 +1,302 @@ +repositoryUrl = $repositoryUrl; + $this->setAuthentication($credentials); + } + + /** + * @return string + */ + public function getRepositoryUrl() { + return $this->repositoryUrl; + } + + /** + * Figure out which reference (i.e tag or branch) contains the latest version. + * + * @param string $configBranch Start looking in this branch. + * @return null|Puc_v4p6_Vcs_Reference + */ + abstract public function chooseReference($configBranch); + + /** + * Get the readme.txt file from the remote repository and parse it + * according to the plugin readme standard. + * + * @param string $ref Tag or branch name. + * @return array Parsed readme. + */ + public function getRemoteReadme($ref = 'master') { + $fileContents = $this->getRemoteFile($this->getLocalReadmeName(), $ref); + if ( empty($fileContents) ) { + return array(); + } + + $parser = new PucReadmeParser(); + return $parser->parse_readme_contents($fileContents); + } + + /** + * Get the case-sensitive name of the local readme.txt file. + * + * In most cases it should just be called "readme.txt", but some plugins call it "README.txt", + * "README.TXT", or even "Readme.txt". Most VCS are case-sensitive so we need to know the correct + * capitalization. + * + * Defaults to "readme.txt" (all lowercase). + * + * @return string + */ + public function getLocalReadmeName() { + static $fileName = null; + if ( $fileName !== null ) { + return $fileName; + } + + $fileName = 'readme.txt'; + if ( isset($this->localDirectory) ) { + $files = scandir($this->localDirectory); + if ( !empty($files) ) { + foreach ($files as $possibleFileName) { + if ( strcasecmp($possibleFileName, 'readme.txt') === 0 ) { + $fileName = $possibleFileName; + break; + } + } + } + } + return $fileName; + } + + /** + * Get a branch. + * + * @param string $branchName + * @return Puc_v4p6_Vcs_Reference|null + */ + abstract public function getBranch($branchName); + + /** + * Get a specific tag. + * + * @param string $tagName + * @return Puc_v4p6_Vcs_Reference|null + */ + abstract public function getTag($tagName); + + /** + * Get the tag that looks like the highest version number. + * (Implementations should skip pre-release versions if possible.) + * + * @return Puc_v4p6_Vcs_Reference|null + */ + abstract public function getLatestTag(); + + /** + * Check if a tag name string looks like a version number. + * + * @param string $name + * @return bool + */ + protected function looksLikeVersion($name) { + //Tag names may be prefixed with "v", e.g. "v1.2.3". + $name = ltrim($name, 'v'); + + //The version string must start with a number. + if ( !is_numeric(substr($name, 0, 1)) ) { + return false; + } + + //The goal is to accept any SemVer-compatible or "PHP-standardized" version number. + return (preg_match('@^(\d{1,5}?)(\.\d{1,10}?){0,4}?($|[abrdp+_\-]|\s)@i', $name) === 1); + } + + /** + * Check if a tag appears to be named like a version number. + * + * @param stdClass $tag + * @return bool + */ + protected function isVersionTag($tag) { + $property = $this->tagNameProperty; + return isset($tag->$property) && $this->looksLikeVersion($tag->$property); + } + + /** + * Sort a list of tags as if they were version numbers. + * Tags that don't look like version number will be removed. + * + * @param stdClass[] $tags Array of tag objects. + * @return stdClass[] Filtered array of tags sorted in descending order. + */ + protected function sortTagsByVersion($tags) { + //Keep only those tags that look like version numbers. + $versionTags = array_filter($tags, array($this, 'isVersionTag')); + //Sort them in descending order. + usort($versionTags, array($this, 'compareTagNames')); + + return $versionTags; + } + + /** + * Compare two tags as if they were version number. + * + * @param stdClass $tag1 Tag object. + * @param stdClass $tag2 Another tag object. + * @return int + */ + protected function compareTagNames($tag1, $tag2) { + $property = $this->tagNameProperty; + if ( !isset($tag1->$property) ) { + return 1; + } + if ( !isset($tag2->$property) ) { + return -1; + } + return -version_compare(ltrim($tag1->$property, 'v'), ltrim($tag2->$property, 'v')); + } + + /** + * Get the contents of a file from a specific branch or tag. + * + * @param string $path File name. + * @param string $ref + * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error. + */ + abstract public function getRemoteFile($path, $ref = 'master'); + + /** + * Get the timestamp of the latest commit that changed the specified branch or tag. + * + * @param string $ref Reference name (e.g. branch or tag). + * @return string|null + */ + abstract public function getLatestCommitTime($ref); + + /** + * Get the contents of the changelog file from the repository. + * + * @param string $ref + * @param string $localDirectory Full path to the local plugin or theme directory. + * @return null|string The HTML contents of the changelog. + */ + public function getRemoteChangelog($ref, $localDirectory) { + $filename = $this->findChangelogName($localDirectory); + if ( empty($filename) ) { + return null; + } + + $changelog = $this->getRemoteFile($filename, $ref); + if ( $changelog === null ) { + return null; + } + + /** @noinspection PhpUndefinedClassInspection */ + return Parsedown::instance()->text($changelog); + } + + /** + * Guess the name of the changelog file. + * + * @param string $directory + * @return string|null + */ + protected function findChangelogName($directory = null) { + if ( !isset($directory) ) { + $directory = $this->localDirectory; + } + if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) { + return null; + } + + $possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md'); + $files = scandir($directory); + $foundNames = array_intersect($possibleNames, $files); + + if ( !empty($foundNames) ) { + return reset($foundNames); + } + return null; + } + + /** + * Set authentication credentials. + * + * @param $credentials + */ + public function setAuthentication($credentials) { + $this->credentials = $credentials; + } + + public function isAuthenticationEnabled() { + return !empty($this->credentials); + } + + /** + * @param string $url + * @return string + */ + public function signDownloadUrl($url) { + return $url; + } + + /** + * @param string $filterName + */ + public function setHttpFilterName($filterName) { + $this->httpFilterName = $filterName; + } + + /** + * @param string $directory + */ + public function setLocalDirectory($directory) { + if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) { + $this->localDirectory = null; + } else { + $this->localDirectory = $directory; + } + } + + /** + * @param string $slug + */ + public function setSlug($slug) { + $this->slug = $slug; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/BaseChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/BaseChecker.php new file mode 100755 index 0000000..85a5715 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/BaseChecker.php @@ -0,0 +1,27 @@ +[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) { + $this->username = $matches['username']; + $this->repository = $matches['repository']; + } else { + throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"'); + } + + parent::__construct($repositoryUrl, $credentials); + } + + /** + * Figure out which reference (i.e tag or branch) contains the latest version. + * + * @param string $configBranch Start looking in this branch. + * @return null|Puc_v4p6_Vcs_Reference + */ + public function chooseReference($configBranch) { + $updateSource = null; + + //Check if there's a "Stable tag: 1.2.3" header that points to a valid tag. + $updateSource = $this->getStableTag($configBranch); + + //Look for version-like tags. + if ( !$updateSource && ($configBranch === 'master') ) { + $updateSource = $this->getLatestTag(); + } + //If all else fails, use the specified branch itself. + if ( !$updateSource ) { + $updateSource = $this->getBranch($configBranch); + } + + return $updateSource; + } + + public function getBranch($branchName) { + $branch = $this->api('/refs/branches/' . $branchName); + if ( is_wp_error($branch) || empty($branch) ) { + return null; + } + + return new Puc_v4p6_Vcs_Reference(array( + 'name' => $branch->name, + 'updated' => $branch->target->date, + 'downloadUrl' => $this->getDownloadUrl($branch->name), + )); + } + + /** + * Get a specific tag. + * + * @param string $tagName + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getTag($tagName) { + $tag = $this->api('/refs/tags/' . $tagName); + if ( is_wp_error($tag) || empty($tag) ) { + return null; + } + + return new Puc_v4p6_Vcs_Reference(array( + 'name' => $tag->name, + 'version' => ltrim($tag->name, 'v'), + 'updated' => $tag->target->date, + 'downloadUrl' => $this->getDownloadUrl($tag->name), + )); + } + + /** + * Get the tag that looks like the highest version number. + * + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getLatestTag() { + $tags = $this->api('/refs/tags?sort=-target.date'); + if ( !isset($tags, $tags->values) || !is_array($tags->values) ) { + return null; + } + + //Filter and sort the list of tags. + $versionTags = $this->sortTagsByVersion($tags->values); + + //Return the first result. + if ( !empty($versionTags) ) { + $tag = $versionTags[0]; + return new Puc_v4p6_Vcs_Reference(array( + 'name' => $tag->name, + 'version' => ltrim($tag->name, 'v'), + 'updated' => $tag->target->date, + 'downloadUrl' => $this->getDownloadUrl($tag->name), + )); + } + return null; + } + + /** + * Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch. + * + * @param string $branch + * @return null|Puc_v4p6_Vcs_Reference + */ + protected function getStableTag($branch) { + $remoteReadme = $this->getRemoteReadme($branch); + if ( !empty($remoteReadme['stable_tag']) ) { + $tag = $remoteReadme['stable_tag']; + + //You can explicitly opt out of using tags by setting "Stable tag" to + //"trunk" or the name of the current branch. + if ( ($tag === $branch) || ($tag === 'trunk') ) { + return $this->getBranch($branch); + } + + return $this->getTag($tag); + } + + return null; + } + + /** + * @param string $ref + * @return string + */ + protected function getDownloadUrl($ref) { + return sprintf( + 'https://bitbucket.org/%s/%s/get/%s.zip', + $this->username, + $this->repository, + $ref + ); + } + + /** + * Get the contents of a file from a specific branch or tag. + * + * @param string $path File name. + * @param string $ref + * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error. + */ + public function getRemoteFile($path, $ref = 'master') { + $response = $this->api('src/' . $ref . '/' . ltrim($path)); + if ( is_wp_error($response) || !is_string($response) ) { + return null; + } + return $response; + } + + /** + * Get the timestamp of the latest commit that changed the specified branch or tag. + * + * @param string $ref Reference name (e.g. branch or tag). + * @return string|null + */ + public function getLatestCommitTime($ref) { + $response = $this->api('commits/' . $ref); + if ( isset($response->values, $response->values[0], $response->values[0]->date) ) { + return $response->values[0]->date; + } + return null; + } + + /** + * Perform a BitBucket API 2.0 request. + * + * @param string $url + * @param string $version + * @return mixed|WP_Error + */ + public function api($url, $version = '2.0') { + $url = ltrim($url, '/'); + $isSrcResource = Puc_v4p6_Utils::startsWith($url, 'src/'); + + $url = implode('/', array( + 'https://api.bitbucket.org', + $version, + 'repositories', + $this->username, + $this->repository, + $url + )); + $baseUrl = $url; + + if ( $this->oauth ) { + $url = $this->oauth->sign($url,'GET'); + } + + $options = array('timeout' => 10); + if ( !empty($this->httpFilterName) ) { + $options = apply_filters($this->httpFilterName, $options); + } + $response = wp_remote_get($url, $options); + if ( is_wp_error($response) ) { + do_action('puc_api_error', $response, null, $url, $this->slug); + return $response; + } + + $code = wp_remote_retrieve_response_code($response); + $body = wp_remote_retrieve_body($response); + if ( $code === 200 ) { + if ( $isSrcResource ) { + //Most responses are JSON-encoded, but src resources just + //return raw file contents. + $document = $body; + } else { + $document = json_decode($body); + } + return $document; + } + + $error = new WP_Error( + 'puc-bitbucket-http-error', + sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code) + ); + do_action('puc_api_error', $error, $response, $url, $this->slug); + + return $error; + } + + /** + * @param array $credentials + */ + public function setAuthentication($credentials) { + parent::setAuthentication($credentials); + + if ( !empty($credentials) && !empty($credentials['consumer_key']) ) { + $this->oauth = new Puc_v4p6_OAuthSignature( + $credentials['consumer_key'], + $credentials['consumer_secret'] + ); + } else { + $this->oauth = null; + } + } + + public function signDownloadUrl($url) { + //Add authentication data to download URLs. Since OAuth signatures incorporate + //timestamps, we have to do this immediately before inserting the update. Otherwise + //authentication could fail due to a stale timestamp. + if ( $this->oauth ) { + $url = $this->oauth->sign($url); + } + return $url; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitHubApi.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitHubApi.php new file mode 100755 index 0000000..f5273f6 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitHubApi.php @@ -0,0 +1,413 @@ +[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) { + $this->userName = $matches['username']; + $this->repositoryName = $matches['repository']; + } else { + throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"'); + } + + parent::__construct($repositoryUrl, $accessToken); + } + + /** + * Get the latest release from GitHub. + * + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getLatestRelease() { + $release = $this->api('/repos/:user/:repo/releases/latest'); + if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) { + return null; + } + + $reference = new Puc_v4p6_Vcs_Reference(array( + 'name' => $release->tag_name, + 'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3". + 'downloadUrl' => $this->signDownloadUrl($release->zipball_url), + 'updated' => $release->created_at, + 'apiResponse' => $release, + )); + + if ( isset($release->assets[0]) ) { + $reference->downloadCount = $release->assets[0]->download_count; + } + + if ( $this->releaseAssetsEnabled && isset($release->assets, $release->assets[0]) ) { + //Use the first release asset that matches the specified regular expression. + $matchingAssets = array_filter($release->assets, array($this, 'matchesAssetFilter')); + if ( !empty($matchingAssets) ) { + if ( $this->isAuthenticationEnabled() ) { + /** + * Keep in mind that we'll need to add an "Accept" header to download this asset. + * @see setReleaseDownloadHeader() + */ + $reference->downloadUrl = $this->signDownloadUrl($matchingAssets[0]->url); + } else { + //It seems that browser_download_url only works for public repositories. + //Using an access_token doesn't help. Maybe OAuth would work? + $reference->downloadUrl = $matchingAssets[0]->browser_download_url; + } + + $reference->downloadCount = $matchingAssets[0]->download_count; + } + } + + if ( !empty($release->body) ) { + /** @noinspection PhpUndefinedClassInspection */ + $reference->changelog = Parsedown::instance()->text($release->body); + } + + return $reference; + } + + /** + * Get the tag that looks like the highest version number. + * + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getLatestTag() { + $tags = $this->api('/repos/:user/:repo/tags'); + + if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) { + return null; + } + + $versionTags = $this->sortTagsByVersion($tags); + if ( empty($versionTags) ) { + return null; + } + + $tag = $versionTags[0]; + return new Puc_v4p6_Vcs_Reference(array( + 'name' => $tag->name, + 'version' => ltrim($tag->name, 'v'), + 'downloadUrl' => $this->signDownloadUrl($tag->zipball_url), + 'apiResponse' => $tag, + )); + } + + /** + * Get a branch by name. + * + * @param string $branchName + * @return null|Puc_v4p6_Vcs_Reference + */ + public function getBranch($branchName) { + $branch = $this->api('/repos/:user/:repo/branches/' . $branchName); + if ( is_wp_error($branch) || empty($branch) ) { + return null; + } + + $reference = new Puc_v4p6_Vcs_Reference(array( + 'name' => $branch->name, + 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name), + 'apiResponse' => $branch, + )); + + if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) { + $reference->updated = $branch->commit->commit->author->date; + } + + return $reference; + } + + /** + * Get the latest commit that changed the specified file. + * + * @param string $filename + * @param string $ref Reference name (e.g. branch or tag). + * @return StdClass|null + */ + public function getLatestCommit($filename, $ref = 'master') { + $commits = $this->api( + '/repos/:user/:repo/commits', + array( + 'path' => $filename, + 'sha' => $ref, + ) + ); + if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) { + return $commits[0]; + } + return null; + } + + /** + * Get the timestamp of the latest commit that changed the specified branch or tag. + * + * @param string $ref Reference name (e.g. branch or tag). + * @return string|null + */ + public function getLatestCommitTime($ref) { + $commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref)); + if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) { + return $commits[0]->commit->author->date; + } + return null; + } + + /** + * Perform a GitHub API request. + * + * @param string $url + * @param array $queryParams + * @return mixed|WP_Error + */ + protected function api($url, $queryParams = array()) { + $baseUrl = $url; + $url = $this->buildApiUrl($url, $queryParams); + + $options = array('timeout' => 10); + if ( !empty($this->httpFilterName) ) { + $options = apply_filters($this->httpFilterName, $options); + } + $response = wp_remote_get($url, $options); + if ( is_wp_error($response) ) { + do_action('puc_api_error', $response, null, $url, $this->slug); + return $response; + } + + $code = wp_remote_retrieve_response_code($response); + $body = wp_remote_retrieve_body($response); + if ( $code === 200 ) { + $document = json_decode($body); + return $document; + } + + $error = new WP_Error( + 'puc-github-http-error', + sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code) + ); + do_action('puc_api_error', $error, $response, $url, $this->slug); + + return $error; + } + + /** + * Build a fully qualified URL for an API request. + * + * @param string $url + * @param array $queryParams + * @return string + */ + protected function buildApiUrl($url, $queryParams) { + $variables = array( + 'user' => $this->userName, + 'repo' => $this->repositoryName, + ); + foreach ($variables as $name => $value) { + $url = str_replace('/:' . $name, '/' . urlencode($value), $url); + } + $url = 'https://api.github.com' . $url; + + if ( !empty($this->accessToken) ) { + $queryParams['access_token'] = $this->accessToken; + } + if ( !empty($queryParams) ) { + $url = add_query_arg($queryParams, $url); + } + + return $url; + } + + /** + * Get the contents of a file from a specific branch or tag. + * + * @param string $path File name. + * @param string $ref + * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error. + */ + public function getRemoteFile($path, $ref = 'master') { + $apiUrl = '/repos/:user/:repo/contents/' . $path; + $response = $this->api($apiUrl, array('ref' => $ref)); + + if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) { + return null; + } + return base64_decode($response->content); + } + + /** + * Generate a URL to download a ZIP archive of the specified branch/tag/etc. + * + * @param string $ref + * @return string + */ + public function buildArchiveDownloadUrl($ref = 'master') { + $url = sprintf( + 'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s', + urlencode($this->userName), + urlencode($this->repositoryName), + urlencode($ref) + ); + if ( !empty($this->accessToken) ) { + $url = $this->signDownloadUrl($url); + } + return $url; + } + + /** + * Get a specific tag. + * + * @param string $tagName + * @return void + */ + public function getTag($tagName) { + //The current GitHub update checker doesn't use getTag, so I didn't bother to implement it. + throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.'); + } + + public function setAuthentication($credentials) { + parent::setAuthentication($credentials); + $this->accessToken = is_string($credentials) ? $credentials : null; + } + + /** + * Figure out which reference (i.e tag or branch) contains the latest version. + * + * @param string $configBranch Start looking in this branch. + * @return null|Puc_v4p6_Vcs_Reference + */ + public function chooseReference($configBranch) { + $updateSource = null; + + if ( $configBranch === 'master' ) { + //Use the latest release. + $updateSource = $this->getLatestRelease(); + if ( $updateSource === null ) { + //Failing that, use the tag with the highest version number. + $updateSource = $this->getLatestTag(); + } + } + //Alternatively, just use the branch itself. + if ( empty($updateSource) ) { + $updateSource = $this->getBranch($configBranch); + } + + return $updateSource; + } + + /** + * @param string $url + * @return string + */ + public function signDownloadUrl($url) { + if ( empty($this->credentials) ) { + return $url; + } + return add_query_arg('access_token', $this->credentials, $url); + } + + /** + * Enable updating via release assets. + * + * If the latest release contains no usable assets, the update checker + * will fall back to using the automatically generated ZIP archive. + * + * Private repositories will only work with WordPress 3.7 or later. + * + * @param string|null $fileNameRegex Optional. Use only those assets where the file name matches this regex. + */ + public function enableReleaseAssets($fileNameRegex = null) { + $this->releaseAssetsEnabled = true; + $this->assetFilterRegex = $fileNameRegex; + $this->assetApiBaseUrl = sprintf( + '//api.github.com/repos/%1$s/%2$s/releases/assets/', + $this->userName, + $this->repositoryName + ); + + //Optimization: Instead of filtering all HTTP requests, let's do it only when + //WordPress is about to download an update. + add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+ + } + + /** + * Does this asset match the file name regex? + * + * @param stdClass $releaseAsset + * @return bool + */ + protected function matchesAssetFilter($releaseAsset) { + if ( $this->assetFilterRegex === null ) { + //The default is to accept all assets. + return true; + } + return isset($releaseAsset->name) && preg_match($this->assetFilterRegex, $releaseAsset->name); + } + + /** + * @internal + * @param bool $result + * @return bool + */ + public function addHttpRequestFilter($result) { + static $filterAdded = false; + if ( $this->releaseAssetsEnabled && !$filterAdded && $this->isAuthenticationEnabled() ) { + add_filter('http_request_args', array($this, 'setReleaseDownloadHeader'), 10, 2); + $filterAdded = true; + } + return $result; + } + + /** + * Set the HTTP header that's necessary to download private release assets. + * + * See GitHub docs: + * @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset + * + * @internal + * @param array $requestArgs + * @param string $url + * @return array + */ + public function setReleaseDownloadHeader($requestArgs, $url = '') { + //Is WordPress trying to download one of our assets? + if ( strpos($url, $this->assetApiBaseUrl) !== false ) { + $requestArgs['headers']['accept'] = 'application/octet-stream'; + } + return $requestArgs; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitLabApi.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitLabApi.php new file mode 100755 index 0000000..a4c11e7 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/GitLabApi.php @@ -0,0 +1,297 @@ +repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port; + + if ( $this->repositoryHost !== 'gitlab.com' ) { + $this->repositoryProtocol = parse_url($repositoryUrl, PHP_URL_SCHEME); + } + + //Find the repository information + $path = parse_url($repositoryUrl, PHP_URL_PATH); + if ( preg_match('@^/?(?P[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) { + $this->userName = $matches['username']; + $this->repositoryName = $matches['repository']; + } elseif ( ($this->repositoryHost === 'gitlab.com') ) { + //This is probably a repository in a subgroup, e.g. "/organization/category/repo". + $parts = explode('/', trim($path, '/')); + if ( count($parts) < 3 ) { + throw new InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"'); + } + $lastPart = array_pop($parts); + $this->userName = implode('/', $parts); + $this->repositoryName = $lastPart; + } else { + //This is not a traditional url, it could be gitlab is in a deeper subdirectory. + //Get the path segments. + $segments = explode('/', untrailingslashit(ltrim($path, '/'))); + + //We need at least /user-name/repository-name/ + if ( count($segments) < 2 ) { + throw new InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"'); + } + + //Get the username and repository name. + $usernameRepo = array_splice($segments, -2, 2); + $this->userName = $usernameRepo[0]; + $this->repositoryName = $usernameRepo[1]; + + //Append the remaining segments to the host. + $this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments); + } + + parent::__construct($repositoryUrl, $accessToken); + } + + /** + * Get the latest release from GitLab. + * + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getLatestRelease() { + return $this->getLatestTag(); + } + + /** + * Get the tag that looks like the highest version number. + * + * @return Puc_v4p6_Vcs_Reference|null + */ + public function getLatestTag() { + $tags = $this->api('/:id/repository/tags'); + if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) { + return null; + } + + $versionTags = $this->sortTagsByVersion($tags); + if ( empty($versionTags) ) { + return null; + } + + $tag = $versionTags[0]; + return new Puc_v4p6_Vcs_Reference(array( + 'name' => $tag->name, + 'version' => ltrim($tag->name, 'v'), + 'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name), + 'apiResponse' => $tag + )); + } + + /** + * Get a branch by name. + * + * @param string $branchName + * @return null|Puc_v4p6_Vcs_Reference + */ + public function getBranch($branchName) { + $branch = $this->api('/:id/repository/branches/' . $branchName); + if ( is_wp_error($branch) || empty($branch) ) { + return null; + } + + $reference = new Puc_v4p6_Vcs_Reference(array( + 'name' => $branch->name, + 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name), + 'apiResponse' => $branch, + )); + + if ( isset($branch->commit, $branch->commit->committed_date) ) { + $reference->updated = $branch->commit->committed_date; + } + + return $reference; + } + + /** + * Get the timestamp of the latest commit that changed the specified branch or tag. + * + * @param string $ref Reference name (e.g. branch or tag). + * @return string|null + */ + public function getLatestCommitTime($ref) { + $commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref)); + if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) { + return null; + } + + return $commits[0]->committed_date; + } + + /** + * Perform a GitLab API request. + * + * @param string $url + * @param array $queryParams + * @return mixed|WP_Error + */ + protected function api($url, $queryParams = array()) { + $baseUrl = $url; + $url = $this->buildApiUrl($url, $queryParams); + + $options = array('timeout' => 10); + if ( !empty($this->httpFilterName) ) { + $options = apply_filters($this->httpFilterName, $options); + } + + $response = wp_remote_get($url, $options); + if ( is_wp_error($response) ) { + do_action('puc_api_error', $response, null, $url, $this->slug); + return $response; + } + + $code = wp_remote_retrieve_response_code($response); + $body = wp_remote_retrieve_body($response); + if ( $code === 200 ) { + return json_decode($body); + } + + $error = new WP_Error( + 'puc-gitlab-http-error', + sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code) + ); + do_action('puc_api_error', $error, $response, $url, $this->slug); + + return $error; + } + + /** + * Build a fully qualified URL for an API request. + * + * @param string $url + * @param array $queryParams + * @return string + */ + protected function buildApiUrl($url, $queryParams) { + $variables = array( + 'user' => $this->userName, + 'repo' => $this->repositoryName, + 'id' => $this->userName . '/' . $this->repositoryName, + ); + + foreach ($variables as $name => $value) { + $url = str_replace("/:{$name}", '/' . urlencode($value), $url); + } + + $url = substr($url, 1); + $url = sprintf('%1$s://%2$s/api/v4/projects/%3$s', $this->repositoryProtocol, $this->repositoryHost, $url); + + if ( !empty($this->accessToken) ) { + $queryParams['private_token'] = $this->accessToken; + } + + if ( !empty($queryParams) ) { + $url = add_query_arg($queryParams, $url); + } + + return $url; + } + + /** + * Get the contents of a file from a specific branch or tag. + * + * @param string $path File name. + * @param string $ref + * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error. + */ + public function getRemoteFile($path, $ref = 'master') { + $response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref)); + if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) { + return null; + } + + return base64_decode($response->content); + } + + /** + * Generate a URL to download a ZIP archive of the specified branch/tag/etc. + * + * @param string $ref + * @return string + */ + public function buildArchiveDownloadUrl($ref = 'master') { + $url = sprintf( + '%1$s://%2$s/api/v4/projects/%3$s/repository/archive.zip', + $this->repositoryProtocol, + $this->repositoryHost, + urlencode($this->userName . '/' . $this->repositoryName) + ); + $url = add_query_arg('sha', urlencode($ref), $url); + + if ( !empty($this->accessToken) ) { + $url = add_query_arg('private_token', $this->accessToken, $url); + } + + return $url; + } + + /** + * Get a specific tag. + * + * @param string $tagName + * @return void + */ + public function getTag($tagName) { + throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.'); + } + + /** + * Figure out which reference (i.e tag or branch) contains the latest version. + * + * @param string $configBranch Start looking in this branch. + * @return null|Puc_v4p6_Vcs_Reference + */ + public function chooseReference($configBranch) { + $updateSource = null; + + // GitLab doesn't handle releases the same as GitHub so just use the latest tag + if ( $configBranch === 'master' ) { + $updateSource = $this->getLatestTag(); + } + + if ( empty($updateSource) ) { + $updateSource = $this->getBranch($configBranch); + } + + return $updateSource; + } + + public function setAuthentication($credentials) { + parent::setAuthentication($credentials); + $this->accessToken = is_string($credentials) ? $credentials : null; + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/PluginUpdateChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/PluginUpdateChecker.php new file mode 100755 index 0000000..3ca3dad --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/PluginUpdateChecker.php @@ -0,0 +1,213 @@ +api = $api; + $this->api->setHttpFilterName($this->getUniqueName('request_info_options')); + + parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile); + + $this->api->setSlug($this->slug); + } + + public function requestInfo($unusedParameter = null) { + //We have to make several remote API requests to gather all the necessary info + //which can take a while on slow networks. + if ( function_exists('set_time_limit') ) { + @set_time_limit(60); + } + + $api = $this->api; + $api->setLocalDirectory($this->package->getAbsoluteDirectoryPath()); + + $info = new Puc_v4p6_Plugin_Info(); + $info->filename = $this->pluginFile; + $info->slug = $this->slug; + + $this->setInfoFromHeader($this->package->getPluginHeader(), $info); + + //Pick a branch or tag. + $updateSource = $api->chooseReference($this->branch); + if ( $updateSource ) { + $ref = $updateSource->name; + $info->version = $updateSource->version; + $info->last_updated = $updateSource->updated; + $info->download_url = $updateSource->downloadUrl; + + if ( !empty($updateSource->changelog) ) { + $info->sections['changelog'] = $updateSource->changelog; + } + if ( isset($updateSource->downloadCount) ) { + $info->downloaded = $updateSource->downloadCount; + } + } else { + //There's probably a network problem or an authentication error. + do_action( + 'puc_api_error', + new WP_Error( + 'puc-no-update-source', + 'Could not retrieve version information from the repository. ' + . 'This usually means that the update checker either can\'t connect ' + . 'to the repository or it\'s configured incorrectly.' + ), + null, null, $this->slug + ); + return null; + } + + //Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata + //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags. + $mainPluginFile = basename($this->pluginFile); + $remotePlugin = $api->getRemoteFile($mainPluginFile, $ref); + if ( !empty($remotePlugin) ) { + $remoteHeader = $this->package->getFileHeader($remotePlugin); + $this->setInfoFromHeader($remoteHeader, $info); + } + + //Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain + //a lot of useful information like the required/tested WP version, changelog, and so on. + if ( $this->readmeTxtExistsLocally() ) { + $this->setInfoFromRemoteReadme($ref, $info); + } + + //The changelog might be in a separate file. + if ( empty($info->sections['changelog']) ) { + $info->sections['changelog'] = $api->getRemoteChangelog($ref, $this->package->getAbsoluteDirectoryPath()); + if ( empty($info->sections['changelog']) ) { + $info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker'); + } + } + + if ( empty($info->last_updated) ) { + //Fetch the latest commit that changed the tag or branch and use it as the "last_updated" date. + $latestCommitTime = $api->getLatestCommitTime($ref); + if ( $latestCommitTime !== null ) { + $info->last_updated = $latestCommitTime; + } + } + + $info = apply_filters($this->getUniqueName('request_info_result'), $info, null); + return $info; + } + + /** + * Check if the currently installed version has a readme.txt file. + * + * @return bool + */ + protected function readmeTxtExistsLocally() { + return $this->package->fileExists($this->api->getLocalReadmeName()); + } + + /** + * Copy plugin metadata from a file header to a Plugin Info object. + * + * @param array $fileHeader + * @param Puc_v4p6_Plugin_Info $pluginInfo + */ + protected function setInfoFromHeader($fileHeader, $pluginInfo) { + $headerToPropertyMap = array( + 'Version' => 'version', + 'Name' => 'name', + 'PluginURI' => 'homepage', + 'Author' => 'author', + 'AuthorName' => 'author', + 'AuthorURI' => 'author_homepage', + + 'Requires WP' => 'requires', + 'Tested WP' => 'tested', + 'Requires at least' => 'requires', + 'Tested up to' => 'tested', + ); + foreach ($headerToPropertyMap as $headerName => $property) { + if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) { + $pluginInfo->$property = $fileHeader[$headerName]; + } + } + + if ( !empty($fileHeader['Description']) ) { + $pluginInfo->sections['description'] = $fileHeader['Description']; + } + } + + /** + * Copy plugin metadata from the remote readme.txt file. + * + * @param string $ref GitHub tag or branch where to look for the readme. + * @param Puc_v4p6_Plugin_Info $pluginInfo + */ + protected function setInfoFromRemoteReadme($ref, $pluginInfo) { + $readme = $this->api->getRemoteReadme($ref); + if ( empty($readme) ) { + return; + } + + if ( isset($readme['sections']) ) { + $pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']); + } + if ( !empty($readme['tested_up_to']) ) { + $pluginInfo->tested = $readme['tested_up_to']; + } + if ( !empty($readme['requires_at_least']) ) { + $pluginInfo->requires = $readme['requires_at_least']; + } + + if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) { + $pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version]; + } + } + + public function setBranch($branch) { + $this->branch = $branch; + return $this; + } + + public function setAuthentication($credentials) { + $this->api->setAuthentication($credentials); + return $this; + } + + public function getVcsApi() { + return $this->api; + } + + public function getUpdate() { + $update = parent::getUpdate(); + + if ( isset($update) && !empty($update->download_url) ) { + $update->download_url = $this->api->signDownloadUrl($update->download_url); + } + + return $update; + } + + public function onDisplayConfiguration($panel) { + parent::onDisplayConfiguration($panel); + $panel->row('Branch', $this->branch); + $panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No'); + $panel->row('API client', get_class($this->api)); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Reference.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Reference.php new file mode 100755 index 0000000..fc60eb8 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/Reference.php @@ -0,0 +1,49 @@ +properties = $properties; + } + + /** + * @param string $name + * @return mixed|null + */ + public function __get($name) { + return array_key_exists($name, $this->properties) ? $this->properties[$name] : null; + } + + /** + * @param string $name + * @param mixed $value + */ + public function __set($name, $value) { + $this->properties[$name] = $value; + } + + /** + * @param string $name + * @return bool + */ + public function __isset($name) { + return isset($this->properties[$name]); + } + + } + +endif; diff --git a/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/ThemeUpdateChecker.php b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/ThemeUpdateChecker.php new file mode 100755 index 0000000..082e456 --- /dev/null +++ b/admin/includes/plugin-update-checker/Puc/v4p6/Vcs/ThemeUpdateChecker.php @@ -0,0 +1,118 @@ +api = $api; + $this->api->setHttpFilterName($this->getUniqueName('request_update_options')); + + parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName); + + $this->api->setSlug($this->slug); + } + + public function requestUpdate() { + $api = $this->api; + $api->setLocalDirectory($this->package->getAbsoluteDirectoryPath()); + + $update = new Puc_v4p6_Theme_Update(); + $update->slug = $this->slug; + + //Figure out which reference (tag or branch) we'll use to get the latest version of the theme. + $updateSource = $api->chooseReference($this->branch); + if ( $updateSource ) { + $ref = $updateSource->name; + $update->download_url = $updateSource->downloadUrl; + } else { + do_action( + 'puc_api_error', + new WP_Error( + 'puc-no-update-source', + 'Could not retrieve version information from the repository. ' + . 'This usually means that the update checker either can\'t connect ' + . 'to the repository or it\'s configured incorrectly.' + ), + null, null, $this->slug + ); + $ref = $this->branch; + } + + //Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata + //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags. + $remoteHeader = $this->package->getFileHeader($api->getRemoteFile('style.css', $ref)); + $update->version = Puc_v4p6_Utils::findNotEmpty(array( + $remoteHeader['Version'], + Puc_v4p6_Utils::get($updateSource, 'version'), + )); + + //The details URL defaults to the Theme URI header or the repository URL. + $update->details_url = Puc_v4p6_Utils::findNotEmpty(array( + $remoteHeader['ThemeURI'], + $this->package->getHeaderValue('ThemeURI'), + $this->metadataUrl, + )); + + if ( empty($update->version) ) { + //It looks like we didn't find a valid update after all. + $update = null; + } + + $update = $this->filterUpdateResult($update); + return $update; + } + + //FIXME: This is duplicated code. Both theme and plugin subclasses that use VCS share these methods. + + public function setBranch($branch) { + $this->branch = $branch; + return $this; + } + + public function setAuthentication($credentials) { + $this->api->setAuthentication($credentials); + return $this; + } + + public function getVcsApi() { + return $this->api; + } + + public function getUpdate() { + $update = parent::getUpdate(); + + if ( isset($update) && !empty($update->download_url) ) { + $update->download_url = $this->api->signDownloadUrl($update->download_url); + } + + return $update; + } + + public function onDisplayConfiguration($panel) { + parent::onDisplayConfiguration($panel); + $panel->row('Branch', $this->branch); + $panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No'); + $panel->row('API client', get_class($this->api)); + } + } + +endif; diff --git a/admin/includes/plugin-update-checker/css/puc-debug-bar.css b/admin/includes/plugin-update-checker/css/puc-debug-bar.css new file mode 100755 index 0000000..2cb3f8e --- /dev/null +++ b/admin/includes/plugin-update-checker/css/puc-debug-bar.css @@ -0,0 +1,70 @@ +.puc-debug-bar-panel-v4 pre { + margin-top: 0; +} + +/* Style the debug data table to match "widefat" table style used by WordPress. */ +table.puc-debug-data { + width: 100%; + clear: both; + margin: 0; + + border-spacing: 0; + background-color: #f9f9f9; + + border-radius: 3px; + border: 1px solid #dfdfdf; + border-collapse: separate; +} + +table.puc-debug-data * { + word-wrap: break-word; +} + +table.puc-debug-data th { + width: 11em; + padding: 7px 7px 8px; + text-align: left; + + font-family: "Georgia", "Times New Roman", "Bitstream Charter", "Times", serif; + font-weight: 400; + font-size: 14px; + line-height: 1.3em; + text-shadow: rgba(255, 255, 255, 0.804) 0 1px 0; +} + +table.puc-debug-data td, table.puc-debug-data th { + border-width: 1px 0; + border-style: solid; + + border-top-color: #fff; + border-bottom-color: #dfdfdf; + + text-transform: none; +} + +table.puc-debug-data td { + color: #555; + font-size: 12px; + padding: 4px 7px 2px; + vertical-align: top; +} + +.puc-ajax-response { + border: 1px solid #dfdfdf; + border-radius: 3px; + padding: 0.5em; + margin: 5px 0; + background-color: white; +} + +.puc-ajax-nonce { + display: none; +} + +.puc-ajax-response dt { + margin: 0; +} + +.puc-ajax-response dd { + margin: 0 0 1em; +} diff --git a/admin/includes/plugin-update-checker/js/debug-bar.js b/admin/includes/plugin-update-checker/js/debug-bar.js new file mode 100755 index 0000000..b8435db --- /dev/null +++ b/admin/includes/plugin-update-checker/js/debug-bar.js @@ -0,0 +1,52 @@ +jQuery(function($) { + + function runAjaxAction(button, action) { + button = $(button); + var panel = button.closest('.puc-debug-bar-panel-v4'); + var responseBox = button.closest('td').find('.puc-ajax-response'); + + responseBox.text('Processing...').show(); + $.post( + ajaxurl, + { + action : action, + uid : panel.data('uid'), + _wpnonce: panel.data('nonce') + }, + function(data) { + responseBox.html(data); + }, + 'html' + ); + } + + $('.puc-debug-bar-panel-v4 input[name="puc-check-now-button"]').click(function() { + runAjaxAction(this, 'puc_v4_debug_check_now'); + return false; + }); + + $('.puc-debug-bar-panel-v4 input[name="puc-request-info-button"]').click(function() { + runAjaxAction(this, 'puc_v4_debug_request_info'); + return false; + }); + + + // Debug Bar uses the panel class name as part of its link and container IDs. This means we can + // end up with multiple identical IDs if more than one plugin uses the update checker library. + // Fix it by replacing the class name with the plugin slug. + var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v4'); + panels.each(function() { + var panel = $(this); + var uid = panel.data('uid'); + var target = panel.closest('.debug-menu-target'); + + //Change the panel wrapper ID. + target.attr('id', 'debug-menu-target-puc-' + uid); + + //Change the menu link ID as well and point it at the new target ID. + $('#debug-bar-menu').find('.puc-debug-menu-link-' + uid) + .closest('.debug-menu-link') + .attr('id', 'debug-menu-link-puc-' + uid) + .attr('href', '#' + target.attr('id')); + }); +}); \ No newline at end of file diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-cs_CZ.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-cs_CZ.mo new file mode 100755 index 0000000000000000000000000000000000000000..ac6d20ea77cb6c6ad2aa9204312c53c86078e08c GIT binary patch literal 1077 zcmZWoO>fgc5H(P7$gP|Z>S3s;)T*rGq^c+m;iI8N6={juv{b!B8+#f%adxfUb=pSo z8#o~jobm&Z`UiRnH;&x-8(f*KlYWSm#&5^_=Iz_H=g)(guMUm-6mt}Ho6z`_!zIqr z{4)hme4&`9IH#ym{H9o{DPi$ zOoWgoStk}?Vw2#^8xVK`15`Se0^~7R#)6)bXtx_1{8vquZj-YVj0Ee~bs9=`F)(Z^ zWCyvvKapkmk=VpxVHZ=W4BOV7IArTtN3*8%q0soyWHp7{kTv#}G<_(0rDx1rWn~Xa zp1-=X?5%hn5!o&dVta&JJWGYrs=xAl*`raYb8T2taiJ4#r1IfFcFoW4K?Hle8z%5# zKsg4{Yi(0Eko}ibBRU!HAZsG;`%oLwIxOZuzO!}`2TNBh9|Fy4M}1DW(aJMa6z~rO{OP zo11Lynr9DmjEZfDK!&mC_^{TFP2rH$Wgyv}%v6AO&J)rLbc_5QvUey@<+osIz#uXv z)qb&#;UIv|5!G zR$8Zi>1jD2yrF_z1yO_4nMeAxaB00^k4vA49LZK{lU6F7qaIz5l8GE}1H5N4ay#S! zQp-%6LZBG`fKY0arDA;HIy*QN<57QnG3|zl#@P)4s<`Zt9XS|}Y)cHMy^`6Vyo*\n" +"Language-Team: Czech (Czech Republic)\n" +"Language: cs-CZ\n" +"Plural-Forms: nplurals=2; plural=(n != 1)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Loco-Source-Locale: cs_CZ\n" +"X-Generator: Loco - https://localise.biz/\n" +"X-Poedit-Basepath: ..\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"X-Poedit-SearchPath-0: .\n" +"X-Loco-Parser: loco_parse_po" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Zkontrolovat aktualizace" + +#: Puc/v4p1/Plugin/UpdateChecker.php:405 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "Plugin %s je aktuální." + +#: Puc/v4p1/Plugin/UpdateChecker.php:407 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Nová verze pluginu %s je dostupná." + +#: Puc/v4p1/Plugin/UpdateChecker.php:409 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Neznámý status kontroly aktualizací \"%s\"" + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "Changelog není dostupný." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.mo new file mode 100755 index 0000000000000000000000000000000000000000..9c59670712307a7dec1419ce48ba2613300f91aa GIT binary patch literal 1010 zcmZWo&u`N(7!5EuloK2gLLWoZK*J&FHf>7P19Tgjwux$VXt&C1zNV&`UD?ilNF4Yl zICDerA0Tnu9f>>QUxAmVTRUOp<@vKee}1uF{@kDY6rkM!9s;|-UEl*ywy(fF;2S`| z4`3en4K#tjfGGPng5Vc01Rj*}tsqzgAA%o&KY~N>XYdp7PcTx)?Izv`gE`>#c%;%Z z=~mPlaBoO`W2qRW(z6RX1GY@ckv7yDNS$$RGLk1!pfh*m{CqBu%cmzSdDC_fzu32xChlg(SsiwzG zik~&61>Ty%_PAB)N~jWcRep!hPmN98u5v!1Znx3pM)xd?r#a!z{8deTEILSHoGs%F|hy=lDlbzO2ta4E_O#F(`Ea literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.po new file mode 100755 index 0000000..8f2bc0d --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-da_DK.po @@ -0,0 +1,42 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-05-20 10:53+0300\n" +"PO-Revision-Date: 2017-10-17 11:07+0200\n" +"Last-Translator: Mikk3lRo\n" +"Language-Team: Mikk3lRo\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.0.4\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Language: da_DK\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Undersøg for opdateringer" + +#: Puc/v4p1/Plugin/UpdateChecker.php:405 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "Plugin'et %s er allerede opdateret." + +#: Puc/v4p1/Plugin/UpdateChecker.php:407 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "En ny version af plugin'et %s er tilgængelig." + +#: Puc/v4p1/Plugin/UpdateChecker.php:409 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Ukendt opdateringsstatus: \"%s\"" + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "Der er ingen ændringslog tilgængelig." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-de_DE.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-de_DE.mo new file mode 100755 index 0000000000000000000000000000000000000000..0734cae2dc9b76d41f5f6f99b1380ec2f685e1be GIT binary patch literal 980 zcmZuv&2AGh7+j!$6i)Plgi!Sn35g$h$wp9>4M9MfqKXtEnj&tIll`(;vauuEn^K9_ z;K+>wJOH=e`U)I4apXA|chjbourxcLcR$aL?fJ91@+H8y0^9;Rz%}4A;Kz61KJWv$ z4*UWL_zTrP?cpW?f-vECFuYrGp(Rw^k1}lK~;K#+1 zPM?>3^@0@d)0~aXv?4tsH_j~0@*>R?p^|f%<#Ld77_`PboX|)cDrSjvY=hpI4f`&o zX*iZDVih)w9nRIf$rqP8yTPf*77=s_*2)zB#3@jUaJ{ZC&MKYCpD zb)1n1$`gw*|dEss6VZzTU9UMR*Qx-jz)0iqd+dJ*0 z@hGfST3R_)5I&f}q2o{P;VhS#YWUMLmR)nNw\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.1\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e\n" +"Language: de_DE\n" +"X-Poedit-SearchPath-0: .\n" + +#: github-checker.php:137 +msgid "There is no changelog available." +msgstr "Es ist keine Liste von Programmänderungen verfügbar." + +#: plugin-update-checker.php:852 +msgid "Check for updates" +msgstr "Nach Update suchen" + +#: plugin-update-checker.php:896 +msgid "This plugin is up to date." +msgstr "Das Plugin ist aktuell." + +#: plugin-update-checker.php:898 +msgid "A new version of this plugin is available." +msgstr "Es ist eine neue Version für das Plugin verfügbar." + +#: plugin-update-checker.php:900 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Unbekannter Update Status \"%s\"" diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.mo new file mode 100755 index 0000000000000000000000000000000000000000..a68f1004811da6f8438dcb46da94dd438ba24843 GIT binary patch literal 1128 zcmZWoO;1xn6n!dcQdhb(E^bJSA7q~I6+fECM^FSqgxEkK?#R$i+b55iX5JLUxX^{j zf~|jmh1EtOfHBeE!D5~yE?l_vFLmQ_tX!08MILH_4soF=HQY2)>b;uw zdPS|CiLzl66*kv37#%ueT?g!tl`B3eu~99!!4m8t^drg#;awKwS$L1a+fhF33&J2k zBbye>v0L_dUl_1_!S(eAeL;VJkelSGVI|FFnsB3Z1YgZctY~`f$>e<+tcxU3BYIgS z+%K!8Vf4#dlh*_*3BD8&oYRb1O#}_bvZ_WJTBWY^V|~;cQI*e6Oy{O1rpAsI4E-QC zs-zJT238x`#E9qSRwLoD9B|*VPK6noEse9nQJ*tf6`GC7vZ}fZ4MwZu zD0_3T@#CW#X1B@5BH7ztuORM>xV2jLi+l1=f3@F`b_U@Vf-R`G-B$m$|9^wdU*s>7 C2(8ip literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.po new file mode 100755 index 0000000..20b6938 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fa_IR.po @@ -0,0 +1,38 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2016-02-17 14:21+0100\n" +"PO-Revision-Date: 2016-10-28 14:30+0330\n" +"Last-Translator: studio RVOLA \n" +"Language-Team: Pro Style \n" +"Language: fa_IR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.8\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e\n" +"X-Poedit-SearchPath-0: .\n" + +#: github-checker.php:120 +msgid "There is no changelog available." +msgstr "شرحی برای تغییرات یافت نشد" + +#: plugin-update-checker.php:637 +msgid "Check for updates" +msgstr "بررسی برای بروزرسانی " + +#: plugin-update-checker.php:681 +msgid "This plugin is up to date." +msgstr "شما از آخرین نسخه استفاده میکنید . به‌روز باشید" + +#: plugin-update-checker.php:683 +msgid "A new version of this plugin is available." +msgstr "نسخه جدیدی برای افزونه ارائه شده است ." + +#: plugin-update-checker.php:685 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "وضعیت ناشناخته برای بروزرسانی \"%s\"" diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_CA.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_CA.mo new file mode 100755 index 0000000000000000000000000000000000000000..24639b694e7ba21e2b5f9997b9f12d2d831ac69a GIT binary patch literal 1208 zcmZuwO>Y}F5M>&-1=K^)9{T|d3>Zk!aJ##85MxybNff&LJ!fDKMyPa&$<1lrsRn<7q_YSWChrKqFfjXPxdlxFOM zc9z_TT8pi4VT5Rx0=(tjbB(E>CsM_c{Zv~B99<|T1-&cxc`jQad0PV#doyHHQ*_j3 zoru1754nu;ppp+3DvPB!xhRZW=Gp0gKaf4oDk2kk56%VUX?9a)nasB-yIG|9mua4+ zFqA*=Ot%@Y?RI3E%PglXExyiWdINTcsBxplEC;Nn1$B-Nj`r3fvLx;FoQ-Uw9GumN z7Wr}fsy0g7ZhJvKaNIo}?8}|ComV!D*vmazx=Pz|K|3cpc7BxKvSqKL^9A)CS2|Lj zq{%k^ESB=F3S6r=DJV%gebabl{uqVi|VxZd)2mcduExMcEhKwf}wB_>y}I zSp_Y0txo@r&rY4M!l4eapy9APLq+?eP?k zF)7{j)~a{~jr_28=aLXszMS-ticFDAM?5%x>GeqCr5X-2)dAo0U+EzPivvUU?U zks{TUjh*jWW$@nSmKTOp=}|W|+S-OVL<)_cG3N7DIL2GGu9>kh zylMa(YY-0?$#&imXoc4E^6>}L+J(@DYE@L{FPASLou;Y5sci}?VQ+d 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: Eric Gagnon \n" +"Language: fr_CA\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p3/Plugin/UpdateChecker.php:395 +msgid "Check for updates" +msgstr "Vérifier les mises à jour" + +#: Puc/v4p3/Plugin/UpdateChecker.php:548 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "L’extension %s est à jour." + +#: Puc/v4p3/Plugin/UpdateChecker.php:550 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Une nouvelle version de l’extension %s est disponible." + +#: Puc/v4p3/Plugin/UpdateChecker.php:552 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "Impossible de déterminer si une mise à jour est disponible pour \"%s\"" + +#: Puc/v4p3/Plugin/UpdateChecker.php:558 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Un problème inconnu est survenu \"%s\"" + +#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 +msgid "There is no changelog available." +msgstr "Il n’y a aucun journal de mise à jour disponible." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.mo new file mode 100755 index 0000000000000000000000000000000000000000..a492d96f6eb4b2d988877b0f15c6adc60613195e GIT binary patch literal 1066 zcmZuw&2AGh5H?Ua1TJs|q*0|xAn1R4EshMJY0DWU2&l2I$v2KbMK|0U|;#BAXDl-5v5>kmhg#p{q2ilDF zG=Mae0WCN$eC}X&&doBPB4jEbNDW?kg)=LlaSS80P8toS4~1gRor&nQO9%WHO_u%@ z=NWhdh2Ma6tl7ud^H#!l%ly$aEiYe*PaRe|TV39?C_H)KuP8WzT3B7=Vey0NLiGIE zldu+sB;?yTl7-i+bql4gP1VW80C^Y1Fro_Ni8QdiyVYKS7peDIG(SHcj{`e0N(8YP zE?3S%BIw)R+ID55wXu5PyBdU*rqLd?=iQ@>40=5D^O+J-*NfY*4t-;%yT+F;bXI8B zN6S}rY!ayl5iIRVUwOyZQKJ>!*a$iX6X~HAgh7q|DVO}EaF_|7Mi2y*j>@f2e9hRQ zi$K%$(b6?)^`e?IZ9LMj4AsZ=i}<%Dw=p(LTM?AL&a=P4qp`7xYfI-N==JJ7toIJ1 z>eE_GOqFo-l7)Fydfb#TmC3>S>g(3#r9)8IIPH*49+J@t+dVz8vM;IS6gn76N6*tQ zuuo=KOM(9N@$(S~5P6*I$*vX(5}YW{gpf#=87-#`4Vg82>hyR>jZan7ItO$fTy955 o^GQ$dXrxafAE8os-pQ0!(Rp-9s3)yWJzYdzPT#&tFf|;ozeSTj4gdfE literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.po new file mode 100755 index 0000000..9f18e2c --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-fr_FR.po @@ -0,0 +1,42 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-07-07 14:53+0200\n" +"PO-Revision-Date: 2017-07-07 14:54+0200\n" +"Language-Team: studio RVOLA \n" +"Language: fr_FR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.0.2\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: Nicolas GEHIN\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Vérifier les mises à jour" + +#: Puc/v4p1/Plugin/UpdateChecker.php:405 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "L’extension %s est à jour." + +#: Puc/v4p1/Plugin/UpdateChecker.php:407 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Une nouvelle version de l’extension %s est disponible." + +#: Puc/v4p1/Plugin/UpdateChecker.php:409 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Un problème inconnu est survenu \"%s\"" + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:85 +msgid "There is no changelog available." +msgstr "Il n’y a aucun journal de mise à jour disponible." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-hu_HU.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-hu_HU.mo new file mode 100755 index 0000000000000000000000000000000000000000..4789ef1da358b7fdef2879615c49eac1fb2dad98 GIT binary patch literal 982 zcmZuvO>fgc5M7{v6i#qKAPz$$#7DIzPDNE5f+!)S6)8m2MckroGO^v*yVmYHB@w@X zTMt~gl@mR1LgEit{Rfqs~~X?#;8rCB&Z?SFfx$FSrAE}nHY;G7CSLItQBH^1Vg1EO9#TD zVSb1ji!7<29|{>@tb&sz{=Z^b3RXc;>#%J(l4?)Rw5XiKQG>CCjDN zB0%n=NIaOw9)wwMeY>)`vDrR8k?YhdEhQ~V+HsPSb&K!p{WKPlY!uh34cg|mzs6UN z^9pA})VwYGY7oi5gO#1gR^IaGC{dS|y9x)91=m?|mT9F7`BPyq6*lz1aVp(7(<0_; zN+-qxNzYE9Y1SLXJ=3&#N5ah}xOW@J0$VE6eQcG!JSdILot0K zq7;Shhh5s8*J%F=%RlWFy*G{WZ;&7A5be=EUVSD1gFvNatULm~a8 zlo;jFzMfKm>?J1uRnMEzVeKiY&H7o2REtp|>#z-zQ1e>Sq4nWu+GNF8dgRPZMcI&l E0BAre\n" +"Language-Team: \n" +"Language: hu_HU\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.6\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e\n" +"X-Poedit-SearchPath-0: .\n" + +#: github-checker.php:137 +msgid "There is no changelog available." +msgstr "Nem érhető el a changelog." + +#: plugin-update-checker.php:852 +msgid "Check for updates" +msgstr "Frissítés ellenőrzése" + +#: plugin-update-checker.php:896 +msgid "This plugin is up to date." +msgstr "Ez a plugin naprakész." + +#: plugin-update-checker.php:898 +msgid "A new version of this plugin is available." +msgstr "Új verzió érhető el a kiegészítőhöz" + +#: plugin-update-checker.php:900 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Ismeretlen a frissítés ellenőrző státusza \"%s\"" + +#~ msgid "Every %d hours" +#~ msgstr "Minden %d órában" diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-it_IT.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-it_IT.mo new file mode 100755 index 0000000000000000000000000000000000000000..6a2c57d98f667286c49857745f52a20c6a54107c GIT binary patch literal 989 zcmY*Y-EPw`7!5E$Dpzm;5<=*s65`h(skSjvih!;|)jFtHhq$ZU#7)goJF=aQAzlOV z3ge0w;BK$L1y@}19GooM+F3d|pOf!9KDNL7y|(nt!?*<80(!s|;44s$1K=U>1GozO z1_<~E+ypM4^SnB^4*mmlfXA5MzTkP+!JFV^@CbYZ{2k1|Kfy>n8VJ25p!86V^A(*w zFP70OQeuy0!dR&l=`p#9w3KH>DitB(GcGee%7pK=CnDaZu{KoX33tMJgNZPr%u<@- z30JAebh=nFI4f4<v8MYz;ITY%B#zQ}-wY73WL3lrhLnl7FCwa!DYL=&GtZ=QJ!3JBK=amM=!my5tbs|+7(b`D5 z+DG@~L{=WY^_@7MZSVR*(iw3*t76mAz&+iEn+<3!lH zujo#T!UxT{z_u<-EZUW?h$>^J@|$9RPn*Q{q;(Muhs~il-G4-h7_N5~qy#tdqz^YN zfS(%fo|7u{jGr`~KuLDeb%zI(NSkXVM=}#0u3nC1%!#L|)JE|sj!=4U(XR15w8NkrO?qy=_TQ!e4N-5_+^ylpBq\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.5.5\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e\n" +"Language: de_DE\n" +"X-Poedit-SearchPath-0: .\n" + +#: github-checker.php:137 +msgid "There is no changelog available." +msgstr "Non c'è alcuna sezione di aggiornamento disponibile" + +#: plugin-update-checker.php:852 +msgid "Check for updates" +msgstr "Verifica aggiornamenti" + +#: plugin-update-checker.php:896 +msgid "This plugin is up to date." +msgstr "Il plugin è aggiornato" + +#: plugin-update-checker.php:898 +msgid "A new version of this plugin is available." +msgstr "Una nuova versione del plugin è disponibile" + +#: plugin-update-checker.php:900 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Si è verificato un problema sconosciuto \"%s\"" diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.mo new file mode 100755 index 0000000000000000000000000000000000000000..376102a19c8dc7832685e62607d49c44f202859b GIT binary patch literal 1105 zcmZ{iO-~a+7{^CN5A~!+^)Qlf(y7}T0k_ns6%1Npqs8c{8MZ^abUWM3PI-wQ*xmRN z)Wm3n2qq>3gJ1*<#P~w=Gk8}o6RI~qfqkn2!q~(nn9mINzhLa3C7zH`UEP0_6PGF2pxoY6(WUr4PpnxFA!TH z?rTB_QtNFy^stOz3GJ+}gglL57*a)MlyJW-aJ7=Bk~t__WP)MS!Q941k@5nw>;k5P z)U;@y#iFQ}m$*H|8wHR94oqN2QdxCybBoiAWRc;DRV|ntOH*2`=@jN{2oEyhm^R0D zKMpclob@EwZOaCKRRhxR$<+#$HV$~BC?o6vW=PVVCznHiy!*)Gz)nHNy>GeJ7JVdqU=&~ba8DI-_NS;mTsN-lflCi3STBOSsWk<&xE)k|qGL{I=6oyGHu~~V^t_p*tLLeQ7 zL>s>6*~pMB@=n@xq>gjBM2;nL!|>>_!*OGa3!}m)W`KZbzz{*on^wNB{0ZgXQvRy) zZ!7P?x9NA^=kKA~)Jko9Y3Z{|8Dqi q>u__*TT{!24J6q8fGoQ$MTRdf6`lshVj3 literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.po new file mode 100755 index 0000000..673c311 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-ja.po @@ -0,0 +1,42 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-06-02 18:31+0900\n" +"PO-Revision-Date: 2017-06-02 18:32+0900\n" +"Last-Translator: tak \n" +"Language-Team: \n" +"Language: ja_JP\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.0.2\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x;_x:1,2c\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:362 +msgid "Check for updates" +msgstr "アップデートを確認" + +#: Puc/v4p1/Plugin/UpdateChecker.php:409 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "%s プラグインは、最新バージョンです。" + +#: Puc/v4p1/Plugin/UpdateChecker.php:411 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "%s プラグインの最新バージョンがあります。" + +#: Puc/v4p1/Plugin/UpdateChecker.php:413 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "バージョンアップの確認で想定外の状態になりました。ステータス:\"%s\"" + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "更新履歴はありません。" diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.mo new file mode 100755 index 0000000000000000000000000000000000000000..1cea26dda30ca887087e965d5b494716e48d8416 GIT binary patch literal 1211 zcmah|&59F25N>rQ;T9t9u4ClK@z{3ericUi%PFW*e3e!i-y`f+yUy}&sMoC5~HDc}uIo=?CT;4?tL zH((9;33PzdM}+8sx4;to4*U!F0+jJS9ur~}{2hE1{2P1`yuKnt8~g}d`n?6iWpR$; z7iI!i;`ri5h!aaLbuLbK%E^qz)=`nCDzF!WDLW?Z$yiFJ%1k)36H?nsXKIvjB%Yd? zu{&nz02@SLM?R=fcv@TcYa&dU@~oI>LqUg(S8kKx9olB+wKZhNR9dY2T_a@Mm*9|h z*A`g{J%LgV?B?1);CNRtDd_#{zNls0M~5|_u!AX!oPwpY>PYmReZfhP_fz?-QW-DB z$*M7OS!b>Pa3H&mRX`>3E}Ua()*CHZzapF0sL_fW*DltZ^*RjYW8T(f#s9Rs(yZ(@ z(c?l*SPodtW2$Z4-|Fp&Xhii|*P6g4$ib@|*#f@|m-9?%(=I=d^Bg))2OF}rXXljh zV|KD<5}Rr>iK#Wxq4r$fW5Z4b>tgC#PIaJ0)QYZ04g6PK$UDk&uEI2?D5~|d!l_Jd zSU2}E8GKW``cAW5HV2QL^M+PC)VR>z3-H7iF5zyaET&4@-|!Fk)sA(k-_$MZqVmCOx1&*+}D-m~#^V_d%9vU$*R{TijsRlrF2D6#XK@UB`3 zsoC&OZ=WVsE}8aGmaL<&nkZZ9Y{nQ|o0HL8>~J-oSb?4^=YPU%_HDq3eKOUvky0)a z53v?AHYx9p{Ybx{WEt~N#JJjuDr_0`Kt9@5rX0)z2_9fgU=?tis|+sK8EE~VBXmdN gF4LUZ2XdTXY!*|$SiQwsPx$KxgJsRi;?qd{0TG{S#Q*>R literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.po new file mode 100755 index 0000000..e1734bb --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_BE.po @@ -0,0 +1,48 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2018-03-25 18:15+0200\n" +"PO-Revision-Date: 2018-03-25 18:32+0200\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.7.1\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: Frank Goossens \n" +"Language: nl_BE\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p3/Plugin/UpdateChecker.php:395 +msgid "Check for updates" +msgstr "Controleer op nieuwe versies" + +#: Puc/v4p3/Plugin/UpdateChecker.php:548 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "De meest recente %s versie is geïnstalleerd." + +#: Puc/v4p3/Plugin/UpdateChecker.php:550 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Er is een nieuwe versie van %s beschikbaar." + +#: Puc/v4p3/Plugin/UpdateChecker.php:552 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "Kon niet bepalen of er nieuwe versie van %s beschikbaar is." + +#: Puc/v4p3/Plugin/UpdateChecker.php:558 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Ongekende status bij controle op nieuwe versie: \"%s\"" + +#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 +msgid "There is no changelog available." +msgstr "Er is geen changelog beschikbaar." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.mo new file mode 100755 index 0000000000000000000000000000000000000000..16dde622ba6040399cc911e0d5ef1c970a541b88 GIT binary patch literal 1211 zcmah|&59F25N>rYShMgp(iFTo-2 zt}U_@dIF^!*v+(oz|pQ^QqcR?eO}9oj}B`FtAI-6JvhhItT$S+epNQFQ==6(u3xG*>vb5)r@X1livMYMwOQG% zqsN6Bv+T2)#Z=pPu(7%)q7l_=U26iHAp1KxvIX7_SMp40(=I=d^Bg+Q`)jhbXXljh zBX)AtBsSG%98+tkL+z!!&xV}}*2UDboa#W0s1@Ca8u+iekav~mT!l$YQB>6P~&2IFTgWfxP-fvvY0Aqf5SiIoh|E9zpj0VX)tIH zxINg88<(32xVEl5>MZqVmCQ9fPwBq3-m~#^b5y?Hwt3Jq{TijsRKQ61D6z9!@UB`3 zsoCJs`aVspTr%mQELlfkHBq+I*^Du`HYcOG*y3tFu>z~Eoc}Si*|z~h_Q^y~hf29f zJjPl~*`&NX_Cx)Ol10oz5#wqrs<36$1NmrEnQ|}>BzTB5fmOh5t}?h_XQ1_ej?f*6 gdrUKCAINcnv6)Z(eD&sQJ?5_;43;%3i%%o*2Pb`M*Z=?k literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.po new file mode 100755 index 0000000..7f57a89 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-nl_NL.po @@ -0,0 +1,48 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2018-03-25 18:15+0200\n" +"PO-Revision-Date: 2018-03-25 18:32+0200\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.7.1\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: Frank Goossens \n" +"Language: nl_NL\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p3/Plugin/UpdateChecker.php:395 +msgid "Check for updates" +msgstr "Controleer op nieuwe versies" + +#: Puc/v4p3/Plugin/UpdateChecker.php:548 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "De meest recente %s versie is geïnstalleerd." + +#: Puc/v4p3/Plugin/UpdateChecker.php:550 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Er is een nieuwe versie van %s beschikbaar." + +#: Puc/v4p3/Plugin/UpdateChecker.php:552 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "Kon niet bepalen of er nieuwe versie van %s beschikbaar is." + +#: Puc/v4p3/Plugin/UpdateChecker.php:558 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Ongekende status bij controle op nieuwe versie: \"%s\"" + +#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 +msgid "There is no changelog available." +msgstr "Er is geen changelog beschikbaar." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.mo new file mode 100755 index 0000000000000000000000000000000000000000..d1c0f283287da07c7060255756947399fde75ca6 GIT binary patch literal 1014 zcmZuv!EVz)6f{scgcF=V;_y_d5=dPW2P%rAAllGEMM|SKMcksreu>>WyVmYHZ4oE_ zfe%0&fCEQPT#)h`h+lzm97qtXGJgB)+1bhN{J6UG*2B02+yFYjW#BbXj*q|<;1fW= zS6~_V4zz%ufGFqZJntKD3|vFMdZFTNpgW5oypn^Ib=kY}AEddv&Zz?~t zX;s<@N5?eKhKf9vj;+^A*f6D*l%^<=YRH)$k{ru4lP@#&y+d`Z^og1+00#ed~o)yDXkxO01OB=CIb?>xs5u>EJ;;!s3t`_28bUuZiG31#98mK-BNl>mZ7K z9;c<(|MMCZuOqD!JtLLPq|+v(S_kJ<$RUd!%h5s)ORm4UU)$Z;-J07B{Ccgem16~& zvmAaLpSs(5CR5cc58qgJt;627SfBIC?FMYbmWp(os$od$FH={0As(}0Q~Bs>j#Ed0 zzwWQ&OVx@^X*riJ3CZ_s-K;P&6WiL1Y)A^Xh1Rwj&GPUtZQWG#fP!1i`T7H0n26hz zt&l2Tf7GAy*@-r>?WER))bBU@-0Yv?7Y3`1XhDUgiIOgSh&r6qJltA3NF!-z!xb`1 zU&+ab$rmK?+2p;ZWb%%R(LxgA)aF`EK94!`y@Pq^C}taJg*2wI_Pr<5brLBa%W3dR uv0NHSC{;9(zXh@CV~k{HTE@P&w?I3B7+Z&@l4Ogy;7B66h9le{qWB9G2Q7U7 literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.po new file mode 100755 index 0000000..70a0f62 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-pt_BR.po @@ -0,0 +1,48 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-05-19 15:41-0300\n" +"PO-Revision-Date: 2017-05-19 15:42-0300\n" +"Last-Translator: \n" +"Language-Team: \n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.8\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x;_x:1,2c\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Verificar Atualizações" + +#: Puc/v4p1/Plugin/UpdateChecker.php:401 Puc/v4p1/Plugin/UpdateChecker.php:406 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "O plugin %s já está na sua versão mais recente." + +#: Puc/v4p1/Plugin/UpdateChecker.php:408 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Há uma nova versão para o plugin %s disponível para download." + +#: Puc/v4p1/Plugin/UpdateChecker.php:410 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Status \"%s\" desconhecido." + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "Não há um changelog disponível." + +#~ msgid "The %s plugin is up to date." +#~ msgstr "O plugin %s já está na sua versão mais recente." + +#~ msgid "A new version of the %s plugin is available." +#~ msgstr "Há uma nova versão para o plugin %s disponível para download." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.mo b/admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.mo new file mode 100755 index 0000000000000000000000000000000000000000..4d06fc14f5bb99ac14bc019543e9edacfb457e36 GIT binary patch literal 1006 zcmZWn!EO^V5H(OZgcF=NfHYK!L{+@(rWC4;a)7i&6|EZ46mg5(WU^VZwIkb`wi1W_ z1UI-<2!5a!PAEUX2Otjp5qR58+aN5xeIEOH{5(6q@6LS`7`K4?z$S1T_y82+D{u$+ z1`zNam1R4EsX5^8kov|_KI$pYPP7MXnNmmEPaDa zh?X_)x$EUdPrfbl$J4a3e3G0xthBbFNsTPF6 zQ|y$Xe5o9dlpn+t1eI2nTb0RmWA|N58vg>JYt-sRX)tX(()6%F(L((y!H&somz$-p zm`Y=p>0k5Ffw4WenK~a+r&I56y>l2xk852pO5yOz!hKenyev*kZrs^fo4JRT?G9S7 zDnpp9h@Hvlkht&BMEU5v3oTx*tXO4F{Zwm5h*{I*ME8m!Zv5guX~VIY|;YsJcM3XG8e7a;khF F{sQ>&EFS;> literal 0 HcmV?d00001 diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.po b/admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.po new file mode 100755 index 0000000..b894814 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker-sv_SE.po @@ -0,0 +1,42 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-05-20 10:53+0300\n" +"PO-Revision-Date: 2017-10-16 15:02+0200\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.0.4\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: \n" +"Language: sv_SE\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Sök efter uppdateringar" + +#: Puc/v4p1/Plugin/UpdateChecker.php:405 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "Tillägget %s är uppdaterat." + +#: Puc/v4p1/Plugin/UpdateChecker.php:407 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Det finns en ny version av tillägget %s." + +#: Puc/v4p1/Plugin/UpdateChecker.php:409 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Okänd status för kontroll av uppdatering “%s”" + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "Det finns ingen ändringslogg tillgänglig." diff --git a/admin/includes/plugin-update-checker/languages/plugin-update-checker.pot b/admin/includes/plugin-update-checker/languages/plugin-update-checker.pot new file mode 100755 index 0000000..67f4f00 --- /dev/null +++ b/admin/includes/plugin-update-checker/languages/plugin-update-checker.pot @@ -0,0 +1,49 @@ +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-11-24 17:02+0200\n" +"PO-Revision-Date: 2016-01-10 20:59+0100\n" +"Last-Translator: Tamás András Horváth \n" +"Language-Team: \n" +"Language: en_US\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.0.4\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p3/Plugin/UpdateChecker.php:395 +msgid "Check for updates" +msgstr "" + +#: Puc/v4p3/Plugin/UpdateChecker.php:548 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "" + +#: Puc/v4p3/Plugin/UpdateChecker.php:550 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "" + +#: Puc/v4p3/Plugin/UpdateChecker.php:552 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "" + +#: Puc/v4p3/Plugin/UpdateChecker.php:558 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "" + +#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 +msgid "There is no changelog available." +msgstr "" diff --git a/admin/includes/plugin-update-checker/license.txt b/admin/includes/plugin-update-checker/license.txt new file mode 100755 index 0000000..be948f6 --- /dev/null +++ b/admin/includes/plugin-update-checker/license.txt @@ -0,0 +1,7 @@ +Copyright (c) 2017 Jānis Elsts + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/admin/includes/plugin-update-checker/plugin-update-checker.php b/admin/includes/plugin-update-checker/plugin-update-checker.php new file mode 100755 index 0000000..81bbc1e --- /dev/null +++ b/admin/includes/plugin-update-checker/plugin-update-checker.php @@ -0,0 +1,34 @@ + 'Puc_v4p6_Plugin_UpdateChecker', + 'Theme_UpdateChecker' => 'Puc_v4p6_Theme_UpdateChecker', + + 'Vcs_PluginUpdateChecker' => 'Puc_v4p6_Vcs_PluginUpdateChecker', + 'Vcs_ThemeUpdateChecker' => 'Puc_v4p6_Vcs_ThemeUpdateChecker', + + 'GitHubApi' => 'Puc_v4p6_Vcs_GitHubApi', + 'BitBucketApi' => 'Puc_v4p6_Vcs_BitBucketApi', + 'GitLabApi' => 'Puc_v4p6_Vcs_GitLabApi', + ) + as $pucGeneralClass => $pucVersionedClass +) { + Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.6'); + //Also add it to the minor-version factory in case the major-version factory + //was already defined by another, older version of the update checker. + Puc_v4p6_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.6'); +} diff --git a/admin/includes/plugin-update-checker/vendor/Parsedown.php b/admin/includes/plugin-update-checker/vendor/Parsedown.php new file mode 100755 index 0000000..5d96071 --- /dev/null +++ b/admin/includes/plugin-update-checker/vendor/Parsedown.php @@ -0,0 +1,1538 @@ +DefinitionData = array(); + + # standardize line breaks + $text = str_replace(array("\r\n", "\r"), "\n", $text); + + # remove surrounding line breaks + $text = trim($text, "\n"); + + # split text into lines + $lines = explode("\n", $text); + + # iterate through lines to identify blocks + $markup = $this->lines($lines); + + # trim line breaks + $markup = trim($markup, "\n"); + + return $markup; + } + + # + # Setters + # + + function setBreaksEnabled($breaksEnabled) + { + $this->breaksEnabled = $breaksEnabled; + + return $this; + } + + protected $breaksEnabled; + + function setMarkupEscaped($markupEscaped) + { + $this->markupEscaped = $markupEscaped; + + return $this; + } + + protected $markupEscaped; + + function setUrlsLinked($urlsLinked) + { + $this->urlsLinked = $urlsLinked; + + return $this; + } + + protected $urlsLinked = true; + + # + # Lines + # + + protected $BlockTypes = array( + '#' => array('Header'), + '*' => array('Rule', 'List'), + '+' => array('List'), + '-' => array('SetextHeader', 'Table', 'Rule', 'List'), + '0' => array('List'), + '1' => array('List'), + '2' => array('List'), + '3' => array('List'), + '4' => array('List'), + '5' => array('List'), + '6' => array('List'), + '7' => array('List'), + '8' => array('List'), + '9' => array('List'), + ':' => array('Table'), + '<' => array('Comment', 'Markup'), + '=' => array('SetextHeader'), + '>' => array('Quote'), + '[' => array('Reference'), + '_' => array('Rule'), + '`' => array('FencedCode'), + '|' => array('Table'), + '~' => array('FencedCode'), + ); + + # ~ + + protected $unmarkedBlockTypes = array( + 'Code', + ); + + # + # Blocks + # + + protected function lines(array $lines) + { + $CurrentBlock = null; + + foreach ($lines as $line) + { + if (chop($line) === '') + { + if (isset($CurrentBlock)) + { + $CurrentBlock['interrupted'] = true; + } + + continue; + } + + if (strpos($line, "\t") !== false) + { + $parts = explode("\t", $line); + + $line = $parts[0]; + + unset($parts[0]); + + foreach ($parts as $part) + { + $shortage = 4 - mb_strlen($line, 'utf-8') % 4; + + $line .= str_repeat(' ', $shortage); + $line .= $part; + } + } + + $indent = 0; + + while (isset($line[$indent]) and $line[$indent] === ' ') + { + $indent ++; + } + + $text = $indent > 0 ? substr($line, $indent) : $line; + + # ~ + + $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); + + # ~ + + if (isset($CurrentBlock['continuable'])) + { + $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock); + + if (isset($Block)) + { + $CurrentBlock = $Block; + + continue; + } + else + { + if ($this->isBlockCompletable($CurrentBlock['type'])) + { + $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); + } + } + } + + # ~ + + $marker = $text[0]; + + # ~ + + $blockTypes = $this->unmarkedBlockTypes; + + if (isset($this->BlockTypes[$marker])) + { + foreach ($this->BlockTypes[$marker] as $blockType) + { + $blockTypes []= $blockType; + } + } + + # + # ~ + + foreach ($blockTypes as $blockType) + { + $Block = $this->{'block'.$blockType}($Line, $CurrentBlock); + + if (isset($Block)) + { + $Block['type'] = $blockType; + + if ( ! isset($Block['identified'])) + { + $Blocks []= $CurrentBlock; + + $Block['identified'] = true; + } + + if ($this->isBlockContinuable($blockType)) + { + $Block['continuable'] = true; + } + + $CurrentBlock = $Block; + + continue 2; + } + } + + # ~ + + if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted'])) + { + $CurrentBlock['element']['text'] .= "\n".$text; + } + else + { + $Blocks []= $CurrentBlock; + + $CurrentBlock = $this->paragraph($Line); + + $CurrentBlock['identified'] = true; + } + } + + # ~ + + if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) + { + $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); + } + + # ~ + + $Blocks []= $CurrentBlock; + + unset($Blocks[0]); + + # ~ + + $markup = ''; + + foreach ($Blocks as $Block) + { + if (isset($Block['hidden'])) + { + continue; + } + + $markup .= "\n"; + $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']); + } + + $markup .= "\n"; + + # ~ + + return $markup; + } + + protected function isBlockContinuable($Type) + { + return method_exists($this, 'block'.$Type.'Continue'); + } + + protected function isBlockCompletable($Type) + { + return method_exists($this, 'block'.$Type.'Complete'); + } + + # + # Code + + protected function blockCode($Line, $Block = null) + { + if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] >= 4) + { + $text = substr($Line['body'], 4); + + $Block = array( + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => array( + 'name' => 'code', + 'text' => $text, + ), + ), + ); + + return $Block; + } + } + + protected function blockCodeContinue($Line, $Block) + { + if ($Line['indent'] >= 4) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + $Block['element']['text']['text'] .= "\n"; + + $text = substr($Line['body'], 4); + + $Block['element']['text']['text'] .= $text; + + return $Block; + } + } + + protected function blockCodeComplete($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # Comment + + protected function blockComment($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!') + { + $Block = array( + 'markup' => $Line['body'], + ); + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + } + + protected function blockCommentContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + $Block['markup'] .= "\n" . $Line['body']; + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + + # + # Fenced Code + + protected function blockFencedCode($Line) + { + if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches)) + { + $Element = array( + 'name' => 'code', + 'text' => '', + ); + + if (isset($matches[1])) + { + $class = 'language-'.$matches[1]; + + $Element['attributes'] = array( + 'class' => $class, + ); + } + + $Block = array( + 'char' => $Line['text'][0], + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => $Element, + ), + ); + + return $Block; + } + } + + protected function blockFencedCodeContinue($Line, $Block) + { + if (isset($Block['complete'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) + { + $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1); + + $Block['complete'] = true; + + return $Block; + } + + $Block['element']['text']['text'] .= "\n".$Line['body'];; + + return $Block; + } + + protected function blockFencedCodeComplete($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # Header + + protected function blockHeader($Line) + { + if (isset($Line['text'][1])) + { + $level = 1; + + while (isset($Line['text'][$level]) and $Line['text'][$level] === '#') + { + $level ++; + } + + if ($level > 6) + { + return; + } + + $text = trim($Line['text'], '# '); + + $Block = array( + 'element' => array( + 'name' => 'h' . min(6, $level), + 'text' => $text, + 'handler' => 'line', + ), + ); + + return $Block; + } + } + + # + # List + + protected function blockList($Line) + { + list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]'); + + if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'indent' => $Line['indent'], + 'pattern' => $pattern, + 'element' => array( + 'name' => $name, + 'handler' => 'elements', + ), + ); + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $matches[2], + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + } + + protected function blockListContinue($Line, array $Block) + { + if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['li']['text'] []= ''; + + unset($Block['interrupted']); + } + + unset($Block['li']); + + $text = isset($matches[1]) ? $matches[1] : ''; + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $text, + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + + if ($Line['text'][0] === '[' and $this->blockReference($Line)) + { + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + return $Block; + } + + if ($Line['indent'] > 0) + { + $Block['li']['text'] []= ''; + + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + unset($Block['interrupted']); + + return $Block; + } + } + + # + # Quote + + protected function blockQuote($Line) + { + if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'element' => array( + 'name' => 'blockquote', + 'handler' => 'lines', + 'text' => (array) $matches[1], + ), + ); + + return $Block; + } + } + + protected function blockQuoteContinue($Line, array $Block) + { + if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text'] []= ''; + + unset($Block['interrupted']); + } + + $Block['element']['text'] []= $matches[1]; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $Block['element']['text'] []= $Line['text']; + + return $Block; + } + } + + # + # Rule + + protected function blockRule($Line) + { + if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text'])) + { + $Block = array( + 'element' => array( + 'name' => 'hr' + ), + ); + + return $Block; + } + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (chop($Line['text'], $Line['text'][0]) === '') + { + $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; + + return $Block; + } + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) + { + $element = strtolower($matches[1]); + + if (in_array($element, $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'depth' => 0, + 'markup' => $Line['text'], + ); + + $length = strlen($matches[0]); + + $remainder = substr($Line['text'], $length); + + if (trim($remainder) === '') + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + $Block['closed'] = true; + + $Block['void'] = true; + } + } + else + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + return; + } + + if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) + { + $Block['closed'] = true; + } + } + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open + { + $Block['depth'] ++; + } + + if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close + { + if ($Block['depth'] > 0) + { + $Block['depth'] --; + } + else + { + $Block['closed'] = true; + } + } + + if (isset($Block['interrupted'])) + { + $Block['markup'] .= "\n"; + + unset($Block['interrupted']); + } + + $Block['markup'] .= "\n".$Line['body']; + + return $Block; + } + + # + # Reference + + protected function blockReference($Line) + { + if (preg_match('/^\[(.+?)\]:[ ]*?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches)) + { + $id = strtolower($matches[1]); + + $Data = array( + 'url' => $matches[2], + 'title' => null, + ); + + if (isset($matches[3])) + { + $Data['title'] = $matches[3]; + } + + $this->DefinitionData['Reference'][$id] = $Data; + + $Block = array( + 'hidden' => true, + ); + + return $Block; + } + } + + # + # Table + + protected function blockTable($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '') + { + $alignments = array(); + + $divider = $Line['text']; + + $divider = trim($divider); + $divider = trim($divider, '|'); + + $dividerCells = explode('|', $divider); + + foreach ($dividerCells as $dividerCell) + { + $dividerCell = trim($dividerCell); + + if ($dividerCell === '') + { + continue; + } + + $alignment = null; + + if ($dividerCell[0] === ':') + { + $alignment = 'left'; + } + + if (substr($dividerCell, - 1) === ':') + { + $alignment = $alignment === 'left' ? 'center' : 'right'; + } + + $alignments []= $alignment; + } + + # ~ + + $HeaderElements = array(); + + $header = $Block['element']['text']; + + $header = trim($header); + $header = trim($header, '|'); + + $headerCells = explode('|', $header); + + foreach ($headerCells as $index => $headerCell) + { + $headerCell = trim($headerCell); + + $HeaderElement = array( + 'name' => 'th', + 'text' => $headerCell, + 'handler' => 'line', + ); + + if (isset($alignments[$index])) + { + $alignment = $alignments[$index]; + + $HeaderElement['attributes'] = array( + 'style' => 'text-align: '.$alignment.';', + ); + } + + $HeaderElements []= $HeaderElement; + } + + # ~ + + $Block = array( + 'alignments' => $alignments, + 'identified' => true, + 'element' => array( + 'name' => 'table', + 'handler' => 'elements', + ), + ); + + $Block['element']['text'] []= array( + 'name' => 'thead', + 'handler' => 'elements', + ); + + $Block['element']['text'] []= array( + 'name' => 'tbody', + 'handler' => 'elements', + 'text' => array(), + ); + + $Block['element']['text'][0]['text'] []= array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $HeaderElements, + ); + + return $Block; + } + } + + protected function blockTableContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if ($Line['text'][0] === '|' or strpos($Line['text'], '|')) + { + $Elements = array(); + + $row = $Line['text']; + + $row = trim($row); + $row = trim($row, '|'); + + preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches); + + foreach ($matches[0] as $index => $cell) + { + $cell = trim($cell); + + $Element = array( + 'name' => 'td', + 'handler' => 'line', + 'text' => $cell, + ); + + if (isset($Block['alignments'][$index])) + { + $Element['attributes'] = array( + 'style' => 'text-align: '.$Block['alignments'][$index].';', + ); + } + + $Elements []= $Element; + } + + $Element = array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $Elements, + ); + + $Block['element']['text'][1]['text'] []= $Element; + + return $Block; + } + } + + # + # ~ + # + + protected function paragraph($Line) + { + $Block = array( + 'element' => array( + 'name' => 'p', + 'text' => $Line['text'], + 'handler' => 'line', + ), + ); + + return $Block; + } + + # + # Inline Elements + # + + protected $InlineTypes = array( + '"' => array('SpecialCharacter'), + '!' => array('Image'), + '&' => array('SpecialCharacter'), + '*' => array('Emphasis'), + ':' => array('Url'), + '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'), + '>' => array('SpecialCharacter'), + '[' => array('Link'), + '_' => array('Emphasis'), + '`' => array('Code'), + '~' => array('Strikethrough'), + '\\' => array('EscapeSequence'), + ); + + # ~ + + protected $inlineMarkerList = '!"*_&[:<>`~\\'; + + # + # ~ + # + + public function line($text) + { + $markup = ''; + + # $excerpt is based on the first occurrence of a marker + + while ($excerpt = strpbrk($text, $this->inlineMarkerList)) + { + $marker = $excerpt[0]; + + $markerPosition = strpos($text, $marker); + + $Excerpt = array('text' => $excerpt, 'context' => $text); + + foreach ($this->InlineTypes[$marker] as $inlineType) + { + $Inline = $this->{'inline'.$inlineType}($Excerpt); + + if ( ! isset($Inline)) + { + continue; + } + + # makes sure that the inline belongs to "our" marker + + if (isset($Inline['position']) and $Inline['position'] > $markerPosition) + { + continue; + } + + # sets a default inline position + + if ( ! isset($Inline['position'])) + { + $Inline['position'] = $markerPosition; + } + + # the text that comes before the inline + $unmarkedText = substr($text, 0, $Inline['position']); + + # compile the unmarked text + $markup .= $this->unmarkedText($unmarkedText); + + # compile the inline + $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']); + + # remove the examined text + $text = substr($text, $Inline['position'] + $Inline['extent']); + + continue 2; + } + + # the marker does not belong to an inline + + $unmarkedText = substr($text, 0, $markerPosition + 1); + + $markup .= $this->unmarkedText($unmarkedText); + + $text = substr($text, $markerPosition + 1); + } + + $markup .= $this->unmarkedText($text); + + return $markup; + } + + # + # ~ + # + + protected function inlineCode($Excerpt) + { + $marker = $Excerpt['text'][0]; + + if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(? strlen($matches[0]), + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ); + } + } + + protected function inlineEmailTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches)) + { + $url = $matches[1]; + + if ( ! isset($matches[2])) + { + $url = 'mailto:' . $url; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $matches[1], + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function inlineEmphasis($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + $marker = $Excerpt['text'][0]; + + if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'strong'; + } + elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'em'; + } + else + { + return; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => $emphasis, + 'handler' => 'line', + 'text' => $matches[1], + ), + ); + } + + protected function inlineEscapeSequence($Excerpt) + { + if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) + { + return array( + 'markup' => $Excerpt['text'][1], + 'extent' => 2, + ); + } + } + + protected function inlineImage($Excerpt) + { + if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') + { + return; + } + + $Excerpt['text']= substr($Excerpt['text'], 1); + + $Link = $this->inlineLink($Excerpt); + + if ($Link === null) + { + return; + } + + $Inline = array( + 'extent' => $Link['extent'] + 1, + 'element' => array( + 'name' => 'img', + 'attributes' => array( + 'src' => $Link['element']['attributes']['href'], + 'alt' => $Link['element']['text'], + ), + ), + ); + + $Inline['element']['attributes'] += $Link['element']['attributes']; + + unset($Inline['element']['attributes']['href']); + + return $Inline; + } + + protected function inlineLink($Excerpt) + { + $Element = array( + 'name' => 'a', + 'handler' => 'line', + 'text' => null, + 'attributes' => array( + 'href' => null, + 'title' => null, + ), + ); + + $extent = 0; + + $remainder = $Excerpt['text']; + + if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches)) + { + $Element['text'] = $matches[1]; + + $extent += strlen($matches[0]); + + $remainder = substr($remainder, $extent); + } + else + { + return; + } + + if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches)) + { + $Element['attributes']['href'] = $matches[1]; + + if (isset($matches[2])) + { + $Element['attributes']['title'] = substr($matches[2], 1, - 1); + } + + $extent += strlen($matches[0]); + } + else + { + if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) + { + $definition = strlen($matches[1]) ? $matches[1] : $Element['text']; + $definition = strtolower($definition); + + $extent += strlen($matches[0]); + } + else + { + $definition = strtolower($Element['text']); + } + + if ( ! isset($this->DefinitionData['Reference'][$definition])) + { + return; + } + + $Definition = $this->DefinitionData['Reference'][$definition]; + + $Element['attributes']['href'] = $Definition['url']; + $Element['attributes']['title'] = $Definition['title']; + } + + $Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']); + + return array( + 'extent' => $extent, + 'element' => $Element, + ); + } + + protected function inlineMarkup($Excerpt) + { + if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false) + { + return; + } + + if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] === '!' and preg_match('/^/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + } + + protected function inlineSpecialCharacter($Excerpt) + { + if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text'])) + { + return array( + 'markup' => '&', + 'extent' => 1, + ); + } + + $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot'); + + if (isset($SpecialCharacter[$Excerpt['text'][0]])) + { + return array( + 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';', + 'extent' => 1, + ); + } + } + + protected function inlineStrikethrough($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'del', + 'text' => $matches[1], + 'handler' => 'line', + ), + ); + } + } + + protected function inlineUrl($Excerpt) + { + if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') + { + return; + } + + if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) + { + $Inline = array( + 'extent' => strlen($matches[0][0]), + 'position' => $matches[0][1], + 'element' => array( + 'name' => 'a', + 'text' => $matches[0][0], + 'attributes' => array( + 'href' => $matches[0][0], + ), + ), + ); + + return $Inline; + } + } + + protected function inlineUrlTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches)) + { + $url = str_replace(array('&', '<'), array('&', '<'), $matches[1]); + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + # ~ + + protected function unmarkedText($text) + { + if ($this->breaksEnabled) + { + $text = preg_replace('/[ ]*\n/', "
\n", $text); + } + else + { + $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "
\n", $text); + $text = str_replace(" \n", "\n", $text); + } + + return $text; + } + + # + # Handlers + # + + protected function element(array $Element) + { + $markup = '<'.$Element['name']; + + if (isset($Element['attributes'])) + { + foreach ($Element['attributes'] as $name => $value) + { + if ($value === null) + { + continue; + } + + $markup .= ' '.$name.'="'.$value.'"'; + } + } + + if (isset($Element['text'])) + { + $markup .= '>'; + + if (isset($Element['handler'])) + { + $markup .= $this->{$Element['handler']}($Element['text']); + } + else + { + $markup .= $Element['text']; + } + + $markup .= ''; + } + else + { + $markup .= ' />'; + } + + return $markup; + } + + protected function elements(array $Elements) + { + $markup = ''; + + foreach ($Elements as $Element) + { + $markup .= "\n" . $this->element($Element); + } + + $markup .= "\n"; + + return $markup; + } + + # ~ + + protected function li($lines) + { + $markup = $this->lines($lines); + + $trimmedMarkup = trim($markup); + + if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '

') + { + $markup = $trimmedMarkup; + $markup = substr($markup, 3); + + $position = strpos($markup, "

"); + + $markup = substr_replace($markup, '', $position, 4); + } + + return $markup; + } + + # + # Deprecated Methods + # + + function parse($text) + { + $markup = $this->text($text); + + return $markup; + } + + # + # Static Methods + # + + static function instance($name = 'default') + { + if (isset(self::$instances[$name])) + { + return self::$instances[$name]; + } + + $instance = new static(); + + self::$instances[$name] = $instance; + + return $instance; + } + + private static $instances = array(); + + # + # Fields + # + + protected $DefinitionData; + + # + # Read-Only + + protected $specialCharacters = array( + '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', + ); + + protected $StrongRegex = array( + '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s', + '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us', + ); + + protected $EmRegex = array( + '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', + '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', + ); + + protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?'; + + protected $voidElements = array( + 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', + ); + + protected $textLevelElements = array( + 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', + 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', + 'i', 'rp', 'del', 'code', 'strike', 'marquee', + 'q', 'rt', 'ins', 'font', 'strong', + 's', 'tt', 'sub', 'mark', + 'u', 'xm', 'sup', 'nobr', + 'var', 'ruby', + 'wbr', 'span', + 'time', + ); +} \ No newline at end of file diff --git a/admin/includes/plugin-update-checker/vendor/ParsedownLegacy.php b/admin/includes/plugin-update-checker/vendor/ParsedownLegacy.php new file mode 100755 index 0000000..bbc2d32 --- /dev/null +++ b/admin/includes/plugin-update-checker/vendor/ParsedownLegacy.php @@ -0,0 +1,1535 @@ +DefinitionData = array(); + + # standardize line breaks + $text = str_replace(array("\r\n", "\r"), "\n", $text); + + # remove surrounding line breaks + $text = trim($text, "\n"); + + # split text into lines + $lines = explode("\n", $text); + + # iterate through lines to identify blocks + $markup = $this->lines($lines); + + # trim line breaks + $markup = trim($markup, "\n"); + + return $markup; + } + + # + # Setters + # + + function setBreaksEnabled($breaksEnabled) + { + $this->breaksEnabled = $breaksEnabled; + + return $this; + } + + protected $breaksEnabled; + + function setMarkupEscaped($markupEscaped) + { + $this->markupEscaped = $markupEscaped; + + return $this; + } + + protected $markupEscaped; + + function setUrlsLinked($urlsLinked) + { + $this->urlsLinked = $urlsLinked; + + return $this; + } + + protected $urlsLinked = true; + + # + # Lines + # + + protected $BlockTypes = array( + '#' => array('Header'), + '*' => array('Rule', 'List'), + '+' => array('List'), + '-' => array('SetextHeader', 'Table', 'Rule', 'List'), + '0' => array('List'), + '1' => array('List'), + '2' => array('List'), + '3' => array('List'), + '4' => array('List'), + '5' => array('List'), + '6' => array('List'), + '7' => array('List'), + '8' => array('List'), + '9' => array('List'), + ':' => array('Table'), + '<' => array('Comment', 'Markup'), + '=' => array('SetextHeader'), + '>' => array('Quote'), + '[' => array('Reference'), + '_' => array('Rule'), + '`' => array('FencedCode'), + '|' => array('Table'), + '~' => array('FencedCode'), + ); + + # ~ + + protected $DefinitionTypes = array( + '[' => array('Reference'), + ); + + # ~ + + protected $unmarkedBlockTypes = array( + 'Code', + ); + + # + # Blocks + # + + private function lines(array $lines) + { + $CurrentBlock = null; + + foreach ($lines as $line) + { + if (chop($line) === '') + { + if (isset($CurrentBlock)) + { + $CurrentBlock['interrupted'] = true; + } + + continue; + } + + if (strpos($line, "\t") !== false) + { + $parts = explode("\t", $line); + + $line = $parts[0]; + + unset($parts[0]); + + foreach ($parts as $part) + { + $shortage = 4 - mb_strlen($line, 'utf-8') % 4; + + $line .= str_repeat(' ', $shortage); + $line .= $part; + } + } + + $indent = 0; + + while (isset($line[$indent]) and $line[$indent] === ' ') + { + $indent ++; + } + + $text = $indent > 0 ? substr($line, $indent) : $line; + + # ~ + + $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); + + # ~ + + if (isset($CurrentBlock['incomplete'])) + { + $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock); + + if (isset($Block)) + { + $CurrentBlock = $Block; + + continue; + } + else + { + if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete')) + { + $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); + } + + unset($CurrentBlock['incomplete']); + } + } + + # ~ + + $marker = $text[0]; + + # ~ + + $blockTypes = $this->unmarkedBlockTypes; + + if (isset($this->BlockTypes[$marker])) + { + foreach ($this->BlockTypes[$marker] as $blockType) + { + $blockTypes []= $blockType; + } + } + + # + # ~ + + foreach ($blockTypes as $blockType) + { + $Block = $this->{'block'.$blockType}($Line, $CurrentBlock); + + if (isset($Block)) + { + $Block['type'] = $blockType; + + if ( ! isset($Block['identified'])) + { + $Blocks []= $CurrentBlock; + + $Block['identified'] = true; + } + + if (method_exists($this, 'block'.$blockType.'Continue')) + { + $Block['incomplete'] = true; + } + + $CurrentBlock = $Block; + + continue 2; + } + } + + # ~ + + if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted'])) + { + $CurrentBlock['element']['text'] .= "\n".$text; + } + else + { + $Blocks []= $CurrentBlock; + + $CurrentBlock = $this->paragraph($Line); + + $CurrentBlock['identified'] = true; + } + } + + # ~ + + if (isset($CurrentBlock['incomplete']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete')) + { + $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); + } + + # ~ + + $Blocks []= $CurrentBlock; + + unset($Blocks[0]); + + # ~ + + $markup = ''; + + foreach ($Blocks as $Block) + { + if (isset($Block['hidden'])) + { + continue; + } + + $markup .= "\n"; + $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']); + } + + $markup .= "\n"; + + # ~ + + return $markup; + } + + # + # Code + + protected function blockCode($Line, $Block = null) + { + if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] >= 4) + { + $text = substr($Line['body'], 4); + + $Block = array( + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => array( + 'name' => 'code', + 'text' => $text, + ), + ), + ); + + return $Block; + } + } + + protected function blockCodeContinue($Line, $Block) + { + if ($Line['indent'] >= 4) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + $Block['element']['text']['text'] .= "\n"; + + $text = substr($Line['body'], 4); + + $Block['element']['text']['text'] .= $text; + + return $Block; + } + } + + protected function blockCodeComplete($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # Comment + + protected function blockComment($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!') + { + $Block = array( + 'markup' => $Line['body'], + ); + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + } + + protected function blockCommentContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + $Block['markup'] .= "\n" . $Line['body']; + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + + # + # Fenced Code + + protected function blockFencedCode($Line) + { + if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches)) + { + $Element = array( + 'name' => 'code', + 'text' => '', + ); + + if (isset($matches[2])) + { + $class = 'language-'.$matches[2]; + + $Element['attributes'] = array( + 'class' => $class, + ); + } + + $Block = array( + 'char' => $Line['text'][0], + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => $Element, + ), + ); + + return $Block; + } + } + + protected function blockFencedCodeContinue($Line, $Block) + { + if (isset($Block['complete'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) + { + $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1); + + $Block['complete'] = true; + + return $Block; + } + + $Block['element']['text']['text'] .= "\n".$Line['body'];; + + return $Block; + } + + protected function blockFencedCodeComplete($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # Header + + protected function blockHeader($Line) + { + if (isset($Line['text'][1])) + { + $level = 1; + + while (isset($Line['text'][$level]) and $Line['text'][$level] === '#') + { + $level ++; + } + + if ($level > 6) + { + return; + } + + $text = trim($Line['text'], '# '); + + $Block = array( + 'element' => array( + 'name' => 'h' . min(6, $level), + 'text' => $text, + 'handler' => 'line', + ), + ); + + return $Block; + } + } + + # + # List + + protected function blockList($Line) + { + list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]'); + + if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'indent' => $Line['indent'], + 'pattern' => $pattern, + 'element' => array( + 'name' => $name, + 'handler' => 'elements', + ), + ); + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $matches[2], + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + } + + protected function blockListContinue($Line, array $Block) + { + if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['li']['text'] []= ''; + + unset($Block['interrupted']); + } + + unset($Block['li']); + + $text = isset($matches[1]) ? $matches[1] : ''; + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $text, + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + + if ($Line['text'][0] === '[' and $this->blockReference($Line)) + { + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + return $Block; + } + + if ($Line['indent'] > 0) + { + $Block['li']['text'] []= ''; + + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + unset($Block['interrupted']); + + return $Block; + } + } + + # + # Quote + + protected function blockQuote($Line) + { + if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'element' => array( + 'name' => 'blockquote', + 'handler' => 'lines', + 'text' => (array) $matches[1], + ), + ); + + return $Block; + } + } + + protected function blockQuoteContinue($Line, array $Block) + { + if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text'] []= ''; + + unset($Block['interrupted']); + } + + $Block['element']['text'] []= $matches[1]; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $Block['element']['text'] []= $Line['text']; + + return $Block; + } + } + + # + # Rule + + protected function blockRule($Line) + { + if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text'])) + { + $Block = array( + 'element' => array( + 'name' => 'hr' + ), + ); + + return $Block; + } + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (chop($Line['text'], $Line['text'][0]) === '') + { + $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; + + return $Block; + } + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) + { + if (in_array($matches[1], $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'depth' => 0, + 'markup' => $Line['text'], + ); + + $length = strlen($matches[0]); + + $remainder = substr($Line['text'], $length); + + if (trim($remainder) === '') + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + $Block['closed'] = true; + + $Block['void'] = true; + } + } + else + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + return; + } + + if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) + { + $Block['closed'] = true; + } + } + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open + { + $Block['depth'] ++; + } + + if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close + { + if ($Block['depth'] > 0) + { + $Block['depth'] --; + } + else + { + $Block['closed'] = true; + } + + $Block['markup'] .= $matches[1]; + } + + if (isset($Block['interrupted'])) + { + $Block['markup'] .= "\n"; + + unset($Block['interrupted']); + } + + $Block['markup'] .= "\n".$Line['body']; + + return $Block; + } + + # + # Reference + + protected function blockReference($Line) + { + if (preg_match('/^\[(.+?)\]:[ ]*?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches)) + { + $id = strtolower($matches[1]); + + $Data = array( + 'url' => $matches[2], + 'title' => null, + ); + + if (isset($matches[3])) + { + $Data['title'] = $matches[3]; + } + + $this->DefinitionData['Reference'][$id] = $Data; + + $Block = array( + 'hidden' => true, + ); + + return $Block; + } + } + + # + # Table + + protected function blockTable($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '') + { + $alignments = array(); + + $divider = $Line['text']; + + $divider = trim($divider); + $divider = trim($divider, '|'); + + $dividerCells = explode('|', $divider); + + foreach ($dividerCells as $dividerCell) + { + $dividerCell = trim($dividerCell); + + if ($dividerCell === '') + { + continue; + } + + $alignment = null; + + if ($dividerCell[0] === ':') + { + $alignment = 'left'; + } + + if (substr($dividerCell, - 1) === ':') + { + $alignment = $alignment === 'left' ? 'center' : 'right'; + } + + $alignments []= $alignment; + } + + # ~ + + $HeaderElements = array(); + + $header = $Block['element']['text']; + + $header = trim($header); + $header = trim($header, '|'); + + $headerCells = explode('|', $header); + + foreach ($headerCells as $index => $headerCell) + { + $headerCell = trim($headerCell); + + $HeaderElement = array( + 'name' => 'th', + 'text' => $headerCell, + 'handler' => 'line', + ); + + if (isset($alignments[$index])) + { + $alignment = $alignments[$index]; + + $HeaderElement['attributes'] = array( + 'style' => 'text-align: '.$alignment.';', + ); + } + + $HeaderElements []= $HeaderElement; + } + + # ~ + + $Block = array( + 'alignments' => $alignments, + 'identified' => true, + 'element' => array( + 'name' => 'table', + 'handler' => 'elements', + ), + ); + + $Block['element']['text'] []= array( + 'name' => 'thead', + 'handler' => 'elements', + ); + + $Block['element']['text'] []= array( + 'name' => 'tbody', + 'handler' => 'elements', + 'text' => array(), + ); + + $Block['element']['text'][0]['text'] []= array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $HeaderElements, + ); + + return $Block; + } + } + + protected function blockTableContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if ($Line['text'][0] === '|' or strpos($Line['text'], '|')) + { + $Elements = array(); + + $row = $Line['text']; + + $row = trim($row); + $row = trim($row, '|'); + + preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches); + + foreach ($matches[0] as $index => $cell) + { + $cell = trim($cell); + + $Element = array( + 'name' => 'td', + 'handler' => 'line', + 'text' => $cell, + ); + + if (isset($Block['alignments'][$index])) + { + $Element['attributes'] = array( + 'style' => 'text-align: '.$Block['alignments'][$index].';', + ); + } + + $Elements []= $Element; + } + + $Element = array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $Elements, + ); + + $Block['element']['text'][1]['text'] []= $Element; + + return $Block; + } + } + + # + # ~ + # + + protected function paragraph($Line) + { + $Block = array( + 'element' => array( + 'name' => 'p', + 'text' => $Line['text'], + 'handler' => 'line', + ), + ); + + return $Block; + } + + # + # Inline Elements + # + + protected $InlineTypes = array( + '"' => array('SpecialCharacter'), + '!' => array('Image'), + '&' => array('SpecialCharacter'), + '*' => array('Emphasis'), + ':' => array('Url'), + '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'), + '>' => array('SpecialCharacter'), + '[' => array('Link'), + '_' => array('Emphasis'), + '`' => array('Code'), + '~' => array('Strikethrough'), + '\\' => array('EscapeSequence'), + ); + + # ~ + + protected $inlineMarkerList = '!"*_&[:<>`~\\'; + + # + # ~ + # + + public function line($text) + { + $markup = ''; + + $unexaminedText = $text; + + $markerPosition = 0; + + while ($excerpt = strpbrk($unexaminedText, $this->inlineMarkerList)) + { + $marker = $excerpt[0]; + + $markerPosition += strpos($unexaminedText, $marker); + + $Excerpt = array('text' => $excerpt, 'context' => $text); + + foreach ($this->InlineTypes[$marker] as $inlineType) + { + $Inline = $this->{'inline'.$inlineType}($Excerpt); + + if ( ! isset($Inline)) + { + continue; + } + + if (isset($Inline['position']) and $Inline['position'] > $markerPosition) # position is ahead of marker + { + continue; + } + + if ( ! isset($Inline['position'])) + { + $Inline['position'] = $markerPosition; + } + + $unmarkedText = substr($text, 0, $Inline['position']); + + $markup .= $this->unmarkedText($unmarkedText); + + $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']); + + $text = substr($text, $Inline['position'] + $Inline['extent']); + + $unexaminedText = $text; + + $markerPosition = 0; + + continue 2; + } + + $unexaminedText = substr($excerpt, 1); + + $markerPosition ++; + } + + $markup .= $this->unmarkedText($text); + + return $markup; + } + + # + # ~ + # + + protected function inlineCode($Excerpt) + { + $marker = $Excerpt['text'][0]; + + if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(? strlen($matches[0]), + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ); + } + } + + protected function inlineEmailTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches)) + { + $url = $matches[1]; + + if ( ! isset($matches[2])) + { + $url = 'mailto:' . $url; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $matches[1], + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function inlineEmphasis($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + $marker = $Excerpt['text'][0]; + + if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'strong'; + } + elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'em'; + } + else + { + return; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => $emphasis, + 'handler' => 'line', + 'text' => $matches[1], + ), + ); + } + + protected function inlineEscapeSequence($Excerpt) + { + if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) + { + return array( + 'markup' => $Excerpt['text'][1], + 'extent' => 2, + ); + } + } + + protected function inlineImage($Excerpt) + { + if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') + { + return; + } + + $Excerpt['text']= substr($Excerpt['text'], 1); + + $Link = $this->inlineLink($Excerpt); + + if ($Link === null) + { + return; + } + + $Inline = array( + 'extent' => $Link['extent'] + 1, + 'element' => array( + 'name' => 'img', + 'attributes' => array( + 'src' => $Link['element']['attributes']['href'], + 'alt' => $Link['element']['text'], + ), + ), + ); + + $Inline['element']['attributes'] += $Link['element']['attributes']; + + unset($Inline['element']['attributes']['href']); + + return $Inline; + } + + protected function inlineLink($Excerpt) + { + $Element = array( + 'name' => 'a', + 'handler' => 'line', + 'text' => null, + 'attributes' => array( + 'href' => null, + 'title' => null, + ), + ); + + $extent = 0; + + $remainder = $Excerpt['text']; + + if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches)) + { + $Element['text'] = $matches[1]; + + $extent += strlen($matches[0]); + + $remainder = substr($remainder, $extent); + } + else + { + return; + } + + if (preg_match('/^[(]((?:[^ (]|[(][^ )]+[)])+)(?:[ ]+("[^"]+"|\'[^\']+\'))?[)]/', $remainder, $matches)) + { + $Element['attributes']['href'] = $matches[1]; + + if (isset($matches[2])) + { + $Element['attributes']['title'] = substr($matches[2], 1, - 1); + } + + $extent += strlen($matches[0]); + } + else + { + if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) + { + $definition = $matches[1] ? $matches[1] : $Element['text']; + $definition = strtolower($definition); + + $extent += strlen($matches[0]); + } + else + { + $definition = strtolower($Element['text']); + } + + if ( ! isset($this->DefinitionData['Reference'][$definition])) + { + return; + } + + $Definition = $this->DefinitionData['Reference'][$definition]; + + $Element['attributes']['href'] = $Definition['url']; + $Element['attributes']['title'] = $Definition['title']; + } + + $Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']); + + return array( + 'extent' => $extent, + 'element' => $Element, + ); + } + + protected function inlineMarkup($Excerpt) + { + if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false) + { + return; + } + + if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] === '!' and preg_match('/^/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + } + + protected function inlineSpecialCharacter($Excerpt) + { + if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text'])) + { + return array( + 'markup' => '&', + 'extent' => 1, + ); + } + + $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot'); + + if (isset($SpecialCharacter[$Excerpt['text'][0]])) + { + return array( + 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';', + 'extent' => 1, + ); + } + } + + protected function inlineStrikethrough($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'del', + 'text' => $matches[1], + 'handler' => 'line', + ), + ); + } + } + + protected function inlineUrl($Excerpt) + { + if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') + { + return; + } + + if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) + { + $Inline = array( + 'extent' => strlen($matches[0][0]), + 'position' => $matches[0][1], + 'element' => array( + 'name' => 'a', + 'text' => $matches[0][0], + 'attributes' => array( + 'href' => $matches[0][0], + ), + ), + ); + + return $Inline; + } + } + + protected function inlineUrlTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches)) + { + $url = str_replace(array('&', '<'), array('&', '<'), $matches[1]); + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + # + # ~ + + protected $unmarkedInlineTypes = array("\n" => 'Break', '://' => 'Url'); + + # ~ + + protected function unmarkedText($text) + { + if ($this->breaksEnabled) + { + $text = preg_replace('/[ ]*\n/', "
\n", $text); + } + else + { + $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "
\n", $text); + $text = str_replace(" \n", "\n", $text); + } + + return $text; + } + + # + # Handlers + # + + protected function element(array $Element) + { + $markup = '<'.$Element['name']; + + if (isset($Element['attributes'])) + { + foreach ($Element['attributes'] as $name => $value) + { + if ($value === null) + { + continue; + } + + $markup .= ' '.$name.'="'.$value.'"'; + } + } + + if (isset($Element['text'])) + { + $markup .= '>'; + + if (isset($Element['handler'])) + { + $markup .= $this->{$Element['handler']}($Element['text']); + } + else + { + $markup .= $Element['text']; + } + + $markup .= ''; + } + else + { + $markup .= ' />'; + } + + return $markup; + } + + protected function elements(array $Elements) + { + $markup = ''; + + foreach ($Elements as $Element) + { + $markup .= "\n" . $this->element($Element); + } + + $markup .= "\n"; + + return $markup; + } + + # ~ + + protected function li($lines) + { + $markup = $this->lines($lines); + + $trimmedMarkup = trim($markup); + + if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '

') + { + $markup = $trimmedMarkup; + $markup = substr($markup, 3); + + $position = strpos($markup, "

"); + + $markup = substr_replace($markup, '', $position, 4); + } + + return $markup; + } + + # + # Deprecated Methods + # + + function parse($text) + { + $markup = $this->text($text); + + return $markup; + } + + # + # Static Methods + # + + static function instance($name = 'default') + { + if (isset(self::$instances[$name])) + { + return self::$instances[$name]; + } + + $instance = new self(); + + self::$instances[$name] = $instance; + + return $instance; + } + + private static $instances = array(); + + # + # Fields + # + + protected $DefinitionData; + + # + # Read-Only + + protected $specialCharacters = array( + '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', + ); + + protected $StrongRegex = array( + '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s', + '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us', + ); + + protected $EmRegex = array( + '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', + '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', + ); + + protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?'; + + protected $voidElements = array( + 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', + ); + + protected $textLevelElements = array( + 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', + 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', + 'i', 'rp', 'del', 'code', 'strike', 'marquee', + 'q', 'rt', 'ins', 'font', 'strong', + 's', 'tt', 'sub', 'mark', + 'u', 'xm', 'sup', 'nobr', + 'var', 'ruby', + 'wbr', 'span', + 'time', + ); +} diff --git a/admin/includes/plugin-update-checker/vendor/readme-parser.php b/admin/includes/plugin-update-checker/vendor/readme-parser.php new file mode 100755 index 0000000..ea24751 --- /dev/null +++ b/admin/includes/plugin-update-checker/vendor/readme-parser.php @@ -0,0 +1,341 @@ +parse_readme_contents( $file_contents ); + } + + function parse_readme_contents( $file_contents ) { + $file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents); + $file_contents = trim($file_contents); + if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) ) + $file_contents = substr( $file_contents, 3 ); + + // Markdown transformations + $file_contents = preg_replace( "|^###([^#]+)#*?\s*?\n|im", '=$1='."\n", $file_contents ); + $file_contents = preg_replace( "|^##([^#]+)#*?\s*?\n|im", '==$1=='."\n", $file_contents ); + $file_contents = preg_replace( "|^#([^#]+)#*?\s*?\n|im", '===$1==='."\n", $file_contents ); + + // === Plugin Name === + // Must be the very first thing. + if ( !preg_match('|^===(.*)===|', $file_contents, $_name) ) + return array(); // require a name + $name = trim($_name[1], '='); + $name = $this->sanitize_text( $name ); + + $file_contents = $this->chop_string( $file_contents, $_name[0] ); + + + // Requires at least: 1.5 + if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) ) + $requires_at_least = $this->sanitize_text($_requires_at_least[1]); + else + $requires_at_least = NULL; + + + // Tested up to: 2.1 + if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) ) + $tested_up_to = $this->sanitize_text( $_tested_up_to[1] ); + else + $tested_up_to = NULL; + + + // Stable tag: 10.4-ride-the-fire-eagle-danger-day + if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) ) + $stable_tag = $this->sanitize_text( $_stable_tag[1] ); + else + $stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk + + + // Tags: some tag, another tag, we like tags + if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) { + $tags = preg_split('|,[\s]*?|', trim($_tags[1])); + foreach ( array_keys($tags) as $t ) + $tags[$t] = $this->sanitize_text( $tags[$t] ); + } else { + $tags = array(); + } + + + // Contributors: markjaquith, mdawaffe, zefrank + $contributors = array(); + if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) { + $temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1])); + foreach ( array_keys($temp_contributors) as $c ) { + $tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] ); + if ( strlen(trim($tmp_sanitized)) > 0 ) + $contributors[$c] = $tmp_sanitized; + unset($tmp_sanitized); + } + } + + + // Donate Link: URL + if ( preg_match('|Donate link:(.*)|i', $file_contents, $_donate_link) ) + $donate_link = esc_url( $_donate_link[1] ); + else + $donate_link = NULL; + + + // togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values. + foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link') as $chop ) { + if ( $$chop ) { + $_chop = '_' . $chop; + $file_contents = $this->chop_string( $file_contents, ${$_chop}[0] ); + } + } + + $file_contents = trim($file_contents); + + + // short-description fu + if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) ) + $_short_description = array( 1 => &$file_contents, 2 => &$file_contents ); + $short_desc_filtered = $this->sanitize_text( $_short_description[2] ); + $short_desc_length = strlen($short_desc_filtered); + $short_description = substr($short_desc_filtered, 0, 150); + if ( $short_desc_length > strlen($short_description) ) + $truncated = true; + else + $truncated = false; + if ( $_short_description[1] ) + $file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional + + // == Section == + // Break into sections + // $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section + // the array alternates from there: title2, content2, title3, content3... and so forth + $_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + + $sections = array(); + for ( $i=0; $i < count($_sections); $i +=2 ) { + $title = $this->sanitize_text( $_sections[$i] ); + if ( isset($_sections[$i+1]) ) { + $content = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1

$2

', $_sections[$i+1]); + $content = $this->filter_text( $content, true ); + } else { + $content = ''; + } + $sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $content); + } + + + // Special sections + // This is where we nab our special sections, so we can enforce their order and treat them differently, if needed + // upgrade_notice is not a section, but parse it like it is for now + $final_sections = array(); + foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) { + if ( isset($sections[$special_section]) ) { + $final_sections[$special_section] = $sections[$special_section]['content']; + unset($sections[$special_section]); + } + } + if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) ) + $final_sections['changelog'] = $final_sections['change_log']; + + + $final_screenshots = array(); + if ( isset($final_sections['screenshots']) ) { + preg_match_all('|
  • (.*?)
  • |s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER); + if ( $screenshots ) { + foreach ( (array) $screenshots as $ss ) + $final_screenshots[] = $ss[1]; + } + } + + // Parse the upgrade_notice section specially: + // 1.0 => blah, 1.1 => fnord + $upgrade_notice = array(); + if ( isset($final_sections['upgrade_notice']) ) { + $split = preg_split( '#

    (.*?)

    #', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); + if ( count($split) >= 2 ) { + for ( $i = 0; $i < count( $split ); $i += 2 ) { + $upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 ); + } + } + unset( $final_sections['upgrade_notice'] ); + } + + // No description? + // No problem... we'll just fall back to the old style of description + // We'll even let you use markup this time! + $excerpt = false; + if ( !isset($final_sections['description']) ) { + $final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections); + $excerpt = true; + } + + + // dump the non-special sections into $remaining_content + // their order will be determined by their original order in the readme.txt + $remaining_content = ''; + foreach ( $sections as $s_name => $s_data ) { + $remaining_content .= "\n

    {$s_data['title']}

    \n{$s_data['content']}"; + } + $remaining_content = trim($remaining_content); + + + // All done! + // $r['tags'] and $r['contributors'] are simple arrays + // $r['sections'] is an array with named elements + $r = array( + 'name' => $name, + 'tags' => $tags, + 'requires_at_least' => $requires_at_least, + 'tested_up_to' => $tested_up_to, + 'stable_tag' => $stable_tag, + 'contributors' => $contributors, + 'donate_link' => $donate_link, + 'short_description' => $short_description, + 'screenshots' => $final_screenshots, + 'is_excerpt' => $excerpt, + 'is_truncated' => $truncated, + 'sections' => $final_sections, + 'remaining_content' => $remaining_content, + 'upgrade_notice' => $upgrade_notice + ); + + return $r; + } + + function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos + if ( $_string = strstr($string, $chop) ) { + $_string = substr($_string, strlen($chop)); + return trim($_string); + } else { + return trim($string); + } + } + + function user_sanitize( $text, $strict = false ) { // whitelisted chars + if ( function_exists('user_sanitize') ) // bbPress native + return user_sanitize( $text, $strict ); + + if ( $strict ) { + $text = preg_replace('/[^a-z0-9-]/i', '', $text); + $text = preg_replace('|-+|', '-', $text); + } else { + $text = preg_replace('/[^a-z0-9_-]/i', '', $text); + } + return $text; + } + + function sanitize_text( $text ) { // not fancy + $text = strip_tags($text); + $text = esc_html($text); + $text = trim($text); + return $text; + } + + function filter_text( $text, $markdown = false ) { // fancy, Markdown + $text = trim($text); + + $text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE + + if ( $markdown ) { // Parse markdown. + if ( !class_exists('Parsedown', false) ) { + /** @noinspection PhpIncludeInspection */ + require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php'); + } + $instance = Parsedown::instance(); + $text = $instance->text($text); + } + + $allowed = array( + 'a' => array( + 'href' => array(), + 'title' => array(), + 'rel' => array()), + 'blockquote' => array('cite' => array()), + 'br' => array(), + 'p' => array(), + 'code' => array(), + 'pre' => array(), + 'em' => array(), + 'strong' => array(), + 'ul' => array(), + 'ol' => array(), + 'li' => array(), + 'h3' => array(), + 'h4' => array() + ); + + $text = balanceTags($text); + + $text = wp_kses( $text, $allowed ); + $text = trim($text); + return $text; + } + + function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown + // If doing markdown, first take any user formatted code blocks and turn them into backticks so that + // markdown will preserve things like underscores in code blocks + if ( $markdown ) + $text = preg_replace_callback("!(
    |)(.*?)(
    |)!s", array( __CLASS__,'decodeit'), $text); + + $text = str_replace(array("\r\n", "\r"), "\n", $text); + if ( !$markdown ) { + // This gets the "inline" code blocks, but can't be used with Markdown. + $text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text); + // This gets the "block level" code blocks and converts them to PRE CODE + $text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text); + } else { + // Markdown can do inline code, we convert bbPress style block level code to Markdown style + $text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text); + } + return $text; + } + + function indent( $matches ) { + $text = $matches[3]; + $text = preg_replace('|^|m', $matches[2] . ' ', $text); + return $matches[1] . $text; + } + + function encodeit( $matches ) { + if ( function_exists('encodeit') ) // bbPress native + return encodeit( $matches ); + + $text = trim($matches[2]); + $text = htmlspecialchars($text, ENT_QUOTES); + $text = str_replace(array("\r\n", "\r"), "\n", $text); + $text = preg_replace("|\n\n\n+|", "\n\n", $text); + $text = str_replace('&lt;', '<', $text); + $text = str_replace('&gt;', '>', $text); + $text = "$text"; + if ( "`" != $matches[1] ) + $text = "
    $text
    "; + return $text; + } + + function decodeit( $matches ) { + if ( function_exists('decodeit') ) // bbPress native + return decodeit( $matches ); + + $text = $matches[2]; + $trans_table = array_flip(get_html_translation_table(HTML_ENTITIES)); + $text = strtr($text, $trans_table); + $text = str_replace('
    ', '', $text); + $text = str_replace('&', '&', $text); + $text = str_replace(''', "'", $text); + if ( '
    ' == $matches[1] )
    +			$text = "\n$text\n";
    +		return "`$text`";
    +	}
    +
    +} // end class
    +
    +endif;
    diff --git a/admin/includes/wpestores/slm-wpestores.php b/admin/includes/wpestores/slm-wpestores.php
    index eb38302..df67c8d 100755
    --- a/admin/includes/wpestores/slm-wpestores.php
    +++ b/admin/includes/wpestores/slm-wpestores.php
    @@ -67,7 +67,7 @@ function slm_estore_check_and_generate_key($retrieved_product, $payment_data, $c
         if ($retrieved_product->create_license == 1) {
             $slm_debug_logger->log_debug('Need to create a license key for this product (' . $retrieved_product->id . ')');
             $slm_key = slm_estore_create_license($retrieved_product, $payment_data, $cart_items, $item_name);
    -        $license_data = "\n" . __('Item Name: ', 'slm') . $retrieved_product->name . " - " . __('License Key: ', 'slm') . $slm_key;
    +        $license_data = "\n" . __('Item Name: ', 'softwarelicensemanager') . $retrieved_product->name . " - " . __('License Key: ', 'softwarelicensemanager') . $slm_key;
             $slm_debug_logger->log_debug('Liense data: ' . $license_data);
             $license_data = apply_filters('slm_estore_item_license_data', $license_data);
         }
    diff --git a/admin/slm-add-licenses.php b/admin/slm-add-licenses.php
    index 4cc4e36..f5ddf4f 100755
    --- a/admin/slm-add-licenses.php
    +++ b/admin/slm-add-licenses.php
    @@ -138,7 +138,7 @@ function slm_add_licenses_menu()
                 $result = $wpdb->insert($lk_table, $fields);
                 $id = $wpdb->insert_id;
                 if ($result === false) {
    -                $errors .= __('Record could not be inserted into the database!', 'slm');
    +                $errors .= __('Record could not be inserted into the database!', 'softwarelicensemanager');
                 }
             } else {
                 //Update record
    @@ -146,7 +146,7 @@ function slm_add_licenses_menu()
                 $updated = $wpdb->update($lk_table, $fields, $where);
                 if ($updated === false) {
                     //TODO - log error
    -                $errors .= __('Update of the license key table failed!', 'slm');
    +                $errors .= __('Update of the license key table failed!', 'softwarelicensemanager');
                 }
             }
     
    @@ -175,17 +175,14 @@ function slm_add_licenses_menu()
         
     
         
    -
    +
    -

    - Software License Manager +

    - You can add a new license or edit an existing one from this interface. +

    @@ -231,39 +228,39 @@ function slm_add_licenses_menu() diff --git a/admin/slm-admin-functions.php b/admin/slm-admin-functions.php index a130b40..35a3328 100755 --- a/admin/slm-admin-functions.php +++ b/admin/slm-admin-functions.php @@ -9,7 +9,7 @@ function slm_admin_tools_menu() { echo '
    '; - echo '

    slm logo Software License Manager Admin Tools

    '; + echo '

    slm logo Admin Tools

    '; echo '
    '; $slm_options = get_option('slm_plugin_options'); @@ -38,9 +38,9 @@ function slm_admin_tools_menu() ?>
    -

    +

    -
    Enter the URL where the license deactivation message will be sent to +


    diff --git a/admin/slm-admin-init.php b/admin/slm-admin-init.php index 0cafc52..69f7b9b 100755 --- a/admin/slm-admin-init.php +++ b/admin/slm-admin-init.php @@ -5,13 +5,6 @@ } -/* - * This file only gets included if "is_admin " check is true. - * Admin menu rendering code goes in this file. - */ - - -//Include menu handling files require_once SLM_ADMIN . 'slm-manage-licenses.php'; require_once SLM_ADMIN . 'slm-add-licenses.php'; require_once SLM_ADMIN . 'slm-lic-settings.php'; diff --git a/admin/slm-integration-help-page.php b/admin/slm-integration-help-page.php index acaaa32..069d64c 100755 --- a/admin/slm-integration-help-page.php +++ b/admin/slm-integration-help-page.php @@ -9,123 +9,52 @@ function slm_integration_help_menu() { ?> - slm logo License Manager Integration Help v' . SLM_VERSION . ''; - ?> - -
    -

    -
    - - The License API Query POST URL For Your Installation"; - echo '
    ' . $api_query_post_url . '
    '; - echo "The License Activation or Deactivation API secret key"; - echo '
    ' . $secret_verification_key . '
    '; - echo "The License Creation API secret key"; - echo '
    ' . $creation_secret_key . '
    '; - ?> - -
    -
    - -
    - - - -

    3rd Party Integration

    - - Integrating a 3rd party payment system or shopping cart with License Manager is easy. -

    - The integration process can be accomplished in three steps, namely: -
    -
    1. Generate POST data -
    2. Send POST data to the API POST URL -
    3. Process the returned data -

    - POST Values -
    - License Manager expects a certain set of variables to be sent to it via HTTP POST or GET. These variables are: -

    - Mandatory Variables -
    - ---------------- -
    a. secret_key - A Secret API key for authentication (you can find the secret key value in the settings menu of this plugin) -
    b. slm_action - The action being performed. The values can be slm_create_new or slm_activate or slm_deactivate -

    - Optional Variables -
    - --------------- -
    c. Customer First Name: The first name of the customer -
    d. Customer Last Name: The last name of the customer -
    e. Customer Email: The email address of the customer -
    f. Company Name: The customer's company name -
    g. Maximum Domains Allowed: The number of domains this license key can be used on -
    h. Transaction ID: A unique transaction ID to reference the transaction -

    - Return Value -
    - Upon successful processing, License Manager will return a plain text message that will have two or three lines similar to the following: -
    -
    - Success -
    License key -
    WPLICMGR4bc29fd61e471 -
    - or -
    - Error -
    Secret key is invalid -
    - - 1. The first line is an indication of success or error -
    2. The second line is the result. -
    3. The third line is additional message that resulted from the request. -

    - Sample PHP Code -
    - Below is a sample PHP code that shows how you can create a license via the API -
    - -
    - /*** Mandatory data ***/ -
    // Post URL -
    $postURL = ""; -
    // The Secret key -
    $secretKey = ""; -
    -
    /*** Optional Data ***/ -
    $firstname = "John"; -
    $lastname = "Doe"; -
    $email = "john.doe@gmail.com"; -
    -
    // prepare the data -
    $data = array (); -
    $data['secret_key'] = $secretKey; -
    $data['slm_action'] = 'slm_create_new'; -
    $data['first_name'] = $firstname; -
    $data['last_name'] = $lastname; -
    $data['email'] = $email; -
    -
    // send data to post URL -
    $ch = curl_init ($postURL); -
    curl_setopt ($ch, CURLOPT_POST, true); -
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $data); -
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); -
    $returnValue = curl_exec ($ch); -
    -
    // Process the return values -
    //var_dump($returnValue); -
    - - -
    -

    Error codes and constants

    -
    +    

    License Manager Integration Help v

    + + +
    +
    +

    API Settings

    +
    + The License API Query POST URL For Your Installation"; + echo '
    '; + echo "
    The License Activation or Deactivation API secret key"; + echo '
    '; + echo "
    The License Creation API secret key"; + echo '
    '; + ?> + +
    + +
    +

    Documentation and guides: check out postman demos

    +
    + +
    +

    Error codes and constants

    +
                         const CREATE_FAILED                 = 10;
                         const CREATE_KEY_INVALID            = 100;
                         const DOMAIN_ALREADY_INACTIVE       = 80;
    @@ -151,10 +80,11 @@ function slm_integration_help_menu()
                         const REACHED_MAX_DEVICES           = 120;
                         const REACHED_MAX_DOMAINS           = 50;
                         const VERIFY_KEY_INVALID            = 90;
    -                        
    +
    +
    +
    -
    '; - echo '
    '; - } +'; - echo '

    Settings - Software License Manager

    -
    '; - echo '
    '; - slm_general_settings(); - - echo '
    '; - echo '
    '; } function slm_general_settings() { + ?> + trim($_POST["default_max_domains"]), 'default_max_devices' => trim($_POST["default_max_devices"]), 'lic_verification_secret' => trim($_POST["lic_verification_secret"]), - 'enable_auto_key_expiry' => isset($_POST['enable_auto_key_expiry']) ? '1' : '', + 'enable_auto_key__xpiry' => isset($_POST['enable_auto_key__xpiry']) ? '1' : '', 'enable_debug' => isset($_POST['enable_debug']) ? '1' : '', 'slm_woo' => isset($_POST['slm_woo']) ? '1' : '', 'slm_woo_downloads' => isset($_POST['slm_woo_downloads']) ? '1' : '', 'slm_wpestores' => isset($_POST['slm_wpestores']) ? '1' : '', 'slm_dl_manager' => isset($_POST['slm_dl_manager']) ? '1' : '', + 'expiration_reminder_text' => sanitize_text_field($_POST['expiration_reminder_text']) ); update_option('slm_plugin_options', $options); - echo '

    '; - echo 'Options Updated!'; - echo '

    '; + echo ' +
    +

    Options Updated!

    +
    '; } - $options = get_option('slm_plugin_options'); - + $options = get_option('slm_plugin_options'); $secret_key = $options['lic_creation_secret']; + if (empty($secret_key)) { //$secret_key = md5(uniqid('', true)); $secret_key = SLM_Utility::create_secret_keys(); @@ -74,123 +69,166 @@ function slm_general_settings() //$secret_verification_key = md5(uniqid('', true)); $secret_verification_key = SLM_Utility::create_secret_keys(); } + $tab = ""; //Initialization value; + if (isset($_REQUEST['tab'])) { + $tab = $_REQUEST['tab']; + } else { + $tab = 'general_settings'; + } ?> - - - - -
    -

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Secret Key for License Creation -

    This secret key will be used to authenticate any license creation request. You can change it with something random.

    -
    Secret Key for License Verification Requests -

    This secret key will be used to authenticate any license verification request from customer's site. Important! Do not change this value once your customers start to use your product(s)!

    -
    License Key Prefix -

    You can optionaly specify a prefix for the license keys. This prefix will be added to the uniquely generated license keys.

    -
    Maximum Allowed Domains -

    Maximum number of domains/installs which each license is valid for (default value).

    -
    Maximum Allowed Devices -

    Maximum number of devices which each license is valid for (default value).

    -
    Auto Expire License Keys value="1" />Enable auto expiration -

    When enabled, it will automatically set the status of a license key to "Expired" when the expiry date value of the key is reached. It doesn't remotely deactivate a key. It simply changes the status of the key in your database to expired.

    -
    -
    - - -
    - -
    -

    -
    - - - - - - - - - - - - - - - - - - -
    Woocommerce Support - value="1" /> - A fully customizable, open source eCommerce platform built for WordPress. - value="1" /> - Disable woocommerce download page. Proccess downloads though license order info page.
    Download Manager Support - value="1" /> - Download Manager Plugin – Adds a simple download manager to your WordPress blog. -
    WP eStores Support - value="1" /> - WordPress eStore Plugin – Complete Solution to Sell Digital Products from Your WordPress Blog Securely - -
    -
    +
    +

    Settings - Software License Manager

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

    +
    +

    +
    +

    +
    +

    +
    +

    +
    value="1" /> + +

    +
    +
    + +
    +
    + + + + + + + + + + + + + + + + + +
    + value="1" /> +
    + value="1" /> +
    + value="1" /> + +
    + value="1" /> + + +
    +
    +
    + +
    +
    + + + + + +
    +

    value="1" /> +

    + - .. + - . +
    +
    +
    + +
    +
    + + + + + +
    + +
    +
    +
    + +
    + +
    +
    -
    -

    -
    - - - - - - - -
    Enable Debug Logging value="1" /> -

    If checked, debug output will be written to log files (keep it disabled unless you are troubleshooting).

    - - View debug log file by clicking here.. - - Reset debug log file by clicking here. -
    -
    -
    - -
    - -
    - -%s(%s)'; @@ -55,21 +56,21 @@ function get_views() esc_url(add_query_arg('view', 'pending', $base . '&s=pending')), $current === 'pending' ? ' class="current"' : '', esc_html__('pending', 'slm'), - SLM_Utility::count_licenses( 'pending') + SLM_Utility::count_licenses('pending') ), 'expired' => sprintf( $link_html, esc_url(add_query_arg('view', 'expired', $base . '&s=expired')), $current === 'expired' ? ' class="current"' : '', esc_html__('expired', 'slm'), - SLM_Utility::count_licenses( 'expired') + SLM_Utility::count_licenses('expired') ), 'blocked' => sprintf( $link_html, esc_url(add_query_arg('view', 'blocked', $base . '&s=blocked')), $current === 'blocked' ? ' class="current"' : '', esc_html__('blocked', 'slm'), - SLM_Utility::count_licenses( 'blocked') + SLM_Utility::count_licenses('blocked') ) ); @@ -108,22 +109,20 @@ function column_default($item, $column_name) break; case 'email': - return '' . $item[$column_name] . ' '; + return '' . $item[$column_name] . ' '; break; case 'date_expiry': $now = $item[$column_name]; $date_today = time(); - if ($now != '0000-00-00'){ - if( strtotime($now) < time()) { - return ' '. $now . ' ' . ' ' . SLM_Utility::get_days_remaining($now) . ' day(s) due'; - } - else { + if ($now != '0000-00-00') { + if (strtotime($now) < time()) { + return ' ' . $now . ' ' . ' ' . SLM_Utility::get_days_remaining($now) . ' day(s) due'; + } else { return '' . $item[$column_name] . '' . ' ' . SLM_Utility::get_days_remaining($now) . ' day(s) left'; } - } - else { + } else { //return $item[$column_name]; return 'not set'; } @@ -178,7 +177,7 @@ function get_sortable_columns() 'email' => array('email', true), 'lic_type' => array('lic_type', true), 'until' => array('until', true), - 'current_ver' => array( 'current_ver', true), + 'current_ver' => array('current_ver', true), 'lic_status' => array('lic_status', true) ); @@ -255,8 +254,7 @@ function process_bulk_action() $error_msg = '

    ' . __('Error - Please select some records using the checkboxes', 'slm') . '

    '; echo '
    ' . $error_msg . '
    '; return; - } - else { + } else { $nvp_key = $this->_args['singular']; $liceses_to_activate = $_GET[$nvp_key]; @@ -292,7 +290,8 @@ function block_license_key($key_row_id) echo $success_msg; } - private function sort_data($a, $b){ + private function sort_data($a, $b) + { // Set defaults $orderby = 'id'; $order = 'desc'; @@ -311,9 +310,19 @@ private function sort_data($a, $b){ return -$result; } - function prepare_items(){ + function prepare_items() + { + + $user = get_current_user_id(); + $screen = get_current_screen(); + $option = $screen->get_option('per_page', 'option'); + + $per_page = get_user_meta($user, $option, true); + + if (empty($per_page) || $per_page < 1) { + $per_page = $screen->get_option('per_page', 'default'); + } - $per_page = 24; $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); @@ -346,7 +355,8 @@ function prepare_items(){ } } -class SLM_Plugin{ +class SLM_Plugin +{ // class instance static $instance; @@ -355,12 +365,14 @@ class SLM_Plugin{ public $licenses_obj; // class constructor - public function __construct(){ + public function __construct() + { add_filter('set-screen-option', [__CLASS__, 'set_screen'], 10, 3); add_action('admin_menu', [$this, 'slm_add_admin_menu']); } - public static function set_screen($status, $option, $value){ + public static function set_screen($status, $option, $value) + { return $value; } @@ -375,37 +387,41 @@ public function slm_add_admin_menu() add_submenu_page(SLM_MAIN_MENU_SLUG, "Tools", "Tools", SLM_MANAGEMENT_PERMISSION, 'slm_admin_tools', "slm_admin_tools_menu"); add_submenu_page(SLM_MAIN_MENU_SLUG, "Settings", "Settings", SLM_MANAGEMENT_PERMISSION, 'slm_settings', "slm_settings_menu"); add_submenu_page(SLM_MAIN_MENU_SLUG, "Help", "Help", SLM_MANAGEMENT_PERMISSION, 'slm_help', "slm_integration_help_menu"); - add_action("load-$hook", [$this, 'screen_option']); } + /** * Screen options */ - public function screen_option(){ + public function screen_option() + { $option = 'per_page'; $args = [ 'label' => 'Pagination', - 'default' => 24, + 'default' => 16, 'option' => 'licenses_per_page' ]; - //add_screen_option($option, $args); + add_screen_option($option, $args); $this->licenses_obj = new SLM_List_Licenses(); } /** Singleton instance */ - public static function get_instance(){ + public static function get_instance() + { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } + + } add_action('plugins_loaded', function () { SLM_Plugin::get_instance(); -}); \ No newline at end of file +}); diff --git a/admin/slm-manage-licenses.php b/admin/slm-manage-licenses.php index 469f5b5..ea28afa 100755 --- a/admin/slm-manage-licenses.php +++ b/admin/slm-manage-licenses.php @@ -6,24 +6,18 @@ die; } - -function get_user_info() -{ +function get_user_info(){ if (!current_user_can('manage_licenses')) { $response = array( 'success' => false, - 'message' => __('You do not have permission to manage this license.', 'edd_sl'), + 'message' => _e('You do not have permission to manage this license.', 'softwarelicensemanager'), ); - echo json_encode($response); die(); } } - -function slm_manage_licenses_menu() -{ - +function slm_manage_licenses_menu(){ //include_once('slm-list-licenses-class.php'); $license_list = new SLM_List_Licenses(); @@ -33,16 +27,12 @@ function slm_manage_licenses_menu() } } ?> - -
    -
    -
    -

    Overview - Manage licenses

    +


    - +
    diff --git a/admin/slm-subscribers.php b/admin/slm-subscribers.php index 28bed43..1441766 100644 --- a/admin/slm-subscribers.php +++ b/admin/slm-subscribers.php @@ -167,9 +167,9 @@ function slm_subscribers_menu() if (isset($_REQUEST['slm_subscriber_edit']) && $_REQUEST['slm_subscriber_edit'] == 'true') : ?>
    -

    Overview - Manage Subscriber

    +


    - +
    @@ -178,14 +178,14 @@ function slm_subscribers_menu()
    - - - + + +
    IDLicense keyStatus
    @@ -197,7 +197,7 @@ function slm_subscribers_menu()
    -

    Overview - All Subscribers

    +



    diff --git a/includes/class-slm-installer.php b/includes/class-slm-installer.php index b3e0042..6f1ee41 100755 --- a/includes/class-slm-installer.php +++ b/includes/class-slm-installer.php @@ -15,6 +15,7 @@ $lic_domain_table = SLM_TBL_LIC_DOMAIN; $lic_devices_table = SLM_TBL_LIC_DEVICES; $lic_log_tbl = SLM_TBL_LIC_LOG; +$lic_emails_table = SLM_TBL_EMAILS; $charset_collate = ''; if (!empty($wpdb->charset)){ @@ -55,6 +56,8 @@ )" . $charset_collate . ";"; dbDelta($lk_tbl_sql); + + $ld_tbl_sql = "CREATE TABLE " .$lic_domain_table. " ( id INT NOT NULL AUTO_INCREMENT , lic_key_id INT NOT NULL , @@ -66,6 +69,20 @@ )" . $charset_collate . ";"; dbDelta($ld_tbl_sql); + +$slm_emails_tbl = "CREATE TABLE " . $lic_emails_table . " ( + id INT NOT NULL AUTO_INCREMENT , + lic_key varchar(255) NOT NULL , + sent_to varchar(255) NOT NULL , + status varchar(255) NOT NULL , + sent text NOT NULL , + date_sent date NOT NULL DEFAULT '0000-00-00', + disable_notifications text NOT NULL , + PRIMARY KEY ( id ) + )" . $charset_collate . ";"; +dbDelta($slm_emails_tbl); + + $log_tbl_sql = "CREATE TABLE " . $lic_log_tbl . " ( id INT NOT NULL AUTO_INCREMENT , license_key varchar(255) NOT NULL , @@ -98,8 +115,8 @@ 'slm_woo' => '', 'slm_wpestores' => '', 'slm_woo_downloads' => '', - 'slm_dl_manager' => '' -); + 'slm_dl_manager' => '', + 'expiration_reminder_text' => 'Your account has reverted to Basic with limited functionality. Renew today to keep using it on all of your devices and enjoy the valuable features. It’s a smart investment'); update_option('slm_plugin_options', $options); update_option("slm_db_version", SLM_DB_VERSION); \ No newline at end of file diff --git a/includes/mails/expired.php b/includes/mails/expired.php new file mode 100644 index 0000000..5a2fec3 --- /dev/null +++ b/includes/mails/expired.php @@ -0,0 +1,251 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +'; \ No newline at end of file diff --git a/includes/slm-meta-boxes.php b/includes/slm-meta-boxes.php index 0140081..89c20cf 100644 --- a/includes/slm-meta-boxes.php +++ b/includes/slm-meta-boxes.php @@ -8,6 +8,10 @@ add_filter('woocommerce_product_data_tabs', 'wc_slm_add_tab'); add_action('woocommerce_process_product_meta_simple', 'wc_slm_save_data'); add_action('woocommerce_product_data_panels', 'wc_slm_data_panel'); +add_filter('product_type_options', 'add_wc_slm_data_tab_enabled_product_option'); +add_action('init', 'slm_register_product_type'); +add_filter('product_type_selector', 'slm_add_product_type'); +add_action('admin_footer', 'slm_license_admin_custom_js'); /** * Add 'License' product option */ @@ -15,14 +19,13 @@ function add_wc_slm_data_tab_enabled_product_option($product_type_options) { $product_type_options['wc_slm_data_tab_enabled'] = array( 'id' => '_wc_slm_data_tab_enabled', - 'wrapper_class' => 'show_if_simple show_if_variable', - 'label' => __('License Manager', 'woocommerce'), + 'wrapper_class' => 'show_if_slm_license', + 'label' => __('License Manager', 'softwarelicensemanager'), 'default' => 'no', - 'description' => __('Enables the license creation api.', 'woocommerce') + 'description' => __('Enables the license creation api.', 'softwarelicensemanager') ); return $product_type_options; } -add_filter('product_type_options', 'add_wc_slm_data_tab_enabled_product_option'); /** CSS To Add Custom tab Icon */ @@ -37,23 +40,23 @@ function wcpp_custom_style() +' . __('Settings') . ''; + $links[] = '' . __('GitHub') . ''; + return $links; +} + //Includes require_once( SLM_LIB .'slm-debug-logger.php'); require_once( SLM_LIB .'slm-error-codes.php'); - require_once( SLM_LIB .'slm-init-time-tasks.php'); require_once( SLM_LIB .'slm-api-utility.php'); require_once( SLM_LIB .'slm-api-listener.php'); @@ -124,6 +140,30 @@ function slm_plugins_loaded_handler() { } } +class slm_tabbed_plugin +{ + // singleton class variable + static private $classobj = NULL; + + // singleton method + public static function get_object() + { + if (NULL === self::$classobj) { + self::$classobj = new self; + } + return self::$classobj; + } + + private function __construct() + { } +} + +// initialize plugin +if (function_exists('add_action') && function_exists('register_activation_hook')) { + add_action('plugins_loaded', array('slm_tabbed_plugin', 'get_object')); +} + + //TODO - need to move this to an ajax handler file function slm_del_reg_dom() { global $wpdb; diff --git a/includes/slm-scripts.php b/includes/slm-scripts.php index ab77062..f9b24b0 100644 --- a/includes/slm-scripts.php +++ b/includes/slm-scripts.php @@ -2,7 +2,7 @@ // add admin styles and scipts function slm_admin_assets() { - wp_enqueue_style('slm', SLM_ASSETS_URL .'css/slm.css'); + wp_enqueue_style('softwarelicensemanager', SLM_ASSETS_URL .'css/slm.css'); wp_enqueue_script('slm_validate', 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js', array('jquery'), '1.19.0', true); wp_enqueue_script('slm_validate_js', SLM_ASSETS_URL .'js/slm.js', array('jquery'), '1.0.1', true ); } @@ -21,7 +21,7 @@ function slm_frontend_assets() { wp_enqueue_script( 'bootstrapcdn-slm-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js', array('jquery'), '4.1.3', true ); } // custom css - wp_enqueue_style('slm', SLM_ASSETS_URL .'css/slm-front-end.css'); + wp_enqueue_style('softwarelicensemanager', SLM_ASSETS_URL .'css/slm-front-end.css'); } add_action('wp_enqueue_scripts', 'slm_frontend_assets'); @@ -41,3 +41,4 @@ function slm_get_page(){ } } + diff --git a/includes/slm-utility.php b/includes/slm-utility.php index bf52df0..33d5b3f 100755 --- a/includes/slm-utility.php +++ b/includes/slm-utility.php @@ -5,8 +5,8 @@ */ // Helper Class -class SLM_Helper_Class -{ +class SLM_Helper_Class { + public static function slm_get_option($option) { $option_name = ''; @@ -29,40 +29,75 @@ static function write_log($log) class SLM_Utility { - static function check_for_expired_lic($lic_key = '') - { + static function check_for_expired_lic($lic_key=''){ + global $wpdb, $first_name, $body, $date_expiry, $license_key, $expiration_reminder_text; + + $headers = array('Content-Type: text/html; charset=UTF-8'); + $response = ''; + $sql_query = $wpdb->get_results("SELECT * FROM " . SLM_TBL_LICENSE_KEYS . " WHERE date_expiry < NOW() ORDER BY date_expiry ASC;", ARRAY_A); + $subject = get_bloginfo('name') . ' - Your license has expired'; + $expiration_reminder_text = SLM_Helper_Class::slm_get_option( 'expiration_reminder_text'); + + //SLM_Helper_Class::write_log('Found: ' . $expiration_reminder_text); - // $lic_key = ''; + if (count( $sql_query) > 0) { - // log - SLM_Helper_Class::write_log('-------------------------------------------'); - SLM_Helper_Class::write_log('check_for_expired_lic: is running class'); + foreach ($sql_query as $expired_licenses) { - require_once(ABSPATH . '/wp-load.php'); + // TODO move to template + include SLM_LIB . 'mails/expired.php'; - $to = 'mvelis90@gmail.com'; - $admin_email = get_option('admin_email'); - $subject = 'The subject'; - $body = 'The email body content'; - $headers = array('Content-Type: text/html; charset=UTF-8'); - $response = ''; + $license_key = $expired_licenses['license_key']; + $first_name = $expired_licenses['first_name']; + $last_name = $expired_licenses['last_name']; + $email = $expired_licenses['email']; + $date_expiry = $expired_licenses['date_expiry']; - $sent_email = wp_mail($to, $subject, $body, $headers); + //SLM_Helper_Class::write_log('Found: ' . $license_key); + self::slm_check_sent_emails($license_key, $email, $subject, $body, $headers); + self::create_log($license_key, 'sent expiration email notification'); - // sent - if ($sent_email) { - $response = 'Reminder message was sent.'; - SLM_Helper_Class::write_log($response); + //SLM_Helper_Class::write_log('DB record logged'); + $response = 'Reminder message was sent to: ' . $license_key; + //SLM_Helper_Class::write_log($response); + } } - // mail failed else { - $response = 'Reminder message was not sent.'; - SLM_Helper_Class::write_log('The message was not sent!'); + SLM_Helper_Class::write_log('array is empty'); + $response = 'array is empty'; } - return $response; } + static function slm_check_sent_emails($license_key, $email, $subject, $body, $headers) + { + global $wpdb; + $query = 'SELECT * FROM ' . SLM_TBL_EMAILS . ' WHERE lic_key = "' . $license_key . '";'; + $lic_log_results = $wpdb->get_results($query, ARRAY_A); + + if (count($lic_log_results) > 0) { + foreach ($lic_log_results as $license) { + if ($license["lic_key"] != $license_key) { + // TODO: use mail class from include + wp_mail($email, $subject, $body, $headers); + self::create_email_log($license_key, $email, 'success', 'yes', date("Y/m/d")); + return '200'; //reminder was never sent before, first time (record does not exist) + } + else { + //reminder was sent before + return '400'; + } + } + } + else { + // array or results are empty (lic key was not found) + // TODO: use mail class from include + wp_mail($email, $subject, $body, $headers); + self::create_email_log($license_key, $email, 'success', 'yes', date("Y/m/d")); + return '300'; + } + } + static function do_auto_key_expiry() { global $wpdb; $current_date = (date ("Y-m-d")); @@ -129,18 +164,14 @@ static function delete_license_key_by_row_id($key_row_id) { } - static function count_licenses($status) - { + static function count_licenses($status){ global $wpdb; $license_table = SLM_TBL_LICENSE_KEYS; - $get_lic_status = $wpdb->get_var("SELECT COUNT(*) FROM $license_table WHERE lic_status = '" . $status . "'"); - return $get_lic_status; } - static function get_total_licenses() - { + static function get_total_licenses(){ global $wpdb; $license_table = SLM_TBL_LICENSE_KEYS; $license_count = $wpdb->get_var("SELECT COUNT(*) FROM " . $license_table . ""); @@ -150,7 +181,6 @@ static function get_total_licenses() static function block_license_key_by_row_id($key_row_id){ global $wpdb; $license_table = SLM_TBL_LICENSE_KEYS; - //Now, delete the key from the licenses table. $wpdb->update( $license_table, array('lic_status' => 'blocked'), array('id' => $key_row_id)); @@ -219,6 +249,26 @@ static function create_log($license_key, $action){ $wpdb->insert( $slm_log_table, $log_data ); } + + static function create_email_log($lic_key, $sent_to, $status, $sent, $date_sent) + { + global $wpdb; + $slm_email_table = SLM_TBL_EMAILS; + + $log_data = array( + 'lic_key' => $lic_key, + 'sent_to' => $sent_to, + 'status' => $status, + 'sent' => $sent, + 'date_sent' => $date_sent + ); + + $wpdb->insert($slm_email_table, $log_data); + SLM_Helper_Class::write_log('email log created for '. $lic_key); + } + + + static function slm_wp_dashboards_stats($amount){ global $wpdb; $slm_log_table = SLM_TBL_LICENSE_KEYS; diff --git a/includes/slm-wizard.php b/includes/slm-wizard.php new file mode 100644 index 0000000..02d344b --- /dev/null +++ b/includes/slm-wizard.php @@ -0,0 +1,2 @@ + + */ +class WP_Mail +{ + + private $to = array(); + private $cc = array(); + private $bcc = array(); + private $headers = array(); + private $attachments = array(); + private $sendAsHTML = TRUE; + private $subject = ''; + private $from = ''; + + private $headerTemplate = FALSE; + private $headerVariables = array(); + private $template = FALSE; + private $variables = array(); + private $afterTemplate = FALSE; + private $footerVariables = array(); + + + public static function init() + { + return new Self; + } + + + /** + * Set recipients + * @param Array|String $to + * @return Object $this + */ + public function to($to) + { + if (is_array($to)) { + $this->to = $to; + } else { + $this->to = array($to); + } + return $this; + } + + + /** + * Get recipients + * @return Array $to + */ + public function getTo() + { + return $this->to; + } + + + /** + * Set Cc recipients + * @param String|Array $cc + * @return Object $this + */ + public function cc($cc) + { + if (is_array($cc)) { + $this->cc = $cc; + } else { + $this->cc = array($cc); + } + return $this; + } + + + /** + * Get Cc recipients + * @return Array $cc + */ + public function getCc() + { + return $this->cc; + } + + + /** + * Set Email Bcc recipients + * @param String|Array $bcc + * @return Object $this + */ + public function bcc($bcc) + { + if (is_array($bcc)) { + $this->bcc = $bcc; + } else { + $this->bcc = array($bcc); + } + + return $this; + } + + + /** + * Set email Bcc recipients + * @return Array $bcc + */ + public function getBcc() + { + return $this->bcc; + } + + + /** + * Set email Subject + * @param Srting $subject + * @return Object $this + */ + public function subject($subject) + { + $this->subject = $subject; + return $this; + } + + + /** + * Retruns email subject + * @return Array + */ + public function getSubject() + { + return $this->subject; + } + + + /** + * Set From header + * @param String + * @return Object $this + */ + public function from($from) + { + $this->from = $from; + return $this; + } + + /** + * Set the email's headers + * @param String|Array $headers [description] + * @return Object $this + */ + public function headers($headers) + { + if (is_array($headers)) { + $this->headers = $headers; + } else { + $this->headers = array($headers); + } + + return $this; + } + + + /** + * Retruns headers + * @return Array + */ + public function getHeaders() + { + return $this->headers; + } + + + /** + * Returns email content type + * @return String + */ + public function HTMLFilter() + { + return 'text/html'; + } + + + /** + * Set email content type + * @param Bool $html + * @return Object $this + */ + public function sendAsHTML($html) + { + $this->sendAsHTML = $html; + return $this; + } + + + /** + * Attach a file or array of files. + * Filepaths must be absolute. + * @param String|Array $path + * @throws Exception + * @return Object $this + */ + public function attach($path) + { + if (is_array($path)) { + $this->attachments = array(); + foreach ($path as $path_) { + if (!file_exists($path_)) { + throw new Exception("Attachment not found at $path"); + } else { + $this->attachments[] = $path_; + } + } + } else { + if (!file_exists($path)) { + throw new Exception("Attachment not found at $path"); + } + $this->attachments = array($path); + } + + return $this; + } + + + /** + * Set the before-template file + * @param String $template Path to HTML template + * @param Array $variables + * @throws Exception + * @return Object $this + */ + public function templateHeader($template, $variables = NULL) + { + if (!file_exists($template)) { + throw new Exception('Template file not found'); + } + + if (is_array($variables)) { + $this->headerVariables = $variables; + } + + $this->headerTemplate = $template; + return $this; + } + + + /** + * Set the template file + * @param String $template Path to HTML template + * @param Array $variables + * @throws Exception + * @return Object $this + */ + public function template($template, $variables = NULL) + { + if (!file_exists($template)) { + throw new Exception('File not found'); + } + + if (is_array($variables)) { + $this->variables = $variables; + } + + $this->template = $template; + return $this; + } + + + /** + * Set the after-template file + * @param String $template Path to HTML template + * @param Array $variables + * @throws Exception + * @return Object $this + */ + public function templateFooter($template, $variables = NULL) + { + if (!file_exists($template)) { + throw new Exception('Template file not found'); + } + + if (is_array($variables)) { + $this->footerVariables = $variables; + } + + $this->afterTemplate = $template; + return $this; + } + + + /** + * Renders the template + * @return String + */ + public function render() + { + return $this->renderPart('before') . + $this->renderPart('main') . + $this->renderPart('after'); + } + + + /** + * Render a specific part of the email + * @author Anthony Budd + * @param String $part before, after, main + * @return String + */ + public function renderPart($part = 'main') + { + switch ($part) { + case 'before': + $templateFile = $this->headerTemplate; + $variables = $this->headerVariables; + break; + + case 'after': + $templateFile = $this->afterTemplate; + $variables = $this->footerVariables; + break; + + case 'main': + default: + $templateFile = $this->template; + $variables = $this->variables; + break; + } + + if ($templateFile === FALSE) { + return ''; + } + + + $extension = strtolower(pathinfo($templateFile, PATHINFO_EXTENSION)); + if ($extension === 'php') { + + ob_start(); + ob_clean(); + + foreach ($variables as $key => $value) { + $$key = $value; + } + + include $templateFile; + + $html = ob_get_clean(); + + return $html; + } elseif ($extension === 'html') { + + $template = file_get_contents($templateFile); + + if (!is_array($variables) || empty($variables)) { + return $template; + } + + return $this->parseAsMustache($template, $variables); + } else { + throw new Exception("Unknown extension {$extension} in path '{$templateFile}'"); + } + } + + public function buildSubject() + { + return $this->parseAsMustache( + $this->subject, + array_merge($this->headerVariables, $this->variables, $this->footerVariables) + ); + } + + public function parseAsMustache($string, $variables = array()) + { + + preg_match_all('/\{\{\s*.+?\s*\}\}/', $string, $matches); + + foreach ($matches[0] as $match) { + $var = str_replace('{', '', str_replace('}', '', preg_replace('/\s+/', '', $match))); + + if (isset($variables[$var]) && !is_array($variables[$var])) { + $string = str_replace($match, $variables[$var], $string); + } + } + + return $string; + } + + + /** + * Builds Email Headers + * @return String email headers + */ + public function buildHeaders() + { + $headers = ''; + + $headers .= implode("\r\n", $this->headers) . "\r\n"; + + foreach ($this->bcc as $bcc) { + $headers .= sprintf("Bcc: %s \r\n", $bcc); + } + + foreach ($this->cc as $cc) { + $headers .= sprintf("Cc: %s \r\n", $cc); + } + + if (!empty($this->from)) { + $headers .= sprintf("From: %s \r\n", $this->from); + } + + return $headers; + } + + + /** + * Sends a rendered email using + * WordPress's wp_mail() function + * @return Bool + */ + public function send() + { + if (count($this->to) === 0) { + throw new Exception('You must set at least 1 recipient'); + } + + if (empty($this->template)) { + throw new Exception('You must set a template'); + } + + if ($this->sendAsHTML) { + add_filter('wp_mail_content_type', array($this, 'HTMLFilter')); + } + + return wp_mail($this->to, $this->buildSubject(), $this->render(), $this->buildHeaders(), $this->attachments); + } +} diff --git a/languages/softwarelicensemanager-es_ES.mo b/languages/softwarelicensemanager-es_ES.mo new file mode 100644 index 0000000000000000000000000000000000000000..126b5bd569b36628d552a787b0c90c2353b9168e GIT binary patch literal 11210 zcmb`NTZ~;-dB+!!3z(9U5CRkm%ZA`_I_G%C>ID(hf*-09sd<2?Qb~AeMrx}{2&qypYD-$R6_xS;RaI4LB}#w) zwbtI}%w(LF(xdG8@5{P;>$`uS^YSg%{f6NebG?V_{x=x&8St?i_`~n1HyZOV;HSVj zuy~U(Zvnpv-U$9F$Q1Ku;5)&;0DltvK6nfGL-1zsmR-iY75o5r4!jH0xX*%T!7qWD z|2^wg#2zCQpDfN$l{KLs8Ie;Rx|JpTeHzI*}P4}KYBiupEZ!M_8Y3Lw1q@q8mV z4ekXIky!-yf)_#Y<(I*$;8#G+I|31+e-4yhMPLd3BKQsPUqR9RdvEjn`~#4qnm+=y z?w^B@V159idgdmSLUgl>8nC9|HdvyaL|zc7OiQfQvkT6BJ!H!z7*i zodGR)9nVwXU0??k-F;B|egf3^r$O=iSHUj$Met=5=ug16z0R25eU~vq-oFU5*~;vD zw?Eg1!RvWG1$Mv%P<;LrsPlgw)PBDOvV{44@M-YdAV)EaFz=&a3W|@L{EK#1a0iFfVfuiH9;77pQ-s|l)2k+=)1c_S5T1vi>|+gl2HXHO z{#NVh+5?K7dqC~K2=br#B!5r=^A%8f_jOQm{1zzrybMZTZr|!{6Ztzi1a{4rQ1bhaRK79w&_+xCe0M8NlLGahX zuYoUunm6PnA~qGs(ah(-Ujn}l{tb9HMj-lcfjIH!eW3U=3*H5u1RXt~qc8u+e#%mF_K{wDYxa0aY6wD|Qq;0@qge#Z0nR`88HzZbk7+zV>o4(RLy zypHEjfbv&Qfui?UK%M&w;OjvBc5#XK%}?~nb|2=t5MJI0{#>}fFW~Dz$@W8BXTm$l zNauYtJf8xWxI~lABOU*FuAk+S{^%!p&$&BKqv(b$E)E?H?{&5Zxg=}Zr_P|?tOqCa z+qjp`>%5)tUb2Ig&Ub}Z4o>s;BG&_4$J`swPu)r`h}r#QvyX6z$C8h1RzK9xpej!G z5qOB}F|LDL@)LWw?&Z=?{z1QoJUBaebGVl+O^18w$9b*=F6okfsIBvl_kjDkPH@T2 z?&Q+%FxTT;$GH%x`$hs?vTm7;M-wscf~H*s_YMy0rPSjqD)pCs~=;OUZ_O zHO-E+iyKv@!x7*5t5LR+l-r1MOKauKZsc{Louj1)8lle-!&c_7U9NSeeqD0J^okBX zZSxUCmrUwI_tAVfOmsIIMAdR$4DC{#4l2v7y^t62e36tTD~Y_c+OUIs#hSx$Y)>ca z=I~%(4#Pd`8DdWcK0TUjl;&t%6iHUu^GQ*rd1j6!OZCc1nyrY%6npQ%(6@HsQc7RA%uqSiJlIEpU(Tfj#%rhI_d*L@)*hiJz*JzY>8Bsy6)ZyIOlTye69pI@M z-Kv(>8^R{e=kv}PjbN(Z*|;t0lqiXSfurgac~B0DORLDH|VlVO6L_EDkI)}_=}+{Kjp zmzMI&NokI=?uMPU!!&~r22()F);yeKNfEJ6qwFVAdwV%;=8l=UWj|j|D3(>&ysltk zE0*;lttxqz+}YbQTrKU?r6d{2X~o_oVq0gtFU18LN$N#jV=Copp3A&o-W zX0A$x_H;B%de)pA8!G0LET@+zUrm+!Y(K9DvCZ|BQXOk>Oq`P)WwvU<3b6yyE3=|a1v^L*~S?JK>YL;;zM^GZE?e`HtD&O>|ky2^Xz47RqGChM3fe6$PoQrRz3RHK~y-RXPuF6Rebo96zDgx16!2gH*t2iIlDzmEYC_Eyge&Q%4+Qr!IzybNdp$pqy8#@ zIaQVz>GUWt&K?b3{aWA8qm0YJ&)KudlXX&7C4-%p%Cm%9H2YYSNXXlt3f^8y5j7Gr z3;A-jE`QPN+*oP*A+RQdxS^y`=7ZYB9IfTtEF@)08`J@4@et*@;`2f`)vlFTU!R1%hv=>#9yhTFn3y=y;;!&LzE znVHWc*+rp(fX1c;P9`7z7<+P}v9QCwcDcxhA(cyty&MJ?NuoGZyos`EH%XLp*nun; zTb&EAc}9Zgq~pw3u#`hR^^BQJzVcsSSRZbq-XoW#3+GMav ztH#>rM^C13XwYboAlHRPjX5`_GqA_fl@t%C98yjI}&kI0-c+qxiEH;wco zlHkY^DOydzG?JJAjcO#9(^5eg*24p>>BNB>Ns8sDk3(#h$sHpjRUV_HpDu5(=*Wd+ zr^xa-6I?C3*c6H!M!5Qg01Yi(i#5E?QoI8Tw&8i}3U2Gz>x#?ah;zfVlys#JKC$)m zhMgU?1?dZkl``qos3a{QK^aEHB{o(L==jSDVqKZWXyyr}qR@)swFD>!4;s)luI5P$ z`Es9COekB7QdqNERim=Ee?Q_`t(Us&uz%=6&RVj+3?8f#$m@8Li~a4a_4V~`GDq!Q zfrH99xji(M+1-ci?7oA$P^%}%B0F<&C)iI99o*Uf?wUWd*lD6b=NN9NXAjKG-q)GA zyEA*Aot^2;+|`-6b7qEtowFq664(yoW_t&iqj4uG9Bb13&SDY`dv@2Uxl_l-bj)^V zb`g)sGpmjgv!1Pz%hi7Bz%)B3-&PRM4xL+ksB`aloZP~4Qgn`I{alRf*?X7LYS%|P zKHbGkdv-o|R&by@+nwc$f9xE=;g6zfwP(BC@!N+6(Ms95yh4)9<~`f#pvoO*+*wr~ zs`&`kQuZ%KRaG#dy-miqVS+xbR>MIUQ z95YT_cv^E~oKNxHlxVy+S%f+$WFVpsI+sMlB$SQf4i+P;WV-b&Od`vKzdtU|hQ;3?B zlW{J{z3f+YG%)iKk|bv-ScyK%C?}&x*EsqHsRZS0%KMYbf)JkDgvzrWMDwN$+QIG| zV)H6FpA!eN=|{ziyPxRWOm=FT5fN2uw6^)IKf{()La6Y^knBge6|Y{6Mupm|CC?Kr z%G~~i4XN#9E^v6INFc4I1?IGaC`oh7>0Cp%WM9>;k0aK$nFURqcI7fx+U4}S$)8UI zTOkV=pp0V~#>t4d;0|KOgW%b<1l0@@Uk}gEIn`1B&`ESc*rc_T_)1-_^yyMYt_9?7 zNB~H7vADHVLKa1+Wf?u;DCVF}uO?OuO-@+3ZAnbCa^~l<1l@|9NlmcYY*Z(_CYX>O z$We@~eo8q*h8dB;(IeV?eogHR+=%9SlC?=Q?r`Kl-A@Zt!3 z#s_=Ni5zus{ifI~q`{k$uHn<7X{kzyYYMU)tEbZ$S5l`=YjBHNowC*W1ti?iY^O-N zIAyjHu^0*!e1T|;q-)G`tRaj%>&i!+-JOy;gD^6T)ZPmnD#sV~4u(tQj52nLlg;P) z^&qD{r$6k2n_kO_SSNh!Y zg1BO7@8p-#ET$tzQsasOC8N5f0k$+B$r3kTAYRaZR;rB=xw%1Iv)rz2UPT%?_Ixt< zTidD`mMUkB^xHTn`88|rK(>ntljP#iWi_#w>FS)Vq|X!4pCg`V3casJsdwTjNW%^U?2gf=W|j@X`+2GZtLx?_%jEuN)i*VZA8 zJDB)MgGPJJ zOIN+&J9G0*I;@_U-nyq9GP>R78j7ygU6b0%i3fk@&0)tdj>qYzl#=)xsDo+d2#3NM zd(-o6rjXcS8*)kwrzb?Z<6t^7IcugBS-JCITY|u(Rfq1Mk0}Hc{;5OJ{xt%dP z4NG6c!)d3cyrO3~!1+k_yj8-~+&2q3N}J){2oQ4{U!7^FV>lIBgX5%%CZS@1dW0+% z%xJo42eO@dgecYKb1p&09#u!sLToY!3ThV#S#qLP=v@$myKhYL(OQlwWCG@4j-ix7qzTZ@bR6W9HOc*0h~n6e@+Tcu z&ZLO1%A^>eOzci_fc5cjP$Z?P@&_duKJZP_Q2r?UUsHu3u7o}%E=rwvB=Z@d+3GC5 zbhYg*CcAmUb0s_!9ipXv-(Nj83!2 zjCImU0iD4uIL(1X9|d8%ANbF*t>#~ku zvI-+gH{!2cnS1&_dI7I)F2^3XErSx09fzb)DlyT*G;M(q8l98n%GmN?sG4lStE}OD zpt@lv2lbsy?=#9Bsu%6*%hxhlA#NL|el~LTkenyYOqG_cb5J5oI}_3Ao9k%0N;>F_ zq!s#^SNQiGC#z8WPKR&@q691x2VZYy9hfR?r4f2ha}tz{AtW*auBwTX$eO54f&|LK38 hCpjbf(fgDHIpjF#nrd4n+iUwEAy9jB;k<1T``;B{gu4I$ literal 0 HcmV?d00001 diff --git a/languages/softwarelicensemanager-es_ES.po b/languages/softwarelicensemanager-es_ES.po new file mode 100644 index 0000000..df749a3 --- /dev/null +++ b/languages/softwarelicensemanager-es_ES.po @@ -0,0 +1,495 @@ +msgid "" +msgstr "" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Project-Id-Version: Software License Manager\n" +"POT-Creation-Date: 2019-06-19 10:05-0400\n" +"PO-Revision-Date: 2019-06-19 11:29-0400\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.1.1\n" +"X-Poedit-Basepath: ..\n" +"X-Poedit-Flags-xgettext: --add-comments=translators:\n" +"X-Poedit-WPHeader: software-license-manager.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" +"Last-Translator: \n" +"Language: es\n" +"X-Poedit-SearchPath-0: .\n" +"X-Poedit-SearchPathExcluded-0: *.js\n" + +#: admin/includes/cronjobs/slm-tasks.php:13 +msgid "Every 1 minute" +msgstr "Cada 1 minuto" + +#: admin/includes/wpestores/slm-wpestores.php:70 +msgid "Item Name: " +msgstr "Nombre del artículo" + +#: admin/includes/wpestores/slm-wpestores.php:70 +msgid "License Key: " +msgstr "Clave de licencia" + +#: admin/slm-add-licenses.php:141 +msgid "Record could not be inserted into the database!" +msgstr "¡No se pudo insertar un registro en la base de datos!" + +#: admin/slm-add-licenses.php:149 +msgid "Update of the license key table failed!" +msgstr "¡Error al actualizar la tabla de claves de licencia!" + +#. Plugin Name of the plugin/theme +#: admin/slm-add-licenses.php:185 +msgid "Software License Manager" +msgstr "Administrador de licencias de software" + +#: admin/slm-add-licenses.php:188 +msgid "You can add a new license or edit an existing one from this interface." +msgstr "" +"Puede agregar una nueva licencia o editar una existente desde esta interfaz." + +#: admin/slm-add-licenses.php:234 +msgid "License key and status" +msgstr "Clave de licencia y estado" + +#: admin/slm-add-licenses.php:238 +msgid "User information" +msgstr "Información de usuario" + +#: admin/slm-add-licenses.php:244 +msgid "Devices & Domains" +msgstr "Dispositivos y Dominios" + +#: admin/slm-add-licenses.php:249 +msgid "Transaction" +msgstr "Transacción" + +#: admin/slm-add-licenses.php:253 +msgid "Product" +msgstr "Producto" + +#: admin/slm-add-licenses.php:259 +msgid "Activity log " +msgstr "Registro de actividad" + +#: admin/slm-add-licenses.php:266 +msgid "Export " +msgstr "exportar" + +#: admin/slm-admin-functions.php:41 +msgid "Send Deactivation Message for a License" +msgstr "Enviar mensaje de desactivación para una licencia" + +#: admin/slm-admin-functions.php:43 +msgid "Enter the URL where the license deactivation message will be sent to" +msgstr "" +"Introduzca la URL a la que se enviará el mensaje de desactivación de la " +"licencia" + +#: admin/slm-lic-settings.php:76 +msgid "General settings" +msgstr "Los ajustes generales" + +#: admin/slm-lic-settings.php:80 +msgid "Secret Key for License Creation" +msgstr "Clave secreta para la creación de licencias" + +#: admin/slm-lic-settings.php:82 +msgid "" +"This secret key will be used to authenticate any license creation request. " +"You can change it with something random." +msgstr "" +"Esta clave secreta se utilizará para autenticar cualquier solicitud de " +"creación de licencia. Puedes cambiarlo con algo aleatorio." + +#: admin/slm-lic-settings.php:86 +msgid "Secret Key for License Verification Requests" +msgstr "Clave secreta para las solicitudes de verificación de licencias" + +#: admin/slm-lic-settings.php:88 +msgid "" +"This secret key will be used to authenticate any license verification " +"request from customer's site. Important! Do not change this value once your " +"customers start to use your product(s)!" +msgstr "" +"Esta clave secreta se usará para autenticar cualquier solicitud de " +"verificación de licencia desde el sitio del cliente. ¡Importante! ¡No cambie " +"este valor una vez que sus clientes comiencen a usar su(s) producto(s)!" + +#: admin/slm-lic-settings.php:92 +msgid "License Key Prefix" +msgstr "Prefijo de clave de licencia" + +#: admin/slm-lic-settings.php:94 +msgid "" +"You can optionaly specify a prefix for the license keys. This prefix will be " +"added to the uniquely generated license keys." +msgstr "" +"Opcionalmente, puede especificar un prefijo para las claves de licencia. " +"Este prefijo se agregará a las claves de licencia generadas de forma única." + +#: admin/slm-lic-settings.php:98 +msgid "Maximum Allowed Domains" +msgstr "Máximo de dominios permitidos" + +#: admin/slm-lic-settings.php:100 +msgid "" +"Maximum number of domains/installs which each license is valid for (default " +"value)." +msgstr "" +"Número máximo de dominios/instalaciones para los que cada licencia es válida " +"(valor predeterminado)." + +#: admin/slm-lic-settings.php:104 +msgid "Maximum Allowed Devices" +msgstr "Máximo de dispositivos permitidos" + +#: admin/slm-lic-settings.php:106 +msgid "" +"Maximum number of devices which each license is valid for (default value)." +msgstr "" +"Número máximo de dispositivos para los que cada licencia es válida (valor " +"predeterminado)." + +#: admin/slm-lic-settings.php:110 +msgid "Auto Expire License Keys" +msgstr "Claves de licencia de expiración automática" + +#: admin/slm-lic-settings.php:112 +msgid "Enable auto expiration " +msgstr "Habilitar la expiración automática" + +#: admin/slm-lic-settings.php:113 +msgid "" +" When enabled, it will automatically set the status of a license key to " +"\"Expired\" when the expiry date value of the k ey is reached. It doesn't " +"remotely deactivate a key. It simply changes the status of the key in your " +"database to expired." +msgstr "" +"Cuando está habilitado, establecerá automáticamente el estado de una clave " +"de licencia en \"Expirado\" cuando se alcance el valor de fecha de caducidad " +"del k ey. No desactiva de forma remota una clave. Simplemente cambia el " +"estado de la clave en la base de datos a caducado." + +#: admin/slm-lic-settings.php:121 +msgid "Integrations" +msgstr "Integraciones" + +#: admin/slm-lic-settings.php:125 +msgid "Woocommerce Support" +msgstr "Soporte técnico de Woocommerce" + +#: admin/slm-lic-settings.php:128 +msgid "" +"A fully customizable, open source eCommerce platform built for WordPress." +msgstr "" +"Una plataforma de comercio electrónico totalmente personalizable y de código " +"abierto creada para WordPress." + +#: admin/slm-lic-settings.php:132 +msgid "" +"Disable woocommerce download page. Proccess downloads though license order " +"info page." +msgstr "" +"Deshabilite la página de descarga de woocommerce. Proccess descarga a través " +"de la página de información del pedido de licencia." + +#: admin/slm-lic-settings.php:135 +msgid "Download Manager Support" +msgstr "Descargar soporte de Manager" + +#: admin/slm-lic-settings.php:138 +msgid "" +"Download Manager Plugin – Adds a simple download manager to your WordPress " +"blog." +msgstr "" +"Descargar Manager Plugin – Agrega un simple gestor de descargas a tu blog de " +"WordPress." + +#: admin/slm-lic-settings.php:142 +msgid "WP eStores Support" +msgstr "Soporte de WP eStores" + +#: admin/slm-lic-settings.php:145 +msgid "" +"WordPress eStore Plugin – Complete Solution to Sell Digital Products from " +"Your WordPress Blog Securely" +msgstr "" +"WordPress eStore Plugin – Solución completa para vender productos digitales " +"de su blog de WordPress de forma segura" + +#: admin/slm-lic-settings.php:153 +msgid "Debugging settings" +msgstr "Parámetros" + +#: admin/slm-lic-settings.php:158 +msgid "Enable Debug Logging" +msgstr "Habilitar el registro de depuración" + +#: admin/slm-lic-settings.php:160 +msgid "" +"If checked, debug output will be written to log files (keep it disabled " +"unless you are troubleshooting)." +msgstr "" +"Si está marcada, la salida de depuración se escribirá en los archivos de " +"registro (manténgala deshabilitada a menos que esté solucionando problemas)." + +#: admin/slm-lic-settings.php:162 +msgid "View debug log file by clicking" +msgstr "Ver el archivo de registro de depuración haciendo clic en" + +#: admin/slm-lic-settings.php:162 admin/slm-lic-settings.php:163 +msgid "here" +msgstr "aquí" + +#: admin/slm-lic-settings.php:163 +msgid "Reset debug log file by clicking" +msgstr "Restablecer el archivo de registro de depuración haciendo clic en" + +#: admin/slm-lic-settings.php:171 +msgid "Update Options" +msgstr "Opciones de actualización" + +#: admin/slm-list-licenses-class.php:27 +msgid "No licenses avaliable." +msgstr "No hay licencias disponibles." + +#: admin/slm-list-licenses-class.php:43 +msgid "All" +msgstr "Todos" + +#: admin/slm-list-licenses-class.php:50 +msgid "active" +msgstr "Activo" + +#: admin/slm-list-licenses-class.php:57 +msgid "pending" +msgstr "Pendiente" + +#: admin/slm-list-licenses-class.php:64 +msgid "expired" +msgstr "caducado" + +#: admin/slm-list-licenses-class.php:71 +msgid "blocked" +msgstr "Bloqueado" + +#: admin/slm-list-licenses-class.php:204 admin/slm-list-licenses-class.php:221 +#: admin/slm-list-licenses-class.php:238 admin/slm-list-licenses-class.php:255 +msgid "Error - Please select some records using the checkboxes" +msgstr "" +"Error - Seleccione algunos registros usando las casillas de verificación" + +#: admin/slm-manage-licenses.php:15 +msgid "You do not have permission to manage this license." +msgstr "No tiene permiso para administrar esta licencia." + +#: admin/slm-manage-licenses.php:43 +msgid "Overview - Manage licenses" +msgstr "Descripción general - Administrar licencias" + +#: admin/slm-manage-licenses.php:45 +msgid "Add New" +msgstr "Añadir nueva" + +#: admin/slm-manage-licenses.php:57 admin/slm-subscribers.php:211 +msgid "Search" +msgstr "Buscar" + +#: admin/slm-subscribers.php:170 +msgid "Overview - Manage Subscribers" +msgstr "Visión general - Administrar suscriptores" + +#: admin/slm-subscribers.php:172 +msgid "View all" +msgstr "Ver todos los" + +#: admin/slm-subscribers.php:181 +msgid "ID" +msgstr "Id" + +#: admin/slm-subscribers.php:182 woocommerce/includes/purchase.php:396 +msgid "License key" +msgstr "Clave de licencia" + +#: admin/slm-subscribers.php:183 +msgid "Status" +msgstr "Estado" + +#: admin/slm-subscribers.php:200 +msgid "Overview - All Subscribers" +msgstr "Visión general - Todos los suscriptores" + +#: includes/slm-meta-boxes.php:23 +msgid "License Manager" +msgstr "Administrador de licencias" + +#: includes/slm-meta-boxes.php:25 +msgid "Enables the license creation api." +msgstr "Habilita la API de creación de licencias." + +#: includes/slm-meta-boxes.php:73 +msgid "Licensing" +msgstr "Licencias" + +#: includes/slm-meta-boxes.php:93 +msgid "Domain Licenses" +msgstr "Licencias de dominio" + +#: includes/slm-meta-boxes.php:97 +msgid "Enter the allowed amount of domains this license can have (websites)." +msgstr "" +"Introduzca la cantidad permitida de dominios que esta licencia puede tener " +"(sitios web)." + +#: includes/slm-meta-boxes.php:103 +msgid "Devices Licenses" +msgstr "Licencias de dispositivos" + +#: includes/slm-meta-boxes.php:107 +msgid "" +"Enter the allowed amount of devices this license can have (computers, " +"mobile, etc)." +msgstr "" +"Introduzca la cantidad permitida de dispositivos que puede tener esta " +"licencia (ordenadores, móviles, etc.)." + +#: includes/slm-meta-boxes.php:113 +msgid "License Type" +msgstr "Tipo de licencia" + +#: includes/slm-meta-boxes.php:116 +msgid "type of license: subscription base or lifetime" +msgstr "tipo de licencia: base de suscripción o duración" + +#: includes/slm-meta-boxes.php:118 +msgid "Select one" +msgstr "Seleccione uno" + +#: includes/slm-meta-boxes.php:119 +msgid "subscription" +msgstr "Suscripción" + +#: includes/slm-meta-boxes.php:120 +msgid "lifetime" +msgstr "Vida" + +#: includes/slm-meta-boxes.php:127 +msgid "Renewal period " +msgstr "Período de renovación" + +#: includes/slm-meta-boxes.php:130 +msgid "License renewal period(yearly) , enter 0 for lifetime." +msgstr "" +"Período de renovación de la licencia (anual), escriba 0 durante la vida útil." + +#: includes/slm-meta-boxes.php:137 +msgid "Current Version" +msgstr "Versión actual" + +#: includes/slm-meta-boxes.php:140 +msgid "Enter the current version of your application, theme, or plug-in" +msgstr "" +"Introduzca la versión actual de la aplicación, el tema o el complemento" + +#: includes/slm-meta-boxes.php:147 +msgid "Until Version" +msgstr "Hasta la versión" + +#: includes/slm-meta-boxes.php:150 +msgid "Enter the version until support expires." +msgstr "Introduzca la versión hasta que expire el soporte técnico." + +#: includes/slm-meta-boxes.php:210 +msgid "License product" +msgstr "Producto de licencia" + +#: public/slm-add-menu-frontend.php:54 public/slm-add-menu-frontend.php:67 +msgid "My Licenses" +msgstr "Mis licencias" + +#. translators: %s: Customer first name +#: woocommerce/emails/customer-completed-order.php:13 +#, php-format +msgid "Hi %s," +msgstr "Hola %s," + +#. translators: %s: Site title +#: woocommerce/emails/customer-completed-order.php:15 +#, php-format +msgid "" +"Your %s order has been marked complete on our side. Here is you license " +"information." +msgstr "" +"Su pedido %s ha sido marcado como completo de nuestro lado. Aquí está la " +"información de su licencia." + +#: woocommerce/emails/customer-completed-order.php:23 +msgid "Thanks for shopping with us." +msgstr "Gracias por comprar con nosotros." + +#: woocommerce/includes/class.php:27 +msgid "Order Confirmation" +msgstr "Confirmación del pedido" + +#: woocommerce/includes/purchase.php:88 +msgid "License could not be created: Invalid sites allowed number." +msgstr "No se pudo crear la licencia: número permitido de sitios no válidos." + +#: woocommerce/includes/purchase.php:213 +msgid "License Key(s) generated" +msgstr "Clave(s) de licencia generada(s)" + +#: woocommerce/includes/purchase.php:230 +msgid "License Key(s) could not be created." +msgstr "No se han podido crear claves de licencia." + +#: woocommerce/includes/purchase.php:338 +msgid "Order confirmation email sent to: BV;`m}g$7ks;SUs`qNTJJ{}4+4sG>?Git>GtQd@-h2Sh2K z-#KUI&TiI$Qm!)loyU3n&hP#EIe&lKjlZt=MO=4tJ$i#up9DX26My)9>}I9@1^fkY z4$R-K)DMHNfP26{0hyw{2Hpk!CHN!Ycfi}g?}6_GZ`-TXt>F8>3*ZBwjQbRL9{emQ z^S=$=4(@q}Qg?!PgA?Fk@C0}fTm(N0o&>)GJ_bJULrP78Yv4oR=fPXRzXFBM*Fo9; z+n^lnd*EBan>fq>d^^Z1m4hs)ejXJ1KLx%I{B2O^+XDGd{T+XV{(lB#-hY5cz&&g# zbRP$0{s%!>F9q)auYxk~SHTCtYasurzvhpu^Gy(zsec1yo&WN92a}%QxeLnqH$fTy zr=YC=H=wNlIw<>o7d!;s%AtQ0JP!Ui_>6!42q=8{GV3$A4EiI3EU4ZgTj|jfY-n;fHLnGL+Q#Pchl(DhE3 zB;8K;icFc13|0ehtc>6t0k1v3S zc#gn(!B2x<0$&AX-iVioSgnH`O+62O9Q-o)x8NiD9sTcyIN{GeQ228g6g@o$T6#c{ z%jduz_(f3o^*V^i)PI6&;N1t5ng^c;e*^qFI1R3IXyMoIf;WM;{*>eIo#4$pPk?U& z?*nDuX;AiE1#bjD3W~q_I4J!76;RIo8SpKj{PuDQ@9Uq?C${@I*CqdQ5BRjdf5hWk zL6PnKT<82dk&&GDN&kEXT;UR$Lm*|iDMBa1u&e14z!xkHdj{Em=w#T?c z)?%M>2Kmi6urj}cd(nA0Z^yqE*}+QdyZkE)XZgF#_0wD@>>I~VxfQt}X8RMHeS%AP zEbh(BDbWoMqFeu|NNRmxmm{OMmql+>qt3qe1I?zcRnzS(b zirLg|Yy{B-lS1e|o(+da?nX&au4egAuT*hTYHszVERPm)QxvQuqk*(}uYD$h+?>Wd~X;w)7s%u3bo$7x?!T!IC! z)|gS~d-Vw<5U1leekESSg;1^6vn;Ghjk5JL$%06ag1+hMg**#crGTyOz3?il`h!Mp zoWta>YBh6Hl-sVRmtE==&jcxJ=6WHiAXWe4$DY?5wm>RY8m8Gp5B*3^Zw1gWORvDA z?i-g}tVW|OFV#t_f7-G`&u5k;^-EDjCqDEsOSOORgkNi6h$`8y!6@!BqJ&;ihYRQD zMIm!^fTwzNqgt}w5H@i>r}rx;xd^DtT8m%<*}92zFw82xp~R6FQaM12>s7-b)q`No z=t-n9svx15(!*>e76mh9c%V(#E^9h*L+Gw+uA7x2E={p*mC)V^-sh_N&R_fDW@NiFBHk8a1&RCk~}GPX_hv8A}tj zKeU$j*3^7m+8mkYVYeN6dM?F%#u4U*{B^B4X*FCi`FQ^wy3nj?J)b>q^9pa;zSlv@ z;?}n}uSa*vUNZ`H7M*q4h4_Rhao=5a&br{^S-KkM5^MYZyVZ9aI`_z*V~X%tyf*_b11S+|Ri)-BhIe;P+X@x8EaN-v2!24}}U znx}=+3tDoOhEjqjPADQo5xp(YpiA?EA zVY!ME9F4?TugB#8zun~{Mp8K5;}aTRTL~Qqm(WWxCt08*VJVr8_mNGw%^lOb`U5yz z34ks$b9p4YNT?v7v1yKz$%a3`o}6ebY`?Ew&9k9T)nT zH>yjGqBqFFNzuCdz8I-6SKLrpv_{Lk%!h=p-_q@ z8LZQ)vG%#q?Gz3T8YKp~F4k(yxiOtYpNRW09#C>faRMlhFc|^2vR{2n%o($-a&mQ5 zOFtk94m6RX(G*O>LzSA!6TSTB=VMg~%Oj7%7>ZnEge zhGeVA;&WPDExOngitI<&`h@@uEl!JNc$LO@2NrC?^Y#_&){)Z{o5K<3hH)X%6@74t zt)tiPY^lvjUr4MZlO6;GX#ok!Fvzd4vE+c3zpNmvE8+;vJT0jxw4!(o0g{7z4d^Oc z^B6_G9I}e?Ws8y&Rt?H>RP+uWL_C9PrOOTnhc@J_nS+J*U>#3h$B~>LY-X*muXoKT zzLIR(nW_%fiqa<%UtGAzVR^44QcHmK%k{_&ZCtTmt*4TNvRQ-LfW)qIih~qAo#O0x zERG&JA~`3wM<-J~aa7M7II(PXnN+6 z&h&$wnMd@@bZ`2B&h+8wX$E%Ala!0Vb{RL*yMNk^o2PKBNcTHSCK&eg-ZOJ&PLAoA z=}zw@9+PL59ZAf3x-=W*LF&LbJtDp>C!QU>uym^P@OYfKg;kSxPNrcdjO^)$SK@N- zQyrJ?Vx~R4kXb7@)Sc3lR1)-y&PJaknaz8;(?OLx*0|HM zI9ken6sB2T^v07eEu1z1dWfK|qY2&7U^E`TXlvc$?nFK9j?@rFAYPa3ejbbM>E-1k z%jU>(+MAg=bYyu$AmmMblWz15hg0&+6yb7EmN^reTQk1(6XesN943C0y>+APZL{oh znq?!mXS(4Y?sxkvFH`+n?lfce&IbiDYj}fbYf<;KDV8rRw$5&ojs+OsnTGYdeK@%h zCKdie2He-ZTQfovIEe8D%8EL=C)pXmUQ-zRA`#37L{3&`e0|0A@zw zg#uC^DG_8qr7$Oh<)n3!a(p$r^`#(+bDdUZEl^8Yl+k7p9@G11F`0W;2!%03 zwdJI&7qTzIvI-Kl5Fkm?mYkJnwTv>7ig=BqZ<0+=(Z;-=mqZBR*-a=un?dw%3a=gP z&LOt0k@i_}Ae%7A`}V%ox@k9S>Jb5jYp}NUf;+>uReZE?#}L_%@GMTfYK`*cS3{m7 zS}3#o=h|nt?Q~$apBqT4=z>}8AW+gDvpQGPEwV2w+sYBvHpvBjoo3}Clg!KNcb!6? z_O?PIkf4lX8AfJAXs`!S<3aH3dV;D4314Ry=B(;S3(-onC2TTVs(i^_u7)%!1KS0% zH{<~1yI9;>EJ7BFP|G5?Y$@iTR!mg6Xy8t4vj4x^&1<9GY5VH!eJ4eKQD3SP*Z*j7hNQZ1 z24QvInoK|qgDN>LKu`kx!$6Bo`>aMxIom;Evl59A=aj>{z5Q;|_cb06i zhQlBw43d78LT9Zb(p$2=Fu}~ipr9}9?2WB#CE!%&cmVHxt0|L&NmBn@&5N(POp_N! z;F3Prt4?RAgKarQYBBcSoQw^h7EFn%6u2fY%dvV|ov~GQY_$frD63PsTEBpVYnt^W zc^9Wl`vHrgP~H~^je+PI^DJu!BQMwrQqFEqNvS~?83xkf^Gzzt7ik|1S4bPh*r`vp zUJR=wqeQ1gb=f+@H-r>vIH2Z~etJYof_IRDEqAeJn_uiYUnz~NmH~N&MFH>Kfc95f z-Qopt#iG6KFNIo)N0y}86?sZVRYL=8sXvk^ZoN#rpaU)0Hb!LUdUZ`Ry|#4?X=K>* zy!W@dQ8O%6oHf#K;-JW{UV9g^ZB%HJi$fQyiG-Q9)Y(q@0ulX1;)zV5{gtil>KF86 zkV41-48>|lpr>_&Uz6YpJ!_&(TQAdHMd$5imVy?cHOuNFHfN=Wv~`UJnI&MGXKC2A zeMs#NTA$B)1`n^dlEhe1W>HEpf`)+{$MZkXlP>?Dz>26C5taBY)O5GiJrTZ*2FoyQ zYO^0`pEKJUYm`s5lx=Hm5ctM~3wRQY(->1iZR*}y9U|&z$p`)+W=EESnCr&d&hai{ zpbA0Lfa^33xQkRBl0JAZLm$p&A(pL0<$5^c<*Dj-4jfw&1!8-sL{xe|j*jud?eSwC z)Y_|FyXFkvnw#s>VfDoH#y#zl(M_o9D7tj->eN=8xc7I?9Ci)kc$_e%n#A8g9ZXZl zI26v?HhnDrVvp0*A9vHZxZOO za!PJqv-C|ooa|IrShNijoR7$!w~{c`_w_=S(t5Zv0>s?JS8E#5G@SI^!EsVWpHO0f zvshHZoe_fMQd?XJ`+%n zOHM|hWrPj)xdaZH7=*4&a$@Jld>vDZlxRaQRI+*rkd~p8LZk`M&U75)vlYqxSct;0 zUFA3EHYy`XSC&T2|zYQpDy(j0K~ zNy`EG?lz}M;;gjY5w~6@`wj@))a0lkE7~@v-#cjXx*f#||H@F+b>=+#mm7aD=^F!>Iq-FdiL3B>qRjRh(!r^6tEaT!&?9URAh?oG6@N@6&qBti3((u prkVNw(*nInaz^x{{V5XUkmI1M${m?(ujzyMK<&(h^EO57e*+T-hUNeO literal 0 HcmV?d00001 diff --git a/languages/softwarelicensemanager-es_US.po b/languages/softwarelicensemanager-es_US.po new file mode 100644 index 0000000..c5dbf07 --- /dev/null +++ b/languages/softwarelicensemanager-es_US.po @@ -0,0 +1,495 @@ +msgid "" +msgstr "" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Project-Id-Version: Software License Manager\n" +"POT-Creation-Date: 2019-06-19 10:05-0400\n" +"PO-Revision-Date: 2019-06-19 11:30-0400\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.1.1\n" +"X-Poedit-Basepath: ..\n" +"X-Poedit-Flags-xgettext: --add-comments=translators:\n" +"X-Poedit-WPHeader: software-license-manager.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" +"Last-Translator: \n" +"Language: es_US\n" +"X-Poedit-SearchPath-0: .\n" +"X-Poedit-SearchPathExcluded-0: *.js\n" + +#: admin/includes/cronjobs/slm-tasks.php:13 +msgid "Every 1 minute" +msgstr "Cada 1 minuto" + +#: admin/includes/wpestores/slm-wpestores.php:70 +msgid "Item Name: " +msgstr "Nombre del artículo" + +#: admin/includes/wpestores/slm-wpestores.php:70 +msgid "License Key: " +msgstr "Clave de licencia" + +#: admin/slm-add-licenses.php:141 +msgid "Record could not be inserted into the database!" +msgstr "¡No se pudo insertar un registro en la base de datos!" + +#: admin/slm-add-licenses.php:149 +msgid "Update of the license key table failed!" +msgstr "¡Error al actualizar la tabla de claves de licencia!" + +#. Plugin Name of the plugin/theme +#: admin/slm-add-licenses.php:185 +msgid "Software License Manager" +msgstr "Administrador de licencias de software" + +#: admin/slm-add-licenses.php:188 +msgid "You can add a new license or edit an existing one from this interface." +msgstr "" +"Puede agregar una nueva licencia o editar una existente desde esta interfaz." + +#: admin/slm-add-licenses.php:234 +msgid "License key and status" +msgstr "Clave de licencia y estado" + +#: admin/slm-add-licenses.php:238 +msgid "User information" +msgstr "Información de usuario" + +#: admin/slm-add-licenses.php:244 +msgid "Devices & Domains" +msgstr "Dispositivos y Dominios" + +#: admin/slm-add-licenses.php:249 +msgid "Transaction" +msgstr "Transacción" + +#: admin/slm-add-licenses.php:253 +msgid "Product" +msgstr "Producto" + +#: admin/slm-add-licenses.php:259 +msgid "Activity log " +msgstr "Registro de actividad" + +#: admin/slm-add-licenses.php:266 +msgid "Export " +msgstr "exportar" + +#: admin/slm-admin-functions.php:41 +msgid "Send Deactivation Message for a License" +msgstr "Enviar mensaje de desactivación para una licencia" + +#: admin/slm-admin-functions.php:43 +msgid "Enter the URL where the license deactivation message will be sent to" +msgstr "" +"Introduzca la URL a la que se enviará el mensaje de desactivación de la " +"licencia" + +#: admin/slm-lic-settings.php:76 +msgid "General settings" +msgstr "Los ajustes generales" + +#: admin/slm-lic-settings.php:80 +msgid "Secret Key for License Creation" +msgstr "Clave secreta para la creación de licencias" + +#: admin/slm-lic-settings.php:82 +msgid "" +"This secret key will be used to authenticate any license creation request. " +"You can change it with something random." +msgstr "" +"Esta clave secreta se utilizará para autenticar cualquier solicitud de " +"creación de licencia. Puedes cambiarlo con algo aleatorio." + +#: admin/slm-lic-settings.php:86 +msgid "Secret Key for License Verification Requests" +msgstr "Clave secreta para las solicitudes de verificación de licencias" + +#: admin/slm-lic-settings.php:88 +msgid "" +"This secret key will be used to authenticate any license verification " +"request from customer's site. Important! Do not change this value once your " +"customers start to use your product(s)!" +msgstr "" +"Esta clave secreta se usará para autenticar cualquier solicitud de " +"verificación de licencia desde el sitio del cliente. ¡Importante! ¡No cambie " +"este valor una vez que sus clientes comiencen a usar su(s) producto(s)!" + +#: admin/slm-lic-settings.php:92 +msgid "License Key Prefix" +msgstr "Prefijo de clave de licencia" + +#: admin/slm-lic-settings.php:94 +msgid "" +"You can optionaly specify a prefix for the license keys. This prefix will be " +"added to the uniquely generated license keys." +msgstr "" +"Opcionalmente, puede especificar un prefijo para las claves de licencia. " +"Este prefijo se agregará a las claves de licencia generadas de forma única." + +#: admin/slm-lic-settings.php:98 +msgid "Maximum Allowed Domains" +msgstr "Máximo de dominios permitidos" + +#: admin/slm-lic-settings.php:100 +msgid "" +"Maximum number of domains/installs which each license is valid for (default " +"value)." +msgstr "" +"Número máximo de dominios/instalaciones para los que cada licencia es válida " +"(valor predeterminado)." + +#: admin/slm-lic-settings.php:104 +msgid "Maximum Allowed Devices" +msgstr "Máximo de dispositivos permitidos" + +#: admin/slm-lic-settings.php:106 +msgid "" +"Maximum number of devices which each license is valid for (default value)." +msgstr "" +"Número máximo de dispositivos para los que cada licencia es válida (valor " +"predeterminado)." + +#: admin/slm-lic-settings.php:110 +msgid "Auto Expire License Keys" +msgstr "Claves de licencia de expiración automática" + +#: admin/slm-lic-settings.php:112 +msgid "Enable auto expiration " +msgstr "Habilitar la expiración automática" + +#: admin/slm-lic-settings.php:113 +msgid "" +" When enabled, it will automatically set the status of a license key to " +"\"Expired\" when the expiry date value of the k ey is reached. It doesn't " +"remotely deactivate a key. It simply changes the status of the key in your " +"database to expired." +msgstr "" +"Cuando está habilitado, establecerá automáticamente el estado de una clave " +"de licencia en \"Expirado\" cuando se alcance el valor de fecha de caducidad " +"del k ey. No desactiva de forma remota una clave. Simplemente cambia el " +"estado de la clave en la base de datos a caducado." + +#: admin/slm-lic-settings.php:121 +msgid "Integrations" +msgstr "Integraciones" + +#: admin/slm-lic-settings.php:125 +msgid "Woocommerce Support" +msgstr "Soporte técnico de Woocommerce" + +#: admin/slm-lic-settings.php:128 +msgid "" +"A fully customizable, open source eCommerce platform built for WordPress." +msgstr "" +"Una plataforma de comercio electrónico totalmente personalizable y de código " +"abierto creada para WordPress." + +#: admin/slm-lic-settings.php:132 +msgid "" +"Disable woocommerce download page. Proccess downloads though license order " +"info page." +msgstr "" +"Deshabilite la página de descarga de woocommerce. Proccess descarga a través " +"de la página de información del pedido de licencia." + +#: admin/slm-lic-settings.php:135 +msgid "Download Manager Support" +msgstr "Descargar soporte de Manager" + +#: admin/slm-lic-settings.php:138 +msgid "" +"Download Manager Plugin – Adds a simple download manager to your WordPress " +"blog." +msgstr "" +"Descargar Manager Plugin – Agrega un simple gestor de descargas a tu blog de " +"WordPress." + +#: admin/slm-lic-settings.php:142 +msgid "WP eStores Support" +msgstr "Soporte de WP eStores" + +#: admin/slm-lic-settings.php:145 +msgid "" +"WordPress eStore Plugin – Complete Solution to Sell Digital Products from " +"Your WordPress Blog Securely" +msgstr "" +"WordPress eStore Plugin – Solución completa para vender productos digitales " +"de su blog de WordPress de forma segura" + +#: admin/slm-lic-settings.php:153 +msgid "Debugging settings" +msgstr "Parámetros" + +#: admin/slm-lic-settings.php:158 +msgid "Enable Debug Logging" +msgstr "Habilitar el registro de depuración" + +#: admin/slm-lic-settings.php:160 +msgid "" +"If checked, debug output will be written to log files (keep it disabled " +"unless you are troubleshooting)." +msgstr "" +"Si está marcada, la salida de depuración se escribirá en los archivos de " +"registro (manténgala deshabilitada a menos que esté solucionando problemas)." + +#: admin/slm-lic-settings.php:162 +msgid "View debug log file by clicking" +msgstr "Ver el archivo de registro de depuración haciendo clic en" + +#: admin/slm-lic-settings.php:162 admin/slm-lic-settings.php:163 +msgid "here" +msgstr "aquí" + +#: admin/slm-lic-settings.php:163 +msgid "Reset debug log file by clicking" +msgstr "Restablecer el archivo de registro de depuración haciendo clic en" + +#: admin/slm-lic-settings.php:171 +msgid "Update Options" +msgstr "Opciones de actualización" + +#: admin/slm-list-licenses-class.php:27 +msgid "No licenses avaliable." +msgstr "No hay licencias disponibles." + +#: admin/slm-list-licenses-class.php:43 +msgid "All" +msgstr "Todos" + +#: admin/slm-list-licenses-class.php:50 +msgid "active" +msgstr "Activo" + +#: admin/slm-list-licenses-class.php:57 +msgid "pending" +msgstr "Pendiente" + +#: admin/slm-list-licenses-class.php:64 +msgid "expired" +msgstr "caducado" + +#: admin/slm-list-licenses-class.php:71 +msgid "blocked" +msgstr "Bloqueado" + +#: admin/slm-list-licenses-class.php:204 admin/slm-list-licenses-class.php:221 +#: admin/slm-list-licenses-class.php:238 admin/slm-list-licenses-class.php:255 +msgid "Error - Please select some records using the checkboxes" +msgstr "" +"Error - Seleccione algunos registros usando las casillas de verificación" + +#: admin/slm-manage-licenses.php:15 +msgid "You do not have permission to manage this license." +msgstr "No tiene permiso para administrar esta licencia." + +#: admin/slm-manage-licenses.php:43 +msgid "Overview - Manage licenses" +msgstr "Descripción general - Administrar licencias" + +#: admin/slm-manage-licenses.php:45 +msgid "Add New" +msgstr "Añadir nueva" + +#: admin/slm-manage-licenses.php:57 admin/slm-subscribers.php:211 +msgid "Search" +msgstr "Buscar" + +#: admin/slm-subscribers.php:170 +msgid "Overview - Manage Subscribers" +msgstr "Visión general - Administrar suscriptores" + +#: admin/slm-subscribers.php:172 +msgid "View all" +msgstr "Ver todos los" + +#: admin/slm-subscribers.php:181 +msgid "ID" +msgstr "Id" + +#: admin/slm-subscribers.php:182 woocommerce/includes/purchase.php:396 +msgid "License key" +msgstr "Clave de licencia" + +#: admin/slm-subscribers.php:183 +msgid "Status" +msgstr "Estado" + +#: admin/slm-subscribers.php:200 +msgid "Overview - All Subscribers" +msgstr "Visión general - Todos los suscriptores" + +#: includes/slm-meta-boxes.php:23 +msgid "License Manager" +msgstr "Administrador de licencias" + +#: includes/slm-meta-boxes.php:25 +msgid "Enables the license creation api." +msgstr "Habilita la API de creación de licencias." + +#: includes/slm-meta-boxes.php:73 +msgid "Licensing" +msgstr "Licencias" + +#: includes/slm-meta-boxes.php:93 +msgid "Domain Licenses" +msgstr "Licencias de dominio" + +#: includes/slm-meta-boxes.php:97 +msgid "Enter the allowed amount of domains this license can have (websites)." +msgstr "" +"Introduzca la cantidad permitida de dominios que esta licencia puede tener " +"(sitios web)." + +#: includes/slm-meta-boxes.php:103 +msgid "Devices Licenses" +msgstr "Licencias de dispositivos" + +#: includes/slm-meta-boxes.php:107 +msgid "" +"Enter the allowed amount of devices this license can have (computers, " +"mobile, etc)." +msgstr "" +"Introduzca la cantidad permitida de dispositivos que puede tener esta " +"licencia (ordenadores, móviles, etc.)." + +#: includes/slm-meta-boxes.php:113 +msgid "License Type" +msgstr "Tipo de licencia" + +#: includes/slm-meta-boxes.php:116 +msgid "type of license: subscription base or lifetime" +msgstr "tipo de licencia: base de suscripción o duración" + +#: includes/slm-meta-boxes.php:118 +msgid "Select one" +msgstr "Seleccione uno" + +#: includes/slm-meta-boxes.php:119 +msgid "subscription" +msgstr "Suscripción" + +#: includes/slm-meta-boxes.php:120 +msgid "lifetime" +msgstr "Vida" + +#: includes/slm-meta-boxes.php:127 +msgid "Renewal period " +msgstr "Período de renovación" + +#: includes/slm-meta-boxes.php:130 +msgid "License renewal period(yearly) , enter 0 for lifetime." +msgstr "" +"Período de renovación de la licencia (anual), escriba 0 durante la vida útil." + +#: includes/slm-meta-boxes.php:137 +msgid "Current Version" +msgstr "Versión actual" + +#: includes/slm-meta-boxes.php:140 +msgid "Enter the current version of your application, theme, or plug-in" +msgstr "" +"Introduzca la versión actual de la aplicación, el tema o el complemento" + +#: includes/slm-meta-boxes.php:147 +msgid "Until Version" +msgstr "Hasta la versión" + +#: includes/slm-meta-boxes.php:150 +msgid "Enter the version until support expires." +msgstr "Introduzca la versión hasta que expire el soporte técnico." + +#: includes/slm-meta-boxes.php:210 +msgid "License product" +msgstr "Producto de licencia" + +#: public/slm-add-menu-frontend.php:54 public/slm-add-menu-frontend.php:67 +msgid "My Licenses" +msgstr "Mis licencias" + +#. translators: %s: Customer first name +#: woocommerce/emails/customer-completed-order.php:13 +#, php-format +msgid "Hi %s," +msgstr "Hola %s," + +#. translators: %s: Site title +#: woocommerce/emails/customer-completed-order.php:15 +#, php-format +msgid "" +"Your %s order has been marked complete on our side. Here is you license " +"information." +msgstr "" +"Su pedido %s ha sido marcado como completo de nuestro lado. Aquí está la " +"información de su licencia." + +#: woocommerce/emails/customer-completed-order.php:23 +msgid "Thanks for shopping with us." +msgstr "Gracias por comprar con nosotros." + +#: woocommerce/includes/class.php:27 +msgid "Order Confirmation" +msgstr "Confirmación del pedido" + +#: woocommerce/includes/purchase.php:88 +msgid "License could not be created: Invalid sites allowed number." +msgstr "No se pudo crear la licencia: número permitido de sitios no válidos." + +#: woocommerce/includes/purchase.php:213 +msgid "License Key(s) generated" +msgstr "Clave(s) de licencia generada(s)" + +#: woocommerce/includes/purchase.php:230 +msgid "License Key(s) could not be created." +msgstr "No se han podido crear claves de licencia." + +#: woocommerce/includes/purchase.php:338 +msgid "Order confirmation email sent to: query_vars[self::$endpoint]); if ($is_endpoint && !is_admin() && is_main_query() && in_the_loop() && is_account_page()) { // New page title. - $title = __('My Licenses', 'woocommerce'); + $title = __('My Licenses', 'softwarelicensemanager'); remove_filter('the_title', array($this, 'endpoint_title')); } return $title; @@ -64,7 +64,7 @@ public function slm_woo_menu_list($items) unset($items['customer-logout']); // Insert your custom endpoint. - $items[self::$endpoint] = __('My Licenses', 'woocommerce'); + $items[self::$endpoint] = __('My Licenses', 'softwarelicensemanager'); // Insert back the logout item. $items['customer-logout'] = $logout; @@ -88,134 +88,140 @@ public function endpoint_content() ?> - - - - - - - - - - - - - - get_results("SELECT * FROM " . $wpdb->prefix . "postmeta WHERE `meta_value` = '" . $license_info->purchase_id_ . "' LIMIT 0,1000;", ARRAY_A); - ?> - - - - - - - +
    +
    OrderStatusLicense KeyExpirationInfo
    purchase_id_; ?>lic_status; ?>license_key; ?>date_expiry; ?>View Info
    + + + + + + + - - + get_results("SELECT * FROM " . $wpdb->prefix . "lic_key_tbl WHERE `license_key` = '" . $license_info->license_key . "' ORDER BY `id` LIMIT 0,1000;", ARRAY_A); + foreach ($result as $license_info) : ?> + get_results("SELECT * FROM " . $wpdb->prefix . "lic_reg_domain_tbl WHERE `lic_key` = '" . $license_info->license_key . "' ORDER BY `lic_key_id` LIMIT 0,1000;", ARRAY_A); + $get_subscription = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "postmeta WHERE `meta_value` = '" . $license_info->purchase_id_ . "' LIMIT 0,1000;", ARRAY_A); + ?> - $detailed_devices_info = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "lic_reg_devices_tbl WHERE `lic_key` = '" . $license_info->license_key . "' ORDER BY `lic_key_id` LIMIT 0,1000;", ARRAY_A); + + + + + + + + + - - - - +
    + + + + + +
    Tips and Tricks HQ -Text Domain: slm +Text Domain: softwarelicensemanager +Domain Path: /languages/ */ // If this file is called directly, abort. @@ -19,9 +19,9 @@ global $wpdb, $slm_debug_logger; //Short name/slug "SLM" or "slm" -define('SLM_VERSION', '4.12.1'); -define('SLM_DB_VERSION', '2.9.1'); -define('SLM_REWRITE_VERSION', '1.1.4'); +define('SLM_VERSION', '5.0.2'); +define('SLM_DB_VERSION', '4.0.12'); +define('SLM_REWRITE_VERSION', '2.1.3'); define('SLM_FOLDER', dirname(plugin_basename(__FILE__))); define('SLM_URL', plugins_url('' ,__FILE__)); define('SLM_ASSETS_URL', SLM_URL . '/public/assets/'); @@ -36,6 +36,7 @@ define('SLM_SITE_HOME_URL', home_url()); define('SLM_SITE_URL', get_site_url() . '/'); define('SLM_TBL_LICENSE_KEYS', $wpdb->prefix . "lic_key_tbl"); +define('SLM_TBL_EMAILS', $wpdb->prefix . "lic_emails_tbl"); define('SLM_TBL_LIC_DOMAIN', $wpdb->prefix . "lic_reg_domain_tbl"); define('SLM_TBL_LIC_DEVICES', $wpdb->prefix . "lic_reg_devices_tbl"); define('SLM_TBL_LIC_LOG', $wpdb->prefix . "lic_log_tbl"); @@ -47,6 +48,10 @@ require_once SLM_LIB . 'slm-plugin-core.php'; } +// Options and filters define('WOO_SLM_API_SECRET', SLM_Helper_Class::slm_get_option('lic_creation_secret')); define('KEY_API', SLM_Helper_Class::slm_get_option('lic_creation_secret')); define('KEY_API_PREFIX', SLM_Helper_Class::slm_get_option('lic_prefix')); + +add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'slm_settings_link'); + diff --git a/software-license-manager/addons/loader.php b/software-license-manager/addons/loader.php new file mode 100644 index 0000000..b822895 --- /dev/null +++ b/software-license-manager/addons/loader.php @@ -0,0 +1,4 @@ +post->post_status == 'wc-completed') { + $output = ''; + + // Check if licenses were generated + $licenses = get_post_meta($order->post->ID, '_wc_slm_payment_licenses', true); + + if ($licenses && count($licenses) != 0) { + $output = '

    ' . __('Your Licenses', 'wc-slm') . ':

    '; + foreach ($licenses as $license) { + $output .= ''; + if (isset($license['item']) && isset($license['key'])) { + + if ($output) { + $output .= '
    '; + } + $output .= ''; + $output .= ''; + } else { + // $output .= 'No item and key assigned'; + } + /** + * added expire date in table + * @since 1.0.7 + * @author AvdP (Albert van der Ploeg) + */ + if (isset($license['expires'])) { + $output .= ''; + } + $output .= ''; + } + $output .= '
    ' . __('Item', 'wc-slm') . '' . __('License', 'wc-slm') . '' . __('Expire Date', 'wc-slm') . '
    ' . $license['item'] . '' . $license['key'] . '' . $license['expires'] . '
    '; + } else { + // $output .= 'No License Generatred'; + } + + echo $output; + } +} diff --git a/software-license-manager/addons/woocommerce/includes/helper.php b/software-license-manager/addons/woocommerce/includes/helper.php new file mode 100644 index 0000000..1f0300d --- /dev/null +++ b/software-license-manager/addons/woocommerce/includes/helper.php @@ -0,0 +1,23 @@ +'; + print_r($args); + echo '
    '; +} + +function wc_slm_log($msg) { + $log = ABSPATH . DIRECTORY_SEPARATOR . 'slm_log.txt'; + file_put_contents($log, $msg . ' +', FILE_APPEND); +} diff --git a/software-license-manager/addons/woocommerce/includes/purchase.php b/software-license-manager/addons/woocommerce/includes/purchase.php new file mode 100644 index 0000000..1e65268 --- /dev/null +++ b/software-license-manager/addons/woocommerce/includes/purchase.php @@ -0,0 +1,385 @@ +get_user_id(); + + //user data + $user_info = get_userdata($user_id); + +// write_log('user id '. $user_id); +// write_log('Username: ' . $user_info->user_login . "\n"); +// die(); + /** + * get details from billing form & added company name + * @since 1.0.2 + */ + $get_user_meta = get_user_meta($user_id); + $payment_meta['user_info']['first_name'] = $get_user_meta['billing_first_name'][0]; + $payment_meta['user_info']['last_name'] = $get_user_meta['billing_last_name'][0]; + $payment_meta['user_info']['email'] = $get_user_meta['billing_email'][0]; + $payment_meta['user_info']['company'] = $get_user_meta['billing_company'][0]; + + // Collect license keys + $licenses = array(); + $items = $_order->get_items(); + + foreach ($items as $item => $values) { + $download_id = $product_id = $values['product_id']; + $product = new WC_Product($product_id); + $variation_id = new WC_Product_Variation($product_id); + + //if ($product->is_downloadable() && $product->has_file()) { + + $download_quantity = absint($values['qty']); + + for ($i = 1; $i <= $download_quantity; $i++) { + /** + * Calculate Expire date + * @since 1.0.3 + */ + $renewal_period = (int) wc_slm_get_licensing_renewal_period($product_id); + + if ($renewal_period == 0) { + $renewal_period = '0000-00-00'; + } + else { + $renewal_period = date('Y-m-d', strtotime('+' . $renewal_period . ' years')); + } + // Sites allowed get license meta from variation + $sites_allowed = wc_slm_get_sites_allowed($product_id); + $amount_of_licenses = wc_slm_get_licenses_qty($product_id); + + if (!$sites_allowed) { + $sites_allowed_error = __('License could not be created: Invalid sites allowed number.', 'wc-slm'); + $int = wc_insert_payment_note($order_id, $sites_allowed_error); + break; + } + + // Get an instance of the WC_Order object (same as before) + $order = wc_get_order( $order_id ); + // Get the order ID + $order_id = $order->get_id(); + // Get the custumer ID + $order_id = $order->get_user_id(); + $order_data = $order->get_data(); // The Order data + + + // Iterating through each WC_Order_Item objects + foreach( $order-> get_items() as $item_key => $item_values ){ + + ## Using WC_Order_Item methods ## + $item_id = $item_values->get_id(); + $item_name = $item_values->get_name(); + $item_type = $item_values->get_type(); + ## Access Order Items data properties (in an array of values) ## + $item_data = $item_values->get_data(); + $product_name = $item_data['name']; + $product_id = $item_data['product_id']; + $variation_id = $item_data['variation_id']; + $quantity = $item_data['quantity']; + $tax_class = $item_data['tax_class']; + $line_subtotal = $item_data['subtotal']; + $line_subtotal_tax = $item_data['subtotal_tax']; + $line_total = $item_data['total']; + $line_total_tax = $item_data['total_tax']; + //$amount_of_licenses = $item_data['amount_of_licenses']; + //$amount_of_licenses = get_post_meta($product_id, 'amount_of_licenses', true); + $post_object = get_post($variation_id); + $amount_of_licenses = get_post_meta( $post_object->ID, 'amount_of_licenses', true); + $amount_of_licenses_devices = get_post_meta( $post_object->ID, 'amount_of_licenses_devices', true); + } + + + // Transaction id + $transaction_id = wc_get_payment_transaction_id($product_id); + + // Build item name + $item_name = $product->get_title(); + // $item_name = $product->get_formatted_name(); + + // Build parameters + $api_params = array(); + $api_params['slm_action'] = 'slm_create_new'; + $api_params['secret_key'] = KEY_API; + $api_params['first_name'] = (isset($payment_meta['user_info']['first_name'])) ? $payment_meta['user_info']['first_name'] : ''; + $api_params['last_name'] = (isset($payment_meta['user_info']['last_name'])) ? $payment_meta['user_info']['last_name'] : ''; + $api_params['email'] = (isset($payment_meta['user_info']['email'])) ? $payment_meta['user_info']['email'] : ''; + $api_params['company_name'] = $payment_meta['user_info']['company']; + /** + * set product id as txn + * @since 1.0.2 + * can be set to order id by $order_id var instead of $product_id + * @since 1.0.7 txn_id change from $product_id to $order_id + * @ref https://wordpress.org/support/topic/qty-1-generates-same-license + */ + $api_params['txn_id'] = $order_id; + // $api_params['max_allowed_domains'] = $sites_allowed; //unique per product + $api_params['max_allowed_domains'] = $amount_of_licenses; //unique per product + $api_params['max_allowed_devices'] = $amount_of_licenses_devices; //unique per product + $api_params['date_created'] = date('Y-m-d'); + $api_params['date_expiry'] = $renewal_period; + + +// write_log('sites - allowed: '.$sites_allowed); +// write_log('product id: '.$download_id); +// write_log('variation_id '.$variation_id); +// write_log('amount_of_licenses '.$amount_of_licenses); + +//die(); + + // Send query to the license manager server + $url = 'http://' . WC_SLM_API_URL . '?' . http_build_query($api_params); + $url = str_replace(array('http://', 'https://'), '', $url); + $url = 'http://' . $url; + +//write_log($url, array('timeout' => 20, 'sslverify' => false)); + + + $response = wp_remote_get($url, array('timeout' => 20, 'sslverify' => false)); + $license_key = wc_slm_get_license_key($response); + + + // Collect license keys + if ($license_key) { +//write_log('inside if $license_key'); + $licenses[] = array( + 'item' => $item_name, + 'key' => $license_key, + /** + * Add Expire Date + * @since 1.0.7 + * @author AvdP (Albert van der Ploeg) + */ + 'expires' => $renewal_period, + ); + } + else { +//write_log('inside else $license_key'); + } + } + + + } + + //wc_slm_print_pretty($payment_meta); + + // Payment note + + wc_slm_payment_note($order_id, $licenses); + + // Assign licenses + wc_slm_assign_licenses($order_id, $licenses); +} + +/** + * Get generated license key + * + * @since 1.0.0 + * @return mixed + */ +function wc_slm_get_license_key($response) { + // Check for error in the response + if (is_wp_error($response)) { + return false; + } + + // Get License data + $json = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', utf8_encode(wp_remote_retrieve_body($response))); + $license_data = json_decode($json); + + if (!isset($license_data->key)) { + return false; + } + + // Prepare note text + return $license_data->key; +} + +/** + * Leave payment not for license creation + * + * @since 1.0.0 + * @return void + */ +function wc_slm_payment_note($order_id, $licenses) { + + if ($licenses && count($licenses) != 0) { + $message = __('License Key(s) generated', 'wc-slm'); + + foreach ($licenses as $license) { + + $message .= '
    ' . $license['item'] . ': ' . $license['key']; + } + } else { + $message = __('License Key(s) could not be created.', 'wc-slm'); + } + + // Save note + $int = wc_insert_payment_note($order_id, $message); +} + +/** + * Assign generated license keys to payments + * + * @since 1.0.0 + * @return void + */ +function wc_slm_assign_licenses($order_id, $licenses) { + + if (count($licenses) != 0) { + update_post_meta($order_id, '_wc_slm_payment_licenses', $licenses); + } +} + +/** + * Get sites allowed from download. + * + * @since 1.0.0 + * @return mixed + */ +function wc_slm_get_sites_allowed($product_id) { + + $wc_slm_sites_allowed = absint(get_post_meta($product_id, '_wc_slm_sites_allowed', true)); + + if (empty($wc_slm_sites_allowed)) { + return false; + } + + return $wc_slm_sites_allowed; +} + +function wc_slm_get_licenses_qty($product_id) { + + $amount_of_licenses = absint(get_post_meta($product_id, '_amount_of_licenses', true)); + + if (empty($amount_of_licenses)) { + return false; + } + + return $amount_of_licenses; +} + +/** + * Get sites allowed from download. + * + * @since 1.0.0 + * @return mixed + */ +function wc_slm_get_licensing_renewal_period($product_id) { + + $wc_slm_sites_allowed = absint(get_post_meta($product_id, '_wc_slm_licensing_renewal_period', true)); + + if (empty($wc_slm_sites_allowed)) { + return 0; + } + + return $wc_slm_sites_allowed; +} + +/** + * Check if licensing for a certain download is enabled + * + * @since 1.0.0 + * @return bool + */ +function wc_slm_is_licensing_enabled($download_id) { + + $licensing_enabled = absint(get_post_meta($download_id, '_wc_slm_licensing_enabled', true)); + + // Set defaults + if ($licensing_enabled) { + return true; + } else { + return false; + } +} + +function wc_insert_payment_note($order_id, $msg) { + $order = new WC_Order($order_id); + $order->add_order_note($msg); +} + +function wc_get_payment_transaction_id($order_id) { + return get_post_meta($order_id, '_transaction_id', true); +} + +/** + * add license details to user account details + * @since 1.0.3 + */ +add_action('woocommerce_order_details_after_order_table', 'wc_slm_lic_order_meta', 10, 1); + +function wc_slm_lic_order_meta($order) { + $licenses = get_post_meta($order->post->ID, '_wc_slm_payment_licenses', true); + + if ($licenses && count($licenses) != 0) { + $output = '

    ' . __('Your Licenses', 'wc-slm') . ':

    '; + foreach ($licenses as $license) { + $output .= ''; + if (isset($license['item']) && isset($license['key'])) { + + if ($output) { + $output .= '
    '; + } + $output .= ''; + $output .= ''; + } else { + $output .= 'No item and key assigned'; + } + $output .= ''; + } + $output .= '
    ' . __('Item', 'wc-slm') . '' . __('License', 'wc-slm') . '
    ' . $license['item'] . '' . $license['key'] . '
    '; + } + + if (isset($output)) { + echo $output; + } + +} diff --git a/software-license-manager/addons/woocommerce/includes/settings.php b/software-license-manager/addons/woocommerce/includes/settings.php new file mode 100644 index 0000000..d57846f --- /dev/null +++ b/software-license-manager/addons/woocommerce/includes/settings.php @@ -0,0 +1,64 @@ + __('Software License Manager Settings', 'wc-slm'), 'type' => 'title', 'desc' => '', 'id' => 'wcslider'); + + // API URL Option filed + $settings_slm[] = array( + 'name' => __('API URL', 'wc-slm'), + 'desc_tip' => '', + 'id' => 'wc_slm_api_url', + 'type' => 'text', + 'desc' => 'Enter without http://', + ); + + // Secret Key + $settings_slm[] = array( + 'name' => __('Secret Key', 'wc-slm'), + 'desc_tip' => '', + 'id' => 'wc_slm_api_secret', + 'type' => 'text', + 'desc' => '', + ); + + $settings_slm[] = array('type' => 'sectionend', 'id' => 'wcslider'); + return $settings_slm; + + /** + * If not, return the standard settings + **/ + } else { + return $settings; + } +} \ No newline at end of file diff --git a/software-license-manager/addons/woocommerce/loader.php b/software-license-manager/addons/woocommerce/loader.php new file mode 100644 index 0000000..780e858 --- /dev/null +++ b/software-license-manager/addons/woocommerce/loader.php @@ -0,0 +1,103 @@ +setup_constants(); + self::$instance->includes(); + self::$instance->load_textdomain(); + } + + return self::$instance; + } + private function setup_constants() { + + // Plugin version + define('WC_SLM_VER', '1.0.8'); + + // Plugin path + define('WC_SLM_DIR', plugin_dir_path(__FILE__)); + // Plugin URL + define('WC_SLM_URL', plugin_dir_url(__FILE__)); + // SLM Credentials + $api_url = str_replace(array('http://'), array('https://'), rtrim(get_option('wc_slm_api_url'), '/')); + + // get api settinsg from options table + $slm_settings = get_option('slm_plugin_options'); + $lic_creation_secret = $slm_settings['lic_creation_secret']; + $lic_key_prefix = $slm_settings['lic_prefix']; + + define('WC_SLM_API_URL', $api_url); + define('WC_SLM_API_SECRET', get_option('wc_slm_api_secret')); + define('KEY_API', $lic_creation_secret); + define('KEY_API_PREFIX', $lic_key_prefix); +// write_log(KEY_API); +// write_log(KEY_API_PREFIX); + } + + private function includes() { + + // Get out if WC is not active + if (!function_exists('WC')) { + return; + } + + // log files and scripts + require_once WC_SLM_DIR . 'includes/helper.php'; + + if (is_admin()) { + require_once WC_SLM_DIR . 'includes/meta-boxes.php'; + require_once WC_SLM_DIR . 'includes/settings.php'; + } + + // purchases and emails + require_once WC_SLM_DIR . 'includes/emails.php'; + require_once WC_SLM_DIR . 'includes/purchase.php'; + } + + public function load_textdomain() { + + } + + public static function activation() { + // nothing + } + + public static function uninstall() { + // nothing + } + } + + function WC_SLM_load() { + + return WC_SLM::instance(); + } + + register_activation_hook(__FILE__, array('WC_SLM', 'activation')); + register_uninstall_hook(__FILE__, array('WC_SLM', 'uninstall')); + add_action('plugins_loaded', 'WC_SLM_load'); +} \ No newline at end of file diff --git a/software-license-manager/client-side-examples/index.html b/software-license-manager/client-side-examples/index.html new file mode 100644 index 0000000..e69de29 diff --git a/software-license-manager/client-side-examples/sample-php-scripts/create-license.php b/software-license-manager/client-side-examples/sample-php-scripts/create-license.php new file mode 100644 index 0000000..714880a --- /dev/null +++ b/software-license-manager/client-side-examples/sample-php-scripts/create-license.php @@ -0,0 +1,27 @@ +'; + echo '

    Sample License Management

    '; + + /*** License activate button was clicked ***/ + if (isset($_REQUEST['activate_license'])) { + $license_key = $_REQUEST['sample_license_key']; + + // API query parameters + $api_params = array( + 'slm_action' => 'slm_activate', + 'secret_key' => YOUR_SPECIAL_SECRET_KEY, + 'license_key' => $license_key, + 'registered_domain' => $_SERVER['SERVER_NAME'], + 'item_reference' => urlencode(YOUR_ITEM_REFERENCE), + ); + + // Send query to the license manager server + $query = esc_url_raw(add_query_arg($api_params, YOUR_LICENSE_SERVER_URL)); + $response = wp_remote_get($query, array('timeout' => 20, 'sslverify' => false)); + + // Check for error in the response + if (is_wp_error($response)){ + echo "Unexpected Error! The query returned with an error."; + } + + //var_dump($response);//uncomment it if you want to look at the full response + + // License data. + $license_data = json_decode(wp_remote_retrieve_body($response)); + + // TODO - Do something with it. + //var_dump($license_data);//uncomment it to look at the data + + if($license_data->result == 'success'){//Success was returned for the license activation + + //Uncomment the followng line to see the message that returned from the license server + echo '
    The following message was returned from the server: '.$license_data->message; + + //Save the license key in the options table + update_option('sample_license_key', $license_key); + } + else{ + //Show error to the user. Probably entered incorrect license key. + + //Uncomment the followng line to see the message that returned from the license server + echo '
    The following message was returned from the server: '.$license_data->message; + } + + } + /*** End of license activation ***/ + + /*** License activate button was clicked ***/ + if (isset($_REQUEST['deactivate_license'])) { + $license_key = $_REQUEST['sample_license_key']; + + // API query parameters + $api_params = array( + 'slm_action' => 'slm_deactivate', + 'secret_key' => YOUR_SPECIAL_SECRET_KEY, + 'license_key' => $license_key, + 'registered_domain' => $_SERVER['SERVER_NAME'], + 'item_reference' => urlencode(YOUR_ITEM_REFERENCE), + ); + + // Send query to the license manager server + $query = esc_url_raw(add_query_arg($api_params, YOUR_LICENSE_SERVER_URL)); + $response = wp_remote_get($query, array('timeout' => 20, 'sslverify' => false)); + + // Check for error in the response + if (is_wp_error($response)){ + echo "Unexpected Error! The query returned with an error."; + } + + //var_dump($response);//uncomment it if you want to look at the full response + + // License data. + $license_data = json_decode(wp_remote_retrieve_body($response)); + + // TODO - Do something with it. + //var_dump($license_data);//uncomment it to look at the data + + if($license_data->result == 'success'){//Success was returned for the license activation + + //Uncomment the followng line to see the message that returned from the license server + echo '
    The following message was returned from the server: '.$license_data->message; + + //Remove the licensse key from the options table. It will need to be activated again. + update_option('sample_license_key', ''); + } + else{ + //Show error to the user. Probably entered incorrect license key. + + //Uncomment the followng line to see the message that returned from the license server + echo '
    The following message was returned from the server: '.$license_data->message; + } + + } + /*** End of sample license deactivation ***/ + + ?> +

    Please enter the license key for this product to activate it. You were given a license key when you purchased this item.

    +
    + + + + + +
    +

    + + +

    +
    + '; +} \ No newline at end of file diff --git a/software-license-manager/css/jquery-ui.css b/software-license-manager/css/jquery-ui.css new file mode 100644 index 0000000..b775b44 --- /dev/null +++ b/software-license-manager/css/jquery-ui.css @@ -0,0 +1,1225 @@ +/*! jQuery UI - v1.11.0 - 2014-06-26 +* http://jqueryui.com +* Includes: core.css, accordion.css, autocomplete.css, button.css, datepicker.css, dialog.css, draggable.css, menu.css, progressbar.css, resizable.css, selectable.css, selectmenu.css, slider.css, sortable.css, spinner.css, tabs.css, tooltip.css, theme.css +* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px +* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { + display: none; +} +.ui-helper-hidden-accessible { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.ui-helper-reset { + margin: 0; + padding: 0; + border: 0; + outline: 0; + line-height: 1.3; + text-decoration: none; + font-size: 100%; + list-style: none; +} +.ui-helper-clearfix:before, +.ui-helper-clearfix:after { + content: ""; + display: table; + border-collapse: collapse; +} +.ui-helper-clearfix:after { + clear: both; +} +.ui-helper-clearfix { + min-height: 0; /* support: IE7 */ +} +.ui-helper-zfix { + width: 100%; + height: 100%; + top: 0; + left: 0; + position: absolute; + opacity: 0; + filter:Alpha(Opacity=0); +} + +.ui-front { + z-index: 100; +} + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { + cursor: default !important; +} + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + display: block; + text-indent: -99999px; + overflow: hidden; + background-repeat: no-repeat; +} + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +.ui-accordion .ui-accordion-header { + display: block; + cursor: pointer; + position: relative; + margin: 2px 0 0 0; + padding: .5em .5em .5em .7em; + min-height: 0; /* support: IE7 */ + font-size: 100%; +} +.ui-accordion .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-icons .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-header .ui-accordion-header-icon { + position: absolute; + left: .5em; + top: 50%; + margin-top: -8px; +} +.ui-accordion .ui-accordion-content { + padding: 1em 2.2em; + border-top: 0; + overflow: auto; +} +.ui-autocomplete { + position: absolute; + top: 0; + left: 0; + cursor: default; +} +.ui-button { + display: inline-block; + position: relative; + padding: 0; + line-height: normal; + margin-right: .1em; + cursor: pointer; + vertical-align: middle; + text-align: center; + overflow: visible; /* removes extra width in IE */ +} +.ui-button, +.ui-button:link, +.ui-button:visited, +.ui-button:hover, +.ui-button:active { + text-decoration: none; +} +/* to make room for the icon, a width needs to be set here */ +.ui-button-icon-only { + width: 2.2em; +} +/* button elements seem to need a little more width */ +button.ui-button-icon-only { + width: 2.4em; +} +.ui-button-icons-only { + width: 3.4em; +} +button.ui-button-icons-only { + width: 3.7em; +} + +/* button text element */ +.ui-button .ui-button-text { + display: block; + line-height: normal; +} +.ui-button-text-only .ui-button-text { + padding: .4em 1em; +} +.ui-button-icon-only .ui-button-text, +.ui-button-icons-only .ui-button-text { + padding: .4em; + text-indent: -9999999px; +} +.ui-button-text-icon-primary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 1em .4em 2.1em; +} +.ui-button-text-icon-secondary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 2.1em .4em 1em; +} +.ui-button-text-icons .ui-button-text { + padding-left: 2.1em; + padding-right: 2.1em; +} +/* no icon support for input elements, provide padding by default */ +input.ui-button { + padding: .4em 1em; +} + +/* button icon element(s) */ +.ui-button-icon-only .ui-icon, +.ui-button-text-icon-primary .ui-icon, +.ui-button-text-icon-secondary .ui-icon, +.ui-button-text-icons .ui-icon, +.ui-button-icons-only .ui-icon { + position: absolute; + top: 50%; + margin-top: -8px; +} +.ui-button-icon-only .ui-icon { + left: 50%; + margin-left: -8px; +} +.ui-button-text-icon-primary .ui-button-icon-primary, +.ui-button-text-icons .ui-button-icon-primary, +.ui-button-icons-only .ui-button-icon-primary { + left: .5em; +} +.ui-button-text-icon-secondary .ui-button-icon-secondary, +.ui-button-text-icons .ui-button-icon-secondary, +.ui-button-icons-only .ui-button-icon-secondary { + right: .5em; +} + +/* button sets */ +.ui-buttonset { + margin-right: 7px; +} +.ui-buttonset .ui-button { + margin-left: 0; + margin-right: -.3em; +} + +/* workarounds */ +/* reset extra padding in Firefox, see h5bp.com/l */ +input.ui-button::-moz-focus-inner, +button.ui-button::-moz-focus-inner { + border: 0; + padding: 0; +} +.ui-datepicker { + width: 17em; + padding: .2em .2em 0; + display: none; +} +.ui-datepicker .ui-datepicker-header { + position: relative; + padding: .2em 0; +} +.ui-datepicker .ui-datepicker-prev, +.ui-datepicker .ui-datepicker-next { + position: absolute; + top: 2px; + width: 1.8em; + height: 1.8em; +} +.ui-datepicker .ui-datepicker-prev-hover, +.ui-datepicker .ui-datepicker-next-hover { + top: 1px; +} +.ui-datepicker .ui-datepicker-prev { + left: 2px; +} +.ui-datepicker .ui-datepicker-next { + right: 2px; +} +.ui-datepicker .ui-datepicker-prev-hover { + left: 1px; +} +.ui-datepicker .ui-datepicker-next-hover { + right: 1px; +} +.ui-datepicker .ui-datepicker-prev span, +.ui-datepicker .ui-datepicker-next span { + display: block; + position: absolute; + left: 50%; + margin-left: -8px; + top: 50%; + margin-top: -8px; +} +.ui-datepicker .ui-datepicker-title { + margin: 0 2.3em; + line-height: 1.8em; + text-align: center; +} +.ui-datepicker .ui-datepicker-title select { + font-size: 1em; + margin: 1px 0; +} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { + width: 49%; +} +.ui-datepicker table { + width: 100%; + font-size: .9em; + border-collapse: collapse; + margin: 0 0 .4em; +} +.ui-datepicker th { + padding: .7em .3em; + text-align: center; + font-weight: bold; + border: 0; +} +.ui-datepicker td { + border: 0; + padding: 1px; +} +.ui-datepicker td span, +.ui-datepicker td a { + display: block; + padding: .2em; + text-align: right; + text-decoration: none; +} +.ui-datepicker .ui-datepicker-buttonpane { + background-image: none; + margin: .7em 0 0 0; + padding: 0 .2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} +.ui-datepicker .ui-datepicker-buttonpane button { + float: right; + margin: .5em .2em .4em; + cursor: pointer; + padding: .2em .6em .3em .6em; + width: auto; + overflow: visible; +} +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { + float: left; +} + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { + width: auto; +} +.ui-datepicker-multi .ui-datepicker-group { + float: left; +} +.ui-datepicker-multi .ui-datepicker-group table { + width: 95%; + margin: 0 auto .4em; +} +.ui-datepicker-multi-2 .ui-datepicker-group { + width: 50%; +} +.ui-datepicker-multi-3 .ui-datepicker-group { + width: 33.3%; +} +.ui-datepicker-multi-4 .ui-datepicker-group { + width: 25%; +} +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { + border-left-width: 0; +} +.ui-datepicker-multi .ui-datepicker-buttonpane { + clear: left; +} +.ui-datepicker-row-break { + clear: both; + width: 100%; + font-size: 0; +} + +/* RTL support */ +.ui-datepicker-rtl { + direction: rtl; +} +.ui-datepicker-rtl .ui-datepicker-prev { + right: 2px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next { + left: 2px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-prev:hover { + right: 1px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next:hover { + left: 1px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane { + clear: right; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button { + float: left; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, +.ui-datepicker-rtl .ui-datepicker-group { + float: right; +} +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { + border-right-width: 0; + border-left-width: 1px; +} +.ui-dialog { + overflow: hidden; + position: absolute; + top: 0; + left: 0; + padding: .2em; + outline: 0; +} +.ui-dialog .ui-dialog-titlebar { + padding: .4em 1em; + position: relative; +} +.ui-dialog .ui-dialog-title { + float: left; + margin: .1em 0; + white-space: nowrap; + width: 90%; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute; + right: .3em; + top: 50%; + width: 20px; + margin: -10px 0 0 0; + padding: 1px; + height: 20px; +} +.ui-dialog .ui-dialog-content { + position: relative; + border: 0; + padding: .5em 1em; + background: none; + overflow: auto; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: .5em; + padding: .3em 1em .5em .4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: .5em .4em .5em 0; + cursor: pointer; +} +.ui-dialog .ui-resizable-se { + width: 12px; + height: 12px; + right: -5px; + bottom: -5px; + background-position: 16px 16px; +} +.ui-draggable .ui-dialog-titlebar { + cursor: move; +} +.ui-draggable-handle { + -ms-touch-action: none; + touch-action: none; +} +.ui-menu { + list-style: none; + padding: 0; + margin: 0; + display: block; + outline: none; +} +.ui-menu .ui-menu { + position: absolute; +} +.ui-menu .ui-menu-item { + position: relative; + margin: 0; + padding: 3px 1em 3px .4em; + cursor: pointer; + min-height: 0; /* support: IE7 */ + /* support: IE10, see #8844 */ + list-style-image: url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"); +} +.ui-menu .ui-menu-divider { + margin: 5px 0; + height: 0; + font-size: 0; + line-height: 0; + border-width: 1px 0 0 0; +} +.ui-menu .ui-state-focus, +.ui-menu .ui-state-active { + margin: -1px; +} + +/* icon support */ +.ui-menu-icons { + position: relative; +} +.ui-menu-icons .ui-menu-item { + padding-left: 2em; +} + +/* left-aligned */ +.ui-menu .ui-icon { + position: absolute; + top: 0; + bottom: 0; + left: .2em; + margin: auto 0; +} + +/* right-aligned */ +.ui-menu .ui-menu-icon { + left: auto; + right: 0; +} +.ui-progressbar { + height: 2em; + text-align: left; + overflow: hidden; +} +.ui-progressbar .ui-progressbar-value { + margin: -1px; + height: 100%; +} +.ui-progressbar .ui-progressbar-overlay { + background: url("images/animated-overlay.gif"); + height: 100%; + filter: alpha(opacity=25); + opacity: 0.25; +} +.ui-progressbar-indeterminate .ui-progressbar-value { + background-image: none; +} +.ui-resizable { + position: relative; +} +.ui-resizable-handle { + position: absolute; + font-size: 0.1px; + display: block; + -ms-touch-action: none; + touch-action: none; +} +.ui-resizable-disabled .ui-resizable-handle, +.ui-resizable-autohide .ui-resizable-handle { + display: none; +} +.ui-resizable-n { + cursor: n-resize; + height: 7px; + width: 100%; + top: -5px; + left: 0; +} +.ui-resizable-s { + cursor: s-resize; + height: 7px; + width: 100%; + bottom: -5px; + left: 0; +} +.ui-resizable-e { + cursor: e-resize; + width: 7px; + right: -5px; + top: 0; + height: 100%; +} +.ui-resizable-w { + cursor: w-resize; + width: 7px; + left: -5px; + top: 0; + height: 100%; +} +.ui-resizable-se { + cursor: se-resize; + width: 12px; + height: 12px; + right: 1px; + bottom: 1px; +} +.ui-resizable-sw { + cursor: sw-resize; + width: 9px; + height: 9px; + left: -5px; + bottom: -5px; +} +.ui-resizable-nw { + cursor: nw-resize; + width: 9px; + height: 9px; + left: -5px; + top: -5px; +} +.ui-resizable-ne { + cursor: ne-resize; + width: 9px; + height: 9px; + right: -5px; + top: -5px; +} +.ui-selectable { + -ms-touch-action: none; + touch-action: none; +} +.ui-selectable-helper { + position: absolute; + z-index: 100; + border: 1px dotted black; +} +.ui-selectmenu-menu { + padding: 0; + margin: 0; + position: absolute; + top: 0; + left: 0; + display: none; +} +.ui-selectmenu-menu .ui-menu { + overflow: auto; + /* Support: IE7 */ + overflow-x: hidden; + padding-bottom: 1px; +} +.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup { + font-size: 1em; + font-weight: bold; + line-height: 1.5; + padding: 2px 0.4em; + margin: 0.5em 0 0 0; + height: auto; + border: 0; +} +.ui-selectmenu-open { + display: block; +} +.ui-selectmenu-button { + display: inline-block; + overflow: hidden; + position: relative; + text-decoration: none; + cursor: pointer; +} +.ui-selectmenu-button span.ui-icon { + right: 0.5em; + left: auto; + margin-top: -8px; + position: absolute; + top: 50%; +} +.ui-selectmenu-button span.ui-selectmenu-text { + text-align: left; + padding: 0.4em 2.1em 0.4em 1em; + display: block; + line-height: 1.4; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ui-slider { + position: relative; + text-align: left; +} +.ui-slider .ui-slider-handle { + position: absolute; + z-index: 2; + width: 1.2em; + height: 1.2em; + cursor: default; + -ms-touch-action: none; + touch-action: none; +} +.ui-slider .ui-slider-range { + position: absolute; + z-index: 1; + font-size: .7em; + display: block; + border: 0; + background-position: 0 0; +} + +/* For IE8 - See #6727 */ +.ui-slider.ui-state-disabled .ui-slider-handle, +.ui-slider.ui-state-disabled .ui-slider-range { + filter: inherit; +} + +.ui-slider-horizontal { + height: .8em; +} +.ui-slider-horizontal .ui-slider-handle { + top: -.3em; + margin-left: -.6em; +} +.ui-slider-horizontal .ui-slider-range { + top: 0; + height: 100%; +} +.ui-slider-horizontal .ui-slider-range-min { + left: 0; +} +.ui-slider-horizontal .ui-slider-range-max { + right: 0; +} + +.ui-slider-vertical { + width: .8em; + height: 100px; +} +.ui-slider-vertical .ui-slider-handle { + left: -.3em; + margin-left: 0; + margin-bottom: -.6em; +} +.ui-slider-vertical .ui-slider-range { + left: 0; + width: 100%; +} +.ui-slider-vertical .ui-slider-range-min { + bottom: 0; +} +.ui-slider-vertical .ui-slider-range-max { + top: 0; +} +.ui-sortable-handle { + -ms-touch-action: none; + touch-action: none; +} +.ui-spinner { + position: relative; + display: inline-block; + overflow: hidden; + padding: 0; + vertical-align: middle; +} +.ui-spinner-input { + border: none; + background: none; + color: inherit; + padding: 0; + margin: .2em 0; + vertical-align: middle; + margin-left: .4em; + margin-right: 22px; +} +.ui-spinner-button { + width: 16px; + height: 50%; + font-size: .5em; + padding: 0; + margin: 0; + text-align: center; + position: absolute; + cursor: default; + display: block; + overflow: hidden; + right: 0; +} +/* more specificity required here to override default borders */ +.ui-spinner a.ui-spinner-button { + border-top: none; + border-bottom: none; + border-right: none; +} +/* vertically center icon */ +.ui-spinner .ui-icon { + position: absolute; + margin-top: -8px; + top: 50%; + left: 0; +} +.ui-spinner-up { + top: 0; +} +.ui-spinner-down { + bottom: 0; +} + +/* TR overrides */ +.ui-spinner .ui-icon-triangle-1-s { + /* need to fix icons sprite */ + background-position: -65px -16px; +} +.ui-tabs { + position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ + padding: .2em; +} +.ui-tabs .ui-tabs-nav { + margin: 0; + padding: .2em .2em 0; +} +.ui-tabs .ui-tabs-nav li { + list-style: none; + float: left; + position: relative; + top: 0; + margin: 1px .2em 0 0; + border-bottom-width: 0; + padding: 0; + white-space: nowrap; +} +.ui-tabs .ui-tabs-nav .ui-tabs-anchor { + float: left; + padding: .5em 1em; + text-decoration: none; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active { + margin-bottom: -1px; + padding-bottom: 1px; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor, +.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor, +.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor { + cursor: text; +} +.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor { + cursor: pointer; +} +.ui-tabs .ui-tabs-panel { + display: block; + border-width: 0; + padding: 1em 1.4em; + background: none; +} +.ui-tooltip { + padding: 8px; + position: absolute; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; +} +body .ui-tooltip { + border-width: 2px; +} + +/* Component containers +----------------------------------*/ +.ui-widget { + font-family: Verdana,Arial,sans-serif; + font-size: 1.1em; +} +.ui-widget .ui-widget { + font-size: 1em; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Verdana,Arial,sans-serif; + font-size: 1em; +} +.ui-widget-content { + border: 1px solid #aaaaaa; + background: #ffffff url("images/ui-bg_flat_75_ffffff_40x100.png") 50% 50% repeat-x; + color: #222222; +} +.ui-widget-content a { + color: #222222; +} +.ui-widget-header { + border: 1px solid #aaaaaa; + background: #cccccc url("images/ui-bg_highlight-soft_75_cccccc_1x100.png") 50% 50% repeat-x; + color: #222222; + font-weight: bold; +} +.ui-widget-header a { + color: #222222; +} + +/* Interaction states +----------------------------------*/ +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + border: 1px solid #d3d3d3; + background: #e6e6e6 url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x; + font-weight: normal; + color: #555555; +} +.ui-state-default a, +.ui-state-default a:link, +.ui-state-default a:visited { + color: #555555; + text-decoration: none; +} +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover, +.ui-state-focus, +.ui-widget-content .ui-state-focus, +.ui-widget-header .ui-state-focus { + border: 1px solid #999999; + background: #dadada url("images/ui-bg_glass_75_dadada_1x400.png") 50% 50% repeat-x; + font-weight: normal; + color: #212121; +} +.ui-state-hover a, +.ui-state-hover a:hover, +.ui-state-hover a:link, +.ui-state-hover a:visited, +.ui-state-focus a, +.ui-state-focus a:hover, +.ui-state-focus a:link, +.ui-state-focus a:visited { + color: #212121; + text-decoration: none; +} +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #aaaaaa; + background: #ffffff url("images/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x; + font-weight: normal; + color: #212121; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #212121; + text-decoration: none; +} + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, +.ui-widget-content .ui-state-highlight, +.ui-widget-header .ui-state-highlight { + border: 1px solid #fcefa1; + background: #fbf9ee url("images/ui-bg_glass_55_fbf9ee_1x400.png") 50% 50% repeat-x; + color: #363636; +} +.ui-state-highlight a, +.ui-widget-content .ui-state-highlight a, +.ui-widget-header .ui-state-highlight a { + color: #363636; +} +.ui-state-error, +.ui-widget-content .ui-state-error, +.ui-widget-header .ui-state-error { + border: 1px solid #cd0a0a; + background: #fef1ec url("images/ui-bg_glass_95_fef1ec_1x400.png") 50% 50% repeat-x; + color: #cd0a0a; +} +.ui-state-error a, +.ui-widget-content .ui-state-error a, +.ui-widget-header .ui-state-error a { + color: #cd0a0a; +} +.ui-state-error-text, +.ui-widget-content .ui-state-error-text, +.ui-widget-header .ui-state-error-text { + color: #cd0a0a; +} +.ui-priority-primary, +.ui-widget-content .ui-priority-primary, +.ui-widget-header .ui-priority-primary { + font-weight: bold; +} +.ui-priority-secondary, +.ui-widget-content .ui-priority-secondary, +.ui-widget-header .ui-priority-secondary { + opacity: .7; + filter:Alpha(Opacity=70); + font-weight: normal; +} +.ui-state-disabled, +.ui-widget-content .ui-state-disabled, +.ui-widget-header .ui-state-disabled { + opacity: .35; + filter:Alpha(Opacity=35); + background-image: none; +} +.ui-state-disabled .ui-icon { + filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ +} + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + width: 16px; + height: 16px; +} +.ui-icon, +.ui-widget-content .ui-icon { + background-image: url("images/ui-icons_222222_256x240.png"); +} +.ui-widget-header .ui-icon { + background-image: url("images/ui-icons_222222_256x240.png"); +} +.ui-state-default .ui-icon { + background-image: url("images/ui-icons_888888_256x240.png"); +} +.ui-state-hover .ui-icon, +.ui-state-focus .ui-icon { + background-image: url("images/ui-icons_454545_256x240.png"); +} +.ui-state-active .ui-icon { + background-image: url("images/ui-icons_454545_256x240.png"); +} +.ui-state-highlight .ui-icon { + background-image: url("images/ui-icons_2e83ff_256x240.png"); +} +.ui-state-error .ui-icon, +.ui-state-error-text .ui-icon { + background-image: url("images/ui-icons_cd0a0a_256x240.png"); +} + +/* positioning */ +.ui-icon-blank { background-position: 16px 16px; } +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-on { background-position: -96px -144px; } +.ui-icon-radio-off { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 4px; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 4px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 4px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 4px; +} + +/* Overlays */ +.ui-widget-overlay { + background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); +} +.ui-widget-shadow { + margin: -8px 0 0 -8px; + padding: 8px; + background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); + border-radius: 8px; +} diff --git a/software-license-manager/includes/slm-api-listener.php b/software-license-manager/includes/slm-api-listener.php new file mode 100644 index 0000000..23d8812 --- /dev/null +++ b/software-license-manager/includes/slm-api-listener.php @@ -0,0 +1,350 @@ +creation_api_listener(); + $this->activation_api_listener(); + $this->deactivation_api_listener(); + $this->check_api_listener(); + } + } + + function creation_api_listener() { + if (isset($_REQUEST['slm_action']) && trim($_REQUEST['slm_action']) == 'slm_create_new') { + //Handle the licene creation API query + global $slm_debug_logger; + + $options = get_option('slm_plugin_options'); + $lic_key_prefix = $options['lic_prefix']; + + SLM_API_Utility::verify_secret_key_for_creation(); //Verify the secret key first. + + $slm_debug_logger->log_debug("API - license creation (slm_create_new) request received."); + + //Action hook + do_action('slm_api_listener_slm_create_new'); + + $fields = array(); + if (isset($_REQUEST['license_key']) && !empty($_REQUEST['license_key'])){ + $fields['license_key'] = strip_tags($_REQUEST['license_key']);//Use the key you pass via the request + } + else{ + $fields['license_key'] = uniqid($lic_key_prefix);//Use random generated key + } + $fields['lic_status'] = 'pending'; + $fields['first_name'] = wp_unslash(strip_tags($_REQUEST['first_name'])); + $fields['last_name'] = wp_unslash(strip_tags($_REQUEST['last_name'])); + $fields['email'] = strip_tags($_REQUEST['email']); + $fields['company_name'] = isset( $_REQUEST['company_name'] ) ? wp_unslash( strip_tags( $_REQUEST['company_name'] ) ) : ''; + $fields['txn_id'] = strip_tags($_REQUEST['txn_id']); + + if (empty($_REQUEST['max_allowed_domains'])) { + $fields['max_allowed_domains'] = $options['default_max_domains']; + } + else { + $fields['max_allowed_domains'] = strip_tags($_REQUEST['max_allowed_domains']); + } + if (empty($_REQUEST['max_allowed_devices'])) { + $fields['max_allowed_devices'] = $options['default_max_devices']; + } + else { + $fields['max_allowed_devices'] = strip_tags($_REQUEST['max_allowed_devices']); + } + $fields['date_created'] = isset($_REQUEST['date_created'])?strip_tags($_REQUEST['date_created']):date("Y-m-d"); + $fields['date_expiry'] = isset($_REQUEST['date_expiry'])?strip_tags($_REQUEST['date_expiry']):''; + $fields['product_ref'] = isset( $_REQUEST['product_ref'] ) ? wp_unslash( strip_tags( $_REQUEST['product_ref'] ) ) : ''; + + global $wpdb; + $tbl_name = SLM_TBL_LICENSE_KEYS; + $result = $wpdb->insert($tbl_name, $fields); + if ($result === false) { + //error inserting + $args = (array('result' => 'error', 'message' => 'License creation failed', 'error_code' => SLM_Error_Codes::CREATE_FAILED)); + SLM_API_Utility::output_api_response($args); + } else { + $args = (array('result' => 'success', 'message' => 'License successfully created', 'key' => $fields['license_key'])); + SLM_API_Utility::output_api_response($args); + } + } + } + + /* + * Query Parameters + * 1) slm_action = slm_create_new + * 2) secret_key + * 3) license_key + * 4) registered_domain (optional) + */ + + function activation_api_listener() { + if (isset($_REQUEST['slm_action']) && trim($_REQUEST['slm_action']) == 'slm_activate') { + //Handle the license activation API query + global $slm_debug_logger; + + SLM_API_Utility::verify_secret_key(); //Verify the secret key first. + + $slm_debug_logger->log_debug("API - license activation (slm_activate) request received."); + + //Action hook + do_action('slm_api_listener_slm_activate'); + + $fields = array(); + $fields['lic_key'] = trim(strip_tags($_REQUEST['license_key'])); + $fields['registered_domain'] = trim(wp_unslash(strip_tags($_REQUEST['registered_domain']))); //gethostbyaddr($_SERVER['REMOTE_ADDR']); + $fields['registered_devices'] = trim(wp_unslash(strip_tags($_REQUEST['registered_devices']))); //client ip or machine name + $fields['item_reference'] = trim(strip_tags($_REQUEST['item_reference'])); + + $slm_debug_logger->log_debug("License key: " . $fields['lic_key'] . " Domain: " . $fields['registered_domain']); + $slm_debug_logger->log_debug("License key: " . $fields['lic_key'] . " Device: " . $fields['registered_devices']); + + global $wpdb; + $tbl_name = SLM_TBL_LICENSE_KEYS; + $reg_table = SLM_TBL_LIC_DOMAIN; + $reg_table_devices = SLM_TBL_LIC_DEVICES; + + $key = $fields['lic_key']; + + // $sql_prep0 = $wpdb->prepare("SELECT * FROM $tbl_name WHERE license_key = %s", $key); + $sql_prep1 = $wpdb->prepare("SELECT * FROM $tbl_name WHERE license_key = %s", $key); + $retLic = $wpdb->get_row($sql_prep1, OBJECT); + // $retLicDevices = $wpdb->get_row($sql_prep0, OBJECT); + + $sql_prep2 = $wpdb->prepare("SELECT * FROM $reg_table WHERE lic_key = %s", $key); + $reg_domains = $wpdb->get_results($sql_prep2, OBJECT); + + $sql_prep3 = $wpdb->prepare("SELECT * FROM $reg_table_devices WHERE lic_key = %s", $key); + $reg_devices = $wpdb->get_results($sql_prep3, OBJECT); + + if ($retLic) { + if ($retLic->lic_status == 'blocked') { + $args = (array('result' => 'error', 'message' => 'Your License key is blocked', 'error_code' => SLM_Error_Codes::LICENSE_BLOCKED)); + SLM_API_Utility::output_api_response($args); + } + elseif ($retLic->lic_status == 'expired') { + $args = (array('result' => 'error', 'message' => 'Your License key has expired', 'error_code' => SLM_Error_Codes::LICENSE_EXPIRED)); + SLM_API_Utility::output_api_response($args); + } + + if (isset($_REQUEST['registered_domain']) && !empty($_REQUEST['registered_domain'])) { + if (count($reg_domains) < floor($retLic->max_allowed_domains)) { + foreach ($reg_domains as $reg_domain) { + if (isset($_REQUEST['migrate_from']) && (trim($_REQUEST['migrate_from']) == $reg_domain->registered_domain)) { + $wpdb->update($reg_table, array('registered_domain' => $fields['registered_domain']), array('registered_domain' => trim(strip_tags($_REQUEST['migrate_from'])))); + $args = (array('result' => 'success', 'message' => 'Registered domain has been updated')); + SLM_API_Utility::output_api_response($args); + } + if ($fields['registered_domain'] == $reg_domain->registered_domain) { + $args = (array('result' => 'error', 'message' => 'License key already in use on ' . $reg_domain->registered_domain, 'error_code' => SLM_Error_Codes::LICENSE_IN_USE)); + SLM_API_Utility::output_api_response($args); + } + } + + $fields['lic_key_id'] = $retLic->id; + $wpdb->insert($reg_table, $fields); + + $slm_debug_logger->log_debug("Updating license key status to active for domain."); + $data = array('lic_status' => 'active'); + $where = array('id' => $retLic->id); + $updated = $wpdb->update($tbl_name, $data, $where); + + $args = (array('result' => 'success', 'message' => 'License key activated')); + SLM_API_Utility::output_api_response($args); + } + else { + $args = (array('result' => 'error', 'message' => 'Reached maximum allowable domains', 'error_code' => SLM_Error_Codes::REACHED_MAX_DOMAINS)); + SLM_API_Utility::output_api_response($args); + } + } + + + if (isset($_REQUEST['registered_devices']) && !empty($_REQUEST['registered_devices'])) { + + if (count($reg_devices) < floor($retLic->max_allowed_devices)) { + + foreach ($reg_devices as $reg_devices) { + if (isset($_REQUEST['migrate_from']) && (trim($_REQUEST['migrate_from']) == $reg_devices->registered_devices)) { + + $wpdb->update($reg_table_devices, array('registered_devices' => $fields['registered_devices']), array('registered_devices' => trim(strip_tags($_REQUEST['migrate_from'])))); + $devices_args = (array('result' => 'success', 'message' => 'Registered device has been updated')); + SLM_API_Utility::output_api_response($devices_args); + } + if ($fields['registered_devices'] == $reg_devices->registered_devices) { + $devices_args = (array('result' => 'error', 'message' => 'License key already in use on ' . $reg_devices->registered_devices, 'error_code' => SLM_Error_Codes::LICENSE_IN_USE)); + SLM_API_Utility::output_api_response($devices_args); + } + } + + $fields['lic_key_id'] = $retLic->id; + $wpdb->insert($reg_table_devices, $fields); + + $slm_debug_logger->log_debug("Updating license key status to active for device."); + $data = array('lic_status' => 'active'); + $where = array('id' => $retLic->id); + $updated = $wpdb->update($tbl_name, $data, $where); + + $args = (array('result' => 'success', 'message' => 'License key activated')); + SLM_API_Utility::output_api_response($args); + } + + else { + $args = (array('result' => 'error', 'message' => 'Reached maximum allowable devices', 'error_code' => SLM_Error_Codes::REACHED_MAX_DEVICES)); + SLM_API_Utility::output_api_response($args); + } + } + + } else { + $args = (array('result' => 'error', 'message' => 'Invalid license key', 'error_code' => SLM_Error_Codes::LICENSE_INVALID)); + SLM_API_Utility::output_api_response($args); + } + } + } + + // TODO : add support for devices deactivation + + function deactivation_api_listener() { + if (isset($_REQUEST['slm_action']) && trim($_REQUEST['slm_action']) == 'slm_deactivate') { + //Handle the license deactivation API query + global $slm_debug_logger; + + SLM_API_Utility::verify_secret_key(); //Verify the secret key first. + + $slm_debug_logger->log_debug("API - license deactivation (slm_deactivate) request received."); + + //Action hook + do_action('slm_api_listener_slm_deactivate'); + + $registered_domain = trim(wp_unslash(strip_tags($_REQUEST['registered_domain']))); + $license_key = trim(strip_tags($_REQUEST['license_key'])); + $slm_debug_logger->log_debug("License key: " . $license_key . " Domain: " . $registered_domain); + $registered_devices = trim(wp_unslash(strip_tags($_REQUEST['registered_devices']))); + + global $wpdb; + + if (isset($_REQUEST['registered_domain']) && !empty($_REQUEST['registered_domain'])) { + if (empty($_REQUEST['registered_domain'])) { + $args = (array('result' => 'error', 'message' => 'Registered domain information is missing', 'error_code' => SLM_Error_Codes::DOMAIN_MISSING)); + SLM_API_Utility::output_api_response($args); + } + else { + $registered_dom_table = SLM_TBL_LIC_DOMAIN; + $sql_prep = $wpdb->prepare("DELETE FROM $registered_dom_table WHERE lic_key=%s AND registered_domain=%s", $license_key, $registered_domain); + $delete = $wpdb->query($sql_prep); + + if ($delete === false) { + $slm_debug_logger->log_debug("Error - failed to delete the registered domain from the database."); + } + else if ($delete == 0) { + $args = (array('result' => 'error', 'message' => 'The license key on this domain is already inactive', 'error_code' => SLM_Error_Codes::DOMAIN_ALREADY_INACTIVE)); + SLM_API_Utility::output_api_response($args); + } + else { + $args = (array('result' => 'success', 'message' => 'The license key has been deactivated for this domain')); + SLM_API_Utility::output_api_response($args); + } + } + } + if (isset($_REQUEST['registered_devices']) && !empty($_REQUEST['registered_devices'])) { + // devices deactivation + if (empty($_REQUEST['registered_devices'])) { + $args_ = (array('result' => 'error', 'message' => 'Registered device information is missing', 'error_code' => SLM_Error_Codes::DOMAIN_MISSING)); + SLM_API_Utility::output_api_response($args_); + } + else { + $registered_device_table = SLM_TBL_LIC_DEVICES; + $sql_prep2 = $wpdb->prepare("DELETE FROM $registered_device_table WHERE lic_key=%s AND registered_devices=%s", $license_key, $registered_devices); + $delete2 = $wpdb->query($sql_prep2); + + if ($delete2 === false) { + $slm_debug_logger->log_debug("Error - failed to delete the registered device from the database."); + } + else if ($delete2 == 0) { + $args_ = (array('result' => 'error', 'message' => 'The license key on this device is already inactive', 'error_code' => SLM_Error_Codes::DOMAIN_ALREADY_INACTIVE)); + SLM_API_Utility::output_api_response($args_); + } + else { + $args_ = (array('result' => 'success', 'message' => 'The license key has been deactivated for this device')); + SLM_API_Utility::output_api_response($args_); + } + } + } + } + } + + function check_api_listener() { + if (isset($_REQUEST['slm_action']) && trim($_REQUEST['slm_action']) == 'slm_check') { + //Handle the license check API query + global $slm_debug_logger; + + SLM_API_Utility::verify_secret_key(); //Verify the secret key first. + + $slm_debug_logger->log_debug("API - license check (slm_check) request received."); + + $fields = array(); + $fields['lic_key'] = trim(strip_tags($_REQUEST['license_key'])); + $slm_debug_logger->log_debug("License key: " . $fields['lic_key']); + + //Action hook + do_action('slm_api_listener_slm_check'); + + global $wpdb; + $tbl_name = SLM_TBL_LICENSE_KEYS; + $reg_table = SLM_TBL_LIC_DOMAIN; + $reg_table_devices = SLM_TBL_LIC_DEVICES; + $key = $fields['lic_key']; + $sql_prep1 = $wpdb->prepare("SELECT * FROM $tbl_name WHERE license_key = %s", $key); + $retLic = $wpdb->get_row($sql_prep1, OBJECT); + + $sql_prep2 = $wpdb->prepare("SELECT * FROM $reg_table WHERE lic_key = %s", $key); + $sql_prep3 = $wpdb->prepare("SELECT * FROM $reg_table_devices WHERE lic_key = %s", $key); + + $reg_domains = $wpdb->get_results($sql_prep2, OBJECT); + $reg_devices = $wpdb->get_results($sql_prep3, OBJECT); + if ($retLic) {//A license key exists + $args = (array( + 'result' => 'success', + 'code' => '200', + 'message' => 'License key details retrieved.', + 'status' => $retLic->lic_status, + 'max_allowed_domains' => $retLic->max_allowed_domains, + 'max_allowed_devices' => $retLic->max_allowed_devices, + 'email' => $retLic->email, + 'first_name' => $retLic->first_name, + 'last_name' => $retLic->last_name, + // 'until' => $retLic->until, //until what version license is supported + 'registered_domains' => $reg_domains, + 'registered_devices' => $reg_devices, + 'license_key' => $retLic->license_key, + 'date_created' => $retLic->date_created, + 'date_renewed' => $retLic->date_renewed, + 'date_expiry' => $retLic->date_expiry, + 'product_ref' => $retLic->product_ref, + 'first_name' => $retLic->first_name, + 'last_name' => $retLic->last_name, + 'company_name' => $retLic->company_name, + 'txn_id' => $retLic->txn_id, + + )); + //Output the license details + SLM_API_Utility::output_api_response($args); + } + else { + $args = (array('result' => 'error', 'message' => 'Invalid license key', 'error_code' => SLM_Error_Codes::LICENSE_INVALID)); + SLM_API_Utility::output_api_response($args); + } + } + } + +} \ No newline at end of file diff --git a/software-license-manager/includes/slm-api-utility.php b/software-license-manager/includes/slm-api-utility.php new file mode 100644 index 0000000..75eca81 --- /dev/null +++ b/software-license-manager/includes/slm-api-utility.php @@ -0,0 +1,57 @@ +log_debug('API Response - Result: ' . $args['result'] . ' Message: ' . $args['message']); + //Send response + header('Content-Type: application/json'); //ERICH + echo json_encode($args); + exit(0); + } + + static function verify_secret_key() { + $slm_options = get_option('slm_plugin_options'); + $right_secret_key = $slm_options['lic_verification_secret']; + $received_secret_key = strip_tags($_REQUEST['secret_key']); + if ($received_secret_key != $right_secret_key) { + $args = (array('result' => 'error', 'message' => 'Verification API secret key is invalid', 'error_code' => SLM_Error_Codes::VERIFY_KEY_INVALID)); + SLM_API_Utility::output_api_response($args); + } + } + + static function verify_secret_key_for_creation() { + $slm_options = get_option('slm_plugin_options'); + $right_secret_key = $slm_options['lic_creation_secret']; + $received_secret_key = strip_tags($_REQUEST['secret_key']); + if ($received_secret_key != $right_secret_key) { + $args = (array('result' => 'error', 'message' => 'License Creation API secret key is invalid', 'error_code' => SLM_Error_Codes::CREATE_KEY_INVALID)); + SLM_API_Utility::output_api_response($args); + } + } + + static function insert_license_data_internal($fields) { + /* The fields array should have values for the following keys + //$fields['license_key'] + //$fields['lic_status'] + //$fields['first_name'] + //$fields['last_name'] + //$fields['email'] + //$fields['company_name'] + //$fields['txn_id'] + //$fields['max_allowed_domains'] + */ + global $wpdb; + $tbl_name = SLM_TBL_LICENSE_KEYS; + $fields = array_filter($fields);//Remove any null values. + $result = $wpdb->insert($tbl_name, $fields); + } + +} \ No newline at end of file diff --git a/software-license-manager/includes/slm-error-codes.php b/software-license-manager/includes/slm-error-codes.php new file mode 100644 index 0000000..cdad6ce --- /dev/null +++ b/software-license-manager/includes/slm-error-codes.php @@ -0,0 +1,20 @@ +load_scripts(); + + //Add other init time operations here + add_action ('slm_daily_cron_event', array(&$this, 'slm_daily_cron_event_handler')); + } + + function load_scripts() + { + //Load all common scripts and styles only + wp_enqueue_script('jquery'); + + //Load all admin side scripts and styles only + if(is_admin()) + { + wp_enqueue_script('jquery-ui-datepicker'); + wp_enqueue_script('wplm-custom-admin-js', WP_LICENSE_MANAGER_URL . '/js/wplm-custom-admin.js', array( 'jquery-ui-dialog' ));//admin only custom js code + + if (isset($_GET['page']) && $_GET['page'] == 'wp_lic_mgr_addedit') {//Only include if we are in the license add/edit interface + wp_enqueue_style('jquery-ui-style', WP_LICENSE_MANAGER_URL .'/css/jquery-ui.css'); + } + //wp_enqueue_style('dialogStylesheet', includes_url().'css/jquery-ui-dialog.css'); + } + } + + function slm_daily_cron_event_handler() + { + $options = get_option('slm_plugin_options'); + + do_action('slm_daily_cron_event_triggered'); + + if ( isset($options['enable_auto_key_expiry']) && $options['enable_auto_key_expiry'] == '1'){ + //Do the auto key expiry task + SLM_Debug_Logger::log_debug_st("SLM daily cronjob - auto expiry of license key is enabled."); + SLM_Utility::do_auto_key_expiry(); + } + + //Do any ohter daily cronjob tasks. + + } + +}//End of class \ No newline at end of file diff --git a/software-license-manager/includes/slm-meta-boxes.php b/software-license-manager/includes/slm-meta-boxes.php new file mode 100644 index 0000000..00ed4e1 --- /dev/null +++ b/software-license-manager/includes/slm-meta-boxes.php @@ -0,0 +1,64 @@ +'; + + // License Field + woocommerce_wp_text_input( + array( + 'id' => 'amount_of_licenses['. $loop .']', + 'label' => __( 'Number of Licenses (domain)', 'woocommerce' ), + 'placeholder' => '1-20', + 'desc_tip' => true, + 'wrapper_class' => 'form-row form-row-first', + 'description' => __( 'Ideal for themes, plugins, and websites', 'woocommerce' ), + 'value' => get_post_meta($variation->ID, 'amount_of_licenses', true) + ) + ); + + echo ""; + + echo '
    '; + + // License Field + woocommerce_wp_text_input( + array( + 'id' => 'amount_of_licenses_devices['. $loop .']', + 'label' => __( 'Number of Licenses (devices)', 'woocommerce' ), + 'placeholder' => '1-20', + 'desc_tip' => true, + 'wrapper_class' => 'form-row form-row-first', + 'description' => __( 'Ideal for software and apps.', 'woocommerce' ), + 'value' => get_post_meta($variation->ID, 'amount_of_licenses_devices', true) + ) + ); + + echo "
    "; + +} + +/** Save new fields for variations */ +function save_variation_fields( $variation_id, $i) { + + // License Field + $text_field = stripslashes( $_POST['amount_of_licenses'][$i] ); + update_post_meta( $variation_id, 'amount_of_licenses', esc_attr( $text_field ) ); + + $text_field = stripslashes( $_POST['amount_of_licenses_devices'][$i] ); + update_post_meta( $variation_id, 'amount_of_licenses_devices', esc_attr( $text_field ) ); + +} \ No newline at end of file diff --git a/software-license-manager/includes/slm-third-party-integration.php b/software-license-manager/includes/slm-third-party-integration.php new file mode 100644 index 0000000..b873982 --- /dev/null +++ b/software-license-manager/includes/slm-third-party-integration.php @@ -0,0 +1,301 @@ +log_debug("WP eStore integration - checking if a license key needs to be created for this transaction."); + $products_table_name = $wpdb->prefix . "wp_eStore_tbl"; + $slm_data = ""; + + foreach ($cart_items as $current_cart_item) { + $prod_id = $current_cart_item['item_number']; + $qty = $current_cart_item['quantity']; + $retrieved_product = $wpdb->get_row("SELECT * FROM $products_table_name WHERE id = '$prod_id'", OBJECT); + $package_product = eStore_is_package_product($retrieved_product); + if ($package_product) { + $slm_debug_logger->log_debug('Checking license key generation for package/bundle product.'); + $product_ids = explode(',', $retrieved_product->product_download_url); + foreach ($product_ids as $id) { + $id = trim($id); + $retrieved_product_for_specific_id = $wpdb->get_row("SELECT * FROM $products_table_name WHERE id = '$id'", OBJECT); + $slm_data .= slm_estore_check_and_generate_key($retrieved_product_for_specific_id, $payment_data, $cart_items, $qty); + } + } else { + $slm_debug_logger->log_debug('Checking license key generation for single item product.'); + $slm_data .= slm_estore_check_and_generate_key($retrieved_product, $payment_data, $cart_items, $qty); + } + } + + $body = str_replace("{slm_data}", $slm_data, $body); + return $body; +} + +function slm_estore_check_and_generate_key($retrieved_product, $payment_data, $cart_items, $qty=1) { + global $slm_debug_logger; + $license_data = ''; + + if ($retrieved_product->create_license == 1) { + $requested_qty = (int)$qty; + $slm_debug_logger->log_debug('Need to create a license key for this product: ' . $retrieved_product->id . '. Requested qty: ' . $requested_qty); + if($requested_qty > 1){ + //More than 1 qty of the same product + for($i=0; $i < $requested_qty; $i++){ + $slm_key = slm_estore_create_license($retrieved_product, $payment_data, $cart_items); + $license_data .= "\n" . __('Item Name: ', 'slm') . $retrieved_product->name . " - " . __('License Key '.($i+1).': ', 'slm') . $slm_key; + } + } + else { + //Standard 1 qty + $slm_key = slm_estore_create_license($retrieved_product, $payment_data, $cart_items); + $license_data = "\n" . __('Item Name: ', 'slm') . $retrieved_product->name . " - " . __('License Key: ', 'slm') . $slm_key; + } + + $slm_debug_logger->log_debug('Liense data: ' . $license_data); + $license_data = apply_filters('slm_estore_item_license_data', $license_data); + } + return $license_data; +} + +function slm_estore_create_license($retrieved_product, $payment_data, $cart_items) { + global $slm_debug_logger; + global $wpdb; + $product_meta_table_name = WP_ESTORE_PRODUCTS_META_TABLE_NAME; + + //Retrieve the default settings values. + $options = get_option('slm_plugin_options'); + $lic_key_prefix = $options['lic_prefix']; + $max_domains = $options['default_max_domains']; + $max_devices = $options['default_max_devices']; + + //Lets check any product specific configuration. + $prod_id = $retrieved_product->id; + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_domains'", OBJECT); + if ($product_meta) { + //Found product specific SLM config data. + $max_domains = $product_meta->meta_value; + } else { + //Use the default value from settings (the $max_domains variable contains the default value already). + } + + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_devices'", OBJECT); + if ($product_meta) { + //Found product specific SLM config data. + $max_devices = $product_meta->meta_value; + } else { + //Use the default value from settings (the $max_domains variable contains the default value already). + } + + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_devices'", OBJECT); + if ($product_meta) { + //Found product specific SLM config data. + $max_devices = $product_meta->meta_value; + } else { + //Use the default value from settings (the $max_domains variable contains the default value already). + } //Lets check if any product specific expiry date is set + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_date_of_expiry'", OBJECT); + if ($product_meta) { + //Found product specific SLM config data. + $num_days_before_expiry = $product_meta->meta_value; + $slm_date_of_expiry = date('Y-m-d', strtotime('+'.$num_days_before_expiry.' days')); + } else { + //Use the default value (1 year from today). + $current_date_plus_1year = date('Y-m-d', strtotime('+1 year')); + $slm_date_of_expiry = $current_date_plus_1year; + } + + + $fields = array(); + $fields['license_key'] = uniqid($lic_key_prefix); + $fields['lic_status'] = 'pending'; + $fields['first_name'] = $payment_data['first_name']; + $fields['last_name'] = $payment_data['last_name']; + $fields['email'] = $payment_data['payer_email']; + $fields['company_name'] = $payment_data['company_name']; + $fields['txn_id'] = $payment_data['txn_id']; + $fields['max_allowed_domains'] = $max_domains; + $fields['max_allowed_devices'] = $max_devices; + $fields['date_created'] = date("Y-m-d"); //Today's date + $fields['date_expiry'] = $slm_date_of_expiry; + + $slm_debug_logger->log_debug('Inserting license data into the license manager DB table.'); + $fields = array_filter($fields); //Remove any null values. + + + $tbl_name = SLM_TBL_LICENSE_KEYS; + $result = $wpdb->insert($tbl_name, $fields); + if (!$result) { + $slm_debug_logger->log_debug('Notice! initial database table insert failed on license key table (User Email: ' . $fields['email'] . '). Trying again by converting charset', true); + //Convert the default PayPal IPN charset to UTF-8 format + $first_name = mb_convert_encoding($fields['first_name'], "UTF-8", "windows-1252"); + $fields['first_name'] = esc_sql($first_name); + $last_name = mb_convert_encoding($fields['last_name'], "UTF-8", "windows-1252"); + $fields['last_name'] = esc_sql($last_name); + $company_name = mb_convert_encoding($fields['company_name'], "UTF-8", "windows-1252"); + $fields['company_name'] = esc_sql($company_name); + + $result = $wpdb->insert($tbl_name, $fields); + if (!$result) { + $slm_debug_logger->log_debug('Error! Failed to update license key table. DB insert query failed.', false); + } + } + //SLM_API_Utility::insert_license_data_internal($fields); + + return $fields['license_key']; +} + +/* Code to handle the eStore's product add/edit interface for SLM specific product configuration */ +add_filter('eStore_addon_product_settings_filter', 'slm_estore_product_configuration_html', 10, 2); //Render the product add/edit HTML +add_action('eStore_new_product_added', 'slm_estore_new_product_added', 10, 2); //Handle the DB insert after a product add. +add_action('eStore_product_updated', 'slm_estore_product_updated', 10, 2); //Handle the DB update after a product edit. +add_action('eStore_product_deleted', 'slm_estore_product_deleted'); //Handle the DB delete after a product delete. + +function slm_estore_product_configuration_html($product_config_html, $prod_id) { + global $wpdb; + $product_meta_table_name = WP_ESTORE_PRODUCTS_META_TABLE_NAME; + + if (empty($prod_id)) { + //New product add + $slm_max_allowed_domains = ""; + $slm_max_allowed_devices = ""; + $slm_date_of_expiry = ""; + } else { + //Existing product edit + + //Retrieve the max domain value + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_domains'", OBJECT); + if ($product_meta) { + $slm_max_allowed_domains = $product_meta->meta_value; + } else { + $slm_max_allowed_domains = ""; + } + + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_devices'", OBJECT); + if ($product_meta) { + $slm_max_allowed_devices = $product_meta->meta_value; + } else { + $slm_max_allowed_devices = ""; + } + + //Retrieve the expiry date value + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_date_of_expiry'", OBJECT); + if ($product_meta) { + $slm_date_of_expiry = $product_meta->meta_value; + } else { + $slm_date_of_expiry = ""; + } + + } + + $product_config_html .= '
    Software License Manager Plugin (Click to Expand)
    '; + + $product_config_html .= ''; + + $product_config_html .= ''; + + $product_config_html .= ''; + + $product_config_html .= '
    Maximum Allowed Domains'; + $product_config_html .= ''; + $product_config_html .= '

    Number of domains/installs in which this license can be used. Leave blank if you wish to use the default value set in the license manager plugin settings.

    '; + $product_config_html .= '
    Maximum Allowed Devices'; + $product_config_html .= ''; + $product_config_html .= '

    Number of devices in which this license can be used. Leave blank if you wish to use the default value set in the license manager plugin settings.

    '; + $product_config_html .= '
    Number of Days before Expiry'; + $product_config_html .= ' Days'; + $product_config_html .= '

    Number of days before expiry. The expiry date of the license will be set based on this value. For example, if you want the key to expire in 6 months then enter a value of 180.

    '; + $product_config_html .= '
    '; + + return $product_config_html; +} + +function slm_estore_new_product_added($prod_dat_array, $prod_id) { + global $wpdb; + $product_meta_table_name = WP_ESTORE_PRODUCTS_META_TABLE_NAME; + + //Save max domain value + $fields = array(); + $fields['prod_id'] = $prod_id; + $fields['meta_key'] = 'slm_max_allowed_domains'; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_domains']; + $fields['meta_key'] = 'slm_max_allowed_devices'; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_devices']; + $result = $wpdb->insert($product_meta_table_name, $fields); + if (!$result) { + //insert query failed + } + + //Save expiry date value + $fields = array(); + $fields['prod_id'] = $prod_id; + $fields['meta_key'] = 'slm_date_of_expiry'; + $fields['meta_value'] = $prod_dat_array['slm_date_of_expiry']; + $result = $wpdb->insert($product_meta_table_name, $fields); + if (!$result) { + //insert query failed + } + +} + +function slm_estore_product_updated($prod_dat_array, $prod_id) { + global $wpdb; + $product_meta_table_name = WP_ESTORE_PRODUCTS_META_TABLE_NAME; + + //Find the existing value for the max domains field (for the given product) + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_max_allowed_domains'", OBJECT); + if ($product_meta) { + //Found existing value so lets update it + $fields = array(); + $fields['meta_key'] = 'slm_max_allowed_domains'; + $fields['meta_key'] = 'slm_max_allowed_devices'; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_domains']; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_devices']; + $result = $wpdb->update($product_meta_table_name, $fields, array('prod_id' => $prod_id)); + + } else { + //No value for this field was there so lets insert one. + $fields = array(); + $fields['prod_id'] = $prod_id; + $fields['meta_key'] = 'slm_max_allowed_domains'; + $fields['meta_key'] = 'slm_max_allowed_devices'; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_domains']; + $fields['meta_value'] = $prod_dat_array['slm_max_allowed_devices']; + $result = $wpdb->insert($product_meta_table_name, $fields); + } + + //Find the existing value for the expiry date field (for the given product) + $product_meta = $wpdb->get_row("SELECT * FROM $product_meta_table_name WHERE prod_id = '$prod_id' AND meta_key='slm_date_of_expiry'", OBJECT); + if ($product_meta) { + //Found existing value so lets update it + $fields = array(); + $fields['meta_key'] = 'slm_date_of_expiry'; + $fields['meta_value'] = $prod_dat_array['slm_date_of_expiry']; + $result = $wpdb->update($product_meta_table_name, $fields, array('prod_id' => $prod_id)); + + } else { + //No value for this field was there so lets insert one. + $fields = array(); + $fields['prod_id'] = $prod_id; + $fields['meta_key'] = 'slm_date_of_expiry'; + $fields['meta_value'] = $prod_dat_array['slm_date_of_expiry']; + $result = $wpdb->insert($product_meta_table_name, $fields); + } + +} + +function slm_estore_product_deleted($prod_id) { + global $wpdb; + $product_meta_table_name = WP_ESTORE_PRODUCTS_META_TABLE_NAME; + + $result = $wpdb->delete($product_meta_table_name, array('prod_id' => $prod_id, 'meta_key' => 'slm_max_allowed_domains')); + $result = $wpdb->delete($product_meta_table_name, array('prod_id' => $prod_id, 'meta_key' => 'slm_max_allowed_devices')); + $result = $wpdb->delete($product_meta_table_name, array('prod_id' => $prod_id, 'meta_key' => 'slm_date_of_expiry')); +} + +/************************************/ +/*** End of WP eStore integration ***/ +/************************************/ \ No newline at end of file diff --git a/software-license-manager/includes/slm-utility.php b/software-license-manager/includes/slm-utility.php new file mode 100644 index 0000000..eb9a678 --- /dev/null +++ b/software-license-manager/includes/slm-utility.php @@ -0,0 +1,73 @@ +prepare("SELECT * FROM $tbl_name WHERE lic_status !=%s", 'expired');//Load the non-expired keys + $licenses = $wpdb->get_results($sql_prep, OBJECT); + if(!$licenses){ + SLM_Debug_Logger::log_debug_st("do_auto_key_expiry() - no license keys found."); + return false; + } + + foreach($licenses as $license){ + $key = $license->license_key; + $expiry_date = $license->date_expiry; + if ($expiry_date == '0000-00-00'){ + SLM_Debug_Logger::log_debug_st("This key (".$key.") doesn't have a valid expiry date set. The expiry of this key will not be checked."); + continue; + } + + $today_dt = new DateTime($current_date); + $expire_dt = new DateTime($expiry_date); + if ($today_dt > $expire_dt) { + //This key has reached the expiry. So expire this key. + SLM_Debug_Logger::log_debug_st("This key (".$key.") has expired. Expiry date: ".$expiry_date.". Setting license key status to expired."); + $data = array('lic_status' => 'expired'); + $where = array('id' => $license->id); + $updated = $wpdb->update($tbl_name, $data, $where); + do_action('slm_license_key_expired',$license->id);//Trigger the license expired action hook. + } + + } + } + + /* + * Deletes a license key from the licenses table + */ + static function delete_license_key_by_row_id($key_row_id) { + global $wpdb; + $license_table = SLM_TBL_LICENSE_KEYS; + + //First delete the registered domains entry of this key (if any). + SLM_Utility::delete_registered_domains_of_key($key_row_id); + + //Now, delete the key from the licenses table. + $wpdb->delete( $license_table, array( 'id' => $key_row_id ) ); + + } + + /* + * Deletes any registered domains info from the domain table for the given key's row id. + */ + static function delete_registered_domains_of_key($key_row_id) { + global $slm_debug_logger; + global $wpdb; + $reg_table = SLM_TBL_LIC_DOMAIN; + $sql_prep = $wpdb->prepare("SELECT * FROM $reg_table WHERE lic_key_id = %s", $key_row_id); + $reg_domains = $wpdb->get_results($sql_prep, OBJECT); + foreach ($reg_domains as $domain) { + $row_to_delete = $domain->id; + $wpdb->delete( $reg_table, array( 'id' => $row_to_delete ) ); + //$slm_debug_logger->log_debug("Registered domain with row id (".$row_to_delete.") deleted."); + } + } + +} \ No newline at end of file diff --git a/software-license-manager/index.html b/software-license-manager/index.html new file mode 100644 index 0000000..e69de29 diff --git a/software-license-manager/js/index.html b/software-license-manager/js/index.html new file mode 100644 index 0000000..e69de29 diff --git a/software-license-manager/js/wplm-custom-admin.js b/software-license-manager/js/wplm-custom-admin.js new file mode 100644 index 0000000..313fbc1 --- /dev/null +++ b/software-license-manager/js/wplm-custom-admin.js @@ -0,0 +1,11 @@ +jQuery(document).ready(function($){ + //Add date picker listener on date fields + if ($.fn.datepicker){ + $('.wplm_pick_date').datepicker({ + dateFormat : 'yy-mm-dd' + }); + } + + //Add other admin side only jquery code below + +}); \ No newline at end of file diff --git a/software-license-manager/menu/includes/index.html b/software-license-manager/menu/includes/index.html new file mode 100644 index 0000000..e69de29 diff --git a/software-license-manager/menu/includes/slm-list-table-class.php b/software-license-manager/menu/includes/slm-list-table-class.php new file mode 100644 index 0000000..466af4f --- /dev/null +++ b/software-license-manager/menu/includes/slm-list-table-class.php @@ -0,0 +1,907 @@ + '', + 'singular' => '', + 'ajax' => false, + 'screen' => null, + ) ); + + $this->screen = convert_to_screen( $args['screen'] ); + + add_filter( "manage_{$this->screen->id}_columns", array( &$this, 'get_columns' ), 0 ); + + if ( !$args['plural'] ) + $args['plural'] = $this->screen->base; + + $args['plural'] = sanitize_key( $args['plural'] ); + $args['singular'] = sanitize_key( $args['singular'] ); + + $this->_args = $args; + + if ( $args['ajax'] ) { + // wp_enqueue_script( 'list-table' ); + add_action( 'admin_footer', array( &$this, '_js_vars' ) ); + } + } + + /** + * Checks the current user's permissions + * @uses wp_die() + * + * @since 3.1.0 + * @access public + * @abstract + */ + function ajax_user_can() { + die( 'function WP_Photo_Seller_List_Table::ajax_user_can() must be over-ridden in a sub-class.' ); + } + + /** + * Prepares the list of items for displaying. + * @uses WP_Photo_Seller_List_Table::set_pagination_args() + * + * @since 3.1.0 + * @access public + * @abstract + */ + function prepare_items() { + die( 'function WP_Photo_Seller_List_Table::prepare_items() must be over-ridden in a sub-class.' ); + } + + /** + * An internal method that sets all the necessary pagination arguments + * + * @param array $args An associative array with information about the pagination + * @access protected + */ + function set_pagination_args( $args ) { + $args = wp_parse_args( $args, array( + 'total_items' => 0, + 'total_pages' => 0, + 'per_page' => 0, + ) ); + + if ( !$args['total_pages'] && $args['per_page'] > 0 ) + $args['total_pages'] = ceil( $args['total_items'] / $args['per_page'] ); + + // redirect if page number is invalid and headers are not already sent + if ( ! headers_sent() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) && $args['total_pages'] > 0 && $this->get_pagenum() > $args['total_pages'] ) { + wp_redirect( esc_url(add_query_arg( 'paged', $args['total_pages'] )) ); + exit; + } + + $this->_pagination_args = $args; + } + + /** + * Access the pagination args + * + * @since 3.1.0 + * @access public + * + * @param string $key + * @return array + */ + function get_pagination_arg( $key ) { + if ( 'page' == $key ) + return $this->get_pagenum(); + + if ( isset( $this->_pagination_args[$key] ) ) + return $this->_pagination_args[$key]; + } + + /** + * Whether the table has items to display or not + * + * @since 3.1.0 + * @access public + * + * @return bool + */ + function has_items() { + return !empty( $this->items ); + } + + /** + * Message to be displayed when there are no items + * + * @since 3.1.0 + * @access public + */ + function no_items() { + _e( 'No items found.' ); + } + + /** + * Display the search box. + * + * @since 3.1.0 + * @access public + * + * @param string $text The search button text + * @param string $input_id The search input id + */ + function search_box( $text, $input_id ) { + if ( empty( $_REQUEST['s'] ) && !$this->has_items() ) + return; + + $input_id = $input_id . '-search-input'; + + if ( ! empty( $_REQUEST['orderby'] ) ) + echo ''; + if ( ! empty( $_REQUEST['order'] ) ) + echo ''; + if ( ! empty( $_REQUEST['post_mime_type'] ) ) + echo ''; + if ( ! empty( $_REQUEST['detached'] ) ) + echo ''; +?> + + link ) with the list + * of views available on this table. + * + * @since 3.1.0 + * @access protected + * + * @return array + */ + function get_views() { + return array(); + } + + /** + * Display the list of views available on this table. + * + * @since 3.1.0 + * @access public + */ + function views() { + $views = $this->get_views(); + $views = apply_filters( 'views_' . $this->screen->id, $views ); + + if ( empty( $views ) ) + return; + + echo "
      \n"; + foreach ( $views as $class => $view ) { + $views[ $class ] = "\t
    • $view"; + } + echo implode( " |
    • \n", $views ) . "\n"; + echo "
    "; + } + + /** + * Get an associative array ( option_name => option_title ) with the list + * of bulk actions available on this table. + * + * @since 3.1.0 + * @access protected + * + * @return array + */ + function get_bulk_actions() { + return array(); + } + + /** + * Display the bulk actions dropdown. + * + * @since 3.1.0 + * @access public + */ + function bulk_actions() { + if ( is_null( $this->_actions ) ) { + $no_new_actions = $this->_actions = $this->get_bulk_actions(); + // This filter can currently only be used to remove actions. + $this->_actions = apply_filters( 'bulk_actions-' . $this->screen->id, $this->_actions ); + $this->_actions = array_intersect_assoc( $this->_actions, $no_new_actions ); + $two = ''; + } else { + $two = '2'; + } + + if ( empty( $this->_actions ) ) + return; + + echo "\n"; + + submit_button( __( 'Apply' ), 'action', false, false, array( 'id' => "doaction$two" ) ); + echo "\n"; + } + + /** + * Get the current action selected from the bulk actions dropdown. + * + * @since 3.1.0 + * @access public + * + * @return string|bool The action name or False if no action was selected + */ + function current_action() { + if ( isset( $_REQUEST['action'] ) && -1 != $_REQUEST['action'] ) + return $_REQUEST['action']; + + if ( isset( $_REQUEST['action2'] ) && -1 != $_REQUEST['action2'] ) + return $_REQUEST['action2']; + + return false; + } + + /** + * Generate row actions div + * + * @since 3.1.0 + * @access protected + * + * @param array $actions The list of actions + * @param bool $always_visible Whether the actions should be always visible + * @return string + */ + function row_actions( $actions, $always_visible = false ) { + $action_count = count( $actions ); + $i = 0; + + if ( !$action_count ) + return ''; + + $out = '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + $out .= "$link$sep"; + } + $out .= '
    '; + + return $out; + } + + /** + * Display a monthly dropdown for filtering items + * + * @since 3.1.0 + * @access protected + */ + function months_dropdown( $post_type ) { + global $wpdb, $wp_locale; + + $months = $wpdb->get_results( $wpdb->prepare( " + SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month + FROM $wpdb->posts + WHERE post_type = %s + ORDER BY post_date DESC + ", $post_type ) ); + + $month_count = count( $months ); + + if ( !$month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) + return; + + $m = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0; +?> + + __( 'List View' ), + 'excerpt' => __( 'Excerpt View' ) + ); + +?> + +
    + $title ) { + $class = ( $current_mode == $mode ) ? 'class="current"' : ''; + echo "$title\n"; + } + ?> +
    +'; + + echo "" . number_format_i18n( get_comments_number() ) . ""; + + if ( $pending_comments ) + echo ''; + } + + /** + * Get the current page number + * + * @since 3.1.0 + * @access protected + * + * @return int + */ + function get_pagenum() { + $pagenum = isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 0; + + if( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] ) + $pagenum = $this->_pagination_args['total_pages']; + + return max( 1, $pagenum ); + } + + /** + * Get number of items to display on a single page + * + * @since 3.1.0 + * @access protected + * + * @return int + */ + function get_items_per_page( $option, $default = 20 ) { + $per_page = (int) get_user_option( $option ); + if ( empty( $per_page ) || $per_page < 1 ) + $per_page = $default; + + return (int) apply_filters( $option, $per_page ); + } + + /** + * Display the pagination. + * + * @since 3.1.0 + * @access protected + */ + function pagination( $which ) { + if ( empty( $this->_pagination_args ) ) + return; + + extract( $this->_pagination_args, EXTR_SKIP ); + + $output = '' . sprintf( _n( '1 item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . ''; + + $current = $this->get_pagenum(); + + $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); + + $current_url = remove_query_arg( array( 'hotkeys_highlight_last', 'hotkeys_highlight_first' ), $current_url ); + + $page_links = array(); + + $disable_first = $disable_last = ''; + if ( $current == 1 ) + $disable_first = ' disabled'; + if ( $current == $total_pages ) + $disable_last = ' disabled'; + + $page_links[] = sprintf( "%s", + 'first-page' . $disable_first, + esc_attr__( 'Go to the first page' ), + esc_url( remove_query_arg( 'paged', $current_url ) ), + '«' + ); + + $page_links[] = sprintf( "%s", + 'prev-page' . $disable_first, + esc_attr__( 'Go to the previous page' ), + esc_url( add_query_arg( 'paged', max( 1, $current-1 ), $current_url ) ), + '‹' + ); + + if ( 'bottom' == $which ) + $html_current_page = $current; + else + $html_current_page = sprintf( "", + esc_attr__( 'Current page' ), + $current, + strlen( $total_pages ) + ); + + $html_total_pages = sprintf( "%s", number_format_i18n( $total_pages ) ); + $page_links[] = '' . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . ''; + + $page_links[] = sprintf( "%s", + 'next-page' . $disable_last, + esc_attr__( 'Go to the next page' ), + esc_url( add_query_arg( 'paged', min( $total_pages, $current+1 ), $current_url ) ), + '›' + ); + + $page_links[] = sprintf( "%s", + 'last-page' . $disable_last, + esc_attr__( 'Go to the last page' ), + esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ), + '»' + ); + + $pagination_links_class = 'pagination-links'; + if ( ! empty( $infinite_scroll ) ) + $pagination_links_class = ' hide-if-js'; + $output .= "\n" . join( "\n", $page_links ) . ''; + + if ( $total_pages ) + $page_class = $total_pages < 2 ? ' one-page' : ''; + else + $page_class = ' no-pages'; + + $this->_pagination = "
    $output
    "; + + echo $this->_pagination; + } + + /** + * Get a list of columns. The format is: + * 'internal-name' => 'Title' + * + * @since 3.1.0 + * @access protected + * @abstract + * + * @return array + */ + function get_columns() { + die( 'function WP_Photo_Seller_List_Table::get_columns() must be over-ridden in a sub-class.' ); + } + + /** + * Get a list of sortable columns. The format is: + * 'internal-name' => 'orderby' + * or + * 'internal-name' => array( 'orderby', true ) + * + * The second format will make the initial sorting order be descending + * + * @since 3.1.0 + * @access protected + * + * @return array + */ + function get_sortable_columns() { + return array(); + } + + /** + * Get a list of all, hidden and sortable columns, with filter applied + * + * @since 3.1.0 + * @access protected + * + * @return array + */ + function get_column_info() { + if ( isset( $this->_column_headers ) ) + return $this->_column_headers; + + $columns = get_column_headers( $this->screen ); + $hidden = get_hidden_columns( $this->screen ); + + $_sortable = apply_filters( "manage_{$this->screen->id}_sortable_columns", $this->get_sortable_columns() ); + + $sortable = array(); + foreach ( $_sortable as $id => $data ) { + if ( empty( $data ) ) + continue; + + $data = (array) $data; + if ( !isset( $data[1] ) ) + $data[1] = false; + + $sortable[$id] = $data; + } + + $this->_column_headers = array( $columns, $hidden, $sortable ); + + return $this->_column_headers; + } + + /** + * Return number of visible columns + * + * @since 3.1.0 + * @access public + * + * @return int + */ + function get_column_count() { + list ( $columns, $hidden ) = $this->get_column_info(); + $hidden = array_intersect( array_keys( $columns ), array_filter( $hidden ) ); + return count( $columns ) - count( $hidden ); + } + + /** + * Print column headers, accounting for hidden and sortable columns. + * + * @since 3.1.0 + * @access protected + * + * @param bool $with_id Whether to set the id attribute or not + */ + function print_column_headers( $with_id = true ) { + list( $columns, $hidden, $sortable ) = $this->get_column_info(); + + $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); + $current_url = remove_query_arg( 'paged', $current_url ); + + if ( isset( $_GET['orderby'] ) ) + $current_orderby = $_GET['orderby']; + else + $current_orderby = ''; + + if ( isset( $_GET['order'] ) && 'desc' == $_GET['order'] ) + $current_order = 'desc'; + else + $current_order = 'asc'; + + if ( ! empty( $columns['cb'] ) ) { + static $cb_counter = 1; + $columns['cb'] = '' + . ''; + $cb_counter++; + } + + foreach ( $columns as $column_key => $column_display_name ) { + $class = array( 'manage-column', "column-$column_key" ); + + $style = ''; + if ( in_array( $column_key, $hidden ) ) + $style = 'display:none;'; + + $style = ' style="' . $style . '"'; + + if ( 'cb' == $column_key ) + $class[] = 'check-column'; + elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ) ) ) + $class[] = 'num'; + + if ( isset( $sortable[$column_key] ) ) { + list( $orderby, $desc_first ) = $sortable[$column_key]; + + if ( $current_orderby == $orderby ) { + $order = 'asc' == $current_order ? 'desc' : 'asc'; + $class[] = 'sorted'; + $class[] = $current_order; + } else { + $order = $desc_first ? 'desc' : 'asc'; + $class[] = 'sortable'; + $class[] = $desc_first ? 'asc' : 'desc'; + } + + $column_display_name = '' . $column_display_name . ''; + } + + $id = $with_id ? "id='$column_key'" : ''; + + if ( !empty( $class ) ) + $class = "class='" . join( ' ', $class ) . "'"; + + echo "$column_display_name"; + } + } + + /** + * Display the table + * + * @since 3.1.0 + * @access public + */ + function display() { + extract( $this->_args ); + + $this->display_tablenav( 'top' ); + +?> + + + + print_column_headers(); ?> + + + + + + print_column_headers( false ); ?> + + + + > + display_rows_or_placeholder(); ?> + +
    +display_tablenav( 'bottom' ); + } + + /** + * Get a list of CSS classes for the tag + * + * @since 3.1.0 + * @access protected + * + * @return array + */ + function get_table_classes() { + return array( 'widefat', 'fixed', $this->_args['plural'] ); + } + + /** + * Generate the table navigation above or below the table + * + * @since 3.1.0 + * @access protected + */ + function display_tablenav( $which ) { + if ( 'top' == $which ) + wp_nonce_field( 'bulk-' . $this->_args['plural'] ); +?> +
    + +
    + bulk_actions(); ?> +
    +extra_tablenav( $which ); + $this->pagination( $which ); +?> + +
    +
    + part of the table + * + * @since 3.1.0 + * @access protected + */ + function display_rows_or_placeholder() { + if ( $this->has_items() ) { + $this->display_rows(); + } else { + list( $columns, $hidden ) = $this->get_column_info(); + echo ''; + } + } + + /** + * Generate the table rows + * + * @since 3.1.0 + * @access protected + */ + function display_rows() { + foreach ( $this->items as $item ) + $this->single_row( $item ); + } + + /** + * Generates content for a single row of the table + * + * @since 3.1.0 + * @access protected + * + * @param object $item The current item + */ + function single_row( $item ) { + static $row_class = ''; + $row_class = ( $row_class == '' ? ' class="alternate"' : '' ); + + echo ''; + echo $this->single_row_columns( $item ); + echo ''; + } + + /** + * Generates the columns for a single row of the table + * + * @since 3.1.0 + * @access protected + * + * @param object $item The current item + */ + function single_row_columns( $item ) { + list( $columns, $hidden ) = $this->get_column_info(); + + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class='$column_name column-$column_name'"; + + $style = ''; + if ( in_array( $column_name, $hidden ) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + if ( 'cb' == $column_name ) { + echo ''; + } + elseif ( method_exists( $this, 'column_' . $column_name ) ) { + echo ""; + } + else { + echo ""; + } + } + } + + /** + * Handle an incoming ajax request (called from admin-ajax.php) + * + * @since 3.1.0 + * @access public + */ + function ajax_response() { + $this->prepare_items(); + + extract( $this->_args ); + extract( $this->_pagination_args, EXTR_SKIP ); + + ob_start(); + if ( ! empty( $_REQUEST['no_placeholder'] ) ) + $this->display_rows(); + else + $this->display_rows_or_placeholder(); + + $rows = ob_get_clean(); + + $response = array( 'rows' => $rows ); + + if ( isset( $total_items ) ) + $response['total_items_i18n'] = sprintf( _n( '1 item', '%s items', $total_items ), number_format_i18n( $total_items ) ); + + if ( isset( $total_pages ) ) { + $response['total_pages'] = $total_pages; + $response['total_pages_i18n'] = number_format_i18n( $total_pages ); + } + + die( json_encode( $response ) ); + } + + /** + * Send required variables to JavaScript land + * + * @access private + */ + function _js_vars() { + $args = array( + 'class' => get_class( $this ), + 'screen' => array( + 'id' => $this->screen->id, + 'base' => $this->screen->base, + ) + ); + + printf( "\n", json_encode( $args ) ); + } +} diff --git a/software-license-manager/menu/index.html b/software-license-manager/menu/index.html new file mode 100644 index 0000000..e69de29 diff --git a/software-license-manager/menu/slm-add-licenses.php b/software-license-manager/menu/slm-add-licenses.php new file mode 100644 index 0000000..3f9caa5 --- /dev/null +++ b/software-license-manager/menu/slm-add-licenses.php @@ -0,0 +1,394 @@ +'; + echo '

    Add/Edit Licenses

    '; + echo '
    '; + + //If product is being edited, grab current product info + if (isset($_GET['edit_record'])) { + $errors = ''; + $id = $_GET['edit_record']; + $lk_table = SLM_TBL_LICENSE_KEYS; + $sql_prep = $wpdb->prepare("SELECT * FROM $lk_table WHERE id = %s", $id); + $record = $wpdb->get_row($sql_prep, OBJECT); + $license_key = $record->license_key; + $max_domains = $record->max_allowed_domains; + $max_devices = $record->max_allowed_devices; + $license_status = $record->lic_status; + $first_name = $record->first_name; + $last_name = $record->last_name; + $email = $record->email; + $company_name = $record->company_name; + $txn_id = $record->txn_id; + $reset_count = $record->manual_reset_count; + $purchaseid = $record->purchase_id_; + $created_date = $record->date_created; + $renewed_date = $record->date_renewed; + $expiry_date = $record->date_expiry; + $product_ref = $record->product_ref; + } + + + if (isset($_POST['save_record'])) { + + //Check nonce + if ( !isset($_POST['slm_add_edit_nonce_val']) || !wp_verify_nonce($_POST['slm_add_edit_nonce_val'], 'slm_add_edit_nonce_action' )){ + //Nonce check failed. + wp_die("Error! Nonce verification failed for license save action."); + } + + do_action('slm_add_edit_interface_save_submission'); + + //TODO - do some validation + $license_key = $_POST['license_key']; + $max_domains = $_POST['max_allowed_domains']; + $max_devices = $_POST['max_allowed_devices']; + $license_status = $_POST['lic_status']; + $first_name = $_POST['first_name']; + $last_name = $_POST['last_name']; + $email = $_POST['email']; + $company_name = $_POST['company_name']; + $txn_id = $_POST['txn_id']; + $reset_count = $_POST['manual_reset_count']; + $purchaseid = $_POST['purchase_id_']; + $created_date = $_POST['date_created']; + $renewed_date = $_POST['date_renewed']; + $expiry_date = $_POST['date_expiry']; + $product_ref = $_POST['product_ref']; + + if(empty($created_date)){ + $created_date = $current_date; + } + if(empty($renewed_date)){ + $renewed_date = $current_date; + } + if(empty($expiry_date)){ + $expiry_date = $current_date_plus_1year; + } + + //Save the entry to the database + $fields = array(); + $fields['license_key'] = $license_key; + $fields['max_allowed_domains'] = $max_domains; + $fields['max_allowed_devices'] = $max_devices; + $fields['lic_status'] = $license_status; + $fields['first_name'] = $first_name; + $fields['last_name'] = $last_name; + $fields['email'] = $email; + $fields['company_name'] = $company_name; + $fields['txn_id'] = $txn_id; + $fields['manual_reset_count'] = $reset_count; + $fields['purchase_id_'] = $purchaseid; + $fields['date_created'] = $created_date; + $fields['date_renewed'] = $renewed_date; + $fields['date_expiry'] = $expiry_date; + $fields['product_ref'] = $product_ref; + + $id = isset($_POST['edit_record'])?$_POST['edit_record']:''; + $lk_table = SLM_TBL_LICENSE_KEYS; + if (empty($id)) {//Insert into database + $result = $wpdb->insert( $lk_table, $fields); + $id = $wpdb->insert_id; + if($result === false){ + $errors .= __('Record could not be inserted into the database!', 'slm'); + } + } else { //Update record + $where = array('id'=>$id); + $updated = $wpdb->update($lk_table, $fields, $where); + if($updated === false){ + //TODO - log error + $errors .= __('Update of the license key table failed!', 'slm'); + } + } + + if(empty($errors)){ + $message = "Record successfully saved!"; + echo '

    '; + echo $message; + echo '

    '; + }else{ + echo '
    ' . $errors . '
    '; + } + + $data = array('row_id' => $id, 'key' => $license_key); + do_action('slm_add_edit_interface_save_record_processed',$data); + + } + +?> + + You can add a new license or edit an existing one from this interface. +

    + +
    +

    +
    + +
    "> + +
    '; + $this->no_items(); + echo '
    '; + echo $this->column_cb( $item ); + echo '"; + echo call_user_func( array( &$this, 'column_' . $column_name ), $item ); + echo ""; + echo $this->column_default( $item, $column_name ); + echo "
    + + '; + } else { + if(!isset($editing_record)){//Create an empty object + $editing_record = new stdClass(); + } + //Auto generate unique key + $lic_key_prefix = $slm_options['lic_prefix']; + if (!empty($lic_key_prefix)) { + $license_key = uniqid($lic_key_prefix); + } else { + $license_key = uniqid(); + } + } + ?> + + + + + + + + + + + + + + + + + + + + + prepare("SELECT * FROM $reg_table WHERE lic_key_id = %s", $id); + $reg_domains = $wpdb->get_results($sql_prep, OBJECT); + ?> + + + + + + + prepare("SELECT * FROM `$devices_table` WHERE `lic_key_id` = '%s'", $id); + $reg_devices = $wpdb->get_results($sql_prep2, OBJECT); + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    License Key +
    The unique license key. When adding a new record it automatically generates a unique key in this field for you. You can change this value to customize the key if you like.
    Maximum Allowed Domains
    Number of domains/installs in which this license can be used.
    Maximum Allowed Devices
    Number of domains/installs in which this license can be used.
    License Status + +
    Registered Domains 0) { + ?> +
    +
    + + + > + + + + +
    registered_domain; ?>id ?>>X
    +
    + +
    Registered Devices 0) { + ?> +
    +
    + + + > + + + + +
    registered_devices; ?>id ?>>X
    +
    + +
    First Name
    License user's first name
    Last Name
    License user's last name
    Email Address
    License user's email address
    Company Name
    License user's company name
    Unique Transaction ID
    The unique transaction ID associated with this license key
    Manual Reset Count +
    The number of times this license has been manually reset by the admin (use it if you want to keep track of it). It can be helpful for the admin to keep track of manual reset counts.
    Purchase Order # +
    This is associated with the purchase ID woocommerce support
    Date Created +
    Creation date of license.
    Date Renewed +
    Renewal date of license.
    Date of Expiry +
    Expiry date of license.
    Product +
    The product that this license gives access to.
    + + $id, 'key' => $license_key); + $extra_output = apply_filters('slm_add_edit_interface_above_submit','', $data); + if(!empty($extra_output)){ + echo $extra_output; + } + ?> + +
    + +
    + + + Manage Licenses

    + + + + +'; + echo '

    License Manager Admin Functions

    '; + echo '
    '; + + $slm_options = get_option('slm_plugin_options'); + + if (isset($_POST['send_deactivation_request'])) { + $postURL = $_POST['lic_mgr_deactivation_req_url']; + $secretKeyForVerification = $slm_options['lic_verification_secret']; + $data = array(); + $data['secret_key'] = $secretKeyForVerification; + + $ch = curl_init($postURL); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $returnValue = curl_exec($ch); + + $msg = ""; + if ($returnValue == "Success") { + $msg .= "Success message returned from the remote host."; + } + echo '

    '; + echo 'Request sent to the specified URL!'; + echo '
    ' . $msg; + echo '

    '; + } + ?> +
    +
    +

    +
    +
    Enter the URL where the license deactivation message will be sent to +

    +
    + + +
    + +
    +
    +
    +
    '; + echo '
    '; +} diff --git a/software-license-manager/menu/slm-admin-init.php b/software-license-manager/menu/slm-admin-init.php new file mode 100644 index 0000000..34eff57 --- /dev/null +++ b/software-license-manager/menu/slm-admin-init.php @@ -0,0 +1,25 @@ + + + License Manager Integration Help v' . WP_LICENSE_MANAGER_VERSION . ''; + echo '
    '; + echo '
    '; + + echo '

    For information, updates and documentation, please visit the License Manager Documentation page.

    '; + + $api_query_post_url = SLM_SITE_HOME_URL; + echo "The License API Query POST URL For Your Installation"; + echo '
    ' . $api_query_post_url . '
    '; + + echo "The License Activation or Deactivation API secret key"; + echo '
    ' . $secret_verification_key . '
    '; + + echo "The License Creation API secret key"; + echo '
    ' . $creation_secret_key . '
    '; + ?> +

    3rd Party Integration

    + + Integrating a 3rd party payment system or shopping cart with License Manager is easy. +

    + The integration process can be accomplished in three steps, namely: +
    +
    1. Generate POST data +
    2. Send POST data to the API POST URL +
    3. Process the returned data +

    + POST Values +
    + License Manager expects a certain set of variables to be sent to it via HTTP POST or GET. These variables are: +

    + Mandatory Variables +
    + ---------------- +
    a. secret_key - A Secret API key for authentication (you can find the secret key value in the settings menu of this plugin) +
    b. slm_action - The action being performed. The values can be slm_create_new or slm_activate or slm_deactivate +

    + Optional Variables +
    + --------------- +
    c. Customer First Name: The first name of the customer +
    d. Customer Last Name: The last name of the customer +
    e. Customer Email: The email address of the customer +
    f. Company Name: The customer's company name +
    g. Maximum Domains Allowed: The number of domains this license key can be used on +
    h. Transaction ID: A unique transaction ID to reference the transaction +

    + Return Value +
    + Upon successful processing, License Manager will return a plain text message that will have two or three lines similar to the following: +
    +
    + Success +
    License key +
    WPLICMGR4bc29fd61e471 +
    + or +
    + Error +
    Secret key is invalid +
    + + 1. The first line is an indication of success or error +
    2. The second line is the result. +
    3. The third line is additional message that resulted from the request. +

    + Sample PHP Code +
    + Below is a sample PHP code that shows how you can create a license via the API +
    + +
    + /*** Mandatory data ***/ +
    // Post URL +
    $postURL = ""; +
    // The Secret key +
    $secretKey = ""; +
    +
    /*** Optional Data ***/ +
    $firstname = "John"; +
    $lastname = "Doe"; +
    $email = "john.doe@gmail.com"; +
    +
    // prepare the data +
    $data = array (); +
    $data['secret_key'] = $secretKey; +
    $data['slm_action'] = 'slm_create_new'; +
    $data['first_name'] = $firstname; +
    $data['last_name'] = $lastname; +
    $data['email'] = $email; +
    +
    // send data to post URL +
    $ch = curl_init ($postURL); +
    curl_setopt ($ch, CURLOPT_POST, true); +
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $data); +
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); +
    $returnValue = curl_exec ($ch); +
    +
    // Process the return values +
    //var_dump($returnValue); +
    + +
    '; + echo '
    '; +} diff --git a/software-license-manager/menu/slm-lic-settings.php b/software-license-manager/menu/slm-lic-settings.php new file mode 100644 index 0000000..caaac0e --- /dev/null +++ b/software-license-manager/menu/slm-lic-settings.php @@ -0,0 +1,143 @@ +'; + echo '

    WP License Manager Settings v' . WP_LICENSE_MANAGER_VERSION . '

    '; + echo '
    '; + + wp_lic_mgr_general_settings(); + + echo '
    '; + echo '
    '; +} + +function wp_lic_mgr_general_settings() { + + if (isset($_REQUEST['slm_reset_log'])){ + //$slm_logger = new SLM_Debug_Logger(); + global $slm_debug_logger; + $slm_debug_logger->reset_log_file("log.txt"); + $slm_debug_logger->reset_log_file("log-cron-job.txt"); + echo '

    Debug log files have been reset!

    '; + } + + if (isset($_POST['slm_save_settings'])) { + + if (!is_numeric($_POST["default_max_domains"])) {//Set it to one by default if incorrect value is entered + $_POST["default_max_domains"] = '1'; + } + if (!is_numeric($_POST["default_max_devices"])) {//Set it to one by default if incorrect value is entered + $_POST["default_max_devices"] = '1'; + } + + $options = array( + 'lic_creation_secret' => trim($_POST["lic_creation_secret"]), + 'lic_prefix' => trim($_POST["lic_prefix"]), + 'default_max_domains' => trim($_POST["default_max_domains"]), + 'default_max_devices' => trim($_POST["default_max_devices"]), + 'lic_verification_secret' => trim($_POST["lic_verification_secret"]), + 'enable_auto_key_expiry' => isset($_POST['enable_auto_key_expiry']) ? '1':'', + 'enable_debug' => isset($_POST['enable_debug']) ? '1':'', + ); + update_option('slm_plugin_options', $options); + + echo '

    '; + echo 'Options Updated!'; + echo '

    '; + } + + $options = get_option('slm_plugin_options'); + + $secret_key = $options['lic_creation_secret']; + if (empty($secret_key)) { + $secret_key = uniqid('', true); + } + $secret_verification_key = $options['lic_verification_secret']; + if (empty($secret_verification_key)) { + $secret_verification_key = uniqid('', true); + } + ?> +

    For information, updates and documentation, please visit the License Manager Documentation page.

    + +
    +

    +
    + +

    1. First register a key at purchase time.

    +

    2. Add the code so at activation time it asks for the key.

    +

    3. Integrate the real time online key verification part.

    +
    + +
    + +
    +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Secret Key for License Creation +
    This secret key will be used to authenticate any license creation request. You can change it with something random.
    Secret Key for License Verification Requests +
    This secret key will be used to authenticate any license verification request from customer's site. Important! Do not change this value once your customers start to use your product(s)!
    License Key Prefix +
    You can optionaly specify a prefix for the license keys. This prefix will be added to the uniquely generated license keys.
    Maximum Allowed Domains +
    Maximum number of domains/installs which each license is valid for (default value).
    Maximum Allowed Devices +
    Maximum number of devices which each license is valid for (default value).
    Auto Expire License Keys value="1"/> +

    When enabled, it will automatically set the status of a license key to "Expired" when the expiry date value of the key is reached. + It doesn't remotely deactivate a key. It simply changes the status of the key in your database to expired.

    +
    +
    + +
    +

    +
    + + + + + + + +
    Enable Debug Logging value="1"/> +

    If checked, debug output will be written to log files (keep it disabled unless you are troubleshooting).

    +
    - View debug log file by clicking here. +
    - Reset debug log file by clicking here. +
    +
    + +
    + +
    +
    + 'item', //singular name of the listed records + 'plural' => 'items', //plural name of the listed records + 'ajax' => false //does this table support ajax? + ) ); + + } + + function column_default($item, $column_name){ + return $item[$column_name]; + } + + function column_id($item){ + $row_id = $item['id']; + $actions = array( + 'edit' => sprintf('Edit', $row_id), + 'delete' => sprintf('Delete',$row_id), + ); + return sprintf('%1$s %2$s', + /*$1%s*/ $item['id'], + /*$2%s*/ $this->row_actions($actions) + ); + } + + + function column_cb($item){ + return sprintf( + '', + /*$1%s*/ $this->_args['singular'], //Let's simply repurpose the table's singular label + /*$2%s*/ $item['id'] //The value of the checkbox should be the record's id + ); + } + + function column_active($item){ + if ($item['active'] == 1){ + return 'active'; + } else{ + return 'inactive'; + } + } + + + function get_columns(){ + $columns = array( + 'cb' => '', //Render a checkbox + 'id' => 'ID', + 'license_key' => 'License Key', + 'lic_status' => 'Status', + 'max_allowed_domains' => 'Domains Allowed', + 'email' => 'Registered Email', + 'date_created' => 'Date Created', + 'date_renewed' => 'Date Renewed', + 'date_expiry' => 'Expiry', + ); + return $columns; + } + + function get_sortable_columns() { + $sortable_columns = array( + 'id' => array('id',false), + 'license_key' => array('license_key',false), + 'lic_status' => array('lic_status',false), + 'date_created' => array('date_created',false), + 'date_renewed' => array('date_renewed',false), + 'date_expiry' => array('date_expiry',false), + ); + return $sortable_columns; + } + + function get_bulk_actions() { + $actions = array( + 'delete' => 'Delete', + ); + return $actions; + } + + function process_bulk_action() { + if('delete'===$this->current_action()) + { + //Process delete bulk actions + if(!isset($_REQUEST['item'])){ + $error_msg = '

    '.__('Error - Please select some records using the checkboxes', 'slm').'

    '; + echo '
    '.$error_msg.'
    '; + return; + }else { + $nvp_key = $this->_args['singular']; + $records_to_delete = $_GET[$nvp_key]; + foreach ($records_to_delete as $row){ + SLM_Utility::delete_license_key_by_row_id($row); + } + echo '

    Selected records deleted successfully!

    '; + } + } + } + + + /* + * This function will delete the selected license key entries from the DB. + */ + function delete_license_key($key_row_id) + { + SLM_Utility::delete_license_key_by_row_id($key_row_id); + $success_msg = '

    '; + $success_msg .= 'The selected entry was deleted successfully!'; + $success_msg .= '

    '; + echo $success_msg; + } + + + function prepare_items() { + /** + * First, lets decide how many records per page to show + */ + $per_page = 50; + $columns = $this->get_columns(); + $hidden = array(); + $sortable = $this->get_sortable_columns(); + + $this->_column_headers = array($columns, $hidden, $sortable); + + $this->process_bulk_action(); + + global $wpdb; + $license_table = SLM_TBL_LICENSE_KEYS; + + /* -- Ordering parameters -- */ + //Parameters that are going to be used to order the result + $orderby = !empty($_GET["orderby"]) ? strip_tags($_GET["orderby"]) : 'id'; + $order = !empty($_GET["order"]) ? strip_tags($_GET["order"]) : 'DESC'; + + if (isset($_POST['slm_search'])) { + $search_term = trim(strip_tags($_POST['slm_search'])); + $prepare_query = $wpdb->prepare("SELECT * FROM " . $license_table . " WHERE `license_key` LIKE '%%%s%%' OR `email` LIKE '%%%s%%' OR `txn_id` LIKE '%%%s%%' OR `first_name` LIKE '%%%s%%' OR `last_name` LIKE '%%%s%%'", $search_term, $search_term, $search_term, $search_term, $search_term); + $data = $wpdb->get_results($prepare_query, ARRAY_A); + }else{ + $data = $wpdb->get_results("SELECT * FROM $license_table ORDER BY $orderby $order", ARRAY_A); + } + + $current_page = $this->get_pagenum(); + $total_items = count($data); + $data = array_slice($data,(($current_page-1)*$per_page),$per_page); + $this->items = $data; + $this->set_pagination_args( array( + 'total_items' => $total_items, //WE have to calculate the total number of items + 'per_page' => $per_page, //WE have to determine how many items to show on a page + 'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages + ) ); + } +} \ No newline at end of file diff --git a/software-license-manager/menu/slm-manage-licenses.php b/software-license-manager/menu/slm-manage-licenses.php new file mode 100644 index 0000000..432f1d0 --- /dev/null +++ b/software-license-manager/menu/slm-manage-licenses.php @@ -0,0 +1,49 @@ +'; + echo '

    Manage Licenses

    '; + echo '
    '; + ?> + +
    +

    +
    + Search for a license by using email, name, key or transaction ID +

    +
    "> + + +
    +
    + + +
    +

    +
    + delete_license_key(sanitize_text_field($_REQUEST['id'])); + } + } + //Fetch, prepare, sort, and filter our data... + $license_list->prepare_items(); + //echo "put table of locked entries here"; + ?> +
    + + + + display(); ?> +
    + +
    + +
    '; + echo '
    '; +} + diff --git a/software-license-manager/slm_bootstrap.php b/software-license-manager/slm_bootstrap.php new file mode 100644 index 0000000..913eb09 --- /dev/null +++ b/software-license-manager/slm_bootstrap.php @@ -0,0 +1,51 @@ +charset)){ + $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; +} +else{ + $charset_collate = "DEFAULT CHARSET=utf8"; +} +if (!empty($wpdb->collate)){ + $charset_collate .= " COLLATE $wpdb->collate"; +} + +$lk_tbl_sql = "CREATE TABLE " . $lic_key_table . " ( + id int(12) NOT NULL auto_increment, + license_key varchar(255) NOT NULL, + max_allowed_domains int(40) NOT NULL, + max_allowed_devices int(40) NOT NULL, + lic_status ENUM('pending', 'active', 'blocked', 'expired') NOT NULL DEFAULT 'pending', + first_name varchar(32) NOT NULL default '', + last_name varchar(32) NOT NULL default '', + email varchar(64) NOT NULL, + company_name varchar(100) NOT NULL default '', + txn_id varchar(64) NOT NULL default '', + manual_reset_count varchar(128) NOT NULL default '', + purchase_id_ varchar(255) NOT NULL default '', + date_created date NOT NULL DEFAULT '0000-00-00', + date_renewed date NOT NULL DEFAULT '0000-00-00', + date_expiry date NOT NULL DEFAULT '0000-00-00', + product_ref varchar(255) NOT NULL default '', + PRIMARY KEY (id) + )" . $charset_collate . ";"; +dbDelta($lk_tbl_sql); + +$ld_tbl_sql = "CREATE TABLE " .$lic_domain_table. " ( + id INT NOT NULL AUTO_INCREMENT , + lic_key_id INT NOT NULL , + lic_key varchar(255) NOT NULL , + registered_domain text NOT NULL , + registered_devices text NOT NULL , + item_reference varchar(255) NOT NULL, + PRIMARY KEY ( id ) + )" . $charset_collate . ";"; +dbDelta($ld_tbl_sql); + +$ldv_tbl_sql = "CREATE TABLE " .$lic_devices_table. " ( + id INT NOT NULL AUTO_INCREMENT , + lic_key_id INT NOT NULL , + lic_key varchar(255) NOT NULL , + registered_devices text NOT NULL , + registered_domain text NOT NULL , + item_reference varchar(255) NOT NULL, + PRIMARY KEY ( id ) + )" . $charset_collate . ";"; +dbDelta($ldv_tbl_sql); +update_option("wp_lic_mgr_db_version", WP_LICENSE_MANAGER_DB_VERSION); + +// Add default options +$options = array( + 'lic_creation_secret' => uniqid('', true), + 'lic_prefix' => '', + 'default_max_domains' => '2', + 'default_max_devices' => '1', + 'lic_verification_secret' => uniqid('', true), + 'enable_debug' => '', +); +add_option('slm_plugin_options', $options); \ No newline at end of file diff --git a/software-license-manager/slm_plugin_core.php b/software-license-manager/slm_plugin_core.php new file mode 100644 index 0000000..f690658 --- /dev/null +++ b/software-license-manager/slm_plugin_core.php @@ -0,0 +1,81 @@ +prefix . "lic_key_tbl"); +define('SLM_TBL_LIC_DOMAIN', $wpdb->prefix . "lic_reg_domain_tbl"); +define('SLM_TBL_LIC_DEVICES', $wpdb->prefix . "lic_reg_devices_tbl"); +define('SLM_MANAGEMENT_PERMISSION', 'manage_options'); +define('SLM_MAIN_MENU_SLUG', 'slm-main'); +define('SLM_MENU_ICON', 'dashicons-lock'); + +//Includes +include_once('includes/slm-debug-logger.php'); +include_once('includes/slm-error-codes.php'); +include_once('includes/slm-utility.php'); +include_once('includes/slm-init-time-tasks.php'); +include_once('includes/slm-api-utility.php'); +include_once('includes/slm-api-listener.php'); +include_once('includes/slm-third-party-integration.php'); +// Front end-menu +include_once('menu/slm-add-menu-frontend.php'); + +// support for meta boxes (variations only, this can be applied to single prodicts as well) +include_once('includes/slm-meta-boxes.php'); +//Include admin side only files +if (is_admin()) { + include_once('menu/slm-admin-init.php'); + include_once('menu/includes/slm-list-table-class.php'); //Load our own WP List Table class +} + + +// load addons here +include_once('addons/loader.php'); + +//Action hooks +add_action('init', 'slm_init_handler'); +add_action('plugins_loaded', 'slm_plugins_loaded_handler'); + +//Initialize debug logger +global $slm_debug_logger; +$slm_debug_logger = new SLM_Debug_Logger(); + +//Do init time tasks +function slm_init_handler() { + $init_task = new SLM_Init_Time_Tasks(); + $api_listener = new SLM_API_Listener(); +} + +//Do plugins loaded time tasks +function slm_plugins_loaded_handler() { + //Runs when plugins_loaded action gets fired + if (is_admin()) { + //Check if db update needed + if (get_option('wp_lic_mgr_db_version') != WP_LICENSE_MANAGER_DB_VERSION) { + require_once(dirname(__FILE__) . '/slm_installer.php'); + } + } + +} + +//TODO - need to move this to an ajax handler file +add_action('wp_ajax_del_reistered_domain', 'slm_del_reg_dom'); +function slm_del_reg_dom() { + global $wpdb; + $reg_table = SLM_TBL_LIC_DOMAIN; + $id = strip_tags($_GET['id']); + $ret = $wpdb->query("DELETE FROM $reg_table WHERE id='$id'"); + echo ($ret) ? 'success' : 'failed'; + exit(0); +} + + +add_action('wp_ajax_del_reistered_devices', 'slm_del_reg_devices'); +function slm_del_reg_devices() { + global $wpdb; + $reg_table = SLM_TBL_LIC_DEVICES; + $id = strip_tags($_GET['id']); + $ret = $wpdb->query("DELETE FROM $reg_table WHERE id='$id'"); + echo ($ret) ? 'success' : 'failed'; + exit(0); +} \ No newline at end of file diff --git a/woocommerce/emails/customer-completed-order.php b/woocommerce/emails/customer-completed-order.php deleted file mode 100644 index c5d2227..0000000 --- a/woocommerce/emails/customer-completed-order.php +++ /dev/null @@ -1,27 +0,0 @@ - - - -

    get_billing_first_name() ) ); ?>

    - -

    - - -

    - -

    - -mailer(); - $order = wc_get_order($order_id); - $purchase_id_ = $order->get_id(); - $order_data = $order->get_data(); // The Order data - $order_billing_email = $order_data['billing']['email']; - $recipient = $order_billing_email; - $subject = __('Order Confirmation', 'slm'); - $content = slm_get_processing_notification_content( $order, $subject, $mailer ); - $headers = "Content-Type: text/html\r\n"; - - $mailer->send( $recipient, $subject, $content, $headers ); - -} - -add_action( 'woocommerce_order_status_completed', 'slm_processing_notification', 10, 1 ); -add_action( 'woocommerce_order_status_processing', 'slm_processing_notification', 10, 1 ); - -/** - * Get content html. - * - * @param WC_Order $order - * @param str $heading - * @param obj $mailer - * @return string - */ -function slm_get_processing_notification_content( $order, $heading = false, $mailer ) { - - $template = 'emails/customer-completed-order.php'; - - return wc_get_template_html( $template, array( - 'order' => $order, - 'email_heading' => $heading, - 'sent_to_admin' => true, - 'plain_text' => false, - 'email' => $mailer - ) ); -} - - -if (null !== SLM_Helper_Class::slm_get_option('slm_woo_downloads') && SLM_Helper_Class::slm_get_option('slm_woo_downloads') == 1) { - // disable downloads - function slm_woo_remove_downlaods($items) - { - unset($items['downloads']); - return $items; - } - function slm_remove_order_downloads_from_emails($emails) - { - remove_action('woocommerce_email_order_details', array($emails, 'order_downloads'), 10); - } - add_action('woocommerce_email', 'slm_remove_order_downloads_from_emails', 10, 1); - add_filter('woocommerce_account_menu_items', 'slm_woo_remove_downlaods'); -} diff --git a/woocommerce/includes/purchase.php b/woocommerce/includes/purchase.php index b27ea10..b64f6dc 100755 --- a/woocommerce/includes/purchase.php +++ b/woocommerce/includes/purchase.php @@ -85,7 +85,7 @@ function wc_slm_create_license_keys($order_id) { $amount_of_licenses = wc_slm_get_licenses_qty($product_id); if (!$sites_allowed) { - $sites_allowed_error = __('License could not be created: Invalid sites allowed number.', 'slm'); + $sites_allowed_error = __('License could not be created: Invalid sites allowed number.', 'softwarelicensemanager'); $int = wc_insert_payment_note($purchase_id_, $sites_allowed_error); break; } @@ -158,7 +158,7 @@ function wc_slm_create_license_keys($order_id) { //access_expires //SLM_Helper_Class::write_log('license_type -- ' . $license_type ); // Send query to the license manager server - $url = 'http://' . WOO_SLM_API_URL . '?' . http_build_query($api_params); + $url = SLM_SITE_URL . '?' . http_build_query($api_params); $url = str_replace(array('http://', 'https://'), '', $url); $url = 'http://' . $url; $response = wp_remote_get($url, array('timeout' => 20, 'sslverify' => false)); @@ -210,7 +210,7 @@ function wc_slm_get_license_id($license){ function wc_slm_payment_note($order_id, $licenses) { if ($licenses && count($licenses) != 0) { - $message = __('License Key(s) generated', 'wc-slm'); + $message = __('License Key(s) generated', 'softwarelicensemanager'); foreach ($licenses as $license) { $license_key = $license['key']; @@ -227,7 +227,7 @@ function wc_slm_payment_note($order_id, $licenses) { } } else { - $message = __('License Key(s) could not be created.', 'wc-slm'); + $message = __('License Key(s) could not be created.', 'softwarelicensemanager'); } // Save note @@ -321,18 +321,15 @@ function wc_get_payment_transaction_id($order_id) { function slm_order_completed( $order_id ) { global $user_id, $wpdb; - $order = wc_get_order($order_id); - $purchase_id_ = $order->get_id(); - $order_data = $order->get_data(); // The Order data - $order_billing_email = $order_data['billing']['email']; - - $billing_address = $order_billing_email; - $message = 'error: 000 null'; - - $get_user_meta = get_user_meta($user_id); - - $headers = 'From: '. get_bloginfo( 'name' ).' <'.get_bloginfo('admin_email').'>' . "\r\n"; - wp_mail( $billing_address, 'License details', $message, $headers ); + $order = wc_get_order($order_id); + $purchase_id_ = $order->get_id(); + $order_data = $order->get_data(); // The Order data + $order_billing_email = $order_data['billing']['email']; + $billing_address = $order_billing_email; + $message = 'error: 000 null'; + $get_user_meta = get_user_meta($user_id); + $headers = 'From: '. get_bloginfo( 'name' ).' <'.get_bloginfo('admin_email').'>' . "\r\n"; + //wp_mail( $billing_address, 'License details', $message, $headers ); // The text for the note $note = __("Order confirmation email sent to: " . $billing_address . "" ); @@ -429,4 +426,20 @@ function slm_order_details($order){ '; } -} \ No newline at end of file +} + +/** + * @snippet Add Content to the Customer Processing Order Email - WooCommerce + * https://businessbloomer.com/woocommerce-add-extra-content-order-email/ + */ +add_action('woocommerce_email_before_order_table', 'slm_add_license_to_order_confirmation', 20, 4); + +function slm_add_license_to_order_confirmation($order, $sent_to_admin, $plain_text, $email) +{ + if ($email->id == 'customer_completed_order') { + echo ' +
    License key
    ' . get_post_meta($order->get_id(), 'slm_wc_license_order_key', true) . '


    + '; + } +} + diff --git a/woocommerce/includes/wc-slm.php b/woocommerce/includes/wc-slm.php index 8399053..2f5b872 100755 --- a/woocommerce/includes/wc-slm.php +++ b/woocommerce/includes/wc-slm.php @@ -1,6 +1,6 @@