From 005dccf7d8f95b708bf8170a9e20c72e5ed8c831 Mon Sep 17 00:00:00 2001 From: Ned Zimmerman Date: Tue, 30 May 2017 14:14:32 -0300 Subject: [PATCH] Migration to Human Made coding standards [WIP] (#758) * Initial migration to Human Made coding standards. * Add autoloader to tests/boostrap.php. * Add autoloader to Travis. * Bundle autoloader. * Fix many tests. * Fix coverage paths. * Update phpcs.ruleset.xml. * Exclude specific files from rule. * Fix false positives for isFormSubmission. * Fixes for HM coding standards. * Point to new inc/ directory * Change isFormSubmission() to better conform to coding standards. * Reduce @codingStandardsIgnore * Trick coding standards, * Last call. * Mr clean. * Mrs Clean. * Add more files to scan. * Fix spacing/formatting to better match HM standards. * Increase code coverage. * Remove @covers to fix under reporting in PHPStorm, ran phpcbf. * Add editor tests. * Add sanitize test. * Add utility test. * Fix for HM standards. * Fix coding standards error. --- .travis.yml | 19 +- autoloader.php | 46 + bin/compile-scss.php | 4 +- composer.json | 12 +- composer.lock | 119 +- hooks-admin.php | 37 +- hooks.php | 26 +- .../admin/analytics/namespace.php | 35 +- .../admin/branding/namespace.php | 2 +- .../admin/class-catalog-list-table.php | 141 +- .../admin/class-exportoptions.php | 90 +- .../class-network-managers-list-table.php | 128 +- .../admin/class-publishoptions.php | 165 +- .../admin/customcss/namespace.php | 89 +- .../admin/dashboard/namespace.php | 176 ++- .../admin/diagnostics/namespace.php | 32 +- .../admin/fonts/namespace.php | 2 +- .../pb-laf.php => inc/admin/laf/namespace.php | 509 +++--- .../admin/metaboxes/namespace.php | 525 ++++--- .../class-sharingandprivacyoptions.php | 67 +- .../admin/networkmanagers/namespace.php | 30 +- .../admin/plugins/namespace.php | 4 +- .../analytics/namespace.php | 5 +- .../class-activation.php | 126 +- .../class-pb-book.php => inc/class-book.php | 180 +-- .../class-catalog.php | 243 ++- .../class-container.php | 6 +- .../class-customcss.php | 56 +- .../class-globaltypography.php | 69 +- .../class-htmlawed.php | 6 +- .../class-metadata.php | 212 ++- .../class-options.php | 90 +- .../class-pressbooks.php | 15 +- .../class-pb-sass.php => inc/class-sass.php | 100 +- .../class-taxonomy.php | 144 +- .../class-themelock.php | 40 +- .../pb-editor.php => inc/editor/namespace.php | 150 +- .../pb-image.php => inc/image/namespace.php | 134 +- .../pb-l10n.php => inc/l10n/namespace.php | 52 +- .../pb-media.php => inc/media/namespace.php | 13 +- .../modules/export/class-export.php | 145 +- .../modules/export/epub/class-epub201.php | 538 ++++--- .../modules/export/epub/class-epub3.php | 226 +-- .../epub/templates/epub201/container.php | 2 +- .../export/epub/templates/epub201/html.php | 4 +- .../export/epub/templates/epub201/ibooks.php | 2 +- .../epub/templates/epub201/mobi-hacks.xsl | 0 .../export/epub/templates/epub201/ncx.php | 6 +- .../export/epub/templates/epub201/opf.php | 8 +- .../export/epub/templates/epub3/css/css3.css | 0 .../export/epub/templates/epub3/html.php | 4 +- .../export/epub/templates/epub3/opf.php | 12 +- .../export/epub/templates/epub3/toc.php | 8 +- .../modules/export/indesign/class-icml.php | 29 +- .../export/indesign/templates/xhtml.php | 2 +- .../modules/export/mobi/class-kindlegen.php | 4 +- .../modules/export/odt/class-odt.php | 67 +- .../modules/export/odt/xhtml2odt.xsl | 0 .../modules/export/prince/class-pdf.php | 87 +- .../modules/export/prince/class-printpdf.php | 24 +- .../export/wordpress/class-vanillawxr.php | 6 +- .../modules/export/wordpress/class-wxr.php | 16 +- .../modules/export/xhtml/class-xhtml11.php | 179 +-- .../modules/import/class-import.php | 104 +- .../modules/import/epub/class-epub201.php | 111 +- .../modules/import/html/class-xhtml.php | 91 +- .../modules/import/odf/class-odt.php | 81 +- .../modules/import/odf/xsl/odt2html.xsl | 0 .../modules/import/ooxml/class-docx.php | 121 +- .../modules/import/ooxml/xsl/docx2html.xsl | 0 .../modules/import/wordpress/class-parser.php | 51 +- .../modules/import/wordpress/class-wxr.php | 144 +- .../modules/searchandreplace/class-result.php | 2 +- .../modules/searchandreplace/class-search.php | 41 +- .../class-searchandreplace.php | 43 +- .../searchandreplace/types/class-content.php | 14 +- .../searchandreplace/types/class-part.php | 16 +- .../themeoptions/class-ebookoptions.php | 121 +- .../themeoptions/class-globaloptions.php | 167 +- .../modules/themeoptions/class-pdfoptions.php | 1107 ++++++++------ .../themeoptions/class-themeoptions.php | 24 +- .../modules/themeoptions/class-weboptions.php | 148 +- .../posttype/namespace.php | 143 +- .../redirect/namespace.php | 87 +- .../registration/namespace.php | 59 +- .../sanitize/namespace.php | 49 +- .../shortcodes/footnotes/class-footnotes.php | 109 +- .../shortcodes/generics/class-generics.php | 34 +- .../shortcodes/wikipublisher/class-glyphs.php | 62 +- inc/utility/class-jsonmanifest.php | 46 + .../utility/namespace.php | 237 +-- languages/core-de-de.php | 9 +- languages/core-en-us.php | 9 +- languages/core-es-es.php | 9 +- languages/core-et.php | 9 +- languages/core-fr-fr.php | 9 +- languages/core-it-it.php | 9 +- languages/core-ja.php | 9 +- languages/core-pt-br.php | 9 +- languages/core-sv-se.php | 9 +- languages/core-zh-tw.php | 9 +- phpcs.ruleset.xml | 43 + phpcs.xml | 31 - phpunit.xml | 6 +- pressbooks.php | 26 +- symbionts/Browser.php | 1358 ----------------- templates/admin/results.php | 2 +- templates/admin/search.php | 2 +- tests/bootstrap.php | 14 +- tests/data/template.php | 7 +- tests/test-admin-branding.php | 15 - tests/test-admin-fonts.php | 43 +- tests/test-admin-laf.php | 13 +- tests/test-admin-plugins.php | 37 +- tests/test-analytics.php | 20 +- tests/test-book.php | 130 +- tests/test-compatibility.php | 3 - tests/test-container.php | 44 +- tests/test-customcss.php | 24 +- tests/test-editor.php | 53 +- tests/test-globaltypography.php | 23 +- tests/test-htmlawed.php | 5 +- tests/test-l10n.php | 44 - tests/test-media.php | 16 +- tests/test-metaboxes.php | 8 +- tests/test-metadata.php | 3 - tests/test-modules-export.php | 61 +- tests/test-options.php | 67 +- tests/test-posttype.php | 17 +- tests/test-pressbooks.php | 10 +- tests/test-registration.php | 64 +- tests/test-remote-get-retry.php | 52 +- tests/test-sanitize.php | 85 +- tests/test-sass.php | 45 +- tests/test-searchandreplace.php | 14 +- tests/test-shortcodes-footnotes-footnotes.php | 58 +- tests/test-shortcodes-generics.php | 6 - .../test-shortcodes-wikipublisher-glyphs.php | 34 +- tests/test-themelock.php | 35 +- tests/test-utility.php | 133 +- tests/utils-trait.php | 3 +- 141 files changed, 5242 insertions(+), 5982 deletions(-) create mode 100644 autoloader.php rename includes/admin/pb-analytics.php => inc/admin/analytics/namespace.php (90%) rename includes/admin/pb-branding.php => inc/admin/branding/namespace.php (98%) rename includes/admin/class-pb-catalog-list-table.php => inc/admin/class-catalog-list-table.php (85%) rename includes/admin/class-pb-exportoptions.php => inc/admin/class-exportoptions.php (78%) rename includes/admin/class-pb-network-managers-list-table.php => inc/admin/class-network-managers-list-table.php (63%) rename includes/admin/class-pb-publishoptions.php => inc/admin/class-publishoptions.php (71%) rename includes/admin/pb-customcss.php => inc/admin/customcss/namespace.php (83%) rename includes/admin/pb-dashboard.php => inc/admin/dashboard/namespace.php (72%) rename includes/admin/pb-diagnostics.php => inc/admin/diagnostics/namespace.php (89%) rename includes/admin/pb-fonts.php => inc/admin/fonts/namespace.php (100%) rename includes/admin/pb-laf.php => inc/admin/laf/namespace.php (72%) rename includes/admin/pb-metaboxes.php => inc/admin/metaboxes/namespace.php (67%) rename includes/admin/class-pb-network-sharingandprivacyoptions.php => inc/admin/network/class-sharingandprivacyoptions.php (80%) rename includes/admin/pb-network-managers.php => inc/admin/networkmanagers/namespace.php (89%) rename includes/admin/pb-plugins.php => inc/admin/plugins/namespace.php (96%) rename includes/pb-analytics.php => inc/analytics/namespace.php (88%) rename includes/class-pb-activation.php => inc/class-activation.php (84%) rename includes/class-pb-book.php => inc/class-book.php (84%) rename includes/class-pb-catalog.php => inc/class-catalog.php (81%) rename includes/class-pb-container.php => inc/class-container.php (95%) rename includes/class-pb-customcss.php => inc/class-customcss.php (81%) rename includes/class-pb-globaltypography.php => inc/class-globaltypography.php (91%) rename includes/class-pb-htmlawed.php => inc/class-htmlawed.php (78%) rename includes/class-pb-metadata.php => inc/class-metadata.php (83%) rename includes/class-pb-options.php => inc/class-options.php (75%) rename includes/class-pb-pressbooks.php => inc/class-pressbooks.php (83%) rename includes/class-pb-sass.php => inc/class-sass.php (85%) rename includes/class-pb-taxonomy.php => inc/class-taxonomy.php (62%) rename includes/class-pb-themelock.php => inc/class-themelock.php (87%) rename includes/pb-editor.php => inc/editor/namespace.php (87%) rename includes/pb-image.php => inc/image/namespace.php (77%) rename includes/pb-l10n.php => inc/l10n/namespace.php (94%) rename includes/pb-media.php => inc/media/namespace.php (87%) rename includes/modules/export/class-pb-export.php => inc/modules/export/class-export.php (88%) rename includes/modules/export/epub/class-pb-epub201.php => inc/modules/export/epub/class-epub201.php (82%) rename includes/modules/export/epub/class-pb-epub3.php => inc/modules/export/epub/class-epub3.php (82%) rename {includes => inc}/modules/export/epub/templates/epub201/container.php (77%) rename {includes => inc}/modules/export/epub/templates/epub201/html.php (87%) rename {includes => inc}/modules/export/epub/templates/epub201/ibooks.php (71%) rename {includes => inc}/modules/export/epub/templates/epub201/mobi-hacks.xsl (100%) rename {includes => inc}/modules/export/epub/templates/epub201/ncx.php (90%) rename {includes => inc}/modules/export/epub/templates/epub201/opf.php (94%) rename {includes => inc}/modules/export/epub/templates/epub3/css/css3.css (100%) rename {includes => inc}/modules/export/epub/templates/epub3/html.php (85%) rename {includes => inc}/modules/export/epub/templates/epub3/opf.php (93%) rename {includes => inc}/modules/export/epub/templates/epub3/toc.php (87%) rename includes/modules/export/indesign/class-pb-icml.php => inc/modules/export/indesign/class-icml.php (93%) rename {includes => inc}/modules/export/indesign/templates/xhtml.php (96%) rename includes/modules/export/mobi/class-pb-kindlegen.php => inc/modules/export/mobi/class-kindlegen.php (99%) rename includes/modules/export/odt/class-pb-odt.php => inc/modules/export/odt/class-odt.php (81%) rename {includes => inc}/modules/export/odt/xhtml2odt.xsl (100%) rename includes/modules/export/prince/class-pb-pdf.php => inc/modules/export/prince/class-pdf.php (80%) rename includes/modules/export/prince/class-pb-printpdf.php => inc/modules/export/prince/class-printpdf.php (81%) rename includes/modules/export/wordpress/class-pb-vanillawxr.php => inc/modules/export/wordpress/class-vanillawxr.php (95%) rename includes/modules/export/wordpress/class-pb-wxr.php => inc/modules/export/wordpress/class-wxr.php (87%) rename includes/modules/export/xhtml/class-pb-xhtml11.php => inc/modules/export/xhtml/class-xhtml11.php (88%) rename includes/modules/import/class-pb-import.php => inc/modules/import/class-import.php (83%) rename includes/modules/import/epub/class-pb-epub201.php => inc/modules/import/epub/class-epub201.php (83%) rename includes/modules/import/html/class-pb-xhtml.php => inc/modules/import/html/class-xhtml.php (86%) rename includes/modules/import/odf/class-pb-odt.php => inc/modules/import/odf/class-odt.php (86%) rename {includes => inc}/modules/import/odf/xsl/odt2html.xsl (100%) rename includes/modules/import/ooxml/class-pb-docx.php => inc/modules/import/ooxml/class-docx.php (87%) rename {includes => inc}/modules/import/ooxml/xsl/docx2html.xsl (100%) rename includes/modules/import/wordpress/class-pb-parser.php => inc/modules/import/wordpress/class-parser.php (93%) rename includes/modules/import/wordpress/class-pb-wxr.php => inc/modules/import/wordpress/class-wxr.php (76%) rename includes/modules/searchandreplace/class-pb-result.php => inc/modules/searchandreplace/class-result.php (94%) rename includes/modules/searchandreplace/class-pb-search.php => inc/modules/searchandreplace/class-search.php (84%) rename includes/modules/searchandreplace/class-pb-searchandreplace.php => inc/modules/searchandreplace/class-searchandreplace.php (68%) rename includes/modules/searchandreplace/types/class-pb-content.php => inc/modules/searchandreplace/types/class-content.php (93%) rename includes/modules/searchandreplace/types/class-pb-part.php => inc/modules/searchandreplace/types/class-part.php (93%) rename includes/modules/themeoptions/class-pb-ebookoptions.php => inc/modules/themeoptions/class-ebookoptions.php (75%) rename includes/modules/themeoptions/class-pb-globaloptions.php => inc/modules/themeoptions/class-globaloptions.php (70%) rename includes/modules/themeoptions/class-pb-pdfoptions.php => inc/modules/themeoptions/class-pdfoptions.php (65%) rename includes/modules/themeoptions/class-pb-themeoptions.php => inc/modules/themeoptions/class-themeoptions.php (79%) rename includes/modules/themeoptions/class-pb-weboptions.php => inc/modules/themeoptions/class-weboptions.php (74%) rename includes/pb-posttype.php => inc/posttype/namespace.php (83%) rename includes/pb-redirect.php => inc/redirect/namespace.php (86%) rename includes/pb-registration.php => inc/registration/namespace.php (91%) rename includes/pb-sanitize.php => inc/sanitize/namespace.php (90%) rename includes/shortcodes/footnotes/class-pb-footnotes.php => inc/shortcodes/footnotes/class-footnotes.php (80%) rename includes/shortcodes/generics/class-pb-generics.php => inc/shortcodes/generics/class-generics.php (71%) rename includes/shortcodes/wikipublisher/class-pb-glyphs.php => inc/shortcodes/wikipublisher/class-glyphs.php (89%) create mode 100644 inc/utility/class-jsonmanifest.php rename includes/pb-utility.php => inc/utility/namespace.php (84%) create mode 100644 phpcs.ruleset.xml delete mode 100644 phpcs.xml delete mode 100644 symbionts/Browser.php diff --git a/.travis.yml b/.travis.yml index b44e3a6077..b688d331f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,11 +15,28 @@ php: - 5.6 - 7.0 - 7.1 + - nightly env: - - WP_VERSION=latest WP_MULTISITE=1 + - WP_VERSION=latest WP_MULTISITE=1 TRAVIS_NODE_VERSION="6" + - WP_VERSION=latest WP_MULTISITE=1 TRAVIS_NODE_VERSION="7" + +matrix: + allow_failures: + - php: nightly + +cache: + directories: + - $HOME/.composer/cache + - $HOME/.yarn-cache + - node_modules + - vendor before_install: + - source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION && nvm use $TRAVIS_NODE_VERSION + - node -v + +install: - composer install before_script: diff --git a/autoloader.php b/autoloader.php new file mode 100644 index 0000000000..e4aa8b50d5 --- /dev/null +++ b/autoloader.php @@ -0,0 +1,46 @@ +prefix = $prefix; + $this->prefix_length = strlen( $prefix ); + $this->path = trailingslashit( $path ); + } + + public function load( $class ) { + if ( strpos( $class, $this->prefix . self::NS_SEPARATOR ) !== 0 ) { + return; + } + + // Strip prefix from the start (ala PSR-4) + $class = substr( $class, $this->prefix_length + 1 ); + $class = strtolower( $class ); + $file = ''; + + if ( false !== ( $last_ns_pos = strripos( $class, self::NS_SEPARATOR ) ) ) { + $namespace = substr( $class, 0, $last_ns_pos ); + $class = substr( $class, $last_ns_pos + 1 ); + $file = str_replace( self::NS_SEPARATOR, DIRECTORY_SEPARATOR, $namespace ) . DIRECTORY_SEPARATOR; + } + $file .= 'class-' . str_replace( '_', '-', $class ) . '.php'; + + $path = $this->path . $file; + + if ( file_exists( $path ) ) { + require_once $path; + } + } +} + +function register_class_path( $prefix, $path ) { + $loader = new Autoloader( $prefix, $path ); + spl_autoload_register( [ $loader, 'load' ] ); +} diff --git a/bin/compile-scss.php b/bin/compile-scss.php index 3ae662ce6c..8ceb21767c 100644 --- a/bin/compile-scss.php +++ b/bin/compile-scss.php @@ -23,7 +23,7 @@ // Sassify // -------------------------------------------------------------------------------------------------------------------- -$includePaths = [ +$include_paths = [ __DIR__ . '/../assets/scss/partials', __DIR__ . '/../assets/scss/fonts', dirname( realpath( $input_file_name ) ), @@ -34,7 +34,7 @@ try { $sass = new \Leafo\ScssPhp\Compiler; $sass->setStyle( Sass::STYLE_EXPANDED ); - $sass->setImportPaths( $includePaths ); + $sass->setImportPaths( $include_paths ); $css = $sass->compileFile( $scss ); } catch ( Exception $e ) { die( $e->getMessage() ); diff --git a/composer.json b/composer.json index b4d17bce0b..1a7dd6cfc8 100644 --- a/composer.json +++ b/composer.json @@ -30,12 +30,12 @@ "pimple/pimple": "^3.0", "leafo/scssphp": "^0.6.7", "pressbooks/pb-api": "^1.1", - "perchten/rmrdir": "^1.0" + "perchten/rmrdir": "^1.0", + "sinergi/browser-detector": "^6.1" }, "require-dev": { "phpunit/phpunit": "~5.5", - "squizlabs/php_codesniffer": "^2.7", - "wp-coding-standards/wpcs": "^0.10" + "humanmade/coding-standards": "^0.2.1" }, "archive" : { "exclude": [ @@ -54,12 +54,10 @@ "scripts": { "test": [ "vendor/bin/phpunit --configuration phpunit.xml --coverage-clover coverage.xml", - "vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs", - "vendor/bin/phpcs --standard=phpcs.xml --extensions=php ." + "@standards" ], "standards": [ - "vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs", - "vendor/bin/phpcs --standard=phpcs.xml --extensions=php ." + "vendor/bin/phpcs --standard=phpcs.ruleset.xml *.php inc/ bin/" ] } } diff --git a/composer.lock b/composer.lock index 8a0f7c159f..be6ea62624 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "b2c709d3aa797e66f0b1f5bd1182701f", + "content-hash": "150db5f7140cb28f0f5a4f5065e9b8e5", "packages": [ { "name": "composer/installers", @@ -355,6 +355,55 @@ "ebooks publishing webbooks" ], "time": "2016-11-18T18:52:07+00:00" + }, + { + "name": "sinergi/browser-detector", + "version": "6.1.2", + "source": { + "type": "git", + "url": "https://github.com/sinergi/php-browser-detector.git", + "reference": "e1bee473663bb82e5ff58a3a2c0bf81c8671de5a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sinergi/php-browser-detector/zipball/e1bee473663bb82e5ff58a3a2c0bf81c8671de5a", + "reference": "e1bee473663bb82e5ff58a3a2c0bf81c8671de5a", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8 || ^5.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Sinergi\\BrowserDetector\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Schuld" + }, + { + "name": "Gabriel Bull", + "email": "me@gabrielbull.com" + } + ], + "description": "Detecting the user's browser, operating system and language.", + "keywords": [ + "browser", + "detection", + "language", + "operating system", + "os" + ], + "time": "2016-12-28T16:31:30+00:00" } ], "packages-dev": [ @@ -412,6 +461,74 @@ ], "time": "2015-06-14T21:17:01+00:00" }, + { + "name": "fig-r/psr2r-sniffer", + "version": "0.3.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig-rectified/psr2r-sniffer.git", + "reference": "cdf61b2922efb225903e52c6222d7192d3b97ebf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig-rectified/psr2r-sniffer/zipball/cdf61b2922efb225903e52c6222d7192d3b97ebf", + "reference": "cdf61b2922efb225903e52c6222d7192d3b97ebf", + "shasum": "" + }, + "require": { + "php": ">=5.4.16", + "squizlabs/php_codesniffer": "~2.3" + }, + "bin": [ + "bin/tokenize", + "bin/sniff" + ], + "type": "library", + "autoload": { + "psr-4": { + "PSR2R\\": "PSR2R" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mark Scherer", + "homepage": "http://www.dereuromark.de", + "role": "Contributor" + } + ], + "description": "Code-Sniffer, Auto-Fixer and Tokenizer for PSR2-R", + "time": "2016-07-11T14:35:34+00:00" + }, + { + "name": "humanmade/coding-standards", + "version": "0.2.1", + "source": { + "type": "git", + "url": "https://github.com/humanmade/coding-standards.git", + "reference": "1f1d90c937b1057f1c0999ac65f501db7c72f46c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/humanmade/coding-standards/zipball/1f1d90c937b1057f1c0999ac65f501db7c72f46c", + "reference": "1f1d90c937b1057f1c0999ac65f501db7c72f46c", + "shasum": "" + }, + "require": { + "fig-r/psr2r-sniffer": "^0.3.1", + "wp-coding-standards/wpcs": "^0.10.0" + }, + "type": "project", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0" + ], + "description": "Human Made coding standards", + "time": "2016-12-08T08:41:35+00:00" + }, { "name": "myclabs/deep-copy", "version": "1.6.1", diff --git a/hooks-admin.php b/hooks-admin.php index 61302a4e64..a4a34e4d73 100644 --- a/hooks-admin.php +++ b/hooks-admin.php @@ -12,15 +12,15 @@ // Includes // ------------------------------------------------------------------------------------------------------------------- -require( PB_PLUGIN_DIR . 'includes/admin/pb-dashboard.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-diagnostics.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-laf.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-plugins.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-analytics.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-metaboxes.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-customcss.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-network-managers.php' ); -require( PB_PLUGIN_DIR . 'includes/admin/pb-fonts.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/dashboard/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/diagnostics/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/laf/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/plugins/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/analytics/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/metaboxes/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/customcss/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/networkmanagers/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/fonts/namespace.php' ); // ------------------------------------------------------------------------------------------------------------------- // Look & feel of admin interface and Dashboard @@ -43,8 +43,8 @@ if ( \Pressbooks\Book::isBook() ) { // Aggressively replace default interface - add_action( 'init', array( '\Pressbooks\Modules\SearchAndReplace\SearchAndReplace', 'init' ) ); - add_action( 'init', array( '\Pressbooks\Modules\ThemeOptions\ThemeOptions', 'init' ) ); + add_action( 'init', [ '\Pressbooks\Modules\SearchAndReplace\SearchAndReplace', 'init' ] ); + add_action( 'init', [ '\Pressbooks\Modules\ThemeOptions\ThemeOptions', 'init' ] ); add_action( 'admin_init', '\Pressbooks\Admin\Laf\redirect_away_from_bad_urls' ); add_action( 'admin_menu', '\Pressbooks\Admin\Laf\replace_book_admin_menu', 1 ); add_action( 'wp_dashboard_setup', '\Pressbooks\Admin\Dashboard\replace_dashboard_widgets' ); @@ -63,7 +63,7 @@ add_action( 'wp_network_dashboard_setup', '\Pressbooks\Admin\Dashboard\replace_network_dashboard_widgets' ); } -if ( true == is_main_site() ) { +if ( true === is_main_site() ) { add_action( 'wp_dashboard_setup', '\Pressbooks\Admin\Dashboard\replace_root_dashboard_widgets' ); } @@ -127,6 +127,7 @@ } ); add_action( 'custom_metadata_manager_init_metadata', '\Pressbooks\Admin\Metaboxes\add_meta_boxes' ); +add_action( 'pb_add_bisac_subjects_field', '\Pressbooks\Admin\Metaboxes\add_bisac_subjects_field', 1 ); if ( \Pressbooks\Book::isBook() ) { add_action( 'admin_enqueue_scripts', '\Pressbooks\Admin\Metaboxes\add_metadata_styles' ); @@ -192,7 +193,7 @@ // Posts, Meta Boxes add_action( 'updated_postmeta', function ( $meta_id, $object_id, $meta_key, $meta_value ) { - if ( 'pb_language' == $meta_key ) { + if ( 'pb_language' === $meta_key ) { \Pressbooks\Book::deleteBookObjectCache(); \Pressbooks\Admin\Fonts\update_font_stacks(); } @@ -203,9 +204,9 @@ add_action( 'admin_init', '\Pressbooks\Editor\add_editor_style' ); // Overrides - add_filter( 'pb_epub_css_override', array( '\Pressbooks\Modules\ThemeOptions\EbookOptions', 'scssOverrides' ) ); - add_filter( 'pb_pdf_css_override', array( '\Pressbooks\Modules\ThemeOptions\PDFOptions', 'scssOverrides' ) ); - add_filter( 'pb_web_css_override', array( '\Pressbooks\Modules\ThemeOptions\WebOptions', 'scssOverrides' ) ); + add_filter( 'pb_epub_css_override', [ '\Pressbooks\Modules\ThemeOptions\EbookOptions', 'scssOverrides' ] ); + add_filter( 'pb_pdf_css_override', [ '\Pressbooks\Modules\ThemeOptions\PDFOptions', 'scssOverrides' ] ); + add_filter( 'pb_web_css_override', [ '\Pressbooks\Modules\ThemeOptions\WebOptions', 'scssOverrides' ] ); } // Theme Lock @@ -233,12 +234,12 @@ // Disable all pointers (i.e. tooltips) all the time, see \WP_Internal_Pointers() add_action( 'admin_init', function () { - remove_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) ); + remove_action( 'admin_enqueue_scripts', [ 'WP_Internal_Pointers', 'enqueue_scripts' ] ); } ); // Fix for "are you sure you want to leave page" message when editing a part add_action( 'admin_enqueue_scripts', function () { - if ( 'part' == get_post_type() ) { + if ( 'part' === get_post_type() ) { wp_dequeue_script( 'autosave' ); } } ); diff --git a/hooks.php b/hooks.php index fbce726c7d..77e7640641 100644 --- a/hooks.php +++ b/hooks.php @@ -12,17 +12,17 @@ // Includes // ------------------------------------------------------------------------------------------------------------------- -require( PB_PLUGIN_DIR . 'includes/admin/pb-branding.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-analytics.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-utility.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-image.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-l10n.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-posttype.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-redirect.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-registration.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-sanitize.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-media.php' ); -require( PB_PLUGIN_DIR . 'includes/pb-editor.php' ); +require( PB_PLUGIN_DIR . 'inc/admin/branding/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/analytics/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/utility/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/image/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/l10n/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/posttype/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/redirect/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/registration/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/sanitize/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/media/namespace.php' ); +require( PB_PLUGIN_DIR . 'inc/editor/namespace.php' ); Pressbooks\Utility\include_plugins(); @@ -167,8 +167,8 @@ // Theme Lock if ( \Pressbooks\Book::isBook() && \Pressbooks\ThemeLock::isLocked() ) { - add_filter( 'pb_stylesheet_directory', array( '\Pressbooks\ThemeLock', 'getLockDir' ) ); - add_filter( 'pb_stylesheet_directory_uri', array( '\Pressbooks\ThemeLock', 'getLockDirURI' ) ); + add_filter( 'pb_stylesheet_directory', [ '\Pressbooks\ThemeLock', 'getLockDir' ] ); + add_filter( 'pb_stylesheet_directory_uri', [ '\Pressbooks\ThemeLock', 'getLockDirURI' ] ); } // ------------------------------------------------------------------------------------------------------------------- diff --git a/includes/admin/pb-analytics.php b/inc/admin/analytics/namespace.php similarity index 90% rename from includes/admin/pb-analytics.php rename to inc/admin/analytics/namespace.php index eba8b7116e..4a119c8147 100644 --- a/includes/admin/pb-analytics.php +++ b/inc/admin/analytics/namespace.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Analytics; /** @@ -50,25 +51,25 @@ function network_analytics_settings_init() { __NAMESPACE__ . '\analytics_ga_mu_uaid_callback', $_page, $_section, - array( - __( 'The Google Analytics ID for your network, e.g. ‘UA-01234567-8’.', 'pressbooks' ) - ) + [ + __( 'The Google Analytics ID for your network, e.g. ‘UA-01234567-8’.', 'pressbooks' ), + ] ); register_setting( $_page, 'ga_mu_uaid', __NAMESPACE__ . '\analytics_ga_mu_uaid_sanitize' ); - if ( SUBDOMAIN_INSTALL == true ) : + if ( SUBDOMAIN_INSTALL === true ) : add_settings_field( 'ga_mu_site_specific_allowed', __( 'Site-Specific Tracking', 'pressbooks' ), __NAMESPACE__ . '\analytics_ga_mu_site_specific_allowed_callback', $_page, $_section, - array( - __( 'If enabled, the Google Analytics settings page will be visible to book administrators, allowing them to use their own Google Analytics accounts to track statistics at the book level.', 'pressbooks' ) - ) + [ + __( 'If enabled, the Google Analytics settings page will be visible to book administrators, allowing them to use their own Google Analytics accounts to track statistics at the book level.', 'pressbooks' ), + ] ); register_setting( $_page, @@ -97,9 +98,9 @@ function analytics_settings_init() { __NAMESPACE__ . '\analytics_ga_mu_uaid_callback', $_page, $_section, - array( - __( 'The Google Analytics ID for your book, e.g. ‘UA-01234567-8’.', 'pressbooks' ) - ) + [ + __( 'The Google Analytics ID for your book, e.g. ‘UA-01234567-8’.', 'pressbooks' ), + ] ); register_setting( $_page, @@ -143,6 +144,7 @@ function analytics_ga_mu_site_specific_allowed_callback( $args ) { * Analytics settings, ga_mu_uaid field sanitization * * @param $input + * * @return string */ function analytics_ga_mu_uaid_sanitize( $input ) { @@ -153,6 +155,7 @@ function analytics_ga_mu_uaid_sanitize( $input ) { * Analytics settings, ga_mu_site_specific_allowed field sanitization * * @param $input + * * @return integer */ function analytics_ga_mu_site_specific_allowed_sanitize( $input ) { @@ -166,17 +169,17 @@ function display_network_analytics_settings() { ?>

-
- * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Branding; /** @@ -13,7 +14,6 @@ * that returns a string containing a link tag for your own admin color scheme. */ function custom_color_scheme() { - // @codingStandardsIgnoreLine $html = ''; $html = apply_filters( 'pressbooks_login_color_scheme', $html ); echo $html; diff --git a/includes/admin/class-pb-catalog-list-table.php b/inc/admin/class-catalog-list-table.php similarity index 85% rename from includes/admin/class-pb-catalog-list-table.php rename to inc/admin/class-catalog-list-table.php index 988f8fde6b..5f3328cf90 100644 --- a/includes/admin/class-pb-catalog-list-table.php +++ b/inc/admin/class-catalog-list-table.php @@ -3,13 +3,10 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Admin; -use \Pressbooks\Catalog; +namespace Pressbooks\Admin; -if ( ! class_exists( 'WP_List_Table' ) ) { - require( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); -} +use Pressbooks\Catalog; /** * @see http://codex.wordpress.org/Class_Reference/WP_List_Table @@ -27,11 +24,11 @@ class Catalog_List_Table extends \WP_List_Table { */ function __construct() { - $args = array( + $args = [ 'singular' => 'book', 'plural' => 'books', // Parent will create bulk nonce: "bulk-{$plural}" 'ajax' => true, - ); + ]; parent::__construct( $args ); } @@ -69,9 +66,9 @@ function column_title( $item ) { list( $user_id, $blog_id ) = explode( ':', $item['ID'] ); // Build row actions - $actions = array( + $actions = [ 'visit' => sprintf( '%s', get_site_url( $blog_id ), __( 'Visit Book' ) ), - ); + ]; // Only include admin link if user has admin rights to the book in question if ( is_super_admin( $user_id ) || is_user_member_of_blog( $user_id, $blog_id ) ) { @@ -79,10 +76,9 @@ function column_title( $item ) { } // Return the title contents - return sprintf( '%1$s %2$s', - /*$1%s*/ + return sprintf( + '%1$s %2$s', $item['title'], - /*$2%s*/ $this->row_actions( $actions ) ); } @@ -106,21 +102,20 @@ function column_status( $item ) { // TODO, Better HTML? if ( $item['status'] ) { $status = 'Yes'; - $actions = array( + $actions = [ 'remove' => sprintf( '%s', $remove_url, __( 'Hide in Catalog', 'pressbooks' ) ), - ); + ]; } else { $status = 'No'; - $actions = array( + $actions = [ 'add' => sprintf( '%s', $add_url, __( 'Show in Catalog', 'pressbooks' ) ), - ); + ]; } // Return the title contents - return sprintf( '%1$s %2$s', - /*$1%s*/ + return sprintf( + '%1$s %2$s', $status, - /*$2%s*/ $this->row_actions( $actions ) ); } @@ -154,9 +149,7 @@ function column_cover( $item ) { function column_cb( $item ) { return sprintf( '', - /*$1%s*/ $this->_args['singular'], // Let's simply repurpose the table's singular label ("book") - /*$2%s*/ $item['ID'] // The value of the checkbox should be the record's id ); } @@ -171,14 +164,14 @@ function get_columns() { $profile = ( new Catalog() )->getProfile(); - $columns = array( + $columns = [ 'cb' => '', // Render a checkbox instead of text 'status' => __( 'Catalog Status', 'pressbooks' ), 'privacy' => __( 'Privacy Status', 'pressbooks' ), 'cover' => __( 'Cover', 'pressbooks' ), 'title' => __( 'Title', 'pressbooks' ), 'author' => __( 'Author', 'pressbooks' ), - ); + ]; for ( $i = 1; $i <= Catalog::MAX_TAGS_GROUP; ++$i ) { $columns[ "tag_{$i}" ] = ! empty( $profile[ "pb_catalog_tag_{$i}_name" ] ) ? $profile[ "pb_catalog_tag_{$i}_name" ] : __( 'Tag', 'pressbooks' ) . " $i"; @@ -199,28 +192,27 @@ function get_columns() { */ function get_sortable_columns() { - $sortable_columns = array( - 'status' => array( 'status', false ), - 'privacy' => array( 'privacy', false ), - 'title' => array( 'title', false ), - 'author' => array( 'author', false ), - 'pub_date' => array( 'pub_date', false ), - ); + $sortable_columns = [ + 'status' => [ 'status', false ], + 'privacy' => [ 'privacy', false ], + 'title' => [ 'title', false ], + 'author' => [ 'author', false ], + 'pub_date' => [ 'pub_date', false ], + ]; return $sortable_columns; } - /** * @return array An associative array containing all the bulk actions: 'slugs'=>'Visible Titles' */ function get_bulk_actions() { - $actions = array( + $actions = [ 'add' => __( 'Show in Catalog', 'pressbooks' ), 'remove' => __( 'Hide in Catalog', 'pressbooks' ), - ); + ]; return $actions; } @@ -238,7 +230,7 @@ function prepare_items() { $columns = $this->get_columns(); $hidden = $this->getHiddenColumns(); $sortable = $this->get_sortable_columns(); - $this->_column_headers = array( $columns, $hidden, $sortable ); + $this->_column_headers = [ $columns, $hidden, $sortable ]; // Get data, sort $data = $this->getItemsData(); @@ -248,10 +240,12 @@ function prepare_items() { if ( isset( $_REQUEST['orderby'] ) && isset( $valid_cols[ $_REQUEST['orderby'] ] ) ) { $data = wp_list_sort( $data, $_REQUEST['orderby'], $order ); } else { - $data = wp_list_sort( $data, array( + $data = wp_list_sort( + $data, [ 'status' => 'desc', 'title' => 'asc', - ) ); // Default + ] + ); } // Pagination @@ -272,11 +266,11 @@ function prepare_items() { /* REQUIRED. We also have to register our pagination options & calculations. */ - $args = array( + $args = [ '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 - ); + 'total_pages' => ceil( $total_items / $per_page ), // WE have to calculate the total number of pages + ]; $this->set_pagination_args( $args ); } @@ -337,19 +331,25 @@ protected function renderTagColumn( $item, $column_name ) { $html = Catalog::tagsToString( $item[ $column_name ] ); - if ( ! $html ) { $html = 'n/a'; + if ( ! $html ) { + $html = 'n/a'; } // Build row actions - $actions = array( - 'edit_tags' => sprintf( '%s', $_REQUEST['page'], 'edit_tags', $item['ID'], __( 'Edit Tags', 'pressbooks' ) ), - ); + $actions = [ + 'edit_tags' => sprintf( + '%s', + $_REQUEST['page'], + 'edit_tags', + $item['ID'], + __( 'Edit Tags', 'pressbooks' ) + ), + ]; // Return the title contents - return sprintf( '%1$s %2$s', - /*$1%s*/ + return sprintf( + '%1$s %2$s', $html, - /*$2%s*/ $this->row_actions( $actions ) ); @@ -362,9 +362,9 @@ protected function renderTagColumn( $item, $column_name ) { */ protected function getHiddenColumns() { - $hidden_columns = array( + $hidden_columns = [ 'featured', - ); + ]; return $hidden_columns; } @@ -381,8 +381,8 @@ protected function getItemsData() { $data = $catalog_obj->getAggregate(); foreach ( $data as $key => $val ) { - $data[ $key ]['status'] = ( 1 == $val['deleted'] ) ? 0 : 1; - $data[ $key ]['privacy'] = ( 1 == $val['private'] ? __( 'Private', 'pressbooks' ) : __( 'Public', 'pressbooks' ) ); + $data[ $key ]['status'] = ( ! empty( $val['deleted'] ) ) ? 0 : 1; + $data[ $key ]['privacy'] = ( ! empty( $val['private'] ) ? __( 'Private', 'pressbooks' ) : __( 'Public', 'pressbooks' ) ); $data[ $key ]['cover'] = $val['cover_url']['pb_cover_small']; } @@ -397,14 +397,13 @@ protected function getItemsData() { */ protected function searchFilter( array $data ) { - $keyword = (string) trim( @$_REQUEST['s'] ); + $keyword = ( isset( $_REQUEST['s'] ) && ! empty( $_REQUEST['s'] ) ) ? (string) trim( $_REQUEST['s'] ) : false; if ( ! $keyword ) { - // No keyword return $data; } - $filtered_data = array(); + $filtered_data = []; foreach ( $data as $_ => $val ) { if ( $this->atLeastOneKeyword( $keyword, $val ) ) { $filtered_data[] = $val; @@ -428,8 +427,10 @@ protected function atLeastOneKeyword( $keyword, array $data ) { foreach ( $data as $key => $val ) { if ( is_array( $val ) ) { $found = $this->atLeastOneKeyword( $keyword, $val ); - if ( $found ) { return true; - } else { continue; + if ( $found ) { + return true; + } else { + continue; } } elseif ( false !== stripos( $val, $keyword ) ) { return true; @@ -446,8 +447,7 @@ protected function atLeastOneKeyword( $keyword, array $data ) { static function addMenu() { $url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); - $view_url = static::viewCatalogUrl(); // Verifies $_REQUEST['user_id'] - + $view_url = static::viewCatalogUrl(); $edit_url = $url . '&action=edit_profile'; if ( isset( $_REQUEST['user_id'] ) ) { $edit_url .= '&user_id=' . $_REQUEST['user_id']; @@ -461,8 +461,10 @@ static function addMenu() {

-

' . __( 'Show in Catalog', 'pressbooks' ) . '' ); ?>
- ' . __( 'Hide in Catalog', 'pressbooks' ) . '' ); ?>

+

' . __( 'Show in Catalog', 'pressbooks' ) . '' ); ?> +
+ ' . __( 'Hide in Catalog', 'pressbooks' ) . '' ); ?> +

Catalog Profile page (ex: Authors, Book Genre), then add the appropriate tags to each individual book.', 'pressbooks' ), $edit_url ); ?>

@@ -479,17 +481,18 @@ static function addMenu() { -
- - - + + +
-
- * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin; class ExportOptions extends \Pressbooks\Options { @@ -15,24 +16,24 @@ class ExportOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Export options. - * - * @var array - */ + * Export options. + * + * @var array + */ public $options; /** - * Export defaults. - * - * @var array - */ + * Export defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -55,39 +56,39 @@ function init() { add_settings_section( $_section, '', - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'email_validation_logs', __( 'Email Validation Logs', 'pressbooks' ), - array( $this, 'renderEmailValidationLogsField' ), + [ $this, 'renderEmailValidationLogsField' ], $_page, $_section, - array( + [ '0' => __( 'No. Ignore validation errors.', 'pressbooks' ), '1' => __( 'Yes.', 'pressbooks' ) . ' ' . __( 'Email me validation error logs on export.', 'pressbooks' ), - ) + ] ); if ( ! \Pressbooks\CustomCss::isCustomCss() ) { add_settings_field( 'theme_lock', __( 'Lock Theme', 'pressbooks' ), - array( $this, 'renderThemeLockField' ), + [ $this, 'renderThemeLockField' ], $_page, $_section, - array( + [ __( 'Lock your theme at its current version.', 'pressbooks' ), - ) + ] ); } register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -99,7 +100,7 @@ function display() { } function render() { - ?> + ?>

getTitle(); ?>

@@ -118,7 +119,7 @@ function upgrade( $version ) { function doInitialUpgrade() { $_option = $this->getSlug(); - $options = array(); + $options = []; $email_validation_logs = get_option( 'pressbooks_email_validation_logs', 0 ); @@ -130,31 +131,37 @@ function doInitialUpgrade() { /** * Render the email_validation_logs radio buttons. + * * @param array $args */ function renderEmailValidationLogsField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'email_validation_logs', - 'name' => $this->getSlug(), - 'option' => 'email_validation_logs', - 'value' => ( isset( $this->options['email_validation_logs'] ) ) ? $this->options['email_validation_logs'] : '', - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'email_validation_logs', + 'name' => $this->getSlug(), + 'option' => 'email_validation_logs', + 'value' => ( isset( $this->options['email_validation_logs'] ) ) ? $this->options['email_validation_logs'] : '', + 'choices' => $args, + ] + ); } /** * Render the lock_theme checkbox. + * * @param array $args */ function renderThemeLockField( $args ) { - $this->renderCheckbox( array( - 'id' => 'theme_lock', - 'name' => $this->getSlug(), - 'option' => 'theme_lock', - 'value' => ( isset( $this->options['theme_lock'] ) ) ? $this->options['theme_lock'] : '', - 'label' => $args[0], - 'description' => __( 'This will prevent any changes to your book’s appearance and page count when themes are updated.', 'pressbooks' ), - ) ); + $this->renderCheckbox( + [ + 'id' => 'theme_lock', + 'name' => $this->getSlug(), + 'option' => 'theme_lock', + 'value' => ( isset( $this->options['theme_lock'] ) ) ? $this->options['theme_lock'] : '', + 'label' => $args[0], + 'description' => __( 'This will prevent any changes to your book’s appearance and page count when themes are updated.', 'pressbooks' ), + ] + ); } /** @@ -181,10 +188,10 @@ static function getTitle() { * @return array $defaults */ static function getDefaults() { - return array( + return [ 'email_validation_logs' => 0, 'theme_lock' => 0, - ); + ]; } /** @@ -193,16 +200,17 @@ static function getDefaults() { * @return array $options */ static function getBooleanOptions() { - return array( + return [ 'email_validation_logs', 'theme_lock', - ); + ]; } /** * Filter the array of default values for this set of options * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { diff --git a/includes/admin/class-pb-network-managers-list-table.php b/inc/admin/class-network-managers-list-table.php similarity index 63% rename from includes/admin/class-pb-network-managers-list-table.php rename to inc/admin/class-network-managers-list-table.php index 8aa7f87d39..10861a82ef 100644 --- a/includes/admin/class-pb-network-managers-list-table.php +++ b/inc/admin/class-network-managers-list-table.php @@ -8,10 +8,6 @@ namespace Pressbooks\Admin; -if ( ! class_exists( 'WP_List_Table' ) ) { - require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); -} - /** * @see http://codex.wordpress.org/Class_Reference/WP_List_Table */ @@ -22,11 +18,13 @@ class Network_Managers_List_Table extends \WP_List_Table { ***************************************************************************/ function __construct() { - parent::__construct( array( - 'singular' => 'super-admin', - 'plural' => 'super-admins', - 'ajax' => false, - ) ); + parent::__construct( + [ + 'singular' => 'super-admin', + 'plural' => 'super-admins', + 'ajax' => false, + ] + ); } @@ -35,7 +33,9 @@ function __construct() { * Custom column method for the display_name column. * * @see WP_List_Table::::single_row_columns() + * * @param array $item A singular item (one full row's worth of data) + * * @return string Text to be placed inside the column **************************************************************************/ function column_display_name( $item ) { @@ -46,7 +46,9 @@ function column_display_name( $item ) { * Custom column method for the user_email column. * * @see WP_List_Table::::single_row_columns() + * * @param array $item A singular item (one full row's worth of data) + * * @return string Text to be placed inside the column **************************************************************************/ function column_user_email( $item ) { @@ -58,7 +60,9 @@ function column_user_email( $item ) { * Custom column method for the user_login column. * * @see WP_List_Table::::single_row_columns() + * * @param array $item A singular item (one full row's worth of data) + * * @return string HTML to be placed inside the column **************************************************************************/ function column_user_login( $item ) { @@ -67,24 +71,25 @@ function column_user_login( $item ) { $current_user = wp_get_current_user(); if ( absint( $item['ID'] ) !== absint( $current_user->ID ) ) { // Don't let users restrict themselves - if ( 1 == $item['restricted'] ) { - $actions = array( - 'unrestrict' => '' . __( 'Unrestrict Access', 'pressbooks' ) . '', - ); + if ( ! empty( $item['restricted'] ) ) { + $actions = [ + 'unrestrict' => '' . __( 'Unrestrict Access', 'pressbooks' ) . '', + ]; } else { - $actions = array( - 'restrict' => '' . __( 'Restrict Access', 'pressbooks' ) . '', - ); + $actions = [ + 'restrict' => '' . __( 'Restrict Access', 'pressbooks' ) . '', + ]; } } else { - $actions = array(); + $actions = []; } // Return the title contents - return sprintf('%1$s %2$s %3$s', - /*$1%s*/ get_avatar( $item['ID'], 32 ), - /*$2%s*/ '', - /*$3%s*/ $this->row_actions( $actions ) + return sprintf( + '%1$s %3$s', + get_avatar( $item['ID'], 32 ), + $item['user_login'], + $this->row_actions( $actions ) ); } @@ -96,11 +101,11 @@ function column_user_login( $item ) { * @return array An associative array containing column information: 'slugs'=>'Visible Titles' **************************************************************************/ function get_columns() { - $columns = array( - 'user_login' => 'Username', - 'display_name' => 'Name', - 'user_email' => 'E-mail', - ); + $columns = [ + 'user_login' => 'Username', + 'display_name' => 'Name', + 'user_email' => 'E-mail', + ]; return $columns; } @@ -111,11 +116,11 @@ function get_columns() { * @return array An associative array containing all the columns that should be sortable: 'slugs'=>array('data_values',bool) **************************************************************************/ function get_sortable_columns() { - $sortable_columns = array( - 'user_login' => array( 'user_login', true ), //true means it's already sorted - 'display_name' => array( 'display_name', false ), - 'user_email' => array( 'user_email', false ), - ); + $sortable_columns = [ + 'user_login' => [ 'user_login', true ], // True means it's already sorted + 'display_name' => [ 'display_name', false ], + 'user_email' => [ 'user_email', false ], + ]; return $sortable_columns; } @@ -123,11 +128,10 @@ function get_sortable_columns() { * Set up classes for a single row based on active status * * @param object $item The current item - * @return string A row of cells */ function single_row( $item ) { $class = ''; - if ( 1 == $item['restricted'] ) { + if ( ! empty( $item['restricted'] ) ) { $class = 'restricted'; } echo ""; @@ -147,59 +151,49 @@ function single_row( $item ) { * @uses $this->set_pagination_args() **************************************************************************/ function prepare_items() { - global $wpdb; /** * Define column headers. */ $columns = $this->get_columns(); - $hidden = array(); + $hidden = []; $sortable = $this->get_sortable_columns(); /** * Build column header array. */ - $this->_column_headers = array( $columns, $hidden, $sortable ); + $this->_column_headers = [ $columns, $hidden, $sortable ]; /** * Check for sorting input and sort the data in our array accordingly. */ - $data = $wpdb->get_results( "SELECT * FROM {$wpdb->sitemeta} WHERE meta_key = 'site_admins'" ); // Get site admins - $data = maybe_unserialize( $data[0]->meta_value ); - if ( ! is_array( $data ) ) { - $data = array( $data ); - } - $restricted = $wpdb->get_results( "SELECT * FROM {$wpdb->sitemeta} WHERE meta_key = 'pressbooks_network_managers'" ); - // Get restricted site admins (network managers) - if ( $restricted ) { - $restricted = maybe_unserialize( $restricted[0]->meta_value ); - } else { - $restricted = array(); - } - $tmp = array(); - foreach ( $data as $id => $username ) { + $network_admins = get_site_option( 'site_admins' ); + $network_managers = get_network_option( null, 'pressbooks_network_managers', [] ); + $tmp = []; + foreach ( $network_admins as $id => $username ) { $user = get_user_by( 'slug', $username ); $user = $user->data; - $is_restricted = ( in_array( $user->ID, $restricted ) ) ? true : false; // Determine admin's restricted status - $tmp[ $id ] = array( - 'ID' => $user->ID, - 'user_login' => $user->user_login, - 'display_name' => $user->display_name, - 'user_email' => $user->user_email, - 'restricted' => $is_restricted, - ); + $is_restricted = ( in_array( absint( $user->ID ), $network_managers, true ) ) ? true : false; // Determine admin's restricted status + $tmp[ $id ] = [ + 'ID' => $user->ID, + 'user_login' => $user->user_login, + 'display_name' => $user->display_name, + 'user_email' => $user->user_email, + 'restricted' => $is_restricted, + ]; } - $data = $tmp; - usort( $data, function( $a, $b ) { - $orderby = ( ! empty( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : 'user_login'; - $order = ( ! empty( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : 'asc'; - $result = strcmp( $a[ $orderby ], $b[ $orderby ] ); - return ( 'asc' === $order ) ? $result : -$result; - }); - - $this->items = $data; // Return our data + $network_admins = $tmp; + usort( + $network_admins, function ( $a, $b ) { + $orderby = ( ! empty( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : 'user_login'; + $order = ( ! empty( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : 'asc'; + $result = strcmp( $a[ $orderby ], $b[ $orderby ] ); + return ( 'asc' === $order ) ? $result : -$result; + } + ); + $this->items = $network_admins; // Return our data } } diff --git a/includes/admin/class-pb-publishoptions.php b/inc/admin/class-publishoptions.php similarity index 71% rename from includes/admin/class-pb-publishoptions.php rename to inc/admin/class-publishoptions.php index 19f6bc53ec..d09fb16410 100644 --- a/includes/admin/class-pb-publishoptions.php +++ b/inc/admin/class-publishoptions.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin; class PublishOptions extends \Pressbooks\Options { @@ -15,26 +16,26 @@ class PublishOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Publish options. - * - * @var array - */ + * Publish options. + * + * @var array + */ public $options; /** - * Publish defaults. - * - * @var array - */ + * Publish defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { - $this->options = $options; + $this->options = $options; $this->defaults = $this->getDefaults(); $this->urls = $this->getUrlOptions(); @@ -55,14 +56,14 @@ function init() { add_settings_section( $_section, '', - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'amazon', __( 'Amazon URL', 'pressbooks' ), - array( $this, 'renderAmazonField' ), + [ $this, 'renderAmazonField' ], $_page, $_section ); @@ -70,7 +71,7 @@ function init() { add_settings_field( 'oreilly', __( 'O\'Reilly URL', 'pressbooks' ), - array( $this, 'renderOReillyField' ), + [ $this, 'renderOReillyField' ], $_page, $_section ); @@ -78,7 +79,7 @@ function init() { add_settings_field( 'barnesandnoble', __( 'Barnes and Noble URL', 'pressbooks' ), - array( $this, 'renderBarnesAndNobleField' ), + [ $this, 'renderBarnesAndNobleField' ], $_page, $_section ); @@ -86,7 +87,7 @@ function init() { add_settings_field( 'kobo', __( 'Kobo URL', 'pressbooks' ), - array( $this, 'renderKoboField' ), + [ $this, 'renderKoboField' ], $_page, $_section ); @@ -94,7 +95,7 @@ function init() { add_settings_field( 'ibooks', __( 'iBooks URL', 'pressbooks' ), - array( $this, 'renderiBooksField' ), + [ $this, 'renderiBooksField' ], $_page, $_section ); @@ -102,7 +103,7 @@ function init() { add_settings_field( 'otherservice', __( 'Other Service URL', 'pressbooks' ), - array( $this, 'renderOtherServiceField' ), + [ $this, 'renderOtherServiceField' ], $_page, $_section ); @@ -110,7 +111,7 @@ function init() { register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -142,7 +143,7 @@ function display() { } function render() { - ?> + ?>

getTitle(); ?>

@@ -159,90 +160,103 @@ function upgrade( $version ) { } } - function doInitialUpgrade() {} + function doInitialUpgrade() { + } /** * Render the amazon field. */ function renderAmazonField() { - $this->renderField( array( - 'id' => 'amazon', - 'name' => $this->getSlug(), - 'option' => 'amazon', - 'value' => ( isset( $this->options['amazon'] ) ) ? $this->options['amazon'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'amazon', + 'name' => $this->getSlug(), + 'option' => 'amazon', + 'value' => ( isset( $this->options['amazon'] ) ) ? $this->options['amazon'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** * Render the oreilly field. */ function renderOReillyField() { - $this->renderField( array( - 'id' => 'oreilly', - 'name' => $this->getSlug(), - 'option' => 'oreilly', - 'value' => ( isset( $this->options['oreilly'] ) ) ? $this->options['oreilly'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'oreilly', + 'name' => $this->getSlug(), + 'option' => 'oreilly', + 'value' => ( isset( $this->options['oreilly'] ) ) ? $this->options['oreilly'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** * Render the barnesandnoble field. */ function renderBarnesAndNobleField() { - $this->renderField( array( - 'id' => 'barnesandnoble', - 'name' => $this->getSlug(), - 'option' => 'barnesandnoble', - 'value' => ( isset( $this->options['barnesandnoble'] ) ) ? $this->options['barnesandnoble'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'barnesandnoble', + 'name' => $this->getSlug(), + 'option' => 'barnesandnoble', + 'value' => ( isset( $this->options['barnesandnoble'] ) ) ? $this->options['barnesandnoble'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** * Render the barnesandnoble field. */ function renderKoboField() { - $this->renderField( array( - 'id' => 'kobo', - 'name' => $this->getSlug(), - 'option' => 'kobo', - 'value' => ( isset( $this->options['kobo'] ) ) ? $this->options['kobo'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'kobo', + 'name' => $this->getSlug(), + 'option' => 'kobo', + 'value' => ( isset( $this->options['kobo'] ) ) ? $this->options['kobo'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** * Render the ibooks field. */ function renderiBooksField() { - $this->renderField( array( - 'id' => 'ibooks', - 'name' => $this->getSlug(), - 'option' => 'ibooks', - 'value' => ( isset( $this->options['ibooks'] ) ) ? $this->options['ibooks'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'ibooks', + 'name' => $this->getSlug(), + 'option' => 'ibooks', + 'value' => ( isset( $this->options['ibooks'] ) ) ? $this->options['ibooks'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** * Render the ibooks field. */ function renderOtherServiceField() { - $this->renderField( array( - 'id' => 'otherservice', - 'name' => $this->getSlug(), - 'option' => 'otherservice', - 'value' => ( isset( $this->options['otherservice'] ) ) ? $this->options['otherservice'] : '', - 'type' => 'url', - 'class' => 'regular-text code', - ) ); + $this->renderField( + [ + 'id' => 'otherservice', + 'name' => $this->getSlug(), + 'option' => 'otherservice', + 'value' => ( isset( $this->options['otherservice'] ) ) ? $this->options['otherservice'] : '', + 'type' => 'url', + 'class' => 'regular-text code', + ] + ); } /** @@ -269,14 +283,14 @@ static function getTitle() { * @return array $defaults */ static function getDefaults() { - return array( + return [ 'amazon' => '', 'oreilly' => '', 'barnesandnoble' => '', 'kobo' => '', 'ibooks' => '', 'otherservice' => '', - ); + ]; } /** @@ -285,20 +299,21 @@ static function getDefaults() { * @return array $options */ static function getUrlOptions() { - return array( + return [ 'amazon', 'oreilly', 'barnesandnoble', 'kobo', 'ibooks', 'otherservice', - ); + ]; } /** * Filter the array of default values for this set of options * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { diff --git a/includes/admin/pb-customcss.php b/inc/admin/customcss/namespace.php similarity index 83% rename from includes/admin/pb-customcss.php rename to inc/admin/customcss/namespace.php index cfe7b6ce0d..c5f47ccdd8 100644 --- a/includes/admin/pb-customcss.php +++ b/inc/admin/customcss/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Admin\CustomCss; +namespace Pressbooks\Admin\CustomCss; use Pressbooks\Book; use Pressbooks\Container; @@ -25,8 +25,9 @@ function add_menu() { */ function redirect_css_editor() { - $post_id = absint( @$_REQUEST['post'] ); - if ( ! $post_id ) { + if ( isset( $_REQUEST['post'] ) && ! empty( $_REQUEST['post'] ) ) { + $post_id = absint( $_REQUEST['post'] ); + } else { return; // Do nothing } @@ -35,7 +36,7 @@ function redirect_css_editor() { return; // Do nothing } - if ( 'custom-css' != $post->post_type ) { + if ( 'custom-css' !== $post->post_type ) { return; // Do nothing } @@ -52,11 +53,12 @@ function display_custom_css() { $custom_css = new CustomCss(); $slug = isset( $_GET['slug'] ) ? $_GET['slug'] : get_transient( 'pb-last-custom-css-slug' ); - if ( ! $slug ) { $slug = 'web'; + if ( ! $slug ) { + $slug = 'web'; } $supported = array_keys( $custom_css->supported ); - if ( ! in_array( $slug, $supported ) ) { + if ( ! in_array( $slug, $supported, true ) ) { wp_die( "Unknown slug: $slug" ); } @@ -65,13 +67,13 @@ function display_custom_css() { wp_die( sprintf( __( 'Unexpected Error: There was a problem trying to query slug: %s - Please contact technical support.', 'pressbooks' ), $slug ) ); } - $vars = array( + $vars = [ 'slugs_dropdown' => render_dropdown_for_slugs( $custom_css, $slug ), 'css_copy_dropdown' => render_dropdown_for_css_copy( $custom_css, $slug ), 'revisions_table' => render_revisions_table( $custom_css, $slug, $css_post->ID ), 'post_id' => absint( $css_post->ID ), 'my_custom_css' => $css_post->post_content, - ); + ]; load_custom_css_template( $vars ); set_transient( 'pb-last-custom-css-slug', $slug ); @@ -84,9 +86,7 @@ function display_custom_css() { * @param array $vars */ function load_custom_css_template( $vars ) { - - // @codingStandardsIgnoreLine - extract( $vars ); + extract( $vars ); // @codingStandardsIgnoreLine require( PB_PLUGIN_DIR . 'templates/admin/custom-css.php' ); } @@ -102,14 +102,14 @@ function load_custom_css_template( $vars ) { */ function render_revisions_table( $custom_css, $slug, $post_id ) { - $args = array( + $args = [ 'posts_per_page' => 10, 'post_type' => 'revision', 'post_status' => 'inherit', 'post_parent' => $post_id, 'orderby' => 'date', 'order' => 'DESC', - ); + ]; $q = new \WP_Query(); $results = $q->query( $args ); @@ -155,10 +155,10 @@ function render_dropdown_for_slugs( $custom_css, $slug ) { $html .= ''; $html .= ''; foreach ( $themes as $key => $theme ) { - if ( 'pressbooks-custom-css' == $key ) { continue; // Skip + if ( 'pressbooks-custom-css' === $key ) { + continue; // Skip } $html .= ''; @@ -236,13 +237,13 @@ function render_dropdown_for_css_copy( $custom_css, $slug ) { function load_css_from() { check_ajax_referer( 'pb-load-css-from' ); - if ( false == current_user_can( 'edit_theme_options' ) ) { - die( - 1 ); + if ( empty( current_user_can( 'edit_theme_options' ) ) ) { + die( -1 ); } $css = ''; - $themes = wp_get_themes( array( 'allowed' => true ) ); - list( $theme, $slug ) = explode( '__', @$_POST['slug'] ); + $themes = wp_get_themes( [ 'allowed' => true ] ); + list( $theme, $slug ) = explode( '__', $_POST['slug'] ); if ( isset( $themes[ $theme ] ) ) { @@ -253,8 +254,10 @@ function load_css_from() { $sass = Container::get( 'Sass' ); + $path_to_style = ''; + $uri_to_style = ''; if ( $sass->isCurrentThemeCompatible( 1, $theme ) ) { - if ( 'web' == $slug ) { + if ( 'web' === $slug ) { $path_to_style = realpath( $theme->get_stylesheet_directory() . '/style.scss' ); $uri_to_style = $theme->get_stylesheet_directory_uri(); } else { @@ -264,7 +267,7 @@ function load_css_from() { } elseif ( $sass->isCurrentThemeCompatible( 2, $theme ) ) { $path_to_style = realpath( $theme->get_stylesheet_directory() . "/assets/styles/$slug/style.scss" ); $uri_to_style = false; // We don't want a URI for EPUB or Prince exports - if ( 'web' == $slug ) { + if ( 'web' === $slug ) { $uri_to_style = $theme->get_stylesheet_directory_uri(); } } @@ -275,13 +278,15 @@ function load_css_from() { if ( $sass->isCurrentThemeCompatible( 1, $theme ) ) { $includes = [ - $sass->pathToUserGeneratedSass(), - $sass->pathToPartials(), - $sass->pathToFonts(), - $theme->get_stylesheet_directory(), + $sass->pathToUserGeneratedSass(), + $sass->pathToPartials(), + $sass->pathToFonts(), + $theme->get_stylesheet_directory(), ]; } elseif ( $sass->isCurrentThemeCompatible( 2, $theme ) ) { $includes = $sass->defaultIncludePaths( $slug, $theme ); + } else { + $includes = []; } $css = $sass->compile( $scss, $includes ); @@ -296,7 +301,7 @@ function load_css_from() { // Send back JSON header( 'Content-Type: application/json' ); - $json = json_encode( array( 'content' => $css ) ); + $json = json_encode( [ 'content' => $css ] ); echo $json; // @see http://codex.wordpress.org/AJAX_in_Plugins#Error_Return_Values @@ -319,23 +324,25 @@ function fix_url_paths( $css, $style_uri ) { $style_uri = rtrim( trim( $style_uri ), '/' ); } - // Search for url("*"), url('*'), and url(*) + // Search for all possible permutations of CSS url syntax: url("*"), url('*'), and url(*) $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; - $css = preg_replace_callback( $url_regex, function ( $matches ) use ( $style_uri ) { + $css = preg_replace_callback( + $url_regex, function ( $matches ) use ( $style_uri ) { - $url = $matches[3]; - $url = ltrim( trim( $url ), '/' ); + $url = $matches[3]; + $url = ltrim( trim( $url ), '/' ); - if ( preg_match( '#^https?://#i', $url ) ) { - return $matches[0]; // No change - } + if ( preg_match( '#^https?://#i', $url ) ) { + return $matches[0]; // No change + } - if ( $style_uri ) { - return "url($style_uri/$url)"; - } else { - return "url($url)"; - } - }, $css ); + if ( $style_uri ) { + return "url($style_uri/$url)"; + } else { + return "url($url)"; + } + }, $css + ); return $css; } diff --git a/includes/admin/pb-dashboard.php b/inc/admin/dashboard/namespace.php similarity index 72% rename from includes/admin/pb-dashboard.php rename to inc/admin/dashboard/namespace.php index 4517f58988..a6d2ec75d5 100644 --- a/includes/admin/pb-dashboard.php +++ b/inc/admin/dashboard/namespace.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Dashboard; /** @@ -16,12 +17,16 @@ function replace_network_dashboard_widgets() { unset( $wp_meta_boxes['dashboard-network']['side']['core']['dashboard_primary'] ); // Add our news feed. - $options = array_map( 'stripslashes_deep', get_site_option( 'pressbooks_dashboard_feed', [ - 'display_feed' => 1, - 'url' => 'https://pressbooks.com/feed/', - 'title' => __( 'Pressbooks News', 'pressbooks' ), - ] ) ); - if ( 1 == $options['display_feed'] ) { + $options = array_map( + 'stripslashes_deep', get_site_option( + 'pressbooks_dashboard_feed', [ + 'display_feed' => 1, + 'url' => 'https://pressbooks.com/feed/', + 'title' => __( 'Pressbooks News', 'pressbooks' ), + ] + ) + ); + if ( ! empty( $options['display_feed'] ) ) { add_meta_box( 'pb_dashboard_widget_blog', $options['title'], __NAMESPACE__ . '\display_pressbooks_blog', 'dashboard-network', 'side', 'low' ); } } @@ -39,12 +44,16 @@ function replace_root_dashboard_widgets() { unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'] ); // Add our news feed. - $options = array_map( 'stripslashes_deep', get_site_option( 'pressbooks_dashboard_feed', [ - 'display_feed' => 1, - 'url' => 'https://pressbooks.com/feed/', - 'title' => __( 'Pressbooks News', 'pressbooks' ), - ] ) ); - if ( 1 == $options['display_feed'] ) { + $options = array_map( + 'stripslashes_deep', get_site_option( + 'pressbooks_dashboard_feed', [ + 'display_feed' => 1, + 'url' => 'https://pressbooks.com/feed/', + 'title' => __( 'Pressbooks News', 'pressbooks' ), + ] + ) + ); + if ( ! empty( $options['display_feed'] ) ) { add_meta_box( 'pb_dashboard_widget_blog', $options['title'], __NAMESPACE__ . '\display_pressbooks_blog', 'dashboard', 'side', 'low' ); } } @@ -57,10 +66,10 @@ function replace_dashboard_widgets() { global $wp_meta_boxes; // Remove all dashboard widgets - foreach ( $wp_meta_boxes['dashboard'] as $widgetSection => $widgetType ) { - foreach ( $widgetType as $widgetCat => $widget ) { - foreach ( $widget as $widgetName => $widgetData ) { - unset( $wp_meta_boxes['dashboard'][ $widgetSection ][ $widgetCat ][ $widgetName ] ); + foreach ( $wp_meta_boxes['dashboard'] as $widget_section => $widget_type ) { + foreach ( $widget_type as $widget_cat => $widget ) { + foreach ( $widget as $widget_name => $widget_data ) { + unset( $wp_meta_boxes['dashboard'][ $widget_section ][ $widget_cat ][ $widget_name ] ); } } } @@ -70,12 +79,16 @@ function replace_dashboard_widgets() { add_meta_box( 'pb_dashboard_widget_users', __( 'Users', 'pressbooks' ), __NAMESPACE__ . '\display_users_widget', 'dashboard', 'side', 'high' ); // Add our news feed. - $options = array_map( 'stripslashes_deep', get_site_option( 'pressbooks_dashboard_feed', [ - 'display_feed' => 1, - 'url' => 'https://pressbooks.com/feed/', - 'title' => __( 'Pressbooks News', 'pressbooks' ), - ] ) ); - if ( 1 == $options['display_feed'] ) { + $options = array_map( + 'stripslashes_deep', get_site_option( + 'pressbooks_dashboard_feed', [ + 'display_feed' => 1, + 'url' => 'https://pressbooks.com/feed/', + 'title' => __( 'Pressbooks News', 'pressbooks' ), + ] + ) + ); + if ( ! empty( $options['display_feed'] ) ) { add_meta_box( 'pb_dashboard_widget_blog', $options['title'], __NAMESPACE__ . '\display_pressbooks_blog', 'dashboard', 'side', 'low' ); } @@ -128,19 +141,25 @@ function display_book_widget() { */ function display_pressbooks_blog() { - $options = array_map( 'stripslashes_deep', get_site_option( 'pressbooks_dashboard_feed', [ - 'display_feed' => 1, - 'url' => 'https://pressbooks.com/feed/', - 'title' => 'Pressbooks News', - ] ) ); - - wp_widget_rss_output( array( - 'url' => $options['url'], - 'items' => 5, - 'show_summary' => 1, - 'show_author' => 0, - 'show_date' => 1, - ) ); + $options = array_map( + 'stripslashes_deep', get_site_option( + 'pressbooks_dashboard_feed', [ + 'display_feed' => 1, + 'url' => 'https://pressbooks.com/feed/', + 'title' => 'Pressbooks News', + ] + ) + ); + + wp_widget_rss_output( + [ + 'url' => $options['url'], + 'items' => 5, + 'show_summary' => 1, + 'show_author' => 0, + 'show_date' => 1, + ] + ); } @@ -169,7 +188,7 @@ function display_users_widget() { * */ function add_menu() { - $page = add_submenu_page( + add_submenu_page( 'settings.php', __( 'Dashboard', 'pressbooks' ), __( 'Dashboard', 'pressbooks' ), @@ -189,7 +208,6 @@ function options() { function dashboard_options_init() { $_page = 'pb_dashboard'; - $_option = 'pressbooks_dashboard_feed'; add_settings_section( 'dashboard_feed', @@ -204,26 +222,26 @@ function dashboard_options_init() { __NAMESPACE__ . '\display_feed_callback', $_page, 'dashboard_feed', - array( - 'description' => __( 'Display an RSS feed widget on the dashboard.', 'pressbooks' ), - ) + [ + 'description' => __( 'Display an RSS feed widget on the dashboard.', 'pressbooks' ), + ] ); - add_settings_field( - 'title', - __( 'Feed Title', 'pressbooks' ), - __NAMESPACE__ . '\title_callback', - $_page, - 'dashboard_feed' - ); - - add_settings_field( - 'url', - __( 'Feed URL', 'pressbooks' ), - __NAMESPACE__ . '\url_callback', - $_page, - 'dashboard_feed' - ); + add_settings_field( + 'title', + __( 'Feed Title', 'pressbooks' ), + __NAMESPACE__ . '\title_callback', + $_page, + 'dashboard_feed' + ); + + add_settings_field( + 'url', + __( 'Feed URL', 'pressbooks' ), + __NAMESPACE__ . '\url_callback', + $_page, + 'dashboard_feed' + ); register_setting( $_page, @@ -231,17 +249,17 @@ function dashboard_options_init() { __NAMESPACE__ . '\display_feed_sanitize' ); - register_setting( - $_page, - 'title', - __NAMESPACE__ . '\title_sanitize' - ); - - register_setting( - $_page, - 'url', - __NAMESPACE__ . '\url_sanitize' - ); + register_setting( + $_page, + 'title', + __NAMESPACE__ . '\title_sanitize' + ); + + register_setting( + $_page, + 'url', + __NAMESPACE__ . '\url_sanitize' + ); } function dashboard_feed_callback( $args ) { @@ -250,11 +268,13 @@ function dashboard_feed_callback( $args ) { 1, 'url' => 'https://pressbooks.com/feed/', 'title' => 'Pressbooks News', - ] ); + ] + ); $html = ''; $html .= '

' . $args['description'] . '

'; @@ -262,21 +282,27 @@ function display_feed_callback( $args ) { } function title_callback( $args ) { - $options = array_map( 'stripslashes_deep', get_site_option( 'pressbooks_dashboard_feed', [ - 'display_feed' => 1, - 'url' => 'https://pressbooks.com/feed/', - 'title' => 'Pressbooks News', - ] ) ); + $options = array_map( + 'stripslashes_deep', get_site_option( + 'pressbooks_dashboard_feed', [ + 'display_feed' => 1, + 'url' => 'https://pressbooks.com/feed/', + 'title' => 'Pressbooks News', + ] + ) + ); $html = ''; echo $html; } function url_callback( $args ) { - $options = get_site_option( 'pressbooks_dashboard_feed', [ + $options = get_site_option( + 'pressbooks_dashboard_feed', [ 'display_feed' => 1, 'url' => 'https://pressbooks.com/feed/', 'title' => 'Pressbooks News', - ] ); + ] + ); $html = ''; echo $html; } diff --git a/includes/admin/pb-diagnostics.php b/inc/admin/diagnostics/namespace.php similarity index 89% rename from includes/admin/pb-diagnostics.php rename to inc/admin/diagnostics/namespace.php index db1ea42f79..c8435d7a87 100644 --- a/includes/admin/pb-diagnostics.php +++ b/inc/admin/diagnostics/namespace.php @@ -3,16 +3,19 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Diagnostics; -require_once( PB_PLUGIN_DIR . 'symbionts/Browser.php' ); +use Sinergi\BrowserDetector\Browser; +use Sinergi\BrowserDetector\Os; +use Sinergi\BrowserDetector\UserAgent; /** * Add the diagnostics menu (with parent page set to null) */ function add_menu() { - $page = add_submenu_page( + add_submenu_page( 'options.php', __( 'Diagnostics', 'pressbooks' ), __( 'Diagnostics', 'pressbooks' ), @@ -27,11 +30,14 @@ function add_menu() { */ function render_page() { global $wpdb; - $browser = new \Browser; ?> + $browser = new Browser; + $os = new Os; + $user_agent = new UserAgent; ?>

- -
+
* @license GPLv2 (or any later version) */ -namespace Pressbooks\Admin\Fonts; +namespace Pressbooks\Admin\Fonts; use Pressbooks\Container; diff --git a/includes/admin/pb-laf.php b/inc/admin/laf/namespace.php similarity index 72% rename from includes/admin/pb-laf.php rename to inc/admin/laf/namespace.php index 6211b88b76..c40de615c0 100644 --- a/includes/admin/pb-laf.php +++ b/inc/admin/laf/namespace.php @@ -5,6 +5,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Laf; /** @@ -71,7 +72,12 @@ function replace_book_admin_menu() { remove_menu_page( 'edit.php?post_type=metadata' ); remove_menu_page( 'link-manager.php' ); remove_menu_page( 'edit.php?post_type=page' ); - add_theme_page( __( 'Theme Options', 'pressbooks' ), __( 'Theme Options', 'pressbooks' ), 'edit_theme_options', 'pressbooks_theme_options', array( '\Pressbooks\Modules\ThemeOptions\ThemeOptions', 'render' ) ); + add_theme_page( + __( 'Theme Options', 'pressbooks' ), __( 'Theme Options', 'pressbooks' ), 'edit_theme_options', 'pressbooks_theme_options', [ + '\Pressbooks\Modules\ThemeOptions\ThemeOptions', + 'render', + ] + ); remove_submenu_page( 'tools.php', 'tools.php' ); remove_submenu_page( 'tools.php', 'import.php' ); @@ -82,23 +88,27 @@ function replace_book_admin_menu() { // Organize $page = add_submenu_page( 'edit.php?post_type=chapter', __( 'Organize', 'pressbooks' ), __( 'Organize', 'pressbooks' ), 'edit_posts', 'pressbooks', __NAMESPACE__ . '\display_organize' ); - add_action( 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { - if ( $hook == $page ) { - wp_enqueue_style( 'pb-organize' ); - wp_enqueue_script( 'jquery-blockui' ); - wp_enqueue_script( 'pb-organize' ); - wp_localize_script( 'pb-organize', 'PB_OrganizeToken', array( - // Ajax nonces - 'orderNonce' => wp_create_nonce( 'pb-update-book-order' ), - 'exportNonce' => wp_create_nonce( 'pb-update-book-export' ), - 'showTitleNonce' => wp_create_nonce( 'pb-update-book-show-title' ), - 'privacyNonce' => wp_create_nonce( 'pb-update-book-privacy' ), - 'private' => __( 'Private', 'pressbooks' ), - 'published' => __( 'Published', 'pressbooks' ), - 'public' => __( 'Public', 'pressbooks' ), - ) ); + add_action( + 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { + if ( $hook === $page ) { + wp_enqueue_style( 'pb-organize' ); + wp_enqueue_script( 'jquery-blockui' ); + wp_enqueue_script( 'pb-organize' ); + wp_localize_script( + 'pb-organize', 'PB_OrganizeToken', [ + // Ajax nonces + 'orderNonce' => wp_create_nonce( 'pb-update-book-order' ), + 'exportNonce' => wp_create_nonce( 'pb-update-book-export' ), + 'showTitleNonce' => wp_create_nonce( 'pb-update-book-show-title' ), + 'privacyNonce' => wp_create_nonce( 'pb-update-book-privacy' ), + 'private' => __( 'Private', 'pressbooks' ), + 'published' => __( 'Published', 'pressbooks' ), + 'public' => __( 'Public', 'pressbooks' ), + ] + ); + } } - } ); + ); if ( current_user_can( 'publish_posts' ) ) { $add_chapter = $submenu['edit.php?post_type=chapter'][10]; unset( $submenu['edit.php?post_type=chapter'][10] ); @@ -139,31 +149,38 @@ function replace_book_admin_menu() { $book_info_url = 'post-new.php?post_type=metadata'; } $page = add_menu_page( __( 'Book Info', 'pressbooks' ), __( 'Book Info', 'pressbooks' ), 'edit_posts', $book_info_url, '', 'dashicons-info', 12 ); - add_action( 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { - if ( 'post-new.php' == $hook || 'post.php' == $hook ) { - if ( 'metadata' == get_post_type() ) { - wp_enqueue_script( 'pb-metadata' ); - wp_localize_script( 'pb-metadata', 'PB_BookInfoToken', array( - 'bookInfoMenuId' => preg_replace( '|[^a-zA-Z0-9_:.]|', '-', $page ), - ) ); + add_action( + 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { + if ( 'post-new.php' === $hook || 'post.php' === $hook ) { + if ( 'metadata' === get_post_type() ) { + wp_enqueue_script( 'pb-metadata' ); + wp_localize_script( + 'pb-metadata', 'PB_BookInfoToken', [ + 'bookInfoMenuId' => preg_replace( '|[^a-zA-Z0-9_:.]|', '-', $page ), + ] + ); + } } } - } ); + ); // Export $page = add_menu_page( __( 'Export', 'pressbooks' ), __( 'Export', 'pressbooks' ), 'edit_posts', 'pb_export', __NAMESPACE__ . '\display_export', 'dashicons-migrate', 14 ); - add_action( 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { - if ( $hook == $page ) { - wp_enqueue_style( 'pb-export' ); - wp_enqueue_script( 'pb-export' ); - wp_localize_script( 'pb-export', 'PB_ExportToken', array( - 'mobiConfirm' => __( 'EPUB is required for MOBI export. Would you like to reenable it?', 'pressbooks' ), - ) ); + add_action( + 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { + if ( $hook === $page ) { + wp_enqueue_style( 'pb-export' ); + wp_enqueue_script( 'pb-export' ); + wp_localize_script( + 'pb-export', 'PB_ExportToken', [ + 'mobiConfirm' => __( 'EPUB is required for MOBI export. Would you like to reenable it?', 'pressbooks' ), + ] + ); + } } - } ); + ); // Publish - require dirname( __FILE__ ) . '/class-pb-publishoptions.php'; $option = get_option( 'pressbooks_ecommerce_links', \Pressbooks\Admin\PublishOptions::getDefaults() ); $page = new \Pressbooks\Admin\PublishOptions( $option ); $page->init(); @@ -177,13 +194,12 @@ function replace_book_admin_menu() { } } - add_menu_page( __( 'Publish', 'pressbooks' ), __( 'Publish', 'pressbooks' ), 'edit_posts', 'pb_publish', array( $page, 'render' ), 'dashicons-products', 16 ); + add_menu_page( __( 'Publish', 'pressbooks' ), __( 'Publish', 'pressbooks' ), 'edit_posts', 'pb_publish', [ $page, 'render' ], 'dashicons-products', 16 ); // Privacy add_options_page( __( 'Sharing and Privacy Settings', 'pressbooks' ), __( 'Sharing & Privacy', 'pressbooks' ), 'manage_options', 'pressbooks_sharingandprivacy_options', __NAMESPACE__ . '\display_privacy_settings' ); // Export - require dirname( __FILE__ ) . '/class-pb-exportoptions.php'; $option = get_option( 'pressbooks_export_options', \Pressbooks\Admin\ExportOptions::getDefaults() ); $page = new \Pressbooks\Admin\ExportOptions( $option ); $page->init(); @@ -197,22 +213,23 @@ function replace_book_admin_menu() { } } - add_options_page( __( 'Export Settings', 'pressbooks' ), __( 'Export', 'pressbooks' ), 'manage_options', 'pressbooks_export_options', array( $page, 'render' ) ); + add_options_page( __( 'Export Settings', 'pressbooks' ), __( 'Export', 'pressbooks' ), 'manage_options', 'pressbooks_export_options', [ $page, 'render' ] ); // Import $page = add_management_page( __( 'Import', 'pressbooks' ), __( 'Import', 'pressbooks' ), 'edit_posts', 'pb_import', __NAMESPACE__ . '\display_import' ); - add_action( 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { - if ( $hook == $page ) { - wp_enqueue_script( 'pb-import' ); + add_action( + 'admin_enqueue_scripts', function ( $hook ) use ( $page ) { + if ( $hook === $page ) { + wp_enqueue_script( 'pb-import' ); + } } - } ); + ); // Catalog add_submenu_page( 'index.php', __( 'My Catalog', 'pressbooks' ), __( 'My Catalog', 'pressbooks' ), 'read', 'pb_catalog', '\Pressbooks\Catalog::addMenu' ); } function network_admin_menu() { - require dirname( __FILE__ ) . '/class-pb-network-sharingandprivacyoptions.php'; $option = get_site_option( 'pressbooks_sharingandprivacy_options', \Pressbooks\Admin\Network\SharingAndPrivacyOptions::getDefaults(), false ); $page = new \Pressbooks\Admin\Network\SharingAndPrivacyOptions( $option ); $page->init(); @@ -225,7 +242,12 @@ function network_admin_menu() { } } - add_submenu_page( 'settings.php', __( 'Sharing and Privacy Settings', 'pressbooks' ), __( 'Sharing & Privacy', 'pressbooks' ), 'manage_network', 'pressbooks_sharingandprivacy_options', array( $page, 'render' ) ); + add_submenu_page( + 'settings.php', __( 'Sharing and Privacy Settings', 'pressbooks' ), __( 'Sharing & Privacy', 'pressbooks' ), 'manage_network', 'pressbooks_sharingandprivacy_options', [ + $page, + 'render', + ] + ); } /** @@ -283,48 +305,58 @@ function replace_menu_bar_branding( $wp_admin_bar ) { $wp_admin_bar->remove_menu( 'wp-logo' ); $wp_admin_bar->remove_menu( 'documentation' ); $wp_admin_bar->remove_menu( 'feedback' ); - $wp_admin_bar->add_menu( array( - 'id' => 'wp-logo', - 'title' => '', - 'href' => ( 'https://pressbooks.com/about' ), - 'meta' => array( - 'title' => __( 'About Pressbooks', 'pressbooks' ), - ), - ) ); + $wp_admin_bar->add_menu( + [ + 'id' => 'wp-logo', + 'title' => '', + 'href' => ( 'https://pressbooks.com/about' ), + 'meta' => [ + 'title' => __( 'About Pressbooks', 'pressbooks' ), + ], + ] + ); if ( is_user_logged_in() ) { // Add "About WordPress" link - $wp_admin_bar->add_menu( array( - 'parent' => 'wp-logo', - 'id' => 'about', - 'title' => __( 'About Pressbooks', 'pressbooks' ), - 'href' => 'https://pressbooks.com/about', - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => 'wp-logo', + 'id' => 'about', + 'title' => __( 'About Pressbooks', 'pressbooks' ), + 'href' => 'https://pressbooks.com/about', + ] + ); } // Add WordPress.org link - $wp_admin_bar->add_menu( array( - 'parent' => 'wp-logo-external', - 'id' => 'wporg', - 'title' => __( 'Pressbooks.com', 'pressbooks' ), - 'href' => 'https://pressbooks.com', - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => 'wp-logo-external', + 'id' => 'wporg', + 'title' => __( 'Pressbooks.com', 'pressbooks' ), + 'href' => 'https://pressbooks.com', + ] + ); // Add forums link - $wp_admin_bar->add_menu( array( - 'parent' => 'wp-logo-external', - 'id' => 'support-forums', - 'title' => __( 'Help', 'pressbooks' ), - 'href' => 'https://pressbooks.com/help', - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => 'wp-logo-external', + 'id' => 'support-forums', + 'title' => __( 'Help', 'pressbooks' ), + 'href' => 'https://pressbooks.com/help', + ] + ); // Add feedback link - $wp_admin_bar->add_menu( array( - 'parent' => 'wp-logo-external', - 'id' => 'contact', - 'title' => __( 'Contact', 'pressbooks' ), - 'href' => 'https://pressbooks.com/contact', - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => 'wp-logo-external', + 'id' => 'contact', + 'title' => __( 'Contact', 'pressbooks' ), + 'href' => 'https://pressbooks.com/contact', + ] + ); } @@ -347,67 +379,88 @@ function replace_menu_bar_my_sites( $wp_admin_bar ) { return; } - $wp_admin_bar->add_menu( array( - 'id' => 'my-books', - 'title' => __( 'My Catalog', 'pressbooks' ), - 'href' => admin_url( 'index.php?page=pb_catalog' ), - ) ); + $wp_admin_bar->add_menu( + [ + 'id' => 'my-books', + 'title' => __( 'My Catalog', 'pressbooks' ), + 'href' => admin_url( 'index.php?page=pb_catalog' ), + ] + ); - $wp_admin_bar->add_node( array( - 'parent' => 'my-books', - 'id' => 'add-new-book', - 'title' => __( 'Add A New Book', 'pressbooks' ), - 'href' => network_home_url( 'wp-signup.php' ), - ) ); + $wp_admin_bar->add_node( + [ + 'parent' => 'my-books', + 'id' => 'add-new-book', + 'title' => __( 'Add A New Book', 'pressbooks' ), + 'href' => network_home_url( 'wp-signup.php' ), + ] + ); if ( is_super_admin() ) { - $wp_admin_bar->add_group( array( - 'parent' => 'my-books', - 'id' => 'my-books-super-admin', - ) ); - - $wp_admin_bar->add_menu( array( - 'parent' => 'my-books-super-admin', - 'id' => 'pb-network-admin', - 'title' => __( 'Network Admin', 'pressbooks' ), - 'href' => network_admin_url(), - ) ); - - $wp_admin_bar->add_menu( array( - 'parent' => 'pb-network-admin', - 'id' => 'pb-network-admin-d', - 'title' => __( 'Dashboard', 'pressbooks' ), - 'href' => network_admin_url(), - ) ); - $wp_admin_bar->add_menu( array( - 'parent' => 'pb-network-admin', - 'id' => 'pb-network-admin-s', - 'title' => __( 'Sites', 'pressbooks' ), - 'href' => network_admin_url( 'sites.php' ), - ) ); - $wp_admin_bar->add_menu( array( - 'parent' => 'pb-network-admin', - 'id' => 'pb-network-admin-u', - 'title' => __( 'Users', 'pressbooks' ), - 'href' => network_admin_url( 'users.php' ), - ) ); - $wp_admin_bar->add_menu( array( - 'parent' => 'pb-network-admin', - 'id' => 'pb-network-admin-v', - 'title' => __( 'Visit Network', 'pressbooks' ), - 'href' => network_home_url(), - ) ); + $wp_admin_bar->add_group( + [ + 'parent' => 'my-books', + 'id' => 'my-books-super-admin', + ] + ); + + $wp_admin_bar->add_menu( + [ + 'parent' => 'my-books-super-admin', + 'id' => 'pb-network-admin', + 'title' => __( 'Network Admin', 'pressbooks' ), + 'href' => network_admin_url(), + ] + ); + + $wp_admin_bar->add_menu( + [ + 'parent' => 'pb-network-admin', + 'id' => 'pb-network-admin-d', + 'title' => __( 'Dashboard', 'pressbooks' ), + 'href' => network_admin_url(), + ] + ); + + $wp_admin_bar->add_menu( + [ + 'parent' => 'pb-network-admin', + 'id' => 'pb-network-admin-s', + 'title' => __( 'Sites', 'pressbooks' ), + 'href' => network_admin_url( 'sites.php' ), + ] + ); + + $wp_admin_bar->add_menu( + [ + 'parent' => 'pb-network-admin', + 'id' => 'pb-network-admin-u', + 'title' => __( 'Users', 'pressbooks' ), + 'href' => network_admin_url( 'users.php' ), + ] + ); + + $wp_admin_bar->add_menu( + [ + 'parent' => 'pb-network-admin', + 'id' => 'pb-network-admin-v', + 'title' => __( 'Visit Network', 'pressbooks' ), + 'href' => network_home_url(), + ] + ); } // Add site links - $wp_admin_bar->add_group( array( - 'parent' => 'my-books', - 'id' => 'my-books-list', - 'meta' => array( - 'class' => is_super_admin() ? 'ab-sub-secondary' : '', - ), - ) ); + $wp_admin_bar->add_group( + [ + 'parent' => 'my-books', + 'id' => 'my-books-list', + 'meta' => [ + 'class' => is_super_admin() ? 'ab-sub-secondary' : '', + ], + ] + ); foreach ( (array) $wp_admin_bar->user->blogs as $blog ) { @@ -418,31 +471,37 @@ function replace_menu_bar_my_sites( $wp_admin_bar ) { $admin_url = get_admin_url( $blog->userblog_id ); - $wp_admin_bar->add_menu( array( - 'parent' => 'my-books-list', - 'id' => $menu_id, - 'title' => $blavatar . $blogname, - 'href' => $admin_url, - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => 'my-books-list', + 'id' => $menu_id, + 'title' => $blavatar . $blogname, + 'href' => $admin_url, + ] + ); - $wp_admin_bar->add_menu( array( - 'parent' => $menu_id, - 'id' => $menu_id . '-d', - 'title' => __( 'Dashboard', 'pressbooks' ), - 'href' => $admin_url, - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => $menu_id, + 'id' => $menu_id . '-d', + 'title' => __( 'Dashboard', 'pressbooks' ), + 'href' => $admin_url, + ] + ); if ( current_user_can_for_blog( $blog->userblog_id, 'edit_posts' ) ) { $wp_admin_bar->remove_menu( $menu_id . '-n' ); $wp_admin_bar->remove_menu( $menu_id . '-c' ); } - $wp_admin_bar->add_menu( array( - 'parent' => $menu_id, - 'id' => $menu_id . '-v', - 'title' => __( 'Visit Site', 'pressbooks' ), - 'href' => get_home_url( $blog->userblog_id, '/' ), - ) ); + $wp_admin_bar->add_menu( + [ + 'parent' => $menu_id, + 'id' => $menu_id . '-v', + 'title' => __( 'Visit Site', 'pressbooks' ), + 'href' => get_home_url( $blog->userblog_id, '/' ), + ] + ); } } @@ -493,13 +552,13 @@ function customize_register( $wp_customize ) { function default_meta_checkboxes() { global $pagenow; - if ( 'post-new.php' == $pagenow ) { + if ( 'post-new.php' === $pagenow ) { ?> - - + jQuery('#pb_export').attr('checked', 'checked'); + jQuery('#pb_show_title').attr('checked', 'checked'); + + - - + __( 'Are you sure you want to unlock your theme? This will update your book to the most recent version of your selected theme, which may change your book’s appearance and page count. Once you save your settings on this page, this action will NOT be reversable!', 'pressbooks' ), - ) ); + ] + ); } - if ( 'pb_custom_css' == esc_attr( @$_REQUEST['page'] ) ) { + if ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === 'pb_custom_css' ) { wp_enqueue_style( 'pb-custom-css', \Pressbooks\Utility\asset_path( 'styles/custom-css.css' ) ); } // Don't let other plugins override our scripts - $badScripts = array( 'jquery-blockui', 'jquery-bootstrap', 'pb-organize', 'pb-feedback', 'pb-export', 'pb-metadata', 'pb-import' ); - array_walk( $badScripts, function ( $value, $key ) { - wp_deregister_script( $value ); - } ); + $bad_scripts = [ 'jquery-blockui', 'jquery-bootstrap', 'pb-organize', 'pb-feedback', 'pb-export', 'pb-metadata', 'pb-import' ]; + array_walk( + $bad_scripts, function ( $value, $key ) { + wp_deregister_script( $value ); + } + ); // Enqueue later, on-the-fly, using action: admin_print_scripts- wp_register_script( 'jquery-blockui', \Pressbooks\Utility\asset_path( 'scripts/blockui.js' ), [ 'jquery', 'jquery-ui-core' ] ); @@ -627,7 +698,7 @@ function redirect_away_from_bad_urls() { // If user is on post-new.php, check for valid post_type if ( preg_match( '~/wp-admin/post-new\.php$~', $check_against_url ) ) { - if ( ! in_array( @$_REQUEST['post_type'], \Pressbooks\PostType\list_post_types() ) ) { + if ( isset( $_REQUEST['post_type'] ) && ! in_array( $_REQUEST['post_type'], \Pressbooks\PostType\list_post_types(), true ) ) { $_SESSION['pb_notices'][] = __( 'Unsupported post type.', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } @@ -636,7 +707,7 @@ function redirect_away_from_bad_urls() { // --------------------------------------------------------------------------------------------------------------- // Don't let user go to any of these pages, under any circumstance - $restricted = array( + $restricted = [ 'edit-tags', 'export', 'import', @@ -647,7 +718,7 @@ function redirect_away_from_bad_urls() { 'theme-editor', 'update-core', 'widgets', - ); + ]; // Todo: Fine grained control over: options-general.php @@ -695,7 +766,7 @@ function privacy_settings_init() { 'privacy_settings_section' ); $sharingandprivacy = get_site_option( 'pressbooks_sharingandprivacy_options' ); - if ( isset( $sharingandprivacy['allow_redistribution'] ) && 1 == $sharingandprivacy['allow_redistribution'] ) { + if ( isset( $sharingandprivacy['allow_redistribution'] ) && ! empty( $sharingandprivacy['allow_redistribution'] ) ) { add_settings_field( 'latest_files_public', __( 'Share Latest Export Files', 'pressbooks' ), @@ -744,12 +815,14 @@ function privacy_settings_section_callback() { function privacy_blog_public_callback( $args ) { $blog_public = get_option( 'blog_public' ); $html = '
'; $html .= ''; @@ -766,7 +839,7 @@ function privacy_permissive_private_content_callback( $args ) { $subscriber = get_role( 'subscriber' ); $contributor = get_role( 'contributor' ); $author = get_role( 'author' ); - if ( 1 == $permissive_private_content ) { // If permissive private content is set to true, adjust capabilities + if ( ! empty( $permissive_private_content ) ) { // If permissive private content is set to true, adjust capabilities $subscriber->add_cap( 'read_private_posts' ); $contributor->add_cap( 'read_private_posts' ); $author->add_cap( 'read_private_posts' ); @@ -778,8 +851,8 @@ function privacy_permissive_private_content_callback( $args ) {

/> -
- /> +
+ />
1 ) ); + $options = get_option( 'pressbooks_sharingandprivacy_options', [ 'disable_comments' => 1 ] ); $html = '
'; $html .= ''; @@ -830,6 +905,7 @@ function privacy_latest_files_public_callback( $args ) { * Privacy settings, blog_public field sanitization * * @param $input + * * @return string */ function privacy_blog_public_sanitize( $input ) { @@ -840,6 +916,7 @@ function privacy_blog_public_sanitize( $input ) { * Privacy settings, permissive_private_content field sanitization * * @param $input + * * @return string */ function privacy_permissive_private_content_sanitize( $input ) { @@ -850,6 +927,7 @@ function privacy_permissive_private_content_sanitize( $input ) { * Privacy settings, disable_comments field sanitization * * @param $input + * * @return string */ function privacy_disable_comments_sanitize( $input ) { @@ -861,6 +939,7 @@ function privacy_disable_comments_sanitize( $input ) { * Privacy settings, pbt_redistribute_settings field sanitization * * @param $input + * * @return string */ function privacy_pbt_redistribute_settings_sanitize( $input ) { @@ -873,16 +952,16 @@ function privacy_pbt_redistribute_settings_sanitize( $input ) { */ function display_privacy_settings() { ?> -
-

- - - - -
+
+

+
+ + +
+
-

' . $msg . '

'; } - // Destroy + // Destroy the session. unset( $_SESSION['pb_errors'] ); } if ( ! empty( $_SESSION['pb_notices'] ) ) { - // Array-ify + // Array-ify the notice(s). if ( ! is_array( $_SESSION['pb_notices'] ) ) { - $_SESSION['pb_notices'] = array( $_SESSION['pb_notices'] ); + $_SESSION['pb_notices'] = [ $_SESSION['pb_notices'] ]; } - // Print + // Print the notice(s). foreach ( $_SESSION['pb_notices'] as $msg ) { echo '

' . $msg . '

'; } - // Destroy + // Destroy the session. unset( $_SESSION['pb_notices'] ); } } diff --git a/includes/admin/pb-metaboxes.php b/inc/admin/metaboxes/namespace.php similarity index 67% rename from includes/admin/pb-metaboxes.php rename to inc/admin/metaboxes/namespace.php index 964f9c6ae1..9528c10d52 100644 --- a/includes/admin/pb-metaboxes.php +++ b/inc/admin/metaboxes/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Admin\Metaboxes; +namespace Pressbooks\Admin\Metaboxes; /** * If the user updates the book's title, then also update the blog name @@ -15,7 +15,7 @@ * @param string $meta_value */ function title_update( $meta_id, $post_id, $meta_key, $meta_value ) { - if ( 'pb_title' != $meta_key ) { + if ( 'pb_title' !== $meta_key ) { return; } else { update_option( 'blogname', $meta_value ); @@ -51,7 +51,7 @@ function add_required_data( $pid, $post ) { */ function upload_cover_image( $pid, $post ) { - if ( @empty( $_FILES['pb_cover_image']['name'] ) ) { + if ( ! isset( $_FILES['pb_cover_image']['name'] ) || empty( $_FILES['pb_cover_image']['name'] ) ) { return; // Bail } @@ -59,8 +59,8 @@ function upload_cover_image( $pid, $post ) { return; // Bail } - $allowed_file_types = array( 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png' ); - $overrides = array( 'test_form' => false, 'mimes' => $allowed_file_types ); + $allowed_file_types = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png' ]; + $overrides = [ 'test_form' => false, 'mimes' => $allowed_file_types ]; $image = wp_handle_upload( $_FILES['pb_cover_image'], $overrides ); if ( ! empty( $image['error'] ) ) { @@ -84,18 +84,19 @@ function upload_cover_image( $pid, $post ) { // Delete old images foreach ( $old as $old_url ) { $old_id = \Pressbooks\Image\attachment_id_from_url( $old_url ); - if ( $old_id ) { wp_delete_attachment( $old_id, true ); + if ( $old_id ) { + wp_delete_attachment( $old_id, true ); } } // Insert new image, create thumbnails - $args = array( + $args = [ 'post_mime_type' => $image['type'], 'post_title' => __( 'Cover Image', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', 'post_name' => 'pb-cover-image', - ); + ]; $id = wp_insert_attachment( $args, $image['file'], $pid ); wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $image['file'] ) ); } @@ -108,14 +109,17 @@ function upload_cover_image( $pid, $post ) { */ function add_metadata_styles( $hook ) { - if ( 'post-new.php' == $hook || 'post.php' == $hook ) { + if ( 'post-new.php' === $hook || 'post.php' === $hook ) { $post_type = get_post_type(); - if ( 'metadata' == $post_type ) { + if ( 'metadata' === $post_type ) { wp_enqueue_style( 'metadata', \Pressbooks\Utility\asset_path( 'styles/metadata.css' ) ); - } elseif ( 'part' == $post_type ) { + } elseif ( 'part' === $post_type ) { wp_enqueue_style( 'part', \Pressbooks\Utility\asset_path( 'styles/part.css' ) ); - add_filter( 'page_attributes_dropdown_pages_args', function () { return array( 'post_type' => '__GARBAGE__' ); - } ); // Hide this dropdown by querying for garbage + add_filter( + 'page_attributes_dropdown_pages_args', function () { + return [ 'post_type' => '__GARBAGE__' ]; + } + ); // Hide this dropdown by querying for garbage } } } @@ -141,237 +145,307 @@ function add_meta_boxes() { // Book Metadata - x_add_metadata_group( 'general-book-information', 'metadata', array( + x_add_metadata_group( + 'general-book-information', 'metadata', [ 'label' => __( 'General Book Information', 'pressbooks' ), 'priority' => 'high', - ) ); + ] + ); - x_add_metadata_field( 'pb_title', 'metadata', array( + x_add_metadata_field( + 'pb_title', 'metadata', [ 'group' => 'general-book-information', 'label' => 'Title', - ) ); + ] + ); - x_add_metadata_field( 'pb_short_title', 'metadata', array( + x_add_metadata_field( + 'pb_short_title', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Short Title', 'pressbooks' ), 'description' => __( 'In case of long titles that might be truncated in running heads in the PDF export.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_subtitle', 'metadata', array( + x_add_metadata_field( + 'pb_subtitle', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Subtitle', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_author', 'metadata', array( + x_add_metadata_field( + 'pb_author', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Author', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_author_file_as', 'metadata', array( + x_add_metadata_field( + 'pb_author_file_as', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Author, file as', 'pressbooks' ), 'description' => __( 'This ensures that your ebook will sort properly in ebook stores, by the author\'s last name.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_contributing_authors', 'metadata', array( + x_add_metadata_field( + 'pb_contributing_authors', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Contributing Authors', 'pressbooks' ), 'multiple' => true, 'description' => __( 'This may be used when more than one person shares the responsibility for the intellectual content of a book.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_publisher', 'metadata', array( + x_add_metadata_field( + 'pb_publisher', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Publisher', 'pressbooks' ), 'description' => __( 'This text appears on the title page of your book.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_publisher_city', 'metadata', array( + x_add_metadata_field( + 'pb_publisher_city', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Publisher City', 'pressbooks' ), 'description' => __( 'This text appears on the title page of your book.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_publication_date', 'metadata', array( + x_add_metadata_field( + 'pb_publication_date', 'metadata', [ 'field_type' => 'datepicker', 'group' => 'general-book-information', 'label' => __( 'Publication Date', 'pressbooks' ), 'description' => __( 'This is added to the metadata in your ebook.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_onsale_date', 'metadata', array( + x_add_metadata_field( + 'pb_onsale_date', 'metadata', [ 'field_type' => 'datepicker', 'group' => 'general-book-information', 'label' => __( 'On-Sale Date', 'pressbooks' ), 'description' => __( 'This is added to the metadata in your ebook.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_ebook_isbn', 'metadata', array( + x_add_metadata_field( + 'pb_ebook_isbn', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Ebook ISBN', 'pressbooks' ), 'description' => __( 'ISBN is the International Standard Book Number, and you\'ll need one if you want to sell your book in some online ebook stores. This is added to the metadata in your ebook.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_print_isbn', 'metadata', array( + x_add_metadata_field( + 'pb_print_isbn', 'metadata', [ 'group' => 'general-book-information', 'label' => __( 'Print ISBN', 'pressbooks' ), 'description' => __( 'ISBN is the International Standard Book Number, and you\'ll need one if you want to sell your book in online and physical book stores.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_language', 'metadata', array( + x_add_metadata_field( + 'pb_language', 'metadata', [ 'group' => 'general-book-information', 'field_type' => 'select', 'values' => \Pressbooks\L10n\supported_languages(), 'select2' => true, 'label' => __( 'Language', 'pressbooks' ), 'description' => __( 'This sets metadata in your ebook, making it easier to find in some stores. It also changes some system generated content for supported languages, such as the "Contents" header.', 'pressbooks' ) . '
' . sprintf( '%s', __( 'Help translate Pressbooks into your language!', 'pressbooks' ) ), - ) ); + ] + ); - x_add_metadata_group( 'copyright', 'metadata', array( + x_add_metadata_group( + 'copyright', 'metadata', [ 'label' => __( 'Copyright', 'pressbooks' ), 'priority' => 'low', - ) ); + ] + ); - x_add_metadata_field( 'pb_copyright_year', 'metadata', array( + x_add_metadata_field( + 'pb_copyright_year', 'metadata', [ 'group' => 'copyright', 'label' => __( 'Copyright Year', 'pressbooks' ), 'description' => __( 'Year that the book is/was published.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_copyright_holder', 'metadata', array( + x_add_metadata_field( + 'pb_copyright_holder', 'metadata', [ 'group' => 'copyright', 'label' => __( 'Copyright Holder', 'pressbooks' ), 'description' => __( 'Name of the copyright holder.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_book_license', 'metadata', array( + x_add_metadata_field( + 'pb_book_license', 'metadata', [ 'group' => 'copyright', 'field_type' => 'select', - 'values' => array( - '' => '--Select--', - 'public-domain' => 'No Rights Reserved (Public Domain)', - 'cc-by' => 'CC BY (Attribution)', - 'cc-by-sa' => 'CC BY-SA (Attribution ShareAlike)', - 'cc-by-nd' => 'CC BY-ND (Attribution NoDerivatives)', - 'cc-by-nc' => 'CC BY-NC (Attribution NonCommercial)', - 'cc-by-nc-sa' => 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', - 'cc-by-nc-nd' => 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', - 'all-rights-reserved' => 'All Rights Reserved', - ), + 'values' => [ + '' => '--Select--', + 'public-domain' => __( 'No Rights Reserved (Public Domain)', 'pressbooks' ), + 'cc-by' => __( 'CC BY (Attribution)', 'pressbooks' ), + 'cc-by-sa' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), + 'cc-by-nd' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), + 'cc-by-nc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), + 'cc-by-nc-sa' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), + 'cc-by-nc-nd' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), + 'all-rights-reserved' => __( 'All Rights Reserved', 'pressbooks' ), + ], 'label' => __( 'Copyright License', 'pressbooks' ), 'description' => __( 'You can select various licenses including Creative Commons.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_custom_copyright', 'metadata', array( + x_add_metadata_field( + 'pb_custom_copyright', 'metadata', [ 'field_type' => 'wysiwyg', 'group' => 'copyright', 'label' => __( 'Copyright Notice', 'pressbooks' ), 'description' => __( 'Enter a custom copyright notice, with whatever infomation you like. This will override the auto-generated copyright notice, and be inserted after the title page.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_group( 'about-the-book', 'metadata', array( + x_add_metadata_group( + 'about-the-book', 'metadata', [ 'label' => 'About the Book', 'priority' => 'low', - ) ); + ] + ); - x_add_metadata_field( 'pb_about_140', 'metadata', array( + x_add_metadata_field( + 'pb_about_140', 'metadata', [ 'group' => 'about-the-book', 'label' => __( 'Book Tagline', 'pressbooks' ), 'description' => __( 'A very short description of your book. It should fit in a Twitter post, and encapsulate your book in the briefest sentence.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_about_50', 'metadata', array( + x_add_metadata_field( + 'pb_about_50', 'metadata', [ 'field_type' => 'textarea', 'group' => 'about-the-book', 'label' => __( 'Short Description', 'pressbooks' ), 'description' => __( 'A short paragraph about your book, for catalogs, reviewers etc. to quote.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_about_unlimited', 'metadata', array( + x_add_metadata_field( + 'pb_about_unlimited', 'metadata', [ 'field_type' => 'wysiwyg', 'group' => 'about-the-book', 'label' => __( 'Long Description', 'pressbooks' ), 'description' => __( 'The full description of your book.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_group( 'additional-catalogue-information', 'metadata', array( + x_add_metadata_group( + 'additional-catalogue-information', 'metadata', [ 'label' => __( 'Additional Catalog Information', 'pressbooks' ), 'priority' => 'low', - ) ); + ] + ); - x_add_metadata_field( 'pb_series_title', 'metadata', array( + x_add_metadata_field( + 'pb_series_title', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Series Title', 'pressbooks' ), 'description' => __( 'Add if your book is part of a series. This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_series_number', 'metadata', array( + x_add_metadata_field( + 'pb_series_number', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Series Number', 'pressbooks' ), 'description' => __( 'Add if your book is part of a series. This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_editor', 'metadata', array( + x_add_metadata_field( + 'pb_editor', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Editor', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_translator', 'metadata', array( + x_add_metadata_field( + 'pb_translator', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Translator', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_keywords_tags', 'metadata', array( + x_add_metadata_field( + 'pb_keywords_tags', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Keywords', 'pressbooks' ), 'multiple' => true, 'description' => __( 'These are added to your webbook cover page, and in your ebook metadata. Keywords are used by online book stores and search engines.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_hashtag', 'metadata', array( + x_add_metadata_field( + 'pb_hashtag', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Hashtag', 'pressbooks' ), 'description' => __( 'These are added to your webbook cover page. For those of you who like Twitter.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_list_price_print', 'metadata', array( + x_add_metadata_field( + 'pb_list_price_print', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'List Price (Print)', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_list_price_pdf', 'metadata', array( + x_add_metadata_field( + 'pb_list_price_pdf', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'List Price (PDF)', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_list_price_epub', 'metadata', array( + x_add_metadata_field( + 'pb_list_price_epub', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'List Price (ebook)', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_list_price_web', 'metadata', array( + x_add_metadata_field( + 'pb_list_price_web', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'List Price (Web)', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_audience', 'metadata', array( + x_add_metadata_field( + 'pb_audience', 'metadata', [ 'group' => 'additional-catalogue-information', 'field_type' => 'select', - 'values' => array( + 'values' => [ '' => __( 'Choose an audience…', 'pressbooks' ), 'juvenile' => __( 'Juvenile', 'pressbooks' ), 'young-adult' => __( 'Young Adult', 'pressbooks' ), 'adult' => __( 'Adult', 'pressbooks' ), - ), + ], 'label' => __( 'Audience', 'pressbooks' ), 'description' => __( 'The target audience for your book.', 'pressbooks' ), - ) ); + ] + ); /** * Add metadata field for BISAC Subject(s). @@ -380,196 +454,248 @@ function add_meta_boxes() { */ do_action( 'pb_add_bisac_subjects_field' ); - x_add_metadata_field( 'pb_bisac_regional_theme', 'metadata', array( + x_add_metadata_field( + 'pb_bisac_regional_theme', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'BISAC Regional Theme', 'pressbooks' ), 'description' => __( 'This is not used by Pressbooks.', 'pressbooks' ), - ) ); + ] + ); // Only display Catalog Order metadata field if site is running a root theme other than Pressbooks Root. switch_to_blog( 1 ); $root_theme = wp_get_theme(); if ( 'pressbooks-root' !== $root_theme->Template ) { - x_add_metadata_field( 'pb_catalogue_order', 'metadata', array( + x_add_metadata_field( + 'pb_catalogue_order', 'metadata', [ 'group' => 'additional-catalogue-information', 'label' => __( 'Catalog Order', 'pressbooks' ), - ) ); + ] + ); } restore_current_blog(); // Chapter Metadata - x_add_metadata_group( 'chapter-metadata', 'chapter', array( + x_add_metadata_group( + 'chapter-metadata', 'chapter', [ 'label' => __( 'Chapter Metadata', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_short_title', 'chapter', array( + x_add_metadata_field( + 'pb_short_title', 'chapter', [ 'group' => 'chapter-metadata', 'label' => __( 'Chapter Short Title (appears in the PDF running header)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_subtitle', 'chapter', array( + x_add_metadata_field( + 'pb_subtitle', 'chapter', [ 'group' => 'chapter-metadata', 'label' => __( 'Chapter Subtitle (appears in the Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_author', 'chapter', array( + x_add_metadata_field( + 'pb_section_author', 'chapter', [ 'group' => 'chapter-metadata', 'label' => __( 'Chapter Author (appears in Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_license', 'chapter', array( + x_add_metadata_field( + 'pb_section_license', 'chapter', [ 'group' => 'chapter-metadata', 'field_type' => 'select', - 'values' => array( - '' => '--Select--', - 'public-domain' => 'No Rights Reserved (Public Domain)', - 'cc-by' => 'CC BY (Attribution)', - 'cc-by-sa' => 'CC BY-SA (Attribution ShareAlike)', - 'cc-by-nd' => 'CC BY-ND (Attribution NoDerivatives)', - 'cc-by-nc' => 'CC BY-NC (Attribution NonCommercial)', - 'cc-by-nc-sa' => 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', - 'cc-by-nc-nd' => 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', - 'all-rights-reserved' => 'All Rights Reserved', - ), + 'values' => [ + '' => '--Select--', + 'public-domain' => __( 'No Rights Reserved (Public Domain)', 'pressbooks' ), + 'cc-by' => __( 'CC BY (Attribution)', 'pressbooks' ), + 'cc-by-sa' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), + 'cc-by-nd' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), + 'cc-by-nc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), + 'cc-by-nc-sa' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), + 'cc-by-nc-nd' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), + 'all-rights-reserved' => __( 'All Rights Reserved', 'pressbooks' ), + ], 'label' => __( 'Chapter Copyright License (overrides book license on this page)', 'pressbooks' ), - ) ); + ] + ); // Chapter Parent - x_add_metadata_group( 'chapter-parent', 'chapter', array( + x_add_metadata_group( + 'chapter-parent', 'chapter', [ 'label' => __( 'Part', 'pressbooks' ), 'context' => 'side', 'priority' => 'high', - ) ); + ] + ); // Export - x_add_metadata_group( 'export', array( 'chapter', 'front-matter', 'back-matter' ), array( + x_add_metadata_group( + 'export', [ 'chapter', 'front-matter', 'back-matter' ], [ 'label' => __( 'Export Settings', 'pressbooks' ), 'context' => 'side', 'priority' => 'high', - ) ); + ] + ); - x_add_metadata_field( 'pb_export', array( 'chapter', 'front-matter', 'back-matter' ), array( + x_add_metadata_field( + 'pb_export', [ 'chapter', 'front-matter', 'back-matter' ], [ 'group' => 'export', 'field_type' => 'checkbox', 'label' => __( 'Include in exports', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_show_title', array( 'chapter', 'front-matter', 'back-matter' ), array( + x_add_metadata_field( + 'pb_show_title', [ 'chapter', 'front-matter', 'back-matter' ], [ 'group' => 'export', 'field_type' => 'checkbox', 'label' => __( 'Show title in exports', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_ebook_start', array( 'chapter', 'front-matter', 'back-matter' ), array( + x_add_metadata_field( + 'pb_ebook_start', [ 'chapter', 'front-matter', 'back-matter' ], [ 'group' => 'export', 'field_type' => 'checkbox', 'label' => __( 'Set as ebook start-point', 'pressbooks' ), - ) ); + ] + ); // Front Matter Metadata - x_add_metadata_group( 'front-matter-metadata', 'front-matter', array( + x_add_metadata_group( + 'front-matter-metadata', 'front-matter', [ 'label' => __( 'Front Matter Metadata', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_short_title', 'front-matter', array( + x_add_metadata_field( + 'pb_short_title', 'front-matter', [ 'group' => 'front-matter-metadata', 'label' => __( 'Front Matter Short Title (appears in the PDF running header)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_subtitle', 'front-matter', array( + x_add_metadata_field( + 'pb_subtitle', 'front-matter', [ 'group' => 'front-matter-metadata', 'label' => __( 'Front Matter Subtitle (appears in the Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_author', 'front-matter', array( + x_add_metadata_field( + 'pb_section_author', 'front-matter', [ 'group' => 'front-matter-metadata', 'label' => __( 'Front Matter Author (appears in Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_license', 'front-matter', array( + x_add_metadata_field( + 'pb_section_license', 'front-matter', [ 'group' => 'front-matter-metadata', 'field_type' => 'select', - 'values' => array( - '' => '--Select--', - 'public-domain' => 'No Rights Reserved (Public Domain)', - 'cc-by' => 'CC BY (Attribution)', - 'cc-by-sa' => 'CC BY-SA (Attribution ShareAlike)', - 'cc-by-nd' => 'CC BY-ND (Attribution NoDerivatives)', - 'cc-by-nc' => 'CC BY-NC (Attribution NonCommercial)', - 'cc-by-nc-sa' => 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', - 'cc-by-nc-nd' => 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', - 'all-rights-reserved' => 'All Rights Reserved', - ), + 'values' => [ + '' => '--Select--', + 'public-domain' => __( 'No Rights Reserved (Public Domain)', 'pressbooks' ), + 'cc-by' => __( 'CC BY (Attribution)', 'pressbooks' ), + 'cc-by-sa' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), + 'cc-by-nd' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), + 'cc-by-nc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), + 'cc-by-nc-sa' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), + 'cc-by-nc-nd' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), + 'all-rights-reserved' => __( 'All Rights Reserved', 'pressbooks' ), + ], 'label' => __( 'Front Matter Copyright License (overrides book license on this page)', 'pressbooks' ), - ) ); + ] + ); // Back Matter Metadata - x_add_metadata_group( 'back-matter-metadata', 'back-matter', array( + x_add_metadata_group( + 'back-matter-metadata', 'back-matter', [ 'label' => __( 'Back Matter Metadata', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_short_title', 'back-matter', array( + x_add_metadata_field( + 'pb_short_title', 'back-matter', [ 'group' => 'back-matter-metadata', 'label' => __( 'Back Matter Short Title (appears in the PDF running header)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_subtitle', 'back-matter', array( + x_add_metadata_field( + 'pb_subtitle', 'back-matter', [ 'group' => 'back-matter-metadata', 'label' => __( 'Back Matter Subtitle (appears in the Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_author', 'back-matter', array( + x_add_metadata_field( + 'pb_section_author', 'back-matter', [ 'group' => 'back-matter-metadata', 'label' => __( 'Back Matter Author (appears in Web/ebook/PDF output)', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_section_license', 'back-matter', array( + x_add_metadata_field( + 'pb_section_license', 'back-matter', [ 'group' => 'back-matter-metadata', 'field_type' => 'select', - 'values' => array( - '' => '--Select--', - 'public-domain' => 'No Rights Reserved (Public Domain)', - 'cc-by' => 'CC BY (Attribution)', - 'cc-by-sa' => 'CC BY-SA (Attribution ShareAlike)', - 'cc-by-nd' => 'CC BY-ND (Attribution NoDerivatives)', - 'cc-by-nc' => 'CC BY-NC (Attribution NonCommercial)', - 'cc-by-nc-sa' => 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', - 'cc-by-nc-nd' => 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', - 'all-rights-reserved' => 'All Rights Reserved', - ), + 'values' => [ + '' => '--Select--', + 'public-domain' => __( 'No Rights Reserved (Public Domain)', 'pressbooks' ), + 'cc-by' => __( 'CC BY (Attribution)', 'pressbooks' ), + 'cc-by-sa' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), + 'cc-by-nd' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), + 'cc-by-nc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), + 'cc-by-nc-sa' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), + 'cc-by-nc-nd' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), + 'all-rights-reserved' => __( 'All Rights Reserved', 'pressbooks' ), + ], 'label' => __( 'Back Matter Copyright License (overrides book license on this page)', 'pressbooks' ), - ) ); + ] + ); // Part Metadata - x_add_metadata_group( 'part-metadata-text', 'part', array( + x_add_metadata_group( + 'part-metadata-text', 'part', [ 'label' => __( 'Part Text', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_field( 'pb_part_content', 'part', array( + x_add_metadata_field( + 'pb_part_content', 'part', [ 'field_type' => 'wysiwyg', 'group' => 'part-metadata-text', 'label' => '', 'description' => __( 'Appears on part page. Parts will not appear if a book has only one part.', 'pressbooks' ), - ) ); + ] + ); - x_add_metadata_group( 'part-metadata-visibility', 'part', array( + x_add_metadata_group( + 'part-metadata-visibility', 'part', [ 'label' => __( 'Part Visibility', 'pressbooks' ), 'context' => 'side', 'priority' => 'low', - ) ); + ] + ); - x_add_metadata_field( 'pb_part_invisible', 'part', array( + x_add_metadata_field( + 'pb_part_invisible', 'part', [ 'field_type' => 'checkbox', 'group' => 'part-metadata-visibility', 'label' => 'Invisible', 'description' => __( 'Hide from table of contents and part numbering.', 'pressbooks' ), - ) ); + ] + ); } @@ -580,7 +706,7 @@ function add_meta_boxes() { */ function override_parent_id( $post ) { - if ( 'chapter' != $post->post_type ) { + if ( 'chapter' !== $post->post_type ) { return; // Do nothing } @@ -593,13 +719,13 @@ function override_parent_id( $post ) { } $pages = wp_dropdown_pages( - array( + [ 'post_type' => 'part', 'selected' => $selected, 'name' => 'parent_id', 'sort_column' => 'menu_order', 'echo' => 0, - ) + ] ); if ( ! empty( $pages ) ) { @@ -620,7 +746,8 @@ function delete_cover_image() { // Delete old images $old_id = \Pressbooks\Image\attachment_id_from_url( $image_url ); - if ( $old_id ) { wp_delete_attachment( $old_id, true ); + if ( $old_id ) { + wp_delete_attachment( $old_id, true ); } update_post_meta( $pid, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); @@ -639,12 +766,12 @@ function delete_cover_image() { * @param \WP_Post $post */ function part_save_box( $post ) { - if ( 'publish' == $post->post_status ) { ?> - - + if ( 'publish' === $post->post_status ) { ?> + + - - + + post_status ) { ?> - - + if ( 'publish' === $post->post_status ) { ?> + + - - + + 'additional-catalogue-information', 'label' => __( 'BISAC Subject(s)', 'pressbooks' ), 'multiple' => true, 'description' => __( 'BISAC Subject Headings help libraries and (e)book stores properly classify your book.', 'pressbooks' ), - ) ); + ] + ); } - -add_action( 'pb_add_bisac_subjects_field', __NAMESPACE__ . '\\add_bisac_subjects_field', 1 ); diff --git a/includes/admin/class-pb-network-sharingandprivacyoptions.php b/inc/admin/network/class-sharingandprivacyoptions.php similarity index 80% rename from includes/admin/class-pb-network-sharingandprivacyoptions.php rename to inc/admin/network/class-sharingandprivacyoptions.php index 43ec4c4d06..516cb12f02 100644 --- a/includes/admin/class-pb-network-sharingandprivacyoptions.php +++ b/inc/admin/network/class-sharingandprivacyoptions.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Network; class SharingAndPrivacyOptions extends \Pressbooks\Options { @@ -15,24 +16,24 @@ class SharingAndPrivacyOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Sharing and Privacy options. - * - * @var array - */ + * Sharing and Privacy options. + * + * @var array + */ public $options; /** - * Sharing and Privacy defaults. - * - * @var array - */ + * Sharing and Privacy defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -55,25 +56,25 @@ function init() { add_settings_section( $_section, '', - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'allow_redistribution', __( 'Allow Redistribution', 'pressbooks' ), - array( $this, 'renderAllowRedistributionField' ), + [ $this, 'renderAllowRedistributionField' ], $_page, $_section, - array( + [ __( 'Allow book administrators to enable redistribution of export files.', 'pressbooks' ), - ) + ] ); register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -89,12 +90,12 @@ function render() { ?>

getTitle(); ?>

- getSlug() ); - $this->renderCheckbox( array( - 'id' => 'allow_redistribution', - 'name' => $this->getSlug(), - 'option' => 'allow_redistribution', - 'value' => ( isset( $options['allow_redistribution'] ) ) ? $options['allow_redistribution'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'allow_redistribution', + 'name' => $this->getSlug(), + 'option' => 'allow_redistribution', + 'value' => ( isset( $options['allow_redistribution'] ) ) ? $options['allow_redistribution'] : '', + 'label' => $args[0], + ] + ); } /** @@ -155,9 +159,9 @@ static function getTitle() { * @return array $defaults */ static function getDefaults() { - return array( + return [ 'allow_redistribution' => 0, - ); + ]; } /** @@ -166,15 +170,16 @@ static function getDefaults() { * @return array $options */ static function getBooleanOptions() { - return array( - 'allow_redistribution' - ); + return [ + 'allow_redistribution', + ]; } /** * Filter the array of default values for this set of options * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { diff --git a/includes/admin/pb-network-managers.php b/inc/admin/networkmanagers/namespace.php similarity index 89% rename from includes/admin/pb-network-managers.php rename to inc/admin/networkmanagers/namespace.php index 3a776a575d..70e29825f2 100644 --- a/includes/admin/pb-network-managers.php +++ b/inc/admin/networkmanagers/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Admin\NetworkManagers; +namespace Pressbooks\Admin\NetworkManagers; /** * @@ -27,9 +27,11 @@ function add_menu() { function admin_enqueues() { wp_enqueue_style( 'pb-network-managers', \Pressbooks\Utility\asset_path( 'styles/network-managers.css' ) ); wp_enqueue_script( 'pb-network-managers', \Pressbooks\Utility\asset_path( 'scripts/network-managers.js' ), [ 'jquery' ] ); - wp_localize_script( 'pb-network-managers', 'PB_NetworkManagerToken', array( + wp_localize_script( + 'pb-network-managers', 'PB_NetworkManagerToken', [ 'networkManagerNonce' => wp_create_nonce( 'pb-network-managers' ), - ) ); + ] + ); } /** @@ -43,17 +45,17 @@ function update_admin_status() { if ( $restricted ) { $restricted = maybe_unserialize( $restricted[0]->meta_value ); } else { - $restricted = array(); + $restricted = []; } $id = absint( $_POST['admin_id'] ); if ( 1 === absint( $_POST['status'] ) ) { - if ( ! in_array( $id, $restricted ) ) { + if ( ! in_array( absint( $id ), $restricted, true ) ) { $restricted[] = $id; } } elseif ( 0 === absint( $_POST['status'] ) ) { - if ( ( $key = array_search( $id, $restricted ) ) !== false ) { + if ( ( $key = array_search( absint( $id ), $restricted, true ) ) !== false ) { unset( $restricted[ $key ] ); } } @@ -102,10 +104,10 @@ function is_restricted() { if ( $restricted ) { $restricted = maybe_unserialize( $restricted[0]->meta_value ); } else { - $restricted = array(); + $restricted = []; } - if ( in_array( $user->ID, $restricted ) ) { + if ( in_array( $user->ID, $restricted, true ) ) { $val = true; } @@ -113,7 +115,7 @@ function is_restricted() { } /** - * + * @param \WP_Admin_Bar $wp_admin_bar */ function hide_admin_bar_menus( $wp_admin_bar ) { if ( is_restricted() ) { @@ -122,7 +124,9 @@ function hide_admin_bar_menus( $wp_admin_bar ) { } /** + * @param string $classes * + * @return string */ function admin_body_class( $classes ) { if ( is_restricted() ) { @@ -169,7 +173,7 @@ function restrict_access() { if ( $restricted ) { $restricted = maybe_unserialize( $restricted[0]->meta_value ); } else { - $restricted = array(); + $restricted = []; } $check_against_url = parse_url( ( is_ssl() ? 'http://' : 'https://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], PHP_URL_PATH ); @@ -178,7 +182,7 @@ function restrict_access() { // --------------------------------------------------------------------------------------------------------------- // Don't let user go to any of these pages, under any circumstances - $restricted_urls = array( + $restricted_urls = [ 'themes', 'theme-(install|editor)', 'plugins', @@ -186,10 +190,10 @@ function restrict_access() { 'settings', 'update-core', 'upgrade', - ); + ]; $expr = '~/wp-admin/network/(' . implode( '|', $restricted_urls ) . ')\.php$~'; - if ( in_array( $user->ID, $restricted ) && preg_match( $expr, $check_against_url ) ) { + if ( in_array( $user->ID, $restricted, true ) && preg_match( $expr, $check_against_url ) ) { \Pressbooks\Redirect\location( $redirect_url ); } diff --git a/includes/admin/pb-plugins.php b/inc/admin/plugins/namespace.php similarity index 96% rename from includes/admin/pb-plugins.php rename to inc/admin/plugins/namespace.php index 96dfcf8bbf..1f025bf976 100644 --- a/includes/admin/pb-plugins.php +++ b/inc/admin/plugins/namespace.php @@ -5,6 +5,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Admin\Plugins; /** @@ -13,6 +14,7 @@ * `remove_filter( 'all_plugins', '\Pressbooks\Admin\Plugins\filter_plugins', 10 );` * * @param array $plugins + * * @return array $plugins */ @@ -24,7 +26,7 @@ function filter_plugins( $plugins ) { $approved[] = $slug . '/' . $slug . '.php'; } foreach ( $plugins as $slug => $value ) { - if ( false === strpos( $slug, 'pressbooks-' ) && ! in_array( $slug, $approved ) ) { + if ( false === strpos( $slug, 'pressbooks-' ) && ! in_array( $slug, $approved, true ) ) { unset( $plugins[ $slug ] ); } } diff --git a/includes/pb-analytics.php b/inc/analytics/namespace.php similarity index 88% rename from includes/pb-analytics.php rename to inc/analytics/namespace.php index 3e3b2942c4..db695bdcba 100644 --- a/includes/pb-analytics.php +++ b/inc/analytics/namespace.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Analytics; /** @@ -28,12 +29,12 @@ function print_analytics() { } if ( $network && $book ) { - if ( $ga_mu_uaid_network == $ga_mu_uaid ) { + if ( absint( $ga_mu_uaid_network ) === absint( $ga_mu_uaid ) ) { $book = false; } } - if ( true == $book && ( ! isset( $ga_mu_site_specific_allowed ) || '' == $ga_mu_site_specific_allowed || '0' == $ga_mu_site_specific_allowed ) ) { + if ( true === $book && ( ! isset( $ga_mu_site_specific_allowed ) || empty( $ga_mu_site_specific_allowed ) ) ) { $book = false; } diff --git a/includes/class-pb-activation.php b/inc/class-activation.php similarity index 84% rename from includes/class-pb-activation.php rename to inc/class-activation.php index ab217cfc05..fb1c9608da 100644 --- a/includes/class-pb-activation.php +++ b/inc/class-activation.php @@ -6,8 +6,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; +namespace Pressbooks; class Activation { @@ -24,10 +24,10 @@ class Activation { /** * @var array The set of default WP options to set up on activation */ - private $opts = array( + private $opts = [ 'show_on_front' => 'page', 'rewrite_rules' => '', - ); + ]; /** @@ -89,11 +89,15 @@ function wpmuNewBlog( $blog_id, $user_id ) { switch_to_blog( $this->blog_id ); if ( ! $this->isBookSetup() ) { $this->wpmuActivate(); - array_walk( $this->opts, function ( $v, $k ) { - if ( empty( $v ) ) { delete_option( $k ); - } else { update_option( $k, $v ); + array_walk( + $this->opts, function ( $v, $k ) { + if ( empty( $v ) ) { + delete_option( $k ); + } else { + update_option( $k, $v ); + } } - } ); + ); wp_cache_flush(); } @@ -127,10 +131,10 @@ private function isBookSetup() { if ( empty( $act ) ) { return false; } - if ( ( get_option( 'template' ) != 'pressbooks-book' ) || ( get_option( 'stylesheet' ) != 'pressbooks-book' ) ) { + if ( ( get_option( 'template' ) !== 'pressbooks-book' ) || ( get_option( 'stylesheet' ) !== 'pressbooks-book' ) ) { return false; } - if ( ( get_option( 'show_on_front' ) != 'page' ) || ( ( ! is_int( $pof ) ) || ( ! get_post( $pof ) ) ) || ( ( ! is_int( $pop ) ) || ( ! get_post( $pop ) ) ) ) { + if ( ( get_option( 'show_on_front' ) !== 'page' ) || ( ( ! is_int( $pof ) ) || ( ! get_post( $pof ) ) ) || ( ( ! is_int( $pop ) ) || ( ! get_post( $pop ) ) ) ) { return false; } if ( ( count( get_all_category_ids() ) < 3 ) || ( wp_count_posts()->publish < 3 ) || ( wp_count_posts( 'page' )->publish < 3 ) ) { @@ -155,92 +159,99 @@ private function wpmuActivate() { \Pressbooks\Taxonomy::insertTerms(); - $posts = array( + $posts = [ // Parts, Chapters, Front-Matter, Back-Matter - array( + [ 'post_title' => __( 'Main Body', 'pressbooks' ), 'post_name' => 'main-body', 'post_type' => 'part', 'menu_order' => 1, - ), - array( + ], + [ 'post_title' => __( 'Introduction', 'pressbooks' ), 'post_name' => 'introduction', 'post_content' => __( 'This is where you can write your introduction.', 'pressbooks' ), 'post_type' => 'front-matter', 'menu_order' => 1, - ), - array( + ], + [ 'post_title' => __( 'Chapter 1', 'pressbooks' ), 'post_name' => 'chapter-1', 'post_content' => __( 'This is the first chapter in the main body of the text. You can change the text, rename the chapter, add new chapters, and add new parts.', 'pressbooks' ), 'post_type' => 'chapter', 'menu_order' => 1, - ), - array( + ], + [ 'post_title' => __( 'Appendix', 'pressbooks' ), 'post_name' => 'appendix', 'post_content' => __( 'This is where you can add appendices or other back matter.', 'pressbooks' ), 'post_type' => 'back-matter', 'menu_order' => 1, - ), + ], // Pages - array( + [ 'post_title' => __( 'Authors', 'pressbooks' ), 'post_name' => 'authors', 'post_type' => 'page', - ), - array( + ], + [ 'post_title' => __( 'Cover', 'pressbooks' ), 'post_name' => 'cover', 'post_type' => 'page', - ), - array( + ], + [ 'post_title' => __( 'Table of Contents', 'pressbooks' ), 'post_name' => 'table-of-contents', 'post_type' => 'page', - ), - array( + ], + [ 'post_title' => __( 'About', 'pressbooks' ), 'post_name' => 'about', 'post_type' => 'page', - ), - array( + ], + [ 'post_title' => __( 'Buy', 'pressbooks' ), 'post_name' => 'buy', 'post_type' => 'page', - ), - array( + ], + [ 'post_title' => __( 'Access Denied', 'pressbooks' ), 'post_name' => 'access-denied', 'post_content' => __( 'This book is private, and accessible only to registered users. If you have an account you can login here. You can also set up your own Pressbooks book at: Pressbooks.com.', 'pressbooks' ), 'post_type' => 'page', - ), + ], // Custom CSS - array( + [ 'post_title' => __( 'Custom CSS for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-css', - ), - array( + ], + [ 'post_title' => __( 'Custom CSS for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-css', - ), - array( + ], + [ 'post_title' => __( 'Custom CSS for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-css', - ), - array( + ], + [ 'post_title' => __( 'Book Information', 'pressbooks' ), 'post_name' => 'book-information', 'post_type' => 'metadata', - ), - ); - - $post = array( 'post_status' => 'publish', 'comment_status' => 'open', 'post_author' => $this->user_id ); - $page = array( 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => '', 'post_author' => $this->user_id, 'tags_input' => __( 'Default Data', 'pressbooks' ) ); + ], + ]; + + $post = [ 'post_status' => 'publish', 'comment_status' => 'open', 'post_author' => $this->user_id ]; + $page = [ + 'post_status' => 'publish', + 'comment_status' => 'closed', + 'ping_status' => 'closed', + 'post_content' => '', + 'post_author' => $this->user_id, + 'tags_input' => __( 'Default Data', 'pressbooks' ), + ]; /** * Allow the default description of a new book to be customized. @@ -258,9 +269,17 @@ private function wpmuActivate() { foreach ( $posts as $item ) { - $exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", array( $item['post_title'], $item['post_type'], $item['post_name'] ) ) ); + $exists = $wpdb->get_var( + $wpdb->prepare( + "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", [ + $item['post_title'], + $item['post_type'], + $item['post_name'], + ] + ) + ); if ( empty( $exists ) ) { - if ( 'page' == $item['post_type'] ) { + if ( 'page' === $item['post_type'] ) { $data = array_merge( $item, $page ); } else { $data = array_merge( $item, $post ); @@ -277,29 +296,30 @@ private function wpmuActivate() { break; } - if ( 'part' == $item['post_type'] ) { + if ( 'part' === $item['post_type'] ) { $parent_part = $newpost; - } elseif ( 'chapter' == $item['post_type'] ) { - $my_post = array(); + } elseif ( 'chapter' === $item['post_type'] ) { + $my_post = []; $my_post['ID'] = $newpost; $my_post['post_parent'] = $parent_part; wp_update_post( $my_post ); $chapter1 = $newpost; - } elseif ( 'front-matter' == $item['post_type'] ) { + } elseif ( 'front-matter' === $item['post_type'] ) { $intro = $newpost; - } elseif ( 'back-matter' == $item['post_type'] ) { + } elseif ( 'back-matter' === $item['post_type'] ) { $appendix = $newpost; - } elseif ( 'metadata' == $item['post_type'] ) { + } elseif ( 'metadata' === $item['post_type'] ) { $metadata_id = $newpost; if ( 0 !== get_current_user_id() ) { $user_info = get_userdata( get_current_user_id() ); $name = $user_info->display_name; update_post_meta( $metadata_id, 'pb_author', $name ); } - if ( $locale = get_option( 'WPLANG' ) ) { - $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes() ); + $locale = get_option( 'WPLANG' ); + if ( ! empty( $locale ) ) { + $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes(), true ); } elseif ( $locale = get_site_option( 'WPLANG' ) ) { - $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes() ); + $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes(), true ); } else { $locale = 'en'; } diff --git a/includes/class-pb-book.php b/inc/class-book.php similarity index 84% rename from includes/class-pb-book.php rename to inc/class-book.php index 404cfd018d..2eeec04eb1 100644 --- a/includes/class-pb-book.php +++ b/inc/class-book.php @@ -7,6 +7,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks; class Book { @@ -18,14 +19,11 @@ class Book { * @see wp_unique_post_slug() * @var array */ - static $fixDupeSlugs = array(); - + static $fixDupeSlugs = []; function __construct() { - } - /** * Check if the current blog_id is considered a "book" * @@ -46,15 +44,16 @@ static function isBook() { * Returns book information in a useful, string only, format. Data is converted to HTML. * * @param int $id The book ID. + * * @return array */ - static function getBookInformation( $id = '' ) { + static function getBookInformation( $id = null ) { // ----------------------------------------------------------------------------- // Is cached? // ----------------------------------------------------------------------------- + if ( ! empty( $id ) && is_int( $id ) ) { - // @codingStandardsIgnoreLine $blog_id = $id; switch_to_blog( $blog_id ); } else { @@ -70,11 +69,11 @@ static function getBookInformation( $id = '' ) { // Book Information // ---------------------------------------------------------------------------- - $expected_array = array( 'pb_keywords_tags', 'pb_bisac_subject', 'pb_contributing_authors' ); - $expected_the_content = array( 'pb_custom_copyright', 'pb_about_unlimited' ); - $expected_url = array( 'pb_cover_image' ); + $expected_array = [ 'pb_keywords_tags', 'pb_bisac_subject', 'pb_contributing_authors' ]; + $expected_the_content = [ 'pb_custom_copyright', 'pb_about_unlimited' ]; + $expected_url = [ 'pb_cover_image' ]; - $book_information = array(); + $book_information = []; $meta = new Metadata(); $data = $meta->getMetaPostMetadata(); @@ -87,7 +86,7 @@ static function getBookInformation( $id = '' ) { // We only care about strings if ( is_array( $val ) ) { - if ( false !== in_array( $key, $expected_array ) ) { + if ( false !== in_array( $key, $expected_array, true ) ) { $val = implode( ', ', $val ); } else { $val = array_values( $val ); @@ -100,7 +99,7 @@ static function getBookInformation( $id = '' ) { continue; } - if ( false !== in_array( $key, $expected_the_content ) ) { + if ( false !== in_array( $key, $expected_the_content, true ) ) { $val = wptexturize( $val ); $val = wpautop( $val ); } else { @@ -108,7 +107,7 @@ static function getBookInformation( $id = '' ) { } // Normalize URLs - if ( in_array( $key, $expected_url ) ) { + if ( in_array( $key, $expected_url, true ) ) { $val = set_url_scheme( $val ); } @@ -149,16 +148,17 @@ static function getBookInformation( $id = '' ) { * * @see bottom of this file for more info * - * @param string $id + * @param int $id + * * @return array */ - static function getBookStructure( $id = '' ) { + static function getBookStructure( $id = null ) { // ----------------------------------------------------------------------------- // Is cached? // ----------------------------------------------------------------------------- + if ( ! empty( $id ) && is_int( $id ) ) { - // @codingStandardsIgnoreLine $blog_id = $id; switch_to_blog( $id ); } else { @@ -174,14 +174,14 @@ static function getBookStructure( $id = '' ) { // Query our custom post types, keep minimal data in $book_structure // ----------------------------------------------------------------------------- - $book_structure = array(); + $book_structure = []; - $custom_types = array( + $custom_types = [ 'front-matter', 'part', 'chapter', 'back-matter', - ); + ]; $q = new \WP_Query(); @@ -189,24 +189,24 @@ static function getBookStructure( $id = '' ) { * Fetch all pb_export meta values for this book */ global $wpdb; - $post_ids_to_export = array(); + $post_ids_to_export = []; foreach ( $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s", 'pb_export' ), ARRAY_A ) as $val ) { $post_ids_to_export[ $val['post_id'] ] = $val['meta_value']; } foreach ( $custom_types as $type ) { - $book_structure[ $type ] = array(); + $book_structure[ $type ] = []; - $args = array( + $args = [ 'post_type' => $type, - 'posts_per_page' => - 1, + 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => 'any', 'orderby' => 'menu_order', 'order' => 'ASC', 'no_found_rows' => true, 'cache_results' => true, - ); + ]; $results = $q->query( $args ); @@ -214,7 +214,7 @@ static function getBookStructure( $id = '' ) { $post_name = static::fixSlug( $post->post_name ); - $book_structure[ $type ][] = array( + $book_structure[ $type ][] = [ 'ID' => $post->ID, 'post_title' => $post->post_title, 'post_name' => $post_name, @@ -222,9 +222,9 @@ static function getBookStructure( $id = '' ) { 'comment_count' => $post->comment_count, 'menu_order' => $post->menu_order, 'post_status' => $post->post_status, - 'export' => ( isset( $post_ids_to_export[ $post->ID ] ) && 'on' == $post_ids_to_export[ $post->ID ] ) ? true : false, + 'export' => ( isset( $post_ids_to_export[ $post->ID ] ) && 'on' === $post_ids_to_export[ $post->ID ] ) ? true : false, 'post_parent' => $post->post_parent, - ); + ]; } } @@ -233,12 +233,12 @@ static function getBookStructure( $id = '' ) { // ----------------------------------------------------------------------------- foreach ( $book_structure['part'] as $i => $part ) { - $book_structure['part'][ $i ]['chapters'] = array(); + $book_structure['part'][ $i ]['chapters'] = []; } foreach ( $book_structure['chapter'] as $i => $chapter ) { foreach ( $book_structure['part'] as $j => $part ) { - if ( $part['ID'] == $chapter['post_parent'] ) { + if ( $part['ID'] === $chapter['post_parent'] ) { $book_structure['part'][ $j ]['chapters'][] = $chapter; unset( $book_structure['chapter'][ $i ] ); continue 2; @@ -253,20 +253,20 @@ static function getBookStructure( $id = '' ) { } unset( $book_structure['chapter'] ); - $custom_types = array_diff( $custom_types, array( 'chapter' ) ); + $custom_types = array_diff( $custom_types, [ 'chapter' ] ); // ----------------------------------------------------------------------------- // Create __order and __lookup arrays, remove post_parent // ----------------------------------------------------------------------------- - $book_structure['__order'] = array(); - $book_structure['__export_lookup'] = array(); + $book_structure['__order'] = []; + $book_structure['__export_lookup'] = []; foreach ( $custom_types as $type ) { foreach ( $book_structure[ $type ] as $i => $struct ) { unset( $book_structure[ $type ][ $i ]['post_parent'] ); - if ( 'part' != $type ) { - $book_structure['__order'][ $struct['ID'] ] = array( 'export' => $struct['export'], 'post_status' => $struct['post_status'] ); + if ( 'part' !== $type ) { + $book_structure['__order'][ $struct['ID'] ] = [ 'export' => $struct['export'], 'post_status' => $struct['post_status'] ]; if ( $struct['export'] ) { $book_structure['__export_lookup'][ $struct['post_name'] ] = $type; } @@ -274,9 +274,9 @@ static function getBookStructure( $id = '' ) { foreach ( $struct['chapters'] as $j => $chapter ) { unset( $book_structure[ $type ][ $i ]['chapters'][ $j ]['post_parent'] ); if ( get_post_meta( $struct['ID'], 'pb_part_content', true ) && get_post_meta( $struct['ID'], 'pb_part_invisible', true ) !== 'on' ) { - $book_structure['__order'][ $struct['ID'] ] = array( 'export' => $struct['export'], 'post_status' => $struct['post_status'] ); + $book_structure['__order'][ $struct['ID'] ] = [ 'export' => $struct['export'], 'post_status' => $struct['post_status'] ]; } - $book_structure['__order'][ $chapter['ID'] ] = array( 'export' => $chapter['export'], 'post_status' => $chapter['post_status'] ); + $book_structure['__order'][ $chapter['ID'] ] = [ 'export' => $chapter['export'], 'post_status' => $chapter['post_status'] ]; if ( $chapter['export'] ) { $book_structure['__export_lookup'][ $chapter['post_name'] ] = 'chapter'; } @@ -332,7 +332,7 @@ static function getBookContents() { continue; // Skip __magic keys } - if ( 'part' == $type ) { + if ( 'part' === $type ) { foreach ( $struct as $i => $part ) { $book_contents[ $type ][ $i ] = $part + get_post( $part['ID'], ARRAY_A ); foreach ( $part['chapters'] as $j => $chapter ) { @@ -363,9 +363,9 @@ static function deleteBookObjectCache() { global $blog_id; - wp_cache_delete( "book-inf-$blog_id", 'pb' ); // getBookInfo() - wp_cache_delete( "book-str-$blog_id", 'pb' ); // getBookStructure() - wp_cache_delete( "book-cnt-$blog_id", 'pb' ); // getBookContents() + wp_cache_delete( "book-inf-$blog_id", 'pb' ); // Delete the cached value for getBookInfo() + wp_cache_delete( "book-str-$blog_id", 'pb' ); // Delete the cached value for getBookStructure() + wp_cache_delete( "book-cnt-$blog_id", 'pb' ); // Delete the cached value for getBookContents() ( new Catalog() )->deleteCacheByBookId( $blog_id ); } @@ -373,6 +373,7 @@ static function deleteBookObjectCache() { * Returns an array of subsections in front matter, back matter, or chapters. * * @param $id + * * @return array|false */ static function getSubsections( $id ) { @@ -381,7 +382,7 @@ static function getSubsections( $id ) { $parent = get_post( $id ); $type = $parent->post_type; - $output = array(); + $output = []; $s = 1; $content = mb_convert_encoding( apply_filters( 'the_content', $parent->post_content ), 'HTML-ENTITIES', 'UTF-8' ); @@ -422,7 +423,7 @@ static function tagSubsections( $content, $id ) { $parent = get_post( $id ); $type = $parent->post_type; $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ); - $content = str_replace( array( '', '', '', '' ), array( '', '', '', '' ), $content ); + $content = str_replace( [ '', '', '', '' ], [ '', '', '', '' ], $content ); if ( empty( $content ) ) { return false; @@ -432,12 +433,14 @@ static function tagSubsections( $content, $id ) { $doc->loadHTML( $content ); $sections = $doc->getElementsByTagName( 'h1' ); foreach ( $sections as $section ) { + /** @var $section \DOMElement */ $section->setAttribute( 'id', $type . '-' . $id . '-section-' . $s++ ); $section->setAttribute( 'class', 'section-header' ); } $xpath = new \DOMXPath( $doc ); while ( ( $nodes = $xpath->query( '//*[not(text() or node() or self::br or self::hr or self::img)]' ) ) && $nodes->length > 0 ) { foreach ( $nodes as $node ) { + /** @var $node \DOMElement */ $node->appendChild( new \DOMText( '' ) ); } } @@ -446,7 +449,7 @@ static function tagSubsections( $content, $id ) { $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); - return preg_replace( '/^/', '', str_replace( array( '', '', '', '' ), array( '', '', '', '' ), $html ) ); + return preg_replace( '/^/', '', str_replace( [ '', '', '', '' ], [ '', '', '', '' ], $html ) ); } /** @@ -460,26 +463,26 @@ static function updateChapter() { $id = absint( $_POST['id'] ); if ( current_user_can( 'edit_post', $id ) && check_ajax_referer( 'pb-update-book-order' ) ) { - parse_str( $_POST['new_part_order'], $newPartOrder ); - parse_str( $_POST['old_part_order'], $oldPartOrder ); - $newPart = (int) $_POST['new_part']; - $oldPart = (int) $_POST['old_part']; + parse_str( $_POST['new_part_order'], $new_part_order ); + parse_str( $_POST['old_part_order'], $old_part_order ); + $new_part = (int) $_POST['new_part']; + $old_part = (int) $_POST['old_part']; // if the part for this chapter changed, set new part for chapter // and new order for this part - if ( $newPart != $oldPart ) { + if ( $new_part !== $old_part ) { - $my_post = array(); + $my_post = []; $my_post['ID'] = $id; - $my_post['post_parent'] = $newPart; + $my_post['post_parent'] = $new_part; wp_update_post( $my_post ); - if ( is_array( $newPartOrder ) ) { - foreach ( $newPartOrder as $key => $values ) { - if ( 'chapter' == $key ) { + if ( is_array( $new_part_order ) ) { + foreach ( $new_part_order as $key => $values ) { + if ( 'chapter' === $key ) { foreach ( $values as $position => $id ) { $position += 1; // array is 0-indexed, but we want it to start from 1 - $wpdb->update( $wpdb->posts, array( 'menu_order' => $position ), array( 'ID' => $id ) ); + $wpdb->update( $wpdb->posts, [ 'menu_order' => $position ], [ 'ID' => $id ] ); clean_post_cache( $id ); } } @@ -488,12 +491,12 @@ static function updateChapter() { } // always update the order of the part this chapter was originally in - if ( is_array( $oldPartOrder ) ) { - foreach ( $oldPartOrder as $key => $values ) { - if ( 'chapter' == $key ) { + if ( is_array( $old_part_order ) ) { + foreach ( $old_part_order as $key => $values ) { + if ( 'chapter' === $key ) { foreach ( $values as $position => $id ) { $position += 1; // array is 0-indexed, but we want it to start from 1 - $wpdb->update( $wpdb->posts, array( 'menu_order' => $position ), array( 'ID' => $id ) ); + $wpdb->update( $wpdb->posts, [ 'menu_order' => $position ], [ 'ID' => $id ] ); clean_post_cache( $id ); } } @@ -518,14 +521,14 @@ static function updateFrontMatter() { if ( current_user_can( 'edit_posts' ) && check_ajax_referer( 'pb-update-book-order' ) ) { - parse_str( $_POST['front_matter_order'], $frontMatterOrder ); + parse_str( $_POST['front_matter_order'], $front_matter_order ); - if ( is_array( $frontMatterOrder ) ) { - foreach ( $frontMatterOrder as $key => $values ) { - if ( 'front-matter' == $key ) { + if ( is_array( $front_matter_order ) ) { + foreach ( $front_matter_order as $key => $values ) { + if ( 'front-matter' === $key ) { foreach ( $values as $position => $id ) { $position += 1; - $wpdb->update( $wpdb->posts, array( 'menu_order' => $position ), array( 'ID' => $id ) ); + $wpdb->update( $wpdb->posts, [ 'menu_order' => $position ], [ 'ID' => $id ] ); clean_post_cache( $id ); } } @@ -546,14 +549,14 @@ static function updateBackMatter() { if ( current_user_can( 'edit_posts' ) && check_ajax_referer( 'pb-update-book-order' ) ) { - parse_str( $_POST['back_matter_order'], $backMatterOrder ); + parse_str( $_POST['back_matter_order'], $back_matter_order ); - if ( is_array( $backMatterOrder ) ) { - foreach ( $backMatterOrder as $key => $values ) { - if ( 'back-matter' == $key ) { + if ( is_array( $back_matter_order ) ) { + foreach ( $back_matter_order as $key => $values ) { + if ( 'back-matter' === $key ) { foreach ( $values as $position => $id ) { $position += 1; - $wpdb->update( $wpdb->posts, array( 'menu_order' => $position ), array( 'ID' => $id ) ); + $wpdb->update( $wpdb->posts, [ 'menu_order' => $position ], [ 'ID' => $id ] ); clean_post_cache( $id ); } } @@ -571,11 +574,11 @@ static function updateExportOptions() { if ( check_ajax_referer( 'pb-update-book-export' ) ) { $post_id = absint( $_POST['post_id'] ); if ( current_user_can( 'edit_post', $post_id ) ) { - $valid_meta_keys = array( + $valid_meta_keys = [ 'pb_export', - ); + ]; - $meta_key = in_array( $_POST['type'], $valid_meta_keys ) ? $_POST['type'] : false; + $meta_key = in_array( $_POST['type'], $valid_meta_keys, true ) ? $_POST['type'] : false; if ( $meta_key ) { $meta_value = ( $_POST['chapter_export'] ) ? 'on' : 0; update_post_meta( $post_id, $meta_key, $meta_value ); @@ -592,11 +595,11 @@ static function updateShowTitleOptions() { if ( check_ajax_referer( 'pb-update-book-show-title' ) ) { $post_id = absint( $_POST['post_id'] ); if ( current_user_can( 'edit_post', $post_id ) ) { - $valid_meta_keys = array( + $valid_meta_keys = [ 'pb_show_title', - ); + ]; - $meta_key = in_array( $_POST['type'], $valid_meta_keys ) ? $_POST['type'] : false; + $meta_key = in_array( $_POST['type'], $valid_meta_keys, true ) ? $_POST['type'] : false; if ( $meta_key ) { $meta_value = ( $_POST['chapter_show_title'] ) ? 'on' : 0; update_post_meta( $post_id, $meta_key, $meta_value ); @@ -615,7 +618,7 @@ static function updatePrivacyOptions() { if ( current_user_can( 'edit_post', $post_id ) ) { $post_status = $_POST['post_status']; - $my_post = array(); + $my_post = []; $my_post['ID'] = $post_id; $my_post['post_status'] = $post_status; @@ -647,7 +650,7 @@ static function updateGlobalPrivacyOptions() { */ static function get( $what = 'next' ) { - if ( 'first' == $what ) { + if ( 'first' === $what ) { return static::getFirst(); } @@ -660,12 +663,12 @@ static function get( $what = 'next' ) { $order = $book_structure['__order']; $pos = array_keys( $order ); - $what = ( 'next' == $what ? 'next' : 'prev' ); + $what = ( 'next' === $what ? 'next' : 'prev' ); // Move internal pointer to correct position reset( $pos ); while ( $find_me = current( $pos ) ) { - if ( $find_me == $current_post_id ) { + if ( $find_me === $current_post_id ) { break; } else { next( $pos ); @@ -675,7 +678,7 @@ static function get( $what = 'next' ) { // Get next/previous $what( $pos ); while ( $post_id = current( $pos ) ) { - if ( 'publish' == $order[ $post_id ]['post_status'] ) { + if ( 'publish' === $order[ $post_id ]['post_status'] ) { break; } elseif ( current_user_can_for_blog( $blog_id, 'read_private_posts' ) ) { break; @@ -705,7 +708,7 @@ static function getFirst() { reset( $pos ); while ( $first_id = current( $pos ) ) { - if ( 'publish' == $order[ $first_id ]['post_status'] ) { + if ( 'publish' === $order[ $first_id ]['post_status'] ) { break; } elseif ( current_user_can_for_blog( $blog_id, 'read_private_posts' ) ) { break; @@ -724,14 +727,14 @@ static function getFirst() { /** * Ensures this chapter/part/front matter has a "menu_order" when it is saved * - * @param integer $pid Post ID + * @param integer $pid Post ID * @param \WP_Post $post Post * * @return bool */ static function consolidatePost( $pid, $post ) { - if ( false == Book::isBook() || wp_is_post_revision( $pid ) || 'auto-draft' == get_post_status( $pid ) ) { + if ( false === Book::isBook() || wp_is_post_revision( $pid ) || 'auto-draft' === get_post_status( $pid ) ) { return false; } @@ -741,7 +744,7 @@ static function consolidatePost( $pid, $post ) { // if this is a new post, set its order if ( empty( $post->menu_order ) ) { - if ( 'chapter' == $post->post_type ) { + if ( 'chapter' === $post->post_type ) { $new = $wpdb->get_var( $wpdb->prepare( "SELECT max({$wpdb->posts}.menu_order) + 1 @@ -797,7 +800,7 @@ static function consolidatePost( $pid, $post ) { */ static function deletePost( $pid ) { - if ( false == Book::isBook() || wp_is_post_revision( $pid ) || 'auto-draft' == get_post_status( $pid ) ) { + if ( false === Book::isBook() || wp_is_post_revision( $pid ) || 'auto-draft' === get_post_status( $pid ) ) { return false; } @@ -812,9 +815,7 @@ static function deletePost( $pid ) { $type = $post_to_delete->post_type; $parent = $post_to_delete->post_parent; - $query = "UPDATE {$wpdb->posts} SET menu_order = menu_order - 1 WHERE menu_order > {$order} AND post_type = '{$type}' "; - - if ( 'chapter' == $type ) { + if ( 'chapter' === $type ) { $success = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET menu_order = menu_order - 1 WHERE menu_order > %d AND post_type = %s AND post_parent = %d ", @@ -835,7 +836,7 @@ static function deletePost( $pid ) { clean_post_cache( $post_to_delete ); - if ( 'part' == $type ) { + if ( 'part' === $type ) { // We're setting two things here - the new post_parent (to the first part) // And the new menu order for the chapters that were in the part being deleted. @@ -901,7 +902,8 @@ static protected function fixSlug( $old_post_name ) { ++static::$fixDupeSlugs[ $new_post_name ]; ++static::$fixDupeSlugs[ $old_post_name ]; $new_post_name = $old_post_name . '-' . static::$fixDupeSlugs[ $old_post_name ]; - if ( $i > 999 ) { break; // Safety + if ( $i > 999 ) { + break; // Safety } ++$i; } diff --git a/includes/class-pb-catalog.php b/inc/class-catalog.php similarity index 81% rename from includes/class-pb-catalog.php rename to inc/class-catalog.php index 795712ca60..17c8ce44a1 100644 --- a/includes/class-pb-catalog.php +++ b/inc/class-catalog.php @@ -6,10 +6,9 @@ * @license GPLv2 (or any later version) */ -// @codingStandardsIgnoreStart - namespace Pressbooks; +use function \Pressbooks\Utility\getset; class Catalog { @@ -52,12 +51,12 @@ class Catalog { * * @var array */ - protected $dbColumns = array( + protected $dbColumns = [ 'users_id' => '%d', 'blogs_id' => '%d', 'deleted' => '%d', 'featured' => '%d', - ); + ]; /** @@ -65,13 +64,13 @@ class Catalog { * * @var array */ - protected $profileMetaKeys = array( + protected $profileMetaKeys = [ 'pb_catalog_about' => '%s', 'pb_catalog_logo' => '%s', 'pb_catalog_url' => '%s', 'pb_catalog_color' => '%s', // Tags added in constructor (Ie. pb_catalog_tag_1_name, pb_catalog_tag_2_name, ...) - ); + ]; /** @@ -121,12 +120,12 @@ function getUserId() { * @return array */ function get() { - /** @var $wpdb \wpdb */ global $wpdb; - $sql = $wpdb->prepare( "SELECT * FROM {$this->dbTable} WHERE users_id = %d AND deleted = 0 ", $this->userId ); - return $wpdb->get_results( $sql, ARRAY_A ); + $sql = "SELECT * FROM {$this->dbTable} WHERE users_id = %d AND deleted = 0 "; + + return $wpdb->get_results( $wpdb->prepare( $sql, $this->userId ), ARRAY_A ); // @codingStandardsIgnoreLine } @@ -151,18 +150,18 @@ function getAggregate() { // User Catalog // ---------------------------------------------------------------------------- - $cover_sizes = array( + $cover_sizes = [ 'thumbnail' => PB_PLUGIN_URL . 'assets/dist/images/default-book-cover-100x100.jpg', 'pb_cover_small' => PB_PLUGIN_URL . 'assets/dist/images/default-book-cover-65x0.jpg', 'pb_cover_medium' => PB_PLUGIN_URL . 'assets/dist/images/default-book-cover-225x0.jpg', 'pb_cover_large' => PB_PLUGIN_URL . 'assets/dist/images/default-book-cover.jpg', - ); + ]; $catalog = $this->get(); $usercatalog = new static( $this->userId ); - $data = array(); + $data = []; $i = 0; - $already_loaded = array(); + $already_loaded = []; foreach ( $catalog as $val ) { if ( ! get_site( $val['blogs_id'] ) ) { @@ -179,9 +178,9 @@ function getAggregate() { $data[ $i ]['featured'] = $val['featured']; $data[ $i ]['deleted'] = 0; $data[ $i ]['title'] = ! empty( $metadata['pb_title'] ) ? $metadata['pb_title'] : get_bloginfo( 'name' ); - $data[ $i ]['author'] = @$metadata['pb_author']; + $data[ $i ]['author'] = ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : ''; $data[ $i ]['pub_date'] = ! empty( $metadata['pb_publication_date'] ) ? date( 'Y-m-d', (int) $metadata['pb_publication_date'] ) : ''; - $data[ $i ]['private'] = ( 1 == get_option( 'blog_public' ) ? 0 : 1 ); + $data[ $i ]['private'] = ( ! empty( get_option( 'blog_public' ) ) ? 0 : 1 ); // About if ( ! empty( $metadata['pb_about_50'] ) ) { @@ -196,7 +195,8 @@ function getAggregate() { $data[ $i ]['about'] = $about; // Cover Full - if ( $meta_version < 7 ) { $cover = PB_PLUGIN_URL . 'assets/dist/images/default-book-cover.jpg'; + if ( $meta_version < 7 ) { + $cover = PB_PLUGIN_URL . 'assets/dist/images/default-book-cover.jpg'; } elseif ( empty( $metadata['pb_cover_image'] ) ) { $cover = PB_PLUGIN_URL . 'assets/dist/images/default-book-cover.jpg'; } elseif ( \Pressbooks\Image\is_default_cover( $metadata['pb_cover_image'] ) ) { @@ -217,8 +217,8 @@ function getAggregate() { * @since 3.9.5.1 * * @param string $cover The url to cover image. - * @param string $metadata['pb_cover_image'] The original url to the - * cover image. + * @param string $metadata ['pb_cover_image'] The original url to the + * cover image. */ $cid = \Pressbooks\Image\attachment_id_from_url( apply_filters( 'pb_cover_image', $cover, $metadata['pb_cover_image'] ) ); foreach ( $cover_sizes as $size => $default ) { @@ -262,9 +262,9 @@ function getAggregate() { $data[ $i ]['featured'] = 0; $data[ $i ]['deleted'] = 1; $data[ $i ]['title'] = ! empty( $metadata['pb_title'] ) ? $metadata['pb_title'] : get_bloginfo( 'name' ); - $data[ $i ]['author'] = @$metadata['pb_author']; + $data[ $i ]['author'] = ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : ''; $data[ $i ]['pub_date'] = ! empty( $metadata['pb_publication_date'] ) ? date( 'Y-m-d', (int) $metadata['pb_publication_date'] ) : ''; - $data[ $i ]['private'] = ( 1 == get_option( 'blog_public' ) ? 0 : 1 ); + $data[ $i ]['private'] = ( ! empty( get_option( 'blog_public' ) ) ? 0 : 1 ); // About if ( ! empty( $metadata['pb_about_50'] ) ) { @@ -340,9 +340,7 @@ function getByTagId( $tag_group, $tag_id ) { INNER JOIN {$this->dbTagsTable} ON {$this->dbTagsTable}.id = {$this->dbLinkTable}.tags_id WHERE {$this->dbLinkTable}.users_id = %d AND {$this->dbLinkTable}.tags_group = %d AND {$this->dbLinkTable}.tags_id = %d AND {$this->dbTable}.deleted = 0 "; - $sql = $wpdb->prepare( $sql, $this->userId, $tag_group, $tag_id ); - - return $wpdb->get_results( $sql, ARRAY_A ); + return $wpdb->get_results( $wpdb->prepare( $sql, $this->userId, $tag_group, $tag_id ), ARRAY_A ); // @codingStandardsIgnoreLine } @@ -374,9 +372,9 @@ function delete( $for_real = false ) { global $wpdb; if ( $for_real ) { - return $wpdb->delete( $this->dbTable, array( 'users_id' => $this->userId ), array( '%d' ) ); + return $wpdb->delete( $this->dbTable, [ 'users_id' => $this->userId ], [ '%d' ] ); } else { - return $wpdb->update( $this->dbTable, array( 'deleted' => 1 ), array( 'users_id' => $this->userId ), array( '%d' ), array( '%d' ) ); + return $wpdb->update( $this->dbTable, [ 'deleted' => 1 ], [ 'users_id' => $this->userId ], [ '%d' ], [ '%d' ] ); } } @@ -392,9 +390,10 @@ function getBook( $blog_id ) { /** @var $wpdb \wpdb */ global $wpdb; - $sql = $wpdb->prepare( "SELECT * FROM {$this->dbTable} WHERE users_id = %d AND blogs_id = %d AND deleted = 0 ", $this->userId, $blog_id ); - return $wpdb->get_row( $sql, ARRAY_A ); + $sql = "SELECT * FROM {$this->dbTable} WHERE users_id = %d AND blogs_id = %d AND deleted = 0 "; + + return $wpdb->get_row( $wpdb->prepare( $sql, $this->userId, $blog_id ), ARRAY_A ); // @codingStandardsIgnoreLine } @@ -407,9 +406,10 @@ function getBookIds() { /** @var $wpdb \wpdb */ global $wpdb; - $sql = $wpdb->prepare( "SELECT blogs_id FROM {$this->dbTable} WHERE users_id = %d AND deleted = 0 ", $this->userId ); - return $wpdb->get_col( $sql ); + $sql = "SELECT blogs_id FROM {$this->dbTable} WHERE users_id = %d AND deleted = 0 "; + + return $wpdb->get_col( $wpdb->prepare( $sql, $this->userId ) ); // @codingStandardsIgnoreLine } @@ -428,8 +428,8 @@ function saveBook( $blog_id, array $item ) { unset( $item['users_id'], $item['blogs_id'], $item['deleted'] ); // Don't allow spoofing - $data = array( 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'deleted' => 0 ); - $format = array( 'users_id' => $this->dbColumns['users_id'], 'blogs_id' => $this->dbColumns['blogs_id'], 'deleted' => $this->dbColumns['deleted'] ); + $data = [ 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'deleted' => 0 ]; + $format = [ 'users_id' => $this->dbColumns['users_id'], 'blogs_id' => $this->dbColumns['blogs_id'], 'deleted' => $this->dbColumns['deleted'] ]; foreach ( $item as $key => $val ) { if ( isset( $this->dbColumns[ $key ] ) ) { @@ -441,7 +441,7 @@ function saveBook( $blog_id, array $item ) { // INSERT ... ON DUPLICATE KEY UPDATE // @see http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html - $args = array(); + $args = []; $sql = "INSERT INTO {$this->dbTable} ( "; foreach ( $data as $key => $val ) { $sql .= "`$key`, "; @@ -456,19 +456,19 @@ function saveBook( $blog_id, array $item ) { $i = 0; foreach ( $data as $key => $val ) { - if ( 'users_id' == $key || 'blogs_id' == $key ) { continue; + if ( 'users_id' === $key || 'blogs_id' === $key ) { + continue; } $sql .= "`$key` = {$format[$key]}, "; $args[] = $val; ++$i; } $sql = rtrim( $sql, ', ' ); - if ( ! $i ) { $sql .= ' users_id = users_id '; // Do nothing + if ( ! $i ) { + $sql .= ' users_id = users_id '; // Do nothing } - $sql = $wpdb->prepare( $sql, $args ); - - return $wpdb->query( $sql ); + return $wpdb->query( $wpdb->prepare( $sql, $args ) ); // @codingStandardsIgnoreLine } @@ -486,9 +486,9 @@ function deleteBook( $blog_id, $for_real = false ) { global $wpdb; if ( $for_real ) { - return $wpdb->delete( $this->dbTable, array( 'users_id' => $this->userId, 'blogs_id' => $blog_id ), array( '%d', '%d' ) ); + return $wpdb->delete( $this->dbTable, [ 'users_id' => $this->userId, 'blogs_id' => $blog_id ], [ '%d', '%d' ] ); } else { - return $wpdb->update( $this->dbTable, array( 'deleted' => 1 ), array( 'users_id' => $this->userId, 'blogs_id' => $blog_id ), array( '%d' ), array( '%d', '%d' ) ); + return $wpdb->update( $this->dbTable, [ 'deleted' => 1 ], [ 'users_id' => $this->userId, 'blogs_id' => $blog_id ], [ '%d' ], [ '%d', '%d' ] ); } } @@ -511,13 +511,12 @@ function getTags( $tag_group, $show_hidden_tags = true ) { INNER JOIN {$this->dbTable} ON {$this->dbTable}.users_id = {$this->dbLinkTable}.users_id AND {$this->dbTable}.blogs_id = {$this->dbLinkTable}.blogs_id WHERE {$this->dbLinkTable}.tags_group = %d AND {$this->dbLinkTable}.users_id = %d "; - if ( true !== $show_hidden_tags ) { $sql .= "AND {$this->dbTable}.deleted = 0 "; + if ( true !== $show_hidden_tags ) { + $sql .= "AND {$this->dbTable}.deleted = 0 "; } $sql .= "ORDER BY {$this->dbTagsTable}.tag ASC "; - $sql = $wpdb->prepare( $sql, $tag_group, $this->userId ); - - return $wpdb->get_results( $sql, ARRAY_A ); + return $wpdb->get_results( $wpdb->prepare( $sql, $tag_group, $this->userId ), ARRAY_A ); // @codingStandardsIgnoreLine } @@ -540,9 +539,7 @@ function getTagsByBook( $blog_id, $tag_group ) { WHERE {$this->dbLinkTable}.tags_group = %d AND {$this->dbLinkTable}.users_id = %d AND {$this->dbLinkTable}.blogs_id = %d ORDER BY {$this->dbTagsTable}.tag ASC "; - $sql = $wpdb->prepare( $sql, $tag_group, $this->userId, $blog_id ); - - return $wpdb->get_results( $sql, ARRAY_A ); + return $wpdb->get_results( $wpdb->prepare( $sql, $tag_group, $this->userId, $blog_id ), ARRAY_A ); // @codingStandardsIgnoreLine } @@ -567,20 +564,17 @@ function saveTag( $tag, $blog_id, $tag_group ) { // @see http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html $sql = "INSERT INTO {$this->dbTagsTable} ( users_id, tag ) VALUES ( %d, %s ) ON DUPLICATE KEY UPDATE id = id "; - $sql = $wpdb->prepare( $sql, $this->userId, $tag ); - $_ = $wpdb->query( $sql ); + $_ = $wpdb->query( $wpdb->prepare( $sql, $this->userId, $tag ) ); // @codingStandardsIgnoreLine // Get ID $sql = "SELECT id FROM {$this->dbTagsTable} WHERE tag = %s "; - $sql = $wpdb->prepare( $sql, $tag ); - $tag_id = $wpdb->get_var( $sql ); + $tag_id = $wpdb->get_var( $wpdb->prepare( $sql, $tag ) ); // @codingStandardsIgnoreLine // Create JOIN $sql = "INSERT INTO {$this->dbLinkTable} ( users_id, blogs_id, tags_id, tags_group ) VALUES ( %d, %d, %d, %d ) ON DUPLICATE KEY UPDATE users_id = users_id "; - $sql = $wpdb->prepare( $sql, $this->userId, $blog_id, $tag_id, $tag_group ); - $result = $wpdb->query( $sql ); + $result = $wpdb->query( $wpdb->prepare( $sql, $this->userId, $blog_id, $tag_id, $tag_group ) ); // @codingStandardsIgnoreLine return $result; } @@ -606,27 +600,27 @@ function deleteTag( $tag, $blog_id, $tag_group, $for_real = false ) { // Get ID $sql = "SELECT id FROM {$this->dbTagsTable} WHERE tag = %s "; - $sql = $wpdb->prepare( $sql, $tag ); - $tag_id = $wpdb->get_var( $sql ); + $tag_id = $wpdb->get_var( $wpdb->prepare( $sql, $tag ) ); // @codingStandardsIgnoreLine if ( ! $tag_id ) { return false; } if ( $for_real && is_super_admin() ) { - - $wpdb->delete( $this->dbLinkTable, array( 'tags_id' => $tag_id ), array( '%d' ) ); - $wpdb->delete( $this->dbTagsTable, array( 'id' => $tag_id ), array( '%d' ) ); + $wpdb->delete( $this->dbLinkTable, [ 'tags_id' => $tag_id ], [ '%d' ] ); + $wpdb->delete( $this->dbTagsTable, [ 'id' => $tag_id ], [ '%d' ] ); $result = 1; - } else { - - $result = $wpdb->delete( $this->dbLinkTable, array( 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'tags_id' => $tag_id, 'tags_group' => $tag_group ), array( '%d', '%d', '%d', '%d' ) ); + $result = $wpdb->delete( + $this->dbLinkTable, + [ 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'tags_id' => $tag_id, 'tags_group' => $tag_group ], + [ '%d', '%d', '%d', '%d' ] + ); } // TODO: - // $wpdb->query( "OPTIMIZE TABLE {$this->dbLinkTable} " ); - // $wpdb->query( "OPTIMIZE TABLE {$this->dbTagsTable} " ); + // Optimize the links table: $wpdb->query( "OPTIMIZE TABLE {$this->dbLinkTable} " ); + // Optimize the tags table: $wpdb->query( "OPTIMIZE TABLE {$this->dbTagsTable} " ); return $result; } @@ -647,10 +641,10 @@ function deleteTags( $blog_id, $tag_group ) { /** @var $wpdb \wpdb */ global $wpdb; - $result = $wpdb->delete( $this->dbLinkTable, array( 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'tags_group' => $tag_group ), array( '%d', '%d', '%d' ) ); + $result = $wpdb->delete( $this->dbLinkTable, [ 'users_id' => $this->userId, 'blogs_id' => $blog_id, 'tags_group' => $tag_group ], [ '%d', '%d', '%d' ] ); // TODO: - // $wpdb->query( "OPTIMIZE TABLE {$this->dbLinkTable} " ); + // Optimize the links table: $wpdb->query( "OPTIMIZE TABLE {$this->dbLinkTable} " ); return $result; @@ -694,17 +688,17 @@ function saveProfile( array $item ) { foreach ( $item as $key => $val ) { - if ( 'pb_catalog_logo' == $key ) { + if ( 'pb_catalog_logo' === $key ) { continue; // Skip, dev should use uploadLogo() instead } - if ( 'pb_catalog_url' == $key && $val ) { + if ( 'pb_catalog_url' === $key && $val ) { $val = \Pressbooks\Sanitize\canonicalize_url( $val ); } - if ( '%d' == $this->profileMetaKeys[ $key ] ) { + if ( '%d' === $this->profileMetaKeys[ $key ] ) { $val = (int) $val; - } elseif ( '%f' == $this->profileMetaKeys[ $key ] ) { + } elseif ( '%f' === $this->profileMetaKeys[ $key ] ) { $val = (float) $val; } else { $val = (string) $val; @@ -720,7 +714,7 @@ function saveProfile( array $item ) { */ function uploadLogo( $meta_key ) { - if ( @empty( $_FILES[ $meta_key ]['name'] ) ) { + if ( isset( $_FILES[ $meta_key ]['name'] ) && empty( $_FILES[ $meta_key ]['name'] ) ) { return; // Bail } @@ -731,8 +725,8 @@ function uploadLogo( $meta_key ) { switch_to_blog( $book->blog_id ); - $allowed_file_types = array( 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png' ); - $overrides = array( 'test_form' => false, 'mimes' => $allowed_file_types ); + $allowed_file_types = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png' ]; + $overrides = [ 'test_form' => false, 'mimes' => $allowed_file_types ]; $image = wp_handle_upload( $_FILES[ $meta_key ], $overrides ); if ( ! empty( $image['error'] ) ) { @@ -746,19 +740,20 @@ function uploadLogo( $meta_key ) { // Delete old images foreach ( $old as $old_url ) { $old_id = \Pressbooks\Image\attachment_id_from_url( $old_url ); - if ( $old_id ) { wp_delete_attachment( $old_id, true ); + if ( $old_id ) { + wp_delete_attachment( $old_id, true ); } } // Insert new image, create thumbnails - $args = array( + $args = [ 'post_mime_type' => $image['type'], 'post_title' => __( 'Catalog Logo', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', 'post_name' => "pb-catalog-logo-{$this->userId}", 'post_author' => $this->userId, - ); + ]; $id = wp_insert_attachment( $args, $image['file'], 0 ); wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $image['file'] ) ); @@ -786,7 +781,7 @@ function deleteCacheByBookId( $book_id ) { global $wpdb; $sql = "SELECT users_id FROM {$this->dbTable} WHERE blogs_id = %d "; - $results = $wpdb->get_col( $wpdb->prepare( $sql, $book_id ) ); + $results = $wpdb->get_col( $wpdb->prepare( $sql, $book_id ) ); // @codingStandardsIgnoreLine foreach ( $results as $user_id ) { wp_cache_delete( "cat-$user_id", 'pb' ); @@ -876,7 +871,8 @@ static function stringToTags( $tags ) { $val = mb_split( '\W', $val ); // Split on negated \w $val = implode( ' ', $val ); // Put back together with spaces $val = trim( $val ); - if ( ! $val ) { unset( $tags[ $key ] ); + if ( ! $val ) { + unset( $tags[ $key ] ); } } @@ -930,19 +926,15 @@ static function thumbnailFromUserId( $user_id, $size ) { * WP Hook, Instantiate UI */ static function addMenu() { - - switch ( @$_REQUEST['action'] ) { - + switch ( getset( '_REQUEST', 'action' ) ) { case 'edit_profile': case 'edit_tags': require( PB_PLUGIN_DIR . 'templates/admin/catalog.php' ); break; - case 'add': case 'remove': // This should not happen, formSubmit() is supposed to catch this break; - default: Admin\Catalog_List_Table::addMenu(); break; @@ -953,14 +945,16 @@ static function addMenu() { /** * Find and load our catalog template. * - * @param int $userId + * @param int $user_id */ - static function loadTemplate( $userId ) { + static function loadTemplate( $user_id ) { global $wp_query; - $wp_query->set( 'pb_user_id', $userId ); + $wp_query->set( 'pb_user_id', $user_id ); + + $overridden_template = locate_template( 'pb-catalog.php' ); - if ( $overridden_template = locate_template( 'pb-catalog.php' ) ) { + if ( $overridden_template ) { load_template( $overridden_template, false ); } else { load_template( PB_PLUGIN_DIR . 'templates/pb-catalog.php', false ); @@ -978,7 +972,7 @@ static function loadTemplate( $userId ) { */ static function formSubmit() { - if ( false == static::isFormSubmission() || false == current_user_can( 'read' ) ) { + if ( empty( static::isFormSubmission() ) || empty( current_user_can( 'read' ) ) ) { // Don't do anything in this function, bail. return; } @@ -1005,11 +999,15 @@ static function formSubmit() { */ static function isFormSubmission() { - if ( 'pb_catalog' != @$_REQUEST['page'] ) { + if ( empty( $_REQUEST['page'] ) ) { + return false; + } + + if ( 'pb_catalog' !== $_REQUEST['page'] ) { return false; } - if ( ! empty( $_POST ) ) { + if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } @@ -1032,14 +1030,15 @@ static function isFormSubmission() { */ static function isCurrentAction( $action ) { - if ( isset( $_REQUEST['action'] ) && - 1 != $_REQUEST['action'] ) { + if ( isset( $_REQUEST['action'] ) && -1 !== (int) $_REQUEST['action'] ) { $compare = $_REQUEST['action']; - } else if ( isset( $_REQUEST['action2'] ) && - 1 != $_REQUEST['action2'] ) { + } elseif ( isset( $_REQUEST['action2'] ) && -1 !== (int) $_REQUEST['action2'] ) { $compare = $_REQUEST['action2']; - } else { return false; + } else { + return false; } - return ( $action == $compare ); + return ( $action === $compare ); } @@ -1060,7 +1059,8 @@ static function deleteLogo() { // Delete old images $old_id = \Pressbooks\Image\attachment_id_from_url( $image_url ); - if ( $old_id ) { wp_delete_attachment( $old_id, true ); + if ( $old_id ) { + wp_delete_attachment( $old_id, true ); } update_user_meta( $user_id, 'pb_catalog_logo', \Pressbooks\Image\default_cover_url() ); @@ -1090,12 +1090,10 @@ protected static function formBulk( $action ) { // Bulk check_admin_referer( 'bulk-books' ); // Nonce auto-generated by WP_List_Table $books = $_REQUEST['book']; - } elseif ( ! empty( $_REQUEST['ID'] ) ) { // Single item check_admin_referer( $_REQUEST['ID'] ); - $books = array( $_REQUEST['ID'] ); - + $books = [ $_REQUEST['ID'] ]; } else { // Handle empty bulk submission if ( ! empty( $_REQUEST['user_id'] ) ) { @@ -1112,7 +1110,7 @@ protected static function formBulk( $action ) { } // Fix redirect URL - if ( get_current_user_id() != $user_id ) { + if ( get_current_user_id() !== $user_id ) { $redirect_url .= '&user_id=' . $user_id; } @@ -1122,9 +1120,9 @@ protected static function formBulk( $action ) { foreach ( $books as $book ) { list( $_, $book_id ) = explode( ':', $book ); - if ( 'add' == $action ) { - $catalog->saveBook( $book_id, array() ); - } elseif ( 'remove' == $action ) { + if ( 'add' === $action ) { + $catalog->saveBook( $book_id, [] ); + } elseif ( 'remove' === $action ) { $catalog->deleteBook( $book_id ); } else { // TODO: Throw Error @@ -1149,34 +1147,39 @@ protected static function formTags() { check_admin_referer( 'pb-user-catalog' ); - list( $user_id, $blog_id ) = explode( ':', @$_REQUEST['ID'] ); - if ( ! empty( $_REQUEST['user_id'] ) ) { $user_id = $_REQUEST['user_id']; + if ( ! empty( $_REQUEST['ID'] ) ) { + list( $user_id, $blog_id ) = explode( ':', $_REQUEST['ID'] ); + } else { + $user_id = ''; + $blog_id = ''; + } + if ( ! empty( $_REQUEST['user_id'] ) ) { + $user_id = absint( $_REQUEST['user_id'] ); } - if ( ! empty( $_REQUEST['blog_id'] ) ) { $blog_id = $_REQUEST['blog_id']; + if ( ! empty( $_REQUEST['blog_id'] ) ) { + $blog_id = absint( $_REQUEST['blog_id'] ); } - $user_id = absint( $user_id ); - $blog_id = absint( $blog_id ); if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL - if ( get_current_user_id() != $user_id ) { + if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } /* Go! */ - $catalog = new static( $user_id ); - $catalog->saveBook( $blog_id, array( 'featured' => absint( @$_REQUEST['featured'] ) ) ); + $featured = ( isset( $_REQUEST['featured'] ) ) ? absint( $_REQUEST['featured'] ) : 0; + $catalog->saveBook( $blog_id, [ 'featured' => $featured ] ); // Tags for ( $i = 1; $i <= self::MAX_TAGS_GROUP; ++$i ) { $catalog->deleteTags( $blog_id, $i ); - $tags = ( isset( $_REQUEST[ "tags_$i" ] ) ) ? $_REQUEST[ "tags_$i" ] : array(); + $tags = ( isset( $_REQUEST[ "tags_$i" ] ) ) ? $_REQUEST[ "tags_$i" ] : []; foreach ( $tags as $tag ) { $catalog->saveTag( $tag, $blog_id, $i ); } @@ -1199,15 +1202,14 @@ protected static function formProfile() { check_admin_referer( 'pb-user-catalog' ); - $user_id = @$_REQUEST['user_id']; - $user_id = absint( $user_id ); + $user_id = isset( $_REQUEST['user_id'] ) ? absint( $_REQUEST['user_id'] ) : 0; - if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { + if ( empty( $user_id ) || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL - if ( get_current_user_id() != $user_id ) { + if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); @@ -1240,7 +1242,7 @@ static function formAddByUrl() { $user_id = $catalog->getUserId(); // Set Redirect URL - if ( get_current_user_id() != $user_id ) { + if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); @@ -1254,7 +1256,7 @@ static function formAddByUrl() { \Pressbooks\Redirect\location( $redirect_url ); } - if ( $url['host'] == $main['host'] ) { + if ( $url['host'] === $main['host'] ) { // Get slug using the path $slug = str_replace( $main['path'], '', $url['path'] ); $slug = trim( $slug, '/' ); @@ -1274,12 +1276,7 @@ static function formAddByUrl() { \Pressbooks\Redirect\location( $redirect_url ); } - // if ( ! get_blog_option( $book_id, 'blog_public' ) ) { - // $_SESSION['pb_errors'][] = __( 'Book is not public', 'pressbooks' ); - // \Pressbooks\Redirect\location( $redirect_url ); - // } - - $catalog->saveBook( $book_id, array() ); + $catalog->saveBook( $book_id, [] ); $catalog->deleteCache(); // Ok! @@ -1288,8 +1285,4 @@ static function formAddByUrl() { // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); } - - } - -// @codingStandardsIgnoreEnd diff --git a/includes/class-pb-container.php b/inc/class-container.php similarity index 95% rename from includes/class-pb-container.php rename to inc/class-container.php index 605fc4b8d6..a4bc61e264 100644 --- a/includes/class-pb-container.php +++ b/inc/class-container.php @@ -7,6 +7,7 @@ * PhpStorm IDE to auto-complete things or hot-swap services for Unit Testing. */ class Container { + /** * @var \Pimple\Container */ @@ -29,6 +30,7 @@ static function init( $pimple = null ) { /** * @param string $var + * * @return mixed */ static function get( $var ) { @@ -50,9 +52,9 @@ static function set( $key, $val, $type = null ) { throw new \LogicException( '\Pimple\Container not set, call init() or setPimple() before using set().' ); } - if ( 'factory' == $type ) { + if ( 'factory' === $type ) { static::$pimple[ $key ] = static::$pimple->factory( $val ); - } elseif ( 'protect' == $type ) { + } elseif ( 'protect' === $type ) { static::$pimple[ $key ] = static::$pimple->protect( $val ); } else { static::$pimple[ $key ] = $val; diff --git a/includes/class-pb-customcss.php b/inc/class-customcss.php similarity index 81% rename from includes/class-pb-customcss.php rename to inc/class-customcss.php index 68e2b8c63f..3e264acd78 100644 --- a/includes/class-pb-customcss.php +++ b/inc/class-customcss.php @@ -3,12 +3,11 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; +namespace Pressbooks; class CustomCss { - /** * Supported formats * Array key is slug, array val is text (passed to _e() where necessary.) @@ -18,17 +17,15 @@ class CustomCss { * * @var array */ - public $supported = array( + public $supported = [ 'web' => 'Web', 'epub' => 'Ebook', 'prince' => 'PDF', - ); - + ]; function __construct() { } - /** * Get CSS from database * @@ -47,7 +44,6 @@ function getCss( $slug ) { return $result->post_content; } - /** * Returns the latest "custom-css" post * @@ -62,11 +58,11 @@ function getPost( $slug ) { // Supported post names (ie. slugs) $supported = array_keys( $this->supported ); - if ( ! in_array( $slug, $supported ) ) { + if ( ! in_array( $slug, $supported, true ) ) { return false; } - $args = array( + $args = [ 'name' => $slug, 'post_type' => 'custom-css', 'posts_per_page' => 1, @@ -74,7 +70,7 @@ function getPost( $slug ) { 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, - ); + ]; $q = new \WP_Query(); $results = $q->query( $args ); @@ -110,8 +106,7 @@ static function getCustomCssFolder() { * @return bool */ static function isCustomCss() { - - return ( 'pressbooks-custom-css' == get_stylesheet() ); + return ( 'pressbooks-custom-css' === get_stylesheet() ); } @@ -123,8 +118,10 @@ static function isCustomCss() { static function isRomanized() { $options = get_option( 'pressbooks_theme_options_pdf' ); - - return (bool) ( @$options['pdf_romanize_parts'] ); + if ( isset( $options['pdf_romanize_parts'] ) ) { + return (bool) ( $options['pdf_romanize_parts'] ); + } + return false; } @@ -140,28 +137,27 @@ static function isRomanized() { */ static function formSubmit() { - if ( false == static::isFormSubmission() || false == current_user_can( 'edit_theme_options' ) ) { + if ( empty( static::isFormSubmission() ) || empty( current_user_can( 'edit_theme_options' ) ) ) { // Don't do anything in this function, bail. return; } // Process form - if ( 'yes' == @$_GET['customcss'] && isset( $_POST['my_custom_css'] ) && check_admin_referer( 'pb-custom-css' ) ) { - + if ( isset( $_GET['customcss'] ) && $_GET['customcss'] === 'yes' && isset( $_POST['my_custom_css'] ) && check_admin_referer( 'pb-custom-css' ) ) { $slug = isset( $_POST['slug'] ) ? $_POST['slug'] : 'web'; $redirect_url = get_admin_url( get_current_blog_id(), '/themes.php?page=pb_custom_css&slug=' . $slug ); - if ( md5( NONCE_KEY . @$_POST['post_id'] ) != @$_POST['post_id_integrity'] ) { + if ( isset( $_POST['post_id'] ) && isset( $_POST['post_id_integrity'] ) && md5( NONCE_KEY . $_POST['post_id'] ) !== $_POST['post_id_integrity'] ) { // A hacker trying to overwrite posts?. error_log( '\Pressbooks\CustomCss::formSubmit error: unexpected value for post_id_integrity' ); \Pressbooks\Redirect\location( $redirect_url . '&customcss_error=true' ); } // Write to database - $my_post = array( + $my_post = [ 'ID' => absint( $_POST['post_id'] ), 'post_content' => static::cleanupCss( $_POST['my_custom_css'] ), - ); + ]; $response = wp_update_post( $my_post, true ); if ( is_wp_error( $response ) ) { @@ -192,12 +188,15 @@ static function formSubmit() { */ static function isFormSubmission() { - if ( 'pb_custom_css' != @$_REQUEST['page'] ) { + if ( empty( $_REQUEST['page'] ) ) { return false; } - // @codingStandardsIgnoreLine - if ( ! empty( $_POST ) ) { + if ( 'pb_custom_css' !== $_REQUEST['page'] ) { + return false; + } + + if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } @@ -223,16 +222,16 @@ protected static function cleanupCss( $css ) { $css = preg_replace( '/\\\\([0-9a-fA-F]{2,4})/', '\\\\\\\\$1', $prev = $css ); - if ( $css != $prev ) { + if ( $css !== $prev ) { $warnings[] = 'preg_replace() double escaped unicode escape sequences'; } $css = str_replace( '<=', '<=', $css ); // Some people put weird stuff in their CSS, KSES tends to be greedy - $css = wp_kses_split( $prev = $css, array(), array() ); + $css = wp_kses_split( $prev = $css, [], [] ); $css = str_replace( '>', '>', $css ); // kses replaces lone '>' with > $css = strip_tags( $css ); - if ( $css != $prev ) { + if ( $css !== $prev ) { $warnings[] = 'kses() and strip_tags() do not match'; } @@ -243,6 +242,7 @@ protected static function cleanupCss( $css ) { /** * Determine base theme that was used for the selected Custom CSS. + * * @param $slug string * * @return string @@ -252,8 +252,8 @@ static function getBaseTheme( $slug ) { if ( ! file_exists( $filename ) ) { return false; } - $theme = get_file_data( $filename, array( 'ThemeURI' => 'Theme URI' ) ); - $theme_slug = str_replace( array( 'http://pressbooks.com/themes/', 'https://pressbooks.com/themes/' ), array( '', '' ), $theme['ThemeURI'] ); + $theme = get_file_data( $filename, [ 'ThemeURI' => 'Theme URI' ] ); + $theme_slug = str_replace( [ 'http://pressbooks.com/themes/', 'https://pressbooks.com/themes/' ], [ '', '' ], $theme['ThemeURI'] ); return untrailingslashit( $theme_slug ); } diff --git a/includes/class-pb-globaltypography.php b/inc/class-globaltypography.php similarity index 91% rename from includes/class-pb-globaltypography.php rename to inc/class-globaltypography.php index 8a8baac9b4..e458ff16f9 100644 --- a/includes/class-pb-globaltypography.php +++ b/inc/class-globaltypography.php @@ -5,8 +5,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; +namespace Pressbooks; class GlobalTypography { @@ -16,7 +16,7 @@ class GlobalTypography { * @return array */ function getSupportedLanguages() { - return array( + return [ 'grc' => __( 'Ancient Greek', 'pressbooks' ), 'ar' => __( 'Arabic', 'pressbooks' ), 'he' => __( 'Biblical Hebrew', 'pressbooks' ), @@ -32,7 +32,7 @@ function getSupportedLanguages() { 'ta' => __( 'Tamil', 'pressbooks' ), 'bo' => __( 'Tibetan', 'pressbooks' ), 'tr' => __( 'Turkish', 'pressbooks' ), - ); + ]; } @@ -40,6 +40,7 @@ function getSupportedLanguages() { * Get the current theme's font stacks. * * @param string $type (prince, epub, web ...) + * * @return string */ function getThemeFontStacks( $type ) { @@ -59,9 +60,10 @@ function getThemeFontStacks( $type ) { * Get required languages for this book, excluding those supported by the theme. */ function _getRequiredLanguages() { - $languages = get_option( 'pressbooks_global_typography', array() ); + $languages = get_option( 'pressbooks_global_typography', [] ); + $book_lang = $this->_getBookLanguage(); - if ( $book_lang = $this->_getBookLanguage() ) { + if ( ! empty( $book_lang ) ) { $languages[] = $book_lang; } @@ -188,6 +190,7 @@ function getThemeSupportedLanguages() { /** * @param $type * @param array $languages + * * @return void */ protected function _sassify( $type, array $languages ) { @@ -248,58 +251,58 @@ function getFonts( $languages = null ) { } // List fonts - $fontpacks = array( - 'cans' => array( + $fontpacks = [ + 'cans' => [ 'baseurl' => 'https://github.com/googlei18n/noto-fonts/raw/master/unhinted/', - 'files' => array( + 'files' => [ 'NotoSansCanadianAboriginal-Regular.ttf', - ), - ), - 'hi' => array( + ], + ], + 'hi' => [ 'baseurl' => 'https://github.com/googlei18n/noto-fonts/raw/master/unhinted/', - 'files' => array( + 'files' => [ 'NotoSansDevanagari-Regular.ttf', 'NotoSansDevanagari-Bold.ttf', 'NotoSerifDevanagari-Bold.ttf', 'NotoSerifDevanagari-Regular.ttf', - ), - ), - 'ja' => array( + ], + ], + 'ja' => [ 'baseurl' => 'https://github.com/googlei18n/noto-cjk/raw/master/', - 'files' => array( + 'files' => [ 'NotoSansCJKjp-Light.otf', 'NotoSansCJKjp-Regular.otf', 'NotoSansCJKjp-Bold.otf', - ), - ), - 'ko' => array( + ], + ], + 'ko' => [ 'baseurl' => 'https://github.com/googlei18n/noto-cjk/raw/master/', - 'files' => array( + 'files' => [ 'NotoSansCJKkr-Regular.otf', 'NotoSansCJKkr-Bold.otf', - ), - ), - 'zh_HANS' => array( + ], + ], + 'zh_HANS' => [ 'baseurl' => 'https://github.com/googlei18n/noto-cjk/raw/master/', - 'files' => array( + 'files' => [ 'NotoSansCJKsc-Regular.otf', 'NotoSansCJKsc-Bold.otf', - ), - ), - 'zh_HANT' => array( + ], + ], + 'zh_HANT' => [ 'baseurl' => 'https://github.com/googlei18n/noto-cjk/raw/master/', - 'files' => array( + 'files' => [ 'NotoSansCJKtc-Light.otf', 'NotoSansCJKtc-Regular.otf', 'NotoSansCJKtc-Bold.otf', - ), - ), - ); + ], + ], + ]; $language_names = $this->getSupportedLanguages(); foreach ( $fontpacks as $language => $val ) { - if ( in_array( $language, $languages ) ) { + if ( in_array( $language, $languages, true ) ) { foreach ( $val['files'] as $font ) { if ( ! file_exists( $basepath . $font ) ) { if ( ! function_exists( 'download_url' ) ) { @@ -307,7 +310,7 @@ function getFonts( $languages = null ) { } $result = download_url( $val['baseurl'] . $font ); if ( is_wp_error( $result ) ) { - $_SESSION['pb_errors'][] = sprintf( __( 'Your %1$s font could not be downloaded from %2$s.', 'pressbooks' ), $language_names[ $language ], '' . $baseurl . $font . '' ) . '
' . $result->get_error_message() . '
'; + $_SESSION['pb_errors'][] = sprintf( __( 'Your %1$s font could not be downloaded from %2$s.', 'pressbooks' ), $language_names[ $language ], '' . $val['baseurl'] . $font . '' ) . '
' . $result->get_error_message() . '
'; return false; } else { rename( $result, $basepath . $font ); diff --git a/includes/class-pb-htmlawed.php b/inc/class-htmlawed.php similarity index 78% rename from includes/class-pb-htmlawed.php rename to inc/class-htmlawed.php index 40ee28a9d8..8e5652d810 100644 --- a/includes/class-pb-htmlawed.php +++ b/inc/class-htmlawed.php @@ -6,6 +6,7 @@ * @license GPLv2 (or any later version) * @since 3.9.8.2 */ + namespace Pressbooks; class HtmLawed { @@ -16,10 +17,11 @@ class HtmLawed { * @param string $html * @param int|array $config * @param array|string $spec + * * @return string */ static function filter( $html, array $config = null, $spec = null ) { - require_once( PB_PLUGIN_DIR . 'symbionts/htmLawed/htmLawed.php' ); - return htmLawed( $html, $config, $spec ); + require_once( PB_PLUGIN_DIR . 'symbionts/htmLawed/htmLawed.php' ); + return htmLawed( $html, $config, $spec ); } } diff --git a/includes/class-pb-metadata.php b/inc/class-metadata.php similarity index 83% rename from includes/class-pb-metadata.php rename to inc/class-metadata.php index ed008c4930..037a8b8970 100644 --- a/includes/class-pb-metadata.php +++ b/inc/class-metadata.php @@ -7,12 +7,11 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; +namespace Pressbooks; use Pressbooks\Sanitize; - class Metadata { /** @@ -30,16 +29,15 @@ class Metadata { * * @var array */ - public $upgradeCheckboxes = array( + public $upgradeCheckboxes = [ 'chapter-export' => 1, 'front-matter-export' => 1, 'back-matter-export' => 1, 'show-title' => 1, - ); + ]; function __construct() { - } @@ -50,14 +48,14 @@ function __construct() { */ function getMetaPost() { - $args = array( + $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, - ); + ]; $q = new \WP_Query(); $results = $q->query( $args ); @@ -80,7 +78,7 @@ function getMetaPostMetadata() { $meta_post = $this->getMetaPost(); if ( ! $meta_post ) { - return array(); + return []; } return get_post_meta( $meta_post->ID ); @@ -90,7 +88,7 @@ function getMetaPostMetadata() { /** * Return a database ID for a given meta key. * - * @param int $post_id + * @param int $post_id * @param string $meta_key * * @return int|bool @@ -100,7 +98,7 @@ function getMidByKey( $post_id, $meta_key ) { /** @var \wpdb $wpdb */ global $wpdb; $mid = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s LIMIT 1 ", $post_id, $meta_key ) ); - if ( '' != $mid ) { + if ( ! empty( $mid ) ) { return absint( $mid ); } @@ -115,12 +113,12 @@ function getMidByKey( $post_id, $meta_key ) { */ static function getSeoMetaElements() { // map items that are already captured - $meta_mapping = array( + $meta_mapping = [ 'author' => 'pb_author', 'description' => 'pb_about_50', 'keywords' => 'pb_keywords_tags', 'publisher' => 'pb_publisher', - ); + ]; $html = "\n"; $metadata = Book::getBookInformation(); @@ -142,7 +140,7 @@ static function getSeoMetaElements() { static function getMicrodataElements() { $html = ''; // map items that are already captured - $micro_mapping = array( + $micro_mapping = [ 'about' => 'pb_bisac_subject', 'alternativeHeadline' => 'pb_subtitle', 'author' => 'pb_author', @@ -156,13 +154,13 @@ static function getMicrodataElements() { 'inLanguage' => 'pb_language', 'keywords' => 'pb_keywords_tags', 'publisher' => 'pb_publisher', - ); + ]; $metadata = Book::getBookInformation(); // create microdata elements foreach ( $micro_mapping as $itemprop => $content ) { if ( array_key_exists( $content, $metadata ) ) { - if ( 'pb_publication_date' == $content ) { + if ( 'pb_publication_date' === $content ) { $content = date( 'Y-m-d', (int) $metadata[ $content ] ); } else { $content = $metadata[ $content ]; @@ -181,50 +179,50 @@ static function getMicrodataElements() { * @param string $copyright_holder of the page * @param string $src_url of the page * @param string $title of the page + * * @return string $xml response */ static function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang = '' ) { $endpoint = 'https://api.creativecommons.org/rest/1.5/'; $lang = ( ! empty( $lang ) ) ? substr( $lang, 0, 2 ) : ''; - $expected = array( - 'public-domain' => array( - 'license' => 'zero', - 'commercial' => 'y', - 'derivatives' => 'y', - ), - 'cc-by' => array( - 'license' => 'standard', - 'commercial' => 'y', - 'derivatives' => 'y', - ), - 'cc-by-sa' => array( - 'license' => 'standard', - 'commercial' => 'y', - 'derivatives' => 'sa', - ), - 'cc-by-nd' => array( - 'license' => 'standard', - 'commercial' => 'y', - 'derivatives' => 'n', - ), - 'cc-by-nc' => array( - 'license' => 'standard', - 'commercial' => 'n', - 'derivatives' => 'y', - ), - 'cc-by-nc-sa' => array( - 'license' => 'standard', - 'commercial' => 'n', - 'derivatives' => 'sa', - ), - 'cc-by-nc-nd' => array( - 'license' => 'standard', - 'commercial' => 'n', - 'derivatives' => 'n', - ), - 'all-rights-reserved' => array(), - // 'other' => array(), - ); + $expected = [ + 'public-domain' => [ + 'license' => 'zero', + 'commercial' => 'y', + 'derivatives' => 'y', + ], + 'cc-by' => [ + 'license' => 'standard', + 'commercial' => 'y', + 'derivatives' => 'y', + ], + 'cc-by-sa' => [ + 'license' => 'standard', + 'commercial' => 'y', + 'derivatives' => 'sa', + ], + 'cc-by-nd' => [ + 'license' => 'standard', + 'commercial' => 'y', + 'derivatives' => 'n', + ], + 'cc-by-nc' => [ + 'license' => 'standard', + 'commercial' => 'n', + 'derivatives' => 'y', + ], + 'cc-by-nc-sa' => [ + 'license' => 'standard', + 'commercial' => 'n', + 'derivatives' => 'sa', + ], + 'cc-by-nc-nd' => [ + 'license' => 'standard', + 'commercial' => 'n', + 'derivatives' => 'n', + ], + 'all-rights-reserved' => [], + ]; // nothing meaningful to hit the api with, so bail if ( ! array_key_exists( $type, $expected ) ) { @@ -235,14 +233,9 @@ static function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang // api doesn't have an 'all-rights-reserved' endpoint, so manual build necessary case 'all-rights-reserved': $xml = '' - . "" . Sanitize\sanitize_xml_attribute( $title ) . ' © ' - . Sanitize\sanitize_xml_attribute( $copyright_holder ) . '. ' . __( 'All Rights Reserved', 'pressbooks' ) . '.'; + . "" . Sanitize\sanitize_xml_attribute( $title ) . ' © ' + . Sanitize\sanitize_xml_attribute( $copyright_holder ) . '. ' . __( 'All Rights Reserved', 'pressbooks' ) . '.'; break; - - // case 'other': - // //@TODO - // break; - default: $key = array_keys( $expected[ $type ] ); @@ -250,13 +243,13 @@ static function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang // build the url $url = $endpoint . $key[0] . '/' . $val[0] . '/get?' . $key[1] . '=' . $val[1] . '&' . $key[2] . '=' . $val[2] . - '&creator=' . urlencode( $copyright_holder ) . '&attribution_url=' . urlencode( $src_url ) . '&title=' . urlencode( $title ) . '&locale=' . $lang ; + '&creator=' . urlencode( $copyright_holder ) . '&attribution_url=' . urlencode( $src_url ) . '&title=' . urlencode( $title ) . '&locale=' . $lang; $xml = wp_remote_get( $url ); $ok = wp_remote_retrieve_response_code( $xml ); // if server response is not ok - if ( 200 != $ok ) { + if ( 200 !== absint( $ok ) ) { return ''; } @@ -279,6 +272,7 @@ static function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang * Returns an HTML blob if given an XML object * * @param \SimpleXMLElement $response + * * @return string $html blob of copyright information */ static function getWebLicenseHtml( \SimpleXMLElement $response ) { @@ -286,7 +280,7 @@ static function getWebLicenseHtml( \SimpleXMLElement $response ) { if ( is_object( $response ) ) { $content = $response->asXML(); - $content = trim( str_replace( array( '

', '

', '', '' ), array( '', '', '', '' ), $content ) ); + $content = trim( str_replace( [ '

', '

', '', '' ], [ '', '', '', '' ], $content ) ); $content = preg_replace( '/http:\/\/i.creativecommons/iU', 'https://i.creativecommons', $content ); $html = '

' . rtrim( $content, '.' ) . ', ' . __( 'except where otherwise noted.', 'pressbooks' ) . '

'; @@ -333,7 +327,7 @@ function upgrade( $version ) { if ( $version < 5 ) { $this->changeDefaultBookCover(); } - if ( $version < 6 ||$version < 7 ) { + if ( $version < 6 || $version < 7 ) { $this->makeThumbnailsForBookCover(); } if ( $version < 8 ) { @@ -353,11 +347,11 @@ function upgradeEcommerce() { $options = get_option( 'ecomm-url' ); $compare = $this->getDeprecatedComparisonTable( 'ecommerce' ); - $new_options = array(); + $new_options = []; if ( $options ) { foreach ( $options as $meta_key => $meta_value ) { - $new_meta_key = @$compare[ $meta_key ]; + $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $new_options[ $new_meta_key ] = $meta_value; } @@ -385,7 +379,7 @@ function upgradeBookInformation() { $compare = $this->getDeprecatedComparisonTable( 'metadata' ); foreach ( $metadata as $meta_key => $meta_value ) { - $new_meta_key = @$compare[ $meta_key ]; + $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $meta_post->ID, $meta_key ); if ( $meta_id ) { @@ -397,14 +391,14 @@ function upgradeBookInformation() { } // Overrides - if ( 'pb_language' == $new_meta_key ) { + if ( 'pb_language' === $new_meta_key ) { $meta_value = substr( strtolower( $meta_value ), 0, 2 ); } - if ( 'pb_publication_date' == $new_meta_key ) { + if ( 'pb_publication_date' === $new_meta_key ) { $meta_value = strtotime( $meta_value ); } - // Updating [$meta_key] to [$new_meta_key] + // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } @@ -426,7 +420,7 @@ function upgradeBook() { $compare = $this->getDeprecatedComparisonTable( get_post_type( $post_id ) ); foreach ( $meta as $meta_key => $meta_value ) { - $new_meta_key = @$compare[ $meta_key ]; + $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $post_id, $meta_key ); if ( $meta_id ) { @@ -436,7 +430,7 @@ function upgradeBook() { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } - // Updating [$meta_key] to [$new_meta_key] + // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } @@ -455,53 +449,43 @@ function upgradeBook() { * @return array */ function getDeprecatedComparisonTable( $table, $new_as_keys = false ) { - - if ( 'chapter' == $table ) { - + if ( 'chapter' === $table ) { // Chapter - $metadata = array( + $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'chapter-export' => 'pb_export', 'show-title' => 'pb_show_title', - ); - - } elseif ( 'front-matter' == $table ) { - + ]; + } elseif ( 'front-matter' === $table ) { // Front Matter - $metadata = array( + $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'front-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', - ); - - } elseif ( 'back-matter' == $table ) { - + ]; + } elseif ( 'back-matter' === $table ) { // Back Matter - $metadata = array( + $metadata = [ 'back-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', - ); - - } elseif ( 'ecommerce' == $table ) { - + ]; + } elseif ( 'ecommerce' === $table ) { // Ecommerce - $metadata = array( + $metadata = [ 'url1' => 'amazon', 'url2' => 'oreilly', 'url3' => 'barnesandnoble', 'url4' => 'kobo', 'url5' => 'ibooks', 'url6' => 'otherservice', - ); - - } elseif ( 'metadata' == $table ) { - + ]; + } elseif ( 'metadata' === $table ) { // Book Information - $metadata = array( + $metadata = [ 'Title' => 'pb_title', 'Short Title' => 'pb_short_title', 'Subtitle' => 'pb_subtitle', @@ -533,10 +517,9 @@ function getDeprecatedComparisonTable( $table, $new_as_keys = false ) { 'Bisac Subject 1' => 'pb_bisac_subject', 'Bisac Regional Theme' => 'pb_bisac_regional_theme', 'catalogue_order' => 'pb_catalogue_order', - ); - + ]; } else { - $metadata = array(); + $metadata = []; } if ( $new_as_keys ) { @@ -557,28 +540,33 @@ function upgradeCustomCss() { /** @var $wpdb \wpdb */ global $wpdb; - $posts = array( - array( + $posts = [ + [ 'post_title' => __( 'Custom CSS for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-css', - ), - array( + ], + [ 'post_title' => __( 'Custom CSS for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-css', - ), - array( + ], + [ 'post_title' => __( 'Custom CSS for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-css', - ), - ); + ], + ]; - $post = array( 'post_status' => 'publish', 'post_author' => wp_get_current_user()->ID ); + $post = [ 'post_status' => 'publish', 'post_author' => wp_get_current_user()->ID ]; foreach ( $posts as $item ) { - $exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", array( $item['post_title'], $item['post_type'], $item['post_name'] ) ) ); + $exists = $wpdb->get_var( + $wpdb->prepare( + "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", + [ $item['post_title'], $item['post_type'], $item['post_name'] ] + ) + ); if ( empty( $exists ) ) { $data = array_merge( $item, $post ); wp_insert_post( $data ); @@ -637,12 +625,12 @@ function makeThumbnailsForBookCover() { $type = $type['type']; // Insert new image, create thumbnails - $args = array( + $args = [ 'post_mime_type' => $type, 'post_title' => __( 'Cover Image', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', - ); + ]; include_once( ABSPATH . 'wp-admin/includes/image.php' ); $id = wp_insert_attachment( $args, $path, $post->ID ); diff --git a/includes/class-pb-options.php b/inc/class-options.php similarity index 75% rename from includes/class-pb-options.php rename to inc/class-options.php index 3f29f272b2..1b2ba2a2b8 100644 --- a/includes/class-pb-options.php +++ b/inc/class-options.php @@ -6,6 +6,14 @@ namespace Pressbooks; +/** + * @property array booleans + * @property array strings + * @property array urls + * @property array integers + * @property array floats + * @property array predefined + */ abstract class Options { /** @@ -24,7 +32,7 @@ abstract function display(); abstract function render(); /** - * Upgrade handler for the options page or tab. + * Upgrade handler for the options page or tab. * * @param int $version */ @@ -55,26 +63,28 @@ abstract static function getDefaults(); * Filter the array of default values for this set of options * * @param array $defaults + * * @return array $defaults */ abstract static function filterDefaults( $defaults ); /** - * Sanitize various options (boolean, string, integer, float). - * - * @param array $input + * Sanitize various options (boolean, string, integer, float). + * + * @param array $input + * * @return array $options - */ + */ function sanitize( $input ) { - $options = array(); + $options = []; if ( ! is_array( $input ) ) { - $input = array(); + $input = []; } if ( property_exists( $this, 'booleans' ) ) { foreach ( $this->booleans as $key ) { - if ( ! isset( $input[ $key ] ) || 1 != @$input[ $key ] ) { + if ( ! isset( $input[ $key ] ) || empty( $input[ $key ] ) ) { $options[ $key ] = 0; } else { $options[ $key ] = 1; @@ -146,19 +156,19 @@ function sanitize( $input ) { * @param array $args { * Arguments to render the input. * - * @type string $id The id which will be assigned to the rendered field. - * @type string $name The name of the field. - * @type string $option The name of the option that the field is within. - * @type string $value The stored value of the field as retrieved from the database. - * @type string $description A description which will be displayed below the field. - * @type string $append A string which will be appended to the field (e.g. 'px'). - * @type string $type The type property of the input. Default 'text'. - * @type string $class The class(es) which will be assigned to the rendered input. Default 'regular-text'. - * @type bool $disabled Is the field disabled? - * } + * @type string $id The id which will be assigned to the rendered field. + * @type string $name The name of the field. + * @type string $option The name of the option that the field is within. + * @type string $value The stored value of the field as retrieved from the database. + * @type string $description A description which will be displayed below the field. + * @type string $append A string which will be appended to the field (e.g. 'px'). + * @type string $type The type property of the input. Default 'text'. + * @type string $class The class(es) which will be assigned to the rendered input. Default 'regular-text'. + * @type bool $disabled Is the field disabled? + * } */ static function renderField( $args ) { - $defaults = array( + $defaults = [ 'id' => null, 'name' => null, 'option' => null, @@ -168,7 +178,7 @@ static function renderField( $args ) { 'type' => 'text', 'class' => 'regular-text', 'disabled' => false, - ); + ]; $args = wp_parse_args( $args, $defaults ); @@ -180,7 +190,7 @@ static function renderField( $args ) { $args['option'], $args['type'], $args['value'], - ( isset( $args['disabled'] ) && true == $args['disabled'] ) ? ' disabled' : '' + ( isset( $args['disabled'] ) && ! empty( $args['disabled'] ) ) ? ' disabled' : '' ); if ( isset( $args['append'] ) ) { echo ' ' . $args['append']; @@ -199,7 +209,7 @@ static function renderField( $args ) { * @param array $args */ static function renderCheckbox( $args ) { - $defaults = array( + $defaults = [ 'id' => null, 'name' => null, 'option' => null, @@ -207,7 +217,7 @@ static function renderCheckbox( $args ) { 'label' => null, 'disabled' => false, 'description' => null, - ); + ]; $args = wp_parse_args( $args, $defaults ); @@ -217,7 +227,7 @@ static function renderCheckbox( $args ) { $args['name'], $args['option'], checked( 1, $args['value'], false ), - ( isset( $args['disabled'] ) && true == $args['disabled'] ) ? ' disabled' : '', + ( isset( $args['disabled'] ) && ! empty( $args['disabled'] ) ) ? ' disabled' : '', $args['id'], $args['label'] ); @@ -235,15 +245,15 @@ static function renderCheckbox( $args ) { * @param array $args */ static function renderRadioButtons( $args ) { - $defaults = array( + $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', - 'choices' => array(), + 'choices' => [], 'custom' => false, 'disabled' => false, - ); + ]; $args = wp_parse_args( $args, $defaults ); @@ -259,8 +269,8 @@ static function renderRadioButtons( $args ) { $args['name'], $args['option'], $key, - ( $args['custom'] && $is_custom && '' == $key ) ? 'checked' : checked( $key, $args['value'], false ), - ( isset( $args['disabled'] ) && true == $args['disabled'] ) ? ' disabled' : '', + ( $args['custom'] && $is_custom && empty( $key ) ) ? 'checked' : checked( $key, $args['value'], false ), + ( isset( $args['disabled'] ) && ! empty( $args['disabled'] ) ) ? ' disabled' : '', $label ); } @@ -272,15 +282,15 @@ static function renderRadioButtons( $args ) { * @param array $args */ static function renderSelect( $args ) { - $defaults = array( + $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', - 'choices' => array(), + 'choices' => [], 'multiple' => false, 'disabled' => false, - ); + ]; $args = wp_parse_args( $args, $defaults ); @@ -294,12 +304,12 @@ static function renderSelect( $args ) { ); } printf( - '', + '', $args['name'], $args['option'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', - ( isset( $args['disabled'] ) && true == $args['disabled'] ) ? ' disabled' : '', + ( isset( $args['disabled'] ) && ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); } @@ -310,14 +320,14 @@ static function renderSelect( $args ) { * @param array $args */ static function renderCustomSelect( $args ) { - $defaults = array( + $defaults = [ 'id' => null, 'name' => null, 'value' => '', - 'choices' => array(), + 'choices' => [], 'multiple' => false, 'disabled' => false, - ); + ]; $args = wp_parse_args( $args, $defaults ); @@ -330,16 +340,16 @@ static function renderCustomSelect( $args ) { $options .= sprintf( '', $key, - ( '' == $key && $is_custom ) ? ' selected' : selected( $key, $args['value'], false ), + ( empty( $key ) && $is_custom ) ? ' selected' : selected( $key, $args['value'], false ), $label ); } printf( - '
', + '
', $args['name'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', - ( isset( $args['disabled'] ) && true == $args['disabled'] ) ? ' disabled' : '', + ( isset( $args['disabled'] ) && ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); } diff --git a/includes/class-pb-pressbooks.php b/inc/class-pressbooks.php similarity index 83% rename from includes/class-pb-pressbooks.php rename to inc/class-pressbooks.php index 40335c5e79..12d4b1372b 100644 --- a/includes/class-pb-pressbooks.php +++ b/inc/class-pressbooks.php @@ -3,9 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; - +namespace Pressbooks; class Pressbooks { @@ -18,7 +17,7 @@ function __construct() { * Memcached Object Cache v2.0.2 doesn't like when we loop on switch_to_blog() * We "fix" this by storing our cached items in global group 'pb' */ - wp_cache_add_global_groups( array( 'pb' ) ); + wp_cache_add_global_groups( [ 'pb' ] ); $this->registerThemeDirectories(); @@ -32,7 +31,7 @@ function __construct() { function registerThemeDirectories() { // No trailing slash, otherwise we get a double slash bug - // @see \Pressbooks\Metadata::fixDoubleSlashBug + // See \Pressbooks\Metadata::fixDoubleSlashBug register_theme_directory( PB_PLUGIN_DIR . 'themes-root' ); register_theme_directory( PB_PLUGIN_DIR . 'themes-book' ); @@ -48,9 +47,9 @@ function registerThemeDirectories() { if ( is_admin() ) { if ( Book::isBook() ) { - add_filter( 'allowed_themes', array( $this, 'allowedBookThemes' ) ); + add_filter( 'allowed_themes', [ $this, 'allowedBookThemes' ] ); } elseif ( ! is_network_admin() ) { - add_filter( 'allowed_themes', array( $this, 'allowedRootThemes' ) ); + add_filter( 'allowed_themes', [ $this, 'allowedRootThemes' ] ); } } } @@ -71,7 +70,7 @@ function allowedBookThemes( $themes ) { $stylesheet = str_replace( 'style.css', '', $val['theme_file'] ); $theme = wp_get_theme( $stylesheet, $val['theme_root'] ); // Hide any available non-book themes, as identified by checking to see if they are either pressbooks-book or a child theme of pressbooks-book. - if ( 'pressbooks-book/style.css' != $val['theme_file'] && 'pressbooks-book' != $theme->get( 'Template' ) ) { + if ( 'pressbooks-book/style.css' !== $val['theme_file'] && 'pressbooks-book' !== $theme->get( 'Template' ) ) { unset( $themes[ $key ] ); } } @@ -94,7 +93,7 @@ function allowedRootThemes( $themes ) { $stylesheet = str_replace( 'style.css', '', $val['theme_file'] ); $theme = wp_get_theme( $stylesheet, $val['theme_root'] ); // Hide any available book themes, as identified by checking to see if they are either pressbooks-book or a child theme of pressbooks-book. - if ( 'pressbooks-book/style.css' == $val['theme_file'] || 'pressbooks-book' == $theme->get( 'Template' ) ) { + if ( 'pressbooks-book/style.css' === $val['theme_file'] || 'pressbooks-book' === $theme->get( 'Template' ) ) { unset( $themes[ $key ] ); } } diff --git a/includes/class-pb-sass.php b/inc/class-sass.php similarity index 85% rename from includes/class-pb-sass.php rename to inc/class-sass.php index 79befa36ac..76966c2582 100644 --- a/includes/class-pb-sass.php +++ b/inc/class-sass.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; +namespace Pressbooks; class Sass { @@ -13,19 +13,22 @@ class Sass { * * @var array */ - public $errorsEmail = array( + public $errorsEmail = [ 'errors@pressbooks.com', - ); + ]; /** * Get default include paths * * @param string $type + * @param string $theme + * + * @return array */ function defaultIncludePaths( $type, $theme = null ) { - if ( null == $theme ) { + if ( null === $theme ) { $theme = wp_get_theme(); } @@ -115,7 +118,6 @@ function urlToUserGeneratedCss() { } - /** * Get path to a directory we can dump user generated Sass files into (create dir if it does not exist) * @@ -157,9 +159,10 @@ function pathToDebugDir() { * * @param string $scss * @param array $includes (optional) + * * @return string */ - function compile( $scss, $includes = array() ) { + function compile( $scss, $includes = [] ) { $scss = $this->prependLocalizedVars( $scss ); @@ -194,6 +197,7 @@ function compile( $scss, $includes = array() ) { * Prepend localized version of content string variables. * * @param string $scss + * * @return string */ function prependLocalizedVars( $scss ) { @@ -215,17 +219,21 @@ function prependLocalizedVars( $scss ) { * Parse an SCSS file into an array of variables. * * @param string $scss + * * @return array */ function parseVariables( $scss ) { preg_match_all( '/\$(.*?):(.*?);/', $scss, $matches ); $output = array_combine( $matches[1], $matches[2] ); - $output = array_map( function( $val ) { - return ltrim( str_replace( ' !default', '', $val ) ); - }, $output ); + $output = array_map( + function ( $val ) { + return ltrim( str_replace( ' !default', '', $val ) ); + }, $output + ); return $output; } + /** * Log Exceptions * @@ -238,19 +246,19 @@ protected function logException( \Exception $e ) { /** $var \WP_User $current_user */ global $current_user; - $info = array( + $info = [ 'time' => strftime( '%c' ), 'user' => ( isset( $current_user ) ? $current_user->user_login : '__UNKNOWN__' ), 'site_url' => site_url(), 'blog_id' => get_current_blog_id(), - 'Exception' => array( + 'Exception' => [ 'code' => $e->getCode(), 'error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), - ), - ); + ], + ]; $message = print_r( array_merge( $info ), true ); @@ -266,6 +274,8 @@ protected function logException( \Exception $e ) { * Write CSS to a a debug dir * * @param string $css + * @param string $scss + * @param string $filename * * @param string $filename */ @@ -285,31 +295,33 @@ function debug( $css, $scss, $filename ) { * Are the current theme's stylesheets SCSS compatible? * * @param int $version + * @param string $theme * * @return bool */ function isCurrentThemeCompatible( $version = 1, $theme = null ) { - if ( null == $theme ) { + if ( null === $theme ) { $theme = wp_get_theme(); } $basepath = apply_filters( 'pb_stylesheet_directory', $theme->get_stylesheet_directory() ); - $types = array( - 'prince', - 'epub', - 'web', - ); + $types = [ + 'prince', + 'epub', + 'web', + ]; foreach ( $types as $type ) { - if ( 1 == $version && 'web' !== $type ) { + $path = ''; + if ( 1 === $version && 'web' !== $type ) { $path = $basepath . "/export/$type/style.scss"; - } elseif ( 1 == $version && 'web' == $type ) { + } elseif ( 1 === $version && 'web' === $type ) { $path = $basepath . '/style.scss'; } - if ( 2 == $version ) { + if ( 2 === $version ) { $path = $basepath . "/assets/styles/$type/style.scss"; } @@ -360,12 +372,14 @@ function updateWebBookStyleSheet() { $scss .= $this->applyOverrides( file_get_contents( $path_to_style ), $overrides ); $scss .= "\n"; - $css = $this->compile( $scss, [ - $this->pathToUserGeneratedSass(), - $this->pathToPartials(), - $this->pathToFonts(), - get_stylesheet_directory(), - ] ); + $css = $this->compile( + $scss, [ + $this->pathToUserGeneratedSass(), + $this->pathToPartials(), + $this->pathToFonts(), + get_stylesheet_directory(), + ] + ); } elseif ( $this->isCurrentThemeCompatible( 2 ) ) { $path_to_style = realpath( get_stylesheet_directory() . '/assets/styles/web/style.scss' ); @@ -389,30 +403,32 @@ function updateWebBookStyleSheet() { * Fix relative/ambiguous URLs to web fonts * * @param $css + * * @return mixed */ function fixWebFonts( $css ) { - // Search for url("*"), url('*'), and url(*) + // Search for all possible permutations of CSS url syntax: url("*"), url('*'), and url(*) $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; - $css = preg_replace_callback( $url_regex, function ( $matches ) { + $css = preg_replace_callback( + $url_regex, function ( $matches ) { - $url = $matches[3]; - $filename = sanitize_file_name( basename( $url ) ); + $url = $matches[3]; - // Look for themes-book/pressbooks-book/fonts/*.otf (or .woff, or .ttf), update URL - if ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { - return 'url(' . PB_PLUGIN_URL . $url . ')'; - } + // Look for themes-book/pressbooks-book/fonts/*.otf (or .woff, or .ttf), update URL + if ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { + return 'url(' . PB_PLUGIN_URL . $url . ')'; + } - // Look for uploads/assets/fonts/*.otf (or .woff, or .ttf), update URL - if ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { - return 'url(' . WP_CONTENT_URL . '/' . $url . ')'; - } + // Look for uploads/assets/fonts/*.otf (or .woff, or .ttf), update URL + if ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { + return 'url(' . WP_CONTENT_URL . '/' . $url . ')'; + } - return $matches[0]; // No change + return $matches[0]; // No change - }, $css ); + }, $css + ); return $css; } diff --git a/includes/class-pb-taxonomy.php b/inc/class-taxonomy.php similarity index 62% rename from includes/class-pb-taxonomy.php rename to inc/class-taxonomy.php index 9a1e4c46d9..a26a300f24 100644 --- a/includes/class-pb-taxonomy.php +++ b/inc/class-taxonomy.php @@ -7,6 +7,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks; class Taxonomy { @@ -19,7 +20,8 @@ class Taxonomy { */ const VERSION = 1; - function __construct() {} + function __construct() { + } /** * Create a custom taxonomy for Chapter, Front Matter and Back Matter post types @@ -28,7 +30,7 @@ static function registerTaxonomies() { /* Front Matter Type */ - $labels = array( + $labels = [ 'name' => _x( 'Front Matter Types', 'taxonomy general name' ), 'singular_name' => _x( 'Front Matter Type', 'taxonomy singular name' ), 'search_items' => __( 'Search Front Matter Types', 'pressbooks' ), @@ -44,31 +46,31 @@ static function registerTaxonomies() { 'add_or_remove_items' => __( 'Add or remove front matter type', 'pressbooks' ), 'choose_from_most_used' => __( 'Choose from the most used front matter type', 'pressbooks' ), 'menu_name' => __( 'Front Matter Types', 'pressbooks' ), - ); + ]; // can only apply front matter taxonomy to front matter post type register_taxonomy( 'front-matter-type', 'front-matter', - array( + [ 'hierarchical' => true, // only super-admins can change front matter terms - 'capabilities' => array( + 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', - ), + ], 'labels' => $labels, 'show_ui' => true, 'query_var' => true, - 'rewrite' => array( 'slug' => 'front-matter-type' ), - ) + 'rewrite' => [ 'slug' => 'front-matter-type' ], + ] ); /* Back Matter Type */ - $labels = array( + $labels = [ 'name' => _x( 'Back Matter Types', 'taxonomy general name' ), 'singular_name' => _x( 'Back Matter Type', 'taxonomy singular name' ), 'search_items' => __( 'Search Back Matter Types', 'pressbooks' ), @@ -84,31 +86,31 @@ static function registerTaxonomies() { 'add_or_remove_items' => __( 'Add or remove back matter type', 'pressbooks' ), 'choose_from_most_used' => __( 'Choose from the most used back matter type', 'pressbooks' ), 'menu_name' => __( 'Back Matter Types', 'pressbooks' ), - ); + ]; // can only apply back matter taxonomy to back matter post type register_taxonomy( 'back-matter-type', 'back-matter', - array( + [ 'hierarchical' => true, // only super-admins can change back matter terms - 'capabilities' => array( + 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', - ), + ], 'labels' => $labels, 'show_ui' => true, 'query_var' => true, - 'rewrite' => array( 'slug' => 'back-matter-type' ), - ) + 'rewrite' => [ 'slug' => 'back-matter-type' ], + ] ); /* Chapter Type */ - $labels = array( + $labels = [ 'name' => _x( 'Chapter Types', 'taxonomy general name' ), 'singular_name' => _x( 'Chapter Type', 'taxonomy singular name' ), 'search_items' => __( 'Search Chapter Types', 'pressbooks' ), @@ -124,26 +126,26 @@ static function registerTaxonomies() { 'add_or_remove_items' => __( 'Add or remove chapter type', 'pressbooks' ), 'choose_from_most_used' => __( 'Choose from the most used chapter type', 'pressbooks' ), 'menu_name' => __( 'Chapter Types', 'pressbooks' ), - ); + ]; // can only apply chapter taxonomy to chapter post type register_taxonomy( 'chapter-type', 'chapter', - array( + [ 'hierarchical' => true, // only super-admins can change chapter terms - 'capabilities' => array( + 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', - ), + ], 'labels' => $labels, 'show_ui' => true, 'query_var' => true, - 'rewrite' => array( 'slug' => 'chapter-type' ), - ) + 'rewrite' => [ 'slug' => 'chapter-type' ], + ] ); } @@ -153,57 +155,57 @@ static function registerTaxonomies() { static function insertTerms() { // Front Matter - wp_insert_term( 'Abstract', 'front-matter-type', array( 'slug' => 'abstracts' ) ); - wp_insert_term( 'Acknowledgements', 'front-matter-type', array( 'slug' => 'acknowledgements' ) ); - wp_insert_term( 'Before Title Page', 'front-matter-type', array( 'slug' => 'before-title' ) ); - wp_insert_term( 'Chronology, Timeline', 'front-matter-type', array( 'slug' => 'chronology-timeline' ) ); - wp_insert_term( 'Dedication', 'front-matter-type', array( 'slug' => 'dedication' ) ); - wp_insert_term( 'Disclaimer', 'front-matter-type', array( 'slug' => 'disclaimer' ) ); - wp_insert_term( 'Epigraph', 'front-matter-type', array( 'slug' => 'epigraph' ) ); - wp_insert_term( 'Foreword', 'front-matter-type', array( 'slug' => 'foreword' ) ); - wp_insert_term( 'Genealogy, Family Tree', 'front-matter-type', array( 'slug' => 'genealogy-family-tree' ) ); - wp_insert_term( 'Image credits', 'front-matter-type', array( 'slug' => 'image-credits' ) ); - wp_insert_term( 'Introduction', 'front-matter-type', array( 'slug' => 'introduction' ) ); - wp_insert_term( 'List of Abbreviations', 'front-matter-type', array( 'slug' => 'list-of-abbreviations' ) ); - wp_insert_term( 'List of Characters', 'front-matter-type', array( 'slug' => 'list-of-characters' ) ); - wp_insert_term( 'List of Illustrations', 'front-matter-type', array( 'slug' => 'list-of-illustrations' ) ); - wp_insert_term( 'List of Tables', 'front-matter-type', array( 'slug' => 'list-of-tables' ) ); - wp_insert_term( 'Miscellaneous', 'front-matter-type', array( 'slug' => 'miscellaneous' ) ); - wp_insert_term( 'Other Books by Author', 'front-matter-type', array( 'slug' => 'other-books' ) ); - wp_insert_term( 'Preface', 'front-matter-type', array( 'slug' => 'preface' ) ); - wp_insert_term( 'Prologue', 'front-matter-type', array( 'slug' => 'prologue' ) ); - wp_insert_term( 'Recommended citation', 'front-matter-type', array( 'slug' => 'recommended-citation' ) ); - wp_insert_term( 'Title Page', 'front-matter-type', array( 'slug' => 'title-page' ) ); + wp_insert_term( 'Abstract', 'front-matter-type', [ 'slug' => 'abstracts' ] ); + wp_insert_term( 'Acknowledgements', 'front-matter-type', [ 'slug' => 'acknowledgements' ] ); + wp_insert_term( 'Before Title Page', 'front-matter-type', [ 'slug' => 'before-title' ] ); + wp_insert_term( 'Chronology, Timeline', 'front-matter-type', [ 'slug' => 'chronology-timeline' ] ); + wp_insert_term( 'Dedication', 'front-matter-type', [ 'slug' => 'dedication' ] ); + wp_insert_term( 'Disclaimer', 'front-matter-type', [ 'slug' => 'disclaimer' ] ); + wp_insert_term( 'Epigraph', 'front-matter-type', [ 'slug' => 'epigraph' ] ); + wp_insert_term( 'Foreword', 'front-matter-type', [ 'slug' => 'foreword' ] ); + wp_insert_term( 'Genealogy, Family Tree', 'front-matter-type', [ 'slug' => 'genealogy-family-tree' ] ); + wp_insert_term( 'Image credits', 'front-matter-type', [ 'slug' => 'image-credits' ] ); + wp_insert_term( 'Introduction', 'front-matter-type', [ 'slug' => 'introduction' ] ); + wp_insert_term( 'List of Abbreviations', 'front-matter-type', [ 'slug' => 'list-of-abbreviations' ] ); + wp_insert_term( 'List of Characters', 'front-matter-type', [ 'slug' => 'list-of-characters' ] ); + wp_insert_term( 'List of Illustrations', 'front-matter-type', [ 'slug' => 'list-of-illustrations' ] ); + wp_insert_term( 'List of Tables', 'front-matter-type', [ 'slug' => 'list-of-tables' ] ); + wp_insert_term( 'Miscellaneous', 'front-matter-type', [ 'slug' => 'miscellaneous' ] ); + wp_insert_term( 'Other Books by Author', 'front-matter-type', [ 'slug' => 'other-books' ] ); + wp_insert_term( 'Preface', 'front-matter-type', [ 'slug' => 'preface' ] ); + wp_insert_term( 'Prologue', 'front-matter-type', [ 'slug' => 'prologue' ] ); + wp_insert_term( 'Recommended citation', 'front-matter-type', [ 'slug' => 'recommended-citation' ] ); + wp_insert_term( 'Title Page', 'front-matter-type', [ 'slug' => 'title-page' ] ); // Back Matter - wp_insert_term( 'About the Author', 'back-matter-type', array( 'slug' => 'about-the-author' ) ); - wp_insert_term( 'About the Publisher', 'back-matter-type', array( 'slug' => 'about-the-publisher' ) ); - wp_insert_term( 'Acknowledgements', 'back-matter-type', array( 'slug' => 'acknowledgements' ) ); - wp_insert_term( 'Afterword', 'back-matter-type', array( 'slug' => 'afterword' ) ); - wp_insert_term( 'Appendix', 'back-matter-type', array( 'slug' => 'appendix' ) ); - wp_insert_term( "Author's Note", 'back-matter-type', array( 'slug' => 'authors-note' ) ); - wp_insert_term( 'Back of Book Ad', 'back-matter-type', array( 'slug' => 'back-of-book-ad' ) ); - wp_insert_term( 'Bibliography', 'back-matter-type', array( 'slug' => 'bibliography' ) ); - wp_insert_term( 'Biographical Note', 'back-matter-type', array( 'slug' => 'biographical-note' ) ); - wp_insert_term( 'Colophon', 'back-matter-type', array( 'slug' => 'colophon' ) ); - wp_insert_term( 'Conclusion', 'back-matter-type', array( 'slug' => 'conclusion' ) ); - wp_insert_term( 'Credits', 'back-matter-type', array( 'slug' => 'credits' ) ); - wp_insert_term( 'Dedication', 'back-matter-type', array( 'slug' => 'dedication' ) ); - wp_insert_term( 'Epilogue', 'back-matter-type', array( 'slug' => 'epilogue' ) ); - wp_insert_term( 'Glossary', 'back-matter-type', array( 'slug' => 'glossary' ) ); - wp_insert_term( 'Index', 'back-matter-type', array( 'slug' => 'index' ) ); - wp_insert_term( 'Miscellaneous', 'back-matter-type', array( 'slug' => 'miscellaneous' ) ); - wp_insert_term( 'Notes', 'back-matter-type', array( 'slug' => 'notes' ) ); - wp_insert_term( 'Other Books by Author', 'back-matter-type', array( 'slug' => 'other-books' ) ); - wp_insert_term( 'Permissions', 'back-matter-type', array( 'slug' => 'permissions' ) ); - wp_insert_term( 'Reading Group Guide', 'back-matter-type', array( 'slug' => 'reading-group-guide' ) ); - wp_insert_term( 'Resources', 'back-matter-type', array( 'slug', 'resources' ) ); - wp_insert_term( 'Sources', 'back-matter-type', array( 'slug' => 'sources' ) ); - wp_insert_term( 'Suggested Reading', 'back-matter-type', array( 'slug' => 'suggested-reading' ) ); + wp_insert_term( 'About the Author', 'back-matter-type', [ 'slug' => 'about-the-author' ] ); + wp_insert_term( 'About the Publisher', 'back-matter-type', [ 'slug' => 'about-the-publisher' ] ); + wp_insert_term( 'Acknowledgements', 'back-matter-type', [ 'slug' => 'acknowledgements' ] ); + wp_insert_term( 'Afterword', 'back-matter-type', [ 'slug' => 'afterword' ] ); + wp_insert_term( 'Appendix', 'back-matter-type', [ 'slug' => 'appendix' ] ); + wp_insert_term( "Author's Note", 'back-matter-type', [ 'slug' => 'authors-note' ] ); + wp_insert_term( 'Back of Book Ad', 'back-matter-type', [ 'slug' => 'back-of-book-ad' ] ); + wp_insert_term( 'Bibliography', 'back-matter-type', [ 'slug' => 'bibliography' ] ); + wp_insert_term( 'Biographical Note', 'back-matter-type', [ 'slug' => 'biographical-note' ] ); + wp_insert_term( 'Colophon', 'back-matter-type', [ 'slug' => 'colophon' ] ); + wp_insert_term( 'Conclusion', 'back-matter-type', [ 'slug' => 'conclusion' ] ); + wp_insert_term( 'Credits', 'back-matter-type', [ 'slug' => 'credits' ] ); + wp_insert_term( 'Dedication', 'back-matter-type', [ 'slug' => 'dedication' ] ); + wp_insert_term( 'Epilogue', 'back-matter-type', [ 'slug' => 'epilogue' ] ); + wp_insert_term( 'Glossary', 'back-matter-type', [ 'slug' => 'glossary' ] ); + wp_insert_term( 'Index', 'back-matter-type', [ 'slug' => 'index' ] ); + wp_insert_term( 'Miscellaneous', 'back-matter-type', [ 'slug' => 'miscellaneous' ] ); + wp_insert_term( 'Notes', 'back-matter-type', [ 'slug' => 'notes' ] ); + wp_insert_term( 'Other Books by Author', 'back-matter-type', [ 'slug' => 'other-books' ] ); + wp_insert_term( 'Permissions', 'back-matter-type', [ 'slug' => 'permissions' ] ); + wp_insert_term( 'Reading Group Guide', 'back-matter-type', [ 'slug' => 'reading-group-guide' ] ); + wp_insert_term( 'Resources', 'back-matter-type', [ 'slug', 'resources' ] ); + wp_insert_term( 'Sources', 'back-matter-type', [ 'slug' => 'sources' ] ); + wp_insert_term( 'Suggested Reading', 'back-matter-type', [ 'slug' => 'suggested-reading' ] ); // Chapter - wp_insert_term( 'Standard', 'chapter-type', array( 'slug' => 'standard' ) ); - wp_insert_term( 'Numberless', 'chapter-type', array( 'slug' => 'numberless' ) ); + wp_insert_term( 'Standard', 'chapter-type', [ 'slug' => 'standard' ] ); + wp_insert_term( 'Numberless', 'chapter-type', [ 'slug' => 'numberless' ] ); } /** @@ -258,7 +260,7 @@ static function getChapterType( $id ) { $terms = get_the_terms( $id, 'chapter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { - if ( 'type-1' == $term->slug ) { + if ( 'type-1' === $term->slug ) { return 'standard'; } else { return $term->slug; @@ -299,7 +301,7 @@ function upgradeChapterTypes() { $type_5 = get_term_by( 'slug', 'type-5', 'chapter-type' ); if ( $type_1 ) { - wp_update_term( $type_1->term_id, 'chapter-type', array( 'name' => 'Standard', 'slug' => 'standard' ) ); + wp_update_term( $type_1->term_id, 'chapter-type', [ 'name' => 'Standard', 'slug' => 'standard' ] ); } if ( $type_2 ) { diff --git a/includes/class-pb-themelock.php b/inc/class-themelock.php similarity index 87% rename from includes/class-pb-themelock.php rename to inc/class-themelock.php index 65ca4fc415..00ebb8e51f 100644 --- a/includes/class-pb-themelock.php +++ b/inc/class-themelock.php @@ -3,9 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks; -use Pressbooks\Container; +namespace Pressbooks; class ThemeLock { @@ -27,7 +26,7 @@ static function getLockDir() { } /** - * + * @return string */ static function getLockDirURI() { $wp_upload_dir = wp_upload_dir(); @@ -36,24 +35,30 @@ static function getLockDirURI() { return $lock_dir_uri; } + /** + * @param array $old_value + * @param array $value + * @param $option * + * @return mixed */ static function toggleThemeLock( $old_value, $value, $option ) { - if ( isset( $value['theme_lock'] ) && 1 == $value['theme_lock'] ) { + if ( isset( $value['theme_lock'] ) && 1 === absint( $value['theme_lock'] ) ) { return ThemeLock::lockTheme(); - } elseif ( 1 == $old_value['theme_lock'] && ! isset( $value['theme_lock'] ) ) { + } elseif ( 1 === absint( $old_value['theme_lock'] ) && ! isset( $value['theme_lock'] ) ) { return ThemeLock::unlockTheme(); } + return false; } /** * Lock the current theme by copying assets to the lock directory and generating a timestamped lockfile. * - * @return int + * @return mixed */ static function lockTheme() { - if ( true == ThemeLock::copyAssets() ) { + if ( true === ThemeLock::copyAssets() ) { $time = time(); $data = ThemeLock::generateLock( $time ); $_SESSION['pb_notices'][] = sprintf( @@ -82,20 +87,28 @@ static function copyAssets() { return \Pressbooks\Utility\rcopy( realpath( get_stylesheet_directory() ), ThemeLock::getLockDir() ); } + /** + * @param $time + * + * @return array + */ static function generateLock( $time ) { $theme = wp_get_theme(); - $data = array( + $data = [ 'stylesheet' => get_stylesheet(), 'name' => $theme->get( 'Name' ), 'version' => $theme->get( 'Version' ), 'timestamp' => $time, - ); + ]; $json = json_encode( $data ); $lockfile = ThemeLock::getLockDir() . '/lock.json'; file_put_contents( $lockfile, $json ); return $data; } + /** + * @return \WP_Theme + */ static function unlockTheme() { rmrdir( ThemeLock::getLockDir() ); $_SESSION['pb_notices'][] = sprintf( '%s', __( 'Your book’s theme has been unlocked.', 'pressbooks' ) ); @@ -110,7 +123,7 @@ static function unlockTheme() { */ static function isLocked() { $options = get_option( 'pressbooks_export_options' ); - if ( realpath( ThemeLock::getLockDir() . '/lock.json' ) && 1 == @$options['theme_lock'] ) { + if ( realpath( ThemeLock::getLockDir() . '/lock.json' ) && isset( $options['theme_lock'] ) && 1 === absint( $options['theme_lock'] ) ) { return true; } return false; @@ -134,8 +147,7 @@ static function restrictThemeManagement() { $locked = \Pressbooks\ThemeLock::isLocked(); if ( $locked ) { $data = \Pressbooks\ThemeLock::getLockData(); - } - if ( $locked ) { + // Redirect and notify users of theme lock status. $check_against_url = parse_url( ( is_ssl() ? 'http://' : 'https://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], PHP_URL_PATH ); @@ -144,9 +156,9 @@ static function restrictThemeManagement() { // --------------------------------------------------------------------------------------------------------------- // Don't let user go to theme (options) page, under any circumstance - $restricted = array( + $restricted = [ 'themes', - ); + ]; $expr = '~/wp-admin/(' . implode( '|', $restricted ) . ')\.php$~'; if ( preg_match( $expr, $check_against_url ) ) { diff --git a/includes/pb-editor.php b/inc/editor/namespace.php similarity index 87% rename from includes/pb-editor.php rename to inc/editor/namespace.php index c6ca5bb087..6c43ffbd31 100644 --- a/includes/pb-editor.php +++ b/inc/editor/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Editor; +namespace Pressbooks\Editor; use Pressbooks\Container; @@ -12,6 +12,7 @@ * Ensure that Word formatting that we like doesn't get filtered out. * * @param array $init_array + * * @return array */ function mce_valid_word_elements( $init_array ) { @@ -35,13 +36,13 @@ function add_languages( $array ) { function mce_buttons_2( $buttons ) { array_splice( $buttons, 0, 0, 'styleselect' ); - $p = array_search( 'styleselect', $buttons ); + $p = array_search( 'styleselect', $buttons, true ); array_splice( $buttons, $p + 1, 0, 'textboxes' ); - $p = array_search( 'textboxes', $buttons ); + $p = array_search( 'textboxes', $buttons, true ); array_splice( $buttons, $p + 1, 0, 'underline' ); - $p = array_search( 'hr', $buttons ); + $p = array_search( 'hr', $buttons, true ); array_splice( $buttons, $p + 1, 0, 'alignjustify' ); - $p = array_search( 'forecolor', $buttons ); + $p = array_search( 'forecolor', $buttons, true ); array_splice( $buttons, $p + 1, 0, 'backcolor' ); return $buttons; } @@ -58,6 +59,10 @@ function mce_buttons_3( $buttons ) { /** * Adds Javascript for buttons above. + * + * @param array $plugin_array + * + * @return array */ function mce_button_scripts( $plugin_array ) { $plugin_array['apply_class'] = \Pressbooks\Utility\asset_path( 'scripts/applyclass.js' ); @@ -69,65 +74,69 @@ function mce_button_scripts( $plugin_array ) { /** * Adds Pressbooks custom CSS classes to the style select dropdown initiated above. + * + * @param array $init_array + * + * @return array */ function mce_before_init_insert_formats( $init_array ) { - $style_formats = array( - array( + $style_formats = [ + [ 'title' => __( 'Indent', 'pressbooks' ), 'block' => 'p', 'classes' => 'indent', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Hanging indent', 'pressbooks' ), 'block' => 'p', 'classes' => 'hanging-indent', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'No indent', 'pressbooks' ), 'block' => 'p', 'classes' => 'no-indent', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Tight tracking', 'pressbooks' ), 'block' => 'span', 'classes' => 'tight', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Very tight tracking', 'pressbooks' ), 'block' => 'span', 'classes' => 'very-tight', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Loose tracking', 'pressbooks' ), 'block' => 'span', 'classes' => 'loose', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Very loose tracking', 'pressbooks' ), 'block' => 'span', 'classes' => 'very-loose', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Pullquote (left)', 'pressbooks' ), 'inline' => 'span', 'classes' => 'pullquote-left', 'wrapper' => false, - ), - array( + ], + [ 'title' => __( 'Pullquote (right)', 'pressbooks' ), 'inline' => 'span', 'classes' => 'pullquote-right', 'wrapper' => false, - ), - ); + ], + ]; $style_formats = apply_filters( 'pressbooks_editor_custom_styles', $style_formats ); @@ -151,14 +160,14 @@ function metadata_manager_default_editor_args( $args ) { // Precedence when using the + operator to merge arrays is from left to right - $args = array( - 'media_buttons' => false, - 'tinymce' => array( - 'theme_advanced_buttons1' => 'bold,italic,underline,strikethrough,|,link,unlink,|,numlist,bullist,|,undo,redo,pastetext,pasteword,|', - 'theme_advanced_buttons2' => '', - 'theme_advanced_buttons3' => '', - ), - ) + $args; + $args = [ + 'media_buttons' => false, + 'tinymce' => [ + 'theme_advanced_buttons1' => 'bold,italic,underline,strikethrough,|,link,unlink,|,numlist,bullist,|,undo,redo,pastetext,pasteword,|', + 'theme_advanced_buttons2' => '', + 'theme_advanced_buttons3' => '', + ], + ] + $args; return $args; } @@ -172,52 +181,52 @@ function metadata_manager_default_editor_args( $args ) { * @return array */ function mce_table_editor_options( $settings ) { - $table_classes = array( - array( + $table_classes = [ + [ 'title' => __( 'Standard', 'pressbooks' ), 'value' => '', - ), - array( + ], + [ 'title' => __( 'No lines', 'pressbooks' ), 'value' => 'no-lines', - ), - array( + ], + [ 'title' => __( 'Lines', 'pressbooks' ), 'value' => 'lines', - ), - array( + ], + [ 'title' => __( 'Shaded', 'pressbooks' ), 'value' => 'shaded', - ), - ); - $cell_classes = array( - array( + ], + ]; + $cell_classes = [ + [ 'title' => __( 'Standard', 'pressbooks' ), 'value' => '', - ), - array( + ], + [ 'title' => __( 'Border', 'pressbooks' ), 'value' => 'border', - ), - array( + ], + [ 'title' => __( 'Shaded', 'pressbooks' ), 'value' => 'shaded', - ), - ); - $row_classes = array( - array( + ], + ]; + $row_classes = [ + [ 'title' => __( 'Standard', 'pressbooks' ), 'value' => '', - ), - array( + ], + [ 'title' => __( 'Border', 'pressbooks' ), 'value' => 'border', - ), - array( + ], + [ 'title' => __( 'Shaded', 'pressbooks' ), 'value' => 'shaded', - ), - ); + ], + ]; $table_classes = apply_filters( 'pressbooks_editor_table_classes', $table_classes ); $cell_classes = apply_filters( 'pressbooks_editor_cell_classes', $cell_classes ); @@ -243,23 +252,27 @@ function update_editor_style() { if ( $sass->isCurrentThemeCompatible( 1 ) ) { $scss = file_get_contents( $sass->pathToPartials() . '/_editor-with-custom-fonts.scss' ); - $css = $sass->compile( $scss, [ + $css = $sass->compile( + $scss, [ $sass->pathToUserGeneratedSass(), $sass->pathToPartials(), $sass->pathToFonts(), get_stylesheet_directory(), - ] ); + ] + ); } elseif ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss = file_get_contents( $sass->pathToGlobals() . '/editor/_editor.scss' ); $css = $sass->compile( $scss, $sass->defaultIncludePaths( 'web' ) ); } else { $scss = file_get_contents( $sass->pathToPartials() . '/_editor.scss' ); - $css = $sass->compile( $scss, [ + $css = $sass->compile( + $scss, [ $sass->pathToUserGeneratedSass(), $sass->pathToPartials(), $sass->pathToFonts(), get_stylesheet_directory(), - ] ); + ] + ); } $css = Container::get( 'Sass' )->fixWebFonts( $css ); @@ -289,7 +302,7 @@ function add_editor_style() { */ function customize_wp_link_query_args( $query ) { - $query['post_type'] = array( 'part', 'chapter', 'front-matter', 'back-matter' ); + $query['post_type'] = [ 'part', 'chapter', 'front-matter', 'back-matter' ]; return $query; } @@ -311,7 +324,7 @@ function add_anchors_to_wp_link_query( $results, $query ) { return $results; } - $anchors = array(); + $anchors = []; $post = get_post( $query['post'] ); @@ -325,12 +338,12 @@ function add_anchors_to_wp_link_query( $results, $query ) { foreach ( $doc->getElementsByTagName( 'a' ) as $node ) { if ( $node->hasAttribute( 'id' ) ) { - $anchors[] = array( + $anchors[] = [ 'ID' => $post->ID, 'title' => '#' . $node->getAttribute( 'id' ) . ' (' . $post->post_title . ')', 'permalink' => '#' . $node->getAttribute( 'id' ), 'info' => __( 'Internal Link', 'pressbooks' ), - ); + ]; } } } @@ -338,8 +351,7 @@ function add_anchors_to_wp_link_query( $results, $query ) { $offset = count( $results ) + 1; foreach ( $results as $key => $result ) { - - if ( $results[ $key ]['ID'] == $query['post'] ) { + if ( $results[ $key ]['ID'] === $query['post'] ) { $offset = $key + 1; } } diff --git a/includes/pb-image.php b/inc/image/namespace.php similarity index 77% rename from includes/pb-image.php rename to inc/image/namespace.php index a140f932ca..72593302e7 100644 --- a/includes/pb-image.php +++ b/inc/image/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Image; +namespace Pressbooks\Image; /** * URL to default cover image @@ -56,7 +56,7 @@ function is_valid_image( $file, $filename, $is_stream = false ) { $format = explode( '.', $filename ); $format = strtolower( end( $format ) ); // Extension - if ( ! ( 'jpg' == $format || 'jpeg' == $format || 'gif' == $format || 'png' == $format ) ) { + if ( ! ( 'jpg' === $format || 'jpeg' === $format || 'gif' === $format || 'png' === $format ) ) { return false; } @@ -66,8 +66,8 @@ function is_valid_image( $file, $filename, $is_stream = false ) { $file = $tmp_image_path; } - $type = @exif_imagetype( $file ); - if ( IMAGETYPE_JPEG == $type || IMAGETYPE_GIF == $type || IMAGETYPE_PNG == $type ) { + $type = @exif_imagetype( $file ); // @codingStandardsIgnoreLine + if ( IMAGETYPE_JPEG === $type || IMAGETYPE_GIF === $type || IMAGETYPE_PNG === $type ) { return true; } else { return false; @@ -153,8 +153,10 @@ function thumbnail_from_url( $url, $size ) { $id = attachment_id_from_url( $url ); $image_thumb = wp_get_attachment_image_src( $id, $size ); - if ( $image_thumb ) { return $image_thumb[0]; // URL - } else { return $url; // Couldn't find anything, return original + if ( $image_thumb ) { + return $image_thumb[0]; // URL + } else { + return $url; // Couldn't find anything, return original } } @@ -167,13 +169,13 @@ function thumbnail_from_url( $url, $size ) { * * @return array */ -function intermediate_image_sizes( array $image_sizes = array() ) { +function intermediate_image_sizes( array $image_sizes = [] ) { - $our_sizes = array( - 'pb_cover_small' => array( 'width' => 65, 'height' => 0, 'crop' => false ), - 'pb_cover_medium' => array( 'width' => 225, 'height' => 0, 'crop' => false ), - 'pb_cover_large' => array( 'width' => 350, 'height' => 0, 'crop' => false ), - ); + $our_sizes = [ + 'pb_cover_small' => [ 'width' => 65, 'height' => 0, 'crop' => false ], + 'pb_cover_medium' => [ 'width' => 225, 'height' => 0, 'crop' => false ], + 'pb_cover_large' => [ 'width' => 350, 'height' => 0, 'crop' => false ], + ]; if ( empty( $image_sizes ) ) { return $our_sizes; @@ -194,12 +196,21 @@ function fix_intermediate_image_size_options() { $our_sizes = intermediate_image_sizes(); foreach ( $our_sizes as $key => $val ) { - add_filter( "pre_option_{$key}_size_w", function () use ( $val ) { return $val['width']; - } ); - add_filter( "pre_option_{$key}_size_h", function () use ( $val ) { return $val['height']; - } ); - add_filter( "pre_option_{$key}_crop", function () use ( $val ) { return $val['crop']; - } ); + add_filter( + "pre_option_{$key}_size_w", function () use ( $val ) { + return $val['width']; + } + ); + add_filter( + "pre_option_{$key}_size_h", function () use ( $val ) { + return $val['height']; + } + ); + add_filter( + "pre_option_{$key}_crop", function () use ( $val ) { + return $val['crop']; + } + ); } } @@ -229,7 +240,7 @@ function delete_attachment( $post_id ) { $post = get_post( $post_id ); $meta_post = ( new \Pressbooks\Metadata() )->getMetaPost(); - if ( $meta_post && $post && $post->post_parent == $meta_post->ID ) { + if ( $meta_post && $post && $post->post_parent === $meta_post->ID ) { // Reset pb_cover_image to default update_post_meta( $meta_post->ID, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); @@ -261,6 +272,11 @@ function delete_attachment( $post_id ) { /** * WP Hook for action 'wp_update_attachment_metadata'. Deal with user editing cover image from Media Library. + * + * @param array $data + * @param int $post_id + * + * @return array */ function save_attachment( $data, $post_id ) { @@ -273,7 +289,7 @@ function save_attachment( $data, $post_id ) { $upload_dir = wp_upload_dir(); $url = untrailingslashit( $upload_dir['baseurl'] ) . "/{$data['file']}"; - if ( $meta_post && $post && $post->post_parent == $meta_post->ID ) { + if ( $meta_post && $post && $post->post_parent === $meta_post->ID ) { // Update pb_cover_image to point to edited file update_post_meta( $meta_post->ID, 'pb_cover_image', $url ); @@ -297,7 +313,7 @@ function save_attachment( $data, $post_id ) { function cover_image_box( $post ) { $meta_key = 'pb_cover_image'; - $pid = (int) @$_GET['post']; + $pid = ( isset( $_GET['post'] ) ) ? (int) $_GET['post'] : 0; $image_url = thumbnail_from_url( get_post_meta( $post->ID, $meta_key, true ), 'pb_cover_medium' ); $action = 'pb_delete_cover_image'; $nonce = wp_create_nonce( 'pb-delete-cover-image' ); @@ -326,12 +342,12 @@ function catalog_logo_box( $user_id ) { /** * Render cover image widget * -* @param $form_id -* @param $cover_pid -* @param $image_url -* @param $ajax_action -* @param $nonce -* @param string $description (optional) + * @param $form_id + * @param $cover_pid + * @param $image_url + * @param $ajax_action + * @param $nonce + * @param string $description (optional) */ function render_cover_image_box( $form_id, $cover_pid, $image_url, $ajax_action, $nonce, $description = '' ) { ?> @@ -339,8 +355,8 @@ function render_cover_image_box( $form_id, $cover_pid, $image_url, $ajax_action,
-

cover_image
-

-

- +

cover_image
+ +

+

+ -

cover_image

-

+

cover_image

+

- +
- $MAX_W ); - $h_oversized = ( $orig_h > $MAX_H ); + $w_oversized = ( $orig_w > $max_w ); + $h_oversized = ( $orig_h > $max_h ); if ( $w_oversized || $h_oversized ) { - $new_w = round( min( $MAX_W, $ratio * $MAX_H ) ); - $new_h = round( min( $MAX_H, $MAX_W / $ratio ) ); + $new_w = round( min( $max_w, $ratio * $max_h ) ); + $new_h = round( min( $max_h, $max_w / $ratio ) ); } else { return; // Do nothing, image is small enough already } @@ -461,25 +478,26 @@ function resize_down( $format, $fullpath, $MAX_W = 1024, $MAX_H = 1024 ) { */ function fudge_factor( $format, $fullpath ) { - $size = getimagesize( $fullpath ); - if ( false == $size ) { + $size = @getimagesize( $fullpath ); // @codingStandardsIgnoreLine + if ( false === $size ) { return; } - if ( 'jpeg' == $format ) { + if ( 'jpeg' === $format ) { // Jpeg $fudge = 1.65; // This is a guestimate, your mileage may very - $memoryNeeded = round( ( $size[0] * $size[1] * $size['bits'] * $size['channels'] / 8 + pow( 2, 16 ) ) * $fudge ); + $memory_needed = round( ( $size[0] * $size[1] * $size['bits'] * $size['channels'] / 8 + pow( 2, 16 ) ) * $fudge ); } else { // Not Sure - $memoryNeeded = $size[0] * $size[1]; - if ( isset( $size['bits'] ) ) { $memoryNeeded = $memoryNeeded * $size['bits']; + $memory_needed = $size[0] * $size[1]; + if ( isset( $size['bits'] ) ) { + $memory_needed = $memory_needed * $size['bits']; } - $memoryNeeded = round( $memoryNeeded ); + $memory_needed = round( $memory_needed ); } - if ( memory_get_usage() + $memoryNeeded > (int) ini_get( 'memory_limit' ) * pow( 1024, 2 ) ) { - $memory_limit = (int) ini_get( 'memory_limit' ) + ceil( ( ( memory_get_usage() + $memoryNeeded ) - (int) ini_get( 'memory_limit' ) * pow( 1024, 2 ) ) / pow( 1024, 2 ) ) . 'M'; + if ( memory_get_usage() + $memory_needed > (int) ini_get( 'memory_limit' ) * pow( 1024, 2 ) ) { + $memory_limit = (int) ini_get( 'memory_limit' ) + ceil( ( ( memory_get_usage() + $memory_needed ) - (int) ini_get( 'memory_limit' ) * pow( 1024, 2 ) ) / pow( 1024, 2 ) ) . 'M'; trigger_error( "Image is too big, attempting to compensate by setting memory_limit to {$memory_limit} ...", E_USER_WARNING ); ini_set( 'memory_limit', $memory_limit ); } diff --git a/includes/pb-l10n.php b/inc/l10n/namespace.php similarity index 94% rename from includes/pb-l10n.php rename to inc/l10n/namespace.php index 73e70caa86..cae512f1a1 100644 --- a/includes/pb-l10n.php +++ b/inc/l10n/namespace.php @@ -3,8 +3,11 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\L10n; +use function \Pressbooks\Utility\getset; + /** * KindleGen is based on Mobipocket Creator and apparently supports only the following language codes. * This populates the language dropdown on the Book Info page. @@ -14,7 +17,7 @@ */ function supported_languages() { - $languages = array( + $languages = [ '' => '', 'af' => 'Afrikaans', 'sq' => 'Albanian', @@ -156,7 +159,7 @@ function supported_languages() { 'vi' => 'Vietnamese', 'xh' => 'Xhosa', 'zu' => 'Zulu', - ); + ]; asort( $languages ); @@ -170,7 +173,7 @@ function supported_languages() { */ function wplang_codes() { - $languages = array( + $languages = [ 'af' => 'af', // Afrikaans 'sq' => 'sq', // Albanian 'ar' => 'ar', // Arabic @@ -211,7 +214,7 @@ function wplang_codes() { 'en-ca' => 'en_CA', // English (Canada) 'en-ie' => 'en_UK', // English (Ireland) 'en-jm' => 'en_US', // English (Jamaica) - 'en-nz' => 'en_NZ', // English (New Zealand) + 'en-nz' => 'en_NZ', // English (Aotearoa New Zealand) 'en-ph' => 'en_US', // English (Philippines) 'en-za' => 'en_ZA', // English (South Africa) 'en-tt' => 'en_US', // English (Trinidad) @@ -311,7 +314,7 @@ function wplang_codes() { 'vi' => 'vi', // Vietnamese 'xh' => '', // Xhosa 'zu' => '', // Zulu - ); + ]; return $languages; } @@ -356,15 +359,11 @@ function load_plugin_textdomain() { * @return mixed */ function override_core_strings( $translated, $original, $domain ) { - - // var_dump( array( $translated, $original, $domain) ); - $overrides = include_core_overrides(); if ( isset( $overrides[ $original ] ) ) { $translations = get_translations_for_domain( $domain ); - // @codingStandardsIgnoreLine - $translated = $translations->translate( $overrides[ $original ] ); + $translated = $translations->translate( $overrides[ $original ] ); // @codingStandardsIgnoreLine } return $translated; @@ -381,14 +380,14 @@ function override_core_strings( $translated, $original, $domain ) { function include_core_overrides() { // Cheap cache - static $_overrides = array(); + static $_overrides = []; $locale = apply_filters( 'plugin_locale', get_locale(), 'pressbooks' ); $filename = 'core-' . strtolower( str_replace( '_', '-', $locale ) ) . '.php'; $filepath = PB_PLUGIN_DIR . 'languages/' . $filename; if ( ! isset( $_overrides[ $locale ] ) ) { - $_overrides[ $locale ] = array(); + $_overrides[ $locale ] = []; if ( file_exists( $filepath ) ) { $_overrides[ $locale ] = include( $filepath ); } @@ -417,24 +416,24 @@ function set_locale( $lang ) { if ( is_admin() ) { // If user locale isn't set, use the book information value. if ( function_exists( 'wp_get_current_user' ) && ! get_user_option( 'locale' ) ) { - if ( '__UNSET__' == $loc ) { + if ( '__UNSET__' === $loc ) { $locations = \Pressbooks\L10n\wplang_codes(); $loc = $locations[ $book_lang ]; } } - } elseif ( 'wp-signup.php' == @$GLOBALS['pagenow'] ) { + } elseif ( isset( $GLOBALS['pagenow'] ) && 'wp-signup.php' === $GLOBALS['pagenow'] ) { // If we're on the registration page, use the global setting. $loc = get_site_option( 'WPLANG' ); } else { // Use the book information value. - if ( '__UNSET__' == $loc ) { + if ( '__UNSET__' === $loc ) { $locations = \Pressbooks\L10n\wplang_codes(); $loc = $locations[ $book_lang ]; } } - // Return - if ( '__UNSET__' == $loc ) { + // Return the language + if ( '__UNSET__' === $loc ) { return $lang; } else { return ( $loc ? $loc : $lang ); @@ -460,6 +459,7 @@ function set_root_locale( $lang ) { * When a user changes their book's language, try to install the corresponding language pack. * * @since 3.9.6 + * * @param int $meta_id The metadata ID * @param int $post_ID The book information post ID * @param string $meta_key The metadata key @@ -468,8 +468,8 @@ function set_root_locale( $lang ) { * @return string|bool Returns the language code if successfully downloaded * (or already installed), or false on failure. */ -function install_book_locale( $meta_id, $post_id, $meta_key, $meta_value ) { - if ( 'pb_language' != $meta_key ) { +function install_book_locale( $meta_id, $post_id, $meta_key, $meta_value ) { + if ( 'pb_language' !== $meta_key ) { return false; } @@ -478,7 +478,7 @@ function install_book_locale( $meta_id, $post_id, $meta_key, $meta_value ) { if ( '' !== $locale && 'en_US' !== $locale ) { require_once( ABSPATH . '/wp-admin/includes/translation-install.php' ); $result = \wp_download_language_pack( $locale ); - if ( false == $result ) { + if ( false === $result ) { $supported_languages = supported_languages(); $_SESSION['pb_errors'][] = sprintf( __( 'Please contact your system administrator if you would like them to install extended %s language support for the Pressbooks interface.', 'pressbooks' ), $supported_languages[ $meta_value ] ); } @@ -489,7 +489,6 @@ function install_book_locale( $meta_id, $post_id, $meta_key, $meta_value ) { } - /** * Update previous user interface language meta value to WP 4.7 user locale, try to install the corresponding language pack. * @@ -498,14 +497,14 @@ function install_book_locale( $meta_id, $post_id, $meta_key, $meta_value ) { function update_user_locale() { if ( function_exists( 'get_user_meta' ) ) { $locale = get_user_meta( get_current_user_id(), 'user_interface_lang', true ); - if ( $locale && 'en_US' != $locale ) { + if ( $locale && 'en_US' !== $locale ) { update_user_meta( get_current_user_id(), 'locale', $locale ); require_once( ABSPATH . '/wp-admin/includes/translation-install.php' ); $result = \wp_download_language_pack( $locale ); - if ( false == $result ) { + if ( false === $result ) { $wplang_codes = wplang_codes(); $supported_languages = supported_languages(); - $lang = array_search( $locale, $wplang_codes ); + $lang = array_search( $locale, $wplang_codes, true ); $_SESSION['pb_errors'][] = sprintf( __( 'Please contact your system administrator if you would like them to install extended %s language support for the Pressbooks interface.', 'pressbooks' ), $supported_languages[ $lang ] ); } } @@ -524,7 +523,7 @@ function romanize( $integer ) { $integer = absint( $integer ); - $table = array( 'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1 ); + $table = [ 'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1 ]; $return = ''; while ( $integer > 0 ) { foreach ( $table as $rom => $arb ) { @@ -547,8 +546,7 @@ function romanize( $integer ) { */ function use_book_locale() { - // @codingStandardsIgnoreLine - if ( \Pressbooks\Modules\Export\Export::isFormSubmission() && is_array( @$_POST['export_formats'] ) ) { + if ( \Pressbooks\Modules\Export\Export::isFormSubmission() && is_array( getset( '_POST', 'export_formats' ) ) ) { return true; } diff --git a/includes/pb-media.php b/inc/media/namespace.php similarity index 87% rename from includes/pb-media.php rename to inc/media/namespace.php index 769d27a191..2239b29283 100644 --- a/includes/pb-media.php +++ b/inc/media/namespace.php @@ -3,6 +3,7 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ + namespace Pressbooks\Media; /** @@ -15,9 +16,9 @@ * * @return array */ -function add_mime_types( $existing_mimes = array() ) { +function add_mime_types( $existing_mimes = [] ) { - $add_mimes = array( + $add_mimes = [ 'mp4' => 'video/mp4', 'webm' => 'video/webm', 'ogv' => 'video/ogg', @@ -25,7 +26,7 @@ function add_mime_types( $existing_mimes = array() ) { 'mp3' => 'audio/mpeg', 'aac' => 'audio/x-aac', 'vorbis' => 'audio/vorbis', - ); + ]; return array_merge( $add_mimes, $existing_mimes ); } @@ -33,12 +34,12 @@ function add_mime_types( $existing_mimes = array() ) { /** * Checks for valid EPUB3 video or audio file names. * - * @param string $pathToFile + * @param string $path_to_file * @param string $filename * * @return boolean */ -function is_valid_media( $pathToFile, $filename ) { +function is_valid_media( $path_to_file, $filename ) { $validate = wp_check_filetype( $filename, add_mime_types() ); @@ -74,9 +75,11 @@ function force_wrap_images( $content ) { */ function force_attach_media( $params ) { + // @codingStandardsIgnoreStart global $post_ID; if ( isset( $post_ID ) ) { $params['post_id'] = (int) $post_ID; } + // @codingStandardsIgnoreEnd return $params; } diff --git a/includes/modules/export/class-pb-export.php b/inc/modules/export/class-export.php similarity index 88% rename from includes/modules/export/class-pb-export.php rename to inc/modules/export/class-export.php index e437915215..7cf7969cbe 100644 --- a/includes/modules/export/class-pb-export.php +++ b/inc/modules/export/class-export.php @@ -3,22 +3,21 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Export; +namespace Pressbooks\Modules\Export; use Pressbooks\Book; use Pressbooks\CustomCss; use Pressbooks\Container; use Pressbooks\Metadata; - // IMPORTANT! if this isn't set correctly before include, with a trailing slash, PclZip will fail. if ( ! defined( 'PCLZIP_TEMPORARY_DIR' ) ) { if ( ! empty( $_ENV['TMP'] ) ) { define( 'PCLZIP_TEMPORARY_DIR', trailingslashit( realpath( $_ENV['TMP'] ) ) ); - } else if ( ! empty( $_ENV['TMPDIR'] ) ) { + } elseif ( ! empty( $_ENV['TMPDIR'] ) ) { define( 'PCLZIP_TEMPORARY_DIR', trailingslashit( realpath( $_ENV['TMPDIR'] ) ) ); - } else if ( ! empty( $_ENV['TEMP'] ) ) { + } elseif ( ! empty( $_ENV['TEMP'] ) ) { define( 'PCLZIP_TEMPORARY_DIR', trailingslashit( realpath( $_ENV['TEMP'] ) ) ); } else { define( 'PCLZIP_TEMPORARY_DIR', '/tmp/' ); @@ -32,9 +31,9 @@ abstract class Export { * * @var array */ - public $errorsEmail = array( + public $errorsEmail = [ 'errors@pressbooks.com', - ); + ]; /** @@ -42,14 +41,14 @@ abstract class Export { * * @var array */ - protected $reservedIds = array( + protected $reservedIds = [ 'cover-image', 'half-title-page', 'title-page', 'copyright-page', 'toc', 'pressbooks-promo', - ); + ]; /** @@ -100,7 +99,8 @@ function getExportStylePath( $type ) { if ( CustomCss::isCustomCss() ) { $fullpath = CustomCss::getCustomCssFolder() . "$type.css"; - if ( ! is_file( $fullpath ) ) { $fullpath = false; + if ( ! is_file( $fullpath ) ) { + $fullpath = false; } } @@ -143,7 +143,7 @@ function getExportScriptPath( $type ) { } else { $fullpath = realpath( apply_filters( 'pb_stylesheet_directory', get_stylesheet_directory() ) . "/export/$type/script.js" ); } - if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' == $type ) { + if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' === $type ) { $fullpath = realpath( get_stylesheet_directory() . "/export/$type/script-romanize.js" ); } } @@ -167,7 +167,7 @@ function getExportScriptUrl( $type ) { } elseif ( realpath( apply_filters( 'pb_stylesheet_directory', get_stylesheet_directory() ) . "/export/$type/script.js" ) ) { $url = apply_filters( 'pb_stylesheet_directory_uri', get_stylesheet_directory_uri() ) . "/export/$type/script.js"; } - if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' == $type ) { + if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' === $type ) { $url = get_stylesheet_directory_uri() . "/export/$type/script-romanize.js"; } @@ -183,33 +183,37 @@ static function isParsingSubsections() { $options = get_option( 'pressbooks_theme_options_global' ); - return (bool) ( @$options['parse_subsections'] ); + if ( isset( $options['parse_subsections'] ) ) { + return (bool) ( $options['parse_subsections'] ); + } + + return false; } /** * Log errors using wp_mail() and error_log(), include useful WordPress info. * * @param string $message - * @param array $more_info + * @param array $more_info */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = get_class( $this ); - $info = array( + $info = [ 'time' => strftime( '%c' ), 'user' => ( isset( $current_user ) ? $current_user->user_login : '__UNKNOWN__' ), 'site_url' => site_url(), 'blog_id' => get_current_blog_id(), 'theme' => '' . wp_get_theme(), // Stringify by appending to empty string - ); + ]; $message = print_r( array_merge( $info, $more_info ), true ) . $message; $exportoptions = get_option( 'pressbooks_export_options' ); - if ( @$current_user->user_email && isset( $exportoptions['email_validation_logs'] ) && 1 == $exportoptions['email_validation_logs'] ) { + if ( $current_user->user_email && isset( $exportoptions['email_validation_logs'] ) && 1 === absint( $exportoptions['email_validation_logs'] ) ) { $this->errorsEmail[] = $current_user->user_email; } @@ -239,7 +243,7 @@ function createTmpFile() { function timestampedFileName( $extension, $fullpath = true ) { $book_title = ( get_bloginfo( 'name' ) ) ? get_bloginfo( 'name' ) : __( 'book', 'pressbooks' ); $book_title_slug = sanitize_file_name( $book_title ); - $book_title_slug = str_replace( array( '+' ), '', $book_title_slug ); // Remove symbols which confuse Apache (Ie. form urlencoded spaces) + $book_title_slug = str_replace( [ '+' ], '', $book_title_slug ); // Remove symbols which confuse Apache (Ie. form urlencoded spaces) $book_title_slug = sanitize_file_name( $book_title_slug ); // str_replace() may inadvertently create a new bad filename, sanitize again for good measure. if ( $fullpath ) { @@ -288,7 +292,7 @@ function verifyNonce( $timestamp, $md5 ) { } // Correct md5? - if ( md5( NONCE_KEY . $timestamp ) != $md5 ) { + if ( md5( NONCE_KEY . $timestamp ) !== $md5 ) { return false; } @@ -307,7 +311,7 @@ function fixAnnoyingCharacters( $html ) { // Replace Non-breaking spaces with normal spaces // TODO: Some users want this, others do not want this, make up your mind... - // $html = preg_replace( '/\xC2\xA0/', ' ', $html ); + // $html = preg_replace( '/\xC2\xA0/', ' ', $html ); @codingStandardsIgnoreLine return $html; } @@ -322,7 +326,7 @@ function fixAnnoyingCharacters( $html ) { */ protected function preProcessPostName( $id ) { - if ( in_array( $id, $this->reservedIds ) ) { + if ( in_array( $id, $this->reservedIds, true ) ) { $id = uniqid( "$id-" ); } @@ -356,7 +360,7 @@ protected function createTmpDir() { * Recursively delete all contents of a directory. * * @param string $dirname - * @param bool $only_empty + * @param bool $only_empty * * @return bool */ @@ -366,26 +370,31 @@ protected function obliterateDir( $dirname, $only_empty = false ) { return false; } - $dscan = array( realpath( $dirname ) ); - $darr = array(); + $dscan = [ realpath( $dirname ) ]; + $darr = []; while ( ! empty( $dscan ) ) { $dcur = array_pop( $dscan ); $darr[] = $dcur; - if ( $d = opendir( $dcur ) ) { + $d = opendir( $dcur ); + if ( $d ) { while ( $f = readdir( $d ) ) { - if ( '.' == $f || '..' == $f ) { continue; + if ( '.' === $f || '..' === $f ) { + continue; } $f = $dcur . '/' . $f; - if ( is_dir( $f ) ) { $dscan[] = $f; - } else { unlink( $f ); + if ( is_dir( $f ) ) { + $dscan[] = $f; + } else { + unlink( $f ); } } closedir( $d ); } } $i_until = ( $only_empty ) ? 1 : 0; - for ( $i = count( $darr ) - 1; $i >= $i_until; $i -- ) { - if ( ! rmdir( $darr[ $i ] ) ) { trigger_error( "Warning: There was a problem deleting a temporary file in $dirname", E_USER_WARNING ); + for ( $i = count( $darr ) - 1; $i >= $i_until; $i-- ) { + if ( ! rmdir( $darr[ $i ] ) ) { + trigger_error( "Warning: There was a problem deleting a temporary file in $dirname", E_USER_WARNING ); } } @@ -396,8 +405,8 @@ protected function obliterateDir( $dirname, $only_empty = false ) { /** * Convert an XML string via XSLT file. * - * @param string $content - * @param string $path_to_xsl + * @param string $content + * @param string $path_to_xsl * * @return string */ @@ -433,15 +442,16 @@ protected function transformXML( $content, $path_to_xsl ) { * @param string $title * @param int $id * @param string $section_author + * * @return string $html blob * @throws \Exception */ protected function doCopyrightLicense( $metadata, $title = '', $id = null, $section_author = '' ) { $options = get_option( 'pressbooks_theme_options_global' ); - foreach ( array( 'copyright_license' ) as $requiredGlobalOption ) { - if ( ! isset( $options[ $requiredGlobalOption ] ) ) { - $options[ $requiredGlobalOption ] = 0; + foreach ( [ 'copyright_license' ] as $required_global_option ) { + if ( ! isset( $options[ $required_global_option ] ) ) { + $options[ $required_global_option ] = 0; } } @@ -450,7 +460,7 @@ protected function doCopyrightLicense( $metadata, $title = '', $id = null, $sect // if they don't want to see it, return // at minimum we need book copyright information set - if ( false == $options['copyright_license'] || ! isset( $metadata['pb_book_license'] ) ) { + if ( false === absint( $options['copyright_license'] ) || ! isset( $metadata['pb_book_license'] ) ) { return ''; } @@ -514,7 +524,7 @@ protected function doCopyrightLicense( $metadata, $title = '', $id = null, $sect * @return string * @throws \Exception */ - protected function loadTemplate( $path, array $vars = array() ) { + protected function loadTemplate( $path, array $vars = [] ) { return \Pressbooks\Utility\template( $path, $vars ); } @@ -534,7 +544,7 @@ static function mimeType( $file ) { $mime = finfo_file( $finfo, $file ); finfo_close( $finfo ); } elseif ( function_exists( 'mime_content_type' ) ) { - $mime = @mime_content_type( $file ); // Suppress deprecated message + $mime = @mime_content_type( $file ); // Suppress deprecated message @codingStandardsIgnoreLine } else { exec( 'file -i -b ' . escapeshellarg( $file ), $output ); $mime = $output[0]; @@ -574,7 +584,7 @@ static function getExportFolder() { */ static function formSubmit() { - if ( false == static::isFormSubmission() || false == current_user_can( 'edit_posts' ) ) { + if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } @@ -602,13 +612,13 @@ static function formSubmit() { } // Export - if ( 'yes' == @$_GET['export'] && is_array( @$_POST['export_formats'] ) && check_admin_referer( 'pb-export' ) ) { + if ( isset( $_GET['export'] ) && 'yes' === $_GET['export'] && is_array( $_POST['export_formats'] ) && check_admin_referer( 'pb-export' ) ) { // -------------------------------------------------------------------------------------------------------- // Define modules $x = $_POST['export_formats']; - $modules = array(); + $modules = []; if ( isset( $x['pdf'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\Pdf'; @@ -651,11 +661,11 @@ static function formSubmit() { * For example, here's how one might catch a hypothetical Word exporter: * * add_filter( 'pb_active_export_modules', function ( $modules ) { - * if ( isset( $_POST['export_formats']['docx'] ) ) { - * $modules[] = '\Pressbooks\Modules\Export\Docx\Docx'; - * } - * return $modules; - * } ); + * if ( isset( $_POST['export_formats']['docx'] ) ) { + * $modules[] = '\Pressbooks\Modules\Export\Docx\Docx'; + * } + * return $modules; + * } ); * */ $modules = apply_filters( 'pb_active_export_modules', $modules ); @@ -673,17 +683,17 @@ static function formSubmit() { // -------------------------------------------------------------------------------------------------------- // Do Export - @set_time_limit( 300 ); + set_time_limit( 300 ); $redirect_url = get_admin_url( get_current_blog_id(), '/admin.php?page=pb_export' ); - $conversion_error = array(); - $validation_warning = array(); - $outputs = array(); + $conversion_error = []; + $validation_warning = []; + $outputs = []; foreach ( $modules as $module ) { /** @var \Pressbooks\Modules\Export\Export $exporter */ - $exporter = new $module( array() ); + $exporter = new $module( [] ); if ( ! $exporter->convert() ) { $conversion_error[ $module ] = $exporter->getOutputPath(); @@ -740,7 +750,7 @@ static function formSubmit() { } // -------------------------------------------------------------------------------------------------------- - // Errors :( + // Handle errors :( if ( count( $conversion_error ) ) { // Conversion error @@ -768,7 +778,7 @@ static function setLocale( $lang ) { // Cheap cache static $loc = '__UNSET__'; - if ( '__UNSET__' == $loc && function_exists( 'get_available_languages' ) ) { + if ( '__UNSET__' === $loc && function_exists( 'get_available_languages' ) ) { $compare_with = get_available_languages( PB_PLUGIN_DIR . '/languages/' ); @@ -787,12 +797,13 @@ static function setLocale( $lang ) { } } - if ( '__UNSET__' == $loc ) { $loc = 'en_US'; // No match found, default to english + if ( '__UNSET__' === $loc ) { + $loc = 'en_US'; // No match found, default to english } } - // Return - if ( '__UNSET__' == $loc ) { + // Return the language + if ( '__UNSET__' === $loc ) { return $lang; } else { return ( $loc ? $loc : $lang ); @@ -807,12 +818,15 @@ static function setLocale( $lang ) { */ static function isFormSubmission() { - if ( 'pb_export' != @$_REQUEST['page'] ) { + if ( empty( $_REQUEST['page'] ) ) { return false; } - // @codingStandardsIgnoreLine - if ( ! empty( $_POST ) ) { + if ( 'pb_export' !== $_REQUEST['page'] ) { + return false; + } + + if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } @@ -833,11 +847,11 @@ static function isFormSubmission() { */ static function injectHouseStyles( $css ) { - $scan = array( + $scan = [ '/*__INSERT_PDF_HOUSE_STYLE__*/' => PB_PLUGIN_DIR . '/assets/scss/partials/_pdf-house-style.scss', '/*__INSERT_EPUB_HOUSE_STYLE__*/' => PB_PLUGIN_DIR . '/assets/scss/partials/_epub-house-style.scss', '/*__INSERT_MOBI_HOUSE_STYLE__*/' => PB_PLUGIN_DIR . '/assets/scss/partials/_mobi-house-style.scss', - ); + ]; foreach ( $scan as $token => $replace_with ) { if ( is_file( $replace_with ) ) { @@ -859,7 +873,7 @@ protected static function downloadExportFile( $filename ) { $filepath = static::getExportFolder() . $filename; if ( ! is_readable( $filepath ) ) { // Cannot read file - wp_die( __( 'File not found', 'pressbooks' ) . ": $filename", '', array( 'response' => 404 ) ); + wp_die( __( 'File not found', 'pressbooks' ) . ": $filename", '', [ 'response' => 404 ] ); } // Force download @@ -872,16 +886,13 @@ protected static function downloadExportFile( $filename ) { header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Pragma: public' ); header( 'Content-Length: ' . filesize( $filepath ) ); - @ob_clean(); + @ob_clean(); // @codingStandardsIgnoreLine flush(); - // @codingStandardsIgnoreLine - while ( @ob_end_flush() ) { + while ( @ob_end_flush() ) { // @codingStandardsIgnoreLine // Fix out-of-memory problem } readfile( $filepath ); exit; } - - } diff --git a/includes/modules/export/epub/class-pb-epub201.php b/inc/modules/export/epub/class-epub201.php similarity index 82% rename from includes/modules/export/epub/class-pb-epub201.php rename to inc/modules/export/epub/class-epub201.php index 386153456c..c02dcd852d 100644 --- a/includes/modules/export/epub/class-pb-epub201.php +++ b/inc/modules/export/epub/class-epub201.php @@ -9,24 +9,21 @@ namespace Pressbooks\Modules\Export\Epub; - use Pressbooks\Modules\Export\Export; use Pressbooks\Container; use Pressbooks\Sanitize; -require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' ); - class Epub201 extends Export { /** * @var array */ - protected $fetchedImageCache = array(); + protected $fetchedImageCache = []; /** * @var array */ - protected $fetchedFontCache = array(); + protected $fetchedFontCache = []; /** * Timeout in seconds. @@ -62,7 +59,7 @@ class Epub201 extends Export { * * @var array */ - protected $manifest = array(); + protected $manifest = []; /** @@ -180,6 +177,10 @@ function __construct( array $args ) { // Some defaults + if ( ! class_exists( '\PclZip' ) ) { + require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' ); + } + if ( ! defined( 'PB_EPUBCHECK_COMMAND' ) ) { define( 'PB_EPUBCHECK_COMMAND', '/usr/bin/java -jar /opt/epubcheck/epubcheck.jar' ); } @@ -270,7 +271,7 @@ function validate() { $command = PB_EPUBCHECK_COMMAND . ' -q ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command - $output = array(); + $output = []; $return_var = 0; exec( $command, $output, $return_var ); @@ -290,7 +291,7 @@ function validate() { * * @param string $html * - * @return string|void + * @return string */ function fixAnnoyingCharacters( $html ) { @@ -301,13 +302,12 @@ function fixAnnoyingCharacters( $html ) { // Adobe Digital Editions has problems with exotic dashes, that is to say if this were 1999... // TODO: Some users want this, others do not want this, make up your mind... - // $html = str_replace( array( '–', '–', '—', '—', '‑' ), '-', $html ); + // $html = str_replace( array( '–', '–', '—', '—', '‑' ), '-', $html ); @codingStandardsIgnoreLine return $html; } - /** * Override mimeType, get rid of '; charset=binary' * @@ -339,7 +339,7 @@ protected function themeOptionsOverrides() { // -------------------------------------------------------------------- // Hacks - $hacks = array(); + $hacks = []; $hacks = apply_filters( 'pb_epub_hacks', $hacks ); // Display chapter numbers? @@ -377,7 +377,6 @@ protected function preProcessBookContents( $book_contents ) { foreach ( $struct as $i => $val ) { if ( isset( $val['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val['ID']; $book_contents[ $type ][ $i ]['post_content'] = $this->preProcessPostContent( $val['post_content'] ); } @@ -388,13 +387,12 @@ protected function preProcessBookContents( $book_contents ) { $book_contents[ $type ][ $i ]['post_name'] = $this->preProcessPostName( $val['post_name'] ); } - if ( 'part' == $type ) { + if ( 'part' === $type ) { // Do chapters, which are embedded in part structure foreach ( $book_contents[ $type ][ $i ]['chapters'] as $j => $val2 ) { if ( isset( $val2['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val2['ID']; $book_contents[ $type ][ $i ]['chapters'][ $j ]['post_content'] = $this->preProcessPostContent( $val2['post_content'] ); } @@ -409,7 +407,6 @@ protected function preProcessBookContents( $book_contents ) { } } - // @codingStandardsIgnoreLine $id = $old_id; return $book_contents; } @@ -441,7 +438,7 @@ protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', @@ -449,7 +446,7 @@ protected function tidy( $html ) { 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, 'comment' => 1, - ); + ]; // Reset on each htmLawed invocation unset( $GLOBALS['hl_Ids'] ); @@ -489,21 +486,23 @@ protected function zipEpub( $filename ) { // Open Publication Structure 2.0.1 // mimetype must be uncompressed, unencrypted, and the first file in the ZIP archive $list = $zip->create( $this->tmpDir . '/mimetype', PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH ); - if ( 0 == $list ) { + if ( 0 === absint( $list ) ) { return false; } - $files = array(); + $files = []; foreach ( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $this->tmpDir ) ) as $file ) { - if ( ! $file->isFile() ) { continue; + if ( ! $file->isFile() ) { + continue; } - if ( 'mimetype' == $file->getFilename() ) { continue; + if ( 'mimetype' === $file->getFilename() ) { + continue; } $files[] = $file->getPathname(); } $list = $zip->add( $files, '', $this->tmpDir ); - if ( 0 == $list ) { + if ( 0 === absint( $list ) ) { return false; } @@ -518,7 +517,8 @@ protected function createContainer() { file_put_contents( $this->tmpDir . '/mimetype', - utf8_decode( 'application/epub+zip' ) ); + utf8_decode( 'application/epub+zip' ) + ); mkdir( $this->tmpDir . '/META-INF' ); mkdir( $this->tmpDir . '/OEBPS' ); @@ -526,11 +526,13 @@ protected function createContainer() { file_put_contents( $this->tmpDir . '/META-INF/container.xml', - $this->loadTemplate( $this->dir . '/templates/epub201/container.php' ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/container.php' ) + ); file_put_contents( $this->tmpDir . '/META-INF/com.apple.ibooks.display-options.xml', - $this->loadTemplate( $this->dir . '/templates/epub201/ibooks.php' ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/ibooks.php' ) + ); } @@ -547,7 +549,7 @@ protected function createOEPBS( $book_contents, $metadata ) { $this->createStylesheet(); // Reset manifest - $this->manifest = array(); + $this->manifest = []; /* Note: order affects $this->manifest */ @@ -595,10 +597,10 @@ protected function createStylesheet() { // Copy stylesheet file_put_contents( $path_to_tmp_stylesheet, - $this->loadTemplate( $this->exportStylePath ) ); + $this->loadTemplate( $this->exportStylePath ) + ); $this->scrapeKneadAndSaveCss( $this->exportStylePath, $path_to_tmp_stylesheet ); - } @@ -623,73 +625,79 @@ protected function scrapeKneadAndSaveCss( $path_to_original_stylesheet, $path_to $scss = $sass->applyOverrides( $scss, $this->cssOverrides ); if ( $sass->isCurrentThemeCompatible( 1 ) ) { - $css = $sass->compile( $scss, [ + $css = $sass->compile( + $scss, [ $sass->pathToUserGeneratedSass(), $sass->pathToPartials(), $sass->pathToFonts(), get_stylesheet_directory(), - ] ); + ] + ); } elseif ( $sass->isCurrentThemeCompatible( 2 ) ) { $css = $sass->compile( $scss, $sass->defaultIncludePaths( 'epub' ) ); } else { $css = static::injectHouseStyles( $scss ); } - // Search for url("*"), url('*'), and url(*) + // Search for all possible permutations of CSS url syntax: url("*"), url('*'), and url(*) $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; - $css = preg_replace_callback( $url_regex, function ( $matches ) use ( $scss_dir, $path_to_epub_assets ) { + $css = preg_replace_callback( + $url_regex, function ( $matches ) use ( $scss_dir, $path_to_epub_assets ) { - $url = $matches[3]; - $filename = sanitize_file_name( basename( $url ) ); + $url = $matches[3]; + $filename = sanitize_file_name( basename( $url ) ); - if ( preg_match( '#^images/#', $url ) && substr_count( $url, '/' ) == 1 ) { + if ( preg_match( '#^images/#', $url ) && substr_count( $url, '/' ) === 1 ) { - // Look for "^images/" - // Count 1 slash so that we don't touch stuff like "^images/out/of/bounds/" or "^images/../../denied/" + // Look for "^images/" + // Count 1 slash so that we don't touch stuff like "^images/out/of/bounds/" or "^images/../../denied/" - $my_image = realpath( "$scss_dir/$url" ); - if ( $my_image ) { - copy( $my_image, "$path_to_epub_assets/$filename" ); - return "url(assets/$filename)"; - } - } elseif ( preg_match( '#^../../images/epub/#', $url ) && substr_count( $url, '/' ) == 4 ) { + $my_image = realpath( "$scss_dir/$url" ); + if ( $my_image ) { + copy( $my_image, "$path_to_epub_assets/$filename" ); + return "url(assets/$filename)"; + } + } elseif ( preg_match( '#^../../images/epub/#', $url ) && substr_count( $url, '/' ) === 4 ) { - // Look for "^../../images/epub/" - // Count 4 slashes so that we explicitly select the path to the new assets directory + // Look for "^../../images/epub/" + // Count 4 slashes so that we explicitly select the path to the new assets directory - $my_image = realpath( "$scss_dir/$url" ); - if ( $my_image ) { - copy( $my_image, "$path_to_epub_assets/$filename" ); - return "url(assets/$filename)"; - } - } elseif ( preg_match( '#^https?://#i', $url ) && preg_match( '/(' . $this->supportedImageExtensions . ')$/i', $url ) ) { + $my_image = realpath( "$scss_dir/$url" ); + if ( $my_image ) { + copy( $my_image, "$path_to_epub_assets/$filename" ); + return "url(assets/$filename)"; + } + } elseif ( preg_match( '#^https?://#i', $url ) && preg_match( '/(' . $this->supportedImageExtensions . ')$/i', $url ) ) { - // Look for images via http(s), pull them in locally + // Look for images via http(s), pull them in locally - if ( $new_filename = $this->fetchAndSaveUniqueImage( $url, $path_to_epub_assets ) ) { - return "url(assets/$new_filename)"; - } - } elseif ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { + $new_filename = $this->fetchAndSaveUniqueImage( $url, $path_to_epub_assets ); + if ( $new_filename ) { + return "url(assets/$new_filename)"; + } + } elseif ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { - // Look for themes-book/pressbooks-book/fonts/*.ttf (or .otf), copy into our Epub + // Look for themes-book/pressbooks-book/fonts/*.ttf (or .otf), copy into our Epub - $my_font = realpath( PB_PLUGIN_DIR . $url ); - if ( $my_font ) { - copy( $my_font, "$path_to_epub_assets/$filename" ); - return "url(assets/$filename)"; - } - } elseif ( preg_match( '#^https?://#i', $url ) && preg_match( '/(' . $this->supportedFontExtensions . ')$/i', $url ) ) { + $my_font = realpath( PB_PLUGIN_DIR . $url ); + if ( $my_font ) { + copy( $my_font, "$path_to_epub_assets/$filename" ); + return "url(assets/$filename)"; + } + } elseif ( preg_match( '#^https?://#i', $url ) && preg_match( '/(' . $this->supportedFontExtensions . ')$/i', $url ) ) { - // Look for fonts via http(s), pull them in locally + // Look for fonts via http(s), pull them in locally - if ( $new_filename = $this->fetchAndSaveUniqueFont( $url, $path_to_epub_assets ) ) { - return "url(assets/$new_filename)"; + $new_filename = $this->fetchAndSaveUniqueFont( $url, $path_to_epub_assets ); + if ( $new_filename ) { + return "url(assets/$new_filename)"; + } } - } - return $matches[0]; // No change + return $matches[0]; // No change - }, $css ); + }, $css + ); // Overwrite the new file with new info file_put_contents( $path_to_copy_of_stylesheet, $css ); @@ -737,26 +745,27 @@ protected function createCover( $book_contents, $metadata ) { // Create file, insert into manifest - $vars = array( + $vars = [ 'post_title' => __( 'Cover', 'pressbooks' ), 'stylesheet' => $this->stylesheet, 'post_content' => $html, - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $file_id = 'front-cover'; $filename = "{$file_id}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => -1, 'post_title' => $vars['post_title'], 'filename' => $filename, - ); + ]; } @@ -772,16 +781,16 @@ protected function createBeforeTitle( $book_contents, $metadata ) { $front_matter_printf .= '
%s
%s'; $front_matter_printf .= '
'; - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $i = $this->frontMatterPos; - foreach ( array( 'before-title' ) as $compare ) { + foreach ( [ 'before-title' ] as $compare ) { foreach ( $book_contents['front-matter'] as $front_matter ) { if ( ! $front_matter['export'] ) { @@ -791,7 +800,7 @@ protected function createBeforeTitle( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( $compare != $subclass ) { + if ( $compare !== $subclass ) { continue; //Skip } @@ -800,26 +809,29 @@ protected function createBeforeTitle( $book_contents, $metadata ) { $content = $this->kneadHtml( $front_matter['post_content'], 'front-matter', $i ); $vars['post_title'] = $front_matter['post_title']; - $vars['post_content'] = sprintf( $front_matter_printf, + $vars['post_content'] = sprintf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, - '' ); + '' + ); $file_id = 'front-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => $front_matter['ID'], 'post_title' => $front_matter['post_title'], 'filename' => $filename, - ); + ]; ++$i; } @@ -846,7 +858,7 @@ protected function createTitle( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( 'title-page' != $subclass ) { + if ( 'title-page' !== $subclass ) { continue; // Skip } @@ -861,39 +873,40 @@ protected function createTitle( $book_contents, $metadata ) { $html .= $content; } else { $html .= sprintf( '

%s

', get_bloginfo( 'name' ) ); - $html .= sprintf( '

%s

', @$metadata['pb_subtitle'] ); - $html .= sprintf( '

%s

', @$metadata['pb_author'] ); - $html .= sprintf( '

%s

', @$metadata['pb_contributing_authors'] ); + $html .= sprintf( '

%s

', ( isset( $metadata['pb_subtitle'] ) ) ? $metadata['pb_subtitle'] : '' ); + $html .= sprintf( '

%s

', ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : '' ); + $html .= sprintf( '

%s

', ( isset( $metadata['pb_contributing_authors'] ) ) ? $metadata['pb_contributing_authors'] : '' ); if ( current_theme_supports( 'pressbooks_publisher_logo' ) ) { $html .= sprintf( '', get_theme_support( 'pressbooks_publisher_logo' )[0]['logo_uri'], __( 'Publisher Logo', 'pressbooks' ) ); // TODO: Support custom publisher logo. } - $html .= sprintf( '

%s

', @$metadata['pb_publisher'] ); - $html .= sprintf( '
%s
', @$metadata['pb_publisher_city'] ); + $html .= sprintf( '

%s

', ( isset( $metadata['pb_publisher'] ) ) ? $metadata['pb_publisher'] : '' ); + $html .= sprintf( '
%s
', ( isset( $metadata['pb_publisher_city'] ) ) ? $metadata['pb_publisher_city'] : '' ); } $html .= "\n"; // Create file, insert into manifest - $vars = array( + $vars = [ 'post_title' => __( 'Title Page', 'pressbooks' ), 'stylesheet' => $this->stylesheet, 'post_content' => $this->kneadHtml( $html, 'custom' ), - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $file_id = 'title-page'; $filename = "{$file_id}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => -1, 'post_title' => $vars['post_title'], 'filename' => $filename, - ); + ]; } @@ -905,9 +918,9 @@ protected function createTitle( $book_contents, $metadata ) { protected function createCopyright( $book_contents, $metadata ) { $options = get_option( 'pressbooks_theme_options_global' ); - foreach ( array( 'copyright_license' ) as $requiredGlobalOption ) { - if ( ! isset( $options[ $requiredGlobalOption ] ) ) { - $options[ $requiredGlobalOption ] = 0; + foreach ( [ 'copyright_license' ] as $required_global_option ) { + if ( ! isset( $options[ $required_global_option ] ) ) { + $options[ $required_global_option ] = 0; } } @@ -918,15 +931,16 @@ protected function createCopyright( $book_contents, $metadata ) { $html .= $this->kneadHtml( $this->tidy( $metadata['pb_custom_copyright'] ), 'custom' ); } - if ( 1 == $options['copyright_license'] ) { + if ( 1 === absint( $options['copyright_license'] ) ) { $html .= $this->kneadHtml( $this->tidy( $this->doCopyrightLicense( $metadata ) ), 'custom' ); } // default, so something is displayed - if ( empty( $metadata['pb_custom_copyright'] ) && 0 == $options['copyright_license'] ) { + if ( empty( $metadata['pb_custom_copyright'] ) && 0 === absint( $options['copyright_license'] ) ) { $html .= '

'; $html .= get_bloginfo( 'name' ) . ' ' . __( 'Copyright', 'pressbooks' ) . ' © '; $html .= ( ! empty( $metadata['pb_copyright_year'] ) ) ? $metadata['pb_copyright_year'] : date( 'Y' ); - if ( ! empty( $metadata['pb_copyright_holder'] ) ) { $html .= ' ' . __( 'by', 'pressbooks' ) . ' ' . $metadata['pb_copyright_holder'] . '. '; + if ( ! empty( $metadata['pb_copyright_holder'] ) ) { + $html .= ' ' . __( 'by', 'pressbooks' ) . ' ' . $metadata['pb_copyright_holder'] . '. '; } $html .= '

'; } @@ -942,26 +956,27 @@ protected function createCopyright( $book_contents, $metadata ) { // Create file, insert into manifest - $vars = array( + $vars = [ 'post_title' => __( 'Copyright', 'pressbooks' ), 'stylesheet' => $this->stylesheet, 'post_content' => $html, - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $file_id = 'copyright'; $filename = "{$file_id}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( - 'ID' => - 1, + $this->manifest[ $file_id ] = [ + 'ID' => -1, 'post_title' => $vars['post_title'], 'filename' => $filename, - ); + ]; } @@ -977,17 +992,17 @@ protected function createDedicationAndEpigraph( $book_contents, $metadata ) { $front_matter_printf .= '
%s
%s'; $front_matter_printf .= ''; - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $i = $this->frontMatterPos; $last_pos = false; - foreach ( array( 'dedication', 'epigraph' ) as $compare ) { + foreach ( [ 'dedication', 'epigraph' ] as $compare ) { foreach ( $book_contents['front-matter'] as $front_matter ) { if ( ! $front_matter['export'] ) { @@ -997,7 +1012,7 @@ protected function createDedicationAndEpigraph( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( $compare != $subclass ) { + if ( $compare !== $subclass ) { continue; //Skip } @@ -1006,33 +1021,37 @@ protected function createDedicationAndEpigraph( $book_contents, $metadata ) { $content = $this->kneadHtml( $front_matter['post_content'], 'front-matter', $i ); $vars['post_title'] = $front_matter['post_title']; - $vars['post_content'] = sprintf( $front_matter_printf, + $vars['post_content'] = sprintf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, - '' ); + '' + ); $file_id = 'front-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => $front_matter['ID'], 'post_title' => $front_matter['post_title'], 'filename' => $filename, - ); + ]; ++$i; $last_pos = $i; } } $this->frontMatterPos = $i; - if ( $last_pos ) { $this->frontMatterLastPos = $last_pos - 1; + if ( $last_pos ) { + $this->frontMatterLastPos = $last_pos - 1; } } @@ -1048,14 +1067,14 @@ protected function createFrontMatter( $book_contents, $metadata ) { $front_matter_printf .= '
%s
%s'; $front_matter_printf .= ''; - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_front_matter_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $i = $this->frontMatterPos; foreach ( $book_contents['front-matter'] as $front_matter ) { @@ -1067,11 +1086,11 @@ protected function createFrontMatter( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( 'dedication' == $subclass || 'epigraph' == $subclass || 'title-page' == $subclass || 'before-title' == $subclass ) { + if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } - if ( 'introduction' == $subclass ) { + if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } @@ -1083,7 +1102,7 @@ protected function createFrontMatter( $book_contents, $metadata ) { $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = trim( get_post_meta( $front_matter_id, 'pb_section_author', true ) ); - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $front_matter_id ); if ( $sections ) { @@ -1104,27 +1123,30 @@ protected function createFrontMatter( $book_contents, $metadata ) { } $vars['post_title'] = $front_matter['post_title']; - $vars['post_content'] = sprintf( $front_matter_printf, + $vars['post_content'] = sprintf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, $var['append_front_matter_content'] = $append_front_matter_content, - '' ); + '' + ); $file_id = 'front-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => $front_matter['ID'], 'post_title' => $front_matter['post_title'], 'filename' => $filename, - ); + ]; ++$i; } @@ -1145,23 +1167,24 @@ protected function createPromo( $book_contents, $metadata ) { $file_id = 'pressbooks-promo'; $filename = "{$file_id}.{$this->filext}"; - $vars = array( + $vars = [ 'post_title' => __( 'Make your own books using Pressbooks.com', 'pressbooks' ), 'stylesheet' => $this->stylesheet, 'post_content' => $this->kneadHtml( $promo_html, 'custom' ), - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => -1, 'post_title' => $vars['post_title'], 'filename' => $filename, - ); + ]; } } @@ -1181,20 +1204,20 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $chapter_printf .= '
%s
%s'; $chapter_printf .= ''; - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_chapter_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; // Parts, Chapters $i = $j = $c = $p = 1; foreach ( $book_contents['part'] as $part ) { - $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) == 'on' ) ? 'invisible' : ''; + $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $array_pos = count( $this->manifest ); @@ -1230,7 +1253,7 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $subtitle = trim( get_post_meta( $chapter_id, 'pb_subtitle', true ) ); $author = trim( get_post_meta( $chapter_id, 'pb_section_author', true ) ); - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $chapter_id ); if ( $sections ) { @@ -1256,7 +1279,7 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $this->hasIntroduction = true; } - $n = ( 'numberless' == $subclass ) ? '' : $c; + $n = ( 'numberless' === $subclass ) ? '' : $c; $vars['post_title'] = $chapter['post_title']; $vars['post_content'] = sprintf( ( $chapter_printf_changed ? $chapter_printf_changed : $chapter_printf ), @@ -1277,11 +1300,11 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => $chapter['ID'], 'post_title' => $chapter['post_title'], 'filename' => $filename, - ); + ]; $has_chapters = true; @@ -1292,9 +1315,9 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { } } - if ( count( $book_contents['part'] ) == 1 && $part_content ) { // only part, has content + if ( count( $book_contents['part'] ) === 1 && $part_content ) { // only part, has content $slug = $part['post_name']; - $m = ( 'invisible' == $invisibility ) ? '' : $p; + $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), @@ -1302,7 +1325,8 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), - $part_content ); + $part_content + ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; @@ -1313,21 +1337,22 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { ); // Insert into correct pos - $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + array( - $file_id => array( - 'ID' => $part['ID'], - 'post_title' => $part['post_title'], - 'filename' => $filename, - ), - ) + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); + $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + [ + $file_id => [ + 'ID' => $part['ID'], + 'post_title' => $part['post_title'], + 'filename' => $filename, + ], + ] + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); ++$i; - if ( 'invisible' !== $invisibility ) { ++$p; + if ( 'invisible' !== $invisibility ) { + ++$p; } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( $has_chapters ) { // has chapter $slug = $part['post_name']; - $m = ( 'invisible' == $invisibility ) ? '' : $p; + $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), @@ -1335,31 +1360,34 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), - $part_content ); + $part_content + ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); // Insert into correct pos - $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + array( - $file_id => array( - 'ID' => $part['ID'], - 'post_title' => $part['post_title'], - 'filename' => $filename, - ), - ) + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); + $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + [ + $file_id => [ + 'ID' => $part['ID'], + 'post_title' => $part['post_title'], + 'filename' => $filename, + ], + ] + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); ++$i; - if ( 'invisible' !== $invisibility ) { ++$p; + if ( 'invisible' !== $invisibility ) { + ++$p; } } else { // no chapter if ( $part_content ) { // has content $slug = $part['post_name']; - $m = ( 'invisible' == $invisibility ) ? '' : $p; + $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), @@ -1367,23 +1395,25 @@ protected function createPartsAndChapters( $book_contents, $metadata ) { $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), - $part_content ); + $part_content + ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); // Insert into correct pos - $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + array( - $file_id => array( - 'ID' => $part['ID'], - 'post_title' => $part['post_title'], - 'filename' => $filename, - ), - ) + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); + $this->manifest = array_slice( $this->manifest, 0, $array_pos, true ) + [ + $file_id => [ + 'ID' => $part['ID'], + 'post_title' => $part['post_title'], + 'filename' => $filename, + ], + ] + array_slice( $this->manifest, $array_pos, count( $this->manifest ) - 1, true ); ++$i; if ( 'invisible' !== $invisibility ) { @@ -1412,14 +1442,14 @@ protected function createBackMatter( $book_contents, $metadata ) { $back_matter_printf .= '
%s
%s'; $back_matter_printf .= ''; - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_back_matter_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $i = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { @@ -1438,7 +1468,7 @@ protected function createBackMatter( $book_contents, $metadata ) { $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = trim( get_post_meta( $back_matter_id, 'pb_section_author', true ) ); - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $back_matter_id ); if ( $sections ) { @@ -1459,27 +1489,30 @@ protected function createBackMatter( $book_contents, $metadata ) { } $vars['post_title'] = $back_matter['post_title']; - $vars['post_content'] = sprintf( $back_matter_printf, + $vars['post_content'] = sprintf( + $back_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, $var['append_back_matter_content'] = $append_back_matter_content, - '' ); + '' + ); $file_id = 'back-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); - $this->manifest[ $file_id ] = array( + $this->manifest[ $file_id ] = [ 'ID' => $back_matter['ID'], 'post_title' => $back_matter['post_title'], 'filename' => $filename, - ); + ]; ++$i; } @@ -1495,18 +1528,18 @@ protected function createBackMatter( $book_contents, $metadata ) { */ protected function createToc( $book_contents, $metadata ) { - $vars = array( + $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', - 'isbn' => @$metadata['pb_ebook_isbn'], + 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, - ); + ]; $options = get_option( 'pressbooks_theme_options_global' ); - foreach ( array( 'copyright_license' ) as $requiredGlobalOption ) { - if ( ! isset( $options[ $requiredGlobalOption ] ) ) { - $options[ $requiredGlobalOption ] = 0; + foreach ( [ 'copyright_license' ] as $required_global_option ) { + if ( ! isset( $options[ $required_global_option ] ) ) { + $options[ $required_global_option ] = 0; } } @@ -1517,13 +1550,13 @@ protected function createToc( $book_contents, $metadata ) { $filename = "{$file_id}.{$this->filext}"; $vars['post_title'] = __( 'Table Of Contents', 'pressbooks' ); - $this->manifest = array_slice( $this->manifest, 0, $array_pos + 1, true ) + array( - $file_id => array( - 'ID' => - 1, - 'post_title' => $vars['post_title'], - 'filename' => $filename, - ), - ) + array_slice( $this->manifest, $array_pos + 1, count( $this->manifest ) - 1, true ); + $this->manifest = array_slice( $this->manifest, 0, $array_pos + 1, true ) + [ + $file_id => [ + 'ID' => -1, + 'post_title' => $vars['post_title'], + 'filename' => $filename, + ], + ] + array_slice( $this->manifest, $array_pos + 1, count( $this->manifest ) - 1, true ); // HTML @@ -1548,7 +1581,7 @@ protected function createToc( $book_contents, $metadata ) { $license = ( $options['copyright_license'] ) ? get_post_meta( $v['ID'], 'pb_section_license', true ) : ''; } elseif ( preg_match( '/^part-/', $k ) ) { $class = 'part'; - if ( get_post_meta( $v['ID'], 'pb_part_invisible', true ) == 'on' ) { + if ( get_post_meta( $v['ID'], 'pb_part_invisible', true ) === 'on' ) { $class .= ' display-none'; } else { $title = ( $this->numbered ? __( 'Part', 'pressbooks' ) . ' ' . \Pressbooks\L10n\romanize( $m ) . '. ' : '' ) . $title; @@ -1592,7 +1625,7 @@ protected function createToc( $book_contents, $metadata ) { $html .= ''; - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $v['ID'] ); if ( $sections ) { $html .= '
    '; @@ -1607,7 +1640,8 @@ protected function createToc( $book_contents, $metadata ) { ++$li_count; } - if ( 0 == $li_count ) { $html .= '
  • '; + if ( 0 === $li_count ) { + $html .= '
  • '; } $html .= "
\n"; @@ -1617,7 +1651,8 @@ protected function createToc( $book_contents, $metadata ) { file_put_contents( $this->tmpDir . "/OEBPS/$filename", - $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); + $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) + ); } @@ -1631,14 +1666,15 @@ protected function positionOfToc() { $search = array_keys( $this->manifest ); - if ( false == $this->frontMatterLastPos ) { + if ( false === $this->frontMatterLastPos ) { - $array_pos = array_search( 'copyright', $search ); - if ( false === $array_pos ) { $array_pos = - 1; + $array_pos = array_search( 'copyright', $search, true ); + if ( false === $array_pos ) { + $array_pos = -1; } } else { - $array_pos = - 1; + $array_pos = -1; $preg = '/^front-matter-' . sprintf( '%03s', $this->frontMatterLastPos ) . '$/'; foreach ( $search as $key => $val ) { if ( preg_match( $preg, $val ) ) { @@ -1683,6 +1719,7 @@ protected function kneadHtml( $html, $type, $pos = 0 ) { $xpath = new \DOMXPath( $doc ); while ( ( $nodes = $xpath->query( '//*[not(text() or node() or self::br or self::hr or self::img)]' ) ) && $nodes->length > 0 ) { foreach ( $nodes as $node ) { + /** @var \DOMElement $node */ $node->appendChild( new \DOMText( '' ) ); } } @@ -1690,6 +1727,7 @@ protected function kneadHtml( $html, $type, $pos = 0 ) { // Remove srcset attributes because responsive images aren't a thing in the EPUB world. $srcsets = $xpath->query( '//img[@srcset]' ); foreach ( $srcsets as $srcset ) { + /** @var \DOMElement $srcset */ $srcset->removeAttribute( 'srcset' ); } @@ -1698,7 +1736,7 @@ protected function kneadHtml( $html, $type, $pos = 0 ) { $html = $doc->saveXML( $doc->documentElement ); // Remove auto-created and tags. - $html = preg_replace( '/^/', '', str_replace( array( '', '', '', '' ), array( '', '', '', '' ), $html ) ); + $html = preg_replace( '/^/', '', str_replace( [ '', '', '', '' ], [ '', '', '', '' ], $html ) ); // Mobi7 hacks $html = $this->transformXML( $utf8_hack . "$html", $this->dir . '/templates/epub201/mobi-hacks.xsl' ); @@ -1723,6 +1761,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $url = $image->getAttribute( 'src' ); $filename = $this->fetchAndSaveUniqueImage( $url, $fullpath ); @@ -1754,7 +1793,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { return $this->fetchedImageCache[ $url ]; } - $response = \Pressbooks\Utility\remote_get_retry( $url, array( 'timeout' => $this->timeout ) ); + $response = \Pressbooks\Utility\remote_get_retry( $url, [ 'timeout' => $this->timeout ] ); // WordPress error? if ( is_wp_error( $response ) ) { @@ -1769,7 +1808,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { $url = 'http:' . $url; } } - $response = wp_remote_get( $url, array( 'timeout' => $this->timeout ) ); + $response = wp_remote_get( $url, [ 'timeout' => $this->timeout ] ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } @@ -1786,7 +1825,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { $filename = explode( '?', basename( $url ) ); // isolate latex image service from WP, add file extension - if ( 's.wordpress.com' == parse_url( $url, PHP_URL_HOST ) && 'latex.php' == $filename[0] ) { + if ( 's.wordpress.com' === parse_url( $url, PHP_URL_HOST ) && 'latex.php' === $filename[0] ) { $filename = md5( array_pop( $filename ) ); // content-type = 'image/png' $type = explode( '/', $response['headers']['content-type'] ); @@ -1816,7 +1855,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); - } elseif ( md5( file_get_contents( $tmp_file ) ) != md5( file_get_contents( "$fullpath/$filename" ) ) ) { + } elseif ( md5( file_get_contents( $tmp_file ) ) !== md5( file_get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } @@ -1841,11 +1880,11 @@ protected function fetchAndSaveUniqueFont( $url, $fullpath ) { return $this->fetchedFontCache[ $url ]; } - $response = wp_remote_get( $url, array( 'timeout' => $this->timeout ) ); + $response = wp_remote_get( $url, [ 'timeout' => $this->timeout ] ); // WordPress error? if ( is_wp_error( $response ) ) { - // TODO: handle $response->get_error_message(); + // TODO: Properly handle errors returned via $response->get_error_message(); $this->fetchedFontCache[ $url ] = ''; return ''; } @@ -1866,7 +1905,7 @@ protected function fetchAndSaveUniqueFont( $url, $fullpath ) { // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); - } elseif ( md5( file_get_contents( $tmp_file ) ) != md5( file_get_contents( "$fullpath/$filename" ) ) ) { + } elseif ( md5( file_get_contents( $tmp_file ) ) !== md5( file_get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } @@ -1880,6 +1919,7 @@ protected function fetchAndSaveUniqueFont( $url, $fullpath ) { * Do nothing * * @param \DOMDocument $doc + * * @return \DOMDocument */ protected function scrapeAndKneadMedia( \DOMDocument $doc ) { @@ -1899,7 +1939,7 @@ protected function kneadHref( \DOMDocument $doc, $type, $pos ) { $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $url ) { - + /** @var \DOMElement $url */ $current_url = '' . $url->getAttribute( 'href' ); // Stringify // Don't touch empty urls @@ -1911,12 +1951,14 @@ protected function kneadHref( \DOMDocument $doc, $type, $pos ) { // For example: // This causes an EPUB validation error of: hyperlink to non-standard resource ( of type 'image/...' ) // We fix this by removing the href - if ( $url->childNodes->length ) { foreach ( $url->childNodes as $node ) { - if ( 'img' == $node->nodeName && $this->fuzzyImageNameMatch( $current_url, $node->getAttribute( 'src' ) ) ) { + if ( $url->childNodes->length ) { + foreach ( $url->childNodes as $node ) { + /** @var \DOMElement $node */ + if ( 'img' === $node->nodeName && $this->fuzzyImageNameMatch( $current_url, $node->getAttribute( 'src' ) ) ) { $url->removeAttribute( 'href' ); continue 2; } - } + } } // Determine if we are trying to link to our own internal content @@ -1927,7 +1969,7 @@ protected function kneadHref( \DOMDocument $doc, $type, $pos ) { } // Canonicalize, fix typos, remove garbage - if ( '#' != @$current_url[0] ) { + if ( isset( $current_url[0] ) && '#' !== $current_url[0] ) { $url->setAttribute( 'href', \Pressbooks\Sanitize\canonicalize_url( $current_url ) ); } } @@ -1959,7 +2001,7 @@ protected function fuzzyImageNameMatch( $file1, $file2 ) { $file2 = explode( '.', $file2 ); $ext2 = strtolower( end( $file2 ) ); - if ( $ext1 != $ext2 ) { + if ( $ext1 !== $ext2 ) { return false; } @@ -1971,7 +2013,7 @@ protected function fuzzyImageNameMatch( $file1, $file2 ) { $pre2 = explode( '-', $file2[0] ); $pre2 = strtolower( $pre2[0] ); - if ( $pre1 != $pre2 ) { + if ( $pre1 !== $pre2 ) { return false; } @@ -1997,22 +2039,23 @@ protected function fuzzyHrefMatch( $url, $type, $pos ) { $url = rtrim( $url, '/' ); $domain = parse_url( $url ); - $domain = @$domain['host']; + $domain = ( isset( $domain['host'] ) ) ? $domain['host'] : false; if ( $domain ) { $domain2 = parse_url( wp_guess_url() ); - if ( @$domain2['host'] != $domain ) { + $domain2 = ( isset( $domain2['host'] ) ) ? $domain2['host'] : false; + if ( $domain2 !== $domain ) { return false; // If there is a domain name and it =/= ours, bail. } } $last_part = explode( '/', $url ); $last_pos = count( $last_part ) - 1; - $posttype = @$last_part[ $last_pos - 1 ]; + $posttype = ( isset( $last_part[ $last_pos - 1 ] ) ) ? $last_part[ $last_pos - 1 ] : false; $anchor = ''; // Look for #anchors - if ( $last_pos > 0 && '#' == substr( trim( $last_part[ $last_pos ] ), 0, 1 ) ) { + if ( $last_pos > 0 && '#' === substr( trim( $last_part[ $last_pos ] ), 0, 1 ) ) { $anchor = trim( $last_part[ $last_pos ] ); $last_part = trim( $last_part[ $last_pos - 1 ] ); } elseif ( false !== strpos( $last_part[ $last_pos ], '#' ) ) { @@ -2030,22 +2073,26 @@ protected function fuzzyHrefMatch( $url, $type, $pos ) { $lookup = \Pressbooks\Book::getBookStructure(); if ( 'part' !== $posttype && ! isset( $lookup['__export_lookup'][ $last_part ] ) ) { return false; - } elseif ( 'part' !== $posttype && isset( $lookup['__export_lookup'][ $last_part ] ) ) { + } + + $new_url = ''; + if ( 'part' !== $posttype && isset( $lookup['__export_lookup'][ $last_part ] ) ) { // Handle front/back matter and chapters $new_type = $lookup['__export_lookup'][ $last_part ]; $new_pos = 0; foreach ( $lookup['__export_lookup'] as $p => $t ) { - if ( $t == $new_type ) { ++$new_pos; + if ( $t === $new_type ) { + ++$new_pos; } - if ( $p == $last_part ) { break; + if ( $p === $last_part ) { + break; } } $new_url = "$new_type-" . sprintf( '%03s', $new_pos ) . "-$last_part.{$this->filext}"; - } elseif ( 'part' == $posttype && ! isset( $lookup['__export_lookup'][ $last_part ] ) ) { + } elseif ( 'part' === $posttype && ! isset( $lookup['__export_lookup'][ $last_part ] ) ) { // Handle parts - $new_type = 'part'; foreach ( $lookup['part'] as $key => $part ) { - if ( $part['post_name'] == $last_part ) { + if ( $part['post_name'] === $last_part ) { $new_url = 'part-' . sprintf( '%03s', $key + 1 ) . "-$last_part.{$this->filext}"; } } @@ -2074,12 +2121,12 @@ protected function createOPF( $book_contents, $metadata ) { } // Vars - $vars = array( + $vars = [ 'meta' => $metadata, 'manifest' => $this->manifest, 'stylesheet' => $this->stylesheet, 'lang' => $this->lang, - ); + ]; $vars['manifest_assets'] = $this->buildManifestAssetsHtml(); @@ -2102,13 +2149,14 @@ protected function buildManifestAssetsHtml() { $html = ''; $path_to_assets = $this->tmpDir . '/OEBPS/assets'; $assets = scandir( $path_to_assets ); - $used_ids = array(); + $used_ids = []; foreach ( $assets as $asset ) { - if ( '.' == $asset || '..' == $asset ) { continue; + if ( '.' === $asset || '..' === $asset ) { + continue; } $mimetype = $this->mediaType( "$path_to_assets/$asset" ); - if ( $this->coverImage == $asset ) { + if ( $this->coverImage === $asset ) { $file_id = 'cover-image'; } else { $file_id = 'media-' . pathinfo( "$path_to_assets/$asset", PATHINFO_FILENAME ); @@ -2117,9 +2165,11 @@ protected function buildManifestAssetsHtml() { // Check if a media id has already been used, if so give it a new one $check_if_used = $file_id; - for ( $i = 2; $i <= 999; $i ++ ) { - if ( empty( $used_ids[ $check_if_used ] ) ) { break; - } else { $check_if_used = $file_id . "-$i"; + for ( $i = 2; $i <= 999; $i++ ) { + if ( empty( $used_ids[ $check_if_used ] ) ) { + break; + } else { + $check_if_used = $file_id . "-$i"; } } $file_id = $check_if_used; @@ -2147,13 +2197,13 @@ protected function createNCX( $book_contents, $metadata ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEPBS() ?' ); } - $vars = array( - 'author' => @$metadata['pb_author'], + $vars = [ + 'author' => ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : '', 'manifest' => $this->manifest, 'dtd_uid' => ( ! empty( $metadata['pb_ebook_isbn'] ) ? $metadata['pb_ebook_isbn'] : get_bloginfo( 'url' ) ), 'enable_external_identifier' => true, 'lang' => $this->lang, - ); + ]; file_put_contents( $this->tmpDir . '/toc.ncx', diff --git a/includes/modules/export/epub/class-pb-epub3.php b/inc/modules/export/epub/class-epub3.php similarity index 82% rename from includes/modules/export/epub/class-pb-epub3.php rename to inc/modules/export/epub/class-epub3.php index 69567545c8..64b6954462 100644 --- a/includes/modules/export/epub/class-pb-epub3.php +++ b/inc/modules/export/epub/class-epub3.php @@ -9,15 +9,12 @@ use Pressbooks\Sanitize; -require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' ); - - class Epub3 extends Epub201 { /** * @var array */ - protected $fetchedMediaCache = array(); + protected $fetchedMediaCache = []; /** * @var string @@ -46,111 +43,111 @@ class Epub3 extends Epub201 { * * @var array */ - protected $MathMLTags = array( + protected $MathMLTags = [ 'math', - 'maction', - 'maligngroup', - 'malignmark', - 'menclose', - 'merror', - 'mfenced', - 'mfrac', - 'mglyph', - 'mi', - 'mlabeledtr', + 'maction', + 'maligngroup', + 'malignmark', + 'menclose', + 'merror', + 'mfenced', + 'mfrac', + 'mglyph', + 'mi', + 'mlabeledtr', 'mlongdiv', - 'mmultiscripts', - 'mn', - 'mo', - 'mover', - 'mpadded', - 'mphantom', - 'mroot', - 'mrow', - 'ms', - 'mscarries', - 'mscarry', + 'mmultiscripts', + 'mn', + 'mo', + 'mover', + 'mpadded', + 'mphantom', + 'mroot', + 'mrow', + 'ms', + 'mscarries', + 'mscarry', 'msgroup', - 'msline', - 'mspace', - 'msqrt', - 'msrow', - 'mstack', - 'mstyle', - 'msub', - 'msup', - 'msubsup', - 'mtable', - 'mtd', + 'msline', + 'mspace', + 'msqrt', + 'msrow', + 'mstack', + 'mstyle', + 'msub', + 'msup', + 'msubsup', + 'mtable', + 'mtd', 'mtext', - 'mtr', - 'munder', - 'munderover', - 'semantics', - 'annotation', - 'annotation-xml', - ); + 'mtr', + 'munder', + 'munderover', + 'semantics', + 'annotation', + 'annotation-xml', + ]; /** * JavaScript Events * * @var array */ - protected $javaScriptEvents = array( + protected $javaScriptEvents = [ 'onabort', - 'onblur', - 'oncanplay', - 'oncanplaythrough', - 'onchange', - 'onclick', - 'oncontextmenu', - 'ondblclick', + 'onblur', + 'oncanplay', + 'oncanplaythrough', + 'onchange', + 'onclick', + 'oncontextmenu', + 'ondblclick', 'ondrag', - 'ondragend', - 'ondragenter', - 'ondragleave', - 'ondragover', - 'ondragstart', - 'ondrop', - 'ondurationchange', + 'ondragend', + 'ondragenter', + 'ondragleave', + 'ondragover', + 'ondragstart', + 'ondrop', + 'ondurationchange', 'onemptied', - 'onended', - 'onerror', - 'onfocus', - 'oninput', - 'oninvalid', - 'onkeydown', - 'onkeypress', - 'onkeyup', + 'onended', + 'onerror', + 'onfocus', + 'oninput', + 'oninvalid', + 'onkeydown', + 'onkeypress', + 'onkeyup', 'onload', - 'onloadeddata', - 'onloadedmetadata', - 'onloadstart', - 'onmousedown', - 'onmousemove', - 'onmouseout', + 'onloadeddata', + 'onloadedmetadata', + 'onloadstart', + 'onmousedown', + 'onmousemove', + 'onmouseout', 'onmouseover', - 'onmouseup', - 'onmousewheel', - 'onpause', - 'onplay', - 'onplaying', - 'onprogress', - 'onratechange', + 'onmouseup', + 'onmousewheel', + 'onpause', + 'onplay', + 'onplaying', + 'onprogress', + 'onratechange', 'onreadystatechange', - 'onreset', - 'onscroll', - 'onseeked', - 'onseeking', - 'onselect', - 'onshow', - 'onstalled', + 'onreset', + 'onscroll', + 'onseeked', + 'onseeking', + 'onselect', + 'onshow', + 'onstalled', 'onsubmit', - 'onsuspend', - 'ontimeupdate', - 'onvolumechange', - 'onwaiting', - ); + 'onsuspend', + 'ontimeupdate', + 'onvolumechange', + 'onwaiting', + ]; /** * Create $this->outputPath @@ -169,13 +166,14 @@ function convert() { * Check for existence of properties attributes * * @param string $html_file + * * @return array $properties * @throws \Exception - */ + */ protected function getProperties( $html_file ) { $html = file_get_contents( $html_file ); - $properties = array(); + $properties = []; if ( empty( $html ) ) { throw new \Exception( 'File contents empty for getProperties' ); @@ -231,7 +229,7 @@ protected function isScripted( $html ) { $doc->loadHTML( $html ); foreach ( $doc->getElementsByTagname( '*' ) as $element ) { foreach ( iterator_to_array( $element->attributes ) as $name => $attribute ) { - if ( in_array( $name, $this->javaScriptEvents ) ) { + if ( in_array( $name, $this->javaScriptEvents, true ) ) { return true; } } @@ -267,15 +265,15 @@ protected function tidy( $html ) { // + http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/beta/htmLawed_README.htm // + http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm - $config = array( + $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_epub3', - 'tidy' => - 1, + 'tidy' => -1, 'make_tag_strict' => 2, 'comment' => 1, - ); + ]; $spec = ''; $spec .= 'a=,-charset,-coords,-rev,-shape;'; @@ -316,6 +314,7 @@ protected function tidy( $html ) { * * @param string $url * @param string $fullpath + * * @return string|array */ protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { @@ -324,7 +323,7 @@ protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { return $this->fetchedMediaCache[ $url ]; } - $response = wp_remote_get( $url, array( 'timeout' => $this->timeout ) ); + $response = wp_remote_get( $url, [ 'timeout' => $this->timeout ] ); // WordPress error? if ( is_wp_error( $response ) ) { @@ -339,7 +338,7 @@ protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { $url = 'http:' . $url; } } - $response = wp_remote_get( $url, array( 'timeout' => $this->timeout ) ); + $response = wp_remote_get( $url, [ 'timeout' => $this->timeout ] ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } @@ -369,7 +368,7 @@ protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); - } elseif ( md5( file_get_contents( $tmp_file ) ) != md5( file_get_contents( "$fullpath/$filename" ) ) ) { + } elseif ( md5( file_get_contents( $tmp_file ) ) !== md5( file_get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } @@ -383,19 +382,20 @@ protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { * into /OEBPS/assets/, return the HTML with changed 'src' paths. * * @param \DOMDocument $doc + * * @return \DOMDocument */ protected function scrapeAndKneadMedia( \DOMDocument $doc ) { $fullpath = $this->tmpDir . '/OEBPS/assets'; - $tags = array( 'source', 'audio', 'video' ); + $tags = [ 'source', 'audio', 'video' ]; foreach ( $tags as $tag ) { $sources = $doc->getElementsByTagName( $tag ); foreach ( $sources as $source ) { - - if ( $source->getAttribute( 'src' ) != '' ) { + /** @var $source \DOMElement */ + if ( ! empty( $source->getAttribute( 'src' ) ) ) { // Fetch the audio file $url = $source->getAttribute( 'src' ); $filename = $this->fetchAndSaveUniqueMedia( $url, $fullpath ); @@ -428,12 +428,12 @@ protected function createOPF( $book_contents, $metadata ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEPBS() ?' ); } - $vars = array( + $vars = [ 'meta' => $metadata, 'manifest' => $this->manifest, 'stylesheet' => $this->stylesheet, 'lang' => $this->lang, - ); + ]; $vars['manifest_assets'] = $this->buildManifestAssetsHtml(); @@ -473,13 +473,13 @@ protected function createNCX( $book_contents, $metadata ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEPBS() ?' ); } - $vars = array( - 'author' => @$metadata['pb_author'], + $vars = [ + 'author' => ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : '', 'manifest' => $this->manifest, 'dtd_uid' => ( ! empty( $metadata['pb_ebook_isbn'] ) ? $metadata['pb_ebook_isbn'] : get_bloginfo( 'url' ) ), 'enable_external_identifier' => false, 'lang' => $this->lang, - ); + ]; file_put_contents( $this->tmpDir . '/toc.xhtml', @@ -504,16 +504,16 @@ protected function createNCX( $book_contents, $metadata ) { * @return string * @throws \Exception */ - protected function loadTemplate( $path, array $vars = array() ) { + protected function loadTemplate( $path, array $vars = [] ) { $search = '/templates/epub201/'; $replace = '/templates/epub3/'; $pos = strpos( $path, $search ); if ( false !== $pos ) { - $newPath = substr_replace( $path, $replace, $pos, strlen( $search ) ); - if ( file_exists( $newPath ) ) { - $path = $newPath; + $new_path = substr_replace( $path, $replace, $pos, strlen( $search ) ); + if ( file_exists( $new_path ) ) { + $path = $new_path; } } diff --git a/includes/modules/export/epub/templates/epub201/container.php b/inc/modules/export/epub/templates/epub201/container.php similarity index 77% rename from includes/modules/export/epub/templates/epub201/container.php rename to inc/modules/export/epub/templates/epub201/container.php index 67fb65bfcf..e084d0622d 100644 --- a/includes/modules/export/epub/templates/epub201/container.php +++ b/inc/modules/export/epub/templates/epub201/container.php @@ -1,6 +1,6 @@ - diff --git a/includes/modules/export/epub/templates/epub201/ibooks.php b/inc/modules/export/epub/templates/epub201/ibooks.php similarity index 71% rename from includes/modules/export/epub/templates/epub201/ibooks.php rename to inc/modules/export/epub/templates/epub201/ibooks.php index 8932bba61e..c2f4e98352 100644 --- a/includes/modules/export/epub/templates/epub201/ibooks.php +++ b/inc/modules/export/epub/templates/epub201/ibooks.php @@ -1,6 +1,6 @@ $v ) { - if ( true == $part_open && ! preg_match( '/^chapter-/', $k ) ) { + if ( true === $part_open && ! preg_match( '/^chapter-/', $k ) ) { $part_open = false; echo ''; } @@ -69,7 +69,7 @@ } } - if ( true == $part_open ) { + if ( true === $part_open ) { echo ''; } ?> diff --git a/includes/modules/export/epub/templates/epub201/opf.php b/inc/modules/export/epub/templates/epub201/opf.php similarity index 94% rename from includes/modules/export/epub/templates/epub201/opf.php rename to inc/modules/export/epub/templates/epub201/opf.php index eb31fede27..72b9e55687 100644 --- a/includes/modules/export/epub/templates/epub201/opf.php +++ b/inc/modules/export/epub/templates/epub201/opf.php @@ -1,6 +1,6 @@ \n"; + // TODO: There should be default behaviour? E.g. echo "\n"; break; } } - // Required (for Kindle), Cover + // Required for Kindle: Cover Image echo '' . "\n"; ?> @@ -156,7 +156,7 @@ // If nothing was found, set « the first page after the table of contents » as start point if ( false === $start_key ) { $keys = array_keys( $manifest ); - $position = array_search( 'table-of-contents', $keys ); + $position = array_search( 'table-of-contents', $keys, true ); if ( isset( $keys[ $position + 1 ] ) ) { $start_key = $keys[ $position + 1 ]; } diff --git a/includes/modules/export/epub/templates/epub3/css/css3.css b/inc/modules/export/epub/templates/epub3/css/css3.css similarity index 100% rename from includes/modules/export/epub/templates/epub3/css/css3.css rename to inc/modules/export/epub/templates/epub3/css/css3.css diff --git a/includes/modules/export/epub/templates/epub3/html.php b/inc/modules/export/epub/templates/epub3/html.php similarity index 85% rename from includes/modules/export/epub/templates/epub3/html.php rename to inc/modules/export/epub/templates/epub3/html.php index bfb2305df9..acfd8ec18e 100644 --- a/includes/modules/export/epub/templates/epub3/html.php +++ b/inc/modules/export/epub/templates/epub3/html.php @@ -1,6 +1,6 @@ - diff --git a/includes/modules/export/epub/templates/epub3/opf.php b/inc/modules/export/epub/templates/epub3/opf.php similarity index 93% rename from includes/modules/export/epub/templates/epub3/opf.php rename to inc/modules/export/epub/templates/epub3/opf.php index c0f91cb0d3..bf44513bdc 100644 --- a/includes/modules/export/epub/templates/epub3/opf.php +++ b/inc/modules/export/epub/templates/epub3/opf.php @@ -1,6 +1,6 @@ '; if ( ! empty( $meta['pb_author_file_as'] ) ) { echo $meta['pb_author_file_as']; - } else if ( ! empty( $meta['pb_author'] ) ) { + } elseif ( ! empty( $meta['pb_author'] ) ) { echo $meta['pb_author']; } else { echo 'Authored by: ' . get_bloginfo( 'url' ); @@ -101,7 +101,7 @@ case 'pb_publication_date' : echo ''; - echo date( 'Y-m-d', ( int ) $val ); + echo date( 'Y-m-d', (int) $val ); echo "\n"; break; @@ -113,12 +113,12 @@ break; default: - // TODO: echo "\n"; + // TODO: There should be default behaviour? E.g. echo "\n"; break; } } - // Required (for Kindle), Cover + // Required for Kindle: Cover Image echo '' . "\n"; ?> @@ -167,7 +167,7 @@ // If nothing was found, set « the first page after the table of contents » as start point if ( false === $start_key ) { $keys = array_keys( $manifest ); - $position = array_search( 'table-of-contents', $keys ); + $position = array_search( 'table-of-contents', $keys, true ); if ( isset( $keys[ $position + 1 ] ) ) { $start_key = $keys[ $position + 1 ]; } diff --git a/includes/modules/export/epub/templates/epub3/toc.php b/inc/modules/export/epub/templates/epub3/toc.php similarity index 87% rename from includes/modules/export/epub/templates/epub3/toc.php rename to inc/modules/export/epub/templates/epub3/toc.php index 11e09afddf..d52a575d6c 100644 --- a/includes/modules/export/epub/templates/epub3/toc.php +++ b/inc/modules/export/epub/templates/epub3/toc.php @@ -1,6 +1,6 @@ <?php bloginfo( 'name' ); ?> - @@ -27,7 +27,7 @@ $part_open = false; foreach ( $manifest as $k => $v ) { - if ( true == $part_open && ! preg_match( '/^chapter-/', $k ) ) { + if ( true === $part_open && ! preg_match( '/^chapter-/', $k ) ) { $part_open = false; echo '' . "\n"; } @@ -49,7 +49,7 @@ } } } - if ( true == $part_open ) { + if ( true === $part_open ) { echo '' . "\n"; } ?> diff --git a/includes/modules/export/indesign/class-pb-icml.php b/inc/modules/export/indesign/class-icml.php similarity index 93% rename from includes/modules/export/indesign/class-pb-icml.php rename to inc/modules/export/indesign/class-icml.php index 4c8090308c..7bfcbb69e4 100644 --- a/includes/modules/export/indesign/class-pb-icml.php +++ b/inc/modules/export/indesign/class-icml.php @@ -3,13 +3,11 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Export\InDesign; +namespace Pressbooks\Modules\Export\InDesign; use Pressbooks\Modules\Export\Export; - - class Icml extends Export { @@ -35,10 +33,10 @@ function convert() { // Create ICML - $vars = array( + $vars = [ 'meta' => \Pressbooks\Book::getBookInformation(), 'book_contents' => $this->preProcessBookContents( \Pressbooks\Book::getBookContents() ), - ); + ]; $cc_copyright = strip_tags( $this->doCopyrightLicense( $vars['meta'] ) ); $vars['do_copyright_license'] = $cc_copyright; @@ -88,11 +86,11 @@ function validate() { * @param $message * @param array $more_info (unused, overridden) */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { - $more_info = array( + $more_info = [ 'path' => $this->outputPath, - ); + ]; parent::logError( $message, $more_info ); } @@ -118,7 +116,7 @@ protected function bookHtmlError( $book_html ) { $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $book_html_path ) . ' 2>&1'; // Execute command - $output = array(); + $output = []; $return_var = 0; exec( $command, $output, $return_var ); @@ -151,7 +149,6 @@ protected function preProcessBookContents( $book_contents ) { foreach ( $struct as $i => $val ) { if ( isset( $val['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val['ID']; $book_contents[ $type ][ $i ]['post_content'] = $this->preProcessPostContent( $val['post_content'] ); } @@ -162,13 +159,12 @@ protected function preProcessBookContents( $book_contents ) { $book_contents[ $type ][ $i ]['post_name'] = $this->preProcessPostName( $val['post_name'] ); } - if ( 'part' == $type ) { + if ( 'part' === $type ) { // Do chapters, which are embedded in part structure foreach ( $book_contents[ $type ][ $i ]['chapters'] as $j => $val2 ) { if ( isset( $val2['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val2['ID']; $book_contents[ $type ][ $i ]['chapters'][ $j ]['post_content'] = $this->preProcessPostContent( $val2['post_content'] ); } @@ -183,7 +179,6 @@ protected function preProcessBookContents( $book_contents ) { } } - // @codingStandardsIgnoreLine $id = $old_id; return $book_contents; } @@ -215,23 +210,23 @@ protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'valid_xhtml' => 1, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } /** - * Dependency check. + * Dependency check. * * @return bool */ static function hasDependencies() { - if ( true == \Pressbooks\Utility\check_xmllint_install() ) { + if ( true === \Pressbooks\Utility\check_xmllint_install() ) { return true; } diff --git a/includes/modules/export/indesign/templates/xhtml.php b/inc/modules/export/indesign/templates/xhtml.php similarity index 96% rename from includes/modules/export/indesign/templates/xhtml.php rename to inc/modules/export/indesign/templates/xhtml.php index c4c383e389..2fb28c81c6 100644 --- a/includes/modules/export/indesign/templates/xhtml.php +++ b/inc/modules/export/indesign/templates/xhtml.php @@ -1,6 +1,6 @@ * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Export\Mobi; +namespace Pressbooks\Modules\Export\Mobi; use Pressbooks\Modules\Export\Export; @@ -62,7 +62,7 @@ function convert() { $command = PB_KINDLEGEN_COMMAND . ' ' . escapeshellcmd( $input_path ) . ' -locale en -o ' . escapeshellcmd( basename( $this->outputPath ) ) . ' 2>&1'; - $output = array(); + $output = []; $return_var = 0; exec( $command, $output, $return_var ); diff --git a/includes/modules/export/odt/class-pb-odt.php b/inc/modules/export/odt/class-odt.php similarity index 81% rename from includes/modules/export/odt/class-pb-odt.php rename to inc/modules/export/odt/class-odt.php index 30ce4973a3..2aec92eb13 100755 --- a/includes/modules/export/odt/class-pb-odt.php +++ b/inc/modules/export/odt/class-odt.php @@ -3,12 +3,10 @@ * @author Pressbooks * @license GPLv2 (or any later version)) */ -namespace Pressbooks\Modules\Export\Odt; - -use \Pressbooks\Modules\Export\Export; +namespace Pressbooks\Modules\Export\Odt; -require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' ); +use Pressbooks\Modules\Export\Export; class Odt extends Export { @@ -51,6 +49,11 @@ class Odt extends Export { function __construct( array $args ) { // Some defaults + + if ( ! class_exists( '\PclZip' ) ) { + require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' ); + } + if ( ! defined( 'PB_SAXON_COMMAND' ) ) { define( 'PB_SAXON_COMMAND', '/usr/bin/java -jar /opt/saxon-he/saxon-he.jar' ); } @@ -80,19 +83,19 @@ function convert() { // Save ODT as file in exports folder - $contentPath = pathinfo( $filename ); - $source = $contentPath['dirname'] . '/source.xhtml'; + $content_path = pathinfo( $filename ); + $source = $content_path['dirname'] . '/source.xhtml'; file_put_contents( $source, $this->queryXhtml() ); - $xslt = PB_PLUGIN_DIR . 'includes/modules/export/odt/xhtml2odt.xsl'; - $content = $contentPath['dirname'] . '/content.xml'; - $mimetype = $contentPath['dirname'] . '/mimetype'; - $metafolder = $contentPath['dirname'] . '/META-INF'; - $meta = $contentPath['dirname'] . '/meta.xml'; - $settings = $contentPath['dirname'] . '/settings.xml'; - $styles = $contentPath['dirname'] . '/styles.xml'; - $mediafolder = $contentPath['dirname'] . '/media/'; + $xslt = PB_PLUGIN_DIR . 'inc/modules/export/odt/xhtml2odt.xsl'; + $content = $content_path['dirname'] . '/content.xml'; + $mimetype = $content_path['dirname'] . '/mimetype'; + $metafolder = $content_path['dirname'] . '/META-INF'; + $meta = $content_path['dirname'] . '/meta.xml'; + $settings = $content_path['dirname'] . '/settings.xml'; + $styles = $content_path['dirname'] . '/styles.xml'; + $mediafolder = $content_path['dirname'] . '/media/'; if ( is_dir( $mediafolder ) ) { $this->deleteDirectory( $mediafolder ); @@ -111,11 +114,13 @@ function convert() { $tables = $xpath->query( '//table' ); foreach ( $tables as $table ) { + /** @var \DOMElement $table */ $columncount = 0; $columns = $xpath->query( '//tr[1]/*', $table ); foreach ( $columns as $column ) { + /** @var \DOMElement $column */ if ( $column->hasAttribute( 'colspan' ) ) { - $columncount = $columncount + $column->getAttribute( 'colspan' ); + $columncount = $columncount + (int) $column->getAttribute( 'colspan' ); } else { $columncount++; } @@ -135,8 +140,9 @@ function convert() { } } foreach ( $images as $image ) { + /** @var \DOMElement $image */ $src = $image->getAttribute( 'src' ); - $image_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); + $image_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $image_filename ) { // Replace with new image $image->setAttribute( 'src', $image_filename ); @@ -144,8 +150,9 @@ function convert() { } foreach ( $coverimages as $coverimage ) { + /** @var \DOMElement $coverimage */ $src = $coverimage->getAttribute( 'content' ); - $cover_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); + $cover_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $cover_filename ) { // Replace with new image $coverimage->setAttribute( 'src', $cover_filename ); @@ -192,12 +199,12 @@ function convert() { $zip = new \PclZip( $filename ); if ( $images->length > 0 ) { - $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $mediafolder . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $contentPath['dirname'] . '/' ); + $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $mediafolder . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $content_path['dirname'] . '/' ); } else { - $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $contentPath['dirname'] . '/' ); + $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $content_path['dirname'] . '/' ); } - if ( 0 == $list ) { + if ( 0 === absint( $list ) ) { $this->logError( $zip->errorInfo( true ) ); unlink( $source ); if ( is_dir( $mediafolder ) ) { @@ -235,7 +242,7 @@ public static function deleteDirectory( $dirpath ) { */ protected function queryXhtml() { - $args = array( 'timeout' => $this->timeout ); + $args = [ 'timeout' => $this->timeout ]; $response = wp_remote_get( $this->url, $args ); // WordPress error? @@ -246,7 +253,7 @@ protected function queryXhtml() { } // Server error? - if ( 200 != wp_remote_retrieve_response_code( $response ) ) { + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { $this->logError( wp_remote_retrieve_response_message( $response ) ); return false; @@ -280,11 +287,11 @@ function validate() { * @param $message * @param array $more_info (unused, overridden) */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { - $more_info = array( + $more_info = [ 'url' => $this->url, - ); + ]; parent::logError( $message, $more_info ); } @@ -316,16 +323,16 @@ protected function isOdt( $file ) { protected function fetchAndSaveUniqueImage( $url, $fullpath ) { // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $url ] ) ) { return $already_done[ $url ]; } - $response = wp_remote_get( $url, array( 'timeout' => $this->timeout ) ); + $response = wp_remote_get( $url, [ 'timeout' => $this->timeout ] ); // WordPress error? if ( is_wp_error( $response ) ) { - // TODO: handle $response->get_error_message(); + // TODO: Better handling in the event of $response->get_error_message(); $already_done[ $url ] = ''; return ''; } @@ -334,7 +341,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { $filename = explode( '?', basename( $url ) ); // isolate latex image service from WP, add file extension - if ( 's.wordpress.com' == parse_url( $url, PHP_URL_HOST ) && 'latex.php' == $filename[0] ) { + if ( 's.wordpress.com' === parse_url( $url, PHP_URL_HOST ) && 'latex.php' === $filename[0] ) { $filename = md5( array_pop( $filename ) ); // content-type = 'image/png' $type = explode( '/', $response['headers']['content-type'] ); @@ -363,7 +370,7 @@ protected function fetchAndSaveUniqueImage( $url, $fullpath ) { // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); - } elseif ( md5( file_get_contents( $tmp_file ) ) != md5( file_get_contents( "$fullpath/$filename" ) ) ) { + } elseif ( md5( file_get_contents( $tmp_file ) ) !== md5( file_get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } diff --git a/includes/modules/export/odt/xhtml2odt.xsl b/inc/modules/export/odt/xhtml2odt.xsl similarity index 100% rename from includes/modules/export/odt/xhtml2odt.xsl rename to inc/modules/export/odt/xhtml2odt.xsl diff --git a/includes/modules/export/prince/class-pb-pdf.php b/inc/modules/export/prince/class-pdf.php similarity index 80% rename from includes/modules/export/prince/class-pb-pdf.php rename to inc/modules/export/prince/class-pdf.php index 8cc669630e..de0b1c3c23 100644 --- a/includes/modules/export/prince/class-pb-pdf.php +++ b/inc/modules/export/prince/class-pdf.php @@ -3,12 +3,11 @@ * @author Pressbooks * @license GPLv2 (or any later version)) */ -namespace Pressbooks\Modules\Export\Prince; +namespace Pressbooks\Modules\Export\Prince; use Pressbooks\Modules\Export\Export; use Pressbooks\Container; -use PrinceXMLPhp\PrinceWrapper; class Pdf extends Export { @@ -51,6 +50,16 @@ class Pdf extends Export { */ protected $cssOverrides; + /** + * @var string + */ + protected $pdfProfile; + + /** + * @var string + */ + protected $pdfOutputIntent; + /** * @param array $args @@ -111,7 +120,7 @@ function convert() { $prince = new \PrinceXMLPhp\PrinceWrapper( PB_PRINCE_COMMAND ); $prince->setHTML( true ); $prince->setCompress( true ); - if ( defined( 'WP_ENV' ) && WP_ENV == 'development' || WP_ENV == 'staging' ) { + if ( defined( 'WP_ENV' ) && WP_ENV === 'development' || WP_ENV === 'staging' ) { $prince->setInsecure( true ); } if ( $this->pdfProfile && $this->pdfOutputIntent ) { @@ -158,11 +167,11 @@ function validate() { * @param $message * @param array $more_info (unused, overridden) */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { - $more_info = array( + $more_info = [ 'url' => $this->url, - ); + ]; parent::logError( $message, $more_info ); } @@ -182,18 +191,24 @@ protected function isPdf( $file ) { return ( strpos( $mime, 'application/pdf' ) !== false ); } + /** + * @return string + */ protected function getPdfProfile() { if ( defined( 'PB_PDF_PROFILE' ) ) { return PB_PDF_PROFILE; } - return null; + return ''; } + /** + * @return string + */ protected function getPdfOutputIntent() { if ( defined( 'PB_PDF_OUTPUT_INTENT' ) ) { return PB_PDF_OUTPUT_INTENT; } - return null; + return ''; } /** @@ -209,44 +224,48 @@ protected function kneadCss() { $scss = $sass->applyOverrides( file_get_contents( $this->exportStylePath ), $this->cssOverrides ); if ( $sass->isCurrentThemeCompatible( 1 ) ) { - $css = $sass->compile( $scss, [ + $css = $sass->compile( + $scss, [ $sass->pathToUserGeneratedSass(), $sass->pathToPartials(), $sass->pathToFonts(), get_stylesheet_directory(), - ] ); + ] + ); } elseif ( $sass->isCurrentThemeCompatible( 2 ) ) { $css = $sass->compile( $scss, $sass->defaultIncludePaths( 'prince' ) ); } else { $css = static::injectHouseStyles( $scss ); } - // Search for url("*"), url('*'), and url(*) + // Search for all possible permutations of CSS url syntax: url("*"), url('*'), and url(*) $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; - $css = preg_replace_callback( $url_regex, function ( $matches ) use ( $scss_dir ) { - - $url = $matches[3]; - - if ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { - $my_asset = realpath( PB_PLUGIN_DIR . $url ); - if ( $my_asset ) { - return 'url(' . PB_PLUGIN_DIR . $url . ')'; - } - } elseif ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { - $my_asset = realpath( WP_CONTENT_DIR . '/' . $url ); - if ( $my_asset ) { - return 'url(' . WP_CONTENT_DIR . '/' . $url . ')'; + $css = preg_replace_callback( + $url_regex, function ( $matches ) use ( $scss_dir ) { + + $url = $matches[3]; + + if ( preg_match( '#^themes-book/pressbooks-book/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { + $my_asset = realpath( PB_PLUGIN_DIR . $url ); + if ( $my_asset ) { + return 'url(' . PB_PLUGIN_DIR . $url . ')'; + } + } elseif ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(\.woff|\.otf|\.ttf)$#i', $url ) ) { + $my_asset = realpath( WP_CONTENT_DIR . '/' . $url ); + if ( $my_asset ) { + return 'url(' . WP_CONTENT_DIR . '/' . $url . ')'; + } + } elseif ( ! preg_match( '#^https?://#i', $url ) ) { + $my_asset = realpath( "$scss_dir/$url" ); + if ( $my_asset ) { + return "url($scss_dir/$url)"; + } } - } elseif ( ! preg_match( '#^https?://#i', $url ) ) { - $my_asset = realpath( "$scss_dir/$url" ); - if ( $my_asset ) { - return "url($scss_dir/$url)"; - } - } - return $matches[0]; // No change + return $matches[0]; // No change - }, $css ); + }, $css + ); if ( WP_DEBUG ) { Container::get( 'Sass' )->debug( $css, $scss, 'prince' ); @@ -279,11 +298,11 @@ protected function themeOptionsOverrides() { // -------------------------------------------------------------------- // Hacks - $hacks = array(); + $hacks = []; $hacks = apply_filters( 'pb_pdf_hacks', $hacks ); // Append endnotes to URL? - if ( 'endnotes' == $hacks['pdf_footnotes_style'] ) { + if ( 'endnotes' === $hacks['pdf_footnotes_style'] ) { $this->url .= '&endnotes=true'; } diff --git a/includes/modules/export/prince/class-pb-printpdf.php b/inc/modules/export/prince/class-printpdf.php similarity index 81% rename from includes/modules/export/prince/class-pb-printpdf.php rename to inc/modules/export/prince/class-printpdf.php index 14ce6ec864..73b6145763 100644 --- a/includes/modules/export/prince/class-pb-printpdf.php +++ b/inc/modules/export/prince/class-printpdf.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version)) */ -namespace Pressbooks\Modules\Export\Prince; +namespace Pressbooks\Modules\Export\Prince; use Pressbooks\Container; @@ -15,23 +15,11 @@ class PrintPdf extends Pdf { */ function __construct( array $args ) { - // Some defaults - - if ( ! defined( 'PB_PRINCE_COMMAND' ) ) { - define( 'PB_PRINCE_COMMAND', '/usr/bin/prince' ); - } + parent::__construct( $args ); - $this->exportStylePath = $this->getExportStylePath( 'prince' ); - $this->exportScriptPath = $this->getExportScriptPath( 'prince' ); + // Override $this->pdfProfile = 'PDF/X-1a'; $this->pdfOutputIntent = '/usr/lib/prince/icc/USWebCoatedSWOP.icc'; - - // Set the access protected "format/xhtml" URL with a valid timestamp and NONCE - $timestamp = time(); - $md5 = $this->nonce( $timestamp ); - $this->url = home_url() . "/format/xhtml?timestamp={$timestamp}&hashkey={$md5}"; - - $this->themeOptionsOverrides(); } @@ -69,7 +57,7 @@ function convert() { $prince = new \PrinceXMLPhp\PrinceWrapper( PB_PRINCE_COMMAND ); $prince->setHTML( true ); $prince->setCompress( true ); - if ( defined( 'WP_ENV' ) && WP_ENV == 'development' || WP_ENV == 'staging' ) { + if ( defined( 'WP_ENV' ) && WP_ENV === 'development' || WP_ENV === 'staging' ) { $prince->setInsecure( true ); } $prince->setOptions( '--pdf-profile=' . $this->pdfProfile . ' --pdf-output-intent=' . $this->pdfOutputIntent ); @@ -119,11 +107,11 @@ protected function themeOptionsOverrides() { // -------------------------------------------------------------------- // Hacks - $hacks = array(); + $hacks = []; $hacks = apply_filters( 'pb_pdf_hacks', $hacks ); // Append endnotes to URL? - if ( 'endnotes' == $hacks['pdf_footnotes_style'] ) { + if ( 'endnotes' === $hacks['pdf_footnotes_style'] ) { $this->url .= '&endnotes=true'; } diff --git a/includes/modules/export/wordpress/class-pb-vanillawxr.php b/inc/modules/export/wordpress/class-vanillawxr.php similarity index 95% rename from includes/modules/export/wordpress/class-pb-vanillawxr.php rename to inc/modules/export/wordpress/class-vanillawxr.php index 3690853d6d..46a8aa567a 100644 --- a/includes/modules/export/wordpress/class-pb-vanillawxr.php +++ b/inc/modules/export/wordpress/class-vanillawxr.php @@ -37,7 +37,7 @@ function convert() { throw new \Exception( print_r( libxml_get_errors(), true ) ); } - for ( $i = 0; $i < $post_type->length; $i ++ ) { + for ( $i = 0; $i < $post_type->length; $i++ ) { switch ( $post_type->item( $i )->nodeValue ) { case 'chapter': @@ -64,7 +64,7 @@ function convert() { // when you remove a child node, the next node becomes the first one, // hence '$term->item(0)' and NOT '$term->item($i)' $length = $term->length; - for ( $i = 0; $i < $length; $i ++ ) { + for ( $i = 0; $i < $length; $i++ ) { $this->deleteNode( $term->item( 0 ) ); } @@ -85,7 +85,7 @@ function convert() { foreach ( $category as $uncategorize ) { - switch ( ( string ) $uncategorize->attributes()->domain ) { + switch ( (string) $uncategorize->attributes()->domain ) { case 'front-matter-type': $uncategorize->attributes()->domain = 'category'; $uncategorize->attributes()->nicename = 'uncategorized'; diff --git a/includes/modules/export/wordpress/class-pb-wxr.php b/inc/modules/export/wordpress/class-wxr.php similarity index 87% rename from includes/modules/export/wordpress/class-pb-wxr.php rename to inc/modules/export/wordpress/class-wxr.php index 5c6922e5a3..aeb593a67f 100644 --- a/includes/modules/export/wordpress/class-pb-wxr.php +++ b/inc/modules/export/wordpress/class-wxr.php @@ -3,8 +3,8 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Export\WordPress; +namespace Pressbooks\Modules\Export\WordPress; use Pressbooks\Modules\Export\Export; @@ -94,8 +94,8 @@ function transform() { // Check permissions if ( ! current_user_can( 'manage_options' ) ) { - $timestamp = absint( @$_REQUEST['timestamp'] ); - $hashkey = @$_REQUEST['hashkey']; + $timestamp = ( isset( $_REQUEST['timestamp'] ) ) ? absint( $_REQUEST['timestamp'] ) : ''; + $hashkey = ( isset( $_REQUEST['hashkey'] ) ) ? $_REQUEST['hashkey'] : ''; if ( ! $this->verifyNonce( $timestamp, $hashkey ) ) { wp_die( __( 'Invalid permission error', 'pressbooks' ) ); } @@ -115,11 +115,11 @@ function transform() { * @param $message * @param array $more_info (unused, overridden) */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { - $more_info = array( + $more_info = [ 'url' => $this->url, - ); + ]; parent::logError( $message, $more_info ); } @@ -132,7 +132,7 @@ function logError( $message, array $more_info = array() ) { */ protected function queryWxr() { - $args = array( 'timeout' => $this->timeout ); + $args = [ 'timeout' => $this->timeout ]; $response = wp_remote_get( $this->url, $args ); // WordPress error? @@ -143,7 +143,7 @@ protected function queryWxr() { } // Server error? - if ( 200 != wp_remote_retrieve_response_code( $response ) ) { + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { $this->logError( wp_remote_retrieve_response_message( $response ) ); return false; diff --git a/includes/modules/export/xhtml/class-pb-xhtml11.php b/inc/modules/export/xhtml/class-xhtml11.php similarity index 88% rename from includes/modules/export/xhtml/class-pb-xhtml11.php rename to inc/modules/export/xhtml/class-xhtml11.php index 40075d664a..eb3e4e8c3f 100644 --- a/includes/modules/export/xhtml/class-pb-xhtml11.php +++ b/inc/modules/export/xhtml/class-xhtml11.php @@ -3,17 +3,14 @@ * @author Pressbooks * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Export\Xhtml; +namespace Pressbooks\Modules\Export\Xhtml; use Pressbooks\Modules\Export\Export; use Pressbooks\Sanitize; - - class Xhtml11 extends Export { - /** * Timeout in seconds. * Used with wp_remote_get() @@ -37,7 +34,7 @@ class Xhtml11 extends Export { * * @var array */ - protected $endnotes = array(); + protected $endnotes = []; /** @@ -77,9 +74,9 @@ function __construct( array $args ) { define( 'PB_XMLLINT_COMMAND', '/usr/bin/xmllint' ); } - $defaults = array( + $defaults = [ 'endnotes' => false, - ); + ]; $r = wp_parse_args( $args, $defaults ); // Set the access protected "format/xhtml" URL with a valid timestamp and NONCE @@ -138,7 +135,7 @@ function validate() { $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command - $output = array(); + $output = []; $return_var = 0; exec( $command, $output, $return_var ); @@ -161,8 +158,8 @@ function transform() { // Check permissions if ( ! current_user_can( 'manage_options' ) ) { - $timestamp = absint( @$_REQUEST['timestamp'] ); - $hashkey = @$_REQUEST['hashkey']; + $timestamp = ( isset( $_REQUEST['timestamp'] ) ) ? absint( $_REQUEST['timestamp'] ) : ''; + $hashkey = ( isset( $_REQUEST['hashkey'] ) ) ? $_REQUEST['hashkey'] : ''; if ( ! $this->verifyNonce( $timestamp, $hashkey ) ) { wp_die( __( 'Invalid permission error', 'pressbooks' ) ); } @@ -170,9 +167,9 @@ function transform() { // Override footnote shortcode if ( ! empty( $_GET['endnotes'] ) ) { - add_shortcode( 'footnote', array( $this, 'endnoteShortcode' ) ); + add_shortcode( 'footnote', [ $this, 'endnoteShortcode' ] ); } else { - add_shortcode( 'footnote', array( $this, 'footnoteShortcode' ) ); + add_shortcode( 'footnote', [ $this, 'footnoteShortcode' ] ); } // ------------------------------------------------------------------------------------------------------------ @@ -199,12 +196,13 @@ function transform() { if ( ! empty( $_GET['style'] ) ) { $url = \Pressbooks\Container::get( 'Sass' )->urlToUserGeneratedCss() . '/' . $_GET['style'] . '.css'; - echo "\n"; // @codingStandardsIgnoreLine + echo "\n"; } if ( ! empty( $_GET['script'] ) ) { - if ( $url = $this->getExportScriptUrl( $_GET['script'] ) . '/script.js' ) { - echo "\n"; // @codingStandardsIgnoreLine + $url = $this->getExportScriptUrl( $_GET['script'] ) . '/script.js'; + if ( $url ) { + echo "\n"; } } @@ -254,11 +252,11 @@ function transform() { * @param $message * @param array $more_info (unused, overridden) */ - function logError( $message, array $more_info = array() ) { + function logError( $message, array $more_info = [] ) { - $more_info = array( + $more_info = [ 'url' => $this->url, - ); + ]; parent::logError( $message, $more_info ); } @@ -286,7 +284,7 @@ function footnoteShortcode( $atts, $content = null ) { * @see doEndnotes * * @param array $atts - * @param null $content + * @param null $content * * @return string */ @@ -338,8 +336,8 @@ function doEndnotes( $id ) { */ protected function queryXhtml() { - $args = array( 'timeout' => $this->timeout ); - if ( WP_ENV == 'development' ) { + $args = [ 'timeout' => $this->timeout ]; + if ( defined( 'WP_ENV' ) && WP_ENV === 'development' ) { $args['sslverify'] = false; } $response = wp_remote_get( $this->url, $args ); @@ -352,7 +350,7 @@ protected function queryXhtml() { } // Server error? - if ( 200 != wp_remote_retrieve_response_code( $response ) ) { + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { $this->logError( wp_remote_retrieve_response_message( $response ) ); return false; @@ -387,7 +385,6 @@ protected function preProcessBookContents( $book_contents ) { foreach ( $struct as $i => $val ) { if ( isset( $val['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val['ID']; $book_contents[ $type ][ $i ]['post_content'] = $this->preProcessPostContent( $val['post_content'] ); } @@ -398,13 +395,12 @@ protected function preProcessBookContents( $book_contents ) { $book_contents[ $type ][ $i ]['post_name'] = $this->preProcessPostName( $val['post_name'] ); } - if ( 'part' == $type ) { + if ( 'part' === $type ) { // Do chapters, which are embedded in part structure foreach ( $book_contents[ $type ][ $i ]['chapters'] as $j => $val2 ) { if ( isset( $val2['post_content'] ) ) { - // @codingStandardsIgnoreLine $id = $val2['ID']; $book_contents[ $type ][ $i ]['chapters'][ $j ]['post_content'] = $this->preProcessPostContent( $val2['post_content'] ); } @@ -419,7 +415,6 @@ protected function preProcessBookContents( $book_contents ) { } } - // @codingStandardsIgnoreLine $id = $old_id; return $book_contents; } @@ -482,13 +477,13 @@ protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } @@ -552,7 +547,7 @@ protected function echoBeforeTitle( $book_contents, $metadata ) { $front_matter_printf .= ''; $i = $this->frontMatterPos; - foreach ( array( 'before-title' ) as $compare ) { + foreach ( [ 'before-title' ] as $compare ) { foreach ( $book_contents['front-matter'] as $front_matter ) { if ( ! $front_matter['export'] ) { @@ -562,7 +557,7 @@ protected function echoBeforeTitle( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( $compare != $subclass ) { + if ( $compare !== $subclass ) { continue; //Skip } @@ -570,13 +565,15 @@ protected function echoBeforeTitle( $book_contents, $metadata ) { $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '' ); // Preserve auto-indexing in Prince using hidden span $content = $front_matter['post_content']; - printf( $front_matter_printf, + printf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, - $this->doEndnotes( $front_matter_id ) ); + $this->doEndnotes( $front_matter_id ) + ); echo "\n"; ++$i; @@ -617,7 +614,7 @@ protected function echoTitle( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( 'title-page' != $subclass ) { + if ( 'title-page' !== $subclass ) { continue; // Skip } @@ -632,14 +629,14 @@ protected function echoTitle( $book_contents, $metadata ) { echo $content; } else { printf( '

%s

', get_bloginfo( 'name' ) ); - printf( '

%s

', @$metadata['pb_subtitle'] ); - printf( '

%s

', @$metadata['pb_author'] ); - printf( '

%s

', @$metadata['pb_contributing_authors'] ); + printf( '

%s

', ( isset( $metadata['pb_subtitle'] ) ) ? $metadata['pb_subtitle'] : '' ); + printf( '

%s

', ( isset( $metadata['pb_author'] ) ) ? $metadata['pb_author'] : '' ); + printf( '

%s

', ( isset( $metadata['pb_contributing_authors'] ) ) ? $metadata['pb_contributing_authors'] : '' ); if ( current_theme_supports( 'pressbooks_publisher_logo' ) ) { - printf( '', get_theme_support( 'pressbooks_publisher_logo' )[0]['logo_uri'] ); // TODO: Support custom publisher logo. + printf( '', get_theme_support( 'pressbooks_publisher_logo' )[0]['logo_uri'] ); // TODO: Support custom publisher logo. } - printf( '

%s

', @$metadata['pb_publisher'] ); - printf( '
%s
', @$metadata['pb_publisher_city'] ); + printf( '

%s

', ( isset( $metadata['pb_publisher'] ) ) ? $metadata['pb_publisher'] : '' ); + printf( '
%s
', ( isset( $metadata['pb_publisher_city'] ) ) ? $metadata['pb_publisher_city'] : '' ); } echo "\n"; } @@ -652,9 +649,9 @@ protected function echoTitle( $book_contents, $metadata ) { protected function echoCopyright( $book_contents, $metadata ) { $options = get_option( 'pressbooks_theme_options_global' ); - foreach ( array( 'copyright_license' ) as $requiredGlobalOption ) { - if ( ! isset( $options[ $requiredGlobalOption ] ) ) { - $options[ $requiredGlobalOption ] = 0; + foreach ( [ 'copyright_license' ] as $required_global_option ) { + if ( ! isset( $options[ $required_global_option ] ) ) { + $options[ $required_global_option ] = 0; } } @@ -664,15 +661,16 @@ protected function echoCopyright( $book_contents, $metadata ) { echo $this->tidy( $metadata['pb_custom_copyright'] ); } - if ( 1 == $options['copyright_license'] ) { + if ( 1 === absint( $options['copyright_license'] ) ) { echo $this->doCopyrightLicense( $metadata ); } // default, so something is displayed - if ( empty( $metadata['pb_custom_copyright'] ) && 0 == $options['copyright_license'] ) { + if ( empty( $metadata['pb_custom_copyright'] ) && 0 === absint( $options['copyright_license'] ) ) { echo '

'; echo get_bloginfo( 'name' ) . ' ' . __( 'Copyright', 'pressbooks' ) . ' © '; echo ( ! empty( $metadata['pb_copyright_year'] ) ) ? $metadata['pb_copyright_year'] : date( 'Y' ); - if ( ! empty( $metadata['pb_copyright_holder'] ) ) { echo ' ' . __( 'by', 'pressbooks' ) . ' ' . $metadata['pb_copyright_holder'] . '. '; + if ( ! empty( $metadata['pb_copyright_holder'] ) ) { + echo ' ' . __( 'by', 'pressbooks' ) . ' ' . $metadata['pb_copyright_holder'] . '. '; } echo '

'; } @@ -693,7 +691,7 @@ protected function echoDedicationAndEpigraph( $book_contents, $metadata ) { $front_matter_printf .= ''; $i = $this->frontMatterPos; - foreach ( array( 'dedication', 'epigraph' ) as $compare ) { + foreach ( [ 'dedication', 'epigraph' ] as $compare ) { foreach ( $book_contents['front-matter'] as $front_matter ) { if ( ! $front_matter['export'] ) { @@ -703,21 +701,23 @@ protected function echoDedicationAndEpigraph( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( $compare != $subclass ) { - continue; //Skip + if ( $compare !== $subclass ) { + continue; // Skip } $slug = $front_matter['post_name']; $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '' ); // Preserve auto-indexing in Prince using hidden span $content = $front_matter['post_content']; - printf( $front_matter_printf, + printf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, - $this->doEndnotes( $front_matter_id ) ); + $this->doEndnotes( $front_matter_id ) + ); echo "\n"; ++$i; @@ -734,9 +734,9 @@ protected function echoDedicationAndEpigraph( $book_contents, $metadata ) { protected function echoToc( $book_contents, $metadata ) { $options = get_option( 'pressbooks_theme_options_global' ); - foreach ( array( 'copyright_license' ) as $requiredGlobalOption ) { - if ( ! isset( $options[ $requiredGlobalOption ] ) ) { - $options[ $requiredGlobalOption ] = 0; + foreach ( [ 'copyright_license' ] as $required_global_option ) { + if ( ! isset( $options[ $required_global_option ] ) ) { + $options[ $required_global_option ] = 0; } } @@ -747,13 +747,13 @@ protected function echoToc( $book_contents, $metadata ) { continue; // Skip __magic keys } - if ( 'part' == $type ) { + if ( 'part' === $type ) { foreach ( $struct as $part ) { $slug = $part['post_name']; $title = Sanitize\strip_br( $part['post_title'] ); $part_content = trim( get_post_meta( $part['ID'], 'pb_part_content', true ) ); if ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) !== 'on' ) { // visible - if ( count( $book_contents['part'] ) == 1 ) { // only part + if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content printf( '
  • %s
  • ', $slug, Sanitize\decode( $title ) ); // show in TOC } else { // no content @@ -770,7 +770,7 @@ protected function echoToc( $book_contents, $metadata ) { } } } - } elseif ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) == 'on' ) { // invisible + } elseif ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) { // invisible printf( '', $slug, Sanitize\decode( $title ) ); // hide from TOC } foreach ( $part['chapters'] as $j => $chapter ) { @@ -802,7 +802,7 @@ protected function echoToc( $book_contents, $metadata ) { echo ''; - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $chapter['ID'] ); if ( $sections ) { echo '
      '; @@ -830,9 +830,9 @@ protected function echoToc( $book_contents, $metadata ) { $slug = $val['post_name']; $title = Sanitize\strip_br( $val['post_title'] ); - if ( 'front-matter' == $type ) { + if ( 'front-matter' === $type ) { $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $val['ID'] ); - if ( 'dedication' == $subclass || 'epigraph' == $subclass || 'title-page' == $subclass || 'before-title' == $subclass ) { + if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } else { $typetype = $type . ' ' . $subclass; @@ -840,7 +840,7 @@ protected function echoToc( $book_contents, $metadata ) { $author = trim( get_post_meta( $val['ID'], 'pb_section_author', true ) ); $license = ( $options['copyright_license'] ) ? get_post_meta( $val['ID'], 'pb_section_license', true ) : ''; } - } elseif ( 'back-matter' == $type ) { + } elseif ( 'back-matter' === $type ) { $typetype = $type . ' ' . \Pressbooks\Taxonomy::getBackMatterType( $val['ID'] ); $subtitle = trim( get_post_meta( $val['ID'], 'pb_subtitle', true ) ); $author = trim( get_post_meta( $val['ID'], 'pb_section_author', true ) ); @@ -858,13 +858,13 @@ protected function echoToc( $book_contents, $metadata ) { } if ( $license ) { - echo ' ' . $license . ' '; + echo ' ' . $license . ' '; } echo ''; - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { - $sections = \Pressbooks\Book::getSubsections( $val['ID'], true ); + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { + $sections = \Pressbooks\Book::getSubsections( $val['ID'] ); if ( $sections ) { echo '
        '; foreach ( $sections as $id => $title ) { @@ -905,11 +905,11 @@ protected function echoFrontMatter( $book_contents, $metadata ) { $front_matter_id = $front_matter['ID']; $subclass = \Pressbooks\Taxonomy::getFrontMatterType( $front_matter_id ); - if ( 'dedication' == $subclass || 'epigraph' == $subclass || 'title-page' == $subclass || 'before-title' == $subclass ) { + if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } - if ( 'introduction' == $subclass ) { + if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } @@ -921,7 +921,7 @@ protected function echoFrontMatter( $book_contents, $metadata ) { $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = trim( get_post_meta( $front_matter_id, 'pb_section_author', true ) ); - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $front_matter_id ); if ( $sections ) { $content = \Pressbooks\Book::tagSubsections( $content, $front_matter_id ); @@ -940,14 +940,16 @@ protected function echoFrontMatter( $book_contents, $metadata ) { $content = '
        ' . Sanitize\decode( $short_title ) . '
        ' . $content; } - printf( $front_matter_printf, + printf( + $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, $append_front_matter_content, - $this->doEndnotes( $front_matter_id ) ); + $this->doEndnotes( $front_matter_id ) + ); echo "\n"; ++$i; @@ -987,7 +989,7 @@ protected function echoPartsAndChapters( $book_contents, $metadata ) { $s = $i = $j = 1; foreach ( $book_contents['part'] as $part ) { - $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) == 'on' ) ? 'invisible' : ''; + $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $slug = $part['post_name']; @@ -996,7 +998,7 @@ protected function echoPartsAndChapters( $book_contents, $metadata ) { // Inject introduction class? if ( 'invisible' !== $invisibility ) { // visible - if ( count( $book_contents['part'] ) == 1 ) { // only part + if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content if ( ! $this->hasIntroduction ) { $part_printf_changed = str_replace( '
        hasIntroduction = true; } - $n = ( 'numberless' == $subclass ) ? '' : $j; + $n = ( 'numberless' === $subclass ) ? '' : $j; $my_chapters .= sprintf( ( $chapter_printf_changed ? $chapter_printf_changed : $chapter_printf ), $subclass, @@ -1083,7 +1086,8 @@ protected function echoPartsAndChapters( $book_contents, $metadata ) { Sanitize\decode( $title ), $content, $append_chapter_content, - $this->doEndnotes( $chapter_id ) ) . "\n"; + $this->doEndnotes( $chapter_id ) + ) . "\n"; if ( 'numberless' !== $subclass ) { ++$j; @@ -1093,7 +1097,7 @@ protected function echoPartsAndChapters( $book_contents, $metadata ) { // Echo with parts? if ( 'invisible' !== $invisibility ) { // visible - if ( count( $book_contents['part'] ) == 1 ) { // only part + if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content echo $my_part; // show if ( $my_chapters ) { @@ -1114,7 +1118,7 @@ protected function echoPartsAndChapters( $book_contents, $metadata ) { } } ++$i; - } elseif ( 'invisible' == $invisibility ) { // invisible + } elseif ( 'invisible' === $invisibility ) { // invisible if ( $my_chapters ) { echo $my_chapters; } @@ -1138,7 +1142,8 @@ protected function echoBackMatter( $book_contents, $metadata ) { $i = $s = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { - if ( ! $back_matter['export'] ) { continue; + if ( ! $back_matter['export'] ) { + continue; } $back_matter_id = $back_matter['ID']; @@ -1151,7 +1156,7 @@ protected function echoBackMatter( $book_contents, $metadata ) { $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = trim( get_post_meta( $back_matter_id, 'pb_section_author', true ) ); - if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() == true ) { + if ( \Pressbooks\Modules\Export\Export::isParsingSubsections() === true ) { $sections = \Pressbooks\Book::getSubsections( $back_matter_id ); if ( $sections ) { $content = \Pressbooks\Book::tagSubsections( $content, $back_matter_id ); @@ -1170,14 +1175,16 @@ protected function echoBackMatter( $book_contents, $metadata ) { $content = '
        ' . Sanitize\decode( $short_title ) . '
        ' . $content; } - printf( $back_matter_printf, + printf( + $back_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $content, $append_back_matter_content, - $this->doEndnotes( $back_matter_id ) ); + $this->doEndnotes( $back_matter_id ) + ); echo "\n"; ++$i; @@ -1198,10 +1205,12 @@ protected function atLeastOneExport( array $chapters ) { foreach ( $chapters as $key => $val ) { if ( is_array( $val ) ) { $found = $this->atLeastOneExport( $val ); - if ( $found ) { return true; - } else { continue; + if ( $found ) { + return true; + } else { + continue; } - } elseif ( 'export' == (string) $key && $val ) { + } elseif ( 'export' === (string) $key && $val ) { return true; } } @@ -1215,7 +1224,7 @@ protected function atLeastOneExport( array $chapters ) { * @return bool */ static function hasDependencies() { - if ( true == \Pressbooks\Utility\check_xmllint_install() ) { + if ( true === \Pressbooks\Utility\check_xmllint_install() ) { return true; } diff --git a/includes/modules/import/class-pb-import.php b/inc/modules/import/class-import.php similarity index 83% rename from includes/modules/import/class-pb-import.php rename to inc/modules/import/class-import.php index 4f7076ee64..17d74230a3 100644 --- a/includes/modules/import/class-pb-import.php +++ b/inc/modules/import/class-import.php @@ -6,11 +6,7 @@ namespace Pressbooks\Modules\Import; - -require_once( ABSPATH . 'wp-admin/includes/image.php' ); -require_once( ABSPATH . 'wp-admin/includes/file.php' ); -require_once( ABSPATH . 'wp-admin/includes/media.php' ); - +use function \Pressbooks\Utility\getset; abstract class Import { @@ -20,9 +16,9 @@ abstract class Import { * @deprecated * @var array */ - static $logsEmail = array( + static $logsEmail = [ 'errors@pressbooks.com', - ); + ]; /** @@ -91,7 +87,7 @@ function revokeCurrentImport() { */ function createTmpFile() { - return array_search( 'uri', @array_flip( stream_get_meta_data( $GLOBALS[ mt_rand() ] = tmpfile() ) ) ); + return \Pressbooks\Utility\create_tmp_file(); } @@ -104,14 +100,14 @@ protected function getChapterParent() { $q = new \WP_Query(); - $args = array( + $args = [ 'post_type' => 'part', 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'menu_order', 'order' => 'ASC', 'no_found_rows' => true, - ); + ]; $results = $q->query( $args ); @@ -127,18 +123,18 @@ protected function getChapterParent() { * @return bool */ protected function flaggedForImport( $id ) { - // @codingStandardsIgnoreLine - if ( ! @is_array( $_POST['chapters'] ) ) { + + $chapters = getset( '_POST', 'chapters' ); + + if ( ! is_array( $chapters ) ) { return false; } - // @codingStandardsIgnoreLine - if ( ! @isset( $_POST['chapters'][ $id ]['import'] ) ) { + if ( ! isset( $chapters['chapters'][ $id ] ) && ! isset( $chapters['chapters'][ $id ]['import'] ) ) { return false; } - // @codingStandardsIgnoreLine - return ( 1 == $_POST['chapters'][ $id ]['import'] ? true : false ); + return ( 1 === (int) $chapters['chapters'][ $id ]['import'] ? true : false ); } @@ -150,27 +146,24 @@ protected function flaggedForImport( $id ) { * @return string */ protected function determinePostType( $id ) { - $supported_types = apply_filters( 'pb_import_custom_post_types', array( 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ) ); + $chapters = getset( '_POST', 'chapters' ); + $supported_types = apply_filters( 'pb_import_custom_post_types', [ 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ] ); $default = 'chapter'; - // @codingStandardsIgnoreLine - if ( ! @is_array( $_POST['chapters'] ) ) { + if ( ! is_array( $chapters ) ) { return $default; } - // @codingStandardsIgnoreLine - if ( ! @isset( $_POST['chapters'][ $id ]['type'] ) ) { + if ( ! isset( $chapters['chapters'][ $id ] ) && ! isset( $chapters['chapters'][ $id ]['type'] ) ) { return $default; } - // @codingStandardsIgnoreLine - if ( ! in_array( $_POST['chapters'][ $id ]['type'], $supported_types ) ) { + if ( ! in_array( $chapters['chapters'][ $id ]['type'], $supported_types, true ) ) { return $default; } - // @codingStandardsIgnoreLine - return $_POST['chapters'][ $id ]['type']; + return $chapters['chapters'][ $id ]['type']; } @@ -185,11 +178,11 @@ protected function determinePostType( $id ) { * otherwise returns the filename that was passed to it */ protected function properImageExtension( $path_to_file, $filename ) { - $mimes = array( + $mimes = [ 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', - ); + ]; // Attempt to determine the real file type of a file. $validate = wp_check_filetype_and_ext( $path_to_file, $filename, $mimes ); @@ -214,9 +207,9 @@ protected function tidy( $html ) { // Reduce the vulnerability for scripting attacks - $config = array( + $config = [ 'safe' => 1, - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } @@ -232,7 +225,7 @@ static public function formSubmit() { // -------------------------------------------------------------------------------------------------------- // Sanity check - if ( false == static::isFormSubmission() || false == current_user_can( 'edit_posts' ) ) { + if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } @@ -244,7 +237,7 @@ static public function formSubmit() { $current_import = get_option( 'pressbooks_current_import' ); // Revoke - if ( @$_GET['revoke'] && check_admin_referer( 'pb-revoke-import' ) ) { + if ( isset( $_GET['revoke'] ) && ! empty( $_GET['revoke'] ) && check_admin_referer( 'pb-revoke-import' ) ) { self::revokeCurrentImport(); \Pressbooks\Redirect\location( $redirect_url ); } @@ -252,11 +245,11 @@ static public function formSubmit() { // only html import uses a url, not a file path if ( 0 !== strcmp( $current_import['type_of'], 'html' ) ) { // Appends 'last part' of the path to the dynamic first part of the path ($upload_dir) - $upload_dir = wp_upload_dir(); + $upload_dir = wp_upload_dir(); $current_import['file'] = trailingslashit( $upload_dir['path'] ) . basename( $current_import['file'] ); } - if ( @$_GET['import'] && is_array( @$_POST['chapters'] ) && is_array( $current_import ) && isset( $current_import['file'] ) && check_admin_referer( 'pb-import' ) ) { + if ( isset( $_GET['import'] ) && ! empty( $_GET['import'] ) && isset( $_POST['chapters'] ) && is_array( $_POST['chapters'] ) && is_array( $current_import ) && isset( $current_import['file'] ) && check_admin_referer( 'pb-import' ) ) { // Set post status $current_import['default_post_status'] = ( isset( $_POST['import_as_drafts'] ) ) ? 'draft' : 'publish'; @@ -264,7 +257,7 @@ static public function formSubmit() { // -------------------------------------------------------------------------------------------------------- // Do Import - @set_time_limit( 300 ); + @set_time_limit( 300 ); // @codingStandardsIgnoreLine $ok = false; switch ( $current_import['type_of'] ) { @@ -301,7 +294,9 @@ static public function formSubmit() { * @since 3.9.6 */ $importer = apply_filters( 'pb_initialize_import', null ); - $ok = $importer->import( $current_import ); + if ( is_object( $importer ) ) { + $ok = $importer->import( $current_import ); + } break; } @@ -314,7 +309,7 @@ static public function formSubmit() { $success_url = get_admin_url( get_current_blog_id(), '/admin.php?page=pressbooks' ); \Pressbooks\Redirect\location( $success_url ); } - } elseif ( @$_GET['import'] && ! @empty( $_FILES['import_file']['name'] ) && @$_POST['type_of'] && check_admin_referer( 'pb-import' ) ) { + } elseif ( isset( $_GET['import'] ) && isset( $_FILES['import_file']['name'] ) && ! empty( $_FILES['import_file']['name'] ) && isset( $_POST['type_of'] ) && check_admin_referer( 'pb-import' ) ) { // -------------------------------------------------------------------------------------------------------- // Set the 'pressbooks_current_import' option @@ -326,14 +321,16 @@ static public function formSubmit() { * * @param array The list of currently allowed file types. */ - $allowed_file_types = apply_filters( 'pb_import_file_types', array( + $allowed_file_types = apply_filters( + 'pb_import_file_types', [ 'epub' => 'application/epub+zip', 'xml' => 'application/xml', 'odt' => 'application/vnd.oasis.opendocument.text', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - ) ); + ] + ); - $overrides = array( 'test_form' => false, 'mimes' => $allowed_file_types ); + $overrides = [ 'test_form' => false, 'mimes' => $allowed_file_types ]; if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); @@ -348,7 +345,6 @@ static public function formSubmit() { } $ok = false; - switch ( $_POST['type_of'] ) { case 'wxr': @@ -374,7 +370,9 @@ static public function formSubmit() { default: /** This filter is documented above */ $importer = apply_filters( 'pb_initialize_import', null ); - $ok = $importer->setCurrentImportOption( $upload ); + if ( is_object( $importer ) ) { + $ok = $importer->setCurrentImportOption( $upload ); + } break; } @@ -387,10 +385,10 @@ static public function formSubmit() { $_SESSION['pb_errors'][] = sprintf( __( 'Your file does not appear to be a valid %s.', 'pressbooks' ), strtoupper( $_POST['type_of'] ) ); unlink( $upload['file'] ); } - } elseif ( @$_GET['import'] && 'html' === @$_POST['type_of'] && check_admin_referer( 'pb-import' ) ) { + } elseif ( isset( $_GET['import'] ) && isset( $_POST['type_of'] ) && 'html' === $_POST['type_of'] && check_admin_referer( 'pb-import' ) ) { // check if it's a valid url - if ( false == filter_var( $_POST['import_html'], FILTER_VALIDATE_URL ) ) { + if ( false === filter_var( $_POST['import_html'], FILTER_VALIDATE_URL ) ) { $_SESSION['pb_errors'][] = __( 'Your URL does not appear to be valid', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } @@ -407,7 +405,7 @@ static public function formSubmit() { // weebly.com (and likely some others) prevent HEAD requests, but allow GET requests if ( 200 !== $remote_head['response']['code'] && 405 !== $remote_head['response']['code'] ) { - $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response header on a HEAD request: ' , 'pressbooks' ) . $remote_head['response']['code']; + $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response header on a HEAD request: ', 'pressbooks' ) . $remote_head['response']['code']; \Pressbooks\Redirect\location( $redirect_url ); } @@ -430,7 +428,7 @@ static public function formSubmit() { // check for a successful response code on GET request if ( 200 !== $body['response']['code'] ) { - $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response on a GET request: ' , 'pressbooks' ) . $body['response']['code']; + $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response on a GET request: ', 'pressbooks' ) . $body['response']['code']; \Pressbooks\Redirect\location( $redirect_url ); } @@ -460,12 +458,16 @@ static public function formSubmit() { * @return bool */ static function isFormSubmission() { - if ( 'pb_import' != @$_REQUEST['page'] ) { + + if ( empty( $_REQUEST['page'] ) ) { + return false; + } + + if ( 'pb_import' !== $_REQUEST['page'] ) { return false; } - // @codingStandardsIgnoreLine - if ( ! empty( $_POST ) ) { + if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } @@ -488,19 +490,19 @@ static function isFormSubmission() { * @param string $message * @param array $more_info */ - static function log( $message, array $more_info = array() ) { + static function log( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = '[ Import Log ]'; - $info = array( + $info = [ 'time' => strftime( '%c' ), 'user' => ( isset( $current_user ) ? $current_user->user_login : '__UNKNOWN__' ), 'site_url' => site_url(), 'blog_id' => get_current_blog_id(), - ); + ]; $message = print_r( array_merge( $info, $more_info ), true ) . $message; diff --git a/includes/modules/import/epub/class-pb-epub201.php b/inc/modules/import/epub/class-epub201.php similarity index 83% rename from includes/modules/import/epub/class-pb-epub201.php rename to inc/modules/import/epub/class-epub201.php index 1919de7d3a..36f68da4ae 100644 --- a/includes/modules/import/epub/class-pb-epub201.php +++ b/inc/modules/import/epub/class-epub201.php @@ -7,7 +7,6 @@ namespace Pressbooks\Modules\Import\Epub; - use Pressbooks\Modules\Import\Import; use Pressbooks\Book; @@ -50,6 +49,11 @@ class Epub201 extends Import { * */ function __construct() { + if ( ! function_exists( 'media_handle_sideload' ) ) { + require_once( ABSPATH . 'wp-admin/includes/image.php' ); + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + require_once( ABSPATH . 'wp-admin/includes/media.php' ); + } $this->zip = new \ZipArchive; } @@ -68,35 +72,40 @@ function setCurrentImportOption( array $upload ) { return false; } - $option = array( + $option = [ 'file' => $upload['file'], 'file_type' => $upload['type'], 'type_of' => 'epub', - 'chapters' => array(), - ); + 'chapters' => [], + ]; $xml = $this->getOpf(); foreach ( $xml->manifest->children() as $item ) { - + /** @var \SimpleXMLElement $item */ // Get attributes $id = $title = $type = $href = ''; foreach ( $item->attributes() as $key => $val ) { - if ( 'id' == $key ) { $id = (string) $val; - } elseif ( 'media-type' == $key ) { $type = (string) $val; - } elseif ( 'href' == $key && 'OEBPS/copyright.html' == $val ) { $this->pbCheck( $val ); + if ( 'id' === $key ) { + $id = (string) $val; + } elseif ( 'media-type' === $key ) { + $type = (string) $val; + } elseif ( 'href' === $key && 'OEBPS/copyright.html' === $val ) { + $this->pbCheck( $val ); } - if ( 'href' == $key ) { $href = $val; + if ( 'href' === $key ) { + $href = $val; } } // Skip - if ( 'application/xhtml+xml' != $type ) { continue; + if ( 'application/xhtml+xml' !== $type ) { + continue; } // Set // Extract title from file $html = $this->getZipContent( $this->basedir . $href, false ); - $matches = array(); + $matches = []; preg_match( '/(?:]*>)(.+)<\/title>/isU', $html, $matches ); $title = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : $id ); @@ -144,9 +153,9 @@ protected function parseMetadata( \SimpleXMLElement $xml ) { $val = (string) $val; // Set authors - if ( 'creator' == $key && ! empty( $val ) ) { + if ( 'creator' === $key && ! empty( $val ) ) { $this->authors .= trim( $val ) . ', '; - } elseif ( 'contributor' == $key && ! empty( $val ) ) { + } elseif ( 'contributor' === $key && ! empty( $val ) ) { $this->authors .= trim( $val ) . ', '; } } @@ -162,18 +171,20 @@ protected function parseMetadata( \SimpleXMLElement $xml ) { * @param \SimpleXMLElement $xml * @param array $match_ids * @param $chapter_parent + * @param array $current_import */ protected function parseManifest( \SimpleXMLElement $xml, array $match_ids, $chapter_parent, $current_import ) { $total = 0; foreach ( $xml->manifest->children() as $item ) { - + /** @var \SimpleXMLElement $item */ // Get attributes $id = $href = ''; foreach ( $item->attributes() as $key => $val ) { - if ( 'id' == $key ) { $id = (string) $val; - } elseif ( 'href' == $key ) { - if ( 'OEBPS/copyright.html' == $val ) { + if ( 'id' === $key ) { + $id = (string) $val; + } elseif ( 'href' === $key ) { + if ( 'OEBPS/copyright.html' === $val ) { $this->pbCheck( $val ); } $href = $this->basedir . $val; @@ -204,15 +215,15 @@ protected function parseManifest( \SimpleXMLElement $xml, array $match_ids, $cha */ protected function getOpf() { - $containerXml = $this->getZipContent( 'META-INF/container.xml' ); - $contentPath = $containerXml->rootfiles->rootfile['full-path']; + $container_xml = $this->getZipContent( 'META-INF/container.xml' ); + $content_path = $container_xml->rootfiles->rootfile['full-path']; - $base = dirname( $contentPath ); - if ( '.' != $base ) { + $base = dirname( $content_path ); + if ( '.' !== $base ) { $this->basedir = "$base/"; } - return $this->getZipContent( $contentPath ); + return $this->getZipContent( $content_path ); } @@ -232,14 +243,6 @@ protected function setCurrentZip( $fullpath ) { /* Safety dance */ - /* - // TODO: Do we need this? Some EPUBs are garbage... - $mimetype = $this->getZipContent( 'mimetype', false ); - if ( $mimetype != 'application/epub+zip' ) { - throw new \Exception ( 'Wrong mimetype!' ); - } - */ - $ok = $this->getZipContent( 'META-INF/container.xml' ); if ( ! $ok ) { throw new \Exception( 'Bad or corrupted META-INF/container.xml' ); @@ -284,28 +287,29 @@ protected function getZipContent( $file, $as_xml = true ) { * @param string $href * @param string $post_type * @param int $chapter_parent + * @param string $post_status */ protected function kneadAndInsert( $href, $post_type, $chapter_parent, $post_status ) { $html = $this->getZipContent( $href, false ); - $matches = array(); + $matches = []; preg_match( '/(?:]*>)(.+)<\/title>/isU', $html, $matches ); $title = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '__UNKNOWN__' ); preg_match( '/(?:]*>)(.*)<\/body>/isU', $html, $matches ); - $body = $this->tidy( @$matches[1] ); + $body = ( isset( $matches[1] ) ) ? $this->tidy( $matches[1] ) : ''; $body = $this->kneadHtml( $body, $post_type, $href ); - $new_post = array( + $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, - ); + ]; - if ( 'chapter' == $post_type ) { + if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } @@ -328,12 +332,12 @@ protected function tidy( $html ) { // Reduce the vulnerability for scripting attacks // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'safe' => 1, 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } @@ -380,14 +384,15 @@ protected function kneadHtml( $html, $type, $href ) { * Cleans imported html of unwanted tags * * @param string $html + * * @return string */ protected function regexSearchReplace( $html ) { // Remove auto-created and tags. - $result = preg_replace( '/^/', '', str_replace( array( '', '', '', '' ), array( '', '', '', '' ), $html ) ); + $result = preg_replace( '/^/', '', str_replace( [ '', '', '', '' ], [ '', '', '', '' ], $html ) ); - if ( true == $this->isPbEpub ) { + if ( true === $this->isPbEpub ) { // Remove PB created div id (on EPUB201 Export) that will generate a princexml error on re-export // @see createPartsAndChapters() in export/epub/class-pb-epub201.php $result = preg_replace( '/(?:
        )/isU', '
        ', $result ); @@ -408,13 +413,13 @@ protected function regexSearchReplace( $html ) { /** * Is it an EPUB generated by PB? * - * @param string $copyrightFile + * @param string $copyright_file * * @return boolean * @see createCopyright() in /export/epub/class-pb-epub201.php */ - protected function pbCheck( $copyrightFile ) { - $result = $this->getZipContent( $copyrightFile ); + protected function pbCheck( $copyright_file ) { + $result = $this->getZipContent( $copyright_file ); foreach ( $result->body->div->div->p as $node ) { @@ -424,7 +429,7 @@ protected function pbCheck( $copyrightFile ) { } // applies to PB generated EPUBs with PB_SECRET_SAUCE // @see createCopyright() in export/epub/class-pb-epub201.php - if ( 'copyright-page' == $result->body->div[0]->attributes()->id[0] && 'ugc' == $result->body->div->div->attributes()->class[0] ) { + if ( 'copyright-page' === $result->body->div[0]->attributes()->id[0] && 'ugc' === $result->body->div->div->attributes()->class[0] ) { $this->isPbEpub = true; } } @@ -442,6 +447,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc, $href ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); $new_src = $this->fetchAndSaveUniqueImage( $old_src, $href ); @@ -473,11 +479,11 @@ protected function scrapeAndKneadImages( \DOMDocument $doc, $href ) { protected function fetchAndSaveUniqueImage( $url, $href ) { $path_parts = pathinfo( $href ); - $dir = @$path_parts['dirname']; + $dir = ( isset( $path_parts['dirname'] ) ) ? $path_parts['dirname'] : ''; $img_location = ( $dir ? "$dir/$url" : $url ); // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $img_location ] ) ) { return $already_done[ $img_location ]; } @@ -500,10 +506,11 @@ protected function fetchAndSaveUniqueImage( $url, $href ) { if ( ! $image_content ) { // Could not find image? try { // case where $url is '../Images/someimage.jpg' - $trimUrl = ltrim( $url, './' ); - $image_content = $this->getZipContent( $this->basedir . $trimUrl, false ); + $trim_url = ltrim( $url, './' ); + $image_content = $this->getZipContent( $this->basedir . $trim_url, false ); - if ( ! $image_content ) { throw new \Exception( 'Could not import images from EPUB' ); + if ( ! $image_content ) { + throw new \Exception( 'Could not import images from EPUB' ); } } catch ( \Exception $e ) { $already_done[ $img_location ] = ''; @@ -529,9 +536,10 @@ protected function fetchAndSaveUniqueImage( $url, $href ) { } } - $pid = media_handle_sideload( array( 'name' => $filename, 'tmp_name' => $tmp_name ), 0 ); + $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name ], 0 ); $src = wp_get_attachment_url( $pid ); - if ( ! $src ) { $src = ''; // Change false to empty string + if ( ! $src ) { + $src = ''; // Change false to empty string } $already_done[ $img_location ] = $src; @@ -554,7 +562,4 @@ protected function kneadHref( \DOMDocument $doc, $type, $href ) { return $doc; } - - - } diff --git a/includes/modules/import/html/class-pb-xhtml.php b/inc/modules/import/html/class-xhtml.php similarity index 86% rename from includes/modules/import/html/class-pb-xhtml.php rename to inc/modules/import/html/class-xhtml.php index b785beda16..a7b5578df7 100644 --- a/includes/modules/import/html/class-pb-xhtml.php +++ b/inc/modules/import/html/class-xhtml.php @@ -12,9 +12,21 @@ class Xhtml extends Import { + /** + * + */ + function __construct() { + if ( ! function_exists( 'media_handle_sideload' ) ) { + require_once( ABSPATH . 'wp-admin/includes/image.php' ); + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + require_once( ABSPATH . 'wp-admin/includes/media.php' ); + } + } + /** * * @param array $current_import + * * @return bool */ function import( array $current_import ) { @@ -46,7 +58,7 @@ function import( array $current_import ) { $post_type = $this->determinePostType( $id[0] ); $chapter_parent = $this->getChapterParent(); - $body = $this->kneadandInsert( $html['body'], $post_type, $chapter_parent, $domain, $current_import['default_post_status'] ); + $this->kneadAndInsert( $html['body'], $post_type, $chapter_parent, $domain, $current_import['default_post_status'] ); // Done return $this->revokeCurrentImport(); @@ -55,17 +67,18 @@ function import( array $current_import ) { /** * Pummel then insert HTML into our database * - * @param string $href + * @param string $html * @param string $post_type * @param int $chapter_parent - * @param string $domain domain name of the webpage + * @param string $domain domain name of the web page + * @param string $post_status */ - function kneadandInsert( $html, $post_type, $chapter_parent, $domain, $post_status ) { - $matches = array(); + function kneadAndInsert( $html, $post_type, $chapter_parent, $domain, $post_status ) { + $matches = []; $meta = $this->getLicenseAttribution( $html ); - $author = ( isset( $meta['authors'] )) ? $meta['authors'] : $this->getAuthors( $html ); - $license = ( isset( $meta['license'] )) ? $this->extractCCLicense( $meta['license'] ) : ''; + $author = ( isset( $meta['authors'] ) ) ? $meta['authors'] : $this->getAuthors( $html ); + $license = ( isset( $meta['license'] ) ) ? $this->extractCCLicense( $meta['license'] ) : ''; // get the title, preference to title set by PB preg_match( '/

        (.*)<\/h2>/', $html, $matches ); @@ -87,14 +100,14 @@ function kneadandInsert( $html, $post_type, $chapter_parent, $domain, $post_stat $body = $this->kneadHtml( $xhtml, $post_type, $domain ); - $new_post = array( + $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, - ); + ]; - if ( 'chapter' == $post_type ) { + if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } @@ -119,6 +132,7 @@ function kneadandInsert( $html, $post_type, $chapter_parent, $domain, $post_stat * http://creativecommons.org/licenses/by-sa/4.0/ * * @param string $url + * * @return string license meta value */ protected function extractCCLicense( $url ) { @@ -131,10 +145,10 @@ protected function extractCCLicense( $url ) { // look for creativecommons domain $parts = parse_url( $url ); - if ( 'http' == $parts['scheme'] && 'creativecommons.org' == $parts['host'] ) { + if ( 'http' === $parts['scheme'] && 'creativecommons.org' === $parts['host'] ) { // extract the license information from it $split = explode( '/', $parts['path'] ); - if ( 'zero' == $split[2] ) { + if ( 'zero' === $split[2] ) { $license = 'cc0'; } else { $license = 'cc-' . $split[2]; @@ -149,10 +163,11 @@ protected function extractCCLicense( $url ) { * author and license information. * * @param string $html + * * @return array $meta */ protected function getLicenseAttribution( $html ) { - $meta = array(); + $meta = []; // get license attribution statement if it exists preg_match( '/(?:
        /isU', $html, $matches ); } - $authors = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : ''); + $authors = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '' ); } return $authors; @@ -212,6 +228,7 @@ protected function getAuthors( $html ) { * Cherry pick likely content areas, then cull known, unwanted content areas * * @param string $html + * * @return string $html */ protected function regexSearchReplace( $html ) { @@ -219,19 +236,19 @@ protected function regexSearchReplace( $html ) { /* cherry pick likely content areas */ // HTML5, ungreedy preg_match( '/(?:]*>)(.*)<\/main>/isU', $html, $matches ); - $html = ( ! empty( $matches[1] )) ? $matches[1] : $html; + $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // WP content area, greedy preg_match( '/(?:
        ]*>)(.*)<\/div>/is', $html, $matches ); - $html = ( ! empty( $matches[1] )) ? $matches[1] : $html; + $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // general content area, greedy preg_match( '/(?:
        ]*>)(.*)<\/div>/is', $html, $matches ); - $html = ( ! empty( $matches[1] )) ? $matches[1] : $html; + $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // specific PB content area, greedy preg_match( '/(?:
        ]*>)(.*)<\/div>/is', $html, $matches ); - $html = ( ! empty( $matches[1] )) ? $matches[1] : $html; + $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; /* cull */ // get rid of script tags, ungreedy @@ -259,7 +276,7 @@ protected function regexSearchReplace( $html ) { * * @param string $html * @param string $type front-matter, part, chapter, back-matter, ... - * @param string $domain domain name of the webpage + * @param string $domain domain name of the web page * * @return string */ @@ -288,29 +305,30 @@ function kneadHtml( $html, $type, $domain ) { /** * Extracts section/book author and section/book license if they exist. - * Focus is given to CreativeCommons license information genereted by PB + * Focus is given to CreativeCommons license information generated by PB * * @param \DOMDocument $doc + * * @return array $meta */ protected function scrapeAndKneadMeta( \DOMDocument $doc ) { - $meta = array(); + $meta = []; $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $anchor ) { - + /** @var \DOMElement $anchor */ $license = $anchor->getAttribute( 'rel' ); $property = $anchor->getAttribute( 'property' ); // expecting to find - if ( 'license' == $license ) { + if ( 'license' === $license ) { $meta['license'] = $anchor->getAttribute( 'href' ); } // expecting to find // Arthur Green, Britta Ricker, Siobhan McPhee, Aviv Ettya, Cristina Temenos - if ( 'cc:attributionName' == $property ) { + if ( 'cc:attributionName' === $property ) { $meta['authors'] = $anchor->nodeValue; } } @@ -322,7 +340,7 @@ protected function scrapeAndKneadMeta( \DOMDocument $doc ) { * Parse HTML snippet, save all found tags using media_handle_sideload(), return the HTML with changed paths. * * @param \DOMDocument $doc - * @param string $domain domain name of the webpage + * @param string $domain domain name of the web page * * @return \DOMDocument */ @@ -330,6 +348,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc, $domain ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); @@ -372,7 +391,7 @@ protected function fetchAndSaveUniqueImage( $url ) { $remote_img_location = $url; // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $remote_img_location ] ) ) { return $already_done[ $remote_img_location ]; } @@ -414,12 +433,13 @@ protected function fetchAndSaveUniqueImage( $url ) { } } - $pid = media_handle_sideload( array( 'name' => $filename, 'tmp_name' => $tmp_name ), 0 ); + $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name ], 0 ); $src = wp_get_attachment_url( $pid ); - if ( ! $src ) { $src = ''; // Change false to empty string + if ( ! $src ) { + $src = ''; // Change false to empty string } $already_done[ $remote_img_location ] = $src; - @unlink( $tmp_name ); + @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $src; } @@ -427,6 +447,7 @@ protected function fetchAndSaveUniqueImage( $url ) { /** * * @param array $upload + * * @return bool */ function setCurrentImportOption( array $upload ) { @@ -435,19 +456,19 @@ function setCurrentImportOption( array $upload ) { // safety check if param (character encoding) with `;` isn't set // @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 - $content_type = ( false === strstr( $upload['headers']['content-type'], ';' )) ? $content_type = $upload['headers']['content-type'] : strstr( $upload['headers']['content-type'], ';', true ); + $content_type = ( false === strstr( $upload['headers']['content-type'], ';' ) ) ? $content_type = $upload['headers']['content-type'] : strstr( $upload['headers']['content-type'], ';', true ); // get the title preg_match( '/(.+)<\/title>/', $html, $matches ); $title = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '__UNKNOWN__' ); // set the args - $option = array( + $option = [ 'file' => $upload['url'], 'file_type' => $content_type, 'type_of' => 'html', - 'chapters' => array(), - ); + 'chapters' => [], + ]; // there will be only one chapter $option['chapters'][1] = $title; @@ -467,14 +488,14 @@ protected function tidy( $html ) { // Reduce the vulnerability for scripting attacks // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'deny_attribute' => 'style', 'comment' => 1, 'safe' => 1, 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } diff --git a/includes/modules/import/odf/class-pb-odt.php b/inc/modules/import/odf/class-odt.php similarity index 86% rename from includes/modules/import/odf/class-pb-odt.php rename to inc/modules/import/odf/class-odt.php index 0a0b757d72..13d8f80355 100644 --- a/includes/modules/import/odf/class-pb-odt.php +++ b/inc/modules/import/odf/class-odt.php @@ -7,7 +7,6 @@ namespace Pressbooks\Modules\Import\Odf; - use Pressbooks\Modules\Import\Import; use Pressbooks\Book; @@ -33,6 +32,11 @@ class Odt extends Import { * */ function __construct() { + if ( ! function_exists( 'media_handle_sideload' ) ) { + require_once( ABSPATH . 'wp-admin/includes/image.php' ); + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + require_once( ABSPATH . 'wp-admin/includes/media.php' ); + } $this->zip = new \ZipArchive(); } @@ -70,7 +74,8 @@ function import( array $current_import ) { foreach ( $current_import['chapters'] as $id => $chapter_title ) { // do nothing it has been omitted - if ( ! $this->flaggedForImport( $id ) ) { continue; + if ( ! $this->flaggedForImport( $id ) ) { + continue; } $html = $this->parseContent( $dom_doc, $chapter_title ); @@ -89,9 +94,9 @@ function import( array $current_import ) { */ protected function parseMetaData( \DOMDocument $meta ) { - $nodeList = $meta->getElementsByTagName( 'creator' ); - if ( $nodeList->item( 0 ) ) { - $this->authors = $nodeList->item( 0 )->nodeValue; + $node_list = $meta->getElementsByTagName( 'creator' ); + if ( $node_list->item( 0 ) ) { + $this->authors = $node_list->item( 0 )->nodeValue; } } @@ -103,6 +108,7 @@ protected function parseMetaData( \DOMDocument $meta ) { * @param string $title * @param string $post_type (front-matter', 'chapter', 'back-matter') * @param int $chapter_parent + * @param string $post_status */ protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $post_status ) { @@ -111,14 +117,14 @@ protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $ $title = wp_strip_all_tags( $title ); - $new_post = array( + $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, - ); + ]; - if ( 'chapter' == $post_type ) { + if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } @@ -170,6 +176,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); $new_src = $this->fetchAndSaveUniqueImage( $old_src ); @@ -202,7 +209,7 @@ protected function fetchAndSaveUniqueImage( $href ) { $img_location = $href; // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $img_location ] ) ) { return $already_done[ $img_location ]; } @@ -248,9 +255,10 @@ protected function fetchAndSaveUniqueImage( $href ) { } } - $pid = media_handle_sideload( array( 'name' => $filename, 'tmp_name' => $tmp_name ), 0 ); + $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name ], 0 ); $src = wp_get_attachment_url( $pid ); - if ( ! $src ) { $src = ''; // Change false to empty string + if ( ! $src ) { + $src = ''; // Change false to empty string } $already_done[ $img_location ] = $src; @@ -270,14 +278,14 @@ protected function tidy( $html ) { // Reduce the vulnerability for scripting attacks // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'safe' => 1, 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'elements' => '* -span', 'deny_attribute' => 'id, style', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } @@ -298,12 +306,12 @@ function setCurrentImportOption( array $upload ) { return false; } - $option = array( + $option = [ 'file' => $upload['file'], 'file_type' => $upload['type'], 'type_of' => 'odt', - 'chapters' => array(), - ); + 'chapters' => [], + ]; $option['chapters'] = $this->getFuzzyChapterTitles(); @@ -340,33 +348,33 @@ protected function isValidZip( $fullpath ) { * @param \DOMNode $node * @param string $chapter_name * - * @return \DOMNode + * @return \DOMNode|mixed */ protected function findTheNode( \DOMNode $node, $chapter_name ) { - if ( XML_ELEMENT_NODE !== $node->nodeType ) { + if ( XML_ELEMENT_NODE !== $node->nodeType ) { return ''; } - $currentTag = $node->tagName; - $currentValue = $node->nodeValue; + $current_tag = $node->tagName; + $current_value = $node->nodeValue; - if ( $chapter_name == $currentValue && $this->tag == $currentTag ) { + if ( $chapter_name === $current_value && $this->tag === $current_tag ) { return $node; } // test if ( $node->hasChildNodes() ) { - $nodeList = $node->childNodes; + $node_list = $node->childNodes; - for ( $i = 0; $i < $nodeList->length; $i ++ ) { + for ( $i = 0; $i < $node_list->length; $i++ ) { - if ( $nodeList->item( $i )->nodeType !== XML_ELEMENT_NODE ) { + if ( $node_list->item( $i )->nodeType !== XML_ELEMENT_NODE ) { continue; } - if ( $chapter_name != $nodeList->item( $i )->nodeValue && $this->tag != $nodeList->item( $i )->tagName ) { + if ( $chapter_name !== $node_list->item( $i )->nodeValue && $this->tag !== $node_list->item( $i )->tagName ) { // recursive - return $this->findTheNode( $nodeList->item( $i ), $chapter_name ); + return $this->findTheNode( $node_list->item( $i ), $chapter_name ); } } } @@ -387,7 +395,8 @@ protected function findTheNode( \DOMNode $node, $chapter_name ) { */ protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) { - if ( '' == $chapter_title ) { $chapter_title = 'unknown'; + if ( empty( $chapter_title ) ) { + $chapter_title = 'unknown'; } $chapter = new \DOMDocument( '1.0', 'UTF-8' ); @@ -399,25 +408,25 @@ protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) // Start at the beginning if no h1 tags are found. // In other words...bring in the whole document. - ( '__UNKNOWN__' == $chapter_title ) ? $i = 0 : $i = $index; + ( '__UNKNOWN__' === $chapter_title ) ? $i = 0 : $i = $index; do { $node = $chapter->importNode( $dom_list->item( $i ), true ); $chapter->documentElement->appendChild( $node ); - $i ++; + $i++; // TODO // This is problematic // DOMNodeList can be made up of DOMElement(s) // *and* DOMText(s) which do not have the property ->tagName - } while ( @$dom_list->item( $i )->tagName != $this->tag && $i < $dom_list->length ); + } while ( @$dom_list->item( $i )->tagName != $this->tag && $i < $dom_list->length ); // @codingStandardsIgnoreLine // h1 tag will not be needed in the body of the html $h1 = $chapter->getElementsByTagName( $this->tag )->item( 0 ); // removeChild is quick to throw a fatal error - if ( $h1 && $this->tag == $h1->nodeName && 'div' == $h1->parentNode->nodeName ) { + if ( $h1 && $this->tag === $h1->nodeName && 'div' === $h1->parentNode->nodeName ) { $chapter->documentElement->removeChild( $h1 ); } @@ -448,10 +457,10 @@ protected function parseContent( \DomDocument $xml, $chapter_title ) { $index = 0; // loop through child siblings - for ( $i = 0; $i < $node_list->length; $i ++ ) { + for ( $i = 0; $i < $node_list->length; $i++ ) { $chapter_node = $this->findTheNode( $node_list->item( $i ), $chapter_title ); - if ( '' != $chapter_node ) { + if ( ! empty( $chapter_node ) ) { // assumes h1 is going to be first child of parent 'html' $index = $i; break; @@ -474,7 +483,7 @@ protected function parseContent( \DomDocument $xml, $chapter_title ) { */ protected function getFuzzyChapterTitles() { - $chapters = array(); + $chapters = []; $xml = $this->getZipContent( 'content.xml' ); @@ -491,7 +500,7 @@ protected function getFuzzyChapterTitles() { $headings = $dom_doc->getElementsByTagName( $this->tag ); // populate chapters with title names - for ( $i = 0; $i < $headings->length; $i ++ ) { + for ( $i = 0; $i < $headings->length; $i++ ) { $chapters[] = trim( $headings->item( $i )->nodeValue ); } @@ -499,7 +508,7 @@ protected function getFuzzyChapterTitles() { $chapters = array_values( array_filter( $chapters ) ); // default chapter title if there are no h1 headings in the document - if ( 0 == count( $chapters ) ) { + if ( 0 === count( $chapters ) ) { $chapters[] = '__UNKNOWN__'; } diff --git a/includes/modules/import/odf/xsl/odt2html.xsl b/inc/modules/import/odf/xsl/odt2html.xsl similarity index 100% rename from includes/modules/import/odf/xsl/odt2html.xsl rename to inc/modules/import/odf/xsl/odt2html.xsl diff --git a/includes/modules/import/ooxml/class-pb-docx.php b/inc/modules/import/ooxml/class-docx.php similarity index 87% rename from includes/modules/import/ooxml/class-pb-docx.php rename to inc/modules/import/ooxml/class-docx.php index dc04287bc8..60c6928561 100644 --- a/includes/modules/import/ooxml/class-pb-docx.php +++ b/inc/modules/import/ooxml/class-docx.php @@ -31,17 +31,17 @@ class Docx extends Import { /** * @var array */ - protected $fn = array(); + protected $fn = []; /** - * @var array + * @var array */ - protected $en = array(); + protected $en = []; /** * @var array */ - protected $ln = array(); + protected $ln = []; const DOCUMENT_SCHEMA = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'; const METADATA_SCHEMA = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'; @@ -57,6 +57,11 @@ class Docx extends Import { * */ function __construct() { + if ( ! function_exists( 'media_handle_sideload' ) ) { + require_once( ABSPATH . 'wp-admin/includes/image.php' ); + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + require_once( ABSPATH . 'wp-admin/includes/media.php' ); + } $this->zip = new \ZipArchive(); } @@ -64,6 +69,7 @@ function __construct() { /** * * @param array $current_import + * * @return boolean */ function import( array $current_import ) { @@ -122,7 +128,8 @@ function import( array $current_import ) { foreach ( $current_import['chapters'] as $id => $chapter_title ) { // do nothing it has been omitted - if ( ! $this->flaggedForImport( $id ) ) { continue; + if ( ! $this->flaggedForImport( $id ) ) { + continue; } $html = $this->parseContent( $dom_doc, $chapter_title ); @@ -137,11 +144,12 @@ function import( array $current_import ) { * * @param \DOMDocument $dom_doc * @param string $tag + * @param string $attr * * @return array */ protected function getIDs( \DOMDocument $dom_doc, $tag = 'footnoteReference', $attr = 'w:id' ) { - $fn_ids = array(); + $fn_ids = []; $doc_elem = $dom_doc->documentElement; $tags_fn_ref = $doc_elem->getElementsByTagName( $tag ); @@ -149,6 +157,7 @@ protected function getIDs( \DOMDocument $dom_doc, $tag = 'footnoteReference', $a // if footnotes are in the document, get the ids if ( $tags_fn_ref->length > 0 ) { foreach ( $tags_fn_ref as $id ) { + /** @var \DOMElement $id */ if ( '' !== $id->getAttribute( $attr ) ) { // don't add if its empty $fn_ids[] = $id->getAttribute( $attr ); } @@ -168,7 +177,7 @@ protected function getIDs( \DOMDocument $dom_doc, $tag = 'footnoteReference', $a * @throws \Exception if there is discrepancy between the number of footnotes in document.xml and footnotes.xml */ protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { - $footnotes = array(); + $footnotes = []; $tag_name = rtrim( $tag, 's' ); // get the path for the footnotes @@ -186,7 +195,7 @@ protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { } // safety — if there are no footnotes, return - if ( '' == $target_path ) { + if ( empty( $target_path ) ) { return false; } @@ -206,13 +215,13 @@ protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { // TODO // could be more sophisticated - if ( $text_tags->length != $limit + 2 ) { + if ( $text_tags->length !== $limit + 2 ) { throw new \Exception( 'mismatch between length of FootnoteReference array number of footnotes available' ); } // get all the footnote ids // +2 to the domlist skips over two default nodes that don't contain end/footnotes - for ( $i = 0; $i < $limit; $i ++ ) { + for ( $i = 0; $i < $limit; $i++ ) { $footnotes[ $ids[ $i ] ] = $text_tags->item( $i + 2 )->nodeValue; } @@ -226,6 +235,7 @@ protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { * @param string $title * @param string $post_type (front-matter', 'chapter', 'back-matter') * @param int $chapter_parent + * @param string $post_status */ protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $post_status ) { @@ -234,14 +244,14 @@ protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $ $title = wp_strip_all_tags( $title ); - $new_post = array( + $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, - ); + ]; - if ( 'chapter' == $post_type ) { + if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } @@ -291,6 +301,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); $new_src = $this->fetchAndSaveUniqueImage( $old_src ); @@ -317,7 +328,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc ) { protected function fetchAndSaveUniqueImage( $img_id ) { // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $img_id ] ) ) { return $already_done[ $img_id ]; } @@ -377,9 +388,10 @@ protected function fetchAndSaveUniqueImage( $img_id ) { } } - $pid = media_handle_sideload( array( 'name' => $filename, 'tmp_name' => $tmp_name ), 0 ); + $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name ], 0 ); $src = wp_get_attachment_url( $pid ); - if ( ! $src ) { $src = ''; // Change false to empty string + if ( ! $src ) { + $src = ''; // Change false to empty string } $already_done[ $img_location ] = $src; @@ -399,10 +411,10 @@ protected function parseContent( \DomDocument $xml, $chapter_title ) { $index = 0; // loop through child siblings - for ( $i = 0; $i < $node_list->length; $i ++ ) { + for ( $i = 0; $i < $node_list->length; $i++ ) { $chapter_node = $this->findTheNode( $node_list->item( $i ), $chapter_title ); - if ( '' != $chapter_node ) { + if ( ! empty( $chapter_node ) ) { // assumes h1 is going to be first child of parent 'html' $index = $i; break; @@ -410,7 +422,7 @@ protected function parseContent( \DomDocument $xml, $chapter_title ) { } if ( $chapter_node ) { - $chapter_title = strtolower( preg_replace( '/\s+/', '-', $chapter_node->nodeValue ) ); + $chapter_title = strtolower( preg_replace( '/\s+/', '-', $chapter_node->nodeValue ) ); } // iterate through @@ -429,7 +441,8 @@ protected function parseContent( \DomDocument $xml, $chapter_title ) { */ protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) { - if ( '' == $chapter_title ) { $chapter_title = 'unknown'; + if ( empty( $chapter_title ) ) { + $chapter_title = 'unknown'; } $chapter = new \DOMDocument( '1.0', 'UTF-8' ); @@ -441,24 +454,24 @@ protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) // Start at the beginning if no h1 tags are found. // In other words...bring in the whole document. - ( '__UNKNOWN__' == $chapter_title ) ? $i = 0 : $i = $index; + ( '__UNKNOWN__' === $chapter_title ) ? $i = 0 : $i = $index; do { $node = $chapter->importNode( $dom_list->item( $i ), true ); $chapter->documentElement->appendChild( $node ); - $i ++; + $i++; // TODO // This is problematic // DOMNodeList can be made up of DOMElement(s) // *and* DOMText(s) which do not have the property ->tagName - } while ( @$dom_list->item( $i )->tagName != $this->tag && $i < $dom_list->length ); + } while ( @$dom_list->item( $i )->tagName !== $this->tag && $i < $dom_list->length ); // @codingStandardsIgnoreLine // h1 tag will not be needed in the body of the html $h1 = $chapter->getElementsByTagName( $this->tag )->item( 0 ); // removeChild is quick to throw a fatal error - if ( $h1 && $this->tag == $h1->nodeName && 'div' == $h1->parentNode->nodeName ) { + if ( $h1 && $this->tag === $h1->nodeName && 'div' === $h1->parentNode->nodeName ) { $chapter->documentElement->removeChild( $h1 ); } @@ -482,6 +495,7 @@ protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) * adds external hyperlinks, if they are present in a chapter * * @param \DOMDocument $chapter + * * @return \DOMDocument */ protected function addHyperlinks( \DOMDocument $chapter ) { @@ -489,6 +503,7 @@ protected function addHyperlinks( \DOMDocument $chapter ) { if ( $ln->length > 0 ) { foreach ( $ln as $link ) { + /** @var \DOMElement $link */ if ( $link->hasAttribute( 'class' ) ) { $ln_id = $link->getAttribute( 'class' ); @@ -505,14 +520,16 @@ protected function addHyperlinks( \DOMDocument $chapter ) { * adds footnotes, if they are present in the chapter * * @param \DOMDocument $chapter + * * @return \DOMDocument */ protected function addFootnotes( \DOMDocument $chapter ) { $fn_candidates = $chapter->getelementsByTagName( 'a' ); - $fn_ids = array(); + $fn_ids = []; foreach ( $fn_candidates as $fn_candidate ) { + /** @var \DOMElement $fn_candidate */ $href = $fn_candidate->getAttribute( 'href' ); - if ( null != $href ) { + if ( ! empty( $href ) ) { $fn_matches = null; if ( preg_match( self::FOOTNOTE_HREF_PATTERN, $href, $fn_matches ) ) { $fn_ids[] = $fn_matches[1]; @@ -522,6 +539,7 @@ protected function addFootnotes( \DOMDocument $chapter ) { // TODO either/or is not sufficient, needs to be built to // cover a use case where both are present. + $notes = []; if ( ! empty( $this->fn ) ) { $notes = $this->fn; } @@ -557,7 +575,7 @@ protected function addFootnotes( \DOMDocument $chapter ) { * @param \DOMNode $node * @param string $chapter_name * - * @return \DOMNode + * @return \DOMNode|mixed */ protected function findTheNode( \DOMNode $node, $chapter_name ) { @@ -565,25 +583,25 @@ protected function findTheNode( \DOMNode $node, $chapter_name ) { return ''; } - $currentTag = $node->tagName; - $currentValue = trim( $node->nodeValue ); + $current_tag = $node->tagName; + $current_value = trim( $node->nodeValue ); - if ( $chapter_name == $currentValue && $this->tag == $currentTag ) { + if ( $chapter_name === $current_value && $this->tag === $current_tag ) { return $node; } // test if ( $node->hasChildNodes() ) { - $nodeList = $node->childNodes; + $node_list = $node->childNodes; - for ( $i = 0; $i < $nodeList->length; $i ++ ) { + for ( $i = 0; $i < $node_list->length; $i++ ) { - if ( $nodeList->item( $i )->nodeType !== XML_ELEMENT_NODE ) { + if ( $node_list->item( $i )->nodeType !== XML_ELEMENT_NODE ) { continue; } - if ( $chapter_name != $nodeList->item( $i )->nodeValue && $this->tag != $nodeList->item( $i )->tagName ) { + if ( $chapter_name !== $node_list->item( $i )->nodeValue && $this->tag !== $node_list->item( $i )->tagName ) { // recursive - return $this->findTheNode( $nodeList->item( $i ), $chapter_name ); + return $this->findTheNode( $node_list->item( $i ), $chapter_name ); } } } @@ -596,14 +614,16 @@ protected function findTheNode( \DOMNode $node, $chapter_name ) { * @param \DomDocument $meta */ protected function parseMetaData( \DomDocument $meta ) { - $nodeList = $meta->getElementsByTagName( 'creator' ); - if ( $nodeList->item( 0 ) ) { $this->authors = $nodeList->item( 0 )->nodeValue; + $node_list = $meta->getElementsByTagName( 'creator' ); + if ( $node_list->item( 0 ) ) { + $this->authors = $node_list->item( 0 )->nodeValue; } } /** * * @param array $upload + * * @return boolean */ function setCurrentImportOption( array $upload ) { @@ -613,12 +633,12 @@ function setCurrentImportOption( array $upload ) { return false; } - $option = array( + $option = [ 'file' => $upload['file'], 'file_type' => $upload['type'], 'type_of' => 'docx', - 'chapters' => array(), - ); + 'chapters' => [], + ]; $option['chapters'] = $this->getFuzzyChapterTitles(); @@ -631,7 +651,7 @@ function setCurrentImportOption( array $upload ) { * @return array Chapter titles */ protected function getFuzzyChapterTitles() { - $chapters = array(); + $chapters = []; // get the path to the content and the content $doc_path = $this->getTargetPath( self::DOCUMENT_SCHEMA ); @@ -650,7 +670,7 @@ protected function getFuzzyChapterTitles() { $headings = $dom_doc->getElementsByTagName( $this->tag ); // populate chapters with title names - for ( $i = 0; $i < $headings->length; $i ++ ) { + for ( $i = 0; $i < $headings->length; $i++ ) { $chapters[] = trim( $headings->item( $i )->nodeValue ); } @@ -658,7 +678,7 @@ protected function getFuzzyChapterTitles() { $chapters = array_values( array_filter( $chapters ) ); // default chapter title if there are no h1 headings in the document - if ( 0 == count( $chapters ) ) { + if ( 0 === count( $chapters ) ) { $chapters[] = '__UNKNOWN__'; } @@ -694,6 +714,7 @@ protected function isValidZip( $fullpath ) { * * @param string $schema * @param string $id + * * @return string */ protected function getTargetPath( $schema, $id = '' ) { @@ -712,20 +733,20 @@ protected function getTargetPath( $schema, $id = '' ) { ); foreach ( $relations->Relationship as $rel ) { - if ( $rel['Type'] == $schema ) { + if ( $rel['Type'] === $schema ) { switch ( $id ) { // must be cast as a string to avoid returning SimpleXml Object. case 'footnotes': - $path = 'word/' . ( string ) $rel['Target']; + $path = 'word/' . (string) $rel['Target']; break; case 'endnotes': - $path = 'word/' . ( string ) $rel['Target']; + $path = 'word/' . (string) $rel['Target']; break; case 'hyperlink': - $path[ "{$rel['Id']}" ] = ( string ) $rel['Target']; + $path[ "{$rel['Id']}" ] = (string) $rel['Target']; break; default: - $path = ( string ) $rel['Target']; + $path = (string) $rel['Target']; break; } } @@ -787,14 +808,14 @@ protected function tidy( $html ) { // Reduce the vulnerability for scripting attacks // Make XHTML 1.1 strict using htmlLawed - $config = array( + $config = [ 'safe' => 1, 'valid_xhtml' => 1, 'xml:lang' => 1, // keep xml:lang *and* lang 'no_deprecated_attr' => 2, 'deny_attribute' => 'div -id', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', - ); + ]; return \Pressbooks\HtmLawed::filter( $html, $config ); } diff --git a/includes/modules/import/ooxml/xsl/docx2html.xsl b/inc/modules/import/ooxml/xsl/docx2html.xsl similarity index 100% rename from includes/modules/import/ooxml/xsl/docx2html.xsl rename to inc/modules/import/ooxml/xsl/docx2html.xsl diff --git a/includes/modules/import/wordpress/class-pb-parser.php b/inc/modules/import/wordpress/class-parser.php similarity index 93% rename from includes/modules/import/wordpress/class-pb-parser.php rename to inc/modules/import/wordpress/class-parser.php index 3f25a03454..4f1f30ce4a 100644 --- a/includes/modules/import/wordpress/class-pb-parser.php +++ b/inc/modules/import/wordpress/class-parser.php @@ -3,8 +3,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Import\WordPress; +namespace Pressbooks\Modules\Import\WordPress; /** * This class forked from, inspired by \WXR_Parser_SimpleXML @@ -25,10 +25,10 @@ function parse( $file ) { // Setup & sanity check // ------------------------------------------------------------------------------------------------------------ - $authors = $posts = $categories = $tags = $terms = array(); + $authors = $posts = $categories = $tags = $terms = []; libxml_use_internal_errors( true ); - $oldValue = libxml_disable_entity_loader( true ); + $old_value = libxml_disable_entity_loader( true ); $dom = new \DOMDocument; $dom->recover = true; // Try to parse non-well formed documents $success = $dom->loadXML( file_get_contents( $file ) ); @@ -39,7 +39,7 @@ function parse( $file ) { break; } } - libxml_disable_entity_loader( $oldValue ); + libxml_disable_entity_loader( $old_value ); if ( ! $success || isset( $dom->doctype ) ) { throw new \Exception( print_r( libxml_get_errors(), true ) ); @@ -83,56 +83,57 @@ function parse( $file ) { foreach ( $xml->xpath( '/rss/channel/wp:author' ) as $author_arr ) { $a = $author_arr->children( $namespaces['wp'] ); $login = (string) $a->author_login; - $authors[ $login ] = array( + $authors[ $login ] = [ 'author_id' => (int) $a->author_id, 'author_login' => $login, 'author_email' => (string) $a->author_email, 'author_display_name' => (string) $a->author_display_name, 'author_first_name' => (string) $a->author_first_name, 'author_last_name' => (string) $a->author_last_name, - ); + ]; } // grab cats, tags and terms foreach ( $xml->xpath( '/rss/channel/wp:category' ) as $term_arr ) { $t = $term_arr->children( $namespaces['wp'] ); - $categories[] = array( + $categories[] = [ 'term_id' => (int) $t->term_id, 'category_nicename' => (string) $t->category_nicename, 'category_parent' => (string) $t->category_parent, 'cat_name' => (string) $t->cat_name, 'category_description' => (string) $t->category_description, - ); + ]; } foreach ( $xml->xpath( '/rss/channel/wp:tag' ) as $term_arr ) { $t = $term_arr->children( $namespaces['wp'] ); - $tags[] = array( + $tags[] = [ 'term_id' => (int) $t->term_id, 'tag_slug' => (string) $t->tag_slug, 'tag_name' => (string) $t->tag_name, 'tag_description' => (string) $t->tag_description, - ); + ]; } foreach ( $xml->xpath( '/rss/channel/wp:term' ) as $term_arr ) { $t = $term_arr->children( $namespaces['wp'] ); - $terms[] = array( + $terms[] = [ 'term_id' => (int) $t->term_id, 'term_taxonomy' => (string) $t->term_taxonomy, 'slug' => (string) $t->term_slug, 'term_parent' => (string) $t->term_parent, 'term_name' => (string) $t->term_name, 'term_description' => (string) $t->term_description, - ); + ]; } // grab posts foreach ( $xml->channel->item as $item ) { - $post = array( + /** @var \SimpleXMLElement $item */ + $post = [ 'post_title' => (string) $item->title, 'guid' => (string) $item->guid, - ); + ]; $dc = $item->children( 'http://purl.org/dc/elements/1.1/' ); $post['post_author'] = (string) $dc->creator; @@ -164,33 +165,33 @@ function parse( $file ) { foreach ( $item->category as $c ) { $att = $c->attributes(); if ( isset( $att['nicename'] ) ) { - $post['terms'][] = array( + $post['terms'][] = [ 'name' => (string) $c, 'slug' => (string) $att['nicename'], 'domain' => (string) $att['domain'], - ); + ]; } } foreach ( $wp->postmeta as $meta ) { - $post['postmeta'][] = array( + $post['postmeta'][] = [ 'key' => (string) $meta->meta_key, 'value' => (string) $meta->meta_value, - ); + ]; } foreach ( $wp->comment as $comment ) { - $meta = array(); + $meta = []; if ( isset( $comment->commentmeta ) ) { foreach ( $comment->commentmeta as $m ) { - $meta[] = array( + $meta[] = [ 'key' => (string) $m->meta_key, 'value' => (string) $m->meta_value, - ); + ]; } } - $post['comments'][] = array( + $post['comments'][] = [ 'comment_id' => (int) $comment->comment_id, 'comment_author' => (string) $comment->comment_author, 'comment_author_email' => (string) $comment->comment_author_email, @@ -204,13 +205,13 @@ function parse( $file ) { 'comment_parent' => (string) $comment->comment_parent, 'comment_user_id' => (int) $comment->comment_user_id, 'commentmeta' => $meta, - ); + ]; } $posts[] = $post; } - return array( + return [ 'authors' => $authors, 'posts' => $posts, 'categories' => $categories, @@ -218,7 +219,7 @@ function parse( $file ) { 'terms' => $terms, 'base_url' => $base_url, 'version' => $wxr_version, - ); + ]; } } diff --git a/includes/modules/import/wordpress/class-pb-wxr.php b/inc/modules/import/wordpress/class-wxr.php similarity index 76% rename from includes/modules/import/wordpress/class-pb-wxr.php rename to inc/modules/import/wordpress/class-wxr.php index 2abc179600..5e4934cd17 100644 --- a/includes/modules/import/wordpress/class-pb-wxr.php +++ b/inc/modules/import/wordpress/class-wxr.php @@ -3,8 +3,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Modules\Import\WordPress; +namespace Pressbooks\Modules\Import\WordPress; use Pressbooks\Modules\Import\Import; use Pressbooks\Book; @@ -18,6 +18,16 @@ class Wxr extends Import { */ protected $isPbWxr = false; + /** + * + */ + function __construct() { + if ( ! function_exists( 'media_handle_sideload' ) ) { + require_once( ABSPATH . 'wp-admin/includes/image.php' ); + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + require_once( ABSPATH . 'wp-admin/includes/media.php' ); + } + } /** * @param array $upload @@ -35,14 +45,14 @@ function setCurrentImportOption( array $upload ) { $this->pbCheck( $xml ); - $option = array( + $option = [ 'file' => $upload['file'], 'file_type' => $upload['type'], 'type_of' => 'wxr', - 'chapters' => array(), - 'post_types' => array(), + 'chapters' => [], + 'post_types' => [], 'allow_parts' => true, - ); + ]; /** * Allow custom post types to be imported. @@ -51,7 +61,7 @@ function setCurrentImportOption( array $upload ) { * * @param array */ - $supported_post_types = apply_filters( 'pb_import_custom_post_types', array( 'post', 'page', 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ) ); + $supported_post_types = apply_filters( 'pb_import_custom_post_types', [ 'post', 'page', 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ] ); if ( $this->isPbWxr ) { //put the posts in correct part / menu_order order @@ -61,12 +71,12 @@ function setCurrentImportOption( array $upload ) { foreach ( $xml['posts'] as $p ) { // Skip unsupported post types. - if ( ! in_array( $p['post_type'], $supported_post_types ) ) { + if ( ! in_array( $p['post_type'], $supported_post_types, true ) ) { continue; } // Skip webbook required pages. - if ( '<!-- Here be dragons.-->' == $p['post_content'] || '<!-- Here be dragons. -->' == $p['post_content'] ) { + if ( '<!-- Here be dragons.-->' === $p['post_content'] || '<!-- Here be dragons. -->' === $p['post_content'] ) { continue; } @@ -101,12 +111,12 @@ function import( array $current_import ) { $match_ids = array_flip( array_keys( $current_import['chapters'] ) ); $chapter_parent = $this->getChapterParent(); - $totals = array( + $totals = [ 'front-matter' => 0, 'chapter' => 0, 'part' => 0, 'back-matter' => 0, - ); + ]; /** * Allow custom post taxonomies to be imported. @@ -115,9 +125,9 @@ function import( array $current_import ) { * * @param array */ - $taxonomies = apply_filters( 'pb_import_custom_taxonomies', array( 'front-matter-type', 'chapter-type', 'back-matter-type' ) ); + $taxonomies = apply_filters( 'pb_import_custom_taxonomies', [ 'front-matter-type', 'chapter-type', 'back-matter-type' ] ); - $custom_post_types = apply_filters( 'pb_import_custom_post_types', array( 'post', 'page', 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ) ); + $custom_post_types = apply_filters( 'pb_import_custom_post_types', [ 'post', 'page', 'front-matter', 'chapter', 'part', 'back-matter', 'metadata' ] ); // set custom terms... $terms = apply_filters( 'pb_import_custom_terms', $xml['terms'] ); @@ -129,10 +139,10 @@ function import( array $current_import ) { wp_insert_term( $t['term_name'], $t['term_taxonomy'], - array( + [ 'description' => $t['term_description'], 'slug' => $t['slug'], - ) + ] ); } } @@ -163,23 +173,23 @@ function import( array $current_import ) { $html = $doc->saveXML( $doc->documentElement ); // Remove auto-created <html> <body> and <!DOCTYPE> tags. - $html = preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( array( '<html>', '</html>', '<body>', '</body>' ), array( '', '', '', '' ), $html ) ); + $html = preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( [ '<html>', '</html>', '<body>', '</body>' ], [ '', '', '', '' ], $html ) ); - if ( 'metadata' == $post_type ) { + if ( 'metadata' === $post_type ) { $pid = $this->bookInfoPid(); } else { $pid = $this->insertNewPost( $post_type, $p, $html, $chapter_parent, $current_import['default_post_status'] ); - if ( 'part' == $post_type ) { + if ( 'part' === $post_type ) { $chapter_parent = $pid; } } // if this is a custom post type, // and it has terms associated with it... - if ( ( in_array( $post_type, $custom_post_types ) && isset( $p['terms'] ) ) ) { + if ( ( in_array( $post_type, $custom_post_types, true ) && isset( $p['terms'] ) ) ) { // associate post with terms. foreach ( $p['terms'] as $t ) { - if ( in_array( $t['domain'], $taxonomies ) ) { + if ( in_array( $t['domain'], $taxonomies, true ) ) { wp_set_object_terms( $pid, $t['slug'], @@ -206,13 +216,13 @@ function import( array $current_import ) { // Done $_SESSION['pb_notices'][] = - sprintf( - _x( 'Imported %1$s, %2$s, %3$s, and %4$s.', 'String which tells user how many front matter, parts, chapters and back matter were imported.', 'pressbooks' ), - $totals['front-matter'] . ' ' . __( 'front matter', 'pressbooks' ), - ( 1 == $totals['part'] ) ? $totals['part'] . ' ' . __( 'part', 'pressbooks' ) : $totals['part'] . ' ' . __( 'parts', 'pressbooks' ), - ( 1 == $totals['chapter'] ) ? $totals['chapter'] . ' ' . __( 'chapter', 'pressbooks' ) : $totals['chapter'] . ' ' . __( 'chapters', 'pressbooks' ), - $totals['back-matter'] . ' ' . __( 'back matter', 'pressbooks' ) - ); + sprintf( + _x( 'Imported %1$s, %2$s, %3$s, and %4$s.', 'String which tells user how many front matter, parts, chapters and back matter were imported.', 'pressbooks' ), + $totals['front-matter'] . ' ' . __( 'front matter', 'pressbooks' ), + ( 1 === $totals['part'] ) ? $totals['part'] . ' ' . __( 'part', 'pressbooks' ) : $totals['part'] . ' ' . __( 'parts', 'pressbooks' ), + ( 1 === $totals['chapter'] ) ? $totals['chapter'] . ' ' . __( 'chapter', 'pressbooks' ) : $totals['chapter'] . ' ' . __( 'chapters', 'pressbooks' ), + $totals['back-matter'] . ' ' . __( 'back matter', 'pressbooks' ) + ); return $this->revokeCurrentImport(); } @@ -227,14 +237,15 @@ protected function pbCheck( array $xml ) { foreach ( $xml['posts'] as $p ) { - if ( 'part' == $p['post_type'] ) { $pt = 1; - } elseif ( 'chapter' == $p['post_type'] ) { + if ( 'part' === $p['post_type'] ) { + $pt = 1; + } elseif ( 'chapter' === $p['post_type'] ) { $ch = 1; - } elseif ( 'front-matter' == $p['post_type'] ) { + } elseif ( 'front-matter' === $p['post_type'] ) { $fm = 1; - } elseif ( 'back-matter' == $p['post_type'] ) { + } elseif ( 'back-matter' === $p['post_type'] ) { $bm = 1; - } elseif ( 'metadata' == $p['post_type'] ) { + } elseif ( 'metadata' === $p['post_type'] ) { $meta = 1; } @@ -254,16 +265,18 @@ protected function pbCheck( array $xml ) { * @return array sorted $xml */ protected function customNestedSort( $xml ) { - $array = array(); + $array = []; //first, put them in ascending menu_order - usort( $xml, function ( $a, $b ) { - return ( $a['menu_order'] - $b['menu_order'] ); - }); + usort( + $xml, function ( $a, $b ) { + return ( $a['menu_order'] - $b['menu_order'] ); + } + ); // Start with book info foreach ( $xml as $p ) { - if ( 'metadata' == $p['post_type'] ) { + if ( 'metadata' === $p['post_type'] ) { $array[] = $p; break; } @@ -271,17 +284,17 @@ protected function customNestedSort( $xml ) { //now, list all front matter foreach ( $xml as $p ) { - if ( 'front-matter' == $p['post_type'] ) { - $array[] = $p; + if ( 'front-matter' === $p['post_type'] ) { + $array[] = $p; } } //now, list all parts, then their associated chapters foreach ( $xml as $p ) { - if ( 'part' == $p['post_type'] ) { - $array[] = $p; + if ( 'part' === $p['post_type'] ) { + $array[] = $p; foreach ( $xml as $psub ) { - if ( 'chapter' == $psub['post_type'] && $psub['post_parent'] == $p['post_id'] ) { + if ( 'chapter' === $psub['post_type'] && $psub['post_parent'] === $p['post_id'] ) { $array[] = $psub; } } @@ -290,16 +303,16 @@ protected function customNestedSort( $xml ) { //now, list all back matter foreach ( $xml as $p ) { - if ( 'back-matter' == $p['post_type'] ) { - $array[] = $p; + if ( 'back-matter' === $p['post_type'] ) { + $array[] = $p; } } // Remaining custom post types - $custom_post_types = apply_filters( 'pb_import_custom_post_types', array() ); + $custom_post_types = apply_filters( 'pb_import_custom_post_types', [] ); foreach ( $xml as $p ) { - if ( in_array( $p['post_type'], $custom_post_types ) ) { + if ( in_array( $p['post_type'], $custom_post_types, true ) ) { $array[] = $p; } } @@ -317,11 +330,11 @@ protected function bookInfoPid() { $post = ( new \Pressbooks\Metadata() )->getMetaPost(); if ( empty( $post->ID ) ) { - $new_post = array( + $new_post = [ 'post_title' => __( 'Book Info', 'pressbooks' ), 'post_type' => 'metadata', 'post_status' => 'publish', - ); + ]; $pid = wp_insert_post( add_magic_quotes( $new_post ) ); } else { $pid = $post->ID; @@ -337,23 +350,24 @@ protected function bookInfoPid() { * @param array $p Single Item Returned From \Pressbooks\Modules\Import\WordPress\Parser::parse * @param string $html * @param int $chapter_parent + * @param string $post_status * * @return int Post ID */ protected function insertNewPost( $post_type, $p, $html, $chapter_parent, $post_status ) { - $custom_post_types = apply_filters( 'pb_import_custom_post_types', array() ); + $custom_post_types = apply_filters( 'pb_import_custom_post_types', [] ); - $new_post = array( + $new_post = [ 'post_title' => wp_strip_all_tags( $p['post_title'] ), 'post_type' => $post_type, - 'post_status' => ( 'part' == $post_type ) ? 'publish' : $post_status, - ); + 'post_status' => ( 'part' === $post_type ) ? 'publish' : $post_status, + ]; - if ( 'part' != $post_type ) { + if ( 'part' !== $post_type ) { $new_post['post_content'] = $html; } - if ( 'chapter' == $post_type ) { + if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } @@ -371,15 +385,15 @@ protected function insertNewPost( $post_type, $p, $html, $chapter_parent, $post_ */ protected function importPbPostMeta( $pid, $post_type, $p ) { - if ( 'metadata' == $post_type ) { + if ( 'metadata' === $post_type ) { $this->importMetaBoxes( $pid, $p ); - } elseif ( 'part' == $post_type ) { + } elseif ( 'part' === $post_type ) { $part_content = $this->searchForMetaValue( 'pb_part_content', $p['postmeta'] ); if ( $part_content ) { update_post_meta( $pid, 'pb_part_content', $part_content ); } } else { - $meta_to_update = apply_filters( 'pb_import_metakeys', array( 'pb_section_author', 'pb_section_license', 'pb_short_title', 'pb_subtitle', 'pb_show_title', 'pb_export' ) ); + $meta_to_update = apply_filters( 'pb_import_metakeys', [ 'pb_section_author', 'pb_section_license', 'pb_short_title', 'pb_subtitle', 'pb_show_title', 'pb_export' ] ); foreach ( $meta_to_update as $meta_key ) { $meta_val = $this->searchForMetaValue( $meta_key, $p['postmeta'] ); if ( is_serialized( $meta_val ) ) { @@ -401,11 +415,11 @@ protected function importPbPostMeta( $pid, $post_type, $p ) { protected function importMetaBoxes( $pid, $p ) { // List of meta data keys that can support multiple values: - $multiple = array( + $multiple = [ 'pb_contributing_authors' => true, 'pb_keywords_tags' => true, 'pb_bisac_subject' => true, - ); + ]; // Clear old meta boxes $metadata = get_post_meta( $pid ); @@ -436,7 +450,7 @@ protected function importMetaBoxes( $pid, $p ) { /** * Check for PB specific metadata, returns empty string if not found. * - * @param $meta_key, array $postmeta + * @param $meta_key , array $postmeta * * @return string meta field value */ @@ -448,7 +462,7 @@ protected function searchForMetaValue( $meta_key, array $postmeta ) { foreach ( $postmeta as $meta ) { // prefer this value, if it's set - if ( $meta_key == $meta['key'] ) { + if ( $meta_key === $meta['key'] ) { return $meta['value']; } } @@ -468,6 +482,7 @@ protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { + /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); @@ -505,7 +520,7 @@ protected function fetchAndSaveUniqueImage( $url ) { $remote_img_location = $url; // Cheap cache - static $already_done = array(); + static $already_done = []; if ( isset( $already_done[ $remote_img_location ] ) ) { return $already_done[ $remote_img_location ]; } @@ -547,12 +562,13 @@ protected function fetchAndSaveUniqueImage( $url ) { } } - $pid = media_handle_sideload( array( 'name' => $filename, 'tmp_name' => $tmp_name ), 0 ); + $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name ], 0 ); $src = wp_get_attachment_url( $pid ); - if ( ! $src ) { $src = ''; // Change false to empty string + if ( ! $src ) { + $src = ''; // Change false to empty string } $already_done[ $remote_img_location ] = $src; - @unlink( $tmp_name ); + @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $src; } diff --git a/includes/modules/searchandreplace/class-pb-result.php b/inc/modules/searchandreplace/class-result.php similarity index 94% rename from includes/modules/searchandreplace/class-pb-result.php rename to inc/modules/searchandreplace/class-result.php index d4e0380825..d89f0ef062 100644 --- a/includes/modules/searchandreplace/class-pb-result.php +++ b/inc/modules/searchandreplace/class-result.php @@ -16,7 +16,7 @@ class Result { var $length; var $replace_string; - function single_line() { + function singleLine() { if ( strpos( $this->search_plain, "\r" ) !== false || strpos( $this->search_plain, "\n" ) !== false ) { return false; } diff --git a/includes/modules/searchandreplace/class-pb-search.php b/inc/modules/searchandreplace/class-search.php similarity index 84% rename from includes/modules/searchandreplace/class-pb-search.php rename to inc/modules/searchandreplace/class-search.php index ae08afb756..6ed1edf9c6 100644 --- a/includes/modules/searchandreplace/class-pb-search.php +++ b/inc/modules/searchandreplace/class-search.php @@ -6,6 +6,8 @@ namespace Pressbooks\Modules\SearchAndReplace; +use Pressbooks\Modules\SearchAndReplace\Result; + class Search { var $search = null; var $replace = null; @@ -13,14 +15,13 @@ class Search { var $save = false; var $source = null; var $error = null; - var $regex = false; function name() { return ''; } - function regex_validate( $expr ) { + function regexValidate( $expr ) { // evaluate expression without imput and capture potential error message $regex_error = 'invalid'; $error_handler = function( $errno, $errstr, $errfile, $errline ) use ( &$regex_error ) { @@ -46,22 +47,22 @@ function regex_validate( $expr ) { return null; } - function search_and_replace( $search, $replace, $limit, $offset, $orderby, $save = false ) { + function searchAndReplace( $search, $replace, $limit, $offset, $orderby, $save = false ) { // escape potential backreferences when not in regex mode if ( ! $this->regex ) { $replace = str_replace( '\\', '\\\\', $replace ); $replace = str_replace( '$', '\\$', $replace ); } $this->replace = $replace; - $results = $this->search_for_pattern( $search, $limit, $offset, $orderby ); + $results = $this->searchForPattern( $search, $limit, $offset, $orderby ); if ( false !== $results && $save ) { $this->replace( $results ); } return $results; } - function search_for_pattern( $search, $limit, $offset, $orderby ) { - if ( ! in_array( $orderby, [ 'asc', 'desc' ] ) ) { + function searchForPattern( $search, $limit, $offset, $orderby ) { + if ( ! in_array( $orderby, [ 'asc', 'desc' ], true ) ) { $orderby = 'asc'; } $limit = intval( $limit ); @@ -71,7 +72,7 @@ function search_for_pattern( $search, $limit, $offset, $orderby ) { set_time_limit( 0 ); } if ( $this->regex ) { - $error = $this->regex_validate( $search ); + $error = $this->regexValidate( $search ); if ( null !== $error ) { return __( 'Invalid regular expression', 'pressbooks' ) . ': ' . $error; } @@ -83,17 +84,17 @@ function search_for_pattern( $search, $limit, $offset, $orderby ) { return __( 'No search pattern.', 'pressbooks' ); } - static function get_searches() { + static function getSearches() { global $search_types; if ( ! is_array( $search_types ) ) { $available = get_declared_classes(); - $files = glob( PB_PLUGIN_DIR . 'includes/modules/searchandreplace/types/*.php' ); + $files = glob( PB_PLUGIN_DIR . 'inc/modules/searchandreplace/types/*.php' ); if ( ! empty( $files ) ) { foreach ( $files as $file ) { include_once( $file ); } } - $classes = array(); + $classes = []; $available = array_diff( get_declared_classes(), $available ); if ( count( $available ) > 0 ) { foreach ( $available as $class ) { @@ -105,8 +106,8 @@ static function get_searches() { return $search_types; } - static function valid_search( $class ) { - $classes = \Pressbooks\Modules\SearchAndReplace\Search::get_searches(); + static function validSearch( $class ) { + $classes = Search::getSearches(); foreach ( $classes as $item ) { if ( strcasecmp( get_class( $item ), $class ) === 0 ) { return true; @@ -117,9 +118,9 @@ static function valid_search( $class ) { function matches( $pattern, $content, $id ) { if ( preg_match_all( $pattern, $content, $matches, PREG_OFFSET_CAPTURE ) > 0 ) { - $results = array(); + $results = []; foreach ( $matches[0] as $found ) { - $result = new \Pressbooks\Modules\SearchAndReplace\Result(); + $result = new Result(); $result->id = $id; $result->offset = $found[1]; $result->length = strlen( $found[0] ); @@ -141,7 +142,7 @@ function matches( $pattern, $content, $id ) { $right = rtrim( substr( $content, $found[1] + strlen( $found[0] ), $end ), " \t," ); $result->left = $start; $result->left_length = strlen( $found[0] ) + ( $found[1] - $start) + $end; - if ( 0 != $start ) { + if ( 0 !== $start ) { $result->search = '…'; } $result->search .= esc_html( $left ); @@ -157,7 +158,7 @@ function matches( $pattern, $content, $id ) { // Produce preview $rep = preg_replace( $pattern, $this->replace, $found[0] ); $result->replace_string = $rep; - if ( 0 != $start ) { + if ( 0 !== $start ) { $result->replace = '…'; } $result->replace .= esc_html( $left ); @@ -189,15 +190,15 @@ function replace( $results ) { $lastid = ''; foreach ( $results as $result ) { if ( $result->id !== $lastid ) { - $this->replace_content( $result->id, $result->content ); + $this->replaceContent( $result->id, $result->content ); $lastid = $result->id; } } } } - function replace_inline( $id, $offset, $length, $replace ) { - $content = $this->get_content( $id ); + function replaceInline( $id, $offset, $length, $replace ) { + $content = $this->getContent( $id ); // Delete the original string $before = substr( $content, 0, $offset ); @@ -207,6 +208,6 @@ function replace_inline( $id, $offset, $length, $replace ) { $content = $before . $replace . $after; // Insert back into database - $this->replace_content( $id, $content ); + $this->replaceContent( $id, $content ); } } diff --git a/includes/modules/searchandreplace/class-pb-searchandreplace.php b/inc/modules/searchandreplace/class-searchandreplace.php similarity index 68% rename from includes/modules/searchandreplace/class-pb-searchandreplace.php rename to inc/modules/searchandreplace/class-searchandreplace.php index 3ccc536f04..f80c5ad222 100644 --- a/includes/modules/searchandreplace/class-pb-searchandreplace.php +++ b/inc/modules/searchandreplace/class-searchandreplace.php @@ -8,6 +8,9 @@ namespace Pressbooks\Modules\SearchAndReplace; +use Pressbooks\Modules\SearchAndReplace\Search; +use Pressbooks\Modules\SearchAndReplace\Result; + class SearchAndReplace { private static $instance = null; @@ -21,39 +24,37 @@ static function init() { } function __construct() { - add_filter( 'admin_menu', array( &$this, 'admin_menu' ) ); - add_action( 'load-tools_page_pressbooks-search-and-replace', array( &$this, 'search_head' ) ); + add_filter( 'admin_menu', [ &$this, 'adminMenu' ] ); + add_action( 'load-tools_page_pressbooks-search-and-replace', [ &$this, 'searchHead' ] ); } - function search_head() { - include PB_PLUGIN_DIR . 'includes/modules/searchandreplace/class-pb-search.php'; - include PB_PLUGIN_DIR . 'includes/modules/searchandreplace/class-pb-result.php'; + function searchHead() { wp_enqueue_style( 'search-and-replace', \Pressbooks\Utility\asset_path( 'styles/search-and-replace.css' ) ); wp_register_script( 'search-and-replace', \Pressbooks\Utility\asset_path( 'scripts/search-and-replace.js' ) ); - wp_localize_script( 'search-and-replace', 'pb_sr', $this->get_l10n() ); + wp_localize_script( 'search-and-replace', 'pb_sr', $this->getL10n() ); wp_enqueue_script( 'search-and-replace' ); } - function get_l10n() { + function getL10n() { return [ 'warning_text' => __( 'Once you’ve pressed ‘Replace & Save’ there is no going back! Have you checked ‘Preview Replacements’ to make sure this will do what you want it to do?', 'pressbooks' ), ]; } - function admin_menu() { + function adminMenu() { if ( current_user_can( 'administrator' ) ) { add_management_page( __( 'Search & Replace', 'pressbooks' ), __( 'Search & Replace', 'pressbooks' ), 'administrator', 'pressbooks-search-and-replace', - array( &$this, 'admin_screen' ) + [ &$this, 'adminScreen' ] ); } } - function admin_screen() { - $searches = \Pressbooks\Modules\SearchAndReplace\Search::get_searches(); + function adminScreen() { + $searches = Search::getSearches(); if ( isset( $_POST['search_pattern'] ) && ! wp_verify_nonce( $_POST['pressbooks-search-and-replace-nonce'], 'search' ) ) { return; } @@ -82,7 +83,7 @@ function admin_screen() { $source = isset( $_POST['source'] ) ? stripslashes( $_POST['source'] ) : ''; - if ( \Pressbooks\Modules\SearchAndReplace\Search::valid_search( $source ) && ( isset( $_POST['search'] ) || isset( $_POST['replace'] ) || isset( $_POST['replace_and_save'] ) ) ) { + if ( Search::validSearch( $source ) && ( isset( $_POST['search'] ) || isset( $_POST['replace'] ) || isset( $_POST['replace_and_save'] ) ) ) { $searcher = new $source; // Enable regex mode @@ -94,16 +95,16 @@ function admin_screen() { unset( $_POST['replace_and_save'] ); $_POST['search'] = 'search'; } - $results = array(); + $results = []; if ( isset( $_POST['search'] ) ) { - $results = $searcher->search_for_pattern( $search_pattern, $limit, $offset, $orderby ); + $results = $searcher->searchForPattern( $search_pattern, $limit, $offset, $orderby ); } elseif ( isset( $_POST['replace'] ) ) { - $results = $searcher->search_and_replace( $search_pattern, $replace_pattern, $limit, $offset, $orderby ); + $results = $searcher->searchAndReplace( $search_pattern, $replace_pattern, $limit, $offset, $orderby ); } elseif ( isset( $_POST['replace_and_save'] ) ) { - $results = $searcher->search_and_replace( $search_pattern, $replace_pattern, $limit, $offset, $orderby, true ); + $results = $searcher->searchAndReplace( $search_pattern, $replace_pattern, $limit, $offset, $orderby, true ); } if ( ! is_array( $results ) ) { - $this->render_error( $results ); + $this->renderError( $results ); } elseif ( isset( $_POST['replace_and_save'] ) ) { ?> <div class="updated" id="message" onclick="this.parentNode.removeChild (this)"> @@ -111,12 +112,12 @@ function admin_screen() { </div> <?php } - $this->render( 'search', array( 'search' => $search_pattern, 'replace' => $replace_pattern, 'searches' => $searches, 'source' => $source ) ); + $this->render( 'search', [ 'search' => $search_pattern, 'replace' => $replace_pattern, 'searches' => $searches, 'source' => $source ] ); if ( is_array( $results ) && ! isset( $_POST['replace_and_save'] ) ) { - $this->render( 'results', array( 'search' => $searcher, 'results' => $results ) ); + $this->render( 'results', [ 'search' => $searcher, 'results' => $results ] ); } } else { - $this->render( 'search', array( 'search' => $search_pattern, 'replace' => $replace_pattern, 'searches' => $searches, 'source' => $source ) ); + $this->render( 'search', [ 'search' => $search_pattern, 'replace' => $replace_pattern, 'searches' => $searches, 'source' => $source ] ); } } @@ -130,7 +131,7 @@ private function render( $template, $template_vars = [] ) { } } - function render_error( $message ) { + function renderError( $message ) { ?> <div class="fade error" id="message"> <p><?php echo $message ?></p> diff --git a/includes/modules/searchandreplace/types/class-pb-content.php b/inc/modules/searchandreplace/types/class-content.php similarity index 93% rename from includes/modules/searchandreplace/types/class-pb-content.php rename to inc/modules/searchandreplace/types/class-content.php index b916c0b0cd..b4695b74eb 100644 --- a/includes/modules/searchandreplace/types/class-pb-content.php +++ b/inc/modules/searchandreplace/types/class-content.php @@ -9,9 +9,9 @@ class Content extends \Pressbooks\Modules\SearchAndReplace\Search { function find( $pattern, $limit, $offset, $orderby ) { global $wpdb; - $results = array(); + $results = []; if ( $limit > 0 ) { - if ( 'asc' == $orderby ) { + if ( 'asc' === $orderby ) { $posts = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_content, post_title @@ -39,7 +39,7 @@ function find( $pattern, $limit, $offset, $orderby ) { ); } } else { - if ( 'asc' == $orderby ) { + if ( 'asc' === $orderby ) { $posts = $wpdb->get_results( "SELECT ID, post_content, post_title FROM $wpdb->posts @@ -70,7 +70,7 @@ function find( $pattern, $limit, $offset, $orderby ) { return $results; } - function get_options( $result ) { + function getOptions( $result ) { $options[] = '<a href="' . get_permalink( $result->id ) . '">' . __( 'view', 'pressbooks' ) . '</a>'; if ( current_user_can( 'edit_post', $result->id ) ) { $options[] = '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/post.php?action=edit&post=' . $result->id . '">' . __( 'edit','pressbooks' ) . '</a>'; @@ -91,12 +91,14 @@ function show( $result ) { endswitch; printf( __( '%1$s ID #%2$d: %1$s', 'pressbooks' ), $type, $result->id, $result->title ); } - function get_content( $id ) { + + function getContent( $id ) { global $wpdb; $post = $wpdb->get_row( $wpdb->prepare( "SELECT post_content FROM {$wpdb->prefix}posts WHERE id=%d", $id ) ); return $post->post_content; } - function replace_content( $id, $content ) { + + function replaceContent( $id, $content ) { global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content=%s WHERE ID=%d", $content, $id ) ); wp_cache_flush(); diff --git a/includes/modules/searchandreplace/types/class-pb-part.php b/inc/modules/searchandreplace/types/class-part.php similarity index 93% rename from includes/modules/searchandreplace/types/class-pb-part.php rename to inc/modules/searchandreplace/types/class-part.php index e879a18325..0811ca1612 100644 --- a/includes/modules/searchandreplace/types/class-pb-part.php +++ b/inc/modules/searchandreplace/types/class-part.php @@ -9,9 +9,9 @@ class Part extends \Pressbooks\Modules\SearchAndReplace\Search { function find( $pattern, $limit, $offset, $orderby ) { global $wpdb; - $results = array(); + $results = []; if ( $limit > 0 ) { - if ( 'asc' == $orderby ) { + if ( 'asc' === $orderby ) { $metas = $wpdb->get_results( $wpdb->prepare( "SELECT $wpdb->postmeta.meta_id AS meta_id, @@ -47,7 +47,7 @@ function find( $pattern, $limit, $offset, $orderby ) { ); } } else { - if ( 'asc' == $orderby ) { + if ( 'asc' === $orderby ) { $metas = $wpdb->get_results( "SELECT $wpdb->postmeta.meta_id AS meta_id, $wpdb->postmeta.meta_value AS meta_value, @@ -88,17 +88,19 @@ function find( $pattern, $limit, $offset, $orderby ) { return $results; } - function get_options( $result ) { + function getOptions( $result ) { $options[] = '<a href="' . get_permalink( $result->sub_id ) . '">' . __( 'view', 'pressbooks' ) . '</a>'; if ( current_user_can( 'edit_post', $result->sub_id ) ) { $options[] = '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/post.php?action=edit&post=' . $result->sub_id . '">' . __( 'edit','pressbooks' ) . '</a>'; } return $options; } + function show( $result ) { printf( __( 'Part ID #%1$d: %2$s', 'pressbooks' ), $result->sub_id, $result->title ); } - function get_content( $id ) { + + function getContent( $id ) { global $wpdb; $post = $wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_id=%d", $id ) ); return $post->meta_value; @@ -111,7 +113,7 @@ function replace( $results ) { $lastid = ''; foreach ( $results as $result ) { if ( $result->id !== $lastid ) { - $this->replace_content( $result->sub_id, $result->content ); + $this->replaceContent( $result->sub_id, $result->content ); $lastid = $result->id; } } @@ -119,7 +121,7 @@ function replace( $results ) { } } - function replace_content( $id, $content ) { + function replaceContent( $id, $content ) { update_post_meta( $id, 'pb_part_content', $content ); } diff --git a/includes/modules/themeoptions/class-pb-ebookoptions.php b/inc/modules/themeoptions/class-ebookoptions.php similarity index 75% rename from includes/modules/themeoptions/class-pb-ebookoptions.php rename to inc/modules/themeoptions/class-ebookoptions.php index 40c2fc2292..a6ecc23a91 100644 --- a/includes/modules/themeoptions/class-pb-ebookoptions.php +++ b/inc/modules/themeoptions/class-ebookoptions.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Modules\ThemeOptions; class EbookOptions extends \Pressbooks\Options { @@ -16,24 +17,24 @@ class EbookOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Web theme options. - * - * @var array - */ + * Web theme options. + * + * @var array + */ public $options; /** - * Web theme defaults. - * - * @var array - */ + * Web theme defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -57,38 +58,38 @@ function init() { $_page = $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_section = $this->getSlug() . '_options_section'; - if ( false == get_option( $_option ) ) { + if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'ebook_paragraph_separation', __( 'Paragraph Separation', 'pressbooks' ), - array( $this, 'renderParagraphSeparationField' ), + [ $this, 'renderParagraphSeparationField' ], $_page, $_section, - array( + [ 'indent' => __( 'Indent paragraphs', 'pressbooks' ), 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), - ) + ] ); add_settings_field( 'ebook_compress_images', __( 'Compress Images', 'pressbooks' ), - array( $this, 'renderCompressImagesField' ), + [ $this, 'renderCompressImagesField' ], $_page, $_section, - array( - __( 'Reduce image size and quality', 'pressbooks' ) - ) + [ + __( 'Reduce image size and quality', 'pressbooks' ), + ] ); /** @@ -101,7 +102,7 @@ function init() { register_setting( $_option, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -115,7 +116,8 @@ function display() { /** * Render the Ebook options tab form (NOT USED). */ - function render() {} + function render() { + } /** * Upgrade handler for Ebook options. @@ -135,9 +137,9 @@ function doInitialUpgrade() { $_option = $this->getSlug(); $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); - if ( ! isset( $options['ebook_paragraph_separation'] ) || '1' == $options['ebook_paragraph_separation'] ) { + if ( ! isset( $options['ebook_paragraph_separation'] ) || 1 === absint( $options['ebook_paragraph_separation'] ) ) { $options['ebook_paragraph_separation'] = 'indent'; - } elseif ( '2' == $options['ebook_paragraph_separation'] ) { + } elseif ( 2 === absint( $options['ebook_paragraph_separation'] ) ) { $options['ebook_paragraph_separation'] = 'skiplines'; } @@ -146,30 +148,36 @@ function doInitialUpgrade() { /** * Render the ebook_paragraph_separation radio buttons. + * * @param array $args */ function renderParagraphSeparationField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'ebook_paragraph_separation', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'ebook_paragraph_separation', - 'value' => ( isset( $this->options['ebook_paragraph_separation'] ) ) ? $this->options['ebook_paragraph_separation'] : '', - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'ebook_paragraph_separation', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'ebook_paragraph_separation', + 'value' => ( isset( $this->options['ebook_paragraph_separation'] ) ) ? $this->options['ebook_paragraph_separation'] : '', + 'choices' => $args, + ] + ); } /** * Render the ebook_compress_images checkbox. + * * @param array $args */ function renderCompressImagesField( $args ) { - $this->renderCheckbox( array( - 'id' => 'ebook_compress_images', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'ebook_compress_images', - 'value' => ( isset( $this->options['ebook_compress_images'] ) ) ? $this->options['ebook_compress_images'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'ebook_compress_images', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'ebook_compress_images', + 'value' => ( isset( $this->options['ebook_compress_images'] ) ) ? $this->options['ebook_compress_images'] : '', + 'label' => $args[0], + ] + ); } /** @@ -199,16 +207,19 @@ static function getDefaults() { /** * @since 3.9.7 TODO */ - return apply_filters( 'pb_theme_options_ebook_defaults', array( + return apply_filters( + 'pb_theme_options_ebook_defaults', [ 'ebook_paragraph_separation' => 'indent', 'ebook_compress_images' => 0, - ) ); + ] + ); } /** * Filter the array of default values for the Ebook options tab. * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { @@ -226,9 +237,11 @@ static function getBooleanOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_ebook_booleans', array( - 'ebook_compress_images' - ) ); + return apply_filters( + 'pb_theme_options_ebook_booleans', [ + 'ebook_compress_images', + ] + ); } /** @@ -242,7 +255,7 @@ static function getStringOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_ebook_strings', array() ); + return apply_filters( 'pb_theme_options_ebook_strings', [] ); } /** @@ -256,7 +269,7 @@ static function getIntegerOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_ebook_integers', array() ); + return apply_filters( 'pb_theme_options_ebook_integers', [] ); } /** @@ -270,7 +283,7 @@ static function getFloatOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_ebook_floats', array() ); + return apply_filters( 'pb_theme_options_ebook_floats', [] ); } /** @@ -284,14 +297,20 @@ static function getPredefinedOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_ebook_predefined', array( - 'ebook_paragraph_separation' - ) ); + return apply_filters( + 'pb_theme_options_ebook_predefined', [ + 'ebook_paragraph_separation', + ] + ); } /** * Apply overrides. * + * @param string $scss + * + * @return string + * * @since 3.9.8 */ static function scssOverrides( $scss ) { @@ -315,7 +334,7 @@ static function scssOverrides( $scss ) { $options = get_option( 'pressbooks_theme_options_ebook' ); // Indent paragraphs? - if ( 'skiplines' == $options['ebook_paragraph_separation'] ) { + if ( 'skiplines' === $options['ebook_paragraph_separation'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$para-margin-top: 1em; \n"; $scss .= "\$para-indent: 0; \n"; diff --git a/includes/modules/themeoptions/class-pb-globaloptions.php b/inc/modules/themeoptions/class-globaloptions.php similarity index 70% rename from includes/modules/themeoptions/class-pb-globaloptions.php rename to inc/modules/themeoptions/class-globaloptions.php index b88713686a..a0a6637de3 100644 --- a/includes/modules/themeoptions/class-pb-globaloptions.php +++ b/inc/modules/themeoptions/class-globaloptions.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Modules\ThemeOptions; use Pressbooks\Container; @@ -18,24 +19,24 @@ class GlobalOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Global theme options. - * - * @var array - */ + * Global theme options. + * + * @var array + */ public $options; /** - * Global theme defaults. - * - * @var array - */ + * Global theme defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -59,56 +60,56 @@ function init() { $_page = $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_section = $this->getSlug() . '_options_section'; - if ( false == get_option( $_option ) ) { + if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'chapter_numbers', __( 'Part and Chapter Numbers', 'pressbooks' ), - array( $this, 'renderChapterNumbersField' ), + [ $this, 'renderChapterNumbersField' ], $_page, $_section, - array( - __( 'Display part and chapter numbers', 'pressbooks' ) - ) + [ + __( 'Display part and chapter numbers', 'pressbooks' ), + ] ); add_settings_field( 'parse_subsections', __( 'Two-Level TOC', 'pressbooks' ), - array( $this, 'renderTwoLevelTOCField' ), + [ $this, 'renderTwoLevelTOCField' ], $_page, $_section, - array( - __( 'Enable two-level table of contents (displays headings under chapter titles)', 'pressbooks' ) - ) + [ + __( 'Enable two-level table of contents (displays headings under chapter titles)', 'pressbooks' ), + ] ); - if ( \Pressbooks\Container::get( 'Sass' )->isCurrentThemeCompatible( 1 ) == true || \Pressbooks\Container::get( 'Sass' )->isCurrentThemeCompatible( 2 ) == true ) { // we can only enable foreign language typography for themes that use SCSS + if ( Container::get( 'Sass' )->isCurrentThemeCompatible( 1 ) === true || Container::get( 'Sass' )->isCurrentThemeCompatible( 2 ) === true ) { // we can only enable foreign language typography for themes that use SCSS add_settings_field( 'pressbooks_global_typography', __( 'Language Support', 'pressbooks' ), - array( $this, 'renderLanguagesField' ), + [ $this, 'renderLanguagesField' ], $_page, $_section, - array( - __( 'Include fonts to support the following languages:', 'pressbooks' ) - ) + [ + __( 'Include fonts to support the following languages:', 'pressbooks' ), + ] ); register_setting( $_page, 'pressbooks_global_typography', - array( $this, 'sanitizeLanguages' ) + [ $this, 'sanitizeLanguages' ] ); } @@ -116,12 +117,12 @@ function init() { add_settings_field( 'copyright_license', __( 'Copyright License', 'pressbooks' ), - array( $this, 'renderCopyrightLicenseField' ), + [ $this, 'renderCopyrightLicenseField' ], $_page, $_section, - array( - __( 'Display the selected copyright license', 'pressbooks' ) - ) + [ + __( 'Display the selected copyright license', 'pressbooks' ), + ] ); /** @@ -134,7 +135,7 @@ function init() { register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -148,14 +149,19 @@ function display() { /** * Render the PDF options tab form (NOT USED). */ - function render() {} + function render() { + } /** * Sanitize the languages (just returns the array or an empty array, as these are predefined values). + * + * @param mixed $input + * + * @return array */ function sanitizeLanguages( $input ) { if ( ! is_array( $input ) ) { - $input = array(); + $input = []; } return $input; } @@ -177,12 +183,12 @@ function upgrade( $version ) { function doInitialUpgrade() { $_option = $this->getSlug(); $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); - $deprecated = array( + $deprecated = [ 'pressbooks_enable_chapter_types', - ); + ]; foreach ( $options as $key => $value ) { - if ( in_array( $key, $deprecated ) ) { + if ( in_array( $key, $deprecated, true ) ) { unset( $options[ $key ] ); } } @@ -199,48 +205,55 @@ function doInitialUpgrade() { /** * Render the chapter_numbers checkbox. + * * @param array $args */ function renderChapterNumbersField( $args ) { - $this->renderCheckbox( array( - 'id' => 'chapter_numbers', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'chapter_numbers', - 'value' => ( isset( $this->options['chapter_numbers'] ) ) ? $this->options['chapter_numbers'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'chapter_numbers', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'chapter_numbers', + 'value' => ( isset( $this->options['chapter_numbers'] ) ) ? $this->options['chapter_numbers'] : '', + 'label' => $args[0], + ] + ); } /** * Render the parse_subsections checkbox. + * * @param array $args */ function renderTwoLevelTOCField( $args ) { - $this->renderCheckbox( array( - 'id' => 'parse_subsections', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'parse_subsections', - 'value' => ( isset( $this->options['parse_subsections'] ) ) ? $this->options['parse_subsections'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'parse_subsections', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'parse_subsections', + 'value' => ( isset( $this->options['parse_subsections'] ) ) ? $this->options['parse_subsections'] : '', + 'label' => $args[0], + ] + ); } /** * Render the pressbooks_global_typography select. + * * @param array $args */ function renderLanguagesField( $args ) { $foreign_languages = get_option( 'pressbooks_global_typography' ); if ( ! $foreign_languages ) { - $foreign_languages = array(); + $foreign_languages = []; } - $languages = \Pressbooks\Container::get( 'GlobalTypography' )->getSupportedLanguages(); + $languages = Container::get( 'GlobalTypography' )->getSupportedLanguages(); - $already_supported_languages = \Pressbooks\Container::get( 'GlobalTypography' )->getThemeSupportedLanguages(); + $already_supported_languages = Container::get( 'GlobalTypography' )->getThemeSupportedLanguages(); - if ( false == $already_supported_languages ) { + if ( false === $already_supported_languages ) { $already_supported_languages = []; } @@ -250,7 +263,7 @@ function renderLanguagesField( $args ) { $c = count( $already_supported_languages ); foreach ( $already_supported_languages as $lang ) { $already_supported_languages_string .= $languages[ $lang ]; - if ( $i < $c && $i == $c - 1 ) { + if ( $i < $c && $i === $c - 1 ) { $already_supported_languages_string .= ' ' . __( 'and', 'pressbooks' ) . ' '; } elseif ( $i < $c ) { $already_supported_languages_string .= ', '; @@ -262,7 +275,7 @@ function renderLanguagesField( $args ) { $html = '<label for="global_typography"> ' . $args[0] . '</label><br /><br />'; $html .= '<select id="global_typography" class="select2" style="width: 75%" data-placeholder="' . __( 'Select languages…', 'pressbooks' ) . '" name="pressbooks_global_typography[]" multiple>'; foreach ( $languages as $key => $value ) { - $selected = ( in_array( $key, $foreign_languages ) || in_array( $key, $already_supported_languages ) ) ? ' selected' : ''; + $selected = ( in_array( $key, $foreign_languages, true ) || in_array( $key, $already_supported_languages, true ) ) ? ' selected' : ''; $html .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>'; } $html .= '</select>'; @@ -276,16 +289,19 @@ function renderLanguagesField( $args ) { /** * Render the copyright_license checkbox. + * * @param array $args */ function renderCopyrightLicenseField( $args ) { - $this->renderCheckbox( array( - 'id' => 'copyright_license', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'copyright_license', - 'value' => ( isset( $this->options['copyright_license'] ) ) ? $this->options['copyright_license'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'copyright_license', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'copyright_license', + 'value' => ( isset( $this->options['copyright_license'] ) ) ? $this->options['copyright_license'] : '', + 'label' => $args[0], + ] + ); } /** @@ -315,17 +331,20 @@ static function getDefaults() { /** * @since 3.9.7 TODO */ - return apply_filters( 'pb_theme_options_global_defaults', array( + return apply_filters( + 'pb_theme_options_global_defaults', [ 'chapter_numbers' => 1, 'parse_subsections' => 0, 'copyright_license' => 0, - ) ); + ] + ); } /** * Filter the array of default values for the Global options tab. * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { @@ -343,11 +362,13 @@ static function getBooleanOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_global_booleans', array( + return apply_filters( + 'pb_theme_options_global_booleans', [ 'chapter_numbers', 'parse_subsections', 'copyright_license', - ) ); + ] + ); } /** @@ -361,7 +382,7 @@ static function getStringOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_global_strings', array() ); + return apply_filters( 'pb_theme_options_global_strings', [] ); } /** @@ -375,7 +396,7 @@ static function getIntegerOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_global_integers', array() ); + return apply_filters( 'pb_theme_options_global_integers', [] ); } /** @@ -389,7 +410,7 @@ static function getFloatOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_global_floats', array() ); + return apply_filters( 'pb_theme_options_global_floats', [] ); } /** @@ -403,6 +424,6 @@ static function getPredefinedOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_global_predefined', array() ); + return apply_filters( 'pb_theme_options_global_predefined', [] ); } } diff --git a/includes/modules/themeoptions/class-pb-pdfoptions.php b/inc/modules/themeoptions/class-pdfoptions.php similarity index 65% rename from includes/modules/themeoptions/class-pb-pdfoptions.php rename to inc/modules/themeoptions/class-pdfoptions.php index a4eef6ae02..36c7927cb6 100644 --- a/includes/modules/themeoptions/class-pb-pdfoptions.php +++ b/inc/modules/themeoptions/class-pdfoptions.php @@ -3,10 +3,11 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Modules\ThemeOptions; -use Pressbooks\Container; use Pressbooks\CustomCss; +use function \Pressbooks\Utility\getset; class PDFOptions extends \Pressbooks\Options { @@ -19,24 +20,24 @@ class PDFOptions extends \Pressbooks\Options { const VERSION = 2; /** - * PDF theme options. - * - * @var array - */ + * PDF theme options. + * + * @var array + */ public $options; /** - * PDF theme defaults. - * - * @var array - */ + * PDF theme defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -60,14 +61,14 @@ function init() { $_page = $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_section = $this->getSlug() . '_options_section'; - if ( false == get_option( $_option ) ) { + if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), - array( $this, 'display' ), + [ $this, 'display' ], $_page ); @@ -75,226 +76,226 @@ function init() { add_settings_field( 'pdf_body_font_size', __( 'Body Font Size', 'pressbooks' ), - array( $this, 'renderBodyFontSizeField' ), + [ $this, 'renderBodyFontSizeField' ], $_page, $_section, - array( + [ __( 'Heading sizes are proportional to the body font size and will also be affected by this setting.', 'pressbooks' ), 'pt', - ) + ] ); add_settings_field( 'pdf_body_line_height', __( 'Body Line Height', 'pressbooks' ), - array( $this, 'renderBodyLineHightField' ), + [ $this, 'renderBodyLineHightField' ], $_page, $_section, - array( + [ '', 'em', - ) + ] ); } add_settings_field( 'pdf_page_size', __( 'Page Size', 'pressbooks' ), - array( $this, 'renderPageSizeField' ), + [ $this, 'renderPageSizeField' ], $_page, $_section, - array( - __( 'Digest (5.5" × 8.5")', 'pressbooks' ), - __( 'US Trade (6" × 9")', 'pressbooks' ), - __( 'US Letter (8.5" × 11")', 'pressbooks' ), - __( 'Custom (8.5" × 9.25")', 'pressbooks' ), - __( 'Duodecimo (5" × 7.75")', 'pressbooks' ), - __( 'Pocket (4.25" × 7")', 'pressbooks' ), - __( 'A4 (21cm × 29.7cm)', 'pressbooks' ), - __( 'A5 (14.8cm × 21cm)', 'pressbooks' ), - __( '5" × 8"', 'pressbooks' ), - __( 'Custom…', 'pressbooks' ), - ) + [ + __( 'Digest (5.5" × 8.5")', 'pressbooks' ), + __( 'US Trade (6" × 9")', 'pressbooks' ), + __( 'US Letter (8.5" × 11")', 'pressbooks' ), + __( 'Custom (8.5" × 9.25")', 'pressbooks' ), + __( 'Duodecimo (5" × 7.75")', 'pressbooks' ), + __( 'Pocket (4.25" × 7")', 'pressbooks' ), + __( 'A4 (21cm × 29.7cm)', 'pressbooks' ), + __( 'A5 (14.8cm × 21cm)', 'pressbooks' ), + __( '5" × 8"', 'pressbooks' ), + __( 'Custom…', 'pressbooks' ), + ] ); add_settings_field( 'pdf_page_width', __( 'Page Width', 'pressbooks' ), - array( $this, 'renderPageWidthField' ), + [ $this, 'renderPageWidthField' ], $_page, $_section, - array( - __( 'Page width must be expressed in CSS-compatible units, e.g. ‘5.5in’ or ‘10cm’.' ) - ) + [ + __( 'Page width must be expressed in CSS-compatible units, e.g. ‘5.5in’ or ‘10cm’.' ), + ] ); add_settings_field( 'pdf_page_height', __( 'Page Height', 'pressbooks' ), - array( $this, 'renderPageHeightField' ), + [ $this, 'renderPageHeightField' ], $_page, $_section, - array( - __( 'Page height must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.' ) - ) + [ + __( 'Page height must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.' ), + ] ); if ( \Pressbooks\Container::get( 'Sass' )->isCurrentThemeCompatible( 2 ) ) { add_settings_field( 'pdf_page_margins', __( 'Margins', 'pressbooks' ), - array( $this, 'renderMarginsField' ), + [ $this, 'renderMarginsField' ], $_page, $_section, - array( - __( 'Customize your book’s margins using the fields below.', 'pressbooks' ) - ) + [ + __( 'Customize your book’s margins using the fields below.', 'pressbooks' ), + ] ); add_settings_field( 'pdf_page_margin_outside', __( 'Outside Margin', 'pressbooks' ), - array( $this, 'renderOutsideMarginField' ), + [ $this, 'renderOutsideMarginField' ], $_page, $_section, - array( - __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ) - ) + [ + __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ), + ] ); add_settings_field( 'pdf_page_margin_inside', __( 'Inside Margin', 'pressbooks' ), - array( $this, 'renderInsideMarginField' ), + [ $this, 'renderInsideMarginField' ], $_page, $_section, - array( - __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ) - ) + [ + __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ), + ] ); add_settings_field( 'pdf_page_margin_top', __( 'Top Margin', 'pressbooks' ), - array( $this, 'renderTopMarginField' ), + [ $this, 'renderTopMarginField' ], $_page, $_section, - array( - __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ) - ) + [ + __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ), + ] ); add_settings_field( 'pdf_page_margin_bottom', __( 'Bottom Margin', 'pressbooks' ), - array( $this, 'renderBottomMarginField' ), + [ $this, 'renderBottomMarginField' ], $_page, $_section, - array( - __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ) - ) + [ + __( 'Margins must be expressed in CSS-compatible units, e.g. ‘8.5in’ or ‘10cm’.', 'pressbooks' ), + ] ); } add_settings_field( 'pdf_hyphens', __( 'Hyphens', 'pressbooks' ), - array( $this, 'renderHyphenationField' ), + [ $this, 'renderHyphenationField' ], $_page, $_section, - array( - __( 'Enable hyphenation', 'pressbooks' ) - ) + [ + __( 'Enable hyphenation', 'pressbooks' ), + ] ); add_settings_field( 'pdf_paragraph_separation', __( 'Paragraph Separation', 'pressbooks' ), - array( $this, 'renderParagraphSeparationField' ), + [ $this, 'renderParagraphSeparationField' ], $_page, $_section, - array( - 'indent' => __( 'Indent paragraphs', 'pressbooks' ), - 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), - ) + [ + 'indent' => __( 'Indent paragraphs', 'pressbooks' ), + 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), + ] ); add_settings_field( 'pdf_sectionopenings', __( 'Section Openings', 'pressbooks' ), - array( $this, 'renderSectionOpeningsField' ), + [ $this, 'renderSectionOpeningsField' ], $_page, $_section, - array( - 'openauto' => __( 'Left or right page section opening (for print PDF)', 'pressbooks' ), - 'openright' => __( 'Right page section openings (for print PDF)', 'pressbooks' ), - 'remove' => __( 'No blank pages (for web PDF)', 'pressbooks' ), - ) + [ + 'openauto' => __( 'Left or right page section opening (for print PDF)', 'pressbooks' ), + 'openright' => __( 'Right page section openings (for print PDF)', 'pressbooks' ), + 'remove' => __( 'No blank pages (for web PDF)', 'pressbooks' ), + ] ); add_settings_field( 'pdf_toc', __( 'Table of Contents', 'pressbooks' ), - array( $this, 'renderTOCField' ), + [ $this, 'renderTOCField' ], $_page, $_section, - array( - __( 'Display table of contents', 'pressbooks' ) - ) + [ + __( 'Display table of contents', 'pressbooks' ), + ] ); add_settings_field( 'pdf_image_resolution', __( 'Image resolution', 'pressbooks' ), - array( $this, 'renderImageResolutionField' ), + [ $this, 'renderImageResolutionField' ], $_page, $_section, - array( + [ '300dpi' => __( 'High (300 DPI)', 'pressbooks' ), '72dpi' => __( 'Low (72 DPI)', 'pressbooks' ), - ) + ] ); add_settings_field( 'pdf_crop_marks', __( 'Crop Marks', 'pressbooks' ), - array( $this, 'renderCropMarksField' ), + [ $this, 'renderCropMarksField' ], $_page, $_section, - array( - __( 'Display crop marks', 'pressbooks' ) - ) + [ + __( 'Display crop marks', 'pressbooks' ), + ] ); if ( CustomCss::isCustomCss() ) { add_settings_field( 'pdf_romanize_parts', __( 'Romanize Part Numbers', 'pressbooks' ), - array( $this, 'renderRomanizePartsField' ), + [ $this, 'renderRomanizePartsField' ], $_page, $_section, - array( - __( 'Convert part numbers into Roman numerals', 'pressbooks' ) - ) + [ + __( 'Convert part numbers into Roman numerals', 'pressbooks' ), + ] ); } add_settings_field( 'pdf_footnotes_style', __( 'Footnote Style', 'pressbooks' ), - array( $this, 'renderFootnoteStyleField' ), + [ $this, 'renderFootnoteStyleField' ], $_page, $_section, - array( - 'footnotes' => __( 'Regular footnotes', 'pressbooks' ), - 'endnotes' => __( 'Display as chapter endnotes', 'pressbooks' ), - ) + [ + 'footnotes' => __( 'Regular footnotes', 'pressbooks' ), + 'endnotes' => __( 'Display as chapter endnotes', 'pressbooks' ), + ] ); add_settings_field( 'widows', __( 'Widows', 'pressbooks' ), - array( $this, 'renderWidowsField' ), + [ $this, 'renderWidowsField' ], $_page, $_section ); @@ -302,7 +303,7 @@ function init() { add_settings_field( 'orphans', __( 'Orphans', 'pressbooks' ), - array( $this, 'renderOrphansField' ), + [ $this, 'renderOrphansField' ], $_page, $_section ); @@ -311,21 +312,21 @@ function init() { add_settings_field( 'running_content', __( 'Running Heads & Feet', 'pressbooks' ), - array( $this, 'renderRunningContentField' ), + [ $this, 'renderRunningContentField' ], $_page, $_section, - array( - __( 'Running content appears in either running heads or running feet (at the top or bottom of the page) depending on your theme.', 'pressbooks' ) - ) + [ + __( 'Running content appears in either running heads or running feet (at the top or bottom of the page) depending on your theme.', 'pressbooks' ), + ] ); add_settings_field( 'running_content_front_matter_left', __( 'Front Matter Left Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentFrontMatterLeftField' ), + [ $this, 'renderRunningContentFrontMatterLeftField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -334,16 +335,16 @@ function init() { '%section_subtitle%' => __( 'Front Matter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_front_matter_right', __( 'Front Matter Right Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentFrontMatterRightField' ), + [ $this, 'renderRunningContentFrontMatterRightField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -352,16 +353,16 @@ function init() { '%section_subtitle%' => __( 'Front Matter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_introduction_left', __( 'Introduction Left Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentIntroductionLeftField' ), + [ $this, 'renderRunningContentIntroductionLeftField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -370,16 +371,16 @@ function init() { '%section_subtitle%' => __( 'Introduction Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_introduction_right', __( 'Introduction Right Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentIntroductionRightField' ), + [ $this, 'renderRunningContentIntroductionRightField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -388,16 +389,16 @@ function init() { '%section_subtitle%' => __( 'Introduction Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_part_left', __( 'Part Left Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentPartLeftField' ), + [ $this, 'renderRunningContentPartLeftField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -405,16 +406,16 @@ function init() { '%part_title%' => __( 'Part Title', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_part_right', __( 'Part Right Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentPartRightField' ), + [ $this, 'renderRunningContentPartRightField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -422,16 +423,16 @@ function init() { '%part_title%' => __( 'Part Title', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_chapter_left', __( 'Chapter Left Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentChapterLeftField' ), + [ $this, 'renderRunningContentChapterLeftField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -442,16 +443,16 @@ function init() { '%section_subtitle%' => __( 'Chapter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_chapter_right', __( 'Chapter Right Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentChapterRightField' ), + [ $this, 'renderRunningContentChapterRightField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -462,16 +463,16 @@ function init() { '%section_subtitle%' => __( 'Chapter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_back_matter_left', __( 'Back Matter Left Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentBackMatterLeftField' ), + [ $this, 'renderRunningContentBackMatterLeftField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -480,16 +481,16 @@ function init() { '%section_subtitle%' => __( 'Back Matter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); add_settings_field( 'running_content_back_matter_right', __( 'Back Matter Right Page Running Content', 'pressbooks' ), - array( $this, 'renderRunningContentBackMatterRightField' ), + [ $this, 'renderRunningContentBackMatterRightField' ], $_page, $_section, - array( + [ '%book_title%' => __( 'Book Title', 'pressbooks' ), '%book_subtitle%' => __( 'Book Subtitle', 'pressbooks' ), '%book_author%' => __( 'Book Author', 'pressbooks' ), @@ -498,21 +499,21 @@ function init() { '%section_subtitle%' => __( 'Back Matter Subtitle', 'pressbooks' ), '%blank%' => __( 'Blank', 'pressbooks' ), '' => __( 'Custom…', 'pressbooks' ), - ) + ] ); } if ( ! \Pressbooks\Container::get( 'Sass' )->isCurrentThemeCompatible( 2 ) ) { - add_settings_field( - 'pdf_fontsize', - __( 'Increase Font Size', 'pressbooks' ), - array( $this, 'renderFontSizeField' ), - $_page, - $_section, - array( - __( 'Increases font size and line height for greater accessibility', 'pressbooks' ) - ) - ); + add_settings_field( + 'pdf_fontsize', + __( 'Increase Font Size', 'pressbooks' ), + [ $this, 'renderFontSizeField' ], + $_page, + $_section, + [ + __( 'Increases font size and line height for greater accessibility', 'pressbooks' ), + ] + ); } /** @@ -525,7 +526,7 @@ function init() { register_setting( $_option, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -539,7 +540,8 @@ function display() { /** * Render the PDF options tab form (NOT USED). */ - function render() {} + function render() { + } /** * Upgrade handler for PDF options. @@ -609,21 +611,21 @@ function doInitialUpgrade() { } // Substitute human-readable values - if ( ! isset( $options['pdf_paragraph_separation'] ) || '1' == $options['pdf_paragraph_separation'] ) { + if ( ! isset( $options['pdf_paragraph_separation'] ) || 1 === absint( $options['pdf_paragraph_separation'] ) ) { $options['pdf_paragraph_separation'] = 'indent'; - } elseif ( '2' == $options['pdf_paragraph_separation'] ) { + } elseif ( 2 === absint( $options['pdf_paragraph_separation'] ) ) { $options['pdf_paragraph_separation'] = 'skiplines'; } - if ( ! isset( $options['pdf_blankpages'] ) || '1' == $options['pdf_blankpages'] ) { + if ( ! isset( $options['pdf_blankpages'] ) || 1 === absint( $options['pdf_blankpages'] ) ) { $options['pdf_blankpages'] = 'include'; - } elseif ( '2' == $options['pdf_blankpages'] ) { + } elseif ( 2 === absint( $options['pdf_blankpages'] ) ) { $options['pdf_blankpages'] = 'remove'; } - if ( ! isset( $options['pdf_footnotes_style'] ) || '1' == $options['pdf_footnotes_style'] ) { + if ( ! isset( $options['pdf_footnotes_style'] ) || 1 === absint( $options['pdf_footnotes_style'] ) ) { $options['pdf_footnotes_style'] = 'footnotes'; - } elseif ( '2' == $options['pdf_footnotes_style'] ) { + } elseif ( 2 === absint( $options['pdf_footnotes_style'] ) ) { $options['pdf_footnotes_style'] = 'endnotes'; } @@ -645,9 +647,9 @@ function upgradeSectionOpenings() { $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); // Get more specific - if ( ! isset( $options['pdf_blankpages'] ) || '1' == $options['pdf_blankpages'] || 'include' == $options['pdf_blankpages'] ) { + if ( ! isset( $options['pdf_blankpages'] ) || 1 === absint( $options['pdf_blankpages'] ) || 'include' === $options['pdf_blankpages'] ) { $options['pdf_sectionopenings'] = 'openauto'; - } elseif ( '2' == $options['pdf_blankpages'] || 'remove' == $options['pdf_blankpages'] ) { + } elseif ( 2 === absint( $options['pdf_blankpages'] ) || 'remove' === $options['pdf_blankpages'] ) { $options['pdf_sectionopenings'] = 'remove'; } unset( $options['pdf_blankpages'] ); @@ -657,62 +659,69 @@ function upgradeSectionOpenings() { /** * Render the pdf_body_font_size input. + * * @param array $args */ function renderBodyFontSizeField( $args ) { - $this->renderField( array( - 'id' => 'pdf_body_font_size', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_body_font_size', - 'value' => ( isset( $this->options['pdf_body_font_size'] ) ) ? $this->options['pdf_body_font_size'] : $this->defaults['pdf_body_font_size'], - 'description' => $args[0], - 'append' => $args[1], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_body_font_size', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_body_font_size', + 'value' => ( isset( $this->options['pdf_body_font_size'] ) ) ? $this->options['pdf_body_font_size'] : $this->defaults['pdf_body_font_size'], + 'description' => $args[0], + 'append' => $args[1], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_body_line_height input. + * * @param array $args */ function renderBodyLineHightField( $args ) { - $this->renderField( array( - 'id' => 'pdf_body_line_height', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_body_line_height', - 'value' => ( isset( $this->options['pdf_body_line_height'] ) ) ? $this->options['pdf_body_line_height'] : $this->defaults['pdf_body_line_height'], - 'description' => $args[0], - 'append' => $args[1], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_body_line_height', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_body_line_height', + 'value' => ( isset( $this->options['pdf_body_line_height'] ) ) ? $this->options['pdf_body_line_height'] : $this->defaults['pdf_body_line_height'], + 'description' => $args[0], + 'append' => $args[1], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_page_size select. + * * @param array $args */ function renderPageSizeField( $args ) { if ( ! isset( $this->options['pdf_page_size'] ) ) { if ( isset( $this->options['pdf_page_width'] ) && isset( $this->options['pdf_page_height'] ) ) { - if ( '5.5in' == $this->options['pdf_page_width'] && '8.5in' == $this->options['pdf_page_height'] ) { + if ( '5.5in' === $this->options['pdf_page_width'] && '8.5in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 1; - } elseif ( '6in' == $this->options['pdf_page_width'] && '9in' == $this->options['pdf_page_height'] ) { + } elseif ( '6in' === $this->options['pdf_page_width'] && '9in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 2; - } elseif ( '8.5in' == $this->options['pdf_page_width'] && '11in' == $this->options['pdf_page_height'] ) { + } elseif ( '8.5in' === $this->options['pdf_page_width'] && '11in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 3; - } elseif ( '8.5in' == $this->options['pdf_page_width'] && '9.25in' == $this->options['pdf_page_height'] ) { + } elseif ( '8.5in' === $this->options['pdf_page_width'] && '9.25in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 4; - } elseif ( '5in' == $this->options['pdf_page_width'] && '7.75in' == $this->options['pdf_page_height'] ) { + } elseif ( '5in' === $this->options['pdf_page_width'] && '7.75in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 5; - } elseif ( '4.25in' == $this->options['pdf_page_width'] && '7in' == $this->options['pdf_page_height'] ) { + } elseif ( '4.25in' === $this->options['pdf_page_width'] && '7in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 6; - } elseif ( '21cm' == $this->options['pdf_page_width'] && '29.7cm' == $this->options['pdf_page_height'] ) { + } elseif ( '21cm' === $this->options['pdf_page_width'] && '29.7cm' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 7; - } elseif ( '14.8cm' == $this->options['pdf_page_width'] && '21cm' == $this->options['pdf_page_height'] ) { + } elseif ( '14.8cm' === $this->options['pdf_page_width'] && '21cm' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 8; - } elseif ( '5in' == $this->options['pdf_page_width'] && '8in' == $this->options['pdf_page_height'] ) { + } elseif ( '5in' === $this->options['pdf_page_width'] && '8in' === $this->options['pdf_page_height'] ) { $this->options['pdf_page_size'] = 9; } else { $this->options['pdf_page_size'] = 10; @@ -732,42 +741,49 @@ function renderPageSizeField( $args ) { /** * Render the pdf_page_width input. + * * @param array $args */ function renderPageWidthField( $args ) { - $this->renderField( array( - 'id' => 'pdf_page_width', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_width', - 'value' => @$this->options['pdf_page_width'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_page_width', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_width', + 'value' => getset( $this->options, 'pdf_page_width' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_page_height input. + * * @param array $args */ function renderPageHeightField( $args ) { - $this->renderField( array( - 'id' => 'pdf_page_height', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_height', - 'value' => @$this->options['pdf_page_height'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_page_height', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_height', + 'value' => getset( $this->options, 'pdf_page_height' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the margins diagram. + * * @param array $args */ function renderMarginsField( $args ) { - ?> + ?> <div class="margin-diagram"> <p class="description"><?php echo $args[0]; ?></p> <div class="pages"> @@ -793,447 +809,545 @@ function renderMarginsField( $args ) { </ul> </div> </div> - <p><strong><?php _e( 'IMPORTANT: If you plan to use a print-on-demand service, margins under 2cm on any side can cause your file to be rejected.', 'pressbooks' ); ?></strong></p> + <p> + <strong><?php _e( 'IMPORTANT: If you plan to use a print-on-demand service, margins under 2cm on any side can cause your file to be rejected.', 'pressbooks' ); ?></strong> + </p> <?php } /** * Render the pdf_page_margin_outside input. + * * @param array $args */ function renderOutsideMarginField( $args ) { - ?> - <?php $this->renderField( array( - 'id' => 'pdf_page_margin_outside', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_margin_outside', - 'value' => @$this->options['pdf_page_margin_outside'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + ?> + <?php $this->renderField( + [ + 'id' => 'pdf_page_margin_outside', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_margin_outside', + 'value' => getset( $this->options, 'pdf_page_margin_outside' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_page_margin_inside input. + * * @param array $args */ function renderInsideMarginField( $args ) { - $this->renderField( array( - 'id' => 'pdf_page_margin_inside', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_margin_inside', - 'value' => @$this->options['pdf_page_margin_inside'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_page_margin_inside', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_margin_inside', + 'value' => getset( $this->options, 'pdf_page_margin_inside' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_page_margin_top input. + * * @param array $args */ function renderTopMarginField( $args ) { - $this->renderField( array( - 'id' => 'pdf_page_margin_top', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_margin_top', - 'value' => @$this->options['pdf_page_margin_top'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_page_margin_top', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_margin_top', + 'value' => getset( $this->options, 'pdf_page_margin_top' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_page_margin_bottom input. + * * @param array $args */ function renderBottomMarginField( $args ) { - $this->renderField( array( - 'id' => 'pdf_page_margin_bottom', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_page_margin_bottom', - 'value' => @$this->options['pdf_page_margin_bottom'], - 'description' => $args[0], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'pdf_page_margin_bottom', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_page_margin_bottom', + 'value' => getset( $this->options, 'pdf_page_margin_bottom' ), + 'description' => $args[0], + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the pdf_hyphens checkbox. + * * @param array $args */ function renderHyphenationField( $args ) { - $this->renderCheckbox( array( - 'id' => 'pdf_hyphens', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_hyphens', - 'value' => @$this->options['pdf_hyphens'], - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'pdf_hyphens', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_hyphens', + 'value' => getset( $this->options, 'pdf_hyphens' ), + 'label' => $args[0], + ] + ); } /** * Render the pdf_paragraph_separation radio buttons. + * * @param array $args */ function renderParagraphSeparationField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'pdf_paragraph_separation', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_paragraph_separation', - 'value' => @$this->options['pdf_paragraph_separation'], - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'pdf_paragraph_separation', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_paragraph_separation', + 'value' => getset( $this->options, 'pdf_paragraph_separation' ), + 'choices' => $args, + ] + ); } /** * Render the pdf_sectionopenings radio buttons. + * * @param array $args */ function renderSectionOpeningsField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'pdf_sectionopenings', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_sectionopenings', - 'value' => @$this->options['pdf_sectionopenings'], - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'pdf_sectionopenings', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_sectionopenings', + 'value' => getset( $this->options, 'pdf_sectionopenings' ), + 'choices' => $args, + ] + ); } /** * Render the pdf_toc checkbox. + * * @param array $args */ function renderTOCField( $args ) { - $this->renderCheckbox( array( - 'id' => 'pdf_toc', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_toc', - 'value' => @$this->options['pdf_toc'], - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'pdf_toc', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_toc', + 'value' => getset( $this->options, 'pdf_toc' ), + 'label' => $args[0], + ] + ); } /** * Render the pdf_image_resolution radio buttons. + * * @param array $args */ function renderImageResolutionField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'pdf_image_resolution', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_image_resolution', - 'value' => @$this->options['pdf_image_resolution'], - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'pdf_image_resolution', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_image_resolution', + 'value' => getset( $this->options, 'pdf_image_resolution' ), + 'choices' => $args, + ] + ); } /** * Render the pdf_crop_marks checkbox. + * * @param array $args - */ + */ function renderCropMarksField( $args ) { - $this->renderCheckbox( array( - 'id' => 'pdf_crop_marks', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_crop_marks', - 'value' => @$this->options['pdf_crop_marks'], - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'pdf_crop_marks', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_crop_marks', + 'value' => getset( $this->options, 'pdf_crop_marks' ), + 'label' => $args[0], + ] + ); } /** * Render the pdf_romanize_parts checkbox. + * * @param array $args */ function renderRomanizePartsField( $args ) { - $this->renderCheckbox( array( - 'id' => 'pdf_romanize_parts', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_romanize_parts', - 'value' => @$this->options['pdf_romanize_parts'], - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'pdf_romanize_parts', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_romanize_parts', + 'value' => getset( $this->options, 'pdf_romanize_parts' ), + 'label' => $args[0], + ] + ); } /** * Render the pdf_footnotes_style radio buttons. + * * @param array $args */ function renderFootnoteStyleField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'pdf_footnotes_style', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_footnotes_style', - 'value' => @$this->options['pdf_footnotes_style'], - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'pdf_footnotes_style', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_footnotes_style', + 'value' => getset( $this->options, 'pdf_footnotes_style' ), + 'choices' => $args, + ] + ); } /** * Render the widows input. + * * @param array $args */ function renderWidowsField( $args ) { - $this->renderField( array( - 'id' => 'widows', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'widows', - 'value' => @$this->options['widows'], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'widows', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'widows', + 'value' => getset( $this->options, 'widows' ), + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the orphans input. + * * @param array $args */ function renderOrphansField( $args ) { - $this->renderField( array( - 'id' => 'orphans', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'orphans', - 'value' => @$this->options['orphans'], - 'type' => 'text', - 'class' => 'small-text', - ) ); + $this->renderField( + [ + 'id' => 'orphans', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'orphans', + 'value' => getset( $this->options, 'orphans' ), + 'type' => 'text', + 'class' => 'small-text', + ] + ); } /** * Render the running content instructional diagram. + * * @param array $args */ function renderRunningContentField( $args ) { - ?> + ?> <p class="description"><?php echo $args[0]; ?></p> <?php } /** * Render the running_content_front_matter_left input. + * * @param array $args */ function renderRunningContentFrontMatterLeftField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_front_matter_left', - 'name' => 'running_content_front_matter_left', - 'value' => @$this->options['running_content_front_matter_left'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_front_matter_left', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_front_matter_left', - 'value' => @$this->options['running_content_front_matter_left'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_front_matter_left', + 'name' => 'running_content_front_matter_left', + 'value' => getset( $this->options, 'running_content_front_matter_left' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_front_matter_left', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_front_matter_left', + 'value' => getset( $this->options, 'running_content_front_matter_left' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_front_matter_right input. + * * @param array $args */ function renderRunningContentFrontMatterRightField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_front_matter_right', - 'name' => 'running_content_front_matter_right', - 'value' => @$this->options['running_content_front_matter_right'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_front_matter_right', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_front_matter_right', - 'value' => @$this->options['running_content_front_matter_right'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_front_matter_right', + 'name' => 'running_content_front_matter_right', + 'value' => getset( $this->options, 'running_content_front_matter_right' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_front_matter_right', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_front_matter_right', + 'value' => getset( $this->options, 'running_content_front_matter_right' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_introduction_left input. + * * @param array $args */ function renderRunningContentIntroductionLeftField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_introduction_left', - 'name' => 'running_content_introduction_left', - 'value' => @$this->options['running_content_introduction_left'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_introduction_left', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_introduction_left', - 'value' => @$this->options['running_content_introduction_left'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_introduction_left', + 'name' => 'running_content_introduction_left', + 'value' => getset( $this->options, 'running_content_introduction_left' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_introduction_left', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_introduction_left', + 'value' => getset( $this->options, 'running_content_introduction_left' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_introduction_right input. + * * @param array $args */ function renderRunningContentIntroductionRightField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_introduction_right', - 'name' => 'running_content_introduction_right', - 'value' => @$this->options['running_content_introduction_right'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_introduction_right', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_introduction_right', - 'value' => @$this->options['running_content_introduction_right'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_introduction_right', + 'name' => 'running_content_introduction_right', + 'value' => getset( $this->options, 'running_content_introduction_right' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_introduction_right', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_introduction_right', + 'value' => getset( $this->options, 'running_content_introduction_right' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_part_left input. + * * @param array $args */ function renderRunningContentPartLeftField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_part_left', - 'name' => 'running_content_part_left', - 'value' => @$this->options['running_content_part_left'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_part_left', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_part_left', - 'value' => @$this->options['running_content_part_left'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_part_left', + 'name' => 'running_content_part_left', + 'value' => getset( $this->options, 'running_content_part_left' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_part_left', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_part_left', + 'value' => getset( $this->options, 'running_content_part_left' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_part_right input. + * * @param array $args */ function renderRunningContentPartRightField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_part_right', - 'name' => 'running_content_part_right', - 'value' => @$this->options['running_content_part_right'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_part_right', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_part_right', - 'value' => @$this->options['running_content_part_right'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_part_right', + 'name' => 'running_content_part_right', + 'value' => getset( $this->options, 'running_content_part_right' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_part_right', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_part_right', + 'value' => getset( $this->options, 'running_content_part_right' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_chapter_left input. + * * @param array $args */ function renderRunningContentChapterLeftField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_chapter_left', - 'name' => 'running_content_chapter_left', - 'value' => @$this->options['running_content_chapter_left'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_chapter_left', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_chapter_left', - 'value' => @$this->options['running_content_chapter_left'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_chapter_left', + 'name' => 'running_content_chapter_left', + 'value' => getset( $this->options, 'running_content_chapter_left' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_chapter_left', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_chapter_left', + 'value' => getset( $this->options, 'running_content_chapter_left' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_chapter_right input. + * * @param array $args */ function renderRunningContentChapterRightField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_chapter_right', - 'name' => 'running_content_chapter_right', - 'value' => @$this->options['running_content_chapter_right'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_chapter_right', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_chapter_right', - 'value' => @$this->options['running_content_chapter_right'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_chapter_right', + 'name' => 'running_content_chapter_right', + 'value' => getset( $this->options, 'running_content_chapter_right' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_chapter_right', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_chapter_right', + 'value' => getset( $this->options, 'running_content_chapter_right' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_back_matter_left input. + * * @param array $args */ function renderRunningContentBackMatterLeftField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_back_matter_left', - 'name' => 'running_content_back_matter_left', - 'value' => @$this->options['running_content_back_matter_left'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_back_matter_left', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_back_matter_left', - 'value' => @$this->options['running_content_back_matter_left'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_back_matter_left', + 'name' => 'running_content_back_matter_left', + 'value' => getset( $this->options, 'running_content_back_matter_left' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_back_matter_left', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_back_matter_left', + 'value' => getset( $this->options, 'running_content_back_matter_left' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the running_content_back_matter_right input. + * * @param array $args */ function renderRunningContentBackMatterRightField( $args ) { - $this->renderCustomSelect( array( - 'id' => 'running_content_back_matter_right', - 'name' => 'running_content_back_matter_right', - 'value' => @$this->options['running_content_back_matter_right'], - 'choices' => $args, - ) ); - $this->renderField( array( - 'id' => 'running_content_back_matter_right', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'running_content_back_matter_right', - 'value' => @$this->options['running_content_back_matter_right'], - 'type' => 'text', - 'class' => 'regular-text code', - ) ); + $this->renderCustomSelect( + [ + 'id' => 'running_content_back_matter_right', + 'name' => 'running_content_back_matter_right', + 'value' => getset( $this->options, 'running_content_back_matter_right' ), + 'choices' => $args, + ] + ); + $this->renderField( + [ + 'id' => 'running_content_back_matter_right', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'running_content_back_matter_right', + 'value' => getset( $this->options, 'running_content_back_matter_right' ), + 'type' => 'text', + 'class' => 'regular-text code', + ] + ); } /** * Render the pdf_fontsize checkbox. + * * @param array $args */ function renderFontSizeField( $args ) { - $this->renderCheckbox( array( - 'id' => 'pdf_fontsize', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'pdf_fontsize', - 'value' => @$this->options['pdf_fontsize'], - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'pdf_fontsize', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'pdf_fontsize', + 'value' => getset( $this->options, 'pdf_fontsize' ), + 'label' => $args[0], + ] + ); } /** @@ -1263,7 +1377,8 @@ static function getDefaults() { /** * @since 3.9.7 TODO */ - return apply_filters( 'pb_theme_options_pdf_defaults', array( + return apply_filters( + 'pb_theme_options_pdf_defaults', [ 'pdf_body_font_size' => '11', 'pdf_body_line_height' => '1.4', 'pdf_page_width' => '5.5in', @@ -1293,13 +1408,15 @@ static function getDefaults() { 'running_content_back_matter_left' => '%book_title%', 'running_content_back_matter_right' => '%section_title%', 'pdf_fontsize' => 0, - ) ); + ] + ); } /** * Filter the array of default values for the PDF options tab. * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { @@ -1317,13 +1434,15 @@ static function getBooleanOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_pdf_booleans', array( + return apply_filters( + 'pb_theme_options_pdf_booleans', [ 'pdf_hyphens', 'pdf_toc', 'pdf_crop_marks', 'pdf_romanize_parts', 'pdf_fontsize', - ) ); + ] + ); } /** @@ -1337,7 +1456,8 @@ static function getStringOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_pdf_strings', array( + return apply_filters( + 'pb_theme_options_pdf_strings', [ 'pdf_page_width', 'pdf_page_height', 'pdf_page_margin_outside', @@ -1354,7 +1474,8 @@ static function getStringOptions() { 'running_content_chapter_right', 'running_content_back_matter_left', 'running_content_back_matter_right', - ) ); + ] + ); } /** @@ -1368,11 +1489,13 @@ static function getIntegerOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_pdf_integers', array( + return apply_filters( + 'pb_theme_options_pdf_integers', [ 'pdf_body_font_size', 'widows', 'orphans', - ) ); + ] + ); } /** @@ -1386,9 +1509,11 @@ static function getFloatOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_pdf_floats', array( - 'pdf_body_line_height' - ) ); + return apply_filters( + 'pb_theme_options_pdf_floats', [ + 'pdf_body_line_height', + ] + ); } /** @@ -1402,24 +1527,30 @@ static function getPredefinedOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_pdf_predefined', array( + return apply_filters( + 'pb_theme_options_pdf_predefined', [ 'pdf_paragraph_separation', 'pdf_sectionopenings', 'pdf_image_resolution', 'pdf_footnotes_style', - ) ); + ] + ); } /** * Replace running content tags with strings. * + * @param string $input + * + * @return string + * * @since 3.9.8 */ static function replaceRunningContentTags( $input ) { $input = '"' . $input . '"'; return str_replace( - array( + [ '%book_title%', '%book_subtitle%', '%book_author%', @@ -1429,8 +1560,8 @@ static function replaceRunningContentTags( $input ) { '%section_author%', '%section_subtitle%', '%blank%', - ), - array( + ], + [ '" string(book-title) "', '" string(book-subtitle) "', '" string(book-author) "', @@ -1440,7 +1571,7 @@ static function replaceRunningContentTags( $input ) { '" string(chapter-author) "', '" string(chapter-subtitle) "', '', - ), + ], $input ); } @@ -1448,6 +1579,10 @@ static function replaceRunningContentTags( $input ) { /** * Apply overrides. * + * @param string $scss + * + * @return string + * * @since 3.9.8 */ static function scssOverrides( $scss ) { @@ -1459,7 +1594,7 @@ static function scssOverrides( $scss ) { $sass = \Pressbooks\Container::get( 'Sass' ); $options = get_option( 'pressbooks_theme_options_global' ); - // Display chapter numbers? true (default) / false + // Should we display chapter numbers? True (default) or false. if ( ! $options['chapter_numbers'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$chapter-number-display: none; \n"; @@ -1536,8 +1671,8 @@ static function scssOverrides( $scss ) { $scss .= "img { prince-image-resolution: $resolution; } \n"; } - // Display crop marks? true / false (default) - if ( 1 == $options['pdf_crop_marks'] ) { + // Should we display crop marks? True or false (default). + if ( 1 === absint( $options['pdf_crop_marks'] ) ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$page-cropmarks: crop; \n"; } else { @@ -1546,7 +1681,7 @@ static function scssOverrides( $scss ) { } // Hyphens? - if ( 1 == $options['pdf_hyphens'] ) { + if ( 1 === absint( $options['pdf_hyphens'] ) ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$para-hyphens: auto; \n"; // TODO } else { @@ -1561,7 +1696,7 @@ static function scssOverrides( $scss ) { } // Indent paragraphs? - if ( 'skiplines' == $options['pdf_paragraph_separation'] ) { + if ( 'skiplines' === $options['pdf_paragraph_separation'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$para-margin-top: 1em; \n"; $scss .= "\$para-indent: 0; \n"; @@ -1572,7 +1707,7 @@ static function scssOverrides( $scss ) { // Include blank pages? if ( isset( $options['pdf_sectionopenings'] ) ) { - if ( 'openright' == $options['pdf_sectionopenings'] ) { + if ( 'openright' === $options['pdf_sectionopenings'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$recto-verso-standard-opening: right; \n"; $scss .= "\$recto-verso-first-section-opening: right; \n"; @@ -1581,7 +1716,7 @@ static function scssOverrides( $scss ) { $scss .= "#title-page, #toc, div.part, div.front-matter, div.front-matter.introduction, div.front-matter + div.front-matter, div.chapter, div.chapter + div.chapter, div.back-matter, div.back-matter + div.back-matter, #half-title-page h1.title:first-of-type { page-break-before: right; } \n"; $scss .= "#copyright-page { page-break-before: left; }\n"; } - } elseif ( 'remove' == $options['pdf_sectionopenings'] ) { + } elseif ( 'remove' === $options['pdf_sectionopenings'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$recto-verso-standard-opening: auto; \n"; $scss .= "\$recto-verso-first-section-opening: auto; \n"; @@ -1593,7 +1728,7 @@ static function scssOverrides( $scss ) { } } - // Display TOC? true (default) / false + // Should we display the TOC? True (default) or false. if ( ! $options['pdf_toc'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$toc-display: none; \n"; @@ -1653,7 +1788,7 @@ static function scssOverrides( $scss ) { } // a11y Font Size - if ( @$options['pdf_fontsize'] ) { + if ( isset( $options['pdf_fontsize'] ) && ! empty( $options['pdf_fontsize'] ) ) { if ( ! $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= 'body { font-size: 1.3em; line-height: 1.3; }' . "\n"; } diff --git a/includes/modules/themeoptions/class-pb-themeoptions.php b/inc/modules/themeoptions/class-themeoptions.php similarity index 79% rename from includes/modules/themeoptions/class-pb-themeoptions.php rename to inc/modules/themeoptions/class-themeoptions.php index 5c7f4bb9e5..3faf9c9e8f 100644 --- a/includes/modules/themeoptions/class-pb-themeoptions.php +++ b/inc/modules/themeoptions/class-themeoptions.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Modules\ThemeOptions; class ThemeOptions { @@ -29,8 +30,9 @@ function __construct( array $tabs ) { */ function loadTabs() { foreach ( $this->tabs as $slug => $subclass ) { - add_filter( 'pressbooks_theme_options_' . $slug . '_defaults', array( $subclass, 'filterDefaults' ), 10, 1 ); + add_filter( 'pressbooks_theme_options_' . $slug . '_defaults', [ $subclass, 'filterDefaults' ], 10, 1 ); $option = get_option( 'pressbooks_theme_options_' . $slug, $subclass::getDefaults() ); + /** @var \Pressbooks\Options $tab */ $tab = new $subclass( $option ); $tab->init(); wp_cache_delete( 'pressbooks_theme_options_' . $slug . '_version', 'options' ); @@ -49,16 +51,16 @@ function loadTabs() { * Render the theme options page and load the appropriate tab. */ static function render() { - ?> + ?> <div class="wrap"> - <h1><?php echo wp_get_theme(); ?> <?php _e( 'Theme Options', 'pressbooks' ); ?></h1> + <h1><?php echo wp_get_theme(); ?><?php _e( 'Theme Options', 'pressbooks' ); ?></h1> <?php settings_errors(); ?> <?php $active_tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'global'; ?> <h2 class="nav-tab-wrapper"> <?php foreach ( \Pressbooks\Modules\ThemeOptions\ThemeOptions::getTabs() as $slug => $subclass ) { ?> <a href="<?php echo admin_url( '/themes.php' ); -?>?page=pressbooks_theme_options&tab=<?php echo $slug; -?>" class="nav-tab <?php echo $active_tab == $slug ? 'nav-tab-active' : ''; ?>"><?php echo $subclass::getTitle() ?></a> + ?>?page=pressbooks_theme_options&tab=<?php echo $slug; + ?>" class="nav-tab <?php echo $active_tab === $slug ? 'nav-tab-active' : ''; ?>"><?php echo $subclass::getTitle() ?></a> <?php } ?> </h2> <form method="post" action="options.php"> @@ -75,28 +77,28 @@ static function render() { */ static function init() { $self = new self( \Pressbooks\Modules\ThemeOptions\ThemeOptions::getTabs() ); - add_action( 'admin_init', array( $self, 'loadTabs' ) ); + add_action( 'admin_init', [ $self, 'loadTabs' ] ); } /** * Returns a filtered array of tabs that we should be loading. - * @returns array + * @returns \Pressbooks\Options[] */ static function getTabs() { - $tabs = array( + $tabs = [ 'global' => '\Pressbooks\Modules\ThemeOptions\GlobalOptions', 'web' => '\Pressbooks\Modules\ThemeOptions\WebOptions', 'pdf' => '\Pressbooks\Modules\ThemeOptions\PDFOptions', 'ebook' => '\Pressbooks\Modules\ThemeOptions\EbookOptions', - ); + ]; - if ( false == get_site_transient( 'pb_pdf_compatible' ) && false == \Pressbooks\Modules\Export\Prince\Pdf::hasDependencies() ) { + if ( false === get_site_transient( 'pb_pdf_compatible' ) && false === \Pressbooks\Modules\Export\Prince\Pdf::hasDependencies() ) { unset( $tabs['pdf'] ); } else { set_site_transient( 'pb_pdf_compatible', true ); } - if ( false == get_site_transient( 'pb_epub_compatible' ) && false == \Pressbooks\Modules\Export\Epub\Epub201::hasDependencies() ) { + if ( false === get_site_transient( 'pb_epub_compatible' ) && false === \Pressbooks\Modules\Export\Epub\Epub201::hasDependencies() ) { unset( $tabs['ebook'] ); } else { set_site_transient( 'pb_epub_compatible', true ); diff --git a/includes/modules/themeoptions/class-pb-weboptions.php b/inc/modules/themeoptions/class-weboptions.php similarity index 74% rename from includes/modules/themeoptions/class-pb-weboptions.php rename to inc/modules/themeoptions/class-weboptions.php index b46cefdc4a..f9383ee49f 100644 --- a/includes/modules/themeoptions/class-pb-weboptions.php +++ b/inc/modules/themeoptions/class-weboptions.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Modules\ThemeOptions; class WebOptions extends \Pressbooks\Options { @@ -16,24 +17,24 @@ class WebOptions extends \Pressbooks\Options { const VERSION = 1; /** - * Web theme options. - * - * @var array - */ + * Web theme options. + * + * @var array + */ public $options; /** - * Web theme defaults. - * - * @var array - */ + * Web theme defaults. + * + * @var array + */ public $defaults; /** - * Constructor. - * - * @param array $options - */ + * Constructor. + * + * @param array $options + */ function __construct( array $options ) { $this->options = $options; $this->defaults = $this->getDefaults(); @@ -57,49 +58,49 @@ function init() { $_page = $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_section = $this->getSlug() . '_options_section'; - if ( false == get_option( $_option ) ) { + if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), - array( $this, 'display' ), + [ $this, 'display' ], $_page ); add_settings_field( 'social_media', __( 'Enable Social Media', 'pressbooks' ), - array( $this, 'renderSocialMediaField' ), + [ $this, 'renderSocialMediaField' ], $_page, $_section, - array( - __( 'Add buttons to cover page and each chapter so that readers may share links to your book through social media: Facebook, Twitter, Google+', 'pressbooks' ) - ) + [ + __( 'Add buttons to cover page and each chapter so that readers may share links to your book through social media: Facebook, Twitter, Google+', 'pressbooks' ), + ] ); add_settings_field( 'paragraph_separation', __( 'Paragraph Separation', 'pressbooks' ), - array( $this, 'renderParagraphSeparationField' ), + [ $this, 'renderParagraphSeparationField' ], $_page, $_section, - array( + [ 'indent' => __( 'Indent paragraphs', 'pressbooks' ), 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), - ) + ] ); add_settings_field( 'part_title', __( 'Display Part Title', 'pressbooks' ), - array( $this, 'renderPartTitle' ), + [ $this, 'renderPartTitle' ], $_page, $_section, - array( - __( 'Display the Part title on each chapter', 'pressbooks' ) - ) + [ + __( 'Display the Part title on each chapter', 'pressbooks' ), + ] ); /** @@ -112,7 +113,7 @@ function init() { register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -126,7 +127,8 @@ function display() { /** * Render the web options tab form (NOT USED). */ - function render() {} + function render() { + } /** * Upgrade handler for web options. @@ -145,13 +147,13 @@ function upgrade( $version ) { function doInitialUpgrade() { $_option = $this->getSlug(); $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); - $deprecated = array( + $deprecated = [ 'toc_collapse', 'accessibility_fontsize', - ); + ]; foreach ( $options as $key => $value ) { - if ( in_array( $key, $deprecated ) ) { + if ( in_array( $key, $deprecated, true ) ) { unset( $options[ $key ] ); } } @@ -161,44 +163,53 @@ function doInitialUpgrade() { /** * Render the social_media checkbox. + * * @param array $args */ function renderSocialMediaField( $args ) { - $this->renderCheckbox( array( - 'id' => 'social_media', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'social_media', - 'value' => ( isset( $this->options['social_media'] ) ) ? $this->options['social_media'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'social_media', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'social_media', + 'value' => ( isset( $this->options['social_media'] ) ) ? $this->options['social_media'] : '', + 'label' => $args[0], + ] + ); } /** * Render the paragraph_separation radio buttons. + * * @param array $args */ function renderParagraphSeparationField( $args ) { - $this->renderRadioButtons( array( - 'id' => 'paragraph_separation', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'paragraph_separation', - 'value' => ( isset( $this->options['paragraph_separation'] ) ) ? $this->options['paragraph_separation'] : '', - 'choices' => $args, - ) ); + $this->renderRadioButtons( + [ + 'id' => 'paragraph_separation', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'paragraph_separation', + 'value' => ( isset( $this->options['paragraph_separation'] ) ) ? $this->options['paragraph_separation'] : '', + 'choices' => $args, + ] + ); } /** * Render the social_media checkbox. + * * @param array $args */ function renderPartTitle( $args ) { - $this->renderCheckbox( array( - 'id' => 'part_title', - 'name' => 'pressbooks_theme_options_' . $this->getSlug(), - 'option' => 'part_title', - 'value' => ( isset( $this->options['part_title'] ) ) ? $this->options['part_title'] : '', - 'label' => $args[0], - ) ); + $this->renderCheckbox( + [ + 'id' => 'part_title', + 'name' => 'pressbooks_theme_options_' . $this->getSlug(), + 'option' => 'part_title', + 'value' => ( isset( $this->options['part_title'] ) ) ? $this->options['part_title'] : '', + 'label' => $args[0], + ] + ); } /** @@ -228,17 +239,20 @@ static function getDefaults() { /** * @since 3.9.7 TODO */ - return apply_filters( 'pb_theme_options_web_defaults', array( + return apply_filters( + 'pb_theme_options_web_defaults', [ 'social_media' => 1, 'paragraph_separation' => 'skiplines', 'part_title' => 0, - ) ); + ] + ); } /** * Filter the array of default values for the web options tab. * * @param array $defaults + * * @return array $defaults */ static function filterDefaults( $defaults ) { @@ -256,10 +270,12 @@ static function getBooleanOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_web_booleans', array( + return apply_filters( + 'pb_theme_options_web_booleans', [ 'social_media', 'part_title', - ) ); + ] + ); } /** @@ -273,7 +289,7 @@ static function getStringOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_web_strings', array() ); + return apply_filters( 'pb_theme_options_web_strings', [] ); } /** @@ -287,7 +303,7 @@ static function getIntegerOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_web_integers', array() ); + return apply_filters( 'pb_theme_options_web_integers', [] ); } /** @@ -301,7 +317,7 @@ static function getFloatOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_web_floats', array() ); + return apply_filters( 'pb_theme_options_web_floats', [] ); } /** @@ -315,14 +331,20 @@ static function getPredefinedOptions() { * * @since 3.9.7 */ - return apply_filters( 'pb_theme_options_web_predefined', array( - 'paragraph_separation' - ) ); + return apply_filters( + 'pb_theme_options_web_predefined', [ + 'paragraph_separation', + ] + ); } /** * Apply overrides. * + * @param string $scss + * + * @return string + * * @since 3.9.8 */ static function scssOverrides( $scss ) { @@ -330,14 +352,14 @@ static function scssOverrides( $scss ) { $options = get_option( 'pressbooks_theme_options_web' ); if ( isset( $options['paragraph_separation'] ) ) { - if ( 'indent' == $options['paragraph_separation'] ) { + if ( 'indent' === $options['paragraph_separation'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$para-margin-top: 0; \n"; $scss .= "\$para-indent: 1em; \n"; } else { $scss .= "* + p { text-indent: 1em; margin-top: 0; margin-bottom: 0; } \n"; } - } elseif ( 'skiplines' == $options['paragraph_separation'] ) { + } elseif ( 'skiplines' === $options['paragraph_separation'] ) { if ( $sass->isCurrentThemeCompatible( 2 ) ) { $scss .= "\$para-margin-top: 1em; \n"; $scss .= "\$para-indent: 0; \n"; diff --git a/includes/pb-posttype.php b/inc/posttype/namespace.php similarity index 83% rename from includes/pb-posttype.php rename to inc/posttype/namespace.php index 8f1c943196..4f8011c6c8 100644 --- a/includes/pb-posttype.php +++ b/inc/posttype/namespace.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\PostType; /** @@ -12,13 +13,19 @@ */ function list_post_types() { - return array( + /** + * Allow users to add additional custom post types to the list of permitted post types. + * @since 4.0.0 + */ + return apply_filters( + 'pb_supported_post_types', [ 'metadata', 'part', 'chapter', 'front-matter', 'back-matter', 'custom-css', + ] ); } @@ -30,7 +37,7 @@ function register_post_types() { /* Chapters */ - $labels = array( + $labels = [ 'name' => _x( 'Chapters', 'post type general name', 'pressbooks' ), 'singular_name' => _x( 'Chapter', 'post type singular name', 'pressbooks' ), 'add_new' => _x( 'Add New Chapter', 'book', 'pressbooks' ), @@ -43,9 +50,9 @@ function register_post_types() { 'not_found_in_trash' => __( 'No chapters found in Trash', 'pressbooks' ), 'parent_item_colon' => '', 'menu_name' => __( 'Text', 'pressbooks' ), + ]; - ); - $args = array( + $args = [ 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, @@ -53,19 +60,20 @@ function register_post_types() { 'show_in_menu' => true, 'menu_position' => 5, 'query_var' => true, - 'rewrite' => array( 'slug' => 'chapter', 'with_front' => false ), + 'rewrite' => [ 'slug' => 'chapter', 'with_front' => false ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, // do not set to true unless you want to break permalinks. Do you really want to do that? >:( - 'supports' => array( 'title', 'editor', 'author', 'comments', 'page-attributes', 'revisions' ), - 'taxonomies' => array( 'chapter-type' ), + 'supports' => [ 'title', 'editor', 'author', 'comments', 'page-attributes', 'revisions' ], + 'taxonomies' => [ 'chapter-type' ], 'menu_icon' => 'dashicons-book', - ); + ]; + register_post_type( 'chapter', $args ); /* Parts */ - $labels = array( + $labels = [ 'name' => _x( 'Parts', 'post type general name', 'pressbooks' ), 'singular_name' => _x( 'Part', 'post type singular name', 'pressbooks' ), 'add_new' => _x( 'Add Part', 'book', 'pressbooks' ), @@ -78,9 +86,8 @@ function register_post_types() { 'not_found_in_trash' => __( 'No parts found in Trash', 'pressbooks' ), 'parent_item_colon' => '', 'menu_name' => __( 'Parts', 'pressbooks' ), - - ); - $args = array( + ]; + $args = [ 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, @@ -88,17 +95,17 @@ function register_post_types() { 'show_in_menu' => true, 'menu_position' => 5, 'query_var' => true, - 'rewrite' => array( 'slug' => 'part', 'with_front' => false ), + 'rewrite' => [ 'slug' => 'part', 'with_front' => false ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => true, - 'supports' => array( 'title', 'page-attributes' ), - ); + 'supports' => [ 'title', 'page-attributes' ], + ]; register_post_type( 'part', $args ); /* Front Matter */ - $labels = array( + $labels = [ 'name' => _x( 'Front Matter', 'post type general name', 'pressbooks' ), 'singular_name' => _x( 'Front Matter', 'post type singular name', 'pressbooks' ), 'add_new' => _x( 'Add New Front Matter', 'book', 'pressbooks' ), @@ -111,9 +118,9 @@ function register_post_types() { 'not_found_in_trash' => __( 'No front matter found in Trash', 'pressbooks' ), 'parent_item_colon' => '', 'menu_name' => __( 'Front Matter', 'pressbooks' ), + ]; - ); - $args = array( + $args = [ 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, @@ -121,18 +128,18 @@ function register_post_types() { 'show_in_menu' => true, 'menu_position' => 5, 'query_var' => true, - 'rewrite' => array( 'slug' => 'front-matter', 'with_front' => false ), + 'rewrite' => [ 'slug' => 'front-matter', 'with_front' => false ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => true, - 'supports' => array( 'title', 'editor', 'author', 'comments', 'revisions' ), - 'taxonomies' => array( 'front-matter-type' ), - ); + 'supports' => [ 'title', 'editor', 'author', 'comments', 'revisions' ], + 'taxonomies' => [ 'front-matter-type' ], + ]; register_post_type( 'front-matter', $args ); /* Back Matter */ - $labels = array( + $labels = [ 'name' => _x( 'Back Matter', 'post type general name', 'pressbooks' ), 'singular_name' => _x( 'Back Matter', 'post type singular name', 'pressbooks' ), 'add_new' => _x( 'Add New Back Matter', 'book', 'pressbooks' ), @@ -145,9 +152,9 @@ function register_post_types() { 'not_found_in_trash' => __( 'No back matter found in Trash', 'pressbooks' ), 'parent_item_colon' => '', 'menu_name' => __( 'Back Matter', 'pressbooks' ), + ]; - ); - $args = array( + $args = [ 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, @@ -155,18 +162,18 @@ function register_post_types() { 'show_in_menu' => true, 'menu_position' => 5, 'query_var' => true, - 'rewrite' => array( 'slug' => 'back-matter', 'with_front' => false ), + 'rewrite' => [ 'slug' => 'back-matter', 'with_front' => false ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => true, - 'supports' => array( 'title', 'editor', 'author', 'comments', 'revisions' ), - 'taxonomies' => array( 'back-matter-type' ), - ); + 'supports' => [ 'title', 'editor', 'author', 'comments', 'revisions' ], + 'taxonomies' => [ 'back-matter-type' ], + ]; register_post_type( 'back-matter', $args ); /* Book Information (Ie. Metadata) */ - $labels = array( + $labels = [ 'name' => _x( 'Book Information', 'post type general name', 'pressbooks' ), 'singular_name' => _x( 'Book Information', 'post type singular name', 'pressbooks' ), 'add_new' => _x( 'Add New Book Information', 'book', 'pressbooks' ), @@ -179,9 +186,9 @@ function register_post_types() { 'not_found_in_trash' => __( 'No book information found in Trash', 'pressbooks' ), 'parent_item_colon' => '', 'menu_name' => __( 'Book Information', 'pressbooks' ), + ]; - ); - $args = array( + $args = [ 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, @@ -193,22 +200,22 @@ function register_post_types() { 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, - 'supports' => array( '' ), - ); + 'supports' => [ '' ], + ]; register_post_type( 'metadata', $args ); /* Custom CSS */ - $args = array( + $args = [ 'exclude_from_search' => true, 'public' => false, 'publicly_queryable' => false, 'show_ui' => false, - 'supports' => array( 'revisions' ), + 'supports' => [ 'revisions' ], 'label' => 'Custom CSS', 'can_export' => false, 'rewrite' => false, - 'capabilities' => array( + 'capabilities' => [ 'edit_post' => 'edit_theme_options', 'read_post' => 'read', 'delete_post' => 'edit_theme_options', @@ -216,8 +223,8 @@ function register_post_types() { 'edit_others_posts' => 'edit_theme_options', 'publish_posts' => 'edit_theme_options', 'read_private_posts' => 'read', - ), - ); + ], + ]; register_post_type( 'custom-css', $args ); } @@ -226,7 +233,7 @@ function post_type_messages( $messages ) { $permalink = get_permalink( $post ); - $messages['part'] = array( + $messages['part'] = [ 0 => '', // Unused. Messages start at index 1. 1 => ( get_post_meta( $post->ID, 'pb_part_content' ) ? sprintf( __( 'Part updated. <a target="_blank" href="%s">View Part</a>', 'pressbooks' ), esc_url( $permalink ) ) : __( 'Part updated.', 'pressbooks' ) ), 2 => __( 'Custom field updated.', 'pressbooks' ), @@ -237,13 +244,15 @@ function post_type_messages( $messages ) { 6 => ( get_post_meta( $post->ID, 'pb_part_content' ) ? sprintf( __( 'Part published. <a target="_blank" href="%s">View Part</a>', 'pressbooks' ), esc_url( $permalink ) ) : __( 'Part published.', 'pressbooks' ) ), 7 => __( 'Part saved.', 'pressbooks' ), 8 => sprintf( __( 'Part submitted. <a target="_blank" href="%s">Preview Part</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - 9 => sprintf( __( 'Part scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Part</a>', 'pressbooks' ), + 9 => sprintf( + __( 'Part scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Part</a>', 'pressbooks' ), // translators: Publish box date format, see http://php.net/date - date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), + date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) + ), 10 => sprintf( __( 'Part draft updated. <a target="_blank" href="%s">Preview Part</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - ); + ]; - $messages['metadata'] = array( + $messages['metadata'] = [ 0 => '', // Unused. Messages start at index 1. 1 => __( 'Book Information updated.', 'pressbooks' ), 2 => __( 'Custom field updated.', 'pressbooks' ), @@ -254,9 +263,9 @@ function post_type_messages( $messages ) { 6 => __( 'Book Information updated.', 'pressbooks' ), 7 => __( 'Book Information saved.', 'pressbooks' ), 8 => __( 'Book Information submitted.', 'pressbooks' ), - ); + ]; - $messages['chapter'] = array( + $messages['chapter'] = [ 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Chapter updated. <a target="_blank" href="%s">View Chapter</a>', 'pressbooks' ), esc_url( $permalink ) ), 2 => __( 'Custom field updated.', 'pressbooks' ), @@ -267,13 +276,15 @@ function post_type_messages( $messages ) { 6 => sprintf( __( 'Chapter published. <a href="%s">View Chapter</a>', 'pressbooks' ), esc_url( $permalink ) ), 7 => __( 'Chapter saved.', 'pressbooks' ), 8 => sprintf( __( 'Chapter submitted. <a target="_blank" href="%s">Preview Chapter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - 9 => sprintf( __( 'Chapter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Chapter</a>', 'pressbooks' ), + 9 => sprintf( + __( 'Chapter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Chapter</a>', 'pressbooks' ), // translators: Publish box date format, see http://php.net/date - date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), + date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) + ), 10 => sprintf( __( 'Chapter draft updated. <a target="_blank" href="%s">Preview Chapter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - ); + ]; - $messages['front-matter'] = array( + $messages['front-matter'] = [ 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Front Matter updated. <a target="_blank" href="%s">View Front Matter</a>', 'pressbooks' ), esc_url( $permalink ) ), 2 => __( 'Custom field updated.', 'pressbooks' ), @@ -284,13 +295,15 @@ function post_type_messages( $messages ) { 6 => sprintf( __( 'Front Matter published. <a href="%s">View Front Matter</a>', 'pressbooks' ), esc_url( $permalink ) ), 7 => __( 'Front Matter saved.', 'pressbooks' ), 8 => sprintf( __( 'Front Matter submitted. <a target="_blank" href="%s">Preview Front Matter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - 9 => sprintf( __( 'Front Matter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Front Matter</a>', 'pressbooks' ), + 9 => sprintf( + __( 'Front Matter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Front Matter</a>', 'pressbooks' ), // translators: Publish box date format, see http://php.net/date - date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), + date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) + ), 10 => sprintf( __( 'Front Matter draft updated. <a target="_blank" href="%s">Preview Front Matter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - ); + ]; - $messages['back-matter'] = array( + $messages['back-matter'] = [ 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Back Matter updated. <a target="_blank" href="%s">View Back Matter</a>', 'pressbooks' ), esc_url( $permalink ) ), 2 => __( 'Custom field updated.', 'pressbooks' ), @@ -301,11 +314,13 @@ function post_type_messages( $messages ) { 6 => sprintf( __( 'Back Matter published. <a href="%s">View Back Matter</a>', 'pressbooks' ), esc_url( $permalink ) ), 7 => __( 'Back Matter saved.', 'pressbooks' ), 8 => sprintf( __( 'Back Matter submitted. <a target="_blank" href="%s">Preview Back Matter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - 9 => sprintf( __( 'Back Matter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Back Matter</a>', 'pressbooks' ), + 9 => sprintf( + __( 'Back Matter scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Back Matter</a>', 'pressbooks' ), // translators: Publish box date format, see http://php.net/date - date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), + date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( $permalink ) + ), 10 => sprintf( __( 'Back Matter draft updated. <a target="_blank" href="%s">Preview Back Matter</a>', 'pressbooks' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), - ); + ]; return $messages; } @@ -322,17 +337,17 @@ function add_post_types_rss( $args ) { $num_posts = get_option( 'posts_per_rss' ); // only if book is public - if ( 1 == $blog_public ) { + if ( 1 === absint( $blog_public ) ) { if ( isset( $args['feed'] ) && ! isset( $args['post_type'] ) ) { - $args['post_type'] = array( 'front-matter', 'back-matter', 'chapter' ); + $args['post_type'] = [ 'front-matter', 'back-matter', 'chapter' ]; } // increase default posts per rss - if ( 10 == $num_posts ) { + if ( 10 === absint( $num_posts ) ) { update_option( 'posts_per_rss', 999 ); } - } elseif ( 0 == $blog_public ) { + } elseif ( 0 === absint( $blog_public ) ) { if ( isset( $args['feed'] ) && ! isset( $args['post_type'] ) ) { - $args['post_type'] = array( 'post' ); + $args['post_type'] = [ 'post' ]; } } return $args; @@ -347,12 +362,12 @@ function add_post_types_rss( $args ) { * @return array */ function add_posttypes_to_hypothesis( $posttypes ) { - $posttypes = array( + $posttypes = [ 'part' => __( 'parts', 'pressbooks' ), 'chapter' => __( 'chapters', 'pressbooks' ), 'front-matter' => __( 'front matter', 'pressbooks' ), 'back-matter' => __( 'back matter', 'pressbooks' ), - ); + ]; return $posttypes; } diff --git a/includes/pb-redirect.php b/inc/redirect/namespace.php similarity index 86% rename from includes/pb-redirect.php rename to inc/redirect/namespace.php index 060ad7b581..7ea344cdcf 100644 --- a/includes/pb-redirect.php +++ b/inc/redirect/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Redirect; +namespace Pressbooks\Redirect; /** * Fail-safe Location: redirection @@ -81,35 +81,35 @@ function flusher() { $pull_the_lever = false; - // @see \Pressbooks\PostType\register_post_types + // See \Pressbooks\PostType\register_post_types $set = get_option( 'pressbooks_flushed_post_type' ); if ( ! $set ) { $pull_the_lever = true; update_option( 'pressbooks_flushed_post_type', true ); } - // @see rewrite_rules_for_format() + // See rewrite_rules_for_format() $set = get_option( 'pressbooks_flushed_format' ); if ( ! $set ) { $pull_the_lever = true; update_option( 'pressbooks_flushed_format', true ); } - // @see rewrite_rules_for_catalog() + // See rewrite_rules_for_catalog() $set = get_option( 'pressbooks_flushed_catalog' ); if ( ! $set ) { $pull_the_lever = true; update_option( 'pressbooks_flushed_catalog', true ); } - // @see rewrite_rules_for_sitemap() + // See rewrite_rules_for_sitemap() $set = get_option( 'pressbooks_flushed_sitemap' ); if ( ! $set ) { $pull_the_lever = true; update_option( 'pressbooks_flushed_sitemap', true ); } - // @see \Pressbooks\VIP\Upgrade\rewrite_rules_for_upgrade() + // See rewrite_rules_for_upgrade() $set = get_option( 'pressbooks-vip_flushed_upgrade' ); if ( ! $set ) { $pull_the_lever = true; @@ -158,17 +158,17 @@ function do_format() { $format = get_query_var( 'format' ); - if ( 'xhtml' == $format ) { + if ( 'xhtml' === $format ) { - $args = array(); + $args = []; $foo = new \Pressbooks\Modules\Export\Xhtml\Xhtml11( $args ); $foo->transform(); exit; } - if ( 'wxr' == $format ) { + if ( 'wxr' === $format ) { - $args = array(); + $args = []; $foo = new \Pressbooks\Modules\Export\WordPress\Wxr( $args ); $foo->transform(); exit; @@ -207,9 +207,9 @@ function do_catalog() { } $user = get_user_by( 'login', $user_login ); - if ( false == $user ) { + if ( false === $user ) { $msg = __( 'No catalog was found for user', 'pressbooks' ) . ": $user_login"; - $args = array( 'response' => '404' ); + $args = [ 'response' => '404' ]; wp_die( $msg, '', $args ); } @@ -268,7 +268,7 @@ function do_api() { // optional 'id' $books_id = ( isset( $parts[0] ) ) ? $parts[0] : ''; - $variations = array(); + $variations = []; if ( 'v1' !== $version ) { \Pressbooks\Modules\Api_v1\Api::apiErrors( 'version' ); @@ -277,32 +277,32 @@ function do_api() { // Filter user input if ( is_array( $_GET ) ) { - $args = array( - 'titles' => array( - 'filter' => FILTER_SANITIZE_STRING, - 'flags' => FILTER_FLAG_STRIP_HIGH, - ), + $args = [ + 'titles' => [ + 'filter' => FILTER_SANITIZE_STRING, + 'flags' => FILTER_FLAG_STRIP_HIGH, + ], 'offset' => FILTER_SANITIZE_NUMBER_INT, 'limit' => FILTER_SANITIZE_NUMBER_INT, 'json' => FILTER_SANITIZE_NUMBER_INT, 'xml' => FILTER_SANITIZE_NUMBER_INT, - 'subjects' => array( - 'filter' => FILTER_SANITIZE_STRING, - 'flags' => FILTER_FLAG_STRIP_LOW, - ), - 'authors' => array( - 'filter' => FILTER_SANITIZE_STRING, - 'flags' => FILTER_FLAG_STRIP_LOW, - ), - 'licenses' => array( - 'filter' => FILTER_SANITIZE_STRING, - 'flags' => FILTER_FLAG_STRIP_HIGH, - ), - 'keywords' => array( - 'filter' => FILTER_SANITIZE_STRING, - 'flags' => FILTER_FLAG_STRIP_LOW, - ), - ); + 'subjects' => [ + 'filter' => FILTER_SANITIZE_STRING, + 'flags' => FILTER_FLAG_STRIP_LOW, + ], + 'authors' => [ + 'filter' => FILTER_SANITIZE_STRING, + 'flags' => FILTER_FLAG_STRIP_LOW, + ], + 'licenses' => [ + 'filter' => FILTER_SANITIZE_STRING, + 'flags' => FILTER_FLAG_STRIP_HIGH, + ], + 'keywords' => [ + 'filter' => FILTER_SANITIZE_STRING, + 'flags' => FILTER_FLAG_STRIP_LOW, + ], + ]; $variations = filter_input_array( INPUT_GET, $args, false ); @@ -361,7 +361,7 @@ function do_open() { $action = get_query_var( 'open' ); - if ( 'download' == $action ) { + if ( 'download' === $action ) { // Download if ( ! empty( $_GET['type'] ) ) { $files = \Pressbooks\Utility\latest_exports(); @@ -369,10 +369,10 @@ function do_open() { $filepath = \Pressbooks\Modules\Export\Export::getExportFolder() . $files[ $_GET['type'] ]; $book_title = ( get_bloginfo( 'name' ) ) ? get_bloginfo( 'name' ) : __( 'book', 'pressbooks' ); $book_title_slug = sanitize_file_name( $book_title ); - $book_title_slug = str_replace( array( '+' ), '', $book_title_slug ); // Remove symbols which confuse Apache (Ie. form urlencoded spaces) + $book_title_slug = str_replace( [ '+' ], '', $book_title_slug ); // Remove symbols which confuse Apache (Ie. form urlencoded spaces) $book_title_slug = sanitize_file_name( $book_title_slug ); if ( ! is_readable( $filepath ) ) { - wp_die( __( 'File not found', 'pressbooks' ) . ': ' . $files[ $_GET['type'] ], '', array( 'response' => 404 ) ); + wp_die( __( 'File not found', 'pressbooks' ) . ': ' . $files[ $_GET['type'] ], '', [ 'response' => 404 ] ); } // Force download @@ -385,12 +385,12 @@ function do_open() { header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Pragma: public' ); header( 'Content-Length: ' . filesize( $filepath ) ); - @ob_clean(); + @ob_clean(); // @codingStandardsIgnoreLine flush(); - // @codingStandardsIgnoreLine - while ( @ob_end_flush() ) { + while ( @ob_end_flush() ) { // @codingStandardsIgnoreLine // Fix out-of-memory problem - } readfile( $filepath ); + } + readfile( $filepath ); exit; } @@ -404,7 +404,8 @@ function do_open() { * Callback function that strips whitespace characters * * @see array_filter() - * @param array $value + * + * @param string $value */ function trim_value( &$value ) { $value = trim( $value ); diff --git a/includes/pb-registration.php b/inc/registration/namespace.php similarity index 91% rename from includes/pb-registration.php rename to inc/registration/namespace.php index 66405514cb..a99e260e74 100644 --- a/includes/pb-registration.php +++ b/inc/registration/namespace.php @@ -5,6 +5,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Registration; /** @@ -13,6 +14,7 @@ * @param string $translated_text The modified text string. * @param string $untranslated_text The original WordPress core text string. * @param string $domain The textdomain. + * * @return string $translated_text */ @@ -24,64 +26,64 @@ function custom_signup_text( $translated_text, $untranslated_text, $domain ) { switch ( $untranslated_text ) { case 'Gimme a site!' : $translated_text = __( 'Register my book now', 'pressbooks' ); - break; + break; case 'Just a username, please.' : $translated_text = __( 'Register my book later', 'pressbooks' ); break; case 'Site Name:' : case 'Site Domain:' : $translated_text = __( 'Web Book Address:', 'pressbooks' ); - break; + break; case 'Must be at least 4 characters, letters and numbers only. It cannot be changed, so choose carefully!' : $translated_text = __( 'Must be at least 4 characters, letters and numbers only. Your web book address <strong>cannot be changed</strong>, so choose carefully!', 'pressbooks' ); - break; + break; case 'Site Title:' : $translated_text = __( 'Book Title:', 'pressbooks' ); - break; + break; case 'Site Language:' : $translated_text = __( 'Book Language:', 'pressbooks' ); - break; + break; case 'Allow search engines to index this site.' : $translated_text = __( 'Would you like your web book to be visible to the public?', 'pressbooks' ); - break; + break; case 'Create Site' : case 'Signup' : $translated_text = __( 'Create Book', 'pressbooks' ); - break; + break; case 'Get your own %s account in seconds' : $translated_text = __( 'Register a %s account', 'pressbooks' ); - break; + break; case 'Get <em>another</em> %s site in seconds' : $translated_text = __( 'Create a new book', 'pressbooks' ); - break; + break; case 'Welcome back, %s. By filling out the form below, you can <strong>add another site to your account</strong>. There is no limit to the number of sites you can have, so create to your heart’s content, but write responsibly!' : $translated_text = __( 'Welcome, %s. Fill out the form below to <strong>add a new book to your account</strong>.', 'pressbooks' ); - break; + break; case 'domain' : case 'sitename' : $translated_text = __( 'yourwebbookname', 'pressbooks' ); - break; + break; case 'Sites you are already a member of:' : $translated_text = __( 'Books you are already a member of:', 'pressbooks' ); - break; + break; case 'If you’re not going to use a great site domain, leave it for a new user. Now have at it!' : $translated_text = __( 'Your web book address must be at least 4 characters, letters and numbers only. It <strong>cannot be changed</strong>, so choose carefully!', 'pressbooks' ); - break; + break; case 'Congratulations! Your new site, %s, is almost ready.' : $translated_text = __( 'Congratulations! Your new book, %s, is almost ready', 'pressbooks' ); - break; + break; case 'But, before you can start using your site, <strong>you must activate it</strong>.' : $translated_text = __( 'But, before you can start writing your book, <strong>you must activate it</strong>.', 'pressbooks' ); - break; + break; case 'Your account has been activated. You may now <a href="%1$s">log in</a> to the site using your chosen username of “%2$s”. Please check your email inbox at %3$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%4$s">reset your password</a>.' : $translated_text = __( 'Your account has been activated. You may now <a href="%1$s">log in</a> to your book using your chosen username of “%2$s”. Please check your email inbox at %3$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%4$s">reset your password</a>.', 'pressbooks' ); - break; + break; case 'Your site at <a href="%1$s">%2$s</a> is active. You may now log in to your site using your chosen username of “%3$s”. Please check your email inbox at %4$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%5$s">reset your password</a>.' : $translated_text = __( 'Your book at <a href="%1$s">%2$s</a> is active. You may now log in to your book using your chosen username of “%3$s”. Please check your email inbox at %4$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%5$s">reset your password</a>.', 'pressbooks' ); - break; + break; case 'Your account is now activated. <a href="%1$s">View your site</a> or <a href="%2$s">Log in</a>' : $translated_text = __( 'Your account is now activated. <a href="%1$s">View your book</a> or <a href="%2$s">Log in</a>', 'pressbooks' ); - break; + break; } } @@ -115,6 +117,8 @@ function add_password_field( $errors ) { * Validate user submitted passwords * * @param array $content + * + * @return array */ function validate_passwords( $content ) { if ( isset( $_POST['_signup_form'] ) && ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) { @@ -124,7 +128,7 @@ function validate_passwords( $content ) { $password_1 = isset( $_POST['password_1'] ) ? $_POST['password_1'] : ''; $password_2 = isset( $_POST['password_2'] ) ? $_POST['password_2'] : ''; - if ( isset( $_POST['stage'] ) && 'validate-user-signup' == $_POST['stage'] ) { + if ( isset( $_POST['stage'] ) && 'validate-user-signup' === $_POST['stage'] ) { // No primary password entered if ( trim( $password_1 ) === '' ) { @@ -146,8 +150,9 @@ function validate_passwords( $content ) { * Add password to temporary user meta * * @param array $meta + * + * @return array */ - function add_temporary_password( $meta ) { if ( isset( $_POST['_signup_form'] ) && ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) { wp_die( __( 'Please try again.', 'pressbooks' ) ); @@ -156,7 +161,7 @@ function add_temporary_password( $meta ) { if ( isset( $_POST['password_1'] ) ) { // Store as base64 to avoid injections - $add_meta = array( 'password' => ( isset( $_POST['password_1_base64'] ) ? $_POST['password_1'] : base64_encode( $_POST['password_1'] ) ) ); + $add_meta = [ 'password' => ( isset( $_POST['password_1_base64'] ) ? $_POST['password_1'] : base64_encode( $_POST['password_1'] ) ) ]; $meta = array_merge( $add_meta, $meta ); } @@ -172,15 +177,19 @@ function add_hidden_password_field() { if ( isset( $_POST['_signup_form'] ) && ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) { wp_die( __( 'Please try again.', 'pressbooks' ) ); } - if ( isset( $_POST['password_1'] ) ) { ?><input type="hidden" name="password_1_base64" value="1" /> - <input type="hidden" name="password_1" value="<?php echo ( isset( $_POST['password_1_base64'] ) ? $_POST['password_1'] : base64_encode( $_POST['password_1'] ) ); ?>" /> + if ( isset( $_POST['password_1'] ) ) { ?> + <input type="hidden" name="password_1_base64" value="1"/> + <input type="hidden" name="password_1" value="<?php echo( isset( $_POST['password_1_base64'] ) ? $_POST['password_1'] : base64_encode( $_POST['password_1'] ) ); ?>"/> <?php } } /** * Override wp_generate_password() once when we're generating our form + * + * @param string $password + * + * @return string */ - function override_password_generation( $password ) { if ( isset( $_POST['_signup_form'] ) && ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) { wp_die( __( 'Please try again.', 'pressbooks' ) ); @@ -211,7 +220,7 @@ function override_password_generation( $password ) { // Remove old password from signup meta unset( $meta['password'] ); $meta = maybe_serialize( $meta ); - $wpdb->update( $wpdb->signups, array( 'meta' => $meta ), array( 'activation_key' => $key ), array( '%s' ), array( '%s' ) ); + $wpdb->update( $wpdb->signups, [ 'meta' => $meta ], [ 'activation_key' => $key ], [ '%s' ], [ '%s' ] ); return $password; } else { return $password; // No password meta set = just activate user as normal with random password diff --git a/includes/pb-sanitize.php b/inc/sanitize/namespace.php similarity index 90% rename from includes/pb-sanitize.php rename to inc/sanitize/namespace.php index f8c6ead1cb..056959766d 100644 --- a/includes/pb-sanitize.php +++ b/inc/sanitize/namespace.php @@ -3,8 +3,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Sanitize; +namespace Pressbooks\Sanitize; /** * Convert HTML5 tags to XHTML11 divs. @@ -19,9 +19,9 @@ * * @return string */ -function html5_to_xhtml11( $html, $config = array(), $spec = array() ) { +function html5_to_xhtml11( $html, $config = [], $spec = [] ) { - $html5 = array( + $html5 = [ 'article', 'aside', 'audio', @@ -53,9 +53,9 @@ function html5_to_xhtml11( $html, $config = array(), $spec = array() ) { 'track', 'video', 'wbr', - ); + ]; - $search_open = $replace_open = $search_closed = $replace_closed = array(); + $search_open = $replace_open = $search_closed = $replace_closed = []; foreach ( $html5 as $tag ) { $search_open[] = '`(<' . $tag . ')([^\w])`i'; @@ -78,12 +78,12 @@ function html5_to_xhtml11( $html, $config = array(), $spec = array() ) { * * @return string */ -function html5_to_epub3( $html, $config = array(), $spec = array() ) { +function html5_to_epub3( $html, $config = [], $spec = [] ) { // HTML5 elements we don't want to deal with just yet - $html5 = array( 'command', 'embed', 'track' ); + $html5 = [ 'command', 'embed', 'track' ]; - $search_open = $replace_open = $search_closed = $replace_closed = array(); + $search_open = $replace_open = $search_closed = $replace_closed = []; foreach ( $html5 as $tag ) { $search_open[] = '`(<' . $tag . ')([^\w])`i'; @@ -104,10 +104,12 @@ function html5_to_epub3( $html, $config = array(), $spec = array() ) { */ function fix_audio_shortcode() { - add_filter( 'wp_audio_shortcode', function ( $html, $atts, $audio, $post_id, $library ) { - $html = preg_replace( '/(id=\"audio[0-9\-]*\")(.*)(style="[^\"]*\")/ui', '$1', $html ); - return $html; - }, 10, 5 ); + add_filter( + 'wp_audio_shortcode', function ( $html, $atts, $audio, $post_id, $library ) { + $html = preg_replace( '/(id=\"audio[0-9\-]*\")(.*)(style="[^\"]*\")/ui', '$1', $html ); + return $html; + }, 10, 5 + ); } @@ -134,7 +136,7 @@ function sanitize_xml_attribute( $slug ) { $slug = trim( $slug ); $slug = html_entity_decode( $slug, ENT_COMPAT | ENT_XHTML, 'UTF-8' ); $slug = htmlspecialchars( $slug, ENT_COMPAT | ENT_XHTML, 'UTF-8', false ); - $slug = str_replace( array( "\f" ), '', $slug ); + $slug = str_replace( [ "\f" ], '', $slug ); return $slug; } @@ -156,7 +158,7 @@ function sanitize_xml_id( $slug ) { if ( empty( $slug ) ) { $slug = uniqid( 'slug-' ); - } else if ( ! preg_match( '/^[a-z]/i', $slug ) ) { + } elseif ( ! preg_match( '/^[a-z]/i', $slug ) ) { $slug = 'slug-' . $slug; } @@ -233,12 +235,12 @@ function strip_br( $slug ) { * @return string */ function filter_title( $title ) { - $allowed = array( - 'br' => array(), - 'span' => array( 'class' => array() ), - 'em' => array(), - 'strong' => array(), - ); + $allowed = [ + 'br' => [], + 'span' => [ 'class' => [] ], + 'em' => [], + 'strong' => [], + ]; return wp_kses( $title, $allowed ); } @@ -261,16 +263,17 @@ function canonicalize_url( $url ) { // Add http:// if it's missing if ( ! preg_match( '#^https?://#i', $url ) ) { // Remove ftp://, gopher://, fake://, etc - if ( mb_strpos( $url, '://' ) ) { list( $garbage, $url ) = mb_split( '://', $url ); + if ( mb_strpos( $url, '://' ) ) { + list( $garbage, $url ) = mb_split( '://', $url ); } // Prepend http $url = 'http://' . $url; } // protocol and domain to lowercase (but NOT the rest of the URL), - $scheme = @parse_url( $url, PHP_URL_SCHEME ); + $scheme = parse_url( $url, PHP_URL_SCHEME ); $url = preg_replace( '/' . preg_quote( $scheme ) . '/', mb_strtolower( $scheme ), $url, 1 ); - $host = @parse_url( $url, PHP_URL_HOST ); + $host = parse_url( $url, PHP_URL_HOST ); $url = preg_replace( '/' . preg_quote( $host ) . '/', mb_strtolower( $host ), $url, 1 ); // Sanitize for good measure diff --git a/includes/shortcodes/footnotes/class-pb-footnotes.php b/inc/shortcodes/footnotes/class-footnotes.php similarity index 80% rename from includes/shortcodes/footnotes/class-pb-footnotes.php rename to inc/shortcodes/footnotes/class-footnotes.php index 2e48568336..8750aecd0b 100644 --- a/includes/shortcodes/footnotes/class-pb-footnotes.php +++ b/inc/shortcodes/footnotes/class-footnotes.php @@ -3,8 +3,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Shortcodes\Footnotes; +namespace Pressbooks\Shortcodes\Footnotes; class Footnotes { @@ -13,36 +13,35 @@ class Footnotes { */ static $instance = false; - /** * @var array */ - var $footnotes = array(); - + var $footnotes = []; /** * @var array */ - var $numbered = array(); - + var $numbered = []; /** * This is our constructor, which is private to force the use of getInstance() */ private function __construct() { - add_shortcode( 'footnote', array( $this, 'shortcodeHandler' ) ); - add_filter( 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { - $excluded_shortcodes[] = 'footnote'; - return $excluded_shortcodes; - } ); + add_shortcode( 'footnote', [ $this, 'shortcodeHandler' ] ); + add_filter( + 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { + $excluded_shortcodes[] = 'footnote'; + return $excluded_shortcodes; + } + ); // do_shortcode() is registered as a default filter on 'the_content' with a priority of 11. // We need to run $this->footNoteContent() after this, set to 12 - add_filter( 'the_content', array( $this, 'footnoteContent' ), 12 ); + add_filter( 'the_content', [ $this, 'footnoteContent' ], 12 ); - add_action( 'init', array( $this, 'footnoteButton' ) ); // TinyMCE button - add_action( 'admin_enqueue_scripts', array( $this, 'myCustomQuicktags' ) ); // Quicktag button + add_action( 'init', [ $this, 'footnoteButton' ] ); // TinyMCE button + add_action( 'admin_enqueue_scripts', [ $this, 'myCustomQuicktags' ] ); // Quicktag button } @@ -63,8 +62,8 @@ public static function getInstance() { /** * Pre-process footnote shortcode * - * @param array $atts - * @param string $content + * @param array $atts + * @param string $content * * @return string */ @@ -72,19 +71,21 @@ function shortcodeHandler( $atts, $content = '' ) { global $id; - $a = shortcode_atts( array( - 'numbered' => 'yes', - 'symbol' => '*', - 'suptext' => ' ', - ), $atts ); + $a = shortcode_atts( + [ + 'numbered' => 'yes', + 'symbol' => '*', + 'suptext' => ' ', + ], $atts + ); if ( ! $content ) { return ''; } if ( ! isset( $this->footnotes[ $id ] ) ) { - $this->footnotes[ $id ] = array(); - if ( 'no' == $a['numbered'] ) { + $this->footnotes[ $id ] = []; + if ( 'no' === $a['numbered'] ) { $this->numbered[ $id ] = false; } else { $this->numbered[ $id ] = true; @@ -141,7 +142,7 @@ function footnoteContent( $content ) { } foreach ( $footnotes as $num => $footnote ) { - $num ++; + $num++; $numlabel = "$id-$num"; $content .= '<li id="footnote-' . $numlabel . '">' . make_clickable( $footnote ) . ' <a href="#return-footnote-' . $numlabel . '" class="return-footnote">↵</a></li>'; } @@ -167,18 +168,22 @@ function footnoteButton() { return; } - if ( get_user_option( 'rich_editing' ) == 'true' ) { - - add_action( 'admin_enqueue_scripts', function () { - wp_localize_script( 'editor', 'PB_FootnotesToken', array( - 'nonce' => wp_create_nonce( 'pb-footnote-convert' ), - 'fn_title' => __( 'Insert Footnote', 'pressbooks' ), - 'ftnref_title' => __( 'Convert MS Word Footnotes', 'pressbooks' ), - ) ); - } ); - - add_filter( 'mce_external_plugins', array( $this, 'addFootnotePlugin' ) ); - add_filter( 'mce_buttons_3', array( $this, 'registerFootnoteButtons' ) ); + if ( get_user_option( 'rich_editing' ) ) { + + add_action( + 'admin_enqueue_scripts', function () { + wp_localize_script( + 'editor', 'PB_FootnotesToken', [ + 'nonce' => wp_create_nonce( 'pb-footnote-convert' ), + 'fn_title' => __( 'Insert Footnote', 'pressbooks' ), + 'ftnref_title' => __( 'Convert MS Word Footnotes', 'pressbooks' ), + ] + ); + } + ); + + add_filter( 'mce_external_plugins', [ $this, 'addFootnotePlugin' ] ); + add_filter( 'mce_buttons_3', [ $this, 'registerFootnoteButtons' ] ); } } @@ -230,9 +235,11 @@ function addFootnotePlugin( $plugin_array ) { */ static function ajaxFailure( $msg = '' ) { - if ( ! headers_sent() ) { header( 'HTTP/1.0 500 Internal Server Error' ); + if ( ! headers_sent() ) { + header( 'HTTP/1.0 500 Internal Server Error' ); } - if ( $msg ) { echo "Something went wrong: \n\n $msg"; + if ( $msg ) { + echo "Something went wrong: \n\n $msg"; } wp_die(); } @@ -269,27 +276,27 @@ static function convertWordFootnotes() { * Known Libre Office variations: * href="#sdfootnote123sym" (-> #sdfootnote123anc) */ - $patterns = array( + $patterns = [ '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#sdfootnote([0-9]+)anc)["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // Libre Office - ); + ]; /** * A $replacer must be in the same position as a corresponding $pattern above, * use __REPLACE_ME__ to substitute for what we don't know yet. */ - $replacers = array( + $replacers = [ '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word '~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#sdfootnote__REPLACE_ME__sym)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // Libre Office - ); + ]; - $footnotes = $find = $replace = array(); + $footnotes = $find = $replace = []; foreach ( $patterns as $i => $pattern ) { @@ -297,12 +304,14 @@ static function convertWordFootnotes() { foreach ( $footnotes as $footnote ) { - $tmp = wp_kses( $footnote[3], array( - 'b' => array(), - 'em' => array(), - 'i' => array(), - 'strong' => array(), - ) ); + $tmp = wp_kses( + $footnote[3], [ + 'b' => [], + 'em' => [], + 'i' => [], + 'strong' => [], + ] + ); $tmp = \Pressbooks\Sanitize\remove_control_characters( $tmp ); $tmp = trim( preg_replace( '/\s+/', ' ', $tmp ) ); // Normalize white spaces @@ -323,7 +332,7 @@ static function convertWordFootnotes() { // Send back JSON header( 'Content-Type: application/json' ); - $json = json_encode( array( 'content' => $html ) ); + $json = json_encode( [ 'content' => $html ] ); echo $json; wp_die(); diff --git a/includes/shortcodes/generics/class-pb-generics.php b/inc/shortcodes/generics/class-generics.php similarity index 71% rename from includes/shortcodes/generics/class-pb-generics.php rename to inc/shortcodes/generics/class-generics.php index 4a258880e1..268ec9bb39 100644 --- a/includes/shortcodes/generics/class-pb-generics.php +++ b/inc/shortcodes/generics/class-generics.php @@ -3,6 +3,7 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Shortcodes\Generics; class Generics { @@ -17,25 +18,28 @@ class Generics { * where the key is the shortcode and the value is either a string (the tag) * or an array of two strings (tag and class, respectively). */ - protected $shortcodes = array( - 'blockquote' => 'blockquote', - 'bold' => 'strong', - 'code' => 'code', - 'em' => 'em', - 'italics' => 'em', - 'strong' => 'strong', - 'textbox' => array( 'div', 'textbox' ), - ); + protected $shortcodes = [ + 'blockquote' => 'blockquote', + 'bold' => 'strong', + 'code' => 'code', + 'em' => 'em', + 'italics' => 'em', + 'strong' => 'strong', + 'textbox' => [ 'div', 'textbox' ], + ]; - function __construct() {} + function __construct() { + } function shortcodeHandler( $atts, $content = '', $shortcode ) { $tag = $this->shortcodes[ $shortcode ]; - if ( ! $content ) { return ''; } + if ( ! $content ) { + return ''; + } $class = ''; - if ( is_array( $tag ) || ( is_array( $atts ) && array_key_exists( 'class', $atts ) ) ) { - $classnames = array(); + if ( is_array( $tag ) || ( is_array( $atts ) && array_key_exists( 'class', $atts ) ) ) { + $classnames = []; if ( is_array( $tag ) ) { $classnames[] = $tag[1]; $tag = $tag[0]; @@ -58,11 +62,9 @@ static function getInstance() { } foreach ( self::$instance->shortcodes as $shortcode => $tag ) { - add_shortcode( $shortcode, array( self::$instance, 'shortcodeHandler' ) ); + add_shortcode( $shortcode, [ self::$instance, 'shortcodeHandler' ] ); } return self::$instance; } - - } diff --git a/includes/shortcodes/wikipublisher/class-pb-glyphs.php b/inc/shortcodes/wikipublisher/class-glyphs.php similarity index 89% rename from includes/shortcodes/wikipublisher/class-pb-glyphs.php rename to inc/shortcodes/wikipublisher/class-glyphs.php index 204426dd06..8ebe6f2eef 100644 --- a/includes/shortcodes/wikipublisher/class-pb-glyphs.php +++ b/inc/shortcodes/wikipublisher/class-glyphs.php @@ -9,8 +9,8 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ -namespace Pressbooks\Shortcodes\Wikipublisher; +namespace Pressbooks\Shortcodes\Wikipublisher; class Glyphs { @@ -21,11 +21,11 @@ class Glyphs { // ISO-639-3 - protected $supported_languages = array( + protected $supported_languages = [ 'grc', // Ancient Greek (polytonic) 'ell', // Modern Greek (monotonic) 'hbo', // Ancient Hebrew - ); + ]; /** @@ -35,11 +35,13 @@ class Glyphs { */ private function __construct() { - add_shortcode( 'pb_language', array( $this, 'lang_shortcode' ) ); - add_filter( 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { - $excluded_shortcodes[] = 'pb_language'; - return $excluded_shortcodes; - } ); + add_shortcode( 'pb_language', [ $this, 'langShortcode' ] ); + add_filter( + 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { + $excluded_shortcodes[] = 'pb_language'; + return $excluded_shortcodes; + } + ); } @@ -65,13 +67,15 @@ public static function getInstance() { * * @return string */ - function lang_shortcode( $atts, $content = null ) { + function langShortcode( $atts, $content = null ) { - $a = shortcode_atts( array( - 'lang' => '', - ), $atts ); + $a = shortcode_atts( + [ + 'lang' => '', + ], $atts + ); - if ( empty( $content ) || empty( $a['lang'] ) || ! in_array( $a['lang'], $this->supported_languages ) ) { + if ( empty( $content ) || empty( $a['lang'] ) || ! in_array( $a['lang'], $this->supported_languages, true ) ) { // We don't support this language $_error = "*** ERROR: Unsupported pb_language attribute: {$a['lang']} -- "; $_error .= 'Valid choices, based on ISO-639-3, are: ' . implode( $this->supported_languages, ', ' ) . ') ***'; @@ -81,20 +85,20 @@ function lang_shortcode( $atts, $content = null ) { // Reverse Wordpress' fancy formatting // We want to keep all characters such as ‘ ` " '' [...] < > should be > < Ie. not numeric - $content = str_replace( array( '‘', '’', '‘', '’' ), "'", $content ); // Change back to ' - $content = str_replace( array( '“', '”', '“', '”' ), '"', $content ); // Change back to " - $content = str_replace( array( '<br>', '<br />', '<p>', '</p>', '</p>' ), null, $content ); // Get rid of wpautop() auto-formatting + $content = str_replace( [ '‘', '’', '‘', '’' ], "'", $content ); // Change back to ' + $content = str_replace( [ '“', '”', '“', '”' ], '"', $content ); // Change back to " + $content = str_replace( [ '<br>', '<br />', '<p>', '</p>', '</p>' ], null, $content ); // Get rid of wpautop() auto-formatting $content = htmlspecialchars( $content, ENT_NOQUOTES, 'UTF-8', false ); $language = strtolower( $a['lang'] ); - if ( 'grc' == $language ) { + if ( 'grc' === $language ) { // Ancient Greek (polytonic) $content = '<span lang="grc">' . $this->greek( $content, 'grc' ) . '</span>'; - } elseif ( 'ell' == $language ) { + } elseif ( 'ell' === $language ) { // Modern Greek (monotonic) $content = '<span lang="el">' . $this->greek( $content, 'ell' ) . '</span>'; - } elseif ( 'hbo' == $language ) { + } elseif ( 'hbo' === $language ) { // Ancient Hebrew $content = '<span lang="he" dir="rtl">' . $this->hebrew( $content ) . '</span>'; } @@ -111,7 +115,7 @@ function lang_shortcode( $atts, $content = null ) { */ private function greek( $text, $lang = 'grc' ) { - $monotonics = array( + $monotonics = [ "'a" => 'ά', "'e" => 'έ', "'h" => 'ή', @@ -128,9 +132,9 @@ private function greek( $text, $lang = 'grc' ) { "'W" => 'Ώ', "'\"i" => 'ΐ', "'\"u" => 'ΰ', - ); + ]; - $polytonics = array( + $polytonics = [ '>`a|' => 'ᾂ', '>`h|' => 'ᾒ', '>`w|' => 'ᾢ', @@ -344,10 +348,10 @@ private function greek( $text, $lang = 'grc' ) { "'\"u" => 'ΰ', '`"i' => 'ῒ', '`"u' => 'ῢ', - ); + ]; - $gr_alphabet = array( - '"i' => 'ϊ', + $gr_alphabet = [ + '"i' => 'ϊ', '"u' => 'ϋ', '"I' => 'Ϊ', '"U' => 'Ϋ', @@ -409,9 +413,9 @@ private function greek( $text, $lang = 'grc' ) { '?' => ';', "''&" => '‘&', "''" => '’', - ); + ]; - $r = ( 'grc' == $lang ) ? str_replace( array_keys( $polytonics ), array_values( $polytonics ), $text ) : str_replace( array_keys( $monotonics ), array_values( $monotonics ), $text ); + $r = ( 'grc' === $lang ) ? str_replace( array_keys( $polytonics ), array_values( $polytonics ), $text ) : str_replace( array_keys( $monotonics ), array_values( $monotonics ), $text ); return str_replace( array_keys( $gr_alphabet ), array_values( $gr_alphabet ), $r ); } @@ -424,7 +428,7 @@ private function greek( $text, $lang = 'grc' ) { */ private function hebrew( $text ) { - $he_alphabet = array( + $he_alphabet = [ ';' => '!׃', "'" => 'א', 'b' => 'ב', @@ -488,7 +492,7 @@ private function hebrew( $text ) { '?' => '◌', '!' => '', '|' => '', - ); + ]; return str_replace( array_keys( $he_alphabet ), array_values( $he_alphabet ), $text ); } diff --git a/inc/utility/class-jsonmanifest.php b/inc/utility/class-jsonmanifest.php new file mode 100644 index 0000000000..ebc0903055 --- /dev/null +++ b/inc/utility/class-jsonmanifest.php @@ -0,0 +1,46 @@ +<?php +/** + * Generic utility functions. + * + * @author Pressbooks <code@pressbooks.com> + * @license GPLv2 (or any later version) + */ + +namespace Pressbooks\Utility; + +/** + * Get paths for assets + */ +class JsonManifest { + private $manifest; + + public function __construct( $manifest_path ) { + if ( file_exists( $manifest_path ) ) { + $this->manifest = json_decode( file_get_contents( $manifest_path ), true ); + } else { + $this->manifest = []; + } + } + + public function get() { + return $this->manifest; + } + + public function getPath( $key = '', $default = null ) { + $collection = $this->manifest; + if ( is_null( $key ) ) { + return $collection; + } + if ( isset( $collection[ $key ] ) ) { + return $collection[ $key ]; + } + foreach ( explode( '.', $key ) as $segment ) { + if ( ! isset( $collection[ $segment ] ) ) { + return $default; + } else { + $collection = $collection[ $segment ]; + } + } + return $collection; + } +} diff --git a/includes/pb-utility.php b/inc/utility/namespace.php similarity index 84% rename from includes/pb-utility.php rename to inc/utility/namespace.php index c6dd83cf19..a4f5e2ab74 100644 --- a/includes/pb-utility.php +++ b/inc/utility/namespace.php @@ -5,8 +5,32 @@ * @author Pressbooks <code@pressbooks.com> * @license GPLv2 (or any later version) */ + namespace Pressbooks\Utility; +/** + * Return a value for a given key even if not set + * + * @param mixed $arr either an array or a string that points to an array in $GLOBALS + * @param string $key + * @param mixed $default + * + * @return mixed + */ +function getset( $arr, $key, $default = null ) { + + // Get from array + if ( is_array( $arr ) ) { + return isset( $arr[ $key ] ) ? $arr[ $key ] : $default; + } + + // Get from a global or superglobal + if ( is_string( $arr ) && isset( $GLOBALS[ $arr ] ) && is_array( $GLOBALS[ $arr ] ) ) { + return isset( $GLOBALS[ $arr ][ $key ] ) ? $GLOBALS[ $arr ][ $key ] : $default; + } + + return $default; +} /** * Scan a directory and return the files ordered by date, newest first. @@ -17,18 +41,19 @@ */ function scandir_by_date( $dir ) { - $ignored = array( '.', '..', '.svn', '.git', '.htaccess' ); + $ignored = [ '.', '..', '.svn', '.git', '.htaccess' ]; - $files = array(); + $files = []; foreach ( scandir( $dir ) as $file ) { - if ( in_array( $file, $ignored ) ) { continue; + if ( in_array( $file, $ignored, true ) ) { + continue; } $files[ $file ] = filemtime( $dir . '/' . $file ); } arsort( $files ); $files = array_keys( $files ); - return ( $files ) ? $files : array(); + return ( $files ) ? $files : []; } @@ -36,11 +61,12 @@ function scandir_by_date( $dir ) { * Scan the exports directory, return the files grouped into intervals of 3 minutes, newest first. * * @param string $dir fullpath to the Exports folder. (optional) + * * @return array */ function group_exports( $dir = null ) { - $ignored = array( '.', '..', '.svn', '.git', '.htaccess' ); + $ignored = [ '.', '..', '.svn', '.git', '.htaccess' ]; if ( ! $dir ) { $dir = \Pressbooks\Modules\Export\Export::getExportFolder(); @@ -48,9 +74,10 @@ function group_exports( $dir = null ) { $dir = rtrim( $dir, '/' ) . '/'; } - $files = array(); + $files = []; foreach ( scandir( $dir ) as $file ) { - if ( in_array( $file, $ignored ) ) { continue; + if ( in_array( $file, $ignored, true ) ) { + continue; } $files[ $file ] = filemtime( $dir . $file ); } @@ -58,10 +85,10 @@ function group_exports( $dir = null ) { $interval = 3 * MINUTE_IN_SECONDS; // Three minutes $pos = 0; - $output = array(); + $output = []; foreach ( $files as $file => $timestamp ) { - if ( 0 == $pos ) { + if ( 0 === $pos ) { $pos = $timestamp; } if ( $pos - $timestamp > $interval ) { @@ -159,16 +186,17 @@ function latest_exports() { * For example, here's how one might add a hypothetical Word export format: * * add_filter( 'pb_latest_export_filetypes', function ( $filetypes ) { - * $filetypes['word'] = '.docx'; - * return $filetypes; + * $filetypes['word'] = '.docx'; + * return $filetypes; * } ); * */ - $filetypes = apply_filters( 'pb_latest_export_filetypes', array( + $filetypes = apply_filters( + 'pb_latest_export_filetypes', [ 'epub3' => '._3.epub', 'epub' => '.epub', 'pdf' => '.pdf', - 'print-pdf' => '._print.pdf', + 'print-pdf' => '._print.pdf', 'mobi' => '.mobi', 'icml' => '.icml', 'xhtml' => '.html', @@ -176,11 +204,12 @@ function latest_exports() { 'vanillawxr' => '._vanilla.xml', 'mpdf' => '._oss.pdf', 'odf' => '.odt', - ) ); + ] + ); $dir = \Pressbooks\Modules\Export\Export::getExportFolder(); - $files = array(); + $files = []; // group by extension, sort by date newest first foreach ( \Pressbooks\Utility\scandir_by_date( $dir ) as $file ) { @@ -194,14 +223,13 @@ function latest_exports() { } // get only one of the latest of each type - $latest = array(); + $latest = []; foreach ( $filetypes as $type => $ext ) { if ( array_key_exists( $ext, $files ) ) { $latest[ $type ] = $files[ $ext ][0]; } } - // @TODO filter these results against user prefs return $latest; } @@ -212,7 +240,7 @@ function latest_exports() { */ function add_sitemap_to_robots_txt() { - if ( 1 == get_option( 'blog_public' ) ) { + if ( 1 === absint( get_option( 'blog_public' ) ) ) { echo 'Sitemap: ' . get_option( 'siteurl' ) . "/?feed=sitemap.xml\n\n"; } } @@ -223,7 +251,7 @@ function add_sitemap_to_robots_txt() { */ function do_sitemap() { - if ( 1 == get_option( 'blog_public' ) ) { + if ( 1 === absint( get_option( 'blog_public' ) ) ) { $template = untrailingslashit( PB_PLUGIN_DIR ) . '/templates/pb-sitemap.php'; load_template( $template ); } else { @@ -235,13 +263,14 @@ function do_sitemap() { } /** - * Create a temporary file that automatically gets deleted when php ends + * Create a temporary file that automatically gets deleted when PHP ends. * - * @return string path to file + * @return string Path to temporary file */ function create_tmp_file() { + $stream = stream_get_meta_data( $GLOBALS[ mt_rand() ] = tmpfile() ); - return array_search( 'uri', @array_flip( stream_get_meta_data( $GLOBALS[ mt_rand() ] = tmpfile() ) ) ); + return $stream['uri']; } /** @@ -254,7 +283,7 @@ function check_epubcheck_install() { define( 'PB_EPUBCHECK_COMMAND', '/usr/bin/java -jar /opt/epubcheck/epubcheck.jar' ); } - $output = array(); + $output = []; $return_val = 0; exec( PB_EPUBCHECK_COMMAND . ' -h 2>&1', $output, $return_val ); @@ -280,7 +309,7 @@ function check_kindlegen_install() { define( 'PB_KINDLEGEN_COMMAND', '/opt/kindlegen/kindlegen' ); } - $output = array(); + $output = []; $return_val = 0; exec( PB_KINDLEGEN_COMMAND . ' 2>&1', $output, $return_val ); @@ -306,7 +335,7 @@ function check_prince_install() { define( 'PB_PRINCE_COMMAND', '/usr/bin/prince' ); } - $output = array(); + $output = []; $return_val = 0; exec( PB_PRINCE_COMMAND . ' --version 2>&1', $output, $return_val ); @@ -332,7 +361,7 @@ function check_xmllint_install() { define( 'PB_XMLLINT_COMMAND', '/usr/bin/xmllint' ); } - $output = array(); + $output = []; $return_val = 0; exec( PB_XMLLINT_COMMAND . ' --version 2>&1', $output, $return_val ); @@ -358,7 +387,7 @@ function check_saxonhe_install() { define( 'PB_SAXON_COMMAND', '/usr/bin/java -jar /opt/saxon-he/saxon-he.jar' ); } - $output = array(); + $output = []; $return_val = 0; exec( PB_SAXON_COMMAND . ' -? 2>&1', $output, $return_val ); @@ -382,22 +411,24 @@ function check_saxonhe_install() { /** * Function to determine whether or not experimental features should be visible to users. * + * @param $host string + * * @return boolean */ -function show_experimental_features( $host = null ) { +function show_experimental_features( $host = '' ) { if ( ! $host ) { $host = parse_url( network_site_url(), PHP_URL_HOST ); } // hosts where experimental features should be hidden - $hosts_for_hiding = array( + $hosts_for_hiding = [ 'pressbooks.com', 'pressbooks.pub', - ); + ]; foreach ( $hosts_for_hiding as $host_for_hiding ) { - if ( $host == $host_for_hiding || strpos( $host, $host_for_hiding ) ) { + if ( $host === $host_for_hiding || strpos( $host, $host_for_hiding ) ) { return false; } } @@ -411,10 +442,10 @@ function show_experimental_features( $host = null ) { * @since 2.5.1 */ function include_plugins() { - $plugins = array( + $plugins = [ 'custom-metadata/custom_metadata.php' => 1, 'pressbooks-latex/pb-latex.php' => 1, - ); + ]; $plugins = filter_plugins( $plugins ); @@ -425,7 +456,7 @@ function include_plugins() { } // Disable comments - if ( true == disable_comments() ) { + if ( true === disable_comments() ) { require_once( PB_PLUGIN_DIR . 'symbionts/disable-comments-mu/disable-comments-mu.php' ); } } @@ -434,7 +465,9 @@ function include_plugins() { * Filters out active plugins, to avoid collisions with plugins already installed. * * @since 2.5.1 + * * @param array $plugins An array of plugins, key/values paired like so: 'pressbooks/pressbooks.php' => 1 + * * @return array */ function filter_plugins( $plugins ) { @@ -452,10 +485,10 @@ function filter_plugins( $plugins ) { // Don't include plugins we are trying to activate right now! if ( isset( $_REQUEST['action'] ) ) { - if ( 'activate' == $_REQUEST['action'] && ! empty( $_REQUEST['plugin'] ) ) { + if ( 'activate' === $_REQUEST['action'] && ! empty( $_REQUEST['plugin'] ) ) { $key = (string) $_REQUEST['plugin']; unset( $plugins[ $key ] ); - } elseif ( 'activate-selected' == $_REQUEST['action'] && is_array( $_REQUEST['checked'] ) ) { + } elseif ( 'activate-selected' === $_REQUEST['action'] && is_array( $_REQUEST['checked'] ) ) { foreach ( $_REQUEST['checked'] as $key ) { unset( $plugins[ $key ] ); } @@ -486,11 +519,11 @@ function disable_comments() { } $old_option = get_option( 'disable_comments_options' ); - $new_option = get_option( 'pressbooks_sharingandprivacy_options', array( 'disable_comments' => 1 ) ); + $new_option = get_option( 'pressbooks_sharingandprivacy_options', [ 'disable_comments' => 1 ] ); - if ( false == $old_option ) { + if ( false === absint( $old_option ) ) { $retval = absint( $new_option['disable_comments'] ); - } elseif ( is_array( $old_option['disabled_post_types'] ) && in_array( 'chapter', $old_option['disabled_post_types'] ) && in_array( 'front-matter', $old_option['disabled_post_types'] ) && in_array( 'front-matter', $old_option['disabled_post_types'] ) ) { + } elseif ( is_array( $old_option['disabled_post_types'] ) && in_array( 'chapter', $old_option['disabled_post_types'], true ) && in_array( 'front-matter', $old_option['disabled_post_types'], true ) && in_array( 'front-matter', $old_option['disabled_post_types'], true ) ) { $retval = true; $new_option['disable_comments'] = 1; update_option( 'pressbooks_sharingandprivacy_options', $new_option ); @@ -509,11 +542,12 @@ function disable_comments() { * Remove the Featured tab, change order on the others so that Recommended is first. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * - * @since 3.9.9 + * @since 4.0.0 * @author Joey Kudish <info@jkudish.com> * @author Nick Hamze <me@nickhamze.com> * * @param array $tabs The Plugin Installer tabs. + * * @return array */ function install_plugins_tabs( $tabs ) { @@ -529,13 +563,14 @@ function install_plugins_tabs( $tabs ) { * Replace the core Recommended tab with ours. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * - * @since 3.9.9 + * @since 4.0.0 * @author Joey Kudish <info@jkudish.com> * @author Nick Hamze <me@nickhamze.com> * * @param false|object|array $res The result object or array. Default false. * @param string $action The type of information being requested from the Plugin Install API. * @param object $args Plugin API arguments. + * * @return object */ function hijack_recommended_tab( $res, $action, $args ) { @@ -556,7 +591,7 @@ function hijack_recommended_tab( $res, $action, $args ) { * Fetch recommended plugins from our server. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * - * @since 3.9.9 + * @since 4.0.0 * @author Joey Kudish <info@jkudish.com> * @author Nick Hamze <me@nickhamze.com> * @@ -566,33 +601,38 @@ function fetch_recommended_plugins() { /** * Filter the URL of the Pressbooks Recommended Plugins server. * - * @since 3.9.9 + * @since 4.0.0 */ $url = $http_url = apply_filters( 'pb_recommended_plugins_url', 'https://pressbooks-plugins.now.sh' ) . '/api/plugin-recommendations'; - if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) { + $ssl = wp_http_supports( [ 'ssl' ] ); + if ( $ssl ) { $url = set_url_scheme( $url, 'https' ); } - $request = wp_remote_get( $url, array( 'timeout' => 15 ) ); + $request = wp_remote_get( $url, [ 'timeout' => 15 ] ); if ( $ssl && is_wp_error( $request ) ) { trigger_error( __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site’s server’s configuration.', 'pressbooks' ) . ' ' . __( '(Pressbooks could not establish a secure connection to the plugin recommendations server. Please contact your server administrator.)', 'pressbooks' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); - $request = wp_remote_get( $http_url, array( 'timeout' => 15 ) ); + $request = wp_remote_get( $http_url, [ 'timeout' => 15 ] ); } if ( is_wp_error( $request ) ) { - $res = new WP_Error( 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site’s server’s configuration.', 'pressbooks' ), + $res = new \WP_Error( + 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site’s server’s configuration.', 'pressbooks' ), $request->get_error_message() ); } else { $res = json_decode( wp_remote_retrieve_body( $request ) ); $res->info = (array) $res->info; // WP wants this as an array... - $res->plugins = array_map( function ( $plugin ) { - $plugin->icons = (array) $plugin->icons; // WP wants this as an array... - return $plugin; - }, $res->plugins ); + $res->plugins = array_map( + function ( $plugin ) { + $plugin->icons = (array) $plugin->icons; // WP wants this as an array... + return $plugin; + }, $res->plugins + ); if ( ! is_object( $res ) && ! is_array( $res ) ) { - $res = new WP_Error( 'plugins_api_failed', + $res = new \WP_Error( + 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site’s server’s configuration.', 'pressbooks' ), wp_remote_retrieve_body( $request ) ); @@ -605,13 +645,14 @@ function fetch_recommended_plugins() { * Replace the description on the Recommended tab. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * - * @since 3.9.9 + * @since 4.0.0 * @author Joey Kudish <info@jkudish.com> * @author Nick Hamze <me@nickhamze.com> * * @param string $translation * @param string $text * @param string $domain + * * @return string */ function change_recommendations_sentence( $translation, $text, $domain ) { @@ -629,9 +670,9 @@ function change_recommendations_sentence( $translation, $text, $domain ) { */ function file_upload_max_size() { - static $returnVal = false; + static $return_val = false; // This function is adapted from Drupal and http://stackoverflow.com/questions/13076480/php-get-actual-maximum-upload-size - if ( false === $returnVal ) { + if ( false === $return_val ) { $post_max_size_str = ini_get( 'post_max_size' ); $upload_max_filesize_str = ini_get( 'upload_max_filesize' ); $post_max_size = parse_size( $post_max_size_str ); @@ -639,12 +680,12 @@ function file_upload_max_size() { // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. - $returnVal = $post_max_size_str; + $return_val = $post_max_size_str; if ( $upload_max_filesize > 0 && $upload_max_filesize < $post_max_size ) { - $returnVal = $upload_max_filesize_str; + $return_val = $upload_max_filesize_str; } } - return $returnVal; + return $return_val; } /** @@ -666,14 +707,18 @@ function parse_size( $size ) { /** * format_bytes converts an byte value supplied as an integer into a string suffixed with the appropriate unit of measurement. + * + * @param float $bytes + * @param int $precision + * * @return string */ function format_bytes( $bytes, $precision = 2 ) { - $units = array( 'B', 'KB', 'MB', 'GB', 'TB' ); + $units = [ 'B', 'KB', 'MB', 'GB', 'TB' ]; $bytes = max( $bytes, 0 ); $pow = floor( ( $bytes ? log( $bytes ) : 0 ) / log( 1024 ) ); $pow = min( $pow, count( $units ) - 1 ); - $bytes /= (1 << (10 * $pow)); + $bytes /= ( 1 << ( 10 * $pow ) ); return round( $bytes, $precision ) . ' ' . $units[ $pow ]; } @@ -696,12 +741,16 @@ function email_error_log( $emails, $subject, $message ) { // ------------------------------------------------------------------------------------------------------------ // Email logs - add_filter( 'wp_mail_from', function ( $from_email ) { - return str_replace( 'wordpress@', 'pressbooks@', $from_email ); - } ); - add_filter( 'wp_mail_from_name', function ( $from_name ) { - return 'Pressbooks'; - } ); + add_filter( + 'wp_mail_from', function ( $from_email ) { + return str_replace( 'wordpress@', 'pressbooks@', $from_email ); + } + ); + add_filter( + 'wp_mail_from_name', function ( $from_name ) { + return 'Pressbooks'; + } + ); foreach ( $emails as $email ) { // Call pluggable @@ -719,15 +768,14 @@ function email_error_log( $emails, $subject, $message ) { * @return string * @throws \Exception */ -function template( $path, array $vars = array() ) { +function template( $path, array $vars = [] ) { if ( ! file_exists( $path ) ) { throw new \Exception( "File not found: $path" ); } ob_start(); - // @codingStandardsIgnoreLine - extract( $vars ); + extract( $vars ); // @codingStandardsIgnoreLine include( $path ); $output = ob_get_contents(); ob_end_clean(); @@ -742,16 +790,17 @@ function remote_get_retry( $url, $args, $retry = 3, $attempts = 0, $response = [ $completed = true; } - if ( $completed ) { return $response; + if ( $completed ) { + return $response; } $attempts++; $response = wp_remote_get( $url, $args ); - $retryResponseCodes = apply_filters( 'pressbooks_remote_get_retry_response_codes', [ 400 ] ); + $retry_response_codes = apply_filters( 'pressbooks_remote_get_retry_response_codes', [ 400 ] ); - if ( ! is_array( $response ) || ! in_array( $response['response']['code'], $retryResponseCodes ) ) { + if ( ! is_array( $response ) || ! in_array( $response['response']['code'], $retry_response_codes, true ) ) { return $response; } @@ -760,40 +809,6 @@ function remote_get_retry( $url, $args, $retry = 3, $attempts = 0, $response = [ return remote_get_retry( $url, $args, $retry, $attempts, $response ); } -/** - * Get paths for assets - */ -class JsonManifest { - private $manifest; - public function __construct( $manifest_path ) { - if ( file_exists( $manifest_path ) ) { - $this->manifest = json_decode( file_get_contents( $manifest_path ), true ); - } else { - $this->manifest = []; - } - } - public function get() { - return $this->manifest; - } - public function getPath( $key = '', $default = null ) { - $collection = $this->manifest; - if ( is_null( $key ) ) { - return $collection; - } - if ( isset( $collection[ $key ] ) ) { - return $collection[ $key ]; - } - foreach ( explode( '.', $key ) as $segment ) { - if ( ! isset( $collection[ $segment ] ) ) { - return $default; - } else { - $collection = $collection[ $segment ]; - } - } - return $collection; - } -} - function asset_path( $filename ) { $dist_path = PB_PLUGIN_URL . 'assets/dist/'; $directory = dirname( $filename ) . '/'; @@ -814,7 +829,9 @@ function asset_path( $filename ) { * Set the wp_mail sender address * * @since 3.9.7 + * * @param string $email The default email address + * * @return string */ function mail_from( $email ) { @@ -822,7 +839,7 @@ function mail_from( $email ) { $email = WP_MAIL_FROM; } else { $sitename = strtolower( $_SERVER['SERVER_NAME'] ); - if ( substr( $sitename, 0, 4 ) == 'www.' ) { + if ( substr( $sitename, 0, 4 ) === 'www.' ) { $sitename = substr( $sitename, 4 ); } $email = 'pressbooks@' . $sitename; @@ -834,7 +851,9 @@ function mail_from( $email ) { * Set the wp_mail sender name * * @since 3.9.7 + * * @param string $name The default sender name + * * @return string */ function mail_from_name( $name ) { @@ -851,8 +870,10 @@ function mail_from_name( $name ) { * * @since 3.9.8 * @author Ben Lobaugh <ben@lobaugh.net> + * * @param string $src * @param string $dest + * * @return bool */ function rcopy( $src, $dest ) { @@ -869,7 +890,7 @@ function rcopy( $src, $dest ) { $i = new \DirectoryIterator( $src ); foreach ( $i as $f ) { if ( $f->isFile() ) { - if ( false == copy( $f->getRealPath(), "$dest/" . $f->getFilename() ) ) { + if ( false === copy( $f->getRealPath(), "$dest/" . $f->getFilename() ) ) { return false; } } elseif ( ! $f->isDot() && $f->isDir() ) { diff --git a/languages/core-de-de.php b/languages/core-de-de.php index 457c09fe2d..b2e2b53e58 100644 --- a/languages/core-de-de.php +++ b/languages/core-de-de.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Meine Bücher', 'Create a New Site' => 'Erstellen Sie ein neues Buch', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Besuchen Buch'; diff --git a/languages/core-en-us.php b/languages/core-en-us.php index 817053e1a8..f0f38cf21d 100644 --- a/languages/core-en-us.php +++ b/languages/core-en-us.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'My Books', 'Create a New Site' => 'Create a New Book', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Visit Book'; diff --git a/languages/core-es-es.php b/languages/core-es-es.php index bb9cf77c2e..4a7b00707d 100644 --- a/languages/core-es-es.php +++ b/languages/core-es-es.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Mis libros', 'Create a New Site' => 'Crear un nuevo libro', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Visita libro'; diff --git a/languages/core-et.php b/languages/core-et.php index 8293973bcf..4bf40a2025 100644 --- a/languages/core-et.php +++ b/languages/core-et.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Minu raamatud', 'Create a New Site' => 'Loo uus raamat', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Külasta Book'; diff --git a/languages/core-fr-fr.php b/languages/core-fr-fr.php index accc9fd4c6..f673422655 100644 --- a/languages/core-fr-fr.php +++ b/languages/core-fr-fr.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Mes livres', 'Create a New Site' => 'Créer un nouveau livre', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Visitez livre'; diff --git a/languages/core-it-it.php b/languages/core-it-it.php index b0aa687016..99094c1f86 100644 --- a/languages/core-it-it.php +++ b/languages/core-it-it.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'I miei libri', 'Create a New Site' => 'Crea un nuovo libro', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Vedi libro'; diff --git a/languages/core-ja.php b/languages/core-ja.php index 98ebf35802..85b719f279 100644 --- a/languages/core-ja.php +++ b/languages/core-ja.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'マイブックス', 'Create a New Site' => '新規ブックを作成します。', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'ブックをご覧ください'; diff --git a/languages/core-pt-br.php b/languages/core-pt-br.php index ffabb91d37..9b08462f6d 100644 --- a/languages/core-pt-br.php +++ b/languages/core-pt-br.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Meus livros', 'Create a New Site' => 'Criar um novo livro', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Visitar Livro'; diff --git a/languages/core-sv-se.php b/languages/core-sv-se.php index 383820fd34..dd93d5ffd6 100644 --- a/languages/core-sv-se.php +++ b/languages/core-sv-se.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => 'Mina Böcker', 'Create a New Site' => 'Skapa en ny bok', - ); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = 'Besök Bok'; diff --git a/languages/core-zh-tw.php b/languages/core-zh-tw.php index 5846021d99..a80bb2e203 100644 --- a/languages/core-zh-tw.php +++ b/languages/core-zh-tw.php @@ -7,15 +7,10 @@ * @see pressbooks/includes/pb-l10n.php */ -$overrides = array( - - // 'View all posts filed under %s' => 'See all articles filed under %s', - // 'Howdy, %1$s' => 'Greetings, %1$s!', - // Add some more strings here... - +$overrides = [ 'My Sites' => '我的書籍', 'Create a New Site' => '創建一個新的書', -); +]; if ( \Pressbooks\Book::isBook() ) { $overrides['Visit Site'] = '訪問書'; diff --git a/phpcs.ruleset.xml b/phpcs.ruleset.xml new file mode 100644 index 0000000000..f8bc623f40 --- /dev/null +++ b/phpcs.ruleset.xml @@ -0,0 +1,43 @@ +<?xml version="1.0"?> +<ruleset> + <!-- Scan only PHP files --> + <arg name="extensions" value="php"/> + + <!-- Show colors in console --> + <arg value="-colors"/> + + <!-- Show progress --> + <arg value="p"/> + + <!-- Use HM Coding Standards --> + <rule ref="vendor/humanmade/coding-standards"> + <!-- Disable all ESLint checks --> + <exclude name="HM.Debug.ESLint"/> + <!-- Disable rules Pressbooks disagrees with --> + <exclude name="WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid"/> + <exclude name="WordPress.NamingConventions.ValidVariableName.MemberNotSnakeCase"/> + <exclude name="WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar"/> + <exclude name="WordPress.VIP.SessionVariableUsage"/> + <exclude name="WordPress.VIP.SessionFunctionsUsage"/> + <!-- Disable LayoutOrder until humanmade/coding-standards#5 is fixed --> + <exclude name="HM.Layout.Order.WrongOrder"/> + </rule> + + <!-- Re-enable rules Pressbooks agrees with --> + <rule ref="Generic.NamingConventions.UpperCaseConstantName"/> + <rule ref="PSR1.Methods.CamelCapsMethodName" > + <!-- Except for classes that override WP --> + <exclude-pattern>class-catalog-list-table.php</exclude-pattern> + <exclude-pattern>class-network-managers-list-table.php</exclude-pattern> + </rule> + + <!-- Disable Side Effects rule for the bootstrapping file and those where we have to include WordPress core files. --> + <rule ref="PSR1.Files.SideEffects"> + <exclude-pattern>/pressbooks.php</exclude-pattern> + </rule> + + <exclude-pattern>/autoloader.php</exclude-pattern> + <exclude-pattern>/compatibility.php</exclude-pattern> + <exclude-pattern>/functions.php</exclude-pattern> + +</ruleset> diff --git a/phpcs.xml b/phpcs.xml deleted file mode 100644 index 9789a5a202..0000000000 --- a/phpcs.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0"?> -<ruleset name="Pressbooks"> - <description>Pressbooks Coding Standards</description> - - <!-- Show colors in console --> - <arg value="-colors"/> - <!-- Do not print warnings --> - <arg value="n"/> - <!-- Show sniff codes in all reports --> - <arg value="s"/> - - <!-- Exclude tests --> - <exclude-pattern>tests/</exclude-pattern> - <!-- Exclude symbionts --> - <exclude-pattern>symbionts/</exclude-pattern> - <!-- Exclude vendor --> - <exclude-pattern>vendor/</exclude-pattern> - <!-- Exclude themes-* --> - <exclude-pattern>themes-*/</exclude-pattern> - - <!-- Dem's da rules --> - <rule ref="WordPress-Core"> - <!-- Ignore method name validation for compatibility with class method. --> - <exclude name="WordPress.NamingConventions.ValidFunctionName"/> - <!-- Ignore variable name validation for compatibility with class variables. --> - <exclude name="WordPress.NamingConventions.ValidVariableName"/> - </rule> - <rule ref="WordPress-Extra"> - <exclude name="WordPress.XSS.EscapeOutput" /> - </rule> -</ruleset> diff --git a/phpunit.xml b/phpunit.xml index 6ff35dbcae..191fb84cc6 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -16,10 +16,10 @@ </testsuites> <filter> <whitelist> - <directory suffix=".php">./includes</directory> + <directory suffix=".php">./inc</directory> <exclude> - <directory suffix=".php">./includes/modules/export/epub/templates</directory> - <directory suffix=".php">./includes/modules/export/indesign/templates</directory> + <directory suffix=".php">./inc/modules/export/epub/templates</directory> + <directory suffix=".php">./inc/modules/export/indesign/templates</directory> </exclude> </whitelist> </filter> diff --git a/pressbooks.php b/pressbooks.php index 05766fa17e..daa61635a9 100644 --- a/pressbooks.php +++ b/pressbooks.php @@ -21,7 +21,7 @@ // Turn on $_SESSION // ------------------------------------------------------------------------------------------------------------------- -function _pb_session_start() { +function _pb_session_start() { // @codingStandardsIgnoreLine if ( ! session_id() ) { if ( ! headers_sent() ) { ini_set( 'session.use_only_cookies', true ); @@ -33,8 +33,8 @@ function _pb_session_start() { } } -function _pb_session_kill() { - $_SESSION = array(); +function _pb_session_kill() { // @codingStandardsIgnoreLine + $_SESSION = []; session_destroy(); } @@ -74,23 +74,7 @@ function _pb_session_kill() { // Class autoloader // ------------------------------------------------------------------------------------------------------------------- -function _pressbooks_autoload( $class_name ) { - - $prefix = 'Pressbooks\\'; - $len = strlen( $prefix ); - if ( strncasecmp( $prefix, $class_name, $len ) !== 0 ) { - // Ignore classes not in our namespace - return; - } - - $parts = explode( '\\', strtolower( $class_name ) ); - array_shift( $parts ); - $class_file = 'class-pb-' . str_replace( '_', '-', array_pop( $parts ) ) . '.php'; - $path = count( $parts ) ? implode( '/', $parts ) . '/' : ''; - @include( PB_PLUGIN_DIR . 'includes/' . $path . $class_file ); -} - -spl_autoload_register( '_pressbooks_autoload' ); +\HM\Autoloader\register_class_path( 'Pressbooks', __DIR__ . '/inc' ); // ------------------------------------------------------------------------------------------------------------------- // Composer autoloader (if needed) @@ -106,7 +90,7 @@ function _pressbooks_autoload( $class_name ) { // ------------------------------------------------------------------------------------------------------------------- // Check minimum requirements // ------------------------------------------------------------------------------------------------------------------- -if ( ! function_exists( 'pb_meets_minimum_requirements' ) && ! @include_once( PB_PLUGIN_DIR . 'compatibility.php' ) ) { +if ( ! function_exists( 'pb_meets_minimum_requirements' ) && ! @include_once( PB_PLUGIN_DIR . 'compatibility.php' ) ) { // @codingStandardsIgnoreLine add_action( 'admin_notices', function () { echo '<div id="message" class="error fade"><p>' . __( 'Cannot find Pressbooks install.', 'pressbooks' ) . '</p></div>'; } ); diff --git a/symbionts/Browser.php b/symbionts/Browser.php deleted file mode 100644 index 2cadc3dfb7..0000000000 --- a/symbionts/Browser.php +++ /dev/null @@ -1,1358 +0,0 @@ -<?php - -/** - * File: Browser.php - * Author: Chris Schuld (http://chrisschuld.com/) - * Last Modified: July 22nd, 2016 - * @version 2.0 - * @package PegasusPHP - * - * Copyright (C) 2008-2010 Chris Schuld (chris@chrisschuld.com) - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details at: - * http://www.gnu.org/copyleft/gpl.html - * - * - * Typical Usage: - * - * $browser = new Browser(); - * if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) { - * echo 'You have FireFox version 2 or greater'; - * } - * - * User Agents Sampled from: http://www.useragentstring.com/ - * - * This implementation is based on the original work from Gary White - * http://apptools.com/phptools/browser/ - * - */ - -class Browser -{ - private $_agent = ''; - private $_browser_name = ''; - private $_version = ''; - private $_platform = ''; - private $_os = ''; - private $_is_aol = false; - private $_is_mobile = false; - private $_is_tablet = false; - private $_is_robot = false; - private $_is_facebook = false; - private $_aol_version = ''; - - const BROWSER_UNKNOWN = 'unknown'; - const VERSION_UNKNOWN = 'unknown'; - - const BROWSER_OPERA = 'Opera'; // http://www.opera.com/ - const BROWSER_OPERA_MINI = 'Opera Mini'; // http://www.opera.com/mini/ - const BROWSER_WEBTV = 'WebTV'; // http://www.webtv.net/pc/ - const BROWSER_EDGE = 'Edge'; // https://www.microsoft.com/edge - const BROWSER_IE = 'Internet Explorer'; // http://www.microsoft.com/ie/ - const BROWSER_POCKET_IE = 'Pocket Internet Explorer'; // http://en.wikipedia.org/wiki/Internet_Explorer_Mobile - const BROWSER_KONQUEROR = 'Konqueror'; // http://www.konqueror.org/ - const BROWSER_ICAB = 'iCab'; // http://www.icab.de/ - const BROWSER_OMNIWEB = 'OmniWeb'; // http://www.omnigroup.com/applications/omniweb/ - const BROWSER_FIREBIRD = 'Firebird'; // http://www.ibphoenix.com/ - const BROWSER_FIREFOX = 'Firefox'; // http://www.mozilla.com/en-US/firefox/firefox.html - const BROWSER_ICEWEASEL = 'Iceweasel'; // http://www.geticeweasel.org/ - const BROWSER_SHIRETOKO = 'Shiretoko'; // http://wiki.mozilla.org/Projects/shiretoko - const BROWSER_MOZILLA = 'Mozilla'; // http://www.mozilla.com/en-US/ - const BROWSER_AMAYA = 'Amaya'; // http://www.w3.org/Amaya/ - const BROWSER_LYNX = 'Lynx'; // http://en.wikipedia.org/wiki/Lynx - const BROWSER_SAFARI = 'Safari'; // http://apple.com - const BROWSER_IPHONE = 'iPhone'; // http://apple.com - const BROWSER_IPOD = 'iPod'; // http://apple.com - const BROWSER_IPAD = 'iPad'; // http://apple.com - const BROWSER_CHROME = 'Chrome'; // http://www.google.com/chrome - const BROWSER_ANDROID = 'Android'; // http://www.android.com/ - const BROWSER_GOOGLEBOT = 'GoogleBot'; // http://en.wikipedia.org/wiki/Googlebot - const BROWSER_SLURP = 'Yahoo! Slurp'; // http://en.wikipedia.org/wiki/Yahoo!_Slurp - const BROWSER_W3CVALIDATOR = 'W3C Validator'; // http://validator.w3.org/ - const BROWSER_BLACKBERRY = 'BlackBerry'; // http://www.blackberry.com/ - const BROWSER_ICECAT = 'IceCat'; // http://en.wikipedia.org/wiki/GNU_IceCat - const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser'; // http://en.wikipedia.org/wiki/Web_Browser_for_S60 - const BROWSER_NOKIA = 'Nokia Browser'; // * all other WAP-based browsers on the Nokia Platform - const BROWSER_MSN = 'MSN Browser'; // http://explorer.msn.com/ - const BROWSER_MSNBOT = 'MSN Bot'; // http://search.msn.com/msnbot.htm - const BROWSER_BINGBOT = 'Bing Bot'; // http://en.wikipedia.org/wiki/Bingbot - const BROWSER_VIVALDI = 'Vivalidi'; // https://vivaldi.com/ - - const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator'; // http://browser.netscape.com/ (DEPRECATED) - const BROWSER_GALEON = 'Galeon'; // http://galeon.sourceforge.net/ (DEPRECATED) - const BROWSER_NETPOSITIVE = 'NetPositive'; // http://en.wikipedia.org/wiki/NetPositive (DEPRECATED) - const BROWSER_PHOENIX = 'Phoenix'; // http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox (DEPRECATED) - const BROWSER_PLAYSTATION = "PlayStation"; - - const PLATFORM_UNKNOWN = 'unknown'; - const PLATFORM_WINDOWS = 'Windows'; - const PLATFORM_WINDOWS_CE = 'Windows CE'; - const PLATFORM_APPLE = 'Apple'; - const PLATFORM_LINUX = 'Linux'; - const PLATFORM_OS2 = 'OS/2'; - const PLATFORM_BEOS = 'BeOS'; - const PLATFORM_IPHONE = 'iPhone'; - const PLATFORM_IPOD = 'iPod'; - const PLATFORM_IPAD = 'iPad'; - const PLATFORM_BLACKBERRY = 'BlackBerry'; - const PLATFORM_NOKIA = 'Nokia'; - const PLATFORM_FREEBSD = 'FreeBSD'; - const PLATFORM_OPENBSD = 'OpenBSD'; - const PLATFORM_NETBSD = 'NetBSD'; - const PLATFORM_SUNOS = 'SunOS'; - const PLATFORM_OPENSOLARIS = 'OpenSolaris'; - const PLATFORM_ANDROID = 'Android'; - const PLATFORM_PLAYSTATION = "Sony PlayStation"; - - const OPERATING_SYSTEM_UNKNOWN = 'unknown'; - - /** - * Class constructor - */ - public function __construct($userAgent = "") - { - $this->reset(); - if ($userAgent != "") { - $this->setUserAgent($userAgent); - } else { - $this->determine(); - } - } - - /** - * Reset all properties - */ - public function reset() - { - $this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ""; - $this->_browser_name = self::BROWSER_UNKNOWN; - $this->_version = self::VERSION_UNKNOWN; - $this->_platform = self::PLATFORM_UNKNOWN; - $this->_os = self::OPERATING_SYSTEM_UNKNOWN; - $this->_is_aol = false; - $this->_is_mobile = false; - $this->_is_tablet = false; - $this->_is_robot = false; - $this->_is_facebook = false; - $this->_aol_version = self::VERSION_UNKNOWN; - } - - /** - * Check to see if the specific browser is valid - * @param string $browserName - * @return bool True if the browser is the specified browser - */ - function isBrowser($browserName) - { - return (0 == strcasecmp($this->_browser_name, trim($browserName))); - } - - /** - * The name of the browser. All return types are from the class contants - * @return string Name of the browser - */ - public function getBrowser() - { - return $this->_browser_name; - } - - /** - * Set the name of the browser - * @param $browser string The name of the Browser - */ - public function setBrowser($browser) - { - $this->_browser_name = $browser; - } - - /** - * The name of the platform. All return types are from the class contants - * @return string Name of the browser - */ - public function getPlatform() - { - return $this->_platform; - } - - /** - * Set the name of the platform - * @param string $platform The name of the Platform - */ - public function setPlatform($platform) - { - $this->_platform = $platform; - } - - /** - * The version of the browser. - * @return string Version of the browser (will only contain alpha-numeric characters and a period) - */ - public function getVersion() - { - return $this->_version; - } - - /** - * Set the version of the browser - * @param string $version The version of the Browser - */ - public function setVersion($version) - { - $this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/', '', $version); - } - - /** - * The version of AOL. - * @return string Version of AOL (will only contain alpha-numeric characters and a period) - */ - public function getAolVersion() - { - return $this->_aol_version; - } - - /** - * Set the version of AOL - * @param string $version The version of AOL - */ - public function setAolVersion($version) - { - $this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/', '', $version); - } - - /** - * Is the browser from AOL? - * @return boolean True if the browser is from AOL otherwise false - */ - public function isAol() - { - return $this->_is_aol; - } - - /** - * Is the browser from a mobile device? - * @return boolean True if the browser is from a mobile device otherwise false - */ - public function isMobile() - { - return $this->_is_mobile; - } - - /** - * Is the browser from a tablet device? - * @return boolean True if the browser is from a tablet device otherwise false - */ - public function isTablet() - { - return $this->_is_tablet; - } - - /** - * Is the browser from a robot (ex Slurp,GoogleBot)? - * @return boolean True if the browser is from a robot otherwise false - */ - public function isRobot() - { - return $this->_is_robot; - } - - /** - * Is the browser from facebook? - * @return boolean True if the browser is from facebook otherwise false - */ - public function isFacebook() - { - return $this->_is_facebook; - } - - /** - * Set the browser to be from AOL - * @param $isAol - */ - public function setAol($isAol) - { - $this->_is_aol = $isAol; - } - - /** - * Set the Browser to be mobile - * @param boolean $value is the browser a mobile browser or not - */ - protected function setMobile($value = true) - { - $this->_is_mobile = $value; - } - - /** - * Set the Browser to be tablet - * @param boolean $value is the browser a tablet browser or not - */ - protected function setTablet($value = true) - { - $this->_is_tablet = $value; - } - - /** - * Set the Browser to be a robot - * @param boolean $value is the browser a robot or not - */ - protected function setRobot($value = true) - { - $this->_is_robot = $value; - } - - /** - * Set the Browser to be a Facebook request - * @param boolean $value is the browser a robot or not - */ - protected function setFacebook($value = true) - { - $this->_is_facebook = $value; - } - - /** - * Get the user agent value in use to determine the browser - * @return string The user agent from the HTTP header - */ - public function getUserAgent() - { - return $this->_agent; - } - - /** - * Set the user agent value (the construction will use the HTTP header value - this will overwrite it) - * @param string $agent_string The value for the User Agent - */ - public function setUserAgent($agent_string) - { - $this->reset(); - $this->_agent = $agent_string; - $this->determine(); - } - - /** - * Used to determine if the browser is actually "chromeframe" - * @since 1.7 - * @return boolean True if the browser is using chromeframe - */ - public function isChromeFrame() - { - return (strpos($this->_agent, "chromeframe") !== false); - } - - /** - * Returns a formatted string with a summary of the details of the browser. - * @return string formatted string with a summary of the browser - */ - public function __toString() - { - return "<strong>Browser Name:</strong> {$this->getBrowser()}<br/>\n" . - "<strong>Browser Version:</strong> {$this->getVersion()}<br/>\n" . - "<strong>Browser User Agent String:</strong> {$this->getUserAgent()}<br/>\n" . - "<strong>Platform:</strong> {$this->getPlatform()}<br/>"; - } - - /** - * Protected routine to calculate and determine what the browser is in use (including platform) - */ - protected function determine() - { - $this->checkPlatform(); - $this->checkBrowsers(); - $this->checkForAol(); - } - - /** - * Protected routine to determine the browser type - * @return boolean True if the browser was detected otherwise false - */ - protected function checkBrowsers() - { - return ( - // well-known, well-used - // Special Notes: - // (1) Opera must be checked before FireFox due to the odd - // user agents used in some older versions of Opera - // (2) WebTV is strapped onto Internet Explorer so we must - // check for WebTV before IE - // (3) (deprecated) Galeon is based on Firefox and needs to be - // tested before Firefox is tested - // (4) OmniWeb is based on Safari so OmniWeb check must occur - // before Safari - // (5) Netscape 9+ is based on Firefox so Netscape checks - // before FireFox are necessary - // (6) Vivalid is UA contains both Firefox and Chrome so Vivalid checks - // before Firefox and Chrome - $this->checkBrowserWebTv() || - $this->checkBrowserEdge() || - $this->checkBrowserInternetExplorer() || - $this->checkBrowserOpera() || - $this->checkBrowserGaleon() || - $this->checkBrowserNetscapeNavigator9Plus() || - $this->checkBrowserVivaldi() || - $this->checkBrowserFirefox() || - $this->checkBrowserChrome() || - $this->checkBrowserOmniWeb() || - - // common mobile - $this->checkBrowserAndroid() || - $this->checkBrowseriPad() || - $this->checkBrowseriPod() || - $this->checkBrowseriPhone() || - $this->checkBrowserBlackBerry() || - $this->checkBrowserNokia() || - - // common bots - $this->checkBrowserGoogleBot() || - $this->checkBrowserMSNBot() || - $this->checkBrowserBingBot() || - $this->checkBrowserSlurp() || - - // check for facebook external hit when loading URL - $this->checkFacebookExternalHit() || - - // WebKit base check (post mobile and others) - $this->checkBrowserSafari() || - - // everyone else - $this->checkBrowserNetPositive() || - $this->checkBrowserFirebird() || - $this->checkBrowserKonqueror() || - $this->checkBrowserIcab() || - $this->checkBrowserPhoenix() || - $this->checkBrowserAmaya() || - $this->checkBrowserLynx() || - $this->checkBrowserShiretoko() || - $this->checkBrowserIceCat() || - $this->checkBrowserIceweasel() || - $this->checkBrowserW3CValidator() || - $this->checkBrowserPlayStation() || - $this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */ - ); - } - - /** - * Determine if the user is using a BlackBerry (last updated 1.7) - * @return boolean True if the browser is the BlackBerry browser otherwise false - */ - protected function checkBrowserBlackBerry() - { - if (stripos($this->_agent, 'blackberry') !== false) { - $aresult = explode("/", stristr($this->_agent, "BlackBerry")); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->_browser_name = self::BROWSER_BLACKBERRY; - $this->setMobile(true); - return true; - } - } - return false; - } - - /** - * Determine if the user is using an AOL User Agent (last updated 1.7) - * @return boolean True if the browser is from AOL otherwise false - */ - protected function checkForAol() - { - $this->setAol(false); - $this->setAolVersion(self::VERSION_UNKNOWN); - - if (stripos($this->_agent, 'aol') !== false) { - $aversion = explode(' ', stristr($this->_agent, 'AOL')); - if (isset($aversion[1])) { - $this->setAol(true); - $this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1])); - return true; - } - } - return false; - } - - /** - * Determine if the browser is the GoogleBot or not (last updated 1.7) - * @return boolean True if the browser is the GoogletBot otherwise false - */ - protected function checkBrowserGoogleBot() - { - if (stripos($this->_agent, 'googlebot') !== false) { - $aresult = explode('/', stristr($this->_agent, 'googlebot')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion(str_replace(';', '', $aversion[0])); - $this->_browser_name = self::BROWSER_GOOGLEBOT; - $this->setRobot(true); - return true; - } - } - return false; - } - - /** - * Determine if the browser is the MSNBot or not (last updated 1.9) - * @return boolean True if the browser is the MSNBot otherwise false - */ - protected function checkBrowserMSNBot() - { - if (stripos($this->_agent, "msnbot") !== false) { - $aresult = explode("/", stristr($this->_agent, "msnbot")); - if (isset($aresult[1])) { - $aversion = explode(" ", $aresult[1]); - $this->setVersion(str_replace(";", "", $aversion[0])); - $this->_browser_name = self::BROWSER_MSNBOT; - $this->setRobot(true); - return true; - } - } - return false; - } - - /** - * Determine if the browser is the BingBot or not (last updated 1.9) - * @return boolean True if the browser is the BingBot otherwise false - */ - protected function checkBrowserBingBot() - { - if (stripos($this->_agent, "bingbot") !== false) { - $aresult = explode("/", stristr($this->_agent, "bingbot")); - if (isset($aresult[1])) { - $aversion = explode(" ", $aresult[1]); - $this->setVersion(str_replace(";", "", $aversion[0])); - $this->_browser_name = self::BROWSER_BINGBOT; - $this->setRobot(true); - return true; - } - } - return false; - } - - /** - * Determine if the browser is the W3C Validator or not (last updated 1.7) - * @return boolean True if the browser is the W3C Validator otherwise false - */ - protected function checkBrowserW3CValidator() - { - if (stripos($this->_agent, 'W3C-checklink') !== false) { - $aresult = explode('/', stristr($this->_agent, 'W3C-checklink')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->_browser_name = self::BROWSER_W3CVALIDATOR; - return true; - } - } else if (stripos($this->_agent, 'W3C_Validator') !== false) { - // Some of the Validator versions do not delineate w/ a slash - add it back in - $ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent); - $aresult = explode('/', stristr($ua, 'W3C_Validator')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->_browser_name = self::BROWSER_W3CVALIDATOR; - return true; - } - } else if (stripos($this->_agent, 'W3C-mobileOK') !== false) { - $this->_browser_name = self::BROWSER_W3CVALIDATOR; - $this->setMobile(true); - return true; - } - return false; - } - - /** - * Determine if the browser is the Yahoo! Slurp Robot or not (last updated 1.7) - * @return boolean True if the browser is the Yahoo! Slurp Robot otherwise false - */ - protected function checkBrowserSlurp() - { - if (stripos($this->_agent, 'slurp') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Slurp')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->_browser_name = self::BROWSER_SLURP; - $this->setRobot(true); - $this->setMobile(false); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Edge or not - * @return boolean True if the browser is Edge otherwise false - */ - protected function checkBrowserEdge() - { - if( stripos($this->_agent,'Edge/') !== false ) { - $aresult = explode('/', stristr($this->_agent, 'Edge')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_EDGE); - if(stripos($this->_agent, 'Windows Phone') !== false || stripos($this->_agent, 'Android') !== false) { - $this->setMobile(true); - } - return true; - } - } - return false; - } - - /** - * Determine if the browser is Internet Explorer or not (last updated 1.7) - * @return boolean True if the browser is Internet Explorer otherwise false - */ - protected function checkBrowserInternetExplorer() - { - // Test for IE11 - if( stripos($this->_agent,'Trident/7.0; rv:11.0') !== false ) { - $this->setBrowser(self::BROWSER_IE); - $this->setVersion('11.0'); - return true; - } - // Test for v1 - v1.5 IE - else if (stripos($this->_agent, 'microsoft internet explorer') !== false) { - $this->setBrowser(self::BROWSER_IE); - $this->setVersion('1.0'); - $aresult = stristr($this->_agent, '/'); - if (preg_match('/308|425|426|474|0b1/i', $aresult)) { - $this->setVersion('1.5'); - } - return true; - } // Test for versions > 1.5 - else if (stripos($this->_agent, 'msie') !== false && stripos($this->_agent, 'opera') === false) { - // See if the browser is the odd MSN Explorer - if (stripos($this->_agent, 'msnb') !== false) { - $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'MSN')); - if (isset($aresult[1])) { - $this->setBrowser(self::BROWSER_MSN); - $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1])); - return true; - } - } - $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'msie')); - if (isset($aresult[1])) { - $this->setBrowser(self::BROWSER_IE); - $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1])); - if(stripos($this->_agent, 'IEMobile') !== false) { - $this->setBrowser(self::BROWSER_POCKET_IE); - $this->setMobile(true); - } - return true; - } - } // Test for versions > IE 10 - else if(stripos($this->_agent, 'trident') !== false) { - $this->setBrowser(self::BROWSER_IE); - $result = explode('rv:', $this->_agent); - if (isset($result[1])) { - $this->setVersion(preg_replace('/[^0-9.]+/', '', $result[1])); - $this->_agent = str_replace(array("Mozilla", "Gecko"), "MSIE", $this->_agent); - } - } // Test for Pocket IE - else if (stripos($this->_agent, 'mspie') !== false || stripos($this->_agent, 'pocket') !== false) { - $aresult = explode(' ', stristr($this->_agent, 'mspie')); - if (isset($aresult[1])) { - $this->setPlatform(self::PLATFORM_WINDOWS_CE); - $this->setBrowser(self::BROWSER_POCKET_IE); - $this->setMobile(true); - - if (stripos($this->_agent, 'mspie') !== false) { - $this->setVersion($aresult[1]); - } else { - $aversion = explode('/', $this->_agent); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - } - } - return true; - } - } - return false; - } - - /** - * Determine if the browser is Opera or not (last updated 1.7) - * @return boolean True if the browser is Opera otherwise false - */ - protected function checkBrowserOpera() - { - if (stripos($this->_agent, 'opera mini') !== false) { - $resultant = stristr($this->_agent, 'opera mini'); - if (preg_match('/\//', $resultant)) { - $aresult = explode('/', $resultant); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - } - } else { - $aversion = explode(' ', stristr($resultant, 'opera mini')); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - } - } - $this->_browser_name = self::BROWSER_OPERA_MINI; - $this->setMobile(true); - return true; - } else if (stripos($this->_agent, 'opera') !== false) { - $resultant = stristr($this->_agent, 'opera'); - if (preg_match('/Version\/(1*.*)$/', $resultant, $matches)) { - $this->setVersion($matches[1]); - } else if (preg_match('/\//', $resultant)) { - $aresult = explode('/', str_replace("(", " ", $resultant)); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - } - } else { - $aversion = explode(' ', stristr($resultant, 'opera')); - $this->setVersion(isset($aversion[1]) ? $aversion[1] : ""); - } - if (stripos($this->_agent, 'Opera Mobi') !== false) { - $this->setMobile(true); - } - $this->_browser_name = self::BROWSER_OPERA; - return true; - } else if (stripos($this->_agent, 'OPR') !== false) { - $resultant = stristr($this->_agent, 'OPR'); - if (preg_match('/\//', $resultant)) { - $aresult = explode('/', str_replace("(", " ", $resultant)); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - } - } - if (stripos($this->_agent, 'Mobile') !== false) { - $this->setMobile(true); - } - $this->_browser_name = self::BROWSER_OPERA; - return true; - } - return false; - } - - /** - * Determine if the browser is Chrome or not (last updated 1.7) - * @return boolean True if the browser is Chrome otherwise false - */ - protected function checkBrowserChrome() - { - if (stripos($this->_agent, 'Chrome') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Chrome')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_CHROME); - //Chrome on Android - if (stripos($this->_agent, 'Android') !== false) { - if (stripos($this->_agent, 'Mobile') !== false) { - $this->setMobile(true); - } else { - $this->setTablet(true); - } - } - return true; - } - } - return false; - } - - - /** - * Determine if the browser is WebTv or not (last updated 1.7) - * @return boolean True if the browser is WebTv otherwise false - */ - protected function checkBrowserWebTv() - { - if (stripos($this->_agent, 'webtv') !== false) { - $aresult = explode('/', stristr($this->_agent, 'webtv')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_WEBTV); - return true; - } - } - return false; - } - - /** - * Determine if the browser is NetPositive or not (last updated 1.7) - * @return boolean True if the browser is NetPositive otherwise false - */ - protected function checkBrowserNetPositive() - { - if (stripos($this->_agent, 'NetPositive') !== false) { - $aresult = explode('/', stristr($this->_agent, 'NetPositive')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion(str_replace(array('(', ')', ';'), '', $aversion[0])); - $this->setBrowser(self::BROWSER_NETPOSITIVE); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Galeon or not (last updated 1.7) - * @return boolean True if the browser is Galeon otherwise false - */ - protected function checkBrowserGaleon() - { - if (stripos($this->_agent, 'galeon') !== false) { - $aresult = explode(' ', stristr($this->_agent, 'galeon')); - $aversion = explode('/', $aresult[0]); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - $this->setBrowser(self::BROWSER_GALEON); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Konqueror or not (last updated 1.7) - * @return boolean True if the browser is Konqueror otherwise false - */ - protected function checkBrowserKonqueror() - { - if (stripos($this->_agent, 'Konqueror') !== false) { - $aresult = explode(' ', stristr($this->_agent, 'Konqueror')); - $aversion = explode('/', $aresult[0]); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - $this->setBrowser(self::BROWSER_KONQUEROR); - return true; - } - } - return false; - } - - /** - * Determine if the browser is iCab or not (last updated 1.7) - * @return boolean True if the browser is iCab otherwise false - */ - protected function checkBrowserIcab() - { - if (stripos($this->_agent, 'icab') !== false) { - $aversion = explode(' ', stristr(str_replace('/', ' ', $this->_agent), 'icab')); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - $this->setBrowser(self::BROWSER_ICAB); - return true; - } - } - return false; - } - - /** - * Determine if the browser is OmniWeb or not (last updated 1.7) - * @return boolean True if the browser is OmniWeb otherwise false - */ - protected function checkBrowserOmniWeb() - { - if (stripos($this->_agent, 'omniweb') !== false) { - $aresult = explode('/', stristr($this->_agent, 'omniweb')); - $aversion = explode(' ', isset($aresult[1]) ? $aresult[1] : ""); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_OMNIWEB); - return true; - } - return false; - } - - /** - * Determine if the browser is Phoenix or not (last updated 1.7) - * @return boolean True if the browser is Phoenix otherwise false - */ - protected function checkBrowserPhoenix() - { - if (stripos($this->_agent, 'Phoenix') !== false) { - $aversion = explode('/', stristr($this->_agent, 'Phoenix')); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - $this->setBrowser(self::BROWSER_PHOENIX); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Firebird or not (last updated 1.7) - * @return boolean True if the browser is Firebird otherwise false - */ - protected function checkBrowserFirebird() - { - if (stripos($this->_agent, 'Firebird') !== false) { - $aversion = explode('/', stristr($this->_agent, 'Firebird')); - if (isset($aversion[1])) { - $this->setVersion($aversion[1]); - $this->setBrowser(self::BROWSER_FIREBIRD); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Netscape Navigator 9+ or not (last updated 1.7) - * NOTE: (http://browser.netscape.com/ - Official support ended on March 1st, 2008) - * @return boolean True if the browser is Netscape Navigator 9+ otherwise false - */ - protected function checkBrowserNetscapeNavigator9Plus() - { - if (stripos($this->_agent, 'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i', $this->_agent, $matches)) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR); - return true; - } else if (stripos($this->_agent, 'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i', $this->_agent, $matches)) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR); - return true; - } - return false; - } - - /** - * Determine if the browser is Shiretoko or not (https://wiki.mozilla.org/Projects/shiretoko) (last updated 1.7) - * @return boolean True if the browser is Shiretoko otherwise false - */ - protected function checkBrowserShiretoko() - { - if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i', $this->_agent, $matches)) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_SHIRETOKO); - return true; - } - return false; - } - - /** - * Determine if the browser is Ice Cat or not (http://en.wikipedia.org/wiki/GNU_IceCat) (last updated 1.7) - * @return boolean True if the browser is Ice Cat otherwise false - */ - protected function checkBrowserIceCat() - { - if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i', $this->_agent, $matches)) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_ICECAT); - return true; - } - return false; - } - - /** - * Determine if the browser is Nokia or not (last updated 1.7) - * @return boolean True if the browser is Nokia otherwise false - */ - protected function checkBrowserNokia() - { - if (preg_match("/Nokia([^\/]+)\/([^ SP]+)/i", $this->_agent, $matches)) { - $this->setVersion($matches[2]); - if (stripos($this->_agent, 'Series60') !== false || strpos($this->_agent, 'S60') !== false) { - $this->setBrowser(self::BROWSER_NOKIA_S60); - } else { - $this->setBrowser(self::BROWSER_NOKIA); - } - $this->setMobile(true); - return true; - } - return false; - } - - /** - * Determine if the browser is Firefox or not (last updated 1.7) - * @return boolean True if the browser is Firefox otherwise false - */ - protected function checkBrowserFirefox() - { - if (stripos($this->_agent, 'safari') === false) { - if (preg_match("/Firefox[\/ \(]([^ ;\)]+)/i", $this->_agent, $matches)) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_FIREFOX); - //Firefox on Android - if (stripos($this->_agent, 'Android') !== false) { - if (stripos($this->_agent, 'Mobile') !== false) { - $this->setMobile(true); - } else { - $this->setTablet(true); - } - } - return true; - } else if (preg_match("/Firefox$/i", $this->_agent, $matches)) { - $this->setVersion(""); - $this->setBrowser(self::BROWSER_FIREFOX); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Firefox or not (last updated 1.7) - * @return boolean True if the browser is Firefox otherwise false - */ - protected function checkBrowserIceweasel() - { - if (stripos($this->_agent, 'Iceweasel') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Iceweasel')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_ICEWEASEL); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Mozilla or not (last updated 1.7) - * @return boolean True if the browser is Mozilla otherwise false - */ - protected function checkBrowserMozilla() - { - if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) { - $aversion = explode(' ', stristr($this->_agent, 'rv:')); - preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent, $aversion); - $this->setVersion(str_replace('rv:', '', $aversion[0])); - $this->setBrowser(self::BROWSER_MOZILLA); - return true; - } else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) { - $aversion = explode('', stristr($this->_agent, 'rv:')); - $this->setVersion(str_replace('rv:', '', $aversion[0])); - $this->setBrowser(self::BROWSER_MOZILLA); - return true; - } else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/mozilla\/([^ ]*)/i', $this->_agent, $matches) && stripos($this->_agent, 'netscape') === false) { - $this->setVersion($matches[1]); - $this->setBrowser(self::BROWSER_MOZILLA); - return true; - } - return false; - } - - /** - * Determine if the browser is Lynx or not (last updated 1.7) - * @return boolean True if the browser is Lynx otherwise false - */ - protected function checkBrowserLynx() - { - if (stripos($this->_agent, 'lynx') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Lynx')); - $aversion = explode(' ', (isset($aresult[1]) ? $aresult[1] : "")); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_LYNX); - return true; - } - return false; - } - - /** - * Determine if the browser is Amaya or not (last updated 1.7) - * @return boolean True if the browser is Amaya otherwise false - */ - protected function checkBrowserAmaya() - { - if (stripos($this->_agent, 'amaya') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Amaya')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_AMAYA); - return true; - } - } - return false; - } - - /** - * Determine if the browser is Safari or not (last updated 1.7) - * @return boolean True if the browser is Safari otherwise false - */ - protected function checkBrowserSafari() - { - if (stripos($this->_agent, 'Safari') !== false - && stripos($this->_agent, 'iPhone') === false - && stripos($this->_agent, 'iPod') === false) { - - $aresult = explode('/', stristr($this->_agent, 'Version')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - } else { - $this->setVersion(self::VERSION_UNKNOWN); - } - $this->setBrowser(self::BROWSER_SAFARI); - return true; - } - return false; - } - - /** - * Detect if URL is loaded from FacebookExternalHit - * @return boolean True if it detects FacebookExternalHit otherwise false - */ - protected function checkFacebookExternalHit() - { - if(stristr($this->_agent,'FacebookExternalHit')) - { - $this->setRobot(true); - $this->setFacebook(true); - return true; - } - return false; - } - - /** - * Detect if URL is being loaded from internal Facebook browser - * @return boolean True if it detects internal Facebook browser otherwise false - */ - protected function checkForFacebookIos() - { - if(stristr($this->_agent,'FBIOS')) - { - $this->setFacebook(true); - return true; - } - return false; - } - - /** - * Detect Version for the Safari browser on iOS devices - * @return boolean True if it detects the version correctly otherwise false - */ - protected function getSafariVersionOnIos() - { - $aresult = explode('/',stristr($this->_agent,'Version')); - if( isset($aresult[1]) ) - { - $aversion = explode(' ',$aresult[1]); - $this->setVersion($aversion[0]); - return true; - } - return false; - } - - /** - * Detect Version for the Chrome browser on iOS devices - * @return boolean True if it detects the version correctly otherwise false - */ - protected function getChromeVersionOnIos() - { - $aresult = explode('/',stristr($this->_agent,'CriOS')); - if( isset($aresult[1]) ) - { - $aversion = explode(' ',$aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_CHROME); - return true; - } - return false; - } - - /** - * Determine if the browser is iPhone or not (last updated 1.7) - * @return boolean True if the browser is iPhone otherwise false - */ - protected function checkBrowseriPhone() { - if( stripos($this->_agent,'iPhone') !== false ) { - $this->setVersion(self::VERSION_UNKNOWN); - $this->setBrowser(self::BROWSER_IPHONE); - $this->getSafariVersionOnIos(); - $this->getChromeVersionOnIos(); - $this->checkForFacebookIos(); - $this->setMobile(true); - return true; - } - return false; - } - - /** - * Determine if the browser is iPad or not (last updated 1.7) - * @return boolean True if the browser is iPad otherwise false - */ - protected function checkBrowseriPad() { - if( stripos($this->_agent,'iPad') !== false ) { - $this->setVersion(self::VERSION_UNKNOWN); - $this->setBrowser(self::BROWSER_IPAD); - $this->getSafariVersionOnIos(); - $this->getChromeVersionOnIos(); - $this->checkForFacebookIos(); - $this->setTablet(true); - return true; - } - return false; - } - - /** - * Determine if the browser is iPod or not (last updated 1.7) - * @return boolean True if the browser is iPod otherwise false - */ - protected function checkBrowseriPod() { - if( stripos($this->_agent,'iPod') !== false ) { - $this->setVersion(self::VERSION_UNKNOWN); - $this->setBrowser(self::BROWSER_IPOD); - $this->getSafariVersionOnIos(); - $this->getChromeVersionOnIos(); - $this->checkForFacebookIos(); - $this->setMobile(true); - return true; - } - return false; - } - - /** - * Determine if the browser is Android or not (last updated 1.7) - * @return boolean True if the browser is Android otherwise false - */ - protected function checkBrowserAndroid() - { - if (stripos($this->_agent, 'Android') !== false) { - $aresult = explode(' ', stristr($this->_agent, 'Android')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - } else { - $this->setVersion(self::VERSION_UNKNOWN); - } - if (stripos($this->_agent, 'Mobile') !== false) { - $this->setMobile(true); - } else { - $this->setTablet(true); - } - $this->setBrowser(self::BROWSER_ANDROID); - return true; - } - return false; - } - - /** - * Determine if the browser is Vivaldi - * @return boolean True if the browser is Vivaldi otherwise false - */ - protected function checkBrowserVivaldi() - { - if (stripos($this->_agent, 'Vivaldi') !== false) { - $aresult = explode('/', stristr($this->_agent, 'Vivaldi')); - if (isset($aresult[1])) { - $aversion = explode(' ', $aresult[1]); - $this->setVersion($aversion[0]); - $this->setBrowser(self::BROWSER_VIVALDI); - return true; - } - } - return false; - } - - /** - * Determine if the browser is a PlayStation - * @return boolean True if the browser is PlayStation otherwise false - */ - protected function checkBrowserPlayStation() - { - if (stripos($this->_agent, 'PlayStation ') !== false) { - $aresult = explode(' ', stristr($this->_agent, 'PlayStation ')); - $this->setBrowser(self::BROWSER_PLAYSTATION); - if (isset($aresult[0])) { - $aversion = explode(')', $aresult[2]); - $this->setVersion($aversion[0]); - if (stripos($this->_agent, 'Portable)') !== false || stripos($this->_agent, 'Vita') !== false) { - $this->setMobile(true); - } - return true; - } - } - return false; - } - - /** - * Determine the user's platform (last updated 2.0) - */ - protected function checkPlatform() - { - if (stripos($this->_agent, 'windows') !== false) - { - $this->_platform = self::PLATFORM_WINDOWS; - } - else if (stripos($this->_agent, 'iPad') !== false) - { - $this->_platform = self::PLATFORM_IPAD; - } - else if (stripos($this->_agent, 'iPod') !== false) - { - $this->_platform = self::PLATFORM_IPOD; - } - else if (stripos($this->_agent, 'iPhone') !== false) - { - $this->_platform = self::PLATFORM_IPHONE; - } - elseif (stripos($this->_agent, 'mac') !== false) - { - $this->_platform = self::PLATFORM_APPLE; - } - elseif (stripos($this->_agent, 'android') !== false) - { - $this->_platform = self::PLATFORM_ANDROID; - } - elseif (stripos($this->_agent, 'linux') !== false) - { - $this->_platform = self::PLATFORM_LINUX; - } - else if (stripos($this->_agent, 'Nokia') !== false) - { - $this->_platform = self::PLATFORM_NOKIA; - } - else if (stripos($this->_agent, 'BlackBerry') !== false) - { - $this->_platform = self::PLATFORM_BLACKBERRY; - } - elseif (stripos($this->_agent, 'FreeBSD') !== false) - { - $this->_platform = self::PLATFORM_FREEBSD; - } - elseif (stripos($this->_agent, 'OpenBSD') !== false) - { - $this->_platform = self::PLATFORM_OPENBSD; - } - elseif (stripos($this->_agent, 'NetBSD') !== false) - { - $this->_platform = self::PLATFORM_NETBSD; - } - elseif (stripos($this->_agent, 'OpenSolaris') !== false) - { - $this->_platform = self::PLATFORM_OPENSOLARIS; - } - elseif (stripos($this->_agent, 'SunOS') !== false) - { - $this->_platform = self::PLATFORM_SUNOS; - } - elseif (stripos($this->_agent, 'OS\/2') !== false) - { - $this->_platform = self::PLATFORM_OS2; - } - elseif (stripos($this->_agent, 'BeOS') !== false) - { - $this->_platform = self::PLATFORM_BEOS; - } - elseif (stripos($this->_agent, 'win') !== false) - { - $this->_platform = self::PLATFORM_WINDOWS; - } - elseif (stripos($this->_agent, 'Playstation') !== false) - { - $this->_platform = self::PLATFORM_PLAYSTATION; - } - - } -} diff --git a/templates/admin/results.php b/templates/admin/results.php index f59579025a..d876cf7b95 100644 --- a/templates/admin/results.php +++ b/templates/admin/results.php @@ -9,7 +9,7 @@ <?php foreach ( $results as $pos => $result ) : ?> <li<?php if ( $result->replace ) : ?> class="diff"<?php endif; ?>> <h3 class="title"><?php $search->show( $result ); ?></h3> - <div class="options"><?php echo implode( ' | ', $search->get_options( $result ) ); ?></div> + <div class="options"><?php echo implode( ' | ', $search->getOptions( $result ) ); ?></div> <div class="content original"><?php echo $result->search ?></div> <?php if ( $result->replace ) : ?> <div class="content replacement"><?php echo $result->replace ?></div> diff --git a/templates/admin/search.php b/templates/admin/search.php index 27efa2fc83..74e025624c 100644 --- a/templates/admin/search.php +++ b/templates/admin/search.php @@ -14,7 +14,7 @@ <option value="<?php echo get_class( $search_type ) ?>" <?php // @codingStandardsIgnoreLine selected( stripslashes( @$_POST['source'] ), get_class( $search_type ) ); ?>/><?php echo esc_attr( $search_type->name() ) ?></option> <?php endforeach; ?> - </fieldset> + </select> </td> </tr> <?php /* <tr> diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 178375a23e..02c01bd1c6 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -5,17 +5,15 @@ $_tests_dir = '/tmp/wordpress-tests-lib'; } +if ( ! function_exists( '\HM\Autoloader\register_class_path' ) ) { + require_once( __DIR__ . '/../autoloader.php' ); +} + require_once $_tests_dir . '/includes/functions.php'; function _manually_load_plugin() { - - $dir = dirname( dirname( __FILE__ ) ); - - // When running phpunit WP_PLUGIN_DIR is set to /tmp but Pressbooks is not located there. Override: - define( 'PB_PLUGIN_DIR', "{$dir}/" ); - include_once( "{$dir}/compatibility.php" ); - - require "{$dir}/pressbooks.php"; + require_once( __DIR__ . '/../autoloader.php' ); + require_once( __DIR__ . '/../pressbooks.php' ); } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); diff --git a/tests/data/template.php b/tests/data/template.php index 81153cc109..5595a52de2 100644 --- a/tests/data/template.php +++ b/tests/data/template.php @@ -1,16 +1,17 @@ <?php -if ( ! defined( 'ABSPATH' ) ) +if ( ! defined( 'ABSPATH' ) ) { exit; +} ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> - <title><?= $title ?> + <?php echo $title ?> - + diff --git a/tests/test-admin-branding.php b/tests/test-admin-branding.php index a5eb04516b..987815d706 100644 --- a/tests/test-admin-branding.php +++ b/tests/test-admin-branding.php @@ -2,38 +2,23 @@ class Admin_BrandingTest extends \WP_UnitTestCase { - - /** - * @covers \Pressbooks\Admin\Branding\custom_color_scheme - */ public function test_custom_color_scheme() { $this->expectOutputRegex( '//' ); \Pressbooks\Admin\Branding\custom_color_scheme(); } - /** - * @covers \Pressbooks\Admin\Branding\custom_login_logo - */ public function test_custom_login_logo() { $this->expectOutputRegex( '/<\/style>/' ); \Pressbooks\Admin\Branding\custom_login_logo(); } - - /** - * @covers \Pressbooks\Admin\Branding\login_url - */ public function test_login_url() { $this->assertRegExp( '#^https?://#i', \Pressbooks\Admin\Branding\login_url() ); } - - /** - * @covers \Pressbooks\Admin\Branding\login_title - */ public function test_login_title() { $title = \Pressbooks\Admin\Branding\login_title(); diff --git a/tests/test-admin-fonts.php b/tests/test-admin-fonts.php index 85842881c0..d083cb8350 100644 --- a/tests/test-admin-fonts.php +++ b/tests/test-admin-fonts.php @@ -1,6 +1,6 @@ getMockBuilder( '\Pressbooks\GlobalTypography' ) - ->getMock(); - - return $stub; - } ); + $stub = $this->getMockBuilder( '\Pressbooks\GlobalTypography' ) + ->getMock(); + return $stub; + } + ); // Replace Sass service with mock - Container::set( 'Sass', function () { + Container::set( + 'Sass', function () { - $stub = $this->getMockBuilder( '\Pressbooks\Sass' ) - ->getMock(); + $stub = $this->getMockBuilder( '\Pressbooks\Sass' ) + ->getMock(); - $stub->method( 'pathToUserGeneratedCss' ) - ->willReturn( $this->_createTmpDir() ); + $stub->method( 'pathToUserGeneratedCss' ) + ->willReturn( $this->_createTmpDir() ); - $stub->method( 'pathToPartials' ) - ->willReturn( PB_PLUGIN_DIR . 'assets/scss/partials' ); + $stub->method( 'pathToPartials' ) + ->willReturn( PB_PLUGIN_DIR . 'assets/scss/partials' ); - return $stub; - } ); + return $stub; + } + ); } @@ -51,20 +54,12 @@ public function tearDown() { parent::tearDown(); } - - /** - * @covers \Pressbooks\Admin\Fonts\update_font_stacks - */ public function test_update_font_stacks() { \Pressbooks\Admin\Fonts\update_font_stacks(); $this->assertTrue( true ); } - - /** - * @covers \Pressbooks\Admin\Fonts\fix_missing_font_stacks - */ public function test_fix_missing_font_stacks() { $this->_book(); diff --git a/tests/test-admin-laf.php b/tests/test-admin-laf.php index 71032d97e0..daecb4e5c5 100644 --- a/tests/test-admin-laf.php +++ b/tests/test-admin-laf.php @@ -1,15 +1,12 @@ assertContains( 'Pressbooks', $buffer ); } - /** - * @covers \Pressbooks\Admin\Laf\admin_title - */ function test_admin_title() { $result = \Pressbooks\Admin\Laf\admin_title( 'Hello WordPress!' ); @@ -32,9 +26,6 @@ function test_admin_title() { $this->assertEquals( $result, 'Hello World!' ); } - /** - * @covers \Pressbooks\Admin\Laf\replace_book_admin_menu - */ function test_replace_book_admin_menu() { global $menu, $submenu; @@ -55,4 +46,4 @@ function test_replace_book_admin_menu() { $this->assertArrayHasKey( 'edit.php?post_type=chapter', $submenu ); } -} \ No newline at end of file +} diff --git a/tests/test-admin-plugins.php b/tests/test-admin-plugins.php index 83af62461e..e9385e636a 100644 --- a/tests/test-admin-plugins.php +++ b/tests/test-admin-plugins.php @@ -1,25 +1,22 @@ array( - 'Name' => 'Hello Dolly', - 'PluginURI' => 'http://wordpress.org/extend/plugins/hello-dolly/', - 'Version' => '1.6', - 'Description' => 'This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from Hello, Dolly in the upper right of your admin screen on every page.', - 'Author' => 'Matt Mullenweg', - 'AuthorURI' => 'http://ma.tt/', - 'Title' => 'Hello Dolly', - 'AuthorName' => 'Matt Mullenweg' - ), - 'pressbooks-textbook/pressbooks-textbook.php' => array( + $plugins = [ + 'hello-dolly/hello.php' => [ + 'Name' => 'Hello Dolly', + 'PluginURI' => 'http://wordpress.org/extend/plugins/hello-dolly/', + 'Version' => '1.6', + 'Description' => 'This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from Hello, Dolly in the upper right of your admin screen on every page.', + 'Author' => 'Matt Mullenweg', + 'AuthorURI' => 'http://ma.tt/', + 'Title' => 'Hello Dolly', + 'AuthorName' => 'Matt Mullenweg', + ], + 'pressbooks-textbook/pressbooks-textbook.php' => [ 'Name' => 'Pressbooks Textbook', 'Version' => '2.1.2', 'Description' => 'A plugin that extends Pressbooks for textbook authoring', @@ -28,11 +25,11 @@ public function test_filter_plugins() { 'TextDomain' => 'pressbooks-textbook', 'DomainPath' => '/languages', 'Title' => 'Pressbooks Textbook', - 'AuthorName' => 'Brad Payne' - ) - ); + 'AuthorName' => 'Brad Payne', + ], + ]; $filtered_plugins = \Pressbooks\Admin\Plugins\filter_plugins( $plugins ); - $this->assertArrayHasKey('pressbooks-textbook/pressbooks-textbook.php', $filtered_plugins); + $this->assertArrayHasKey( 'pressbooks-textbook/pressbooks-textbook.php', $filtered_plugins ); } } diff --git a/tests/test-analytics.php b/tests/test-analytics.php index 127f8e32fe..5a5a877251 100644 --- a/tests/test-analytics.php +++ b/tests/test-analytics.php @@ -1,40 +1,25 @@ expectOutputRegex( '/<\/p>/' ); \Pressbooks\Admin\Analytics\analytics_settings_section_callback(); } - - /** - * @covers \Pressbooks\Admin\Analytics\analytics_ga_mu_uaid_sanitize - */ public function test_analytics_ga_mu_uaid_sanitize() { $this->assertInternalType( 'string', \Pressbooks\Admin\Analytics\analytics_ga_mu_uaid_sanitize( 'UA-123456-7890' ) ); } - - /** - * @covers \Pressbooks\Admin\Analytics\analytics_ga_mu_site_specific_allowed_sanitize - */ public function test_analytics_ga_mu_site_specific_allowed_sanitize() { $this->assertInternalType( 'int', \Pressbooks\Admin\Analytics\analytics_ga_mu_site_specific_allowed_sanitize( 1 ) ); } - /** - * @covers \Pressbooks\Analytics\print_analytics - */ public function test_print_analytic() { ob_start(); @@ -45,9 +30,6 @@ public function test_print_analytic() { $this->assertContains( 'Analytics', $buffer ); } - /** - * @covers \Pressbooks\Admin\Analytics\print_admin_analytics - */ public function test_print_admin_analytics() { ob_start(); diff --git a/tests/test-book.php b/tests/test-book.php index 18cb23dc65..e08fd20a8e 100644 --- a/tests/test-book.php +++ b/tests/test-book.php @@ -1,56 +1,126 @@ 'test chapter', 'post_type' => 'chapter', 'post_status' => 'publish', 'post_content' => 'some content', - ); + ]; $pid = wp_insert_post( $new_post ); update_post_meta( $pid, 'pb_export', 'on' ); - $this->book_structure = \Pressbooks\Book::getBookStructure(); - $this->page = $this->book_structure['__orphans'][0]; // In __orphans because doesn't belong to a part + return $pid; } - /** - * @covers \Pressbooks\Book::getBookStructure - */ - public function test_returnsExportMetaValue() { - $this->assertTrue( $this->page['export'] ); + + public function test_isBook() { + + $book = new \Pressbooks\Book(); + + switch_to_blog( get_network()->site_id ); + $this->assertFalse( $book::isBook() ); + + $this->_book(); + $this->assertTrue( $book::isBook() ); } - /** - * @covers \Pressbooks\Book::getBookStructure - */ - public function test_returnsCachedExportValue() { - delete_post_meta( $this->page['ID'], 'pb_export' ); - $book_structure = \Pressbooks\Book::getBookStructure(); - $this->page = $book_structure['__orphans'][0]; + public function test_getBookStructure() { + + $book = new \Pressbooks\Book(); - $this->assertTrue( $this->page['export'] ); + // Returns export value + $this->_book(); + $this->createChapter(); + $structure = $book::getBookStructure(); + $page = $structure['__orphans'][0]; // In __orphans because doesn't belong to a part + $this->assertTrue( $page['export'] ); + $this->assertEquals( $structure['front-matter'][0]['post_title'], __( 'Introduction', 'pressbooks' ) ); + $this->assertArrayHasKey( 'part', $structure ); + $this->assertArrayHasKey( 'chapters', $structure['part'][0] ); + $this->assertArrayHasKey( 'back-matter', $structure ); + + // Returns cached export value, with $blog_id as param + global $blog_id; + delete_post_meta( $page['ID'], 'pb_export' ); + $structure = $book::getBookStructure( $blog_id ); + $page = $structure['__orphans'][0]; + $this->assertTrue( $page['export'] ); + + // Returns latest export value no cache + delete_post_meta( $page['ID'], 'pb_export' ); + $book::deleteBookObjectCache(); + $structure = $book::getBookStructure(); + $page = $structure['__orphans'][0]; + $this->assertFalse( $page['export'] ); } - /** - * @covers \Pressbooks\Book::getBookStructure - */ - public function test_returnsLatestExportValueNoCache() { - delete_post_meta( $this->page['ID'], 'pb_export' ); - wp_cache_flush(); - $book_structure = \Pressbooks\Book::getBookStructure(); + public function test_getBookContents() { + + $book = new \Pressbooks\Book(); + + // Returns export value + $this->_book(); + $this->createChapter(); + $contents = $book::getBookContents(); + $page = $contents['__orphans'][0]; // In __orphans because doesn't belong to a part + $this->assertTrue( $page['export'] ); + $this->assertEquals( $contents['front-matter'][0]['post_content'], __( 'This is where you can write your introduction.', 'pressbooks' ) ); + $this->assertArrayHasKey( 'part', $contents ); + $this->assertArrayHasKey( 'chapters', $contents['part'][0] ); + $this->assertArrayHasKey( 'back-matter', $contents ); + + // Returns cached export value + delete_post_meta( $page['ID'], 'pb_export' ); + $contents = $book::getBookContents(); + $page = $contents['__orphans'][0]; + $this->assertTrue( $page['export'] ); + + // Returns latest export value no cache + delete_post_meta( $page['ID'], 'pb_export' ); + $book::deleteBookObjectCache(); + $contents = $book::getBookContents(); + $page = $contents['__orphans'][0]; + $this->assertFalse( $page['export'] ); + } + + public function test_getBookInformation() { + + $book = new \Pressbooks\Book(); + + $this->_book(); + $mp = ( new \Pressbooks\Metadata() )->getMetaPost(); + add_post_meta( $mp->ID, 'pb_about_unlimited', 'Hello world!', true ); + + // Returns texturized pb_about_unlimited value + $info = $book::getBookInformation(); + $this->assertArrayHasKey( 'pb_about_unlimited', $info ); + $this->assertEquals( $info['pb_about_unlimited'], '

        Hello world!

        ' ); + foreach ( $info as $key => $val ) { + $this->assertStringStartsWith( 'pb_', $key ); + } + + // Returns cached pb_about_unlimited value, with $blog_id as param + global $blog_id; + delete_post_meta( $mp->ID, 'pb_about_unlimited' ); + $info = $book::getBookInformation( $blog_id ); + $this->assertArrayHasKey( 'pb_about_unlimited', $info ); + $this->assertEquals( $info['pb_about_unlimited'], '

        Hello world!

        ' ); - $this->assertFalse( $book_structure['__orphans'][0]['export'] ); + // Returns latest pb_about_unlimited value no cache + delete_post_meta( $mp->ID, 'pb_about_unlimited' ); + $book::deleteBookObjectCache(); + $info = $book::getBookInformation(); + $this->assertArrayNotHasKey( 'pb_about_unlimited', $info ); } } diff --git a/tests/test-compatibility.php b/tests/test-compatibility.php index 52ac62ad12..c7a4308f95 100644 --- a/tests/test-compatibility.php +++ b/tests/test-compatibility.php @@ -2,9 +2,6 @@ class CompatibilityTest extends \WP_UnitTestCase { - /** - * @covers \pb_meets_minimum_requirements - */ public function test_pb_meets_minimum_requirements() { $result = \pb_meets_minimum_requirements(); diff --git a/tests/test-container.php b/tests/test-container.php index 69c83996c9..dd1b739517 100644 --- a/tests/test-container.php +++ b/tests/test-container.php @@ -30,12 +30,6 @@ public function tearDown() { parent::tearDown(); } - - /** - * @covers \Pressbooks\Container::init - * @covers \Pressbooks\Container::setPimple - * @covers \Pressbooks\Container::getPimple - */ public function test_initSetGetPimple() { Container::init( new FakePimpleContainer() ); @@ -45,29 +39,31 @@ public function test_initSetGetPimple() { $this->assertTrue( Container::getPimple() instanceof AnotherFakePimpleContainer ); } - - /** - * @covers \Pressbooks\Container::getPimple - */ public function test_getPimpleException() { - + $this->setExpectedException( '\LogicException' ); $p = Container::getPimple(); } - - - /** - * @covers \Pressbooks\Container::get - * @covers \Pressbooks\Container::set - */ public function test_getSet() { Container::init( new FakePimpleContainer() ); - Container::set( 'test1', function () { return 'test1'; } ); - Container::set( 'test2', function () { return 'test2'; }, 'factory' ); - Container::set( 'test3', function () { return 'test3'; }, 'protect' ); + Container::set( + 'test1', function () { + return 'test1'; + } + ); + Container::set( + 'test2', function () { + return 'test2'; + }, 'factory' + ); + Container::set( + 'test3', function () { + return 'test3'; + }, 'protect' + ); $var1 = Container::get( 'test1' ); $var2 = Container::get( 'test2' ); @@ -82,20 +78,12 @@ public function test_getSet() { } - - /** - * @covers \Pressbooks\Container::get - */ public function test_getException() { $this->setExpectedException( '\LogicException' ); $var = Container::get( 'foo' ); } - - /** - * @covers \Pressbooks\Container::set - */ public function test_setException() { $this->setExpectedException( '\LogicException' ); diff --git a/tests/test-customcss.php b/tests/test-customcss.php index 3ec62bf618..fb2e45ee4b 100644 --- a/tests/test-customcss.php +++ b/tests/test-customcss.php @@ -17,33 +17,27 @@ public function setUp() { $this->cc = new \Pressbooks\CustomCss(); } - /** - * @covers \Pressbooks\CustomCss::getCustomCssFolder - */ public function test_getCustomCssFolder() { - $path = $this->cc->getCustomCssFolder(); - $this->assertStringEndsWith( '/custom-css/', $path ); + $path = $this->cc->getCustomCssFolder(); + $this->assertStringEndsWith( '/custom-css/', $path ); } - /** - * @covers \Pressbooks\CustomCss::getBaseTheme - */ public function test_getBaseTheme() { - $input = file_get_contents( PB_PLUGIN_DIR . 'themes-book/pressbooks-book/style.css' ); - $output = $this->cc->getCustomCssFolder() . sanitize_file_name( 'web.css' ); + $input = file_get_contents( PB_PLUGIN_DIR . 'themes-book/pressbooks-book/style.css' ); + $output = $this->cc->getCustomCssFolder() . sanitize_file_name( 'web.css' ); - file_put_contents( $output, $input ); + file_put_contents( $output, $input ); - $web = $this->cc->getBaseTheme( 'web' ); + $web = $this->cc->getBaseTheme( 'web' ); - $this->assertTrue( 'pressbooks-book' == $web ); + $this->assertTrue( 'pressbooks-book' == $web ); - $prince = $this->cc->getBaseTheme( 'prince' ); + $prince = $this->cc->getBaseTheme( 'prince' ); - $this->assertFalse( 'pressbooks-book' == $prince ); + $this->assertFalse( 'pressbooks-book' == $prince ); } diff --git a/tests/test-editor.php b/tests/test-editor.php index 3023876bf4..3e2bcaf565 100644 --- a/tests/test-editor.php +++ b/tests/test-editor.php @@ -4,48 +4,71 @@ class EditorTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\Editor\mce_valid_word_elements - */ public function test_mce_valid_word_elements() { $array = Pressbooks\Editor\mce_valid_word_elements( [] ); $this->assertArrayHasKey( 'paste_word_valid_elements', $array ); - } - /** - * @covers \Pressbooks\Editor\add_languages - */ public function test_add_languages() { $array = Pressbooks\Editor\add_languages( [] ); $this->assertContains( PB_PLUGIN_DIR . 'languages/tinymce.php', $array ); - } - /** - * @covers \Pressbooks\Editor\mce_buttons_2 - */ public function test_mce_buttons_2() { $buttons = Pressbooks\Editor\mce_buttons_2( [ 'formatselect' ] ); $this->assertContains( 'styleselect', $buttons ); - } - /** - * @covers \Pressbooks\Editor\mce_buttons_3 - */ + public function test_mce_buttons_3() { $buttons = Pressbooks\Editor\mce_buttons_3( [] ); $this->assertContains( 'anchor', $buttons ); + } + + public function test_mce_button_scripts() { + + $x = Pressbooks\Editor\mce_button_scripts( [] ); + + $this->assertArrayHasKey( 'table', $x ); + } + + public function test_mce_before_init_insert_formats() { + + $x = Pressbooks\Editor\mce_before_init_insert_formats( [] ); + + $this->assertArrayHasKey( 'style_formats', $x ); + } + + public function test_metadata_manager_default_editor_args() { + + $x = Pressbooks\Editor\metadata_manager_default_editor_args( [] ); + + $this->assertArrayHasKey( 'tinymce', $x ); + } + + public function test_mce_table_editor_options() { + + $x = Pressbooks\Editor\mce_table_editor_options( [] ); + + $this->assertArrayHasKey( 'table_class_list', $x ); + $this->assertArrayHasKey( 'table_cell_class_list', $x ); + $this->assertArrayHasKey( 'table_row_class_list', $x ); + } + + public function test_customize_wp_link_query_args() { + + $x = \Pressbooks\Editor\customize_wp_link_query_args( [ 'post_type' => [ 'post' ] ] ); + $this->assertFalse( in_array( 'post', $x['post_type'] ) ); + $this->assertTrue( in_array( 'chapter', $x['post_type'] ) ); } } diff --git a/tests/test-globaltypography.php b/tests/test-globaltypography.php index e2331ee54d..10c043b046 100644 --- a/tests/test-globaltypography.php +++ b/tests/test-globaltypography.php @@ -18,10 +18,6 @@ public function setUp() { $this->gt = new \Pressbooks\GlobalTypography(); } - - /** - * @covers \Pressbooks\GlobalTypography::getSupportedLanguages - */ public function test_getSupportedLanguages() { $result = $this->gt->getSupportedLanguages(); @@ -33,9 +29,6 @@ public function test_getSupportedLanguages() { $this->assertArrayHasKey( 'he', $result ); } - /** - * @covers \Pressbooks\GlobalTypography::_getRequiredLanguages - */ public function test_getRequiredLanguages() { $result = $this->gt->_getRequiredLanguages(); @@ -43,13 +36,6 @@ public function test_getRequiredLanguages() { $this->assertTrue( is_array( $result ) ); } - /** - * @covers \Pressbooks\GlobalTypography::getThemeFontStacks - * - * @covers \Pressbooks\GlobalTypography::updateGlobalTypographyMixin - * @covers \Pressbooks\GlobalTypography::_sassify - * @covers \Pressbooks\GlobalTypography::_getBookLanguage - */ public function test_getThemeFontStacks() { $this->_book( 'donham' ); // Pick a theme with some built-in $supported_languages @@ -61,9 +47,6 @@ public function test_getThemeFontStacks() { } - /** - * @covers \Pressbooks\GlobalTypography::getThemeSupportedLanguages - */ public function test_getThemeSupportedLanguages() { $this->_book( 'donham' ); // Pick a theme with some built-in $supported_languages @@ -72,11 +55,9 @@ public function test_getThemeSupportedLanguages() { $this->assertTrue( is_array( $supported_languages ) ); } - /** - * @covers \Pressbooks\GlobalTypography::getFonts - */ + public function test_getFonts() { - $result = $this->gt->getFonts( array( 'ko' ) ); + $result = $this->gt->getFonts( [ 'ko' ] ); $this->assertTrue( $result ); $this->assertFileExists( WP_CONTENT_DIR . '/uploads/assets/fonts/NotoSansCJKkr-Regular.otf' ); $this->assertFileExists( WP_CONTENT_DIR . '/uploads/assets/fonts/NotoSansCJKkr-Bold.otf' ); diff --git a/tests/test-htmlawed.php b/tests/test-htmlawed.php index e473b95d4a..837480b38f 100644 --- a/tests/test-htmlawed.php +++ b/tests/test-htmlawed.php @@ -2,14 +2,11 @@ class HtmLawedTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\HtmLawed::filter - */ public function test_filter() { $output = \Pressbooks\HtmLawed::filter( '

        Hello world!' ); $this->assertEquals( '

        Hello world!

        ', $output ); - $output = \Pressbooks\HtmLawed::filter( 'nothing to see', array( 'safe' => 1 ) ); + $output = \Pressbooks\HtmLawed::filter( 'nothing to see', [ 'safe' => 1 ] ); $this->assertEquals( 'nothing to seealert("xss")', $output ); } } diff --git a/tests/test-l10n.php b/tests/test-l10n.php index d6b63b7246..444c624b98 100644 --- a/tests/test-l10n.php +++ b/tests/test-l10n.php @@ -2,9 +2,6 @@ class L10nTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\L10n\get_locale - */ public function test_get_locale() { $locale = \Pressbooks\L10n\get_locale(); @@ -12,10 +9,6 @@ public function test_get_locale() { $this->assertTrue( is_string( $locale ) ); } - - /** - * @covers \Pressbooks\L10n\load_plugin_textdomain - */ public function test_load_plugin_textdomain() { \Pressbooks\L10n\load_plugin_textdomain(); @@ -23,10 +16,6 @@ public function test_load_plugin_textdomain() { $this->assertTrue( true ); } - - /** - * @covers \Pressbooks\L10n\include_core_overrides - */ public function test_include_core_overrides() { $overrides = \Pressbooks\L10n\include_core_overrides(); @@ -35,10 +24,6 @@ public function test_include_core_overrides() { $this->assertArrayHasKey( 'My Sites', $overrides ); } - - /** - * @covers \Pressbooks\L10n\override_core_strings - */ public function test_override_core_strings() { $text = 'My Sites'; @@ -51,10 +36,6 @@ public function test_override_core_strings() { $this->assertNotEquals( $text, $translated ); // 'My Sites' should be 'My Books', 'Mes Livres', ... } - - /** - * @covers \Pressbooks\L10n\set_locale - */ public function test_set_locate() { $this->assertTrue( @@ -62,10 +43,6 @@ public function test_set_locate() { ); } - - /** - * @covers \Pressbooks\L10n\set_root_locale - */ public function test_set_root_locate() { $this->assertTrue( @@ -73,29 +50,18 @@ public function test_set_root_locate() { ); } - - /** - * @covers \Pressbooks\L10n\supported_languages - */ public function test_supported_languages() { $supported_languages = \Pressbooks\L10n\supported_languages(); $this->assertTrue( is_array( $supported_languages ) ); } - - /** - * @covers \Pressbooks\L10n\wplang_codes - */ public function test_wplang_codes() { $wplang_codes = \Pressbooks\L10n\wplang_codes(); $this->assertTrue( is_array( $wplang_codes ) ); } - /** - * @covers \Pressbooks\L10n\romanize - */ public function test_romanize() { $this->assertEquals( \Pressbooks\L10n\romanize( 1 ), 'I' ); @@ -105,10 +71,6 @@ public function test_romanize() { $this->assertEquals( \Pressbooks\L10n\romanize( 1975 ), 'MCMLXXV' ); } - - /** - * @covers \Pressbooks\L10n\install_book_locale - */ public function test_install_book_locale() { // Test for incorrect meta_key @@ -120,16 +82,10 @@ public function test_install_book_locale() { $this->assertEquals( $output, false ); } - /** - * @covers \Pressbooks\L10n\update_user_locale - */ public function test_update_user_locale() { // TODO } - /** - * @covers \Pressbooks\L10n\use_book_locale - */ public function test_use_book_locale() { $this->assertFalse( \Pressbooks\L10n\use_book_locale() ); diff --git a/tests/test-media.php b/tests/test-media.php index 73a33c5e56..6835457fcd 100644 --- a/tests/test-media.php +++ b/tests/test-media.php @@ -2,9 +2,6 @@ class MediaTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\Media\add_mime_types - */ public function test_add_mime_types() { $supportedFileExtensions = [ 'mp4', 'webm', 'ogv', 'ogg', 'mp3', 'aac', 'vorbis' ]; @@ -22,10 +19,6 @@ public function test_add_mime_types() { $this->assertArrayNotHasKey( 'baz', $mimes ); } - - /** - * @covers \Pressbooks\Media\is_valid_media - */ public function test_is_valid_media() { $goodFiles = [ @@ -48,7 +41,7 @@ public function test_is_valid_media() { 'image.jpg', 'image.jpeg', 'foo.bar', - '/etc/hosts' + '/etc/hosts', ]; foreach ( $badFiles as $file ) { @@ -58,8 +51,6 @@ public function test_is_valid_media() { /** - * @covers \Pressbooks\Media\force_wrap_images - * * @see https://github.com/pressbooks/pressbooks/issues/263 */ public function test_force_wrap_images() { @@ -83,14 +74,11 @@ public function test_force_wrap_images() { $this->assertStringEndsWith( '
        ', $converted ); } - /** - * @covers \Pressbooks\Media\force_attach_media - */ public function test_force_attach_media() { global $post_ID; $post_ID = '42'; - $params = array(); + $params = []; $return = \Pressbooks\Media\force_attach_media( $params ); $this->assertEquals( $return['post_id'], 42 ); } diff --git a/tests/test-metaboxes.php b/tests/test-metaboxes.php index 4d9e8be35c..4eba32b8bd 100644 --- a/tests/test-metaboxes.php +++ b/tests/test-metaboxes.php @@ -1,13 +1,10 @@ assertEquals( $option, $title ); } - /** - * @covers \Pressbooks\Admin\Metaboxes\add_meta_boxes - */ public function test_update_font_stacks() { global $wp_meta_boxes; diff --git a/tests/test-metadata.php b/tests/test-metadata.php index 4542fc8908..7ad962a3e1 100644 --- a/tests/test-metadata.php +++ b/tests/test-metadata.php @@ -2,9 +2,6 @@ class MetadataTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\Metadata::getJsonMetadata - */ public function test_getJsonMetadata() { $result = \Pressbooks\Metadata::getJsonMetadata(); $this->assertEquals( $result, '{"pb_title":"Test Blog","pb_author":"admin","pb_cover_image":"http:\/\/example.org\/wp-content\/plugins\/pressbooks\/assets\/dist\/images\/default-book-cover.jpg"}' ); diff --git a/tests/test-modules-export.php b/tests/test-modules-export.php index 56a91cc175..e4e6705806 100644 --- a/tests/test-modules-export.php +++ b/tests/test-modules-export.php @@ -32,10 +32,6 @@ public function setUp() { $this->export = new \ExportMock(); } - - /** - * @covers \Pressbooks\Modules\Export\Export::getExportStylePath - */ public function test_getExportStylePath() { $this->_book(); @@ -61,19 +57,11 @@ public function test_getExportStylePath() { $this->assertFalse( $path ); } + // public function test_getGlobalTypographyMixinPath() { + // // TODO: Testing this as-is triggers updateGlobalTypographyMixin, generates _mixins.css, generates _global-font-stack.scss... Code needs to be decoupled? + // $this->markTestIncomplete(); + // } -// /** -// * @covers \Pressbooks\Modules\Export\Export::getGlobalTypographyMixinPath -// */ -// public function test_getGlobalTypographyMixinPath() { -// // TODO: Testing this as-is triggers updateGlobalTypographyMixin, generates _mixins.css, generates _global-font-stack.scss... Code needs to be decoupled? -// $this->markTestIncomplete(); -// } - - - /** - * @covers \Pressbooks\Modules\Export\Export::getExportScriptPath - */ public function test_getExportScriptPath() { $this->_book(); @@ -92,7 +80,7 @@ public function test_getExportScriptPath() { $opt = get_option( 'pressbooks_theme_options_pdf' ); $opt['pdf_romanize_parts'] = 0; - update_option( 'pressbooks_theme_options_pdf', $opt); + update_option( 'pressbooks_theme_options_pdf', $opt ); $path = $this->export->getExportScriptPath( 'epub' ); $this->assertFalse( $path ); @@ -101,7 +89,7 @@ public function test_getExportScriptPath() { $this->assertStringEndsWith( '/export/prince/script.js', $path ); $opt['pdf_romanize_parts'] = 1; - update_option( 'pressbooks_theme_options_pdf', $opt); + update_option( 'pressbooks_theme_options_pdf', $opt ); $path = $this->export->getExportScriptPath( 'prince' ); $this->assertStringEndsWith( '/export/prince/script-romanize.js', $path ); @@ -110,29 +98,17 @@ public function test_getExportScriptPath() { $this->assertFalse( $path ); } - - /** - * @covers \Pressbooks\Modules\Export\Export::isParsingSubsections - */ public function test_isParsingSubsections() { $val = $this->export->isParsingSubsections(); $this->assertInternalType( 'bool', $val ); } + // public function test_logError() { + // // TODO: Testing this as-is would send emails, writes to error log... Need to be refactored. + // $this->markTestIncomplete(); + // } -// /** -// * @covers \Pressbooks\Modules\Export\Export::logError -// */ -// public function test_logError() { -// // TODO: Testing this as-is would send emails, writes to error log... Need to be refactored. -// $this->markTestIncomplete(); -// } - - - /** - * @covers \Pressbooks\Modules\Export\Export::createTmpFile - */ public function test_createTmpFile() { $file = $this->export->createTmpFile(); @@ -142,10 +118,6 @@ public function test_createTmpFile() { $this->assertEquals( 'Hello world!', file_get_contents( $file ) ); } - - /** - * @covers \Pressbooks\Modules\Export\Export::timestampedFileName - */ public function test_timestampedFileName() { $this->_book(); @@ -162,11 +134,6 @@ public function test_timestampedFileName() { $this->assertNotContains( '+', $file ); } - - /** - * @covers \Pressbooks\Modules\Export\Export::nonce - * @covers \Pressbooks\Modules\Export\Export::verifyNonce - */ public function test_nonce_AND_verifyNonce() { if ( ! defined( 'NONCE_KEY' ) ) { @@ -189,10 +156,6 @@ public function test_nonce_AND_verifyNonce() { $this->assertFalse( $this->export->verifyNonce( $time3, $nonce3 ) ); } - - /** - * @covers \Pressbooks\Modules\Export\Export::mimeType - */ function test_mimeType() { $i = $this->export; @@ -200,10 +163,6 @@ function test_mimeType() { $this->assertStringStartsWith( 'image/png', $mime ); } - - /** - * @covers \Pressbooks\Modules\Export\Export::getExportFolder - */ function test_getExportFolder() { $this->_book(); diff --git a/tests/test-options.php b/tests/test-options.php index 5a61549ee9..a417d5f876 100644 --- a/tests/test-options.php +++ b/tests/test-options.php @@ -51,14 +51,14 @@ function init() { add_settings_section( $_section, '', - array( $this, 'display' ), + [ $this, 'display' ], $_page ); register_setting( $_page, $_option, - array( $this, 'sanitize' ) + [ $this, 'sanitize' ] ); } @@ -69,7 +69,8 @@ function display() { echo '

        ' . esc_attr__( 'Mock settings.', 'pressbooks' ) . '

        '; } - function render() { ?> + function render() { + ?>

        getTitle(); ?>

        @@ -103,19 +104,20 @@ static function getTitle() { } static function getDefaults() { - return array( + return [ 'option_bool' => 1, 'option_string' => 'foo', 'option_int' => 42, 'option_float' => 2.5, 'option_predef' => 'European Swallow', - ); + ]; } /** * Filter the array of default values for this set of options * * @param array $defaults The input array of default values. + * * @return array $defaults */ static function filterDefaults( $defaults ) { @@ -128,7 +130,7 @@ static function filterDefaults( $defaults ) { * @return array $options */ static function getBooleanOptions() { - return array( 'option_bool' ); + return [ 'option_bool' ]; } /** @@ -137,7 +139,7 @@ static function getBooleanOptions() { * @return array $options */ static function getStringOptions() { - return array( 'option_string' ); + return [ 'option_string' ]; } /** @@ -146,7 +148,7 @@ static function getStringOptions() { * @return array $options */ static function getIntegerOptions() { - return array( 'option_int' ); + return [ 'option_int' ]; } /** @@ -155,7 +157,7 @@ static function getIntegerOptions() { * @return array $options */ static function getFloatOptions() { - return array( 'option_float' ); + return [ 'option_float' ]; } /** @@ -164,7 +166,7 @@ static function getFloatOptions() { * @return array $options */ static function getPredefinedOptions() { - return array( 'option_predef' ); + return [ 'option_predef' ]; } } @@ -182,70 +184,69 @@ class OptionsTest extends \WP_UnitTestCase { */ public function setUp() { parent::setUp(); - $this->options = new \OptionsMock( array( - 'option_bool' => '1', - 'option_string' => 'foo', - 'option_int' => '42', - 'option_float' => '2.5', - 'option_predef' => 'European Swallow', - ) ); + $this->options = new \OptionsMock( + [ + 'option_bool' => '1', + 'option_string' => 'foo', + 'option_int' => '42', + 'option_float' => '2.5', + 'option_predef' => 'European Swallow', + ] + ); } - /** - * @covers \Pressbooks\Options::sanitize - */ public function test_sanitize() { // Test empty boolean. - $input = array(); + $input = []; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_bool', $result ); $this->assertEquals( $result['option_bool'], 0 ); // Test null boolean. - $input = array( + $input = [ 'option_bool' => null, - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_bool', $result ); $this->assertEquals( $result['option_bool'], 0 ); // Test true boolean. - $input = array( + $input = [ 'option_bool' => '1', - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_bool', $result ); $this->assertEquals( $result['option_bool'], 1 ); // Test string. - $input = array( + $input = [ 'option_string' => 'String that needs sanitizing.', - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_string', $result ); $this->assertEquals( $result['option_string'], 'String that needs sanitizing.' ); // Test integer. - $input = array( + $input = [ 'option_int' => '42', - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_int', $result ); $this->assertEquals( $result['option_int'], 42 ); // Test float. - $input = array( + $input = [ 'option_float' => '1.5', - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_float', $result ); $this->assertEquals( $result['option_float'], 1.5 ); // Test predefined. - $input = array( + $input = [ 'option_predef' => 'European Swallow', - ); + ]; $result = $this->options->sanitize( $input ); $this->assertArrayHasKey( 'option_predef', $result ); $this->assertEquals( $result['option_predef'], 'European Swallow' ); diff --git a/tests/test-posttype.php b/tests/test-posttype.php index 8ce5600795..485f10d936 100644 --- a/tests/test-posttype.php +++ b/tests/test-posttype.php @@ -2,16 +2,15 @@ class PostTypeTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\PostType\add_posttypes_to_hypothesis - */ function test_add_posttypes_to_hypothesis() { - $posttypes = \Pressbooks\PostType\add_posttypes_to_hypothesis( array( - 'post' => 'posts', - 'page' => 'pages', - ) ); - $this->assertEquals( false, in_array( 'posts' , $posttypes ) ); - $this->assertTrue( array_key_exists( 'chapter' , $posttypes ) ); + $posttypes = \Pressbooks\PostType\add_posttypes_to_hypothesis( + [ + 'post' => 'posts', + 'page' => 'pages', + ] + ); + $this->assertEquals( false, in_array( 'posts', $posttypes ) ); + $this->assertTrue( array_key_exists( 'chapter', $posttypes ) ); $this->assertEquals( 'chapters', $posttypes['chapter'] ); } diff --git a/tests/test-pressbooks.php b/tests/test-pressbooks.php index 11bc405ace..0f0f855c33 100644 --- a/tests/test-pressbooks.php +++ b/tests/test-pressbooks.php @@ -17,19 +17,13 @@ public function setUp() { $this->pb = new \Pressbooks\Pressbooks(); } - /** - * @covers \Pressbooks\Pressbooks::allowedBookThemes - */ public function test_allowedBookThemes() { - $result = $this->pb->allowedBookThemes( array( 'pressbooks-mcluhan' ) ); + $result = $this->pb->allowedBookThemes( [ 'pressbooks-mcluhan' ] ); $this->assertTrue( is_array( $result ) ); } - /** - * @covers \Pressbooks\Pressbooks::allowedRootThemes - */ public function test_allowedRootThemes() { - $result = $this->pb->allowedRootThemes( array( 'pressbooks-librarian' ) ); + $result = $this->pb->allowedRootThemes( [ 'pressbooks-librarian' ] ); $this->assertTrue( is_array( $result ) ); } } diff --git a/tests/test-registration.php b/tests/test-registration.php index 9a1cbc3072..5a70301687 100644 --- a/tests/test-registration.php +++ b/tests/test-registration.php @@ -14,36 +14,27 @@ function tearDown() { remove_filter( 'gettext', '\Pressbooks\Registration\custom_signup_text' ); } - /** - * @covers \Pressbooks\Registration\custom_signup_text - */ public function test_custom_signup_text() { $output = __( 'Create Site', 'pressbooks' ); $this->assertEquals( 'Create Book', $output ); } - /** - * @covers \Pressbooks\Registration\add_password_field - */ public function test_add_password_field() { // Test for field label in output - + $e = new WP_Error(); $this->expectOutputRegex( '/<\/label>/' ); \Pressbooks\Registration\add_password_field( $e ); } - /** - * @covers \Pressbooks\Registration\validate_passwords - */ public function test_validate_passwords() { global $_POST; // Test for correct stage - $content = array( 'errors' => new WP_Error() ); + $content = [ 'errors' => new WP_Error() ]; $_POST['stage'] = ''; \Pressbooks\Registration\validate_passwords( $content ); @@ -52,70 +43,57 @@ public function test_validate_passwords() { // Test for empty password field - $content = array( 'errors' => new WP_Error() ); + $content = [ 'errors' => new WP_Error() ]; $_POST['stage'] = 'validate-user-signup'; // Validation stage $_POST['password_1'] = ''; // Empty password $_POST['password_2'] = 'barrel aquiline abolish belabour'; // Legitimate password - + \Pressbooks\Registration\validate_passwords( $content ); - + $this->assertEquals( 'You have to enter a password.', $content['errors']->get_error_message( 'password_1' ) ); // Test for password mismatch - $content = array( 'errors' => new WP_Error() ); + $content = [ 'errors' => new WP_Error() ]; $_POST['stage'] = 'validate-user-signup'; // Validation stage $_POST['password_1'] = 'colloquy glint tendril choler'; // Legitimate password $_POST['password_2'] = 'barrel aquiline abolish belabour'; // Legitimate password that doesn't match - + \Pressbooks\Registration\validate_passwords( $content ); - + $this->assertEquals( 'Passwords do not match.', $content['errors']->get_error_message( 'password_1' ) ); } - /** - * @covers \Pressbooks\Registration\validate_passwords - */ public function test_add_temporary_password() { global $_POST; - + // Test for base64-encoded password key in $meta array, matching input password - + $_POST['password_1'] = 'colloquy glint tendril choler'; - - $meta = \Pressbooks\Registration\add_temporary_password( array() ); + + $meta = \Pressbooks\Registration\add_temporary_password( [] ); $this->assertEquals( 'colloquy glint tendril choler', base64_decode( $meta['password'] ) ); - + // Test for absence of password key in $meta array when no password is provided - + unset( $_POST['password_1'] ); - - $meta = \Pressbooks\Registration\add_temporary_password( array() ); + + $meta = \Pressbooks\Registration\add_temporary_password( [] ); $this->assertArrayNotHasKey( 'password', $meta ); } - - /** - * @covers \Pressbooks\Registration\add_hidden_password_field - */ + public function test_add_hidden_password_field() { global $_POST; - + // Test for password field in output when password is supplied - + $_POST['password_1'] = 'colloquy glint tendril choler'; - + $this->expectOutputRegex( '/()/' ); - \Pressbooks\Registration\add_hidden_password_field( array() ); + \Pressbooks\Registration\add_hidden_password_field( [] ); } -// /** -// * @covers \Pressbooks\Registration\override_password_generation -// */ -// public function test_override_password_generation() { -// $this->markTestIncomplete(); -// } - } diff --git a/tests/test-remote-get-retry.php b/tests/test-remote-get-retry.php index bdcba3bd04..8a794d9a5c 100644 --- a/tests/test-remote-get-retry.php +++ b/tests/test-remote-get-retry.php @@ -2,40 +2,40 @@ class Remote_Get_RetryTest extends \WP_UnitTestCase { - public function setUp(){ - parent::setUp(); + public function setUp() { + parent::setUp(); - $i = 0; - $mockedResponses = [ - ['response' => ['code' => 400] ], - ['response' => ['code' => 400] ], - ['response' => ['code' => 200] ], - ]; + $i = 0; + $mockedResponses = [ + [ 'response' => [ 'code' => 400 ] ], + [ 'response' => [ 'code' => 400 ] ], + [ 'response' => [ 'code' => 200 ] ], + ]; - add_filter( 'pre_http_request', function ($preempt, $request, $url) use (&$i, $mockedResponses){ - $preempt = $mockedResponses[$i]; - $i++; - return $preempt; - }, 1, 3); + add_filter( 'pre_http_request', function ( $preempt, $request, $url ) use ( &$i, $mockedResponses ) { + $preempt = $mockedResponses[ $i ]; + $i++; + return $preempt; + }, 1, 3); - // disable sleep to speed up tests - add_filter( 'pressbooks_remote_get_retry_wait_time', function($sleep) { - return 0; - }); - } + // disable sleep to speed up tests + add_filter( 'pressbooks_remote_get_retry_wait_time', function( $sleep ) { + return 0; + }); + } - public function test_remote_get_retry() { + public function test_remote_get_retry() { - $response = \Pressbooks\Utility\remote_get_retry('http://example.com', []); + $response = \Pressbooks\Utility\remote_get_retry( 'http://example.com', [] ); - $this->assertEquals($response['response']['code'], 200); - } + $this->assertEquals( $response['response']['code'], 200 ); + } - public function test_remote_get_single_retry() { + public function test_remote_get_single_retry() { - $response = \Pressbooks\Utility\remote_get_retry('http://example.com', [], 1); + $response = \Pressbooks\Utility\remote_get_retry( 'http://example.com', [], 1 ); - $this->assertEquals($response['response']['code'], 400); - } + $this->assertEquals( $response['response']['code'], 400 ); + } } diff --git a/tests/test-sanitize.php b/tests/test-sanitize.php index a311208b42..e0e43dc032 100644 --- a/tests/test-sanitize.php +++ b/tests/test-sanitize.php @@ -2,10 +2,6 @@ class SanitizeTest extends \WP_UnitTestCase { - - /** - * @covers \Pressbooks\Sanitize\html5_to_xhtml11 - */ public function test_html5_to_xhtml11() { $html = '
        Foo

        Hello!

        Bar'; @@ -16,10 +12,6 @@ public function test_html5_to_xhtml11() { ); } - - /** - * @covers \Pressbooks\Sanitize\html5_to_epub3 - */ public function test_html5_to_epub3() { $html = '
        Foo

        Hello!

        Bar'; @@ -30,24 +22,16 @@ public function test_html5_to_epub3() { ); } - - /** - * @covers \Pressbooks\Sanitize\fix_audio_shortcode - */ public function test_fix_audio_shortcode() { \Pressbooks\Sanitize\fix_audio_shortcode(); $this->assertTrue( has_filter( 'wp_audio_shortcode' ) ); // Verify that style attribute is empty. - $var = wp_audio_shortcode( array( 'src' => 'http://foo/audio.mp3' ) ); + $var = wp_audio_shortcode( [ 'src' => 'http://foo/audio.mp3' ] ); $this->assertFalse( strpos( $var, 'style=' ) ); } - - /** - * @covers \Pressbooks\Sanitize\sanitize_xml_attribute - */ public function test_sanitize_xml_attribute() { $var = 'Hello-World!'; @@ -60,18 +44,14 @@ public function test_sanitize_xml_attribute() { $this->assertEquals( 'test', \Pressbooks\Sanitize\sanitize_xml_attribute( $var ) ); } - - /** - * @covers \Pressbooks\Sanitize\sanitize_xml_id - */ public function test_sanitize_xml_id() { - $var = "Hello-World!"; + $var = 'Hello-World!'; $test = $this->_generateControlCharacters() . $var; $test = \Pressbooks\Sanitize\sanitize_xml_id( $test ); $this->assertEquals( 'Hello-World', $test ); - $var = " Héllö Wôrld! "; + $var = ' Héllö Wôrld! '; $test = \Pressbooks\Sanitize\sanitize_xml_id( $var ); $this->assertEquals( 'HelloWorld', $test ); @@ -79,47 +59,39 @@ public function test_sanitize_xml_id() { $test = \Pressbooks\Sanitize\sanitize_xml_id( $var ); $this->assertStringStartsWith( 'slug-123', $test ); - $var = "こんにちは世界!"; + $var = 'こんにちは世界!'; $test = \Pressbooks\Sanitize\sanitize_xml_id( $var ); $this->assertStringStartsWith( 'slug-', $test ); } - - /** - * @covers \Pressbooks\Sanitize\remove_control_characters - */ public function test_remove_control_characters() { - $var = "Hello-World!"; + $var = 'Hello-World!'; $test = $this->_generateControlCharacters() . $var; $test = \Pressbooks\Sanitize\remove_control_characters( $test ); $this->assertEquals( 12, strlen( $test ) ); - $var = "Héllö Wôrld!"; + $var = 'Héllö Wôrld!'; $test = \Pressbooks\Sanitize\remove_control_characters( $var ); $this->assertEquals( 12, mb_strlen( $test, 'UTF-8' ) ); - $var = "こんにちは世界!"; + $var = 'こんにちは世界!'; $test = \Pressbooks\Sanitize\remove_control_characters( $var ); $this->assertEquals( 8, mb_strlen( $test, 'UTF-8' ) ); } - - /** - * @covers \Pressbooks\Sanitize\force_ascii - */ public function test_force_ascii() { - $var = "Hello-World!"; + $var = 'Hello-World!'; $test = $this->_generateControlCharacters() . $var; $test = \Pressbooks\Sanitize\force_ascii( $test ); $this->assertEquals( 12, strlen( $test ) ); - $var = "Héllö Wôrld!"; + $var = 'Héllö Wôrld!'; $test = \Pressbooks\Sanitize\force_ascii( $var ); $this->assertEquals( 9, strlen( $test ) ); - $var = "こんにちは世界!"; + $var = 'こんにちは世界!'; $test = \Pressbooks\Sanitize\force_ascii( $var ); $this->assertEquals( 1, strlen( $test ) ); } @@ -133,17 +105,13 @@ public function test_force_ascii() { private function _generateControlCharacters() { $controlCharacters = chr( 127 ); - for ( $i = 0; $i < 32; ++ $i ) { + for ( $i = 0; $i < 32; ++$i ) { $controlCharacters .= chr( $i ); } return $controlCharacters; } - - /** - * @covers \Pressbooks\Sanitize\decode - */ public function test_decode() { $test = '012345&6789'; @@ -155,10 +123,6 @@ public function test_decode() { $this->assertEquals( '012345&6789', $test ); } - - /** - * @covers \Pressbooks\Sanitize\strip_br - */ public function test_strip_br() { $test = 'Hello
        World!'; @@ -178,10 +142,6 @@ public function test_strip_br() { $this->assertEquals( 'Hello World!', $test ); } - - /** - * @covers \Pressbooks\Sanitize\filter_title - */ public function test_filter_title() { // Acceptable Tags:
        , with class, , and . @@ -195,10 +155,6 @@ public function test_filter_title() { $this->assertEquals( 'FoobarFoobaz', $test ); } - - /** - * @covers \Pressbooks\Sanitize\canonicalize_url - */ public function test_canonicalize_url() { $url = 'pressbooks.com/'; @@ -220,10 +176,6 @@ public function test_canonicalize_url() { $this->assertEquals( $url, \Pressbooks\Sanitize\canonicalize_url( $url ) ); } - - /** - * @covers \Pressbooks\Sanitize\maybe_https - */ public function test_maybe_https() { if ( isset( $_SERVER['HTTPS'] ) ) { @@ -250,9 +202,20 @@ public function test_maybe_https() { $url = \Pressbooks\Sanitize\maybe_https( $url ); $this->assertEquals( 'https://http.org', $url ); - if ( isset( $old ) ) $_SERVER['HTTPS'] = $old; - else unset( $_SERVER['HTTPS'] ); + if ( isset( $old ) ) { + $_SERVER['HTTPS'] = $old; + } else { + unset( $_SERVER['HTTPS'] ); + } } + public function test_allow_post_content() { + + global $allowedposttags; + + \Pressbooks\Sanitize\allow_post_content(); + + $this->assertTrue( $allowedposttags['h1']['xml:lang'] ); + } } diff --git a/tests/test-sass.php b/tests/test-sass.php index 85cc77e006..f054b343ae 100644 --- a/tests/test-sass.php +++ b/tests/test-sass.php @@ -4,7 +4,7 @@ class SassTest extends \WP_UnitTestCase { use utilsTrait; - /** + /** * @var \Pressbooks\Sass() */ protected $sass; @@ -19,39 +19,30 @@ public function setUp() { } - /** - * @covers \Pressbooks\Sass::getStringsToLocalize - */ - public function test_getStringsToLocalize() { + public function test_getStringsToLocalize() { - $result = $this->sass->getStringsToLocalize(); + $result = $this->sass->getStringsToLocalize(); - $this->assertTrue( is_array( $result ) ); + $this->assertTrue( is_array( $result ) ); - $this->assertArrayHasKey( 'chapter', $result ); + $this->assertArrayHasKey( 'chapter', $result ); - $this->assertEquals( 'chapter', strtolower( $result['chapter'] ) ); + $this->assertEquals( 'chapter', strtolower( $result['chapter'] ) ); - } + } - /** - * @covers \Pressbooks\Sass::prependLocalizedVars - */ - public function test_prependLocalizedVars() { + public function test_prependLocalizedVars() { - $scss = '/* Silence is golden. */'; + $scss = '/* Silence is golden. */'; - $result = $this->sass->prependLocalizedVars( $scss ); + $result = $this->sass->prependLocalizedVars( $scss ); - $this->assertContains( $scss, $result ); + $this->assertContains( $scss, $result ); - $this->assertContains( "\$chapter: 'Chapter';", $result ); + $this->assertContains( "\$chapter: 'Chapter';", $result ); - } + } - /** - * @covers \Pressbooks\Sass::parseVariables - */ public function test_parseVariables() { $scss = '$red: #d4002d !default; $font-size: 14pt;'; @@ -64,17 +55,11 @@ public function test_parseVariables() { $this->assertEquals( $vars['font-size'], '14pt' ); } - /** - * @covers \Pressbooks\Sass::applyOverrides - */ public function test_applyOverrides() { $result = $this->sass->applyOverrides( '// SCSS.', '// Override.' ); $this->assertTrue( strpos( $result, '// SCSS.' ) === 0 ); } - /** - * @covers \Pressbooks\Sass::updateWebBookStyleSheet - */ public function test_updateWebBookStyleSheet() { $this->_book( 'donham' ); // Pick a theme with some built-in $supported_languages @@ -87,10 +72,6 @@ public function test_updateWebBookStyleSheet() { $this->assertNotEmpty( file_get_contents( $file ) ); } - - /** - * @covers \Pressbooks\Sass::fixWebFonts - */ public function test_fixWebFonts() { $css = '@font-face { font-family: "Bergamot Ornaments"; src: url(themes-book/pressbooks-book/fonts/Bergamot-Ornaments.ttf) format("truetype"); font-weight: normal; font-style: normal; }'; diff --git a/tests/test-searchandreplace.php b/tests/test-searchandreplace.php index fef9e6b19c..674757975d 100644 --- a/tests/test-searchandreplace.php +++ b/tests/test-searchandreplace.php @@ -16,17 +16,13 @@ public function setUp() { $this->result = new \Pressbooks\Modules\SearchAndReplace\Result(); } - - /** - * @covers \Pressbooks\Modules\SearchAndReplace\Result::single_line - */ - public function test_single_line() { + public function test_singleLine() { $this->result->search_plain = "line\rbreak"; - $this->assertEquals( $this->result->single_line(), false ); + $this->assertEquals( $this->result->singleLine(), false ); $this->result->search_plain = "line\nbreak"; - $this->assertEquals( $this->result->single_line(), false ); - $this->result->search_plain = "no line break"; - $this->assertEquals( $this->result->single_line(), true ); + $this->assertEquals( $this->result->singleLine(), false ); + $this->result->search_plain = 'no line break'; + $this->assertEquals( $this->result->singleLine(), true ); } } diff --git a/tests/test-shortcodes-footnotes-footnotes.php b/tests/test-shortcodes-footnotes-footnotes.php index daca1494dd..bdb7f5135e 100644 --- a/tests/test-shortcodes-footnotes-footnotes.php +++ b/tests/test-shortcodes-footnotes-footnotes.php @@ -18,15 +18,11 @@ public function setUp() { parent::setUp(); $this->fn = $this->getMockBuilder( '\Pressbooks\Shortcodes\Footnotes\footnotes' ) - ->setMethods( null )// pass null to setMethods() to avoid mocking any method - ->disableOriginalConstructor()// disable private constructor - ->getMock(); + ->setMethods( null )// pass null to setMethods() to avoid mocking any method + ->disableOriginalConstructor()// disable private constructor + ->getMock(); } - - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::getInstance - */ public function test_getInstance() { $val = $this->fn->getInstance(); @@ -34,10 +30,6 @@ public function test_getInstance() { $this->assertTrue( $val instanceof \Pressbooks\Shortcodes\Footnotes\Footnotes ); } - - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::shortcodeHandler - */ public function test_shortcodeHandler_numbered() { global $id; @@ -54,19 +46,15 @@ public function test_shortcodeHandler_numbered() { $this->assertContains( '#footnote-1-3', $content ); - $this->assertEmpty( $this->fn->shortcodeHandler( [ ] ) ); + $this->assertEmpty( $this->fn->shortcodeHandler( [] ) ); } - - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::shortcodeHandler - */ public function test_shortcodeHandler_notNumbered() { global $id; $id = 999; - $content = $this->fn->shortcodeHandler( [ 'numbered' => 'no', ], 'Hello world!' ); + $content = $this->fn->shortcodeHandler( [ 'numbered' => 'no' ], 'Hello world!' ); $this->assertContains( '[*]', $content ); $content = $this->fn->shortcodeHandler( [ 'symbol' => '!' ], 'Hello again world!' ); @@ -79,9 +67,6 @@ public function test_shortcodeHandler_notNumbered() { } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::footnoteContent - */ public function test_footnoteContent_numbered() { global $id; @@ -89,8 +74,8 @@ public function test_footnoteContent_numbered() { // First, add some footnotes $_ = $this->fn->shortcodeHandler( [ 'numbered' => 'yes' ], 'First.' ); - $_ = $this->fn->shortcodeHandler( [ ], 'Second.' ); - $_ = $this->fn->shortcodeHandler( [ ], 'Third.' ); + $_ = $this->fn->shortcodeHandler( [], 'Second.' ); + $_ = $this->fn->shortcodeHandler( [], 'Third.' ); $content = $this->fn->footnoteContent( 'Hello World' ); @@ -102,9 +87,6 @@ public function test_footnoteContent_numbered() { } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::footnoteContent - */ public function test_footnoteContent_notNumbered() { global $id; @@ -112,8 +94,8 @@ public function test_footnoteContent_notNumbered() { // First, add some footnotes $_ = $this->fn->shortcodeHandler( [ 'numbered' => 'no' ], 'First.' ); - $_ = $this->fn->shortcodeHandler( [ ], 'Second.' ); - $_ = $this->fn->shortcodeHandler( [ ], 'Third.' ); + $_ = $this->fn->shortcodeHandler( [], 'Second.' ); + $_ = $this->fn->shortcodeHandler( [], 'Third.' ); $content = $this->fn->footnoteContent( 'Hello World' ); @@ -125,9 +107,6 @@ public function test_footnoteContent_notNumbered() { } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::myCustomQuicktags - */ public function test_myCustomQuicktags() { $this->fn->myCustomQuicktags(); @@ -136,31 +115,22 @@ public function test_myCustomQuicktags() { } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::registerFootnoteButtons - */ public function test_registerFootnoteButtons() { - $buttons = $this->fn->registerFootnoteButtons( [ ] ); + $buttons = $this->fn->registerFootnoteButtons( [] ); $this->assertNotEmpty( $buttons ); } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::addFootnotePlugin - */ public function test_addFootnotePlugin() { - $val = $this->fn->addFootnotePlugin( [ ] ); + $val = $this->fn->addFootnotePlugin( [] ); $this->assertNotEmpty( $val ); } - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::ajaxFailure - */ public function test_ajaxFailure() { $this->_fakeAjax(); @@ -172,10 +142,6 @@ public function test_ajaxFailure() { $this->assertContains( 'foobar', $buffer ); } - - /** - * @covers \Pressbooks\Shortcodes\Footnotes\Footnotes::convertWordFootnotes - */ public function test_convertWordFootnotes() { $this->_fakeAjax(); @@ -189,7 +155,7 @@ public function test_convertWordFootnotes() { // Test is json - $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + $user_id = $this->factory->user->create( [ 'role' => 'administrator' ] ); wp_set_current_user( $user_id ); $_REQUEST['_ajax_nonce'] = wp_create_nonce( 'pb-footnote-convert' ); $_POST['content'] = 'Hello world!'; diff --git a/tests/test-shortcodes-generics.php b/tests/test-shortcodes-generics.php index d240185cbe..bcb304d50d 100644 --- a/tests/test-shortcodes-generics.php +++ b/tests/test-shortcodes-generics.php @@ -22,9 +22,6 @@ public function setUp() { ->getMock(); } - /** - * @covers \Pressbooks\Shortcodes\Generics\Generics::getInstance() - */ public function test_getInstance() { $val = $this->generics->getInstance(); @@ -32,9 +29,6 @@ public function test_getInstance() { } - /** - * @covers \Pressbooks\Shortcodes\Generics\Generics::shortcodeHandler - */ public function test_shortcodeHandler() { // Test a straightforward tag. diff --git a/tests/test-shortcodes-wikipublisher-glyphs.php b/tests/test-shortcodes-wikipublisher-glyphs.php index 12621f708b..ee66b4ae8f 100644 --- a/tests/test-shortcodes-wikipublisher-glyphs.php +++ b/tests/test-shortcodes-wikipublisher-glyphs.php @@ -16,19 +16,14 @@ public function setUp() { parent::setUp(); $this->glyphs = $this->getMockBuilder( '\Pressbooks\Shortcodes\Wikipublisher\Glyphs' ) - ->setMethods( null )// pass null to setMethods() to avoid mocking any method - ->disableOriginalConstructor()// disable private constructor - ->getMock(); + ->setMethods( null )// pass null to setMethods() to avoid mocking any method + ->disableOriginalConstructor()// disable private constructor + ->getMock(); } + public function test_langShortcode_grk() { - /** - * @covers \Pressbooks\Shortcodes\Wikipublisher\Glyphs::lang_shortcode - * @covers \Pressbooks\Shortcodes\Wikipublisher\Glyphs::greek - */ - public function test_lang_shortcode_grk() { - - $content = $this->glyphs->lang_shortcode( + $content = $this->glyphs->langShortcode( [ 'lang' => 'grc' ], 'aeiou' ); @@ -36,7 +31,7 @@ public function test_lang_shortcode_grk() { $this->assertContains( 'assertContains( 'αειου', $content ); - $content = $this->glyphs->lang_shortcode( + $content = $this->glyphs->langShortcode( [ 'lang' => 'ell' ], 'aeiou' ); @@ -45,14 +40,9 @@ public function test_lang_shortcode_grk() { $this->assertContains( 'αειου', $content ); } + public function test_langShortcode_he() { - /** - * @covers \Pressbooks\Shortcodes\Wikipublisher\Glyphs::lang_shortcode - * @covers \Pressbooks\Shortcodes\Wikipublisher\Glyphs::hebrew - */ - public function test_lang_shortcode_he() { - - $content = $this->glyphs->lang_shortcode( + $content = $this->glyphs->langShortcode( [ 'lang' => 'hbo' ], 'aeiou' ); @@ -61,13 +51,9 @@ public function test_lang_shortcode_he() { $this->assertContains( 'ִֵַֹֻ', $content ); } + public function test_langShortcode_bad() { - /** - * @covers \Pressbooks\Shortcodes\Wikipublisher\Glyphs::lang_shortcode - */ - public function test_lang_shortcode_bad() { - - $content = $this->glyphs->lang_shortcode( + $content = $this->glyphs->langShortcode( [ 'lang' => 'foobar' ], 'aeiou' ); diff --git a/tests/test-themelock.php b/tests/test-themelock.php index d9594fc0be..4c45b34746 100644 --- a/tests/test-themelock.php +++ b/tests/test-themelock.php @@ -2,9 +2,6 @@ class ThemeLockTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\ThemeLock::getLockDir - */ public function test_getLockDir() { $result = \Pressbooks\ThemeLock::getLockDir(); @@ -12,23 +9,17 @@ public function test_getLockDir() { $this->assertEquals( true, substr( $result, -strlen( '/wp-content/uploads/lock' ) ) == '/wp-content/uploads/lock' ); } - /** - * @covers \Pressbooks\ThemeLock::getLockDirURI - */ public function test_getLockDirURI() { $result = \Pressbooks\ThemeLock::getLockDirURI(); $this->assertEquals( true, substr( $result, -strlen( '/wp-content/uploads/lock' ) ) == '/wp-content/uploads/lock' ); } - /** - * @covers \Pressbooks\ThemeLock::toggleThemeLock - */ public function test_toggleThemeLock() { $time = time(); sleep( 10 ); $theme = wp_get_theme(); - $result = \Pressbooks\ThemeLock::toggleThemeLock( array(), array( 'theme_lock' => 1 ), 'pressbooks_export_options' ); + $result = \Pressbooks\ThemeLock::toggleThemeLock( [], [ 'theme_lock' => 1 ], 'pressbooks_export_options' ); $this->assertArrayHasKey( 'stylesheet', $result ); $this->assertArrayHasKey( 'name', $result ); @@ -40,14 +31,11 @@ public function test_toggleThemeLock() { $this->assertGreaterThanOrEqual( $time, $result['timestamp'] ); $theme = wp_get_theme(); - $result = \Pressbooks\ThemeLock::toggleThemeLock( array( 'theme_lock' => 1 ), array(), 'pressbooks_export_options' ); + $result = \Pressbooks\ThemeLock::toggleThemeLock( [ 'theme_lock' => 1 ], [], 'pressbooks_export_options' ); $this->assertEquals( $theme, $result ); } - /** - * @covers \Pressbooks\ThemeLock::lockTheme - */ public function test_lockTheme() { $time = time(); sleep( 10 ); @@ -65,9 +53,6 @@ public function test_lockTheme() { $this->assertGreaterThanOrEqual( $time, $result['timestamp'] ); } - /** - * @covers \Pressbooks\ThemeLock::copyAssets - */ public function test_copyAssets() { $return = \Pressbooks\ThemeLock::copyAssets(); @@ -78,9 +63,6 @@ public function test_copyAssets() { $this->assertEquals( $base, $lock ); } - /** - * @covers \Pressbooks\ThemeLock::generateLock - */ public function test_generateLock() { $time = time(); @@ -99,9 +81,6 @@ public function test_generateLock() { $this->assertEquals( $result['timestamp'], $time ); } - /** - * @covers \Pressbooks\ThemeLock::unlockTheme - */ public function test_unlockTheme() { $dir = \Pressbooks\ThemeLock::getLockDir(); \Pressbooks\ThemeLock::unlockTheme(); @@ -109,18 +88,15 @@ public function test_unlockTheme() { $this->assertEquals( false, is_dir( $dir ) ); } - /** - * @covers \Pressbooks\ThemeLock::isLocked - */ public function test_isLocked() { - update_option( 'pressbooks_export_options', array( 'theme_lock' => 1 ) ); + update_option( 'pressbooks_export_options', [ 'theme_lock' => 1 ] ); \Pressbooks\ThemeLock::generateLock( time() ); $value = \Pressbooks\ThemeLock::isLocked(); $this->assertEquals( true, $value ); - update_option( 'pressbooks_export_options', array() ); + update_option( 'pressbooks_export_options', [] ); \Pressbooks\ThemeLock::unlockTheme(); $value = \Pressbooks\ThemeLock::isLocked(); @@ -128,9 +104,6 @@ public function test_isLocked() { $this->assertEquals( false, $value ); } - /** - * @covers \Pressbooks\ThemeLock::getLockData - */ public function test_getLockData() { $time = time(); sleep( 10 ); diff --git a/tests/test-utility.php b/tests/test-utility.php index f83efdeae9..c5fc145a29 100644 --- a/tests/test-utility.php +++ b/tests/test-utility.php @@ -2,9 +2,27 @@ class UtilityTest extends \WP_UnitTestCase { - /** - * @covers \Pressbooks\Utility\scandir_by_date - */ + + public function test_getset() { + + $array = [ 'hello' => 'world' ]; + $this->assertEquals( \Pressbooks\Utility\getset( $array, 'hello' ), 'world' ); + $this->assertEquals( \Pressbooks\Utility\getset( $array, 'nothing' ), null ); + $this->assertEquals( \Pressbooks\Utility\getset( $array, 'nothing', 'something' ), 'something' ); + + global $fake_out; + $fake_out['hello'] = 'world'; + $this->assertEquals( \Pressbooks\Utility\getset( 'fake_out', 'hello' ), 'world' ); + $this->assertEquals( \Pressbooks\Utility\getset( 'fake_out', 'nothing' ), null ); + $this->assertEquals( \Pressbooks\Utility\getset( 'fake_out', 'nothing', 'something' ), 'something' ); + + $_POST['hello'] = 'world'; + $this->assertEquals( \Pressbooks\Utility\getset( '_POST', 'hello' ), 'world' ); + $this->assertEquals( \Pressbooks\Utility\getset( '_POST', 'nothing' ), null ); + $this->assertEquals( \Pressbooks\Utility\getset( '_POST', 'nothing', 'something' ), 'something' ); + } + + public function test_scandir_by_date() { $files = \Pressbooks\Utility\scandir_by_date( __DIR__ ); @@ -15,9 +33,6 @@ public function test_scandir_by_date() { } - /** - * @covers \Pressbooks\Utility\group_exports - */ public function test_group_exports() { $files = \Pressbooks\Utility\group_exports(); @@ -28,18 +43,11 @@ public function test_group_exports() { } -// /** -// * @covers \Pressbooks\Utility\truncate_exports -// */ -// public function test_truncate_exports() { -// // TODO: Testing this as-is would delete files. Need to refactor to allow mocking the file system. -// $this->markTestIncomplete(); -// } - + // public function test_truncate_exports() { + // // TODO: Testing this as-is would delete files. Need to refactor to allow mocking the file system. + // $this->markTestIncomplete(); + // } - /** - * @covers \Pressbooks\Utility\get_media_prefix - */ public function test_get_media_prefix() { $prefix = \Pressbooks\Utility\get_media_prefix(); @@ -49,10 +57,6 @@ public function test_get_media_prefix() { ); } - - /** - * @covers \Pressbooks\Utility\get_media_path - */ public function test_get_media_path() { $guid = 'http://pressbooks.dev/test/wp-content/uploads/sites/3/2015/11/foobar.jpg'; @@ -66,10 +70,6 @@ public function test_get_media_path() { ); } - - /** - * @covers \Pressbooks\Utility\add_sitemap_to_robots_txt - */ public function test_add_sitemap_to_robots_txt_0() { update_option( 'blog_public', 0 ); @@ -77,10 +77,6 @@ public function test_add_sitemap_to_robots_txt_0() { \Pressbooks\Utility\add_sitemap_to_robots_txt(); } - - /** - * @covers \Pressbooks\Utility\add_sitemap_to_robots_txt - */ public function test_add_sitemap_to_robots_txt_1() { update_option( 'blog_public', 1 ); @@ -88,10 +84,6 @@ public function test_add_sitemap_to_robots_txt_1() { \Pressbooks\Utility\add_sitemap_to_robots_txt(); } - - /** - * @covers \Pressbooks\Utility\do_sitemap - */ public function test_do_sitemap_0() { update_option( 'blog_public', 0 ); @@ -99,10 +91,6 @@ public function test_do_sitemap_0() { \Pressbooks\Utility\do_sitemap(); } - - /** - * @covers \Pressbooks\Utility\do_sitemap - */ public function test_do_sitemap_1() { update_option( 'blog_public', 1 ); @@ -110,10 +98,6 @@ public function test_do_sitemap_1() { \Pressbooks\Utility\do_sitemap(); } - - /** - * @covers \Pressbooks\Utility\create_tmp_file - */ public function test_create_tmp_file() { $file = \Pressbooks\Utility\create_tmp_file(); @@ -123,46 +107,36 @@ public function test_create_tmp_file() { $this->assertEquals( 'Hello world!', file_get_contents( $file ) ); } - - /** - * @covers \Pressbooks\Utility\check_prince_install - */ public function test_check_prince_install() { $this->assertInternalType( 'bool', \Pressbooks\Utility\check_prince_install() ); $this->assertTrue( defined( 'PB_PRINCE_COMMAND' ) ); } - /** - * @covers \Pressbooks\Utility\check_epubcheck_install - */ public function test_check_epubcheck_install() { $this->assertInternalType( 'bool', \Pressbooks\Utility\check_epubcheck_install() ); $this->assertTrue( defined( 'PB_EPUBCHECK_COMMAND' ) ); } - /** - * @covers \Pressbooks\Utility\check_kindlegen_install - */ public function test_check_kindlegen_install() { $this->assertInternalType( 'bool', \Pressbooks\Utility\check_kindlegen_install() ); $this->assertTrue( defined( 'PB_KINDLEGEN_COMMAND' ) ); } - /** - * @covers \Pressbooks\Utility\check_xmllint_install - */ public function test_check_xmllint_install() { $this->assertInternalType( 'bool', \Pressbooks\Utility\check_xmllint_install() ); $this->assertTrue( defined( 'PB_XMLLINT_COMMAND' ) ); } - /** - * @covers \Pressbooks\Utility\show_experimental_features - */ + public function test_check_saxonhe_install() { + + $this->assertInternalType( 'bool', \Pressbooks\Utility\check_saxonhe_install() ); + $this->assertTrue( defined( 'PB_SAXON_COMMAND' ) ); + } + public function test_show_experimental_features() { $this->assertInternalType( 'bool', \Pressbooks\Utility\show_experimental_features() ); @@ -170,20 +144,12 @@ public function test_show_experimental_features() { } - - /** - * @covers \Pressbooks\Utility\include_plugins - */ public function test_include_plugins() { \Pressbooks\Utility\include_plugins(); $this->assertTrue( class_exists( 'custom_metadata_manager' ) ); } - - /** - * @covers \Pressbooks\Utility\filter_plugins - */ public function test_filter_plugins() { $symbionts = [ 'a-plugin-that-does-not-exist/foobar.php' => 1 ]; @@ -194,10 +160,6 @@ public function test_filter_plugins() { $this->assertArrayHasKey( 'a-plugin-that-does-not-exist/foobar.php', $filtered ); } - - /** - * @covers \Pressbooks\Utility\file_upload_max_size - */ public function test_file_upload_max_size() { $maxSize = \Pressbooks\Utility\file_upload_max_size(); @@ -208,10 +170,6 @@ public function test_file_upload_max_size() { } - - /** - * @covers \Pressbooks\Utility\parse_size - */ public function test_parse_size() { $this->assertTrue( is_float( \Pressbooks\Utility\parse_size( '1' ) ) ); @@ -221,10 +179,6 @@ public function test_parse_size() { $this->assertEquals( 8388608, \Pressbooks\Utility\parse_size( '8M' ) ); } - - /** - * @covers \Pressbooks\Utility\format_bytes - */ public function test_format_bytes() { $this->assertEquals( '200 B', \Pressbooks\Utility\format_bytes( 200 ) ); @@ -244,18 +198,12 @@ public function test_format_bytes() { } -// /** -// * @covers \Pressbooks\Utility\email_error_log -// */ -// public function test_email_error_log() { -// // TODO: Testing this as-is would send emails, write to error_log... Need to refactor -// $this->markTestIncomplete(); -// } + // public function test_email_error_log() { + // // TODO: Testing this as-is would send emails, write to error_log... Need to refactor + // $this->markTestIncomplete(); + // } - /** - * @covers \Pressbooks\Utility\template - */ public function test_template() { $template = \Pressbooks\Utility\template( @@ -278,32 +226,23 @@ public function test_template() { $this->fail(); } - /** - * @covers \Pressbooks\Utility\mail_from - */ public function test_mail_from() { $this->assertEquals( 'pressbooks@example.org', \Pressbooks\Utility\mail_from( '' ) ); define( 'WP_MAIL_FROM', 'hi@pressbooks.org' ); $this->assertEquals( 'hi@pressbooks.org', \Pressbooks\Utility\mail_from( '' ) ); } - /** - * @covers \Pressbooks\Utility\mail_from_name - */ public function test_mail_from_name() { $this->assertEquals( 'Pressbooks', \Pressbooks\Utility\mail_from_name( '' ) ); define( 'WP_MAIL_FROM_NAME', 'Ned' ); $this->assertEquals( 'Ned', \Pressbooks\Utility\mail_from_name( '' ) ); } - /** - * @covers \Pressbooks\Utility\rcopy - */ public function test_rcopy() { $uploads = wp_upload_dir(); $src = trailingslashit( $uploads['path'] ) . 'src'; $dest = trailingslashit( $uploads['path'] ) . 'dest'; - mkdir( $src ); + @mkdir( $src ); file_put_contents( $src . '/test.txt', 'test' ); $return = \Pressbooks\Utility\rcopy( $src, $dest ); diff --git a/tests/utils-trait.php b/tests/utils-trait.php index efe48a5b1b..02ded55488 100644 --- a/tests/utils-trait.php +++ b/tests/utils-trait.php @@ -42,7 +42,8 @@ private function _createTmpDir() { */ private function _fakeAjax() { - if ( ! defined( 'DOING_AJAX' ) ) define( 'DOING_AJAX', true ); + if ( ! defined( 'DOING_AJAX' ) ) { define( 'DOING_AJAX', true ); + } add_filter( 'wp_die_ajax_handler', '__return_false', 1, 1 ); // Override die() error_reporting( error_reporting() & ~E_WARNING ); // Suppress warnings }