repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.doImportGenerator
static function doImportGenerator( array $current_import ) : \Generator { // Set post status $current_import['default_post_status'] = ( isset( $_POST['show_imports_in_web'] ) ) ? 'publish' : 'private'; // @codingStandardsIgnoreLine /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 600, 'import' ) ); // @codingStandardsIgnoreLine $importer = null; switch ( $current_import['type_of'] ) { case Epub\Epub201::TYPE_OF: $importer = new Epub\Epub201(); break; case Wordpress\Wxr::TYPE_OF: $importer = new Wordpress\Wxr(); break; case Odf\Odt::TYPE_OF: $importer = new Odf\Odt(); break; case Ooxml\Docx::TYPE_OF: $importer = new Ooxml\Docx(); break; case Api\Api::TYPE_OF: $importer = new Api\Api(); break; case Html\Xhtml::TYPE_OF: $importer = new Html\Xhtml(); break; default: /** * Allows users to add a custom import routine for custom import type. * * @since 3.9.6 * * @param \Pressbooks\Modules\Import\Import $value */ $importers = apply_filters( 'pb_initialize_import', [] ); if ( ! is_array( $importers ) ) { $importers = [ $importers ]; } foreach ( $importers as $i ) { if ( is_object( $i ) ) { $class = get_class( $i ); if ( count( $importers ) === 1 || defined( "{$class}::TYPE_OF" ) && $class::TYPE_OF === $current_import['type_of'] ) { $importer = $i; break; } } } } if ( $importer !== null ) { if ( is_subclass_of( $importer, '\Pressbooks\Modules\Import\ImportGenerator' ) ) { /** @var \Pressbooks\Modules\Import\ImportGenerator $importer */ try { yield from $importer->importGenerator( $current_import ); } catch ( \Exception $e ) { } } else { /** @var \Pressbooks\Modules\Import\Import $importer */ yield 10 => __( 'Importing', 'pressbooks' ); $ok = $importer->import( $current_import ); yield 100 => __( 'Finishing up', 'pressbooks' ); } } }
php
static function doImportGenerator( array $current_import ) : \Generator { // Set post status $current_import['default_post_status'] = ( isset( $_POST['show_imports_in_web'] ) ) ? 'publish' : 'private'; // @codingStandardsIgnoreLine /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 600, 'import' ) ); // @codingStandardsIgnoreLine $importer = null; switch ( $current_import['type_of'] ) { case Epub\Epub201::TYPE_OF: $importer = new Epub\Epub201(); break; case Wordpress\Wxr::TYPE_OF: $importer = new Wordpress\Wxr(); break; case Odf\Odt::TYPE_OF: $importer = new Odf\Odt(); break; case Ooxml\Docx::TYPE_OF: $importer = new Ooxml\Docx(); break; case Api\Api::TYPE_OF: $importer = new Api\Api(); break; case Html\Xhtml::TYPE_OF: $importer = new Html\Xhtml(); break; default: /** * Allows users to add a custom import routine for custom import type. * * @since 3.9.6 * * @param \Pressbooks\Modules\Import\Import $value */ $importers = apply_filters( 'pb_initialize_import', [] ); if ( ! is_array( $importers ) ) { $importers = [ $importers ]; } foreach ( $importers as $i ) { if ( is_object( $i ) ) { $class = get_class( $i ); if ( count( $importers ) === 1 || defined( "{$class}::TYPE_OF" ) && $class::TYPE_OF === $current_import['type_of'] ) { $importer = $i; break; } } } } if ( $importer !== null ) { if ( is_subclass_of( $importer, '\Pressbooks\Modules\Import\ImportGenerator' ) ) { /** @var \Pressbooks\Modules\Import\ImportGenerator $importer */ try { yield from $importer->importGenerator( $current_import ); } catch ( \Exception $e ) { } } else { /** @var \Pressbooks\Modules\Import\Import $importer */ yield 10 => __( 'Importing', 'pressbooks' ); $ok = $importer->import( $current_import ); yield 100 => __( 'Finishing up', 'pressbooks' ); } } }
[ "static", "function", "doImportGenerator", "(", "array", "$", "current_import", ")", ":", "\\", "Generator", "{", "// Set post status", "$", "current_import", "[", "'default_post_status'", "]", "=", "(", "isset", "(", "$", "_POST", "[", "'show_imports_in_web'", "]...
Do Import @param array $current_import WP option 'pressbooks_current_import' @return \Generator
[ "Do", "Import" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L281-L368
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.setImportOptions
static protected function setImportOptions() { if ( ! check_admin_referer( 'pb-import' ) ) { return false; } $overrides = [ 'test_form' => false, 'test_type' => false, ]; if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } // If Import Type is a URL then download and fake $_FILES on success // // This is redundant for a webbook URL (REST API) but we do it anyway because: // + The select option UI expects us to fallback to the file when not a webbook in the same Submit // + Sanity check verifies that we can access the website like any other // if ( getset( '_POST', 'import_type' ) === 'url' ) { $overrides['action'] = 'pb_handle_url_upload'; self::createFileFromUrl(); } if ( empty( $_FILES['import_file']['name'] ) ) { return false; } $bad_extensions = '/\.(php([0-9])?|htaccess|htpasswd|cgi|sh|pl|bat|exe|cmd|dll)$/i'; if ( preg_match( $bad_extensions, $_FILES['import_file']['name'] ) ) { $_SESSION['pb_errors'][] = __( 'Sorry, this file type is not permitted for security reasons.' ); return false; } // Handle PHP uploads in WordPress $upload = wp_handle_upload( $_FILES['import_file'], $overrides ); $upload['url'] = getset( '_POST', 'import_http' ); if ( empty( $upload['type'] ) && ! empty( $_FILES['import_file']['type'] ) ) { $upload['type'] = $_FILES['import_file']['type']; } if ( ! empty( $upload['error'] ) ) { // Error, redirect back to form $_SESSION['pb_notices'][] = $upload['error']; return false; } $ok = false; switch ( $_POST['type_of'] ) { case Wordpress\Wxr::TYPE_OF: $importer = new Wordpress\Wxr(); $ok = $importer->setCurrentImportOption( $upload ); break; case Epub\Epub201::TYPE_OF: $importer = new Epub\Epub201(); $ok = $importer->setCurrentImportOption( $upload ); break; case Odf\Odt::TYPE_OF: $importer = new Odf\Odt(); $ok = $importer->setCurrentImportOption( $upload ); break; case Ooxml\Docx::TYPE_OF: $importer = new Ooxml\Docx(); $ok = $importer->setCurrentImportOption( $upload ); break; case Api\Api::TYPE_OF: case Html\Xhtml::TYPE_OF: if ( ! empty( $upload['url'] ) && Cloner::isEnabled() && self::hasApi( $upload ) ) { // API (Cloning) $importer = new Api\Api(); $ok = $importer->setCurrentImportOption( $upload ); } else { // HTML unset( $_SESSION['pb_errors'] ); $importer = new Html\Xhtml(); $ok = $importer->setCurrentImportOption( $upload ); } break; default: /** * Allows users to add custom import routine for custom import type * via HTTP GET requests * * @since 4.0.0 * * @param \Pressbooks\Modules\Import\Import $value */ $importers = apply_filters( 'pb_initialize_import', [] ); if ( ! is_array( $importers ) ) { $importers = [ $importers ]; } foreach ( $importers as $importer ) { if ( is_object( $importer ) ) { $class = get_class( $importer ); if ( count( $importers ) === 1 || defined( "{$class}::TYPE_OF" ) && $class::TYPE_OF === $_POST['type_of'] ) { $ok = $importer->setCurrentImportOption( $upload ); break; } } } } if ( ! $ok ) { // Not ok? $_SESSION['pb_errors'][] = sprintf( __( 'Your file does not appear to be a valid %s.', 'pressbooks' ), strtoupper( $_POST['type_of'] ) ); unlink( $upload['file'] ); return false; } return true; }
php
static protected function setImportOptions() { if ( ! check_admin_referer( 'pb-import' ) ) { return false; } $overrides = [ 'test_form' => false, 'test_type' => false, ]; if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } // If Import Type is a URL then download and fake $_FILES on success // // This is redundant for a webbook URL (REST API) but we do it anyway because: // + The select option UI expects us to fallback to the file when not a webbook in the same Submit // + Sanity check verifies that we can access the website like any other // if ( getset( '_POST', 'import_type' ) === 'url' ) { $overrides['action'] = 'pb_handle_url_upload'; self::createFileFromUrl(); } if ( empty( $_FILES['import_file']['name'] ) ) { return false; } $bad_extensions = '/\.(php([0-9])?|htaccess|htpasswd|cgi|sh|pl|bat|exe|cmd|dll)$/i'; if ( preg_match( $bad_extensions, $_FILES['import_file']['name'] ) ) { $_SESSION['pb_errors'][] = __( 'Sorry, this file type is not permitted for security reasons.' ); return false; } // Handle PHP uploads in WordPress $upload = wp_handle_upload( $_FILES['import_file'], $overrides ); $upload['url'] = getset( '_POST', 'import_http' ); if ( empty( $upload['type'] ) && ! empty( $_FILES['import_file']['type'] ) ) { $upload['type'] = $_FILES['import_file']['type']; } if ( ! empty( $upload['error'] ) ) { // Error, redirect back to form $_SESSION['pb_notices'][] = $upload['error']; return false; } $ok = false; switch ( $_POST['type_of'] ) { case Wordpress\Wxr::TYPE_OF: $importer = new Wordpress\Wxr(); $ok = $importer->setCurrentImportOption( $upload ); break; case Epub\Epub201::TYPE_OF: $importer = new Epub\Epub201(); $ok = $importer->setCurrentImportOption( $upload ); break; case Odf\Odt::TYPE_OF: $importer = new Odf\Odt(); $ok = $importer->setCurrentImportOption( $upload ); break; case Ooxml\Docx::TYPE_OF: $importer = new Ooxml\Docx(); $ok = $importer->setCurrentImportOption( $upload ); break; case Api\Api::TYPE_OF: case Html\Xhtml::TYPE_OF: if ( ! empty( $upload['url'] ) && Cloner::isEnabled() && self::hasApi( $upload ) ) { // API (Cloning) $importer = new Api\Api(); $ok = $importer->setCurrentImportOption( $upload ); } else { // HTML unset( $_SESSION['pb_errors'] ); $importer = new Html\Xhtml(); $ok = $importer->setCurrentImportOption( $upload ); } break; default: /** * Allows users to add custom import routine for custom import type * via HTTP GET requests * * @since 4.0.0 * * @param \Pressbooks\Modules\Import\Import $value */ $importers = apply_filters( 'pb_initialize_import', [] ); if ( ! is_array( $importers ) ) { $importers = [ $importers ]; } foreach ( $importers as $importer ) { if ( is_object( $importer ) ) { $class = get_class( $importer ); if ( count( $importers ) === 1 || defined( "{$class}::TYPE_OF" ) && $class::TYPE_OF === $_POST['type_of'] ) { $ok = $importer->setCurrentImportOption( $upload ); break; } } } } if ( ! $ok ) { // Not ok? $_SESSION['pb_errors'][] = sprintf( __( 'Your file does not appear to be a valid %s.', 'pressbooks' ), strtoupper( $_POST['type_of'] ) ); unlink( $upload['file'] ); return false; } return true; }
[ "static", "protected", "function", "setImportOptions", "(", ")", "{", "if", "(", "!", "check_admin_referer", "(", "'pb-import'", ")", ")", "{", "return", "false", ";", "}", "$", "overrides", "=", "[", "'test_form'", "=>", "false", ",", "'test_type'", "=>", ...
Look at $_POST and $_FILES, sets 'pressbooks_current_import' option based on submission @return bool
[ "Look", "at", "$_POST", "and", "$_FILES", "sets", "pressbooks_current_import", "option", "based", "on", "submission" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L382-L501
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.hasApi
static protected function hasApi( &$upload ) { $cloner = new Cloner( $upload['url'] ); $is_compatible = $cloner->isCompatible( $upload['url'] ); if ( $is_compatible ) { $upload['url'] = $cloner->getSourceBookUrl(); return true; } return false; }
php
static protected function hasApi( &$upload ) { $cloner = new Cloner( $upload['url'] ); $is_compatible = $cloner->isCompatible( $upload['url'] ); if ( $is_compatible ) { $upload['url'] = $cloner->getSourceBookUrl(); return true; } return false; }
[ "static", "protected", "function", "hasApi", "(", "&", "$", "upload", ")", "{", "$", "cloner", "=", "new", "Cloner", "(", "$", "upload", "[", "'url'", "]", ")", ";", "$", "is_compatible", "=", "$", "cloner", "->", "isCompatible", "(", "$", "upload", ...
@param array $upload Passed by reference because we want to change the URL @return bool
[ "@param", "array", "$upload", "Passed", "by", "reference", "because", "we", "want", "to", "change", "the", "URL" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L508-L516
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.createFileFromUrl
static protected function createFileFromUrl() { if ( ! check_admin_referer( 'pb-import' ) ) { return false; } // check if it's a valid url $url = trim( getset( '_POST', 'import_http', '' ) ); if ( false === filter_var( $url, FILTER_VALIDATE_URL ) ) { $_SESSION['pb_errors'][] = __( 'Your URL does not appear to be valid', 'pressbooks' ); return false; } // Check that it's small enough $max_file_size = \Pressbooks\Utility\parse_size( \Pressbooks\Utility\file_upload_max_size() ); if ( ! self::isUrlSmallerThanUploadMaxSize( $url, $max_file_size ) ) { $_SESSION['pb_errors'][] = __( 'The URL you are trying to import is bigger than the maximum file size.', 'pressbooks' ); return false; } $tmp_file = \Pressbooks\Utility\create_tmp_file(); $args = [ 'stream' => true, 'filename' => $tmp_file, ]; $response = wp_remote_get( $url, $args ); // Something failed if ( is_wp_error( $response ) ) { debug_error_log( '\Pressbooks\Modules\Import::formSubmit html import error, wp_remote_head()' . $response->get_error_message() ); $_SESSION['pb_errors'][] = $response->get_error_message(); unlink( $tmp_file ); return false; } $code = wp_remote_retrieve_response_code( $response ); if ( $code >= 400 ) { $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response code: ', 'pressbooks' ) . $code; unlink( $tmp_file ); return false; } // Double check file size if ( filesize( $tmp_file ) > $max_file_size ) { $_SESSION['pb_errors'][] = __( 'The URL you are trying to import is bigger than the maximum file size.', 'pressbooks' ); unlink( $tmp_file ); return false; } // Basename $parsed_url = wp_parse_url( $url ); if ( isset( $parsed_url['path'] ) ) { $basename = basename( $parsed_url['path'] ); } if ( empty( $basename ) ) { $basename = uniqid( 'import-' ); } // Mime type $mime = \Pressbooks\Media\mime_type( $tmp_file ); if ( empty( $mime ) ) { $mime = wp_remote_retrieve_header( $response, 'content-type' ); } $_FILES['import_file'] = [ 'name' => $basename, 'type' => $mime, 'tmp_name' => $tmp_file, 'error' => 0, 'size' => filesize( $tmp_file ), ]; return true; }
php
static protected function createFileFromUrl() { if ( ! check_admin_referer( 'pb-import' ) ) { return false; } // check if it's a valid url $url = trim( getset( '_POST', 'import_http', '' ) ); if ( false === filter_var( $url, FILTER_VALIDATE_URL ) ) { $_SESSION['pb_errors'][] = __( 'Your URL does not appear to be valid', 'pressbooks' ); return false; } // Check that it's small enough $max_file_size = \Pressbooks\Utility\parse_size( \Pressbooks\Utility\file_upload_max_size() ); if ( ! self::isUrlSmallerThanUploadMaxSize( $url, $max_file_size ) ) { $_SESSION['pb_errors'][] = __( 'The URL you are trying to import is bigger than the maximum file size.', 'pressbooks' ); return false; } $tmp_file = \Pressbooks\Utility\create_tmp_file(); $args = [ 'stream' => true, 'filename' => $tmp_file, ]; $response = wp_remote_get( $url, $args ); // Something failed if ( is_wp_error( $response ) ) { debug_error_log( '\Pressbooks\Modules\Import::formSubmit html import error, wp_remote_head()' . $response->get_error_message() ); $_SESSION['pb_errors'][] = $response->get_error_message(); unlink( $tmp_file ); return false; } $code = wp_remote_retrieve_response_code( $response ); if ( $code >= 400 ) { $_SESSION['pb_errors'][] = __( 'The website you are attempting to reach is not returning a successful response code: ', 'pressbooks' ) . $code; unlink( $tmp_file ); return false; } // Double check file size if ( filesize( $tmp_file ) > $max_file_size ) { $_SESSION['pb_errors'][] = __( 'The URL you are trying to import is bigger than the maximum file size.', 'pressbooks' ); unlink( $tmp_file ); return false; } // Basename $parsed_url = wp_parse_url( $url ); if ( isset( $parsed_url['path'] ) ) { $basename = basename( $parsed_url['path'] ); } if ( empty( $basename ) ) { $basename = uniqid( 'import-' ); } // Mime type $mime = \Pressbooks\Media\mime_type( $tmp_file ); if ( empty( $mime ) ) { $mime = wp_remote_retrieve_header( $response, 'content-type' ); } $_FILES['import_file'] = [ 'name' => $basename, 'type' => $mime, 'tmp_name' => $tmp_file, 'error' => 0, 'size' => filesize( $tmp_file ), ]; return true; }
[ "static", "protected", "function", "createFileFromUrl", "(", ")", "{", "if", "(", "!", "check_admin_referer", "(", "'pb-import'", ")", ")", "{", "return", "false", ";", "}", "// check if it's a valid url", "$", "url", "=", "trim", "(", "getset", "(", "'_POST'"...
Tries to download URL in $_POST['import_http'], impersonates $_FILES on success Note: Faking the $_FILES array will cause PHP's is_uploaded_file() to fail @return bool
[ "Tries", "to", "download", "URL", "in", "$_POST", "[", "import_http", "]", "impersonates", "$_FILES", "on", "success", "Note", ":", "Faking", "the", "$_FILES", "array", "will", "cause", "PHP", "s", "is_uploaded_file", "()", "to", "fail" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L524-L598
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.isUrlSmallerThanUploadMaxSize
static protected function isUrlSmallerThanUploadMaxSize( $url, $max ) { $response = wp_safe_remote_head( $url, [ 'redirection' => 2, ] ); $size = (int) wp_remote_retrieve_header( $response, 'Content-Length' ); if ( empty( $size ) ) { return true; // Unable to verify, return true and hope for the best... } return ( $max >= $size ); }
php
static protected function isUrlSmallerThanUploadMaxSize( $url, $max ) { $response = wp_safe_remote_head( $url, [ 'redirection' => 2, ] ); $size = (int) wp_remote_retrieve_header( $response, 'Content-Length' ); if ( empty( $size ) ) { return true; // Unable to verify, return true and hope for the best... } return ( $max >= $size ); }
[ "static", "protected", "function", "isUrlSmallerThanUploadMaxSize", "(", "$", "url", ",", "$", "max", ")", "{", "$", "response", "=", "wp_safe_remote_head", "(", "$", "url", ",", "[", "'redirection'", "=>", "2", ",", "]", ")", ";", "$", "size", "=", "(",...
Check that a URL is smaller than MAX UPLOAD without downloading the file @param string $url @param int $max @return bool
[ "Check", "that", "a", "URL", "is", "smaller", "than", "MAX", "UPLOAD", "without", "downloading", "the", "file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L609-L620
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.log
static function log( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = '[ Import Log ]'; $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; // @codingStandardsIgnoreLine if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { \Pressbooks\Utility\email_error_log( self::$logsEmail, $subject, $message ); } }
php
static function log( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = '[ Import Log ]'; $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; // @codingStandardsIgnoreLine if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { \Pressbooks\Utility\email_error_log( self::$logsEmail, $subject, $message ); } }
[ "static", "function", "log", "(", "$", "message", ",", "array", "$", "more_info", "=", "[", "]", ")", "{", "/** $var \\WP_User $current_user */", "global", "$", "current_user", ";", "$", "subject", "=", "'[ Import Log ]'", ";", "$", "info", "=", "[", "'time'...
Log something using wp_mail() and error_log(), include useful WordPress info. Note: This method is here temporarily. We are using it to find & fix bugs for the first iterations of import. Do not count on this method being here in the future. @deprecated @param string $message @param array $more_info
[ "Log", "something", "using", "wp_mail", "()", "and", "error_log", "()", "include", "useful", "WordPress", "info", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L661-L680
pressbooks/pressbooks
inc/modules/export/indesign/class-icml.php
Icml.convert
function convert() { // Create ICML $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; $book_html = $this->loadTemplate( __DIR__ . '/templates/xhtml.php', $vars ); $content = $this->transformXML( $book_html, PB_PLUGIN_DIR . 'symbionts/icml/tkbr2icml-v044.xsl' ); // Save ICML as file in exports folder $filename = $this->timestampedFileName( '.icml' ); \Pressbooks\Utility\put_contents( $filename, $content ); $this->outputPath = $filename; if ( ! filesize( $this->outputPath ) ) { $this->logError( $this->bookHtmlError( $book_html ) ); unlink( $this->outputPath ); return false; } return true; }
php
function convert() { // Create ICML $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; $book_html = $this->loadTemplate( __DIR__ . '/templates/xhtml.php', $vars ); $content = $this->transformXML( $book_html, PB_PLUGIN_DIR . 'symbionts/icml/tkbr2icml-v044.xsl' ); // Save ICML as file in exports folder $filename = $this->timestampedFileName( '.icml' ); \Pressbooks\Utility\put_contents( $filename, $content ); $this->outputPath = $filename; if ( ! filesize( $this->outputPath ) ) { $this->logError( $this->bookHtmlError( $book_html ) ); unlink( $this->outputPath ); return false; } return true; }
[ "function", "convert", "(", ")", "{", "// Create ICML", "$", "vars", "=", "[", "'meta'", "=>", "\\", "Pressbooks", "\\", "Book", "::", "getBookInformation", "(", ")", ",", "'book_contents'", "=>", "$", "this", "->", "preProcessBookContents", "(", "\\", "Pres...
Create $this->outputPath @return bool
[ "Create", "$this", "-", ">", "outputPath" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/indesign/class-icml.php#L32-L62
pressbooks/pressbooks
inc/modules/export/indesign/class-icml.php
Icml.logError
function logError( $message, array $more_info = [] ) { $more_info['path'] = $this->outputPath; parent::logError( $message, $more_info ); }
php
function logError( $message, array $more_info = [] ) { $more_info['path'] = $this->outputPath; parent::logError( $message, $more_info ); }
[ "function", "logError", "(", "$", "message", ",", "array", "$", "more_info", "=", "[", "]", ")", "{", "$", "more_info", "[", "'path'", "]", "=", "$", "this", "->", "outputPath", ";", "parent", "::", "logError", "(", "$", "message", ",", "$", "more_in...
Add $this->outputPath as additional log info, fallback to parent. @param $message @param array $more_info (unused, overridden)
[ "Add", "$this", "-", ">", "outputPath", "as", "additional", "log", "info", "fallback", "to", "parent", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/indesign/class-icml.php#L89-L94
pressbooks/pressbooks
inc/modules/export/indesign/class-icml.php
Icml.bookHtmlError
protected function bookHtmlError( $book_html ) { $message = "ICML conversion returned a file of zero bytes. \n"; $message .= 'This usually happens when bad XHTML (I.e. $book_html) is passed to the XSL transform routine. ' . "\n"; $message .= 'Analysis of $book_html follows: ' . "\n\n"; $book_html_path = $this->createTmpFile(); \Pressbooks\Utility\put_contents( $book_html_path, $book_html ); // Xmllint params $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $book_html_path ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); return $message . implode( "\n", $output ); }
php
protected function bookHtmlError( $book_html ) { $message = "ICML conversion returned a file of zero bytes. \n"; $message .= 'This usually happens when bad XHTML (I.e. $book_html) is passed to the XSL transform routine. ' . "\n"; $message .= 'Analysis of $book_html follows: ' . "\n\n"; $book_html_path = $this->createTmpFile(); \Pressbooks\Utility\put_contents( $book_html_path, $book_html ); // Xmllint params $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $book_html_path ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); return $message . implode( "\n", $output ); }
[ "protected", "function", "bookHtmlError", "(", "$", "book_html", ")", "{", "$", "message", "=", "\"ICML conversion returned a file of zero bytes. \\n\"", ";", "$", "message", ".=", "'This usually happens when bad XHTML (I.e. $book_html) is passed to the XSL transform routine. '", "...
Log problems with $book_html that probably caused transformXML() to fail. @param $book_html @return string
[ "Log", "problems", "with", "$book_html", "that", "probably", "caused", "transformXML", "()", "to", "fail", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/indesign/class-icml.php#L104-L122
pressbooks/pressbooks
inc/modules/export/indesign/class-icml.php
Icml.preProcessPostContent
protected function preProcessPostContent( $content ) { $content = apply_filters( 'the_content', $content ); $content = str_ireplace( [ '<b></b>', '<i></i>', '<strong></strong>', '<em></em>' ], '', $content ); $content = $this->fixAnnoyingCharacters( $content ); $content = $this->tidy( $content ); return $content; }
php
protected function preProcessPostContent( $content ) { $content = apply_filters( 'the_content', $content ); $content = str_ireplace( [ '<b></b>', '<i></i>', '<strong></strong>', '<em></em>' ], '', $content ); $content = $this->fixAnnoyingCharacters( $content ); $content = $this->tidy( $content ); return $content; }
[ "protected", "function", "preProcessPostContent", "(", "$", "content", ")", "{", "$", "content", "=", "apply_filters", "(", "'the_content'", ",", "$", "content", ")", ";", "$", "content", "=", "str_ireplace", "(", "[", "'<b></b>'", ",", "'<i></i>'", ",", "'<...
@param string $content @return string
[ "@param", "string", "$content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/indesign/class-icml.php#L190-L197
pressbooks/pressbooks
inc/modules/export/indesign/class-icml.php
Icml.tidy
protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed $html = \Pressbooks\Interactive\Content::init()->replaceInteractiveTags( $html ); $config = [ 'valid_xhtml' => 1, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, ]; return \Pressbooks\HtmLawed::filter( $html, $config ); }
php
protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed $html = \Pressbooks\Interactive\Content::init()->replaceInteractiveTags( $html ); $config = [ 'valid_xhtml' => 1, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, ]; return \Pressbooks\HtmLawed::filter( $html, $config ); }
[ "protected", "function", "tidy", "(", "$", "html", ")", "{", "// Make XHTML 1.1 strict using htmlLawed", "$", "html", "=", "\\", "Pressbooks", "\\", "Interactive", "\\", "Content", "::", "init", "(", ")", "->", "replaceInteractiveTags", "(", "$", "html", ")", ...
Tidy HTML @param string $html @return string
[ "Tidy", "HTML" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/indesign/class-icml.php#L207-L221
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.hooks
static public function hooks( Attachments $obj ) { add_shortcode( self::SHORTCODE, [ $obj, 'shortcodeHandler' ] ); // prevent further processing of formatted strings add_filter( 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { $excluded_shortcodes[] = Attachments::SHORTCODE; return $excluded_shortcodes; } ); // add img tag when searching for media add_filter( 'media_embedded_in_content_allowed_types', function ( $allowed_media_types ) { if ( ! in_array( 'img', $allowed_media_types, true ) ) { array_push( $allowed_media_types, 'img' ); } return $allowed_media_types; } ); // don't show unless user options $options = get_option( 'pressbooks_theme_options_global' ); // check it's set if ( isset( $options['attachment_attributions'] ) ) { // check it's turned on if ( 1 === $options['attachment_attributions'] ) { add_filter( 'the_content', [ $obj, 'getAttributions' ], 12 ); } } }
php
static public function hooks( Attachments $obj ) { add_shortcode( self::SHORTCODE, [ $obj, 'shortcodeHandler' ] ); // prevent further processing of formatted strings add_filter( 'no_texturize_shortcodes', function ( $excluded_shortcodes ) { $excluded_shortcodes[] = Attachments::SHORTCODE; return $excluded_shortcodes; } ); // add img tag when searching for media add_filter( 'media_embedded_in_content_allowed_types', function ( $allowed_media_types ) { if ( ! in_array( 'img', $allowed_media_types, true ) ) { array_push( $allowed_media_types, 'img' ); } return $allowed_media_types; } ); // don't show unless user options $options = get_option( 'pressbooks_theme_options_global' ); // check it's set if ( isset( $options['attachment_attributions'] ) ) { // check it's turned on if ( 1 === $options['attachment_attributions'] ) { add_filter( 'the_content', [ $obj, 'getAttributions' ], 12 ); } } }
[ "static", "public", "function", "hooks", "(", "Attachments", "$", "obj", ")", "{", "add_shortcode", "(", "self", "::", "SHORTCODE", ",", "[", "$", "obj", ",", "'shortcodeHandler'", "]", ")", ";", "// prevent further processing of formatted strings", "add_filter", ...
Hooks our bits into the machine @since 5.5.0 @param Attachments $obj
[ "Hooks", "our", "bits", "into", "the", "machine" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L44-L79
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.getBookMedia
function getBookMedia( $reset = false ) { // Cheap cache static $book_media = null; if ( $reset || $book_media === null ) { $book_media = []; $args = [ 'post_type' => 'attachment', 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => 'inherit', 'no_found_rows' => true, ]; $attached_media = get_posts( $args ); foreach ( $attached_media as $media ) { $book_media[ $media->ID ] = $media->guid; } } return $book_media; }
php
function getBookMedia( $reset = false ) { // Cheap cache static $book_media = null; if ( $reset || $book_media === null ) { $book_media = []; $args = [ 'post_type' => 'attachment', 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => 'inherit', 'no_found_rows' => true, ]; $attached_media = get_posts( $args ); foreach ( $attached_media as $media ) { $book_media[ $media->ID ] = $media->guid; } } return $book_media; }
[ "function", "getBookMedia", "(", "$", "reset", "=", "false", ")", "{", "// Cheap cache", "static", "$", "book_media", "=", "null", ";", "if", "(", "$", "reset", "||", "$", "book_media", "===", "null", ")", "{", "$", "book_media", "=", "[", "]", ";", ...
Returns the array of attachments set in the instance variable. @param bool $reset (optional, default is false) @since 5.5.0 @return array|null
[ "Returns", "the", "array", "of", "attachments", "set", "in", "the", "instance", "variable", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L90-L109
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.getAttributions
function getAttributions( $content ) { $media_in_page = get_media_embedded_in_content( $content ); // these are not the droids you're looking for if ( empty( $media_in_page ) ) { return $content; } // get all book attachments $book_media = $this->getBookMedia(); if ( ! empty( $book_media ) ) { $media_ids = Media\extract_id_from_media( $media_in_page ); // intersect media_ids found in page with found in book $unique_ids = Media\intersect_media_ids( $media_ids, $book_media ); } else { return $content; } // get attribution meta for each attachment $all_attributions = $this->getAttributionsMeta( $unique_ids ); // get the content of the attributions $media_attributions = $this->attributionsContent( $all_attributions ); return $content . $media_attributions; }
php
function getAttributions( $content ) { $media_in_page = get_media_embedded_in_content( $content ); // these are not the droids you're looking for if ( empty( $media_in_page ) ) { return $content; } // get all book attachments $book_media = $this->getBookMedia(); if ( ! empty( $book_media ) ) { $media_ids = Media\extract_id_from_media( $media_in_page ); // intersect media_ids found in page with found in book $unique_ids = Media\intersect_media_ids( $media_ids, $book_media ); } else { return $content; } // get attribution meta for each attachment $all_attributions = $this->getAttributionsMeta( $unique_ids ); // get the content of the attributions $media_attributions = $this->attributionsContent( $all_attributions ); return $content . $media_attributions; }
[ "function", "getAttributions", "(", "$", "content", ")", "{", "$", "media_in_page", "=", "get_media_embedded_in_content", "(", "$", "content", ")", ";", "// these are not the droids you're looking for", "if", "(", "empty", "(", "$", "media_in_page", ")", ")", "{", ...
Produces a list of media attributions if they are found in the current page and part of the media library appends said list to the end of the content @since 5.5.0 @param $content @return string
[ "Produces", "a", "list", "of", "media", "attributions", "if", "they", "are", "found", "in", "the", "current", "page", "and", "part", "of", "the", "media", "library", "appends", "said", "list", "to", "the", "end", "of", "the", "content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L122-L147
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.getAttributionsMeta
public function getAttributionsMeta( $ids ) { $all_attributions = []; if ( $ids ) { foreach ( $ids as $id ) { $all_attributions[ $id ]['title'] = get_the_title( $id ); $all_attributions[ $id ]['title_url'] = get_post_meta( $id, 'pb_media_attribution_title_url', true ); $all_attributions[ $id ]['author'] = get_post_meta( $id, 'pb_media_attribution_author', true ); $all_attributions[ $id ]['author_url'] = get_post_meta( $id, 'pb_media_attribution_author_url', true ); $all_attributions[ $id ]['adapted'] = get_post_meta( $id, 'pb_media_attribution_adapted', true ); $all_attributions[ $id ]['adapted_url'] = get_post_meta( $id, 'pb_media_attribution_adapted_url', true ); $all_attributions[ $id ]['license'] = get_post_meta( $id, 'pb_media_attribution_license', true ); } } return $all_attributions; }
php
public function getAttributionsMeta( $ids ) { $all_attributions = []; if ( $ids ) { foreach ( $ids as $id ) { $all_attributions[ $id ]['title'] = get_the_title( $id ); $all_attributions[ $id ]['title_url'] = get_post_meta( $id, 'pb_media_attribution_title_url', true ); $all_attributions[ $id ]['author'] = get_post_meta( $id, 'pb_media_attribution_author', true ); $all_attributions[ $id ]['author_url'] = get_post_meta( $id, 'pb_media_attribution_author_url', true ); $all_attributions[ $id ]['adapted'] = get_post_meta( $id, 'pb_media_attribution_adapted', true ); $all_attributions[ $id ]['adapted_url'] = get_post_meta( $id, 'pb_media_attribution_adapted_url', true ); $all_attributions[ $id ]['license'] = get_post_meta( $id, 'pb_media_attribution_license', true ); } } return $all_attributions; }
[ "public", "function", "getAttributionsMeta", "(", "$", "ids", ")", "{", "$", "all_attributions", "=", "[", "]", ";", "if", "(", "$", "ids", ")", "{", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "all_attributions", "[", "$", "id", "]...
Returns the gamut of attribution metadata that can be associated with an attachment @param array $ids of attachments @return array all attribution metadata
[ "Returns", "the", "gamut", "of", "attribution", "metadata", "that", "can", "be", "associated", "with", "an", "attachment" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L157-L173
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.attributionsContent
function attributionsContent( $attributions ) { $media_attributions = ''; $html = ''; $licensing = new Licensing(); $supported = $licensing->getSupportedTypes(); if ( $attributions ) { // generate appropriate markup for each field foreach ( $attributions as $attribution ) { // unset empty arrays $attribution = array_filter( $attribution, 'strlen' ); // only process if non-empty if ( count( $attribution ) > 0 ) { $author_byline = isset( $attribution['author'] ) ? __( ' by ', 'pressbooks' ) : ''; $adapted_byline = isset( $attribution['adapted'] ) ? __( ' adapted by ', 'pressbooks' ) : ''; $license_prefix = isset( $attribution['license'] ) ? ' &copy; ' : ''; $author = isset( $attribution['author'] ) ? $attribution['author'] : ''; $title = isset( $attribution['title'] ) ? $attribution['title'] : ''; $adapted_author = isset( $attribution['adapted'] ) ? $attribution['adapted'] : ''; $media_attributions .= sprintf( '<li %1$s>%2$s %3$s %4$s %5$s</li>', // about attribute ( isset( $attribution['title_url'] ) ) ? sprintf( 'about="%s"', $attribution['title_url'] ) : '', // title attribution ( isset( $attribution['title_url'] ) ) ? sprintf( '<a rel="cc:attributionURL" href="%1$s" property="dc:title">%2$s</a>', $attribution['title_url'], $title ) : $title, // author attribution sprintf( '%1$s %2$s', $author_byline, ( isset( $attribution['author_url'] ) ) ? sprintf( '<a rel="dc:creator" href="%1$s" property="cc:attributionName">%2$s</a>', $attribution['author_url'], $author ) : $author ), // adapted attribution sprintf( '%1$s %2$s', $adapted_byline, ( isset( $attribution['adapted_url'] ) ) ? sprintf( '<a rel="dc:source" href="%1$s">%2$s</a>', $attribution['adapted_url'], $adapted_author ) : $adapted_author ), // license attribution sprintf( '%1$s %2$s', $license_prefix, ( isset( $attribution['license'] ) ) ? sprintf( '<a rel="license" href="%1$s">%2$s</a>', $licensing->getUrlForLicense( $attribution['license'] ), $supported[ $attribution['license'] ]['desc'] ) : '' ) ); } } if ( ! empty( $media_attributions ) ) { $html = sprintf( '<div class="media-atttributions" prefix:cc="http://creativecommons.org/ns#" prefix:dc="http://purl.org/dc/terms/"><h3>' . __( 'Media Attributions', 'pressbooks' ) . '</h3><ul>%s</ul></div>', $media_attributions ); } } return $html; }
php
function attributionsContent( $attributions ) { $media_attributions = ''; $html = ''; $licensing = new Licensing(); $supported = $licensing->getSupportedTypes(); if ( $attributions ) { // generate appropriate markup for each field foreach ( $attributions as $attribution ) { // unset empty arrays $attribution = array_filter( $attribution, 'strlen' ); // only process if non-empty if ( count( $attribution ) > 0 ) { $author_byline = isset( $attribution['author'] ) ? __( ' by ', 'pressbooks' ) : ''; $adapted_byline = isset( $attribution['adapted'] ) ? __( ' adapted by ', 'pressbooks' ) : ''; $license_prefix = isset( $attribution['license'] ) ? ' &copy; ' : ''; $author = isset( $attribution['author'] ) ? $attribution['author'] : ''; $title = isset( $attribution['title'] ) ? $attribution['title'] : ''; $adapted_author = isset( $attribution['adapted'] ) ? $attribution['adapted'] : ''; $media_attributions .= sprintf( '<li %1$s>%2$s %3$s %4$s %5$s</li>', // about attribute ( isset( $attribution['title_url'] ) ) ? sprintf( 'about="%s"', $attribution['title_url'] ) : '', // title attribution ( isset( $attribution['title_url'] ) ) ? sprintf( '<a rel="cc:attributionURL" href="%1$s" property="dc:title">%2$s</a>', $attribution['title_url'], $title ) : $title, // author attribution sprintf( '%1$s %2$s', $author_byline, ( isset( $attribution['author_url'] ) ) ? sprintf( '<a rel="dc:creator" href="%1$s" property="cc:attributionName">%2$s</a>', $attribution['author_url'], $author ) : $author ), // adapted attribution sprintf( '%1$s %2$s', $adapted_byline, ( isset( $attribution['adapted_url'] ) ) ? sprintf( '<a rel="dc:source" href="%1$s">%2$s</a>', $attribution['adapted_url'], $adapted_author ) : $adapted_author ), // license attribution sprintf( '%1$s %2$s', $license_prefix, ( isset( $attribution['license'] ) ) ? sprintf( '<a rel="license" href="%1$s">%2$s</a>', $licensing->getUrlForLicense( $attribution['license'] ), $supported[ $attribution['license'] ]['desc'] ) : '' ) ); } } if ( ! empty( $media_attributions ) ) { $html = sprintf( '<div class="media-atttributions" prefix:cc="http://creativecommons.org/ns#" prefix:dc="http://purl.org/dc/terms/"><h3>' . __( 'Media Attributions', 'pressbooks' ) . '</h3><ul>%s</ul></div>', $media_attributions ); } } return $html; }
[ "function", "attributionsContent", "(", "$", "attributions", ")", "{", "$", "media_attributions", "=", "''", ";", "$", "html", "=", "''", ";", "$", "licensing", "=", "new", "Licensing", "(", ")", ";", "$", "supported", "=", "$", "licensing", "->", "getSu...
Produces an html blob of attribution statements for the array of attachment ids it's given. @since 5.5.0 @param array $attributions @return string
[ "Produces", "an", "html", "blob", "of", "attribution", "statements", "for", "the", "array", "of", "attachment", "ids", "it", "s", "given", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L185-L267
pressbooks/pressbooks
inc/shortcodes/attributions/class-attachments.php
Attachments.shortcodeHandler
function shortcodeHandler( $atts, $content = '' ) { $retval = ''; $a = shortcode_atts( [ 'id' => '', ], $atts ); if ( ! empty( $a ) ) { $meta = $this->getAttributionsMeta( $a ); $retval = $this->attributionsContent( $meta ); } return $retval; }
php
function shortcodeHandler( $atts, $content = '' ) { $retval = ''; $a = shortcode_atts( [ 'id' => '', ], $atts ); if ( ! empty( $a ) ) { $meta = $this->getAttributionsMeta( $a ); $retval = $this->attributionsContent( $meta ); } return $retval; }
[ "function", "shortcodeHandler", "(", "$", "atts", ",", "$", "content", "=", "''", ")", "{", "$", "retval", "=", "''", ";", "$", "a", "=", "shortcode_atts", "(", "[", "'id'", "=>", "''", ",", "]", ",", "$", "atts", ")", ";", "if", "(", "!", "emp...
If shortcode is present [media_attributions id='33'] returns the one attribution statement for that attachment @since 5.5.0 @param array $atts @param string $content @return string
[ "If", "shortcode", "is", "present", "[", "media_attributions", "id", "=", "33", "]", "returns", "the", "one", "attribution", "statement", "for", "that", "attachment" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/attributions/class-attachments.php#L280-L295
pressbooks/pressbooks
inc/covergenerator/class-covergenerator.php
Covergenerator.commandLineDefaults
static public function commandLineDefaults() { if ( ! defined( 'PB_CONVERT_COMMAND' ) ) { define( 'PB_CONVERT_COMMAND', '/usr/bin/convert' ); } if ( ! defined( 'PB_GS_COMMAND' ) ) { define( 'PB_GS_COMMAND', '/usr/bin/gs' ); } if ( ! defined( 'PB_PDFINFO_COMMAND' ) ) { define( 'PB_PDFINFO_COMMAND', '/usr/bin/pdfinfo' ); } if ( ! defined( 'PB_PDFTOPPM_COMMAND' ) ) { define( 'PB_PDFTOPPM_COMMAND', '/usr/bin/pdftoppm' ); } if ( ! defined( 'PB_PRINCE_COMMAND' ) ) { define( 'PB_PRINCE_COMMAND', '/usr/bin/prince' ); } }
php
static public function commandLineDefaults() { if ( ! defined( 'PB_CONVERT_COMMAND' ) ) { define( 'PB_CONVERT_COMMAND', '/usr/bin/convert' ); } if ( ! defined( 'PB_GS_COMMAND' ) ) { define( 'PB_GS_COMMAND', '/usr/bin/gs' ); } if ( ! defined( 'PB_PDFINFO_COMMAND' ) ) { define( 'PB_PDFINFO_COMMAND', '/usr/bin/pdfinfo' ); } if ( ! defined( 'PB_PDFTOPPM_COMMAND' ) ) { define( 'PB_PDFTOPPM_COMMAND', '/usr/bin/pdftoppm' ); } if ( ! defined( 'PB_PRINCE_COMMAND' ) ) { define( 'PB_PRINCE_COMMAND', '/usr/bin/prince' ); } }
[ "static", "public", "function", "commandLineDefaults", "(", ")", "{", "if", "(", "!", "defined", "(", "'PB_CONVERT_COMMAND'", ")", ")", "{", "define", "(", "'PB_CONVERT_COMMAND'", ",", "'/usr/bin/convert'", ")", ";", "}", "if", "(", "!", "defined", "(", "'PB...
Set defaults for command line utilities
[ "Set", "defaults", "for", "command", "line", "utilities" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-covergenerator.php#L47-L63
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.getExportStylePath
function getExportStylePath( $type ) { $fullpath = false; if ( CustomCss::isCustomCss() ) { $fullpath = CustomCss::getCustomCssFolder() . "$type.css"; if ( ! is_file( $fullpath ) ) { $fullpath = false; } } if ( ! $fullpath ) { // Look for SCSS file $fullpath = Container::get( 'Styles' )->getPathToScss( $type ); if ( ! $fullpath ) { // Look For CSS file $dir = Container::get( 'Styles' )->getDir(); $fullpath = realpath( "$dir/export/$type/style.css" ); } } return $fullpath; }
php
function getExportStylePath( $type ) { $fullpath = false; if ( CustomCss::isCustomCss() ) { $fullpath = CustomCss::getCustomCssFolder() . "$type.css"; if ( ! is_file( $fullpath ) ) { $fullpath = false; } } if ( ! $fullpath ) { // Look for SCSS file $fullpath = Container::get( 'Styles' )->getPathToScss( $type ); if ( ! $fullpath ) { // Look For CSS file $dir = Container::get( 'Styles' )->getDir(); $fullpath = realpath( "$dir/export/$type/style.css" ); } } return $fullpath; }
[ "function", "getExportStylePath", "(", "$", "type", ")", "{", "$", "fullpath", "=", "false", ";", "if", "(", "CustomCss", "::", "isCustomCss", "(", ")", ")", "{", "$", "fullpath", "=", "CustomCss", "::", "getCustomCssFolder", "(", ")", ".", "\"$type.css\""...
Return the fullpath to an export module's style file. @param string $type @return string
[ "Return", "the", "fullpath", "to", "an", "export", "module", "s", "style", "file", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L114-L136
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.truncateExportStylesheets
function truncateExportStylesheets( $type, $max = 1 ) { // This method only supports Prince stylesheets at the moment. if ( in_array( $type, [ 'prince' ], true ) ) { $stylesheets = scandir_by_date( Container::get( 'Sass' )->pathToUserGeneratedCss() ); $max = absint( $max ); $i = 1; foreach ( $stylesheets as $stylesheet ) { if ( preg_match( '/(' . $type . ')-([0-9]*)/', $stylesheet, $matches ) ) { if ( $i > $max ) { unlink( Container::get( 'Sass' )->pathToUserGeneratedCss() . '/' . $stylesheet ); } $i++; } } } }
php
function truncateExportStylesheets( $type, $max = 1 ) { // This method only supports Prince stylesheets at the moment. if ( in_array( $type, [ 'prince' ], true ) ) { $stylesheets = scandir_by_date( Container::get( 'Sass' )->pathToUserGeneratedCss() ); $max = absint( $max ); $i = 1; foreach ( $stylesheets as $stylesheet ) { if ( preg_match( '/(' . $type . ')-([0-9]*)/', $stylesheet, $matches ) ) { if ( $i > $max ) { unlink( Container::get( 'Sass' )->pathToUserGeneratedCss() . '/' . $stylesheet ); } $i++; } } } }
[ "function", "truncateExportStylesheets", "(", "$", "type", ",", "$", "max", "=", "1", ")", "{", "// This method only supports Prince stylesheets at the moment.", "if", "(", "in_array", "(", "$", "type", ",", "[", "'prince'", "]", ",", "true", ")", ")", "{", "$...
Remove all but the most recent compiled stylesheet. @param string $type @param int $max
[ "Remove", "all", "but", "the", "most", "recent", "compiled", "stylesheet", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L184-L199
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.getExportScriptPath
function getExportScriptPath( $type ) { $fullpath = false; if ( CustomCss::isCustomCss() ) { $fullpath = CustomCss::getCustomCssFolder() . "/$type.js"; if ( ! is_file( $fullpath ) ) { $fullpath = false; } } if ( ! $fullpath ) { $dir = Container::get( 'Styles' )->getDir(); if ( Container::get( 'Styles' )->isCurrentThemeCompatible( 2 ) ) { // Check for v2 themes $fullpath = realpath( "$dir/assets/scripts/$type/script.js" ); } else { $fullpath = realpath( "$dir/export/$type/script.js" ); } if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' === $type ) { $fullpath = realpath( get_stylesheet_directory() . "/export/$type/script-romanize.js" ); } } return $fullpath; }
php
function getExportScriptPath( $type ) { $fullpath = false; if ( CustomCss::isCustomCss() ) { $fullpath = CustomCss::getCustomCssFolder() . "/$type.js"; if ( ! is_file( $fullpath ) ) { $fullpath = false; } } if ( ! $fullpath ) { $dir = Container::get( 'Styles' )->getDir(); if ( Container::get( 'Styles' )->isCurrentThemeCompatible( 2 ) ) { // Check for v2 themes $fullpath = realpath( "$dir/assets/scripts/$type/script.js" ); } else { $fullpath = realpath( "$dir/export/$type/script.js" ); } if ( CustomCss::isCustomCss() && CustomCss::isRomanized() && 'prince' === $type ) { $fullpath = realpath( get_stylesheet_directory() . "/export/$type/script-romanize.js" ); } } return $fullpath; }
[ "function", "getExportScriptPath", "(", "$", "type", ")", "{", "$", "fullpath", "=", "false", ";", "if", "(", "CustomCss", "::", "isCustomCss", "(", ")", ")", "{", "$", "fullpath", "=", "CustomCss", "::", "getCustomCssFolder", "(", ")", ".", "\"/$type.js\"...
Return the fullpath to an export module's Javascript file. @param string $type @return string
[ "Return", "the", "fullpath", "to", "an", "export", "module", "s", "Javascript", "file", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L208-L233
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.getExportScriptUrl
function getExportScriptUrl( $type ) { $url = false; $dir = Container::get( 'Styles' )->getDir(); if ( Container::get( 'Styles' )->isCurrentThemeCompatible( 2 ) && realpath( "$dir/assets/scripts/$type/script.js" ) ) { $url = apply_filters( 'pb_stylesheet_directory_uri', get_stylesheet_directory_uri() ) . "/assets/scripts/$type/script.js"; } elseif ( realpath( "$dir/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 ) { $url = get_stylesheet_directory_uri() . "/export/$type/script-romanize.js"; } return $url; }
php
function getExportScriptUrl( $type ) { $url = false; $dir = Container::get( 'Styles' )->getDir(); if ( Container::get( 'Styles' )->isCurrentThemeCompatible( 2 ) && realpath( "$dir/assets/scripts/$type/script.js" ) ) { $url = apply_filters( 'pb_stylesheet_directory_uri', get_stylesheet_directory_uri() ) . "/assets/scripts/$type/script.js"; } elseif ( realpath( "$dir/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 ) { $url = get_stylesheet_directory_uri() . "/export/$type/script-romanize.js"; } return $url; }
[ "function", "getExportScriptUrl", "(", "$", "type", ")", "{", "$", "url", "=", "false", ";", "$", "dir", "=", "Container", "::", "get", "(", "'Styles'", ")", "->", "getDir", "(", ")", ";", "if", "(", "Container", "::", "get", "(", "'Styles'", ")", ...
Return the public URL to an export module's Javascript file. @param string $type @return string
[ "Return", "the", "public", "URL", "to", "an", "export", "module", "s", "Javascript", "file", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L242-L257
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.logError
function logError( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = get_class( $this ); $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; // @codingStandardsIgnoreLine $exportoptions = get_option( 'pressbooks_export_options' ); if ( $current_user->user_email && isset( $exportoptions['email_validation_logs'] ) && 1 === absint( $exportoptions['email_validation_logs'] ) ) { $this->errorsEmail[] = $current_user->user_email; } if ( defined( 'WP_TESTS_MULTISITE' ) ) { // Unit tests if ( empty( $more_info['warning'] ) ) { error_log( "\n{$subject}\n{$message}\n" ); // @codingStandardsIgnoreLine } } else { \Pressbooks\Utility\email_error_log( $this->errorsEmail, $subject, $message ); } }
php
function logError( $message, array $more_info = [] ) { /** $var \WP_User $current_user */ global $current_user; $subject = get_class( $this ); $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; // @codingStandardsIgnoreLine $exportoptions = get_option( 'pressbooks_export_options' ); if ( $current_user->user_email && isset( $exportoptions['email_validation_logs'] ) && 1 === absint( $exportoptions['email_validation_logs'] ) ) { $this->errorsEmail[] = $current_user->user_email; } if ( defined( 'WP_TESTS_MULTISITE' ) ) { // Unit tests if ( empty( $more_info['warning'] ) ) { error_log( "\n{$subject}\n{$message}\n" ); // @codingStandardsIgnoreLine } } else { \Pressbooks\Utility\email_error_log( $this->errorsEmail, $subject, $message ); } }
[ "function", "logError", "(", "$", "message", ",", "array", "$", "more_info", "=", "[", "]", ")", "{", "/** $var \\WP_User $current_user */", "global", "$", "current_user", ";", "$", "subject", "=", "get_class", "(", "$", "this", ")", ";", "$", "info", "=",...
Log errors using wp_mail() and error_log(), include useful WordPress info. @param string $message @param array $more_info
[ "Log", "errors", "using", "wp_mail", "()", "and", "error_log", "()", "include", "useful", "WordPress", "info", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L281-L310
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.verifyNonce
function verifyNonce( $timestamp, $md5 ) { // Within range of 5 minutes? $within_range = time() - $timestamp; if ( $within_range > ( MINUTE_IN_SECONDS * 5 ) ) { return false; } // Correct md5? if ( md5( NONCE_KEY . $timestamp ) !== $md5 ) { return false; } return true; }
php
function verifyNonce( $timestamp, $md5 ) { // Within range of 5 minutes? $within_range = time() - $timestamp; if ( $within_range > ( MINUTE_IN_SECONDS * 5 ) ) { return false; } // Correct md5? if ( md5( NONCE_KEY . $timestamp ) !== $md5 ) { return false; } return true; }
[ "function", "verifyNonce", "(", "$", "timestamp", ",", "$", "md5", ")", "{", "// Within range of 5 minutes?", "$", "within_range", "=", "time", "(", ")", "-", "$", "timestamp", ";", "if", "(", "$", "within_range", ">", "(", "MINUTE_IN_SECONDS", "*", "5", "...
Verify that a NONCE was created within a range of 5 minutes and is valid. @see nonce @param string $timestamp unix timestamp @param string $md5 @return bool
[ "Verify", "that", "a", "NONCE", "was", "created", "within", "a", "range", "of", "5", "minutes", "and", "is", "valid", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L375-L389
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.preProcessPostName
protected function preProcessPostName( $id ) { if ( in_array( $id, $this->reservedIds, true ) ) { $id = uniqid( "$id-" ); } return \Pressbooks\Sanitize\sanitize_xml_id( $id ); }
php
protected function preProcessPostName( $id ) { if ( in_array( $id, $this->reservedIds, true ) ) { $id = uniqid( "$id-" ); } return \Pressbooks\Sanitize\sanitize_xml_id( $id ); }
[ "protected", "function", "preProcessPostName", "(", "$", "id", ")", "{", "if", "(", "in_array", "(", "$", "id", ",", "$", "this", "->", "reservedIds", ",", "true", ")", ")", "{", "$", "id", "=", "uniqid", "(", "\"$id-\"", ")", ";", "}", "return", "...
Check a post_name against a list of reserved IDs, sanitize for use as an XML ID. @param string $id @return string
[ "Check", "a", "post_name", "against", "a", "list", "of", "reserved", "IDs", "sanitize", "for", "use", "as", "an", "XML", "ID", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L418-L425
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.createTmpDir
protected function createTmpDir() { $temp_file = tempnam( sys_get_temp_dir(), '' ); @unlink( $temp_file ); // @codingStandardsIgnoreLine mkdir( $temp_file ); if ( ! is_dir( $temp_file ) ) { return ''; } return untrailingslashit( $temp_file ); }
php
protected function createTmpDir() { $temp_file = tempnam( sys_get_temp_dir(), '' ); @unlink( $temp_file ); // @codingStandardsIgnoreLine mkdir( $temp_file ); if ( ! is_dir( $temp_file ) ) { return ''; } return untrailingslashit( $temp_file ); }
[ "protected", "function", "createTmpDir", "(", ")", "{", "$", "temp_file", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "''", ")", ";", "@", "unlink", "(", "$", "temp_file", ")", ";", "// @codingStandardsIgnoreLine", "mkdir", "(", "$", "temp_file",...
Create a temporary directory, no trailing slash! @return string
[ "Create", "a", "temporary", "directory", "no", "trailing", "slash!" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L433-L444
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.transformXML
protected function transformXML( $content, $path_to_xsl ) { libxml_use_internal_errors( true ); $content = iconv( 'UTF-8', 'UTF-8//IGNORE', $content ); $xsl = new \DOMDocument(); $xsl->load( $path_to_xsl ); $proc = new \XSLTProcessor(); $proc->importStyleSheet( $xsl ); $old_value = libxml_disable_entity_loader( true ); $xml = new \DOMDocument(); $xml->loadXML( $content ); libxml_disable_entity_loader( $old_value ); $content = $proc->transformToXML( $xml ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); return $content; }
php
protected function transformXML( $content, $path_to_xsl ) { libxml_use_internal_errors( true ); $content = iconv( 'UTF-8', 'UTF-8//IGNORE', $content ); $xsl = new \DOMDocument(); $xsl->load( $path_to_xsl ); $proc = new \XSLTProcessor(); $proc->importStyleSheet( $xsl ); $old_value = libxml_disable_entity_loader( true ); $xml = new \DOMDocument(); $xml->loadXML( $content ); libxml_disable_entity_loader( $old_value ); $content = $proc->transformToXML( $xml ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); return $content; }
[ "protected", "function", "transformXML", "(", "$", "content", ",", "$", "path_to_xsl", ")", "{", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "content", "=", "iconv", "(", "'UTF-8'", ",", "'UTF-8//IGNORE'", ",", "$", "content", ")", ";", "$", ...
Convert an XML string via XSLT file. @param string $content @param string $path_to_xsl @return string
[ "Convert", "an", "XML", "string", "via", "XSLT", "file", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L454-L476
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.doCopyrightLicense
protected function doCopyrightLicense( $metadata, $title = '', $id = 0, $section_author = '' ) { if ( ! empty( $section_author ) ) { _deprecated_argument( __METHOD__, '4.1.0' ); } try { $licensing = new \Pressbooks\Licensing(); return $licensing->doLicense( $metadata, $id, $title ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); } return ''; }
php
protected function doCopyrightLicense( $metadata, $title = '', $id = 0, $section_author = '' ) { if ( ! empty( $section_author ) ) { _deprecated_argument( __METHOD__, '4.1.0' ); } try { $licensing = new \Pressbooks\Licensing(); return $licensing->doLicense( $metadata, $id, $title ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); } return ''; }
[ "protected", "function", "doCopyrightLicense", "(", "$", "metadata", ",", "$", "title", "=", "''", ",", "$", "id", "=", "0", ",", "$", "section_author", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "section_author", ")", ")", "{", "_deprec...
Will create an html blob of copyright, returns empty string if something goes wrong @param array $metadata @param string $title (optional) @param int $id (optional) @param string $section_author (deprecated) @return string $html blob
[ "Will", "create", "an", "html", "blob", "of", "copyright", "returns", "empty", "string", "if", "something", "goes", "wrong" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L488-L501
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.doTocLicense
protected function doTocLicense( $post_id ) { $option = get_option( 'pressbooks_theme_options_global' ); if ( ! empty( $option['copyright_license'] ) ) { if ( 1 === absint( $option['copyright_license'] ) ) { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); if ( ! empty( $section_license ) ) { $licensing = new \Pressbooks\Licensing(); $supported_types = $licensing->getSupportedTypes(); if ( array_key_exists( $section_license, $supported_types ) ) { return $supported_types[ $section_license ]['desc']; } else { return ''; } } } elseif ( 2 === absint( $option['copyright_license'] ) ) { return ''; } } return ''; }
php
protected function doTocLicense( $post_id ) { $option = get_option( 'pressbooks_theme_options_global' ); if ( ! empty( $option['copyright_license'] ) ) { if ( 1 === absint( $option['copyright_license'] ) ) { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); if ( ! empty( $section_license ) ) { $licensing = new \Pressbooks\Licensing(); $supported_types = $licensing->getSupportedTypes(); if ( array_key_exists( $section_license, $supported_types ) ) { return $supported_types[ $section_license ]['desc']; } else { return ''; } } } elseif ( 2 === absint( $option['copyright_license'] ) ) { return ''; } } return ''; }
[ "protected", "function", "doTocLicense", "(", "$", "post_id", ")", "{", "$", "option", "=", "get_option", "(", "'pressbooks_theme_options_global'", ")", ";", "if", "(", "!", "empty", "(", "$", "option", "[", "'copyright_license'", "]", ")", ")", "{", "if", ...
Returns a string of text to be used in TOC, returns empty string if user doesn't want it displayed @param int $post_id Post ID. @return string
[ "Returns", "a", "string", "of", "text", "to", "be", "used", "in", "TOC", "returns", "empty", "string", "if", "user", "doesn", "t", "want", "it", "displayed" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L510-L530
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.doSectionLevelLicense
protected function doSectionLevelLicense( $metadata, $post_id ) { $option = get_option( 'pressbooks_theme_options_global' ); if ( ! empty( $option['copyright_license'] ) ) { if ( 1 === absint( $option['copyright_license'] ) ) { return ''; } elseif ( 2 === absint( $option['copyright_license'] ) ) { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); if ( ! empty( $section_license ) ) { try { $licensing = new \Pressbooks\Licensing(); return $licensing->doLicense( $metadata, $post_id ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); } } } } return ''; }
php
protected function doSectionLevelLicense( $metadata, $post_id ) { $option = get_option( 'pressbooks_theme_options_global' ); if ( ! empty( $option['copyright_license'] ) ) { if ( 1 === absint( $option['copyright_license'] ) ) { return ''; } elseif ( 2 === absint( $option['copyright_license'] ) ) { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); if ( ! empty( $section_license ) ) { try { $licensing = new \Pressbooks\Licensing(); return $licensing->doLicense( $metadata, $post_id ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); } } } } return ''; }
[ "protected", "function", "doSectionLevelLicense", "(", "$", "metadata", ",", "$", "post_id", ")", "{", "$", "option", "=", "get_option", "(", "'pressbooks_theme_options_global'", ")", ";", "if", "(", "!", "empty", "(", "$", "option", "[", "'copyright_license'", ...
Returns a string of text to be used in a section (chapter, front-matter, back-matter, ...) returns empty string if user doesn't want it displayed @param array $metadata @param int $post_id Post ID. @return string
[ "Returns", "a", "string", "of", "text", "to", "be", "used", "in", "a", "section", "(", "chapter", "front", "-", "matter", "back", "-", "matter", "...", ")", "returns", "empty", "string", "if", "user", "doesn", "t", "want", "it", "displayed" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L541-L559
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.loadTemplate
protected function loadTemplate( $path, array $vars = [] ) { try { return \Pressbooks\Utility\template( $path, $vars ); } catch ( \Exception $e ) { if ( WP_DEBUG ) { return "File not found: {$path}"; } else { return ''; } } }
php
protected function loadTemplate( $path, array $vars = [] ) { try { return \Pressbooks\Utility\template( $path, $vars ); } catch ( \Exception $e ) { if ( WP_DEBUG ) { return "File not found: {$path}"; } else { return ''; } } }
[ "protected", "function", "loadTemplate", "(", "$", "path", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "try", "{", "return", "\\", "Pressbooks", "\\", "Utility", "\\", "template", "(", "$", "path", ",", "$", "vars", ")", ";", "}", "catch", ...
Simple template system. @param string $path @param array $vars (optional) @return string
[ "Simple", "template", "system", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L569-L579
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.getExportFolder
static function getExportFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'exports/'; if ( ! file_exists( $path ) ) { wp_mkdir_p( $path ); } $path_to_htaccess = $path . '.htaccess'; if ( ! file_exists( $path_to_htaccess ) ) { // Restrict access \Pressbooks\Utility\put_contents( $path_to_htaccess, "deny from all\n" ); } /** * @since 5.3.0 * * Filters the export folder path * Use this hook to change the location of the export folder. * * @param string $path The path to the Pressbooks export folder */ $path = apply_filters( 'pb_get_export_folder', $path ); return $path; }
php
static function getExportFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'exports/'; if ( ! file_exists( $path ) ) { wp_mkdir_p( $path ); } $path_to_htaccess = $path . '.htaccess'; if ( ! file_exists( $path_to_htaccess ) ) { // Restrict access \Pressbooks\Utility\put_contents( $path_to_htaccess, "deny from all\n" ); } /** * @since 5.3.0 * * Filters the export folder path * Use this hook to change the location of the export folder. * * @param string $path The path to the Pressbooks export folder */ $path = apply_filters( 'pb_get_export_folder', $path ); return $path; }
[ "static", "function", "getExportFolder", "(", ")", "{", "$", "path", "=", "\\", "Pressbooks", "\\", "Utility", "\\", "get_media_prefix", "(", ")", ".", "'exports/'", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "wp_mkdir_p", "(", ...
Get the fullpath to the Exports folder. Create if not there. Create .htaccess protection if missing. @return string fullpath
[ "Get", "the", "fullpath", "to", "the", "Exports", "folder", ".", "Create", "if", "not", "there", ".", "Create", ".", "htaccess", "protection", "if", "missing", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L600-L624
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.formSubmit
static function formSubmit() { if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } // Override some WP behaviours when exporting \Pressbooks\Sanitize\fix_audio_shortcode(); // Download if ( ! empty( $_GET['download_export_file'] ) ) { $filename = sanitize_file_name( $_GET['download_export_file'] ); static::downloadExportFile( $filename, false ); exit; } }
php
static function formSubmit() { if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } // Override some WP behaviours when exporting \Pressbooks\Sanitize\fix_audio_shortcode(); // Download if ( ! empty( $_GET['download_export_file'] ) ) { $filename = sanitize_file_name( $_GET['download_export_file'] ); static::downloadExportFile( $filename, false ); exit; } }
[ "static", "function", "formSubmit", "(", ")", "{", "if", "(", "false", "===", "static", "::", "isFormSubmission", "(", ")", "||", "false", "===", "current_user_can", "(", "'edit_posts'", ")", ")", "{", "// Don't do anything in this function, bail.", "return", ";",...
Catch form submissions @see pressbooks/templates/admin/export.php
[ "Catch", "form", "submissions" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L632-L648
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.preExport
static function preExport() { /** * Let other plugins tweak things before exporting * * @since 4.4.0 */ do_action( 'pb_pre_export' ); // -------------------------------------------------------------------------------------------------------- // Clear cache? Range is 1 hour. $last_export = get_option( 'pressbooks_last_export' ); $within_range = time() - $last_export; if ( $within_range > ( HOUR_IN_SECONDS ) ) { \Pressbooks\Book::deleteBookObjectCache(); update_option( 'pressbooks_last_export', time() ); } static::$switchedLocale = switch_to_locale( self::locale() ); }
php
static function preExport() { /** * Let other plugins tweak things before exporting * * @since 4.4.0 */ do_action( 'pb_pre_export' ); // -------------------------------------------------------------------------------------------------------- // Clear cache? Range is 1 hour. $last_export = get_option( 'pressbooks_last_export' ); $within_range = time() - $last_export; if ( $within_range > ( HOUR_IN_SECONDS ) ) { \Pressbooks\Book::deleteBookObjectCache(); update_option( 'pressbooks_last_export', time() ); } static::$switchedLocale = switch_to_locale( self::locale() ); }
[ "static", "function", "preExport", "(", ")", "{", "/**\n\t\t * Let other plugins tweak things before exporting\n\t\t *\n\t\t * @since 4.4.0\n\t\t */", "do_action", "(", "'pb_pre_export'", ")", ";", "// ------------------------------------------------------------------------------------------...
Pre-Export
[ "Pre", "-", "Export" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L653-L672
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.modules
static function modules() { $modules = []; if ( is_array( getset( '_GET', 'export_formats' ) ) && check_admin_referer( 'pb-export' ) ) { // -------------------------------------------------------------------------------------------------------- // Define modules $x = $_GET['export_formats']; if ( isset( $x['pdf'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\Pdf'; } if ( isset( $x['print_pdf'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\PrintPdf'; } if ( isset( $x['epub'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Epub\Epub201'; // Must be set before MOBI } if ( isset( $x['epub3'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Epub\Epub3'; } if ( isset( $x['mobi'] ) ) { if ( ! isset( $x['epub'] ) ) { // Make sure Epub source file is generated $modules[] = '\Pressbooks\Modules\Export\Epub\Epub201'; // Must be set before MOBI } $modules[] = '\Pressbooks\Modules\Export\Mobi\Kindlegen'; // Must be set after EPUB } if ( isset( $x['icml'] ) ) { $modules[] = '\Pressbooks\Modules\Export\InDesign\Icml'; } if ( isset( $x['xhtml'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Xhtml\Xhtml11'; } if ( isset( $x['wxr'] ) ) { $modules[] = '\Pressbooks\Modules\Export\WordPress\Wxr'; } if ( isset( $x['vanillawxr'] ) ) { $modules[] = '\Pressbooks\Modules\Export\WordPress\VanillaWxr'; } if ( isset( $x['odt'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Odt\Odt'; } if ( isset( $x['htmlbook'] ) ) { $modules[] = '\Pressbooks\Modules\Export\HTMLBook\HTMLBook'; } // -------------------------------------------------------------------------------------------------------- // Other People's Plugins /** * Catch enabled custom formats and add their classes to the $modules array. * * 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; * } ); * * @since 3.9.8 * * @param array $modules */ $modules = apply_filters( 'pb_active_export_modules', $modules ); } return $modules; }
php
static function modules() { $modules = []; if ( is_array( getset( '_GET', 'export_formats' ) ) && check_admin_referer( 'pb-export' ) ) { // -------------------------------------------------------------------------------------------------------- // Define modules $x = $_GET['export_formats']; if ( isset( $x['pdf'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\Pdf'; } if ( isset( $x['print_pdf'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\PrintPdf'; } if ( isset( $x['epub'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Epub\Epub201'; // Must be set before MOBI } if ( isset( $x['epub3'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Epub\Epub3'; } if ( isset( $x['mobi'] ) ) { if ( ! isset( $x['epub'] ) ) { // Make sure Epub source file is generated $modules[] = '\Pressbooks\Modules\Export\Epub\Epub201'; // Must be set before MOBI } $modules[] = '\Pressbooks\Modules\Export\Mobi\Kindlegen'; // Must be set after EPUB } if ( isset( $x['icml'] ) ) { $modules[] = '\Pressbooks\Modules\Export\InDesign\Icml'; } if ( isset( $x['xhtml'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Xhtml\Xhtml11'; } if ( isset( $x['wxr'] ) ) { $modules[] = '\Pressbooks\Modules\Export\WordPress\Wxr'; } if ( isset( $x['vanillawxr'] ) ) { $modules[] = '\Pressbooks\Modules\Export\WordPress\VanillaWxr'; } if ( isset( $x['odt'] ) ) { $modules[] = '\Pressbooks\Modules\Export\Odt\Odt'; } if ( isset( $x['htmlbook'] ) ) { $modules[] = '\Pressbooks\Modules\Export\HTMLBook\HTMLBook'; } // -------------------------------------------------------------------------------------------------------- // Other People's Plugins /** * Catch enabled custom formats and add their classes to the $modules array. * * 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; * } ); * * @since 3.9.8 * * @param array $modules */ $modules = apply_filters( 'pb_active_export_modules', $modules ); } return $modules; }
[ "static", "function", "modules", "(", ")", "{", "$", "modules", "=", "[", "]", ";", "if", "(", "is_array", "(", "getset", "(", "'_GET'", ",", "'export_formats'", ")", ")", "&&", "check_admin_referer", "(", "'pb-export'", ")", ")", "{", "// ----------------...
Define modules @return array
[ "Define", "modules" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L679-L748
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.exportGenerator
static function exportGenerator( $modules ) : \Generator { /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 600, 'export' ) ); // @codingStandardsIgnoreLine static::$exportConversionError = []; static::$exportValidationWarning = []; static::$exportOutputs = []; foreach ( $modules as $module ) { $exporter = new $module( [] ); if ( is_subclass_of( $exporter, '\Pressbooks\Modules\Export\ExportGenerator' ) ) { /** @var \Pressbooks\Modules\Export\ExportGenerator $exporter */ try { yield from $exporter->convertGenerator(); try { yield from $exporter->validateGenerator(); } catch ( \Exception $e ) { static::$exportValidationWarning[ $module ] = $exporter->getOutputPath(); } } catch ( \Exception $e ) { static::$exportConversionError[ $module ] = $exporter->getOutputPath(); } } else { /** @var \Pressbooks\Modules\Export\Export $exporter */ $short_module_name = \Pressbooks\Modules\Export\get_name_from_module_classname( $module ); $msg = sprintf( __( '%s: Initializing', 'pressbooks' ), $short_module_name ); yield 1 => $msg; $msg = sprintf( __( '%s: Exporting', 'pressbooks' ), $short_module_name ); yield 10 => $msg; if ( ! $exporter->convert() ) { static::$exportConversionError[ $module ] = $exporter->getOutputPath(); } else { $msg = sprintf( __( '%s: Export successful', 'pressbooks' ), $short_module_name ); yield 70 => $msg; $msg = sprintf( __( '%s: Validating file', 'pressbooks' ), $short_module_name ); yield 80 => $msg; if ( ! $exporter->validate() ) { static::$exportValidationWarning[ $module ] = $exporter->getOutputPath(); } else { $msg = sprintf( __( '%s: Validation successful', 'pressbooks' ), $short_module_name ); yield 90 => $msg; } } $msg = sprintf( __( '%s: Finishing up', 'pressbooks' ), $short_module_name ); yield 100 => $msg; } // Add to outputs array static::$exportOutputs[ $module ] = $exporter->getOutputPath(); /** * Stats hook * * @param string */ do_action( 'pressbooks_track_export', substr( strrchr( $module, '\\' ), 1 ) ); } }
php
static function exportGenerator( $modules ) : \Generator { /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 600, 'export' ) ); // @codingStandardsIgnoreLine static::$exportConversionError = []; static::$exportValidationWarning = []; static::$exportOutputs = []; foreach ( $modules as $module ) { $exporter = new $module( [] ); if ( is_subclass_of( $exporter, '\Pressbooks\Modules\Export\ExportGenerator' ) ) { /** @var \Pressbooks\Modules\Export\ExportGenerator $exporter */ try { yield from $exporter->convertGenerator(); try { yield from $exporter->validateGenerator(); } catch ( \Exception $e ) { static::$exportValidationWarning[ $module ] = $exporter->getOutputPath(); } } catch ( \Exception $e ) { static::$exportConversionError[ $module ] = $exporter->getOutputPath(); } } else { /** @var \Pressbooks\Modules\Export\Export $exporter */ $short_module_name = \Pressbooks\Modules\Export\get_name_from_module_classname( $module ); $msg = sprintf( __( '%s: Initializing', 'pressbooks' ), $short_module_name ); yield 1 => $msg; $msg = sprintf( __( '%s: Exporting', 'pressbooks' ), $short_module_name ); yield 10 => $msg; if ( ! $exporter->convert() ) { static::$exportConversionError[ $module ] = $exporter->getOutputPath(); } else { $msg = sprintf( __( '%s: Export successful', 'pressbooks' ), $short_module_name ); yield 70 => $msg; $msg = sprintf( __( '%s: Validating file', 'pressbooks' ), $short_module_name ); yield 80 => $msg; if ( ! $exporter->validate() ) { static::$exportValidationWarning[ $module ] = $exporter->getOutputPath(); } else { $msg = sprintf( __( '%s: Validation successful', 'pressbooks' ), $short_module_name ); yield 90 => $msg; } } $msg = sprintf( __( '%s: Finishing up', 'pressbooks' ), $short_module_name ); yield 100 => $msg; } // Add to outputs array static::$exportOutputs[ $module ] = $exporter->getOutputPath(); /** * Stats hook * * @param string */ do_action( 'pressbooks_track_export', substr( strrchr( $module, '\\' ), 1 ) ); } }
[ "static", "function", "exportGenerator", "(", "$", "modules", ")", ":", "\\", "Generator", "{", "/**\n\t\t * Maximum execution time, in seconds. If set to zero, no time limit\n\t\t * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration\n\t\t * See also request_terminate_ti...
@param array $modules @return \Generator
[ "@param", "array", "$modules" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L755-L823
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.postExport
static function postExport() { $conversion_error = static::$exportConversionError; $validation_warning = static::$exportValidationWarning; $outputs = static::$exportOutputs; delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ if ( static::$switchedLocale ) { restore_previous_locale(); } // -------------------------------------------------------------------------------------------------------- // MOBI cleanup if ( is_array( getset( '_GET', 'export_formats' ) ) && check_admin_referer( 'pb-export' ) ) { $x = $_GET['export_formats']; if ( isset( $x['mobi'] ) && ! isset( $x['epub'] ) ) { unlink( $outputs['\Pressbooks\Modules\Export\Epub\Epub201'] ); } } // -------------------------------------------------------------------------------------------------------- // No errors? if ( empty( $conversion_error ) && empty( $validation_warning ) ) { // Redirect the user back to the form return; } // -------------------------------------------------------------------------------------------------------- // Error exceptions if ( isset( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ) ) { // The PDF is garbage and we don't want the user to have it. // Delete file. Report error instead of warning. unlink( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ); $conversion_error['\Pressbooks\Modules\Export\Prince\Pdf'] = $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf']; unset( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ); } if ( isset( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ) ) { // The PDF is garbage and we don't want the user to have it. // Delete file. Report error instead of warning. unlink( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ); $conversion_error['\Pressbooks\Modules\Export\Prince\PrintPdf'] = $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf']; unset( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ); } // -------------------------------------------------------------------------------------------------------- // Handle errors :( if ( is_countable( $conversion_error ) && count( $conversion_error ) ) { // Conversion error \Pressbooks\add_error( __( 'The export failed. See logs for more details.', 'pressbooks' ) ); } if ( is_countable( $validation_warning ) && count( $validation_warning ) ) { // Validation warning $exportoptions = get_option( 'pressbooks_export_options' ); if ( 1 === (int) $exportoptions['email_validation_logs'] || is_super_admin() ) { $export_warning = sprintf( '<p>%s</p>%s', __( 'Warning: The export has validation errors. See logs for more details.', 'pressbooks' ), ( isset( $exportoptions['email_validation_logs'] ) && 1 === (int) $exportoptions['email_validation_logs'] ) ? '<p>' . __( 'Emailed to:', 'pressbooks' ) . ' ' . wp_get_current_user()->user_email . '</p>' : '' ); \Pressbooks\add_error( $export_warning ); } } }
php
static function postExport() { $conversion_error = static::$exportConversionError; $validation_warning = static::$exportValidationWarning; $outputs = static::$exportOutputs; delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ if ( static::$switchedLocale ) { restore_previous_locale(); } // -------------------------------------------------------------------------------------------------------- // MOBI cleanup if ( is_array( getset( '_GET', 'export_formats' ) ) && check_admin_referer( 'pb-export' ) ) { $x = $_GET['export_formats']; if ( isset( $x['mobi'] ) && ! isset( $x['epub'] ) ) { unlink( $outputs['\Pressbooks\Modules\Export\Epub\Epub201'] ); } } // -------------------------------------------------------------------------------------------------------- // No errors? if ( empty( $conversion_error ) && empty( $validation_warning ) ) { // Redirect the user back to the form return; } // -------------------------------------------------------------------------------------------------------- // Error exceptions if ( isset( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ) ) { // The PDF is garbage and we don't want the user to have it. // Delete file. Report error instead of warning. unlink( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ); $conversion_error['\Pressbooks\Modules\Export\Prince\Pdf'] = $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf']; unset( $validation_warning['\Pressbooks\Modules\Export\Prince\Pdf'] ); } if ( isset( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ) ) { // The PDF is garbage and we don't want the user to have it. // Delete file. Report error instead of warning. unlink( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ); $conversion_error['\Pressbooks\Modules\Export\Prince\PrintPdf'] = $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf']; unset( $validation_warning['\Pressbooks\Modules\Export\Prince\PrintPdf'] ); } // -------------------------------------------------------------------------------------------------------- // Handle errors :( if ( is_countable( $conversion_error ) && count( $conversion_error ) ) { // Conversion error \Pressbooks\add_error( __( 'The export failed. See logs for more details.', 'pressbooks' ) ); } if ( is_countable( $validation_warning ) && count( $validation_warning ) ) { // Validation warning $exportoptions = get_option( 'pressbooks_export_options' ); if ( 1 === (int) $exportoptions['email_validation_logs'] || is_super_admin() ) { $export_warning = sprintf( '<p>%s</p>%s', __( 'Warning: The export has validation errors. See logs for more details.', 'pressbooks' ), ( isset( $exportoptions['email_validation_logs'] ) && 1 === (int) $exportoptions['email_validation_logs'] ) ? '<p>' . __( 'Emailed to:', 'pressbooks' ) . ' ' . wp_get_current_user()->user_email . '</p>' : '' ); \Pressbooks\add_error( $export_warning ); } } }
[ "static", "function", "postExport", "(", ")", "{", "$", "conversion_error", "=", "static", "::", "$", "exportConversionError", ";", "$", "validation_warning", "=", "static", "::", "$", "exportValidationWarning", ";", "$", "outputs", "=", "static", "::", "$", "...
Post Export
[ "Post", "Export" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L828-L899
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.isFormSubmission
static function isFormSubmission() { if ( empty( $_REQUEST['page'] ) ) { return false; } if ( 'pb_export' !== $_REQUEST['page'] ) { return false; } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } if ( count( $_GET ) > 1 ) { return true; } return false; }
php
static function isFormSubmission() { if ( empty( $_REQUEST['page'] ) ) { return false; } if ( 'pb_export' !== $_REQUEST['page'] ) { return false; } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } if ( count( $_GET ) > 1 ) { return true; } return false; }
[ "static", "function", "isFormSubmission", "(", ")", "{", "if", "(", "empty", "(", "$", "_REQUEST", "[", "'page'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "'pb_export'", "!==", "$", "_REQUEST", "[", "'page'", "]", ")", "{", "return...
Check if a user submitted something to admin.php?page=pb_export @return bool
[ "Check", "if", "a", "user", "submitted", "something", "to", "admin", ".", "php?page", "=", "pb_export" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L928-L947
pressbooks/pressbooks
inc/modules/export/class-export.php
Export.downloadExportFile
protected static function downloadExportFile( $filename, $inline ) { $filepath = static::getExportFolder() . $filename; \Pressbooks\Redirect\force_download( $filepath, $inline ); }
php
protected static function downloadExportFile( $filename, $inline ) { $filepath = static::getExportFolder() . $filename; \Pressbooks\Redirect\force_download( $filepath, $inline ); }
[ "protected", "static", "function", "downloadExportFile", "(", "$", "filename", ",", "$", "inline", ")", "{", "$", "filepath", "=", "static", "::", "getExportFolder", "(", ")", ".", "$", "filename", ";", "\\", "Pressbooks", "\\", "Redirect", "\\", "force_down...
Download an .htaccess protected file from the exports directory. @param string $filename sanitized $_GET['download_export_file'] @param bool $inline
[ "Download", "an", ".", "htaccess", "protected", "file", "from", "the", "exports", "directory", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-export.php#L956-L959
pressbooks/pressbooks
symbionts/custom-metadata/custom_metadata.php
custom_metadata_manager._order_multi_select
function _order_multi_select( array $terms, array $value ) { $ordered_terms = []; foreach ( $value as $slug ) { foreach ( $terms as $value_slug => $value_label ) { if ( $value_slug === $slug ) { $ordered_terms[ $value_slug ] = $value_label; unset( $terms[ $value_slug ] ); continue; } } } return array_merge( $ordered_terms, $terms ); }
php
function _order_multi_select( array $terms, array $value ) { $ordered_terms = []; foreach ( $value as $slug ) { foreach ( $terms as $value_slug => $value_label ) { if ( $value_slug === $slug ) { $ordered_terms[ $value_slug ] = $value_label; unset( $terms[ $value_slug ] ); continue; } } } return array_merge( $ordered_terms, $terms ); }
[ "function", "_order_multi_select", "(", "array", "$", "terms", ",", "array", "$", "value", ")", "{", "$", "ordered_terms", "=", "[", "]", ";", "foreach", "(", "$", "value", "as", "$", "slug", ")", "{", "foreach", "(", "$", "terms", "as", "$", "value_...
Fix: In multi-select, selections do not appear in the order in which they were selected @see https://github.com/select2/select2/issues/3106#issuecomment-339594053 @param array $terms @param array $value @return array
[ "Fix", ":", "In", "multi", "-", "select", "selections", "do", "not", "appear", "in", "the", "order", "in", "which", "they", "were", "selected" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/symbionts/custom-metadata/custom_metadata.php#L1422-L1434
pressbooks/pressbooks
symbionts/custom-metadata/custom_metadata.php
custom_metadata_manager._order_taxonomy_multi_select
function _order_taxonomy_multi_select( array $terms, array $value ) { $ordered_terms = []; foreach ( $value as $slug ) { foreach ( $terms as $i => $term ) { if ( $term->slug === $slug ) { $ordered_terms[] = $term; unset( $terms[ $i ] ); continue; } } } return array_merge( $ordered_terms, $terms ); }
php
function _order_taxonomy_multi_select( array $terms, array $value ) { $ordered_terms = []; foreach ( $value as $slug ) { foreach ( $terms as $i => $term ) { if ( $term->slug === $slug ) { $ordered_terms[] = $term; unset( $terms[ $i ] ); continue; } } } return array_merge( $ordered_terms, $terms ); }
[ "function", "_order_taxonomy_multi_select", "(", "array", "$", "terms", ",", "array", "$", "value", ")", "{", "$", "ordered_terms", "=", "[", "]", ";", "foreach", "(", "$", "value", "as", "$", "slug", ")", "{", "foreach", "(", "$", "terms", "as", "$", ...
Fix: In multi-select, selections do not appear in the order in which they were selected @see https://github.com/select2/select2/issues/3106#issuecomment-339594053 @param \WP_Term[] $terms @param array $value @return array
[ "Fix", ":", "In", "multi", "-", "select", "selections", "do", "not", "appear", "in", "the", "order", "in", "which", "they", "were", "selected" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/symbionts/custom-metadata/custom_metadata.php#L1446-L1458
pressbooks/pressbooks
inc/class-updates.php
Updates.gitHubUpdater
public function gitHubUpdater() { static $updater = null; if ( $updater === null ) { $updater = \Puc_v4_Factory::buildUpdateChecker( 'https://github.com/pressbooks/pressbooks/', untrailingslashit( PB_PLUGIN_DIR ) . '/pressbooks.php', // Fully qualified path to the main plugin file 'pressbooks', 24 ); $updater->setBranch( 'master' ); $updater->getVcsApi()->enableReleaseAssets(); } }
php
public function gitHubUpdater() { static $updater = null; if ( $updater === null ) { $updater = \Puc_v4_Factory::buildUpdateChecker( 'https://github.com/pressbooks/pressbooks/', untrailingslashit( PB_PLUGIN_DIR ) . '/pressbooks.php', // Fully qualified path to the main plugin file 'pressbooks', 24 ); $updater->setBranch( 'master' ); $updater->getVcsApi()->enableReleaseAssets(); } }
[ "public", "function", "gitHubUpdater", "(", ")", "{", "static", "$", "updater", "=", "null", ";", "if", "(", "$", "updater", "===", "null", ")", "{", "$", "updater", "=", "\\", "Puc_v4_Factory", "::", "buildUpdateChecker", "(", "'https://github.com/pressbooks/...
GitHub Plugin Update Checker Hooked into action `plugins_loaded` @see https://github.com/YahnisElsts/plugin-update-checker
[ "GitHub", "Plugin", "Update", "Checker", "Hooked", "into", "action", "plugins_loaded" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-updates.php#L61-L73
pressbooks/pressbooks
inc/class-updates.php
Updates.inPluginUpdateMessage
public function inPluginUpdateMessage( $plugin_data ) { $untested_plugins = $this->getUntestedPlugins( $plugin_data['new_version'] ); if ( ! empty( $untested_plugins ) ) { echo $this->blade->render( 'admin.incompatible-plugins', [ 'version' => $plugin_data['new_version'], 'plugins' => $untested_plugins, 'div_class' => 'incompatible-plugin-upgrade-notice', 'table_class' => 'incompatible-plugin-details-table', ] ); } }
php
public function inPluginUpdateMessage( $plugin_data ) { $untested_plugins = $this->getUntestedPlugins( $plugin_data['new_version'] ); if ( ! empty( $untested_plugins ) ) { echo $this->blade->render( 'admin.incompatible-plugins', [ 'version' => $plugin_data['new_version'], 'plugins' => $untested_plugins, 'div_class' => 'incompatible-plugin-upgrade-notice', 'table_class' => 'incompatible-plugin-details-table', ] ); } }
[ "public", "function", "inPluginUpdateMessage", "(", "$", "plugin_data", ")", "{", "$", "untested_plugins", "=", "$", "this", "->", "getUntestedPlugins", "(", "$", "plugin_data", "[", "'new_version'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "unteste...
Check for incompatible plugins. Displayed when user is looking at wp-admin/plugins.php Hooked into action `in_plugin_update_message-{$file}` @see \wp_plugin_update_row @param array $plugin_data An array of plugin metadata
[ "Check", "for", "incompatible", "plugins", ".", "Displayed", "when", "user", "is", "looking", "at", "wp", "-", "admin", "/", "plugins", ".", "php", "Hooked", "into", "action", "in_plugin_update_message", "-", "{", "$file", "}", "@see", "\\", "wp_plugin_update_...
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-updates.php#L83-L95
pressbooks/pressbooks
inc/class-updates.php
Updates.coreUpgradePreamble
public function coreUpgradePreamble() { $basename = $this->getBaseName(); $updateable_plugins = get_plugin_updates(); if ( $updateable_plugins[ $basename ]->update->new_version ?? null ) { $plugin_data = $updateable_plugins[ $basename ]; // $plugin_data is in \stdClass format } else { return; // Bail } $untested_plugins = $this->getUntestedPlugins( $plugin_data->update->new_version ); if ( ! empty( $untested_plugins ) ) { echo $this->blade->render( 'admin.incompatible-plugins', [ 'h2' => __( 'Plugins For Pressbooks', 'pressbooks' ), 'version' => $plugin_data->update->new_version, 'plugins' => $untested_plugins, 'table_class' => 'wp-list-table widefat striped', ] ); } }
php
public function coreUpgradePreamble() { $basename = $this->getBaseName(); $updateable_plugins = get_plugin_updates(); if ( $updateable_plugins[ $basename ]->update->new_version ?? null ) { $plugin_data = $updateable_plugins[ $basename ]; // $plugin_data is in \stdClass format } else { return; // Bail } $untested_plugins = $this->getUntestedPlugins( $plugin_data->update->new_version ); if ( ! empty( $untested_plugins ) ) { echo $this->blade->render( 'admin.incompatible-plugins', [ 'h2' => __( 'Plugins For Pressbooks', 'pressbooks' ), 'version' => $plugin_data->update->new_version, 'plugins' => $untested_plugins, 'table_class' => 'wp-list-table widefat striped', ] ); } }
[ "public", "function", "coreUpgradePreamble", "(", ")", "{", "$", "basename", "=", "$", "this", "->", "getBaseName", "(", ")", ";", "$", "updateable_plugins", "=", "get_plugin_updates", "(", ")", ";", "if", "(", "$", "updateable_plugins", "[", "$", "basename"...
Check for incompatible plugins. Displayed when user is looking at wp-admin/update-core.php Hooked into action `core_upgrade_preamble`
[ "Check", "for", "incompatible", "plugins", ".", "Displayed", "when", "user", "is", "looking", "at", "wp", "-", "admin", "/", "update", "-", "core", ".", "php", "Hooked", "into", "action", "core_upgrade_preamble" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-updates.php#L102-L122
pressbooks/pressbooks
inc/class-updates.php
Updates.getPluginsWithHeader
public function getPluginsWithHeader( $header ) { $plugins = get_plugins(); $matches = []; foreach ( $plugins as $file => $plugin ) { if ( $plugin['Name'] === 'Pressbooks' ) { continue; // Fix Pluginception... } if ( ! empty( $plugin[ $header ] ) ) { $matches[ $file ] = $plugin; } } return $matches; }
php
public function getPluginsWithHeader( $header ) { $plugins = get_plugins(); $matches = []; foreach ( $plugins as $file => $plugin ) { if ( $plugin['Name'] === 'Pressbooks' ) { continue; // Fix Pluginception... } if ( ! empty( $plugin[ $header ] ) ) { $matches[ $file ] = $plugin; } } return $matches; }
[ "public", "function", "getPluginsWithHeader", "(", "$", "header", ")", "{", "$", "plugins", "=", "get_plugins", "(", ")", ";", "$", "matches", "=", "[", "]", ";", "foreach", "(", "$", "plugins", "as", "$", "file", "=>", "$", "plugin", ")", "{", "if",...
Get plugins that have a specific header @param string $header @return array of plugin info arrays
[ "Get", "plugins", "that", "have", "a", "specific", "header" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-updates.php#L183-L195
pressbooks/pressbooks
inc/class-updates.php
Updates.getPluginsWithPressbooksInDescription
public function getPluginsWithPressbooksInDescription() { $plugins = get_plugins(); $matches = []; foreach ( $plugins as $file => $plugin ) { if ( $plugin['Name'] === 'Pressbooks' ) { continue; // Fix Pluginception... } if ( stristr( $plugin['Name'], 'pressbooks' ) || stristr( $plugin['Description'], 'pressbooks' ) || stristr( $file, 'pressbooks' ) ) { $matches[ $file ] = $plugin; } } return $matches; }
php
public function getPluginsWithPressbooksInDescription() { $plugins = get_plugins(); $matches = []; foreach ( $plugins as $file => $plugin ) { if ( $plugin['Name'] === 'Pressbooks' ) { continue; // Fix Pluginception... } if ( stristr( $plugin['Name'], 'pressbooks' ) || stristr( $plugin['Description'], 'pressbooks' ) || stristr( $file, 'pressbooks' ) ) { $matches[ $file ] = $plugin; } } return $matches; }
[ "public", "function", "getPluginsWithPressbooksInDescription", "(", ")", "{", "$", "plugins", "=", "get_plugins", "(", ")", ";", "$", "matches", "=", "[", "]", ";", "foreach", "(", "$", "plugins", "as", "$", "file", "=>", "$", "plugin", ")", "{", "if", ...
Get plugins with "Pressbooks" in the description @return array of plugin info arrays
[ "Get", "plugins", "with", "Pressbooks", "in", "the", "description" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-updates.php#L202-L214
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.addTooltipScripts
public function addTooltipScripts() { if ( ! is_admin() ) { $assets = new Assets( 'pressbooks', 'plugin' ); wp_enqueue_script( 'glossary-tooltip', $assets->getPath( 'scripts/glossary-tooltip.js' ), false, null, true ); wp_enqueue_style( 'glossary-tooltip', $assets->getPath( 'styles/glossary-tooltip.css' ), false, null ); } }
php
public function addTooltipScripts() { if ( ! is_admin() ) { $assets = new Assets( 'pressbooks', 'plugin' ); wp_enqueue_script( 'glossary-tooltip', $assets->getPath( 'scripts/glossary-tooltip.js' ), false, null, true ); wp_enqueue_style( 'glossary-tooltip', $assets->getPath( 'styles/glossary-tooltip.css' ), false, null ); } }
[ "public", "function", "addTooltipScripts", "(", ")", "{", "if", "(", "!", "is_admin", "(", ")", ")", "{", "$", "assets", "=", "new", "Assets", "(", "'pressbooks'", ",", "'plugin'", ")", ";", "wp_enqueue_script", "(", "'glossary-tooltip'", ",", "$", "assets...
Add JavaScript for the tooltip @since 5.5.0
[ "Add", "JavaScript", "for", "the", "tooltip" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L74-L80
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.getGlossaryTerms
public function getGlossaryTerms( $reset = false ) { // Cheap cache static $glossary_terms = null; if ( $reset || $glossary_terms === null ) { $glossary_terms = []; $args = [ 'post_type' => 'glossary', 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => [ 'private', 'publish' ], ]; $posts = get_posts( $args ); /** @var \WP_Post $post */ foreach ( $posts as $post ) { $type = ''; $terms = get_the_terms( $post->ID, 'glossary-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $type .= "{$term->slug},"; } } $glossary_terms[ $post->post_title ] = [ 'id' => $post->ID, 'content' => $post->post_content, 'type' => rtrim( $type, ',' ), 'status' => $post->post_status, ]; } } return $glossary_terms; }
php
public function getGlossaryTerms( $reset = false ) { // Cheap cache static $glossary_terms = null; if ( $reset || $glossary_terms === null ) { $glossary_terms = []; $args = [ 'post_type' => 'glossary', 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => [ 'private', 'publish' ], ]; $posts = get_posts( $args ); /** @var \WP_Post $post */ foreach ( $posts as $post ) { $type = ''; $terms = get_the_terms( $post->ID, 'glossary-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $type .= "{$term->slug},"; } } $glossary_terms[ $post->post_title ] = [ 'id' => $post->ID, 'content' => $post->post_content, 'type' => rtrim( $type, ',' ), 'status' => $post->post_status, ]; } } return $glossary_terms; }
[ "public", "function", "getGlossaryTerms", "(", "$", "reset", "=", "false", ")", "{", "// Cheap cache", "static", "$", "glossary_terms", "=", "null", ";", "if", "(", "$", "reset", "||", "$", "glossary_terms", "===", "null", ")", "{", "$", "glossary_terms", ...
Gets the instance variable of glossary terms, returns as an array of key = post_title, id = post ID, content = post_content. Sets an instance variable @param bool $reset (optional, default is false) @since 5.5.0 @return array
[ "Gets", "the", "instance", "variable", "of", "glossary", "terms", "returns", "as", "an", "array", "of", "key", "=", "post_title", "id", "=", "post", "ID", "content", "=", "post_content", ".", "Sets", "an", "instance", "variable" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L92-L121
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.getGlossaryTermsListbox
public function getGlossaryTermsListbox( $reset = false ) { $values[] = [ 'text' => '-- ' . __( 'Select', 'pressbooks' ) . ' --', 'value' => '', ]; $terms = $this->getGlossaryTerms( $reset ); foreach ( $terms as $title => $term ) { $values[] = [ 'text' => \Pressbooks\Sanitize\decode( $title ), 'value' => (int) $term['id'], ]; } return wp_json_encode( $values ); }
php
public function getGlossaryTermsListbox( $reset = false ) { $values[] = [ 'text' => '-- ' . __( 'Select', 'pressbooks' ) . ' --', 'value' => '', ]; $terms = $this->getGlossaryTerms( $reset ); foreach ( $terms as $title => $term ) { $values[] = [ 'text' => \Pressbooks\Sanitize\decode( $title ), 'value' => (int) $term['id'], ]; } return wp_json_encode( $values ); }
[ "public", "function", "getGlossaryTermsListbox", "(", "$", "reset", "=", "false", ")", "{", "$", "values", "[", "]", "=", "[", "'text'", "=>", "'-- '", ".", "__", "(", "'Select'", ",", "'pressbooks'", ")", ".", "' --'", ",", "'value'", "=>", "''", ",",...
For tiny mce Get both published and private terms @param bool $reset (optional, default is false) @return string
[ "For", "tiny", "mce", "Get", "both", "published", "and", "private", "terms" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L131-L144
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.glossaryTerms
public function glossaryTerms( $type = '' ) { $output = ''; $glossary = ''; $glossary_terms = $this->getGlossaryTerms(); if ( empty( $glossary_terms ) ) { return ''; } // make sure they are sorted in alphabetical order $ok = ksort( $glossary_terms, SORT_LOCALE_STRING ); if ( true === $ok && count( $glossary_terms ) > 0 ) { foreach ( $glossary_terms as $glossary_term_id => $glossary_term ) { if ( $glossary_term['status'] !== 'publish' ) { continue; } if ( ! empty( $type ) && ! \Pressbooks\Utility\comma_delimited_string_search( $glossary_term['type'], $type ) ) { // Type was not found. Skip this glossary term. continue; } $glossary .= sprintf( '<dt data-type="glossterm"><dfn id="%1$s">%2$s</dfn></dt><dd data-type="glossdef">%3$s</dd>', sprintf( 'dfn-%s', \Pressbooks\Utility\str_lowercase_dash( $glossary_term_id ) ), $glossary_term_id, wpautop( $glossary_term['content'] ) ); } } if ( ! empty( $glossary ) ) { $output = sprintf( '<dl data-type="glossary">%1$s</dl>', $glossary ); } return $output; }
php
public function glossaryTerms( $type = '' ) { $output = ''; $glossary = ''; $glossary_terms = $this->getGlossaryTerms(); if ( empty( $glossary_terms ) ) { return ''; } // make sure they are sorted in alphabetical order $ok = ksort( $glossary_terms, SORT_LOCALE_STRING ); if ( true === $ok && count( $glossary_terms ) > 0 ) { foreach ( $glossary_terms as $glossary_term_id => $glossary_term ) { if ( $glossary_term['status'] !== 'publish' ) { continue; } if ( ! empty( $type ) && ! \Pressbooks\Utility\comma_delimited_string_search( $glossary_term['type'], $type ) ) { // Type was not found. Skip this glossary term. continue; } $glossary .= sprintf( '<dt data-type="glossterm"><dfn id="%1$s">%2$s</dfn></dt><dd data-type="glossdef">%3$s</dd>', sprintf( 'dfn-%s', \Pressbooks\Utility\str_lowercase_dash( $glossary_term_id ) ), $glossary_term_id, wpautop( $glossary_term['content'] ) ); } } if ( ! empty( $glossary ) ) { $output = sprintf( '<dl data-type="glossary">%1$s</dl>', $glossary ); } return $output; }
[ "public", "function", "glossaryTerms", "(", "$", "type", "=", "''", ")", "{", "$", "output", "=", "''", ";", "$", "glossary", "=", "''", ";", "$", "glossary_terms", "=", "$", "this", "->", "getGlossaryTerms", "(", ")", ";", "if", "(", "empty", "(", ...
Returns the HTML <dl> description list of all !published! glossary terms @since 5.5.0 @see \Pressbooks\HTMLBook\Component\Glossary @param string $type The slug of an entry in the Glossary Types taxonomy @return string
[ "Returns", "the", "HTML", "<dl", ">", "description", "list", "of", "all", "!published!", "glossary", "terms" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L156-L188
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.glossaryTooltip
public function glossaryTooltip( $glossary_term_id, $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] // Get the glossary post object the glossary term ID belongs to $glossary_term = get_post( $glossary_term_id ); if ( ! $glossary_term ) { return $content . 'no post'; } if ( $glossary_term->post_status === 'trash' ) { return $content; } $html = '<button class="glossary-term" aria-describedby="' . $id . '-' . $glossary_term_id . '">' . $content . '</button>'; return $html; }
php
public function glossaryTooltip( $glossary_term_id, $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] // Get the glossary post object the glossary term ID belongs to $glossary_term = get_post( $glossary_term_id ); if ( ! $glossary_term ) { return $content . 'no post'; } if ( $glossary_term->post_status === 'trash' ) { return $content; } $html = '<button class="glossary-term" aria-describedby="' . $id . '-' . $glossary_term_id . '">' . $content . '</button>'; return $html; }
[ "public", "function", "glossaryTooltip", "(", "$", "glossary_term_id", ",", "$", "content", ")", "{", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "// Get the glossary post object the glossary term ID belongs to", "$", "glossary_term",...
Returns the tooltip markup and content @since 5.5.0 @param int $glossary_term_id @param string $content @return string
[ "Returns", "the", "tooltip", "markup", "and", "content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L200-L216
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.webShortcodeHandler
public function webShortcodeHandler( $atts, $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $a = shortcode_atts( [ 'id' => '', 'type' => '', ], $atts ); if ( ! empty( $content ) ) { // This is a tooltip if ( $a['id'] ) { if ( ! isset( $this->glossaryTerms[ $id ] ) ) { $this->glossaryTerms[ $id ] = []; } if ( ! isset( $this->glossaryTerms[ $id ][ $a['id'] ] ) ) { $this->glossaryTerms[ $id ][ $a['id'] ] = get_post_field( 'post_content', $a['id'] ); } return $this->glossaryTooltip( $a['id'], $content ); } } else { // This is a list of glossary terms return $this->glossaryTerms( $a['type'] ); } return $content; }
php
public function webShortcodeHandler( $atts, $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $a = shortcode_atts( [ 'id' => '', 'type' => '', ], $atts ); if ( ! empty( $content ) ) { // This is a tooltip if ( $a['id'] ) { if ( ! isset( $this->glossaryTerms[ $id ] ) ) { $this->glossaryTerms[ $id ] = []; } if ( ! isset( $this->glossaryTerms[ $id ][ $a['id'] ] ) ) { $this->glossaryTerms[ $id ][ $a['id'] ] = get_post_field( 'post_content', $a['id'] ); } return $this->glossaryTooltip( $a['id'], $content ); } } else { // This is a list of glossary terms return $this->glossaryTerms( $a['type'] ); } return $content; }
[ "public", "function", "webShortcodeHandler", "(", "$", "atts", ",", "$", "content", ")", "{", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "$", "a", "=", "shortcode_atts", "(", "[", "'id'", "=>", "''", ",", "'type'", ...
Webbook shortcode Gets the tooltip if the param contains the post id, or a list of terms if it's just the short-code @since 5.5.0 @param array $atts @param string $content @return string
[ "Webbook", "shortcode", "Gets", "the", "tooltip", "if", "the", "param", "contains", "the", "post", "id", "or", "a", "list", "of", "terms", "if", "it", "s", "just", "the", "short", "-", "code" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L230-L259
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.tooltipContent
function tooltipContent( $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] if ( ! empty( $this->glossaryTerms ) && isset( $this->glossaryTerms[ $id ] ) ) { $glossary_terms = $this->glossaryTerms[ $id ]; } else { return $content; } $content .= '<div class="glossary">'; foreach ( $glossary_terms as $glossary_term_id => $glossary_term ) { $identifier = "$id-$glossary_term_id"; $content .= '<div class="glossary__tooltip" id="' . $identifier . '" hidden>' . wpautop( $glossary_term ) . '</div>'; } $content .= '</div>'; return $content; }
php
function tooltipContent( $content ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] if ( ! empty( $this->glossaryTerms ) && isset( $this->glossaryTerms[ $id ] ) ) { $glossary_terms = $this->glossaryTerms[ $id ]; } else { return $content; } $content .= '<div class="glossary">'; foreach ( $glossary_terms as $glossary_term_id => $glossary_term ) { $identifier = "$id-$glossary_term_id"; $content .= '<div class="glossary__tooltip" id="' . $identifier . '" hidden>' . wpautop( $glossary_term ) . '</div>'; } $content .= '</div>'; return $content; }
[ "function", "tooltipContent", "(", "$", "content", ")", "{", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "if", "(", "!", "empty", "(", "$", "this", "->", "glossaryTerms", ")", "&&", "isset", "(", "$", "this", "->", ...
Post-process glossary shortcode, creating content for tooltips @param $content @return string
[ "Post", "-", "process", "glossary", "shortcode", "creating", "content", "for", "tooltips" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L268-L288
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.sanitizeGlossaryTerm
public function sanitizeGlossaryTerm( $data ) { if ( isset( $data['post_type'], $data['post_content'] ) && $data['post_type'] === 'glossary' ) { $data['post_content'] = wp_kses( $data['post_content'], [ 'a' => [ 'href' => [], 'target' => [], ], 'br' => [], 'em' => [], 'p' => [], 'strong' => [], ] ); } return $data; }
php
public function sanitizeGlossaryTerm( $data ) { if ( isset( $data['post_type'], $data['post_content'] ) && $data['post_type'] === 'glossary' ) { $data['post_content'] = wp_kses( $data['post_content'], [ 'a' => [ 'href' => [], 'target' => [], ], 'br' => [], 'em' => [], 'p' => [], 'strong' => [], ] ); } return $data; }
[ "public", "function", "sanitizeGlossaryTerm", "(", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'post_type'", "]", ",", "$", "data", "[", "'post_content'", "]", ")", "&&", "$", "data", "[", "'post_type'", "]", "===", "'glossary'", ...
@param array $data An array of slashed post data. @return mixed
[ "@param", "array", "$data", "An", "array", "of", "slashed", "post", "data", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L307-L324
pressbooks/pressbooks
inc/shortcodes/glossary/class-glossary.php
Glossary.backMatterAutoDisplay
public function backMatterAutoDisplay( $content ) { $post = get_post(); if ( ! $post ) { // Try to find using deprecated means global $id; $post = get_post( $id ); } if ( ! $post ) { // Unknown post return $content; } if ( $post->post_type !== 'back-matter' ) { // Post is not a back-matter return $content; } $taxonomy = \Pressbooks\Taxonomy::init(); if ( $taxonomy->getBackMatterType( $post->ID ) !== 'glossary' ) { // Post is not a glossary return $content; } if ( ! \Pressbooks\Utility\empty_space( \Pressbooks\Sanitize\decode( str_replace( '&nbsp;', '', $content ) ) ) ) { // Content is not empty return $content; } return $this->glossaryTerms(); }
php
public function backMatterAutoDisplay( $content ) { $post = get_post(); if ( ! $post ) { // Try to find using deprecated means global $id; $post = get_post( $id ); } if ( ! $post ) { // Unknown post return $content; } if ( $post->post_type !== 'back-matter' ) { // Post is not a back-matter return $content; } $taxonomy = \Pressbooks\Taxonomy::init(); if ( $taxonomy->getBackMatterType( $post->ID ) !== 'glossary' ) { // Post is not a glossary return $content; } if ( ! \Pressbooks\Utility\empty_space( \Pressbooks\Sanitize\decode( str_replace( '&nbsp;', '', $content ) ) ) ) { // Content is not empty return $content; } return $this->glossaryTerms(); }
[ "public", "function", "backMatterAutoDisplay", "(", "$", "content", ")", "{", "$", "post", "=", "get_post", "(", ")", ";", "if", "(", "!", "$", "post", ")", "{", "// Try to find using deprecated means", "global", "$", "id", ";", "$", "post", "=", "get_post...
Automatically display shortcode list in Glossary back matter if content is empty @param string $content @return string
[ "Automatically", "display", "shortcode", "list", "in", "Glossary", "back", "matter", "if", "content", "is", "empty" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/glossary/class-glossary.php#L333-L360
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.convert
public function convert() { try { foreach ( $this->convertGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return false; } return true; }
php
public function convert() { try { foreach ( $this->convertGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return false; } return true; }
[ "public", "function", "convert", "(", ")", "{", "try", "{", "foreach", "(", "$", "this", "->", "convertGenerator", "(", ")", "as", "$", "percentage", "=>", "$", "info", ")", "{", "// Do nothing, this is a compatibility wrapper that makes the generator work like a regu...
Create $this->outputPath @return bool
[ "Create", "$this", "-", ">", "outputPath" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L267-L276
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.convertGenerator
public function convertGenerator() : \Generator { yield 1 => $this->generatorPrefix . __( 'Initializing', 'pressbooks' ); // Sanity check if ( empty( $this->tmpDir ) || ! is_dir( $this->tmpDir ) ) { $this->logError( '$this->tmpDir must be set before calling convert().' ); throw new \Exception(); } if ( empty( $this->exportStylePath ) || ! is_file( $this->exportStylePath ) ) { $this->logError( '$this->exportStylePath must be set before calling convert().' ); throw new \Exception(); } // Convert yield 2 => $this->generatorPrefix . __( 'Preparing book contents', 'pressbooks' ); $metadata = Book::getBookInformation(); $book_contents = $this->preProcessBookContents( Book::getBookContents() ); // Set two letter language code if ( isset( $metadata['pb_language'] ) ) { list( $this->lang ) = explode( '-', $metadata['pb_language'] ); } try { yield 5 => $this->generatorPrefix . __( 'Creating container', 'pressbooks' ); $this->createContainer(); yield from $this->createOEBPSGenerator( $book_contents, $metadata ); $this->createOPF( $book_contents, $metadata ); $this->createNCX( $book_contents, $metadata ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); throw new \Exception(); } yield 75 => $this->generatorPrefix . __( 'Saving file to exports folder', 'pressbooks' ); $filename = $this->timestampedFileName( $this->suffix ); if ( ! $this->zipEpub( $filename ) ) { throw new \Exception(); } $this->outputPath = $filename; yield 80 => $this->generatorPrefix . __( 'Export successful', 'pressbooks' ); }
php
public function convertGenerator() : \Generator { yield 1 => $this->generatorPrefix . __( 'Initializing', 'pressbooks' ); // Sanity check if ( empty( $this->tmpDir ) || ! is_dir( $this->tmpDir ) ) { $this->logError( '$this->tmpDir must be set before calling convert().' ); throw new \Exception(); } if ( empty( $this->exportStylePath ) || ! is_file( $this->exportStylePath ) ) { $this->logError( '$this->exportStylePath must be set before calling convert().' ); throw new \Exception(); } // Convert yield 2 => $this->generatorPrefix . __( 'Preparing book contents', 'pressbooks' ); $metadata = Book::getBookInformation(); $book_contents = $this->preProcessBookContents( Book::getBookContents() ); // Set two letter language code if ( isset( $metadata['pb_language'] ) ) { list( $this->lang ) = explode( '-', $metadata['pb_language'] ); } try { yield 5 => $this->generatorPrefix . __( 'Creating container', 'pressbooks' ); $this->createContainer(); yield from $this->createOEBPSGenerator( $book_contents, $metadata ); $this->createOPF( $book_contents, $metadata ); $this->createNCX( $book_contents, $metadata ); } catch ( \Exception $e ) { $this->logError( $e->getMessage() ); throw new \Exception(); } yield 75 => $this->generatorPrefix . __( 'Saving file to exports folder', 'pressbooks' ); $filename = $this->timestampedFileName( $this->suffix ); if ( ! $this->zipEpub( $filename ) ) { throw new \Exception(); } $this->outputPath = $filename; yield 80 => $this->generatorPrefix . __( 'Export successful', 'pressbooks' ); }
[ "public", "function", "convertGenerator", "(", ")", ":", "\\", "Generator", "{", "yield", "1", "=>", "$", "this", "->", "generatorPrefix", ".", "__", "(", "'Initializing'", ",", "'pressbooks'", ")", ";", "// Sanity check", "if", "(", "empty", "(", "$", "th...
Yields an estimated percentage slice of: 1 to 80 @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "1", "to", "80" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L284-L330
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.validate
public function validate() { try { foreach ( $this->validateGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return false; } return true; }
php
public function validate() { try { foreach ( $this->validateGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return false; } return true; }
[ "public", "function", "validate", "(", ")", "{", "try", "{", "foreach", "(", "$", "this", "->", "validateGenerator", "(", ")", "as", "$", "percentage", "=>", "$", "info", ")", "{", "// Do nothing, this is a compatibility wrapper that makes the generator work like a re...
Check the sanity of $this->outputPath @return bool
[ "Check", "the", "sanity", "of", "$this", "-", ">", "outputPath" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L337-L346
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.validateGenerator
public function validateGenerator() : \Generator { yield 80 => $this->generatorPrefix . __( 'Validating file', 'pressbooks' ); // Epubcheck command, (quiet flag requires version 3.0.1+) $command = PB_EPUBCHECK_COMMAND . ' -q ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); foreach ( $output as $k => $v ) { if ( strpos( $v, 'Picked up _JAVA_OPTIONS:' ) !== false ) { // Remove JAVA warnings that are not actually errors unset( $output[ $k ] ); } elseif ( strpos( $v, 'non-standard font type application/x-font-ttf' ) !== false ) { // @see https://github.com/IDPF/epubcheck/issues/586, https://github.com/IDPF/epubcheck/pull/633 unset( $output[ $k ] ); } elseif ( strpos( $v, 'non-standard font type application/font-sfnt' ) !== false ) { // @see https://github.com/w3c/epubcheck/issues/339 unset( $output[ $k ] ); } } // Is this a valid Epub? if ( ! empty( $output ) ) { $this->logError( implode( "\n", $output ) ); throw new \Exception(); } yield 90 => $this->generatorPrefix . __( 'Validation successful', 'pressbooks' ); yield 100 => $this->generatorPrefix . __( 'Finishing up', 'pressbooks' ); }
php
public function validateGenerator() : \Generator { yield 80 => $this->generatorPrefix . __( 'Validating file', 'pressbooks' ); // Epubcheck command, (quiet flag requires version 3.0.1+) $command = PB_EPUBCHECK_COMMAND . ' -q ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); foreach ( $output as $k => $v ) { if ( strpos( $v, 'Picked up _JAVA_OPTIONS:' ) !== false ) { // Remove JAVA warnings that are not actually errors unset( $output[ $k ] ); } elseif ( strpos( $v, 'non-standard font type application/x-font-ttf' ) !== false ) { // @see https://github.com/IDPF/epubcheck/issues/586, https://github.com/IDPF/epubcheck/pull/633 unset( $output[ $k ] ); } elseif ( strpos( $v, 'non-standard font type application/font-sfnt' ) !== false ) { // @see https://github.com/w3c/epubcheck/issues/339 unset( $output[ $k ] ); } } // Is this a valid Epub? if ( ! empty( $output ) ) { $this->logError( implode( "\n", $output ) ); throw new \Exception(); } yield 90 => $this->generatorPrefix . __( 'Validation successful', 'pressbooks' ); yield 100 => $this->generatorPrefix . __( 'Finishing up', 'pressbooks' ); }
[ "public", "function", "validateGenerator", "(", ")", ":", "\\", "Generator", "{", "yield", "80", "=>", "$", "this", "->", "generatorPrefix", ".", "__", "(", "'Validating file'", ",", "'pressbooks'", ")", ";", "// Epubcheck command, (quiet flag requires version 3.0.1+)...
Yields an estimated percentage slice of: 80 to 100 @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "80", "to", "100" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L354-L386
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.mediaType
function mediaType( $file ) { $mime = static::mimeType( $file ); $mime = explode( ';', $mime ); $mime = trim( $mime[0] ); return $mime; }
php
function mediaType( $file ) { $mime = static::mimeType( $file ); $mime = explode( ';', $mime ); $mime = trim( $mime[0] ); return $mime; }
[ "function", "mediaType", "(", "$", "file", ")", "{", "$", "mime", "=", "static", "::", "mimeType", "(", "$", "file", ")", ";", "$", "mime", "=", "explode", "(", "';'", ",", "$", "mime", ")", ";", "$", "mime", "=", "trim", "(", "$", "mime", "[",...
Override mimeType, get rid of '; charset=binary' @param string $file @return mixed|string
[ "Override", "mimeType", "get", "rid", "of", ";", "charset", "=", "binary" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L418-L425
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.themeOptionsOverrides
protected function themeOptionsOverrides() { // -------------------------------------------------------------------- // CSS $css = ''; $this->cssOverrides = apply_filters( 'pb_epub_css_override', $css ) . "\n"; // -------------------------------------------------------------------- // Hacks $hacks = []; $hacks = apply_filters( 'pb_epub_hacks', $hacks ); // Display chapter numbers? if ( isset( $hacks['chapter_numbers'] ) && $hacks['chapter_numbers'] ) { $this->numbered = true; } else { $this->numbered = false; } if ( isset( $hacks['ebook_compress_images'] ) && $hacks['ebook_compress_images'] ) { $this->compressImages = true; } }
php
protected function themeOptionsOverrides() { // -------------------------------------------------------------------- // CSS $css = ''; $this->cssOverrides = apply_filters( 'pb_epub_css_override', $css ) . "\n"; // -------------------------------------------------------------------- // Hacks $hacks = []; $hacks = apply_filters( 'pb_epub_hacks', $hacks ); // Display chapter numbers? if ( isset( $hacks['chapter_numbers'] ) && $hacks['chapter_numbers'] ) { $this->numbered = true; } else { $this->numbered = false; } if ( isset( $hacks['ebook_compress_images'] ) && $hacks['ebook_compress_images'] ) { $this->compressImages = true; } }
[ "protected", "function", "themeOptionsOverrides", "(", ")", "{", "// --------------------------------------------------------------------", "// CSS", "$", "css", "=", "''", ";", "$", "this", "->", "cssOverrides", "=", "apply_filters", "(", "'pb_epub_css_override'", ",", "...
Override based on Theme Options
[ "Override", "based", "on", "Theme", "Options" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L431-L456
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.tidy
protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed $html = \Pressbooks\Interactive\Content::init()->replaceInteractiveTags( $html ); $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'deny_attribute' => 'itemscope,itemtype,itemref,itemprop,data*,aria*', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, 'comment' => 1, ]; $spec = ''; $spec .= 'img=-longdesc,-srcset;'; $spec .= 'table=-border;'; // Reset on each htmLawed invocation unset( $GLOBALS['hl_Ids'] ); if ( ! empty( $this->fixme ) ) { $GLOBALS['hl_Ids'] = $this->fixme; } return \Pressbooks\HtmLawed::filter( $html, $config, $spec ); }
php
protected function tidy( $html ) { // Make XHTML 1.1 strict using htmlLawed $html = \Pressbooks\Interactive\Content::init()->replaceInteractiveTags( $html ); $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'deny_attribute' => 'itemscope,itemtype,itemref,itemprop,data*,aria*', 'hook' => '\Pressbooks\Sanitize\html5_to_xhtml11', 'tidy' => -1, 'comment' => 1, ]; $spec = ''; $spec .= 'img=-longdesc,-srcset;'; $spec .= 'table=-border;'; // Reset on each htmLawed invocation unset( $GLOBALS['hl_Ids'] ); if ( ! empty( $this->fixme ) ) { $GLOBALS['hl_Ids'] = $this->fixme; } return \Pressbooks\HtmLawed::filter( $html, $config, $spec ); }
[ "protected", "function", "tidy", "(", "$", "html", ")", "{", "// Make XHTML 1.1 strict using htmlLawed", "$", "html", "=", "\\", "Pressbooks", "\\", "Interactive", "\\", "Content", "::", "init", "(", ")", "->", "replaceInteractiveTags", "(", "$", "html", ")", ...
Tidy HTML @param string $html @return string
[ "Tidy", "HTML" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L539-L566
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.html5ToXhtml
protected function html5ToXhtml( $html ) { $config = [ 'valid_xhtml' => 1, 'unique_ids' => 0, ]; $html = \Pressbooks\HtmLawed::filter( $html, $config ); return $html; }
php
protected function html5ToXhtml( $html ) { $config = [ 'valid_xhtml' => 1, 'unique_ids' => 0, ]; $html = \Pressbooks\HtmLawed::filter( $html, $config ); return $html; }
[ "protected", "function", "html5ToXhtml", "(", "$", "html", ")", "{", "$", "config", "=", "[", "'valid_xhtml'", "=>", "1", ",", "'unique_ids'", "=>", "0", ",", "]", ";", "$", "html", "=", "\\", "Pressbooks", "\\", "HtmLawed", "::", "filter", "(", "$", ...
Clean up content processed by HTML5 Parser, change it back into XHTML @param $html @return string
[ "Clean", "up", "content", "processed", "by", "HTML5", "Parser", "change", "it", "back", "into", "XHTML" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L575-L582
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.zipEpub
protected function zipEpub( $filename ) { $zip = new \PclZip( $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 === absint( $list ) ) { return false; } $files = []; foreach ( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $this->tmpDir ) ) as $file ) { if ( ! $file->isFile() ) { continue; } if ( 'mimetype' === $file->getFilename() ) { continue; } $files[] = $file->getPathname(); } $list = $zip->add( $files, '', $this->tmpDir ); if ( 0 === absint( $list ) ) { return false; } return true; }
php
protected function zipEpub( $filename ) { $zip = new \PclZip( $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 === absint( $list ) ) { return false; } $files = []; foreach ( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $this->tmpDir ) ) as $file ) { if ( ! $file->isFile() ) { continue; } if ( 'mimetype' === $file->getFilename() ) { continue; } $files[] = $file->getPathname(); } $list = $zip->add( $files, '', $this->tmpDir ); if ( 0 === absint( $list ) ) { return false; } return true; }
[ "protected", "function", "zipEpub", "(", "$", "filename", ")", "{", "$", "zip", "=", "new", "\\", "PclZip", "(", "$", "filename", ")", ";", "// Open Publication Structure 2.0.1", "// mimetype must be uncompressed, unencrypted, and the first file in the ZIP archive", "$", ...
Zip the contents of an EPUB following the conventions outlined in Open Publication Structure 2.0.1 @param $filename @return bool
[ "Zip", "the", "contents", "of", "an", "EPUB", "following", "the", "conventions", "outlined", "in", "Open", "Publication", "Structure", "2", ".", "0", ".", "1" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L603-L631
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createContainer
protected function createContainer() { \Pressbooks\Utility\put_contents( $this->tmpDir . '/mimetype', utf8_decode( 'application/epub+zip' ) ); mkdir( $this->tmpDir . '/META-INF' ); mkdir( $this->tmpDir . '/OEBPS' ); mkdir( $this->tmpDir . '/OEBPS/assets' ); \Pressbooks\Utility\put_contents( $this->tmpDir . '/META-INF/container.xml', $this->loadTemplate( $this->dir . '/templates/epub201/container.php' ) ); \Pressbooks\Utility\put_contents( $this->tmpDir . '/META-INF/com.apple.ibooks.display-options.xml', $this->loadTemplate( $this->dir . '/templates/epub201/ibooks.php' ) ); }
php
protected function createContainer() { \Pressbooks\Utility\put_contents( $this->tmpDir . '/mimetype', utf8_decode( 'application/epub+zip' ) ); mkdir( $this->tmpDir . '/META-INF' ); mkdir( $this->tmpDir . '/OEBPS' ); mkdir( $this->tmpDir . '/OEBPS/assets' ); \Pressbooks\Utility\put_contents( $this->tmpDir . '/META-INF/container.xml', $this->loadTemplate( $this->dir . '/templates/epub201/container.php' ) ); \Pressbooks\Utility\put_contents( $this->tmpDir . '/META-INF/com.apple.ibooks.display-options.xml', $this->loadTemplate( $this->dir . '/templates/epub201/ibooks.php' ) ); }
[ "protected", "function", "createContainer", "(", ")", "{", "\\", "Pressbooks", "\\", "Utility", "\\", "put_contents", "(", "$", "this", "->", "tmpDir", ".", "'/mimetype'", ",", "utf8_decode", "(", "'application/epub+zip'", ")", ")", ";", "mkdir", "(", "$", "...
Create Open Publication Structure 2.0.1 container.
[ "Create", "Open", "Publication", "Structure", "2", ".", "0", ".", "1", "container", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L637-L658
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createOEBPSGenerator
protected function createOEBPSGenerator( $book_contents, $metadata ) : \Generator { // First, setup and affect $this->stylesheet yield 10 => $this->generatorPrefix . __( 'Compiling styles', 'pressbooks' ); $this->createStylesheet(); // Reset manifest $this->manifest = []; /* Note: order affects $this->manifest */ // Cover yield 15 => $this->generatorPrefix . __( 'Creating cover', 'pressbooks' ); $this->createCover( $book_contents, $metadata ); // Before Title Page $this->createBeforeTitle( $book_contents, $metadata ); // Title yield 20 => $this->generatorPrefix . __( 'Creating title page', 'pressbooks' ); $this->createTitle( $book_contents, $metadata ); // Copyright yield 20 => $this->generatorPrefix . __( 'Creating copyright page', 'pressbooks' ); $this->createCopyright( $book_contents, $metadata ); // Dedication and Epigraph (In that order!) yield 25 => $this->generatorPrefix . __( 'Exporting dedication and epigraph', 'pressbooks' ); $this->createDedicationAndEpigraph( $book_contents, $metadata ); // Front-matter yield 30 => $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ); yield from $this->createFrontMatterGenerator( $book_contents, $metadata ); // Promo $this->createPromo( $book_contents, $metadata ); // Parts, Chapters yield 40 => $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ); yield from $this->createPartsAndChaptersGenerator( $book_contents, $metadata ); // Back-matter yield 50 => $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ); yield from $this->createBackMatterGenerator( $book_contents, $metadata ); // Table of contents // IMPORTANT: Do this last! Uses $this->manifest to generate itself yield 70 => $this->generatorPrefix . __( 'Creating table of contents', 'pressbooks' ); $this->createToc( $book_contents, $metadata ); }
php
protected function createOEBPSGenerator( $book_contents, $metadata ) : \Generator { // First, setup and affect $this->stylesheet yield 10 => $this->generatorPrefix . __( 'Compiling styles', 'pressbooks' ); $this->createStylesheet(); // Reset manifest $this->manifest = []; /* Note: order affects $this->manifest */ // Cover yield 15 => $this->generatorPrefix . __( 'Creating cover', 'pressbooks' ); $this->createCover( $book_contents, $metadata ); // Before Title Page $this->createBeforeTitle( $book_contents, $metadata ); // Title yield 20 => $this->generatorPrefix . __( 'Creating title page', 'pressbooks' ); $this->createTitle( $book_contents, $metadata ); // Copyright yield 20 => $this->generatorPrefix . __( 'Creating copyright page', 'pressbooks' ); $this->createCopyright( $book_contents, $metadata ); // Dedication and Epigraph (In that order!) yield 25 => $this->generatorPrefix . __( 'Exporting dedication and epigraph', 'pressbooks' ); $this->createDedicationAndEpigraph( $book_contents, $metadata ); // Front-matter yield 30 => $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ); yield from $this->createFrontMatterGenerator( $book_contents, $metadata ); // Promo $this->createPromo( $book_contents, $metadata ); // Parts, Chapters yield 40 => $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ); yield from $this->createPartsAndChaptersGenerator( $book_contents, $metadata ); // Back-matter yield 50 => $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ); yield from $this->createBackMatterGenerator( $book_contents, $metadata ); // Table of contents // IMPORTANT: Do this last! Uses $this->manifest to generate itself yield 70 => $this->generatorPrefix . __( 'Creating table of contents', 'pressbooks' ); $this->createToc( $book_contents, $metadata ); }
[ "protected", "function", "createOEBPSGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "// First, setup and affect $this->stylesheet", "yield", "10", "=>", "$", "this", "->", "generatorPrefix", ".", "__", "(", "'Compiling...
Yields an estimated percentage slice of: 10 to 75 Create OEBPS/* files. @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "10", "to", "75", "Create", "OEBPS", "/", "*", "files", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L668-L717
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createStylesheet
protected function createStylesheet() { $this->stylesheet = strtolower( sanitize_file_name( wp_get_theme() . '.css' ) ); $path_to_tmp_stylesheet = $this->tmpDir . "/OEBPS/{$this->stylesheet}"; // Copy stylesheet \Pressbooks\Utility\put_contents( $path_to_tmp_stylesheet, $this->loadTemplate( $this->exportStylePath ) ); $this->scrapeKneadAndSaveCss( $this->exportStylePath, $path_to_tmp_stylesheet ); }
php
protected function createStylesheet() { $this->stylesheet = strtolower( sanitize_file_name( wp_get_theme() . '.css' ) ); $path_to_tmp_stylesheet = $this->tmpDir . "/OEBPS/{$this->stylesheet}"; // Copy stylesheet \Pressbooks\Utility\put_contents( $path_to_tmp_stylesheet, $this->loadTemplate( $this->exportStylePath ) ); $this->scrapeKneadAndSaveCss( $this->exportStylePath, $path_to_tmp_stylesheet ); }
[ "protected", "function", "createStylesheet", "(", ")", "{", "$", "this", "->", "stylesheet", "=", "strtolower", "(", "sanitize_file_name", "(", "wp_get_theme", "(", ")", ".", "'.css'", ")", ")", ";", "$", "path_to_tmp_stylesheet", "=", "$", "this", "->", "tm...
Create stylesheet. Change $this->stylesheet to a filename used by subsequent methods.
[ "Create", "stylesheet", ".", "Change", "$this", "-", ">", "stylesheet", "to", "a", "filename", "used", "by", "subsequent", "methods", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L723-L735
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.scrapeKneadAndSaveCss
protected function scrapeKneadAndSaveCss( $path_to_original_stylesheet, $path_to_copy_of_stylesheet ) { $styles = Container::get( 'Styles' ); $scss = \Pressbooks\Utility\get_contents( $path_to_copy_of_stylesheet ); if ( $this->extraCss ) { $scss .= "\n" . $this->loadTemplate( $this->extraCss ); } $custom_styles = $styles->getEpubPost(); if ( $custom_styles && ! empty( $custom_styles->post_content ) ) { // append the user's custom styles to the theme stylesheet prior to compilation $scss .= "\n" . $custom_styles->post_content; } $css = $styles->customize( 'epub', $scss, $this->cssOverrides ); $scss_dir = pathinfo( $path_to_original_stylesheet, PATHINFO_DIRNAME ); $path_to_epub_assets = $this->tmpDir . '/OEBPS/assets'; $css = $this->normalizeCssUrls( $css, $scss_dir, $path_to_epub_assets ); // Overwrite the new file with new info \Pressbooks\Utility\put_contents( $path_to_copy_of_stylesheet, $css ); if ( WP_DEBUG ) { Container::get( 'Sass' )->debug( $css, $scss, 'epub' ); } }
php
protected function scrapeKneadAndSaveCss( $path_to_original_stylesheet, $path_to_copy_of_stylesheet ) { $styles = Container::get( 'Styles' ); $scss = \Pressbooks\Utility\get_contents( $path_to_copy_of_stylesheet ); if ( $this->extraCss ) { $scss .= "\n" . $this->loadTemplate( $this->extraCss ); } $custom_styles = $styles->getEpubPost(); if ( $custom_styles && ! empty( $custom_styles->post_content ) ) { // append the user's custom styles to the theme stylesheet prior to compilation $scss .= "\n" . $custom_styles->post_content; } $css = $styles->customize( 'epub', $scss, $this->cssOverrides ); $scss_dir = pathinfo( $path_to_original_stylesheet, PATHINFO_DIRNAME ); $path_to_epub_assets = $this->tmpDir . '/OEBPS/assets'; $css = $this->normalizeCssUrls( $css, $scss_dir, $path_to_epub_assets ); // Overwrite the new file with new info \Pressbooks\Utility\put_contents( $path_to_copy_of_stylesheet, $css ); if ( WP_DEBUG ) { Container::get( 'Sass' )->debug( $css, $scss, 'epub' ); } }
[ "protected", "function", "scrapeKneadAndSaveCss", "(", "$", "path_to_original_stylesheet", ",", "$", "path_to_copy_of_stylesheet", ")", "{", "$", "styles", "=", "Container", "::", "get", "(", "'Styles'", ")", ";", "$", "scss", "=", "\\", "Pressbooks", "\\", "Uti...
Parse CSS, copy assets, rewrite copy. @param string $path_to_original_stylesheet * @param string $path_to_copy_of_stylesheet
[ "Parse", "CSS", "copy", "assets", "rewrite", "copy", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L744-L773
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.normalizeCssUrls
protected function normalizeCssUrls( $css, $scss_dir, $path_to_epub_assets ) { $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; $css = preg_replace_callback( $url_regex, function ( $matches ) use ( $scss_dir, $path_to_epub_assets ) { $buckram_dir = get_theme_root( 'pressbooks-book' ) . '/pressbooks-book/packages/buckram/assets'; $typography_dir = get_theme_root( 'pressbooks-book' ) . '/pressbooks-book/assets/book/typography'; $url = $matches[3]; $filename = sanitize_file_name( basename( $url ) ); // Look for images in Buckram if ( preg_match( '#^pressbooks-book/assets/book/images/[a-zA-Z0-9_-]+(' . $this->supportedImageExtensions . ')$#i', $url ) ) { $url = str_replace( 'pressbooks-book/assets/book/', '', $url ); $my_image = realpath( "$buckram_dir/$url" ); if ( $my_image ) { copy( $my_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^images/[a-zA-Z0-9_-]+(' . $this->supportedImageExtensions . ')$#i', $url ) ) { $my_image = realpath( "$buckram_dir/$url" ); if ( $my_image ) { copy( $my_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } else { // This is not a Buckram theme, maybe. $my_legacy_image = realpath( "$scss_dir/$url" ); if ( $my_legacy_image ) { copy( $my_legacy_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } } elseif ( 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/" $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 $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 $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 ) ) { // Update themes-book/pressbooks-book/fonts/*.ttf (or .otf) path to new location, copy into our Epub $url = str_replace( 'themes-book/pressbooks-book/', trailingslashit( $typography_dir ), $url ); $my_font = realpath( $url ); if ( $my_font ) { copy( $my_font, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { // Look for wp-content/themes/pressbooks-book/assets/typography/fonts/*.ttf (or .otf), copy into our Epub $my_font = realpath( "$typography_dir/$url" ); if ( $my_font ) { copy( $my_font, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { // Look for wp-content/uploads/assets/typography/fonts/*.ttf (or .otf), copy into our Epub $my_font = realpath( WP_CONTENT_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 $new_filename = $this->fetchAndSaveUniqueFont( $url, $path_to_epub_assets ); if ( $new_filename ) { return "url(assets/$new_filename)"; } } return $matches[0]; // No change }, $css ); return $css; }
php
protected function normalizeCssUrls( $css, $scss_dir, $path_to_epub_assets ) { $url_regex = '/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i'; $css = preg_replace_callback( $url_regex, function ( $matches ) use ( $scss_dir, $path_to_epub_assets ) { $buckram_dir = get_theme_root( 'pressbooks-book' ) . '/pressbooks-book/packages/buckram/assets'; $typography_dir = get_theme_root( 'pressbooks-book' ) . '/pressbooks-book/assets/book/typography'; $url = $matches[3]; $filename = sanitize_file_name( basename( $url ) ); // Look for images in Buckram if ( preg_match( '#^pressbooks-book/assets/book/images/[a-zA-Z0-9_-]+(' . $this->supportedImageExtensions . ')$#i', $url ) ) { $url = str_replace( 'pressbooks-book/assets/book/', '', $url ); $my_image = realpath( "$buckram_dir/$url" ); if ( $my_image ) { copy( $my_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^images/[a-zA-Z0-9_-]+(' . $this->supportedImageExtensions . ')$#i', $url ) ) { $my_image = realpath( "$buckram_dir/$url" ); if ( $my_image ) { copy( $my_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } else { // This is not a Buckram theme, maybe. $my_legacy_image = realpath( "$scss_dir/$url" ); if ( $my_legacy_image ) { copy( $my_legacy_image, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } } elseif ( 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/" $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 $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 $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 ) ) { // Update themes-book/pressbooks-book/fonts/*.ttf (or .otf) path to new location, copy into our Epub $url = str_replace( 'themes-book/pressbooks-book/', trailingslashit( $typography_dir ), $url ); $my_font = realpath( $url ); if ( $my_font ) { copy( $my_font, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { // Look for wp-content/themes/pressbooks-book/assets/typography/fonts/*.ttf (or .otf), copy into our Epub $my_font = realpath( "$typography_dir/$url" ); if ( $my_font ) { copy( $my_font, "$path_to_epub_assets/$filename" ); return "url(assets/$filename)"; } } elseif ( preg_match( '#^uploads/assets/fonts/[a-zA-Z0-9_-]+(' . $this->supportedFontExtensions . ')$#i', $url ) ) { // Look for wp-content/uploads/assets/typography/fonts/*.ttf (or .otf), copy into our Epub $my_font = realpath( WP_CONTENT_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 $new_filename = $this->fetchAndSaveUniqueFont( $url, $path_to_epub_assets ); if ( $new_filename ) { return "url(assets/$new_filename)"; } } return $matches[0]; // No change }, $css ); return $css; }
[ "protected", "function", "normalizeCssUrls", "(", "$", "css", ",", "$", "scss_dir", ",", "$", "path_to_epub_assets", ")", "{", "$", "url_regex", "=", "'/url\\(([\\s])?([\\\"|\\'])?(.*?)([\\\"|\\'])?([\\s])?\\)/i'", ";", "$", "css", "=", "preg_replace_callback", "(", "...
Search for all possible permutations of CSS url syntax -- url("*"), url('*'), and url(*) -- and update URLs as needed. @param string $css The EPUB's (S)CSS content. @param string $scss_dir The directory which contains the theme's SCSS files. No trailing slash. @param string $path_to_epub_assets The EPUB's assets directory. No trailing slash, @return string
[ "Search", "for", "all", "possible", "permutations", "of", "CSS", "url", "syntax", "--", "url", "(", "*", ")", "url", "(", "*", ")", "and", "url", "(", "*", ")", "--", "and", "update", "URLs", "as", "needed", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L784-L888
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createFrontMatterGenerator
protected function createFrontMatterGenerator( $book_contents, $metadata ) : \Generator { $front_matter_printf = '<div class="front-matter %1$s" id="%2$s">'; $front_matter_printf .= '<div class="front-matter-title-wrap"><h3 class="front-matter-number">%3$s</h3><h1 class="front-matter-title">%4$s</h1>%5$s</div>'; $front_matter_printf .= '<div class="ugc front-matter-ugc">%6$s</div>%7$s'; $front_matter_printf .= '</div>'; $y = new PercentageYield( 30, 40, count( $book_contents['front-matter'] ) ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_front_matter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; $i = $this->frontMatterPos; foreach ( $book_contents['front-matter'] as $front_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ) ); if ( ! $front_matter['export'] ) { continue; // Skip } $front_matter_id = $front_matter['ID']; $subclass = $this->taxonomy->getFrontMatterType( $front_matter_id ); if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } $slug = $front_matter['post_name']; $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $front_matter['post_content'], 'front-matter', $i ); $append_front_matter_content = $this->kneadHtml( apply_filters( 'pb_append_front_matter_content', '', $front_matter_id ), 'front-matter', $i ); $short_title = trim( get_post_meta( $front_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $front_matter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $front_matter_id ) !== false ) { $content = Book::tagSubsections( $content, $front_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $section_license = $this->doSectionLevelLicense( $metadata, $front_matter_id ); if ( $section_license ) { $append_front_matter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'front-matter', $i ); } $vars['post_title'] = $front_matter['post_title']; $vars['post_content'] = sprintf( $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $after_title, $content, $var['append_front_matter_content'] = $append_front_matter_content, '' ); $file_id = 'front-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $front_matter['ID'], 'post_title' => $front_matter['post_title'], 'filename' => $filename, ]; ++$i; } $this->frontMatterPos = $i; }
php
protected function createFrontMatterGenerator( $book_contents, $metadata ) : \Generator { $front_matter_printf = '<div class="front-matter %1$s" id="%2$s">'; $front_matter_printf .= '<div class="front-matter-title-wrap"><h3 class="front-matter-number">%3$s</h3><h1 class="front-matter-title">%4$s</h1>%5$s</div>'; $front_matter_printf .= '<div class="ugc front-matter-ugc">%6$s</div>%7$s'; $front_matter_printf .= '</div>'; $y = new PercentageYield( 30, 40, count( $book_contents['front-matter'] ) ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_front_matter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; $i = $this->frontMatterPos; foreach ( $book_contents['front-matter'] as $front_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ) ); if ( ! $front_matter['export'] ) { continue; // Skip } $front_matter_id = $front_matter['ID']; $subclass = $this->taxonomy->getFrontMatterType( $front_matter_id ); if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } $slug = $front_matter['post_name']; $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $front_matter['post_content'], 'front-matter', $i ); $append_front_matter_content = $this->kneadHtml( apply_filters( 'pb_append_front_matter_content', '', $front_matter_id ), 'front-matter', $i ); $short_title = trim( get_post_meta( $front_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $front_matter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $front_matter_id ) !== false ) { $content = Book::tagSubsections( $content, $front_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $section_license = $this->doSectionLevelLicense( $metadata, $front_matter_id ); if ( $section_license ) { $append_front_matter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'front-matter', $i ); } $vars['post_title'] = $front_matter['post_title']; $vars['post_content'] = sprintf( $front_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $after_title, $content, $var['append_front_matter_content'] = $append_front_matter_content, '' ); $file_id = 'front-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $front_matter['ID'], 'post_title' => $front_matter['post_title'], 'filename' => $filename, ]; ++$i; } $this->frontMatterPos = $i; }
[ "protected", "function", "createFrontMatterGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "front_matter_printf", "=", "'<div class=\"front-matter %1$s\" id=\"%2$s\">'", ";", "$", "front_matter_printf", ".=", "'<div clas...
Yields an estimated percentage slice of: 30-40 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "30", "-", "40" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1267-L1379
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createPartsAndChaptersGenerator
protected function createPartsAndChaptersGenerator( $book_contents, $metadata ) : \Generator { $part_printf = '<div class="part %1$s" id="%2$s">'; $part_printf .= '<div class="part-title-wrap"><h3 class="part-number">%3$s</h3><h1 class="part-title">%4$s</h1></div>%5$s'; $part_printf .= '</div>'; $chapter_printf = '<div class="chapter %1$s" id="%2$s">'; $chapter_printf .= '<div class="chapter-title-wrap"><h3 class="chapter-number">%3$s</h3><h2 class="chapter-title">%4$s</h2>%5$s</div>'; $chapter_printf .= '<div class="ugc chapter-ugc">%6$s</div>%7$s'; $chapter_printf .= '</div>'; $ticks = 0; foreach ( $book_contents['part'] as $key => $part ) { $ticks = $ticks + 1 + count( $book_contents['part'][ $key ]['chapters'] ); } $y = new PercentageYield( 40, 50, $ticks ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_chapter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; // Parts, Chapters $i = 1; $j = 1; $c = 1; $p = 1; foreach ( $book_contents['part'] as $part ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $array_pos = count( $this->manifest ); $has_chapters = false; // Inject introduction class? if ( ! $this->hasIntroduction && count( $book_contents['part'] ) > 1 ) { $part_printf_changed = str_replace( '<div class="part %s" id=', '<div class="part introduction %s" id=', $part_printf ); $this->hasIntroduction = true; } // Inject part content? $part_content = trim( $part['post_content'] ); if ( $part_content ) { $part_content = $this->kneadHtml( $this->preProcessPostContent( $part_content ), 'custom', $p ); $part_printf_changed = str_replace( '</h1></div>%5$s</div>', '</h1></div><div class="ugc part-ugc">%5$s</div></div>', $part_printf ); } foreach ( $part['chapters'] as $chapter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); if ( ! $chapter['export'] ) { continue; // Skip } $chapter_printf_changed = ''; $chapter_id = $chapter['ID']; $subclass = $this->taxonomy->getChapterType( $chapter_id ); $slug = $chapter['post_name']; $title = ( get_post_meta( $chapter_id, 'pb_show_title', true ) ? $chapter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $chapter['post_content'], 'chapter', $j ); $append_chapter_content = $this->kneadHtml( apply_filters( 'pb_append_chapter_content', '', $chapter_id ), 'chapter', $j ); $short_title = false; // Ie. running header title is not used in EPUB $subtitle = trim( get_post_meta( $chapter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $chapter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $chapter_id ) !== false ) { $content = Book::tagSubsections( $content, $chapter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } // Inject introduction class? if ( ! $this->hasIntroduction ) { $subclass .= ' introduction'; $this->hasIntroduction = true; } $section_license = $this->doSectionLevelLicense( $metadata, $chapter_id ); if ( $section_license ) { $append_chapter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'chapter', $j ); } $my_chapter_number = ( strpos( $subclass, 'numberless' ) === false ) ? $c : ''; $vars['post_title'] = $chapter['post_title']; $vars['post_content'] = sprintf( $chapter_printf, $subclass, $slug, ( $this->numbered ? $my_chapter_number : '' ), Sanitize\decode( $title ), $after_title, $content, $var['append_chapter_content'] = $append_chapter_content, '' ); $file_id = 'chapter-' . sprintf( '%03s', $j ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $chapter['ID'], 'post_title' => $chapter['post_title'], 'filename' => $filename, ]; $has_chapters = true; $j++; if ( $my_chapter_number !== '' ) { ++$c; } } if ( count( $book_contents['part'] ) === 1 && $part_content ) { // only part, has content $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( $has_chapters ) { // has chapter $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } else { // no chapter if ( $part_content ) { // has content $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } } } // Did we actually inject the introduction class? if ( $part_printf_changed && ! $has_chapters ) { $this->hasIntroduction = false; } } }
php
protected function createPartsAndChaptersGenerator( $book_contents, $metadata ) : \Generator { $part_printf = '<div class="part %1$s" id="%2$s">'; $part_printf .= '<div class="part-title-wrap"><h3 class="part-number">%3$s</h3><h1 class="part-title">%4$s</h1></div>%5$s'; $part_printf .= '</div>'; $chapter_printf = '<div class="chapter %1$s" id="%2$s">'; $chapter_printf .= '<div class="chapter-title-wrap"><h3 class="chapter-number">%3$s</h3><h2 class="chapter-title">%4$s</h2>%5$s</div>'; $chapter_printf .= '<div class="ugc chapter-ugc">%6$s</div>%7$s'; $chapter_printf .= '</div>'; $ticks = 0; foreach ( $book_contents['part'] as $key => $part ) { $ticks = $ticks + 1 + count( $book_contents['part'][ $key ]['chapters'] ); } $y = new PercentageYield( 40, 50, $ticks ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_chapter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; // Parts, Chapters $i = 1; $j = 1; $c = 1; $p = 1; foreach ( $book_contents['part'] as $part ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $array_pos = count( $this->manifest ); $has_chapters = false; // Inject introduction class? if ( ! $this->hasIntroduction && count( $book_contents['part'] ) > 1 ) { $part_printf_changed = str_replace( '<div class="part %s" id=', '<div class="part introduction %s" id=', $part_printf ); $this->hasIntroduction = true; } // Inject part content? $part_content = trim( $part['post_content'] ); if ( $part_content ) { $part_content = $this->kneadHtml( $this->preProcessPostContent( $part_content ), 'custom', $p ); $part_printf_changed = str_replace( '</h1></div>%5$s</div>', '</h1></div><div class="ugc part-ugc">%5$s</div></div>', $part_printf ); } foreach ( $part['chapters'] as $chapter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); if ( ! $chapter['export'] ) { continue; // Skip } $chapter_printf_changed = ''; $chapter_id = $chapter['ID']; $subclass = $this->taxonomy->getChapterType( $chapter_id ); $slug = $chapter['post_name']; $title = ( get_post_meta( $chapter_id, 'pb_show_title', true ) ? $chapter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $chapter['post_content'], 'chapter', $j ); $append_chapter_content = $this->kneadHtml( apply_filters( 'pb_append_chapter_content', '', $chapter_id ), 'chapter', $j ); $short_title = false; // Ie. running header title is not used in EPUB $subtitle = trim( get_post_meta( $chapter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $chapter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $chapter_id ) !== false ) { $content = Book::tagSubsections( $content, $chapter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } // Inject introduction class? if ( ! $this->hasIntroduction ) { $subclass .= ' introduction'; $this->hasIntroduction = true; } $section_license = $this->doSectionLevelLicense( $metadata, $chapter_id ); if ( $section_license ) { $append_chapter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'chapter', $j ); } $my_chapter_number = ( strpos( $subclass, 'numberless' ) === false ) ? $c : ''; $vars['post_title'] = $chapter['post_title']; $vars['post_content'] = sprintf( $chapter_printf, $subclass, $slug, ( $this->numbered ? $my_chapter_number : '' ), Sanitize\decode( $title ), $after_title, $content, $var['append_chapter_content'] = $append_chapter_content, '' ); $file_id = 'chapter-' . sprintf( '%03s', $j ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $chapter['ID'], 'post_title' => $chapter['post_title'], 'filename' => $filename, ]; $has_chapters = true; $j++; if ( $my_chapter_number !== '' ) { ++$c; } } if ( count( $book_contents['part'] ) === 1 && $part_content ) { // only part, has content $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( $has_chapters ) { // has chapter $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } else { // no chapter if ( $part_content ) { // has content $slug = $part['post_name']; $m = ( 'invisible' === $invisibility ) ? '' : $p; $vars['post_title'] = $part['post_title']; $vars['post_content'] = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, ( $this->numbered ? \Pressbooks\L10n\romanize( $m ) : '' ), Sanitize\decode( $part['post_title'] ), $part_content ); $file_id = 'part-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); // Insert into correct pos $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; } } } } // Did we actually inject the introduction class? if ( $part_printf_changed && ! $has_chapters ) { $this->hasIntroduction = false; } } }
[ "protected", "function", "createPartsAndChaptersGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "part_printf", "=", "'<div class=\"part %1$s\" id=\"%2$s\">'", ";", "$", "part_printf", ".=", "'<div class=\"part-title-wrap...
Yields an estimated percentage slice of: 40-50 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "40", "-", "50" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1423-L1686
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createBackMatterGenerator
protected function createBackMatterGenerator( $book_contents, $metadata ) : \Generator { $back_matter_printf = '<div class="back-matter %1$s" id="%2$s">'; $back_matter_printf .= '<div class="back-matter-title-wrap"><h3 class="back-matter-number">%3$s</h3><h1 class="back-matter-title">%4$s</h1>%5$s</div>'; $back_matter_printf .= '<div class="ugc back-matter-ugc">%6$s</div>%7$s'; $back_matter_printf .= '</div>'; $y = new PercentageYield( 50, 70, count( $book_contents['back-matter'] ) ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_back_matter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; $i = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ) ); if ( ! $back_matter['export'] ) { continue; // Skip } $back_matter_id = $back_matter['ID']; $subclass = $this->taxonomy->getBackMatterType( $back_matter_id ); $slug = $back_matter['post_name']; $title = ( get_post_meta( $back_matter_id, 'pb_show_title', true ) ? $back_matter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $back_matter['post_content'], 'back-matter', $i ); $append_back_matter_content = $this->kneadHtml( apply_filters( 'pb_append_back_matter_content', '', $back_matter_id ), 'back-matter', $i ); $short_title = trim( get_post_meta( $back_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $back_matter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $back_matter_id ) !== false ) { $content = Book::tagSubsections( $content, $back_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $section_license = $this->doSectionLevelLicense( $metadata, $back_matter_id ); if ( $section_license ) { $append_back_matter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'back-matter', $i ); } $vars['post_title'] = $back_matter['post_title']; $vars['post_content'] = sprintf( $back_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $after_title, $content, $var['append_back_matter_content'] = $append_back_matter_content, '' ); $file_id = 'back-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $back_matter['ID'], 'post_title' => $back_matter['post_title'], 'filename' => $filename, ]; ++$i; } }
php
protected function createBackMatterGenerator( $book_contents, $metadata ) : \Generator { $back_matter_printf = '<div class="back-matter %1$s" id="%2$s">'; $back_matter_printf .= '<div class="back-matter-title-wrap"><h3 class="back-matter-number">%3$s</h3><h1 class="back-matter-title">%4$s</h1>%5$s</div>'; $back_matter_printf .= '<div class="ugc back-matter-ugc">%6$s</div>%7$s'; $back_matter_printf .= '</div>'; $y = new PercentageYield( 50, 70, count( $book_contents['back-matter'] ) ); $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'append_back_matter_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; $i = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ) ); if ( ! $back_matter['export'] ) { continue; // Skip } $back_matter_id = $back_matter['ID']; $subclass = $this->taxonomy->getBackMatterType( $back_matter_id ); $slug = $back_matter['post_name']; $title = ( get_post_meta( $back_matter_id, 'pb_show_title', true ) ? $back_matter['post_title'] : '' ); $after_title = ''; $content = $this->kneadHtml( $back_matter['post_content'], 'back-matter', $i ); $append_back_matter_content = $this->kneadHtml( apply_filters( 'pb_append_back_matter_content', '', $back_matter_id ), 'back-matter', $i ); $short_title = trim( get_post_meta( $back_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $back_matter_id, 'pb_authors' ); if ( Export::shouldParseSubsections() === true ) { if ( Book::getSubsections( $back_matter_id ) !== false ) { $content = Book::tagSubsections( $content, $back_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $section_license = $this->doSectionLevelLicense( $metadata, $back_matter_id ); if ( $section_license ) { $append_back_matter_content .= $this->kneadHtml( $this->tidy( $section_license ), 'back-matter', $i ); } $vars['post_title'] = $back_matter['post_title']; $vars['post_content'] = sprintf( $back_matter_printf, $subclass, $slug, $i, Sanitize\decode( $title ), $after_title, $content, $var['append_back_matter_content'] = $append_back_matter_content, '' ); $file_id = 'back-matter-' . sprintf( '%03s', $i ); $filename = "{$file_id}-{$slug}.{$this->filext}"; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); $this->manifest[ $file_id ] = [ 'ID' => $back_matter['ID'], 'post_title' => $back_matter['post_title'], 'filename' => $filename, ]; ++$i; } }
[ "protected", "function", "createBackMatterGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "back_matter_printf", "=", "'<div class=\"back-matter %1$s\" id=\"%2$s\">'", ";", "$", "back_matter_printf", ".=", "'<div class=\"...
Yields an estimated percentage slice of: 50-60 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "50", "-", "60" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1696-L1798
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createToc
protected function createToc( $book_contents, $metadata ) { $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; // Start by inserting self into correct manifest position $array_pos = $this->positionOfToc(); $file_id = 'table-of-contents'; $filename = "{$file_id}.{$this->filext}"; $vars['post_title'] = __( 'Table Of Contents', 'pressbooks' ); $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 $li_count = 0; $i = 1; // Chapter count $m = 1; // Part count $html = '<div id="toc"><h1>' . __( 'Contents', 'pressbooks' ) . '</h1><ul>'; foreach ( $this->manifest as $k => $v ) { // We only care about front-matter, part, chapter, back-matter // Skip the rest $subtitle = ''; $author = ''; $license = ''; $title = Sanitize\strip_br( $v['post_title'] ); if ( preg_match( '/^front-matter-/', $k ) ) { $class = 'front-matter '; $class .= $this->taxonomy->getFrontMatterType( $v['ID'] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); } elseif ( preg_match( '/^part-/', $k ) ) { $class = 'part'; if ( get_post_meta( $v['ID'], 'pb_part_invisible', true ) === 'on' ) { $class .= ' display-none'; } else { /** * Filter the label used for post types (front matter/parts/chapters/back matter) in the TOC and section headings. * * @since 5.6.0 * * @param string $label * @param array $args * * @return string Filtered label */ $title = ( $this->numbered ? apply_filters( 'pb_post_type_label', __( 'Part', 'pressbooks' ), [ 'post_type' => 'part' ] ) . ' ' . \Pressbooks\L10n\romanize( $m ) . '. ' : '' ) . $title; $m++; } } elseif ( preg_match( '/^chapter-/', $k ) ) { $class = implode( ' ', [ 'chapter', $this->taxonomy->getChapterType( $v['ID'] ) ] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); if ( $this->numbered && $this->taxonomy->getChapterType( $v['ID'] ) !== 'numberless' ) { $title = " $i. " . $title; } if ( $this->taxonomy->getChapterType( $v['ID'] ) !== 'numberless' ) { ++$i; } } elseif ( preg_match( '/^back-matter-/', $k ) ) { $class = 'back-matter '; $class .= $this->taxonomy->getBackMatterType( $v['ID'] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); } else { continue; } $html .= sprintf( '<li class="%s"><a href="%s"><span class="toc-chapter-title">%s</span>', $class, $v['filename'], Sanitize\decode( $title ) ); if ( $subtitle ) { $html .= ' <span class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</span>'; } if ( $author ) { $html .= ' <span class="chapter-author">' . Sanitize\decode( $author ) . '</span>'; } if ( $license ) { $html .= ' <span class="chapter-license">' . $license . '</span> '; } $html .= '</a>'; if ( Export::shouldParseSubsections() === true && $class !== 'part' ) { $sections = Book::getSubsections( $v['ID'] ); if ( $sections ) { $html .= '<ul class="sections">'; foreach ( $sections as $id => $title ) { $html .= '<li class="section"><a href="' . $v['filename'] . '#' . $id . '"><span class="toc-subsection-title">' . Sanitize\decode( $title ) . '</span></a></li>'; } $html .= '</ul>'; } } $html .= "</li>\n"; ++$li_count; } if ( 0 === $li_count ) { $html .= '<li></li>'; } $html .= "</ul></div>\n"; // Create file $vars['post_content'] = $html; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); }
php
protected function createToc( $book_contents, $metadata ) { $vars = [ 'post_title' => '', 'stylesheet' => $this->stylesheet, 'post_content' => '', 'isbn' => ( isset( $metadata['pb_ebook_isbn'] ) ) ? $metadata['pb_ebook_isbn'] : '', 'lang' => $this->lang, ]; // Start by inserting self into correct manifest position $array_pos = $this->positionOfToc(); $file_id = 'table-of-contents'; $filename = "{$file_id}.{$this->filext}"; $vars['post_title'] = __( 'Table Of Contents', 'pressbooks' ); $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 $li_count = 0; $i = 1; // Chapter count $m = 1; // Part count $html = '<div id="toc"><h1>' . __( 'Contents', 'pressbooks' ) . '</h1><ul>'; foreach ( $this->manifest as $k => $v ) { // We only care about front-matter, part, chapter, back-matter // Skip the rest $subtitle = ''; $author = ''; $license = ''; $title = Sanitize\strip_br( $v['post_title'] ); if ( preg_match( '/^front-matter-/', $k ) ) { $class = 'front-matter '; $class .= $this->taxonomy->getFrontMatterType( $v['ID'] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); } elseif ( preg_match( '/^part-/', $k ) ) { $class = 'part'; if ( get_post_meta( $v['ID'], 'pb_part_invisible', true ) === 'on' ) { $class .= ' display-none'; } else { /** * Filter the label used for post types (front matter/parts/chapters/back matter) in the TOC and section headings. * * @since 5.6.0 * * @param string $label * @param array $args * * @return string Filtered label */ $title = ( $this->numbered ? apply_filters( 'pb_post_type_label', __( 'Part', 'pressbooks' ), [ 'post_type' => 'part' ] ) . ' ' . \Pressbooks\L10n\romanize( $m ) . '. ' : '' ) . $title; $m++; } } elseif ( preg_match( '/^chapter-/', $k ) ) { $class = implode( ' ', [ 'chapter', $this->taxonomy->getChapterType( $v['ID'] ) ] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); if ( $this->numbered && $this->taxonomy->getChapterType( $v['ID'] ) !== 'numberless' ) { $title = " $i. " . $title; } if ( $this->taxonomy->getChapterType( $v['ID'] ) !== 'numberless' ) { ++$i; } } elseif ( preg_match( '/^back-matter-/', $k ) ) { $class = 'back-matter '; $class .= $this->taxonomy->getBackMatterType( $v['ID'] ); $subtitle = trim( get_post_meta( $v['ID'], 'pb_subtitle', true ) ); $author = $this->contributors->get( $v['ID'], 'pb_authors' ); $license = $this->doTocLicense( $v['ID'] ); } else { continue; } $html .= sprintf( '<li class="%s"><a href="%s"><span class="toc-chapter-title">%s</span>', $class, $v['filename'], Sanitize\decode( $title ) ); if ( $subtitle ) { $html .= ' <span class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</span>'; } if ( $author ) { $html .= ' <span class="chapter-author">' . Sanitize\decode( $author ) . '</span>'; } if ( $license ) { $html .= ' <span class="chapter-license">' . $license . '</span> '; } $html .= '</a>'; if ( Export::shouldParseSubsections() === true && $class !== 'part' ) { $sections = Book::getSubsections( $v['ID'] ); if ( $sections ) { $html .= '<ul class="sections">'; foreach ( $sections as $id => $title ) { $html .= '<li class="section"><a href="' . $v['filename'] . '#' . $id . '"><span class="toc-subsection-title">' . Sanitize\decode( $title ) . '</span></a></li>'; } $html .= '</ul>'; } } $html .= "</li>\n"; ++$li_count; } if ( 0 === $li_count ) { $html .= '<li></li>'; } $html .= "</ul></div>\n"; // Create file $vars['post_content'] = $html; \Pressbooks\Utility\put_contents( $this->tmpDir . "/OEBPS/$filename", $this->loadTemplate( $this->dir . '/templates/epub201/html.php', $vars ) ); }
[ "protected", "function", "createToc", "(", "$", "book_contents", ",", "$", "metadata", ")", "{", "$", "vars", "=", "[", "'post_title'", "=>", "''", ",", "'stylesheet'", "=>", "$", "this", "->", "stylesheet", ",", "'post_content'", "=>", "''", ",", "'isbn'"...
Uses $this->manifest to generate itself. @param array $book_contents @param array $metadata
[ "Uses", "$this", "-", ">", "manifest", "to", "generate", "itself", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1807-L1937
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.positionOfToc
protected function positionOfToc() { $search = array_keys( $this->manifest ); if ( false === $this->frontMatterLastPos ) { $array_pos = array_search( 'copyright', $search, true ); if ( false === $array_pos ) { $array_pos = -1; } } else { $array_pos = -1; $preg = '/^front-matter-' . sprintf( '%03s', $this->frontMatterLastPos ) . '$/'; foreach ( $search as $key => $val ) { if ( preg_match( $preg, $val ) ) { $array_pos = $key; break; } } } return $array_pos; }
php
protected function positionOfToc() { $search = array_keys( $this->manifest ); if ( false === $this->frontMatterLastPos ) { $array_pos = array_search( 'copyright', $search, true ); if ( false === $array_pos ) { $array_pos = -1; } } else { $array_pos = -1; $preg = '/^front-matter-' . sprintf( '%03s', $this->frontMatterLastPos ) . '$/'; foreach ( $search as $key => $val ) { if ( preg_match( $preg, $val ) ) { $array_pos = $key; break; } } } return $array_pos; }
[ "protected", "function", "positionOfToc", "(", ")", "{", "$", "search", "=", "array_keys", "(", "$", "this", "->", "manifest", ")", ";", "if", "(", "false", "===", "$", "this", "->", "frontMatterLastPos", ")", "{", "$", "array_pos", "=", "array_search", ...
Determine position of TOC based on Chicago Manual Of Style. @return int
[ "Determine", "position", "of", "TOC", "based", "on", "Chicago", "Manual", "Of", "Style", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1945-L1968
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.kneadHtml
protected function kneadHtml( $html, $type, $pos = 0 ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html, [ 'disable_html_ns' => true ] ); // Disable default namespace for \DOMXPath compatibility // Download images, change to relative paths $dom = $this->scrapeAndKneadImages( $dom ); // Download audio files, change to relative paths $dom = $this->scrapeAndKneadMedia( $dom ); // Deal with <a href="">, <a href=''>, and other mutations $dom = $this->kneadHref( $dom, $type, $pos ); // Make sure empty tags (e.g. <b></b>) don't get turned into self-closing versions by adding an empty text node to them. $xpath = new \DOMXPath( $dom ); while ( ( $nodes = $xpath->query( '//*[not(text() or node() or self::br or self::hr or self::img)]' ) ) && $nodes->length > 0 ) { // @codingStandardsIgnoreLine foreach ( $nodes as $node ) { /** @var \DOMElement $node */ $node->appendChild( new \DOMText( '' ) ); } } // If you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. // Ie. It will spit out the characters converted in encoded format. Instead do the following: $html = $dom->saveXML( $dom->documentElement ); // Remove auto-created <html> <body> and <!DOCTYPE> tags. $html = \Pressbooks\Sanitize\strip_container_tags( $html ); // Mobi7 hacks $utf8_hack = '<?xml version="1.0" encoding="UTF-8"?>'; $html = $this->transformXML( "{$utf8_hack }<html>{$html}</html>", $this->dir . '/templates/epub201/mobi-hacks.xsl' ); return $html; }
php
protected function kneadHtml( $html, $type, $pos = 0 ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html, [ 'disable_html_ns' => true ] ); // Disable default namespace for \DOMXPath compatibility // Download images, change to relative paths $dom = $this->scrapeAndKneadImages( $dom ); // Download audio files, change to relative paths $dom = $this->scrapeAndKneadMedia( $dom ); // Deal with <a href="">, <a href=''>, and other mutations $dom = $this->kneadHref( $dom, $type, $pos ); // Make sure empty tags (e.g. <b></b>) don't get turned into self-closing versions by adding an empty text node to them. $xpath = new \DOMXPath( $dom ); while ( ( $nodes = $xpath->query( '//*[not(text() or node() or self::br or self::hr or self::img)]' ) ) && $nodes->length > 0 ) { // @codingStandardsIgnoreLine foreach ( $nodes as $node ) { /** @var \DOMElement $node */ $node->appendChild( new \DOMText( '' ) ); } } // If you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. // Ie. It will spit out the characters converted in encoded format. Instead do the following: $html = $dom->saveXML( $dom->documentElement ); // Remove auto-created <html> <body> and <!DOCTYPE> tags. $html = \Pressbooks\Sanitize\strip_container_tags( $html ); // Mobi7 hacks $utf8_hack = '<?xml version="1.0" encoding="UTF-8"?>'; $html = $this->transformXML( "{$utf8_hack }<html>{$html}</html>", $this->dir . '/templates/epub201/mobi-hacks.xsl' ); return $html; }
[ "protected", "function", "kneadHtml", "(", "$", "html", ",", "$", "type", ",", "$", "pos", "=", "0", ")", "{", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "html", ",", "[", "...
Pummel the HTML into EPUB compatible dough. @param string $html @param string $type front-matter, part, chapter, back-matter, ... @param int $pos (optional) position of content, used when creating filenames like: chapter-001, chapter-002, ... @return string
[ "Pummel", "the", "HTML", "into", "EPUB", "compatible", "dough", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L1980-L2015
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.scrapeAndKneadImages
protected function scrapeAndKneadImages( \DOMDocument $doc ) { $fullpath = $this->tmpDir . '/OEBPS/assets'; $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $url = $image->getAttribute( 'src' ); // Replace Buckram SVGs with PNGs if ( str_starts_with( $url, get_template_directory_uri() . '/packages/buckram/assets/images' ) && str_ends_with( $url, '.svg' ) ) { $url = str_replace( '.svg', '.png', $url ); } $filename = $this->fetchAndSaveUniqueImage( $url, $fullpath ); if ( $filename ) { // Replace with new image $image->setAttribute( 'src', 'assets/' . $filename ); } else { // Tag broken image $image->setAttribute( 'src', "{$url}#fixme" ); } } return $doc; }
php
protected function scrapeAndKneadImages( \DOMDocument $doc ) { $fullpath = $this->tmpDir . '/OEBPS/assets'; $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $url = $image->getAttribute( 'src' ); // Replace Buckram SVGs with PNGs if ( str_starts_with( $url, get_template_directory_uri() . '/packages/buckram/assets/images' ) && str_ends_with( $url, '.svg' ) ) { $url = str_replace( '.svg', '.png', $url ); } $filename = $this->fetchAndSaveUniqueImage( $url, $fullpath ); if ( $filename ) { // Replace with new image $image->setAttribute( 'src', 'assets/' . $filename ); } else { // Tag broken image $image->setAttribute( 'src', "{$url}#fixme" ); } } return $doc; }
[ "protected", "function", "scrapeAndKneadImages", "(", "\\", "DOMDocument", "$", "doc", ")", "{", "$", "fullpath", "=", "$", "this", "->", "tmpDir", ".", "'/OEBPS/assets'", ";", "$", "images", "=", "$", "doc", "->", "getElementsByTagName", "(", "'img'", ")", ...
Parse HTML snippet, download all found <img> tags into /OEBPS/assets/, return the HTML with changed <img> paths. @param \DOMDocument $doc @return \DOMDocument
[ "Parse", "HTML", "snippet", "download", "all", "found", "<img", ">", "tags", "into", "/", "OEBPS", "/", "assets", "/", "return", "the", "HTML", "with", "changed", "<img", ">", "paths", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2025-L2049
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.fetchAndSaveUniqueImage
protected function fetchAndSaveUniqueImage( $url, $fullpath ) { if ( isset( $this->fetchedImageCache[ $url ] ) ) { return $this->fetchedImageCache[ $url ]; } $args = [ 'timeout' => $this->timeout, ]; $response = \Pressbooks\Utility\remote_get_retry( $url, $args ); // WordPress error? if ( is_wp_error( $response ) ) { try { // protocol relative urls handed to wp_remote_get will fail // try adding a protocol $protocol_relative = wp_parse_url( $url ); if ( ! isset( $protocol_relative['scheme'] ) ) { if ( true === is_ssl() ) { $url = 'https:' . $url; } else { $url = 'http:' . $url; } } $response = wp_remote_get( $url, $args ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } } catch ( \Exception $exc ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub201\fetchAndSaveUniqueImage wp_error on wp_remote_get() - ' . $response->get_error_message() . ' - ' . $exc->getMessage() ); return ''; } } // Basename without query string $filename = explode( '?', basename( $url ) ); /** * @since 5.5.0 * * Filters the filename of a unique image * * @param string $filename the filename * @param array $ori_filename the original filename * @param object $response the response * @param string $url the url */ $unique_filename = apply_filters( 'pb_epub201_fetchandsaveuniqueimage_filename', '', $filename, $response, $url ); if ( '' !== $unique_filename ) { $filename = $unique_filename; } else { // isolate latex image service from WP, add file extension $host = wp_parse_url( $url, PHP_URL_HOST ); if ( ( str_ends_with( $host, 'wordpress.com' ) || str_ends_with( $host, 'wp.com' ) ) && 'latex.php' === $filename[0] ) { $filename = md5( array_pop( $filename ) ); // content-type = 'image/png' $type = explode( '/', $response['headers']['content-type'] ); $type = array_pop( $type ); $filename = $filename . '.' . $type; } else { $filename = array_shift( $filename ); $filename = explode( '#', $filename )[0]; // Remove trailing anchors $filename = sanitize_file_name( urldecode( $filename ) ); $filename = Sanitize\force_ascii( $filename ); } } // A book with a lot of images can trigger "Fatal Error Too many open files" because tmpfiles are not closed until PHP exits // Use a $resource_key so we can close the tmpfile ourselves $resource_key = uniqid( 'tmpfile-epub-', true ); $tmp_file = \Pressbooks\Utility\create_tmp_file( $resource_key ); \Pressbooks\Utility\put_contents( $tmp_file, wp_remote_retrieve_body( $response ) ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_file, $filename ) ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub201\fetchAndSaveUniqueImage is_valid_image, not a valid image ' ); fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not an image } if ( $this->compressImages ) { /** * @since 5.5.0 * * Filters if a image should be compressed * * @param boolean $compress should it be compressed * @param file $tmp_file the temp file */ if ( apply_filters( 'pb_epub201_fetchandsaveuniqueimage_compress', true, $tmp_file ) ) { $format = explode( '.', $filename ); $format = strtolower( end( $format ) ); // Extension try { \Pressbooks\Image\resize_down( $format, $tmp_file ); } catch ( \Exception $e ) { return ''; } } } // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); } elseif ( md5( \Pressbooks\Utility\get_contents( $tmp_file ) ) !== md5( \Pressbooks\Utility\get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine $this->fetchedImageCache[ $url ] = $filename; return $filename; }
php
protected function fetchAndSaveUniqueImage( $url, $fullpath ) { if ( isset( $this->fetchedImageCache[ $url ] ) ) { return $this->fetchedImageCache[ $url ]; } $args = [ 'timeout' => $this->timeout, ]; $response = \Pressbooks\Utility\remote_get_retry( $url, $args ); // WordPress error? if ( is_wp_error( $response ) ) { try { // protocol relative urls handed to wp_remote_get will fail // try adding a protocol $protocol_relative = wp_parse_url( $url ); if ( ! isset( $protocol_relative['scheme'] ) ) { if ( true === is_ssl() ) { $url = 'https:' . $url; } else { $url = 'http:' . $url; } } $response = wp_remote_get( $url, $args ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } } catch ( \Exception $exc ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub201\fetchAndSaveUniqueImage wp_error on wp_remote_get() - ' . $response->get_error_message() . ' - ' . $exc->getMessage() ); return ''; } } // Basename without query string $filename = explode( '?', basename( $url ) ); /** * @since 5.5.0 * * Filters the filename of a unique image * * @param string $filename the filename * @param array $ori_filename the original filename * @param object $response the response * @param string $url the url */ $unique_filename = apply_filters( 'pb_epub201_fetchandsaveuniqueimage_filename', '', $filename, $response, $url ); if ( '' !== $unique_filename ) { $filename = $unique_filename; } else { // isolate latex image service from WP, add file extension $host = wp_parse_url( $url, PHP_URL_HOST ); if ( ( str_ends_with( $host, 'wordpress.com' ) || str_ends_with( $host, 'wp.com' ) ) && 'latex.php' === $filename[0] ) { $filename = md5( array_pop( $filename ) ); // content-type = 'image/png' $type = explode( '/', $response['headers']['content-type'] ); $type = array_pop( $type ); $filename = $filename . '.' . $type; } else { $filename = array_shift( $filename ); $filename = explode( '#', $filename )[0]; // Remove trailing anchors $filename = sanitize_file_name( urldecode( $filename ) ); $filename = Sanitize\force_ascii( $filename ); } } // A book with a lot of images can trigger "Fatal Error Too many open files" because tmpfiles are not closed until PHP exits // Use a $resource_key so we can close the tmpfile ourselves $resource_key = uniqid( 'tmpfile-epub-', true ); $tmp_file = \Pressbooks\Utility\create_tmp_file( $resource_key ); \Pressbooks\Utility\put_contents( $tmp_file, wp_remote_retrieve_body( $response ) ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_file, $filename ) ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub201\fetchAndSaveUniqueImage is_valid_image, not a valid image ' ); fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not an image } if ( $this->compressImages ) { /** * @since 5.5.0 * * Filters if a image should be compressed * * @param boolean $compress should it be compressed * @param file $tmp_file the temp file */ if ( apply_filters( 'pb_epub201_fetchandsaveuniqueimage_compress', true, $tmp_file ) ) { $format = explode( '.', $filename ); $format = strtolower( end( $format ) ); // Extension try { \Pressbooks\Image\resize_down( $format, $tmp_file ); } catch ( \Exception $e ) { return ''; } } } // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); } elseif ( md5( \Pressbooks\Utility\get_contents( $tmp_file ) ) !== md5( \Pressbooks\Utility\get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine $this->fetchedImageCache[ $url ] = $filename; return $filename; }
[ "protected", "function", "fetchAndSaveUniqueImage", "(", "$", "url", ",", "$", "fullpath", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "fetchedImageCache", "[", "$", "url", "]", ")", ")", "{", "return", "$", "this", "->", "fetchedImageCache", "...
Fetch an image with wp_remote_get(), save it to $fullpath with a unique name. Will return an empty string if something went wrong. @param $url string @param $fullpath string @return string filename
[ "Fetch", "an", "image", "with", "wp_remote_get", "()", "save", "it", "to", "$fullpath", "with", "a", "unique", "name", ".", "Will", "return", "an", "empty", "string", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2061-L2175
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.fetchAndSaveUniqueFont
protected function fetchAndSaveUniqueFont( $url, $fullpath ) { if ( isset( $this->fetchedFontCache[ $url ] ) ) { return $this->fetchedFontCache[ $url ]; } $args = []; if ( defined( 'WP_ENV' ) && WP_ENV === 'development' ) { $args['sslverify'] = false; } $response = wp_remote_get( $url, array_merge( [ 'timeout' => $this->timeout, ], $args ) ); // WordPress error? if ( is_wp_error( $response ) ) { // TODO: Properly handle errors returned via $response->get_error_message(); $this->fetchedFontCache[ $url ] = ''; return ''; } // Basename without query string $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); $filename = Sanitize\force_ascii( $filename ); $tmp_file = \Pressbooks\Utility\create_tmp_file(); \Pressbooks\Utility\put_contents( $tmp_file, wp_remote_retrieve_body( $response ) ); // TODO: Validate that this is actually a font // TODO: Refactor fetchAndSaveUniqueImage() and fetchAndSaveUniqueFont() into a single method, but "inject" different validation // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); } elseif ( md5( \Pressbooks\Utility\get_contents( $tmp_file ) ) !== md5( \Pressbooks\Utility\get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } $this->fetchedFontCache[ $url ] = $filename; return $filename; }
php
protected function fetchAndSaveUniqueFont( $url, $fullpath ) { if ( isset( $this->fetchedFontCache[ $url ] ) ) { return $this->fetchedFontCache[ $url ]; } $args = []; if ( defined( 'WP_ENV' ) && WP_ENV === 'development' ) { $args['sslverify'] = false; } $response = wp_remote_get( $url, array_merge( [ 'timeout' => $this->timeout, ], $args ) ); // WordPress error? if ( is_wp_error( $response ) ) { // TODO: Properly handle errors returned via $response->get_error_message(); $this->fetchedFontCache[ $url ] = ''; return ''; } // Basename without query string $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); $filename = Sanitize\force_ascii( $filename ); $tmp_file = \Pressbooks\Utility\create_tmp_file(); \Pressbooks\Utility\put_contents( $tmp_file, wp_remote_retrieve_body( $response ) ); // TODO: Validate that this is actually a font // TODO: Refactor fetchAndSaveUniqueImage() and fetchAndSaveUniqueFont() into a single method, but "inject" different validation // Check for duplicates, save accordingly if ( ! file_exists( "$fullpath/$filename" ) ) { copy( $tmp_file, "$fullpath/$filename" ); } elseif ( md5( \Pressbooks\Utility\get_contents( $tmp_file ) ) !== md5( \Pressbooks\Utility\get_contents( "$fullpath/$filename" ) ) ) { $filename = wp_unique_filename( $fullpath, $filename ); copy( $tmp_file, "$fullpath/$filename" ); } $this->fetchedFontCache[ $url ] = $filename; return $filename; }
[ "protected", "function", "fetchAndSaveUniqueFont", "(", "$", "url", ",", "$", "fullpath", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "fetchedFontCache", "[", "$", "url", "]", ")", ")", "{", "return", "$", "this", "->", "fetchedFontCache", "[",...
Fetch a font with wp_remote_get(), save it to $fullpath with a unique name. Will return an empty string if something went wrong. @param $url string @param $fullpath string @return string filename
[ "Fetch", "a", "font", "with", "wp_remote_get", "()", "save", "it", "to", "$fullpath", "with", "a", "unique", "name", ".", "Will", "return", "an", "empty", "string", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2187-L2239
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.kneadHref
protected function kneadHref( \DOMDocument $doc, $type, $pos ) { $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $url ) { /** @var \DOMElement $url */ $current_url = '' . $url->getAttribute( 'href' ); // Stringify // Is this the the attributionUrl? if ( $url->getAttribute( 'rel' ) === 'cc:attributionURL' ) { $url->parentNode->replaceChild( $doc->createTextNode( $url->nodeValue ), $url ); continue; } // Don't touch empty urls if ( ! trim( $current_url ) ) { continue; } // WordPress auto wraps images in a href tags. // For example: <a href="some_image-original.png"><img src="some_image-300x200.png" /></a> // 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 ) { /** @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 $internal_url = $this->fuzzyHrefMatch( $current_url, $pos ); if ( false !== $internal_url ) { $url->setAttribute( 'href', $internal_url ); continue; } // Canonicalize, fix typos, remove garbage if ( isset( $current_url[0] ) && '#' !== $current_url[0] ) { $url->setAttribute( 'href', \Pressbooks\Sanitize\canonicalize_url( $current_url ) ); } } return $doc; }
php
protected function kneadHref( \DOMDocument $doc, $type, $pos ) { $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $url ) { /** @var \DOMElement $url */ $current_url = '' . $url->getAttribute( 'href' ); // Stringify // Is this the the attributionUrl? if ( $url->getAttribute( 'rel' ) === 'cc:attributionURL' ) { $url->parentNode->replaceChild( $doc->createTextNode( $url->nodeValue ), $url ); continue; } // Don't touch empty urls if ( ! trim( $current_url ) ) { continue; } // WordPress auto wraps images in a href tags. // For example: <a href="some_image-original.png"><img src="some_image-300x200.png" /></a> // 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 ) { /** @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 $internal_url = $this->fuzzyHrefMatch( $current_url, $pos ); if ( false !== $internal_url ) { $url->setAttribute( 'href', $internal_url ); continue; } // Canonicalize, fix typos, remove garbage if ( isset( $current_url[0] ) && '#' !== $current_url[0] ) { $url->setAttribute( 'href', \Pressbooks\Sanitize\canonicalize_url( $current_url ) ); } } return $doc; }
[ "protected", "function", "kneadHref", "(", "\\", "DOMDocument", "$", "doc", ",", "$", "type", ",", "$", "pos", ")", "{", "$", "urls", "=", "$", "doc", "->", "getElementsByTagName", "(", "'a'", ")", ";", "foreach", "(", "$", "urls", "as", "$", "url", ...
Change hrefs @param \DOMDocument $doc @param string $type front-matter, part, chapter, back-matter, ... @param int $pos (optional) position of content, used when creating filenames like: chapter-001, chapter-002, ... @return \DOMDocument
[ "Change", "hrefs" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2262-L2311
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.fuzzyImageNameMatch
protected function fuzzyImageNameMatch( $file1, $file2 ) { $file1 = basename( $file1 ); $file2 = basename( $file2 ); /* Compare extensions */ $file1 = explode( '.', $file1 ); $ext1 = strtolower( end( $file1 ) ); $file2 = explode( '.', $file2 ); $ext2 = strtolower( end( $file2 ) ); if ( $ext1 !== $ext2 ) { return false; } /* Compare prefixes */ $pre1 = explode( '-', $file1[0] ); $pre1 = strtolower( $pre1[0] ); $pre2 = explode( '-', $file2[0] ); $pre2 = strtolower( $pre2[0] ); if ( $pre1 !== $pre2 ) { return false; } return true; }
php
protected function fuzzyImageNameMatch( $file1, $file2 ) { $file1 = basename( $file1 ); $file2 = basename( $file2 ); /* Compare extensions */ $file1 = explode( '.', $file1 ); $ext1 = strtolower( end( $file1 ) ); $file2 = explode( '.', $file2 ); $ext2 = strtolower( end( $file2 ) ); if ( $ext1 !== $ext2 ) { return false; } /* Compare prefixes */ $pre1 = explode( '-', $file1[0] ); $pre1 = strtolower( $pre1[0] ); $pre2 = explode( '-', $file2[0] ); $pre2 = strtolower( $pre2[0] ); if ( $pre1 !== $pre2 ) { return false; } return true; }
[ "protected", "function", "fuzzyImageNameMatch", "(", "$", "file1", ",", "$", "file2", ")", "{", "$", "file1", "=", "basename", "(", "$", "file1", ")", ";", "$", "file2", "=", "basename", "(", "$", "file2", ")", ";", "/* Compare extensions */", "$", "file...
Fuzzy image name match. For example: <a href="Some_Image-original.png"><img src="some_image-300x200.PNG" /></a> We consider both 'href' and 'src' above 'the same' @param string $file1 @param string $file2 @return bool
[ "Fuzzy", "image", "name", "match", ".", "For", "example", ":", "<a", "href", "=", "Some_Image", "-", "original", ".", "png", ">", "<img", "src", "=", "some_image", "-", "300x200", ".", "PNG", "/", ">", "<", "/", "a", ">", "We", "consider", "both", ...
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2324-L2354
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.fuzzyHrefMatch
protected function fuzzyHrefMatch( $url, $pos ) { if ( ! $pos ) { return false; } $url = trim( $url ); // Remove trailing slash $url = rtrim( $url, '/' ); // Change /foo/bar/#fragment to /foo/bar#fragment if ( preg_match( '~/#[^/]*$~', $url ) ) { $url = str_lreplace( '/#', '#', $url ); } $domain = wp_parse_url( $url ); $domain = ( isset( $domain['host'] ) ) ? $domain['host'] : false; if ( $domain ) { $guess_url = site_url(); if ( ! $guess_url ) { $guess_url = wp_guess_url(); } $domain2 = wp_parse_url( $guess_url ); $domain2 = ( isset( $domain2['host'] ) ) ? $domain2['host'] : false; if ( $domain2 !== $domain ) { return false; // If there is a domain name and it =/= ours, bail. } } $split_url = explode( '/', $url ); $last_pos = count( $split_url ) - 1; $posttype = ( isset( $split_url[ $last_pos - 1 ] ) ) ? $split_url[ $last_pos - 1 ] : false; $anchor = ''; // Guess the slug if ( $last_pos > 0 && '#' === substr( trim( $split_url[ $last_pos ] ), 0, 1 ) ) { $anchor = trim( $split_url[ $last_pos ] ); // Found an #anchor $slug = trim( $split_url[ $last_pos - 1 ] ); } elseif ( false !== strpos( $split_url[ $last_pos ], '#' ) ) { list( $slug, $anchor ) = explode( '#', $split_url[ $last_pos ] ); // Found an #anchor $anchor = trim( "#{$anchor}" ); $slug = trim( $slug ); } else { $slug = trim( $split_url[ $last_pos ] ); } if ( ! $slug ) { return false; } // Check if an anchor (ie. #fragment) is considered external, don't change the URL if we find a match $external_anchors = [ \Pressbooks\Interactive\Content::ANCHOR ]; if ( in_array( $anchor, $external_anchors, true ) ) { return false; } // Cheap cache static $lookup = false; static $order = false; if ( $lookup === false && $order === false ) { $lookup = Book::getBookStructure(); $order = $this->fixOrder( $lookup['__order'] ); } $found = []; foreach ( $lookup['__order'] as $post_id => $val ) { if ( $val['post_type'] === $posttype && $val['post_name'] === $slug && $val['export'] ) { $found = array_merge( [ 'ID' => $post_id ], $val ); // @codingStandardsIgnoreLine } } if ( empty( $found ) ) { return false; } // Create a new url that points to a file in the epub $new_url = ''; if ( 'part' === $posttype ) { // Handle parts foreach ( $lookup['part'] as $key => $part ) { if ( $part['post_name'] === $slug ) { $new_url = 'part-' . sprintf( '%03s', $key + 1 ) . '-' . ( isset( $this->sanitizedSlugs[ $slug ] ) ? $this->sanitizedSlugs[ $slug ] : $slug ) . ".{$this->filext}"; } } } else { $new_pos = 0; foreach ( $order as $post_id => $val ) { if ( (string) $val['post_type'] === (string) $found['post_type'] && $val['export'] ) { if ( $this->taxonomy->getFrontMatterType( $post_id ) !== 'title-page' ) { // Custom title pages aren't numbered. ++$new_pos; } } if ( (int) $post_id === (int) $found['ID'] ) { break; } } if ( $val['post_type'] === 'front-matter' && $this->taxonomy->getFrontMatterType( $post_id ) === 'title-page' ) { $new_url = "title-page.{$this->filext}"; } else { $new_url = "{$found['post_type']}-" . sprintf( '%03s', $new_pos ) . '-' . ( isset( $this->sanitizedSlugs[ $slug ] ) ? $this->sanitizedSlugs[ $slug ] : $slug ) . ".{$this->filext}"; } } if ( $anchor ) { $new_url .= $anchor; } return $new_url; }
php
protected function fuzzyHrefMatch( $url, $pos ) { if ( ! $pos ) { return false; } $url = trim( $url ); // Remove trailing slash $url = rtrim( $url, '/' ); // Change /foo/bar/#fragment to /foo/bar#fragment if ( preg_match( '~/#[^/]*$~', $url ) ) { $url = str_lreplace( '/#', '#', $url ); } $domain = wp_parse_url( $url ); $domain = ( isset( $domain['host'] ) ) ? $domain['host'] : false; if ( $domain ) { $guess_url = site_url(); if ( ! $guess_url ) { $guess_url = wp_guess_url(); } $domain2 = wp_parse_url( $guess_url ); $domain2 = ( isset( $domain2['host'] ) ) ? $domain2['host'] : false; if ( $domain2 !== $domain ) { return false; // If there is a domain name and it =/= ours, bail. } } $split_url = explode( '/', $url ); $last_pos = count( $split_url ) - 1; $posttype = ( isset( $split_url[ $last_pos - 1 ] ) ) ? $split_url[ $last_pos - 1 ] : false; $anchor = ''; // Guess the slug if ( $last_pos > 0 && '#' === substr( trim( $split_url[ $last_pos ] ), 0, 1 ) ) { $anchor = trim( $split_url[ $last_pos ] ); // Found an #anchor $slug = trim( $split_url[ $last_pos - 1 ] ); } elseif ( false !== strpos( $split_url[ $last_pos ], '#' ) ) { list( $slug, $anchor ) = explode( '#', $split_url[ $last_pos ] ); // Found an #anchor $anchor = trim( "#{$anchor}" ); $slug = trim( $slug ); } else { $slug = trim( $split_url[ $last_pos ] ); } if ( ! $slug ) { return false; } // Check if an anchor (ie. #fragment) is considered external, don't change the URL if we find a match $external_anchors = [ \Pressbooks\Interactive\Content::ANCHOR ]; if ( in_array( $anchor, $external_anchors, true ) ) { return false; } // Cheap cache static $lookup = false; static $order = false; if ( $lookup === false && $order === false ) { $lookup = Book::getBookStructure(); $order = $this->fixOrder( $lookup['__order'] ); } $found = []; foreach ( $lookup['__order'] as $post_id => $val ) { if ( $val['post_type'] === $posttype && $val['post_name'] === $slug && $val['export'] ) { $found = array_merge( [ 'ID' => $post_id ], $val ); // @codingStandardsIgnoreLine } } if ( empty( $found ) ) { return false; } // Create a new url that points to a file in the epub $new_url = ''; if ( 'part' === $posttype ) { // Handle parts foreach ( $lookup['part'] as $key => $part ) { if ( $part['post_name'] === $slug ) { $new_url = 'part-' . sprintf( '%03s', $key + 1 ) . '-' . ( isset( $this->sanitizedSlugs[ $slug ] ) ? $this->sanitizedSlugs[ $slug ] : $slug ) . ".{$this->filext}"; } } } else { $new_pos = 0; foreach ( $order as $post_id => $val ) { if ( (string) $val['post_type'] === (string) $found['post_type'] && $val['export'] ) { if ( $this->taxonomy->getFrontMatterType( $post_id ) !== 'title-page' ) { // Custom title pages aren't numbered. ++$new_pos; } } if ( (int) $post_id === (int) $found['ID'] ) { break; } } if ( $val['post_type'] === 'front-matter' && $this->taxonomy->getFrontMatterType( $post_id ) === 'title-page' ) { $new_url = "title-page.{$this->filext}"; } else { $new_url = "{$found['post_type']}-" . sprintf( '%03s', $new_pos ) . '-' . ( isset( $this->sanitizedSlugs[ $slug ] ) ? $this->sanitizedSlugs[ $slug ] : $slug ) . ".{$this->filext}"; } } if ( $anchor ) { $new_url .= $anchor; } return $new_url; }
[ "protected", "function", "fuzzyHrefMatch", "(", "$", "url", ",", "$", "pos", ")", "{", "if", "(", "!", "$", "pos", ")", "{", "return", "false", ";", "}", "$", "url", "=", "trim", "(", "$", "url", ")", ";", "// Remove trailing slash", "$", "url", "=...
Try to determine if a URL is pointing to internal content. @param $url @param int $pos (optional) position of content, used when creating filenames like: chapter-001, chapter-002, ... @return bool|string
[ "Try", "to", "determine", "if", "a", "URL", "is", "pointing", "to", "internal", "content", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2365-L2475
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.fixOrder
protected function fixOrder( $order ) { $fixed = []; $fm = []; foreach ( $order as $post_id => $val ) { if ( $val['post_type'] === 'front-matter' ) { $type = $this->taxonomy->getFrontMatterType( $post_id ); if ( ! in_array( $type, [ 'before-title', 'title-page', 'dedication', 'epigraph' ], true ) ) { // Add front matter that isn't being reorderd without intervention. $fixed[ $post_id ] = $val; } else { // Add front matter that is being reordered to temporary array. $fm[ $post_id ] = array_merge( $val, [ 'type' => $type ] ); } } else { // Add parts, chapters, and back matter without intervention. $fixed[ $post_id ] = $val; } } // Work our way backwards, starting with epigraph foreach ( [ 'epigraph', 'dedication', 'title-page', 'before-title' ] as $type ) { foreach ( $fm as $post_id => $val ) { if ( $val['type'] === $type ) { $fixed = [ $post_id => $val ] + $fixed; break; } } } return $fixed; }
php
protected function fixOrder( $order ) { $fixed = []; $fm = []; foreach ( $order as $post_id => $val ) { if ( $val['post_type'] === 'front-matter' ) { $type = $this->taxonomy->getFrontMatterType( $post_id ); if ( ! in_array( $type, [ 'before-title', 'title-page', 'dedication', 'epigraph' ], true ) ) { // Add front matter that isn't being reorderd without intervention. $fixed[ $post_id ] = $val; } else { // Add front matter that is being reordered to temporary array. $fm[ $post_id ] = array_merge( $val, [ 'type' => $type ] ); } } else { // Add parts, chapters, and back matter without intervention. $fixed[ $post_id ] = $val; } } // Work our way backwards, starting with epigraph foreach ( [ 'epigraph', 'dedication', 'title-page', 'before-title' ] as $type ) { foreach ( $fm as $post_id => $val ) { if ( $val['type'] === $type ) { $fixed = [ $post_id => $val ] + $fixed; break; } } } return $fixed; }
[ "protected", "function", "fixOrder", "(", "$", "order", ")", "{", "$", "fixed", "=", "[", "]", ";", "$", "fm", "=", "[", "]", ";", "foreach", "(", "$", "order", "as", "$", "post_id", "=>", "$", "val", ")", "{", "if", "(", "$", "val", "[", "'p...
Reorder the book structure to conform to Chicago Style, so that the book begins with Before Title, Title Page, Dedication, Epigraph. @param array $order @return array
[ "Reorder", "the", "book", "structure", "to", "conform", "to", "Chicago", "Style", "so", "that", "the", "book", "begins", "with", "Before", "Title", "Title", "Page", "Dedication", "Epigraph", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2484-L2512
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.createOPF
protected function createOPF( $book_contents, $metadata ) { if ( empty( $this->manifest ) ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' ); } // Vars $vars = [ 'manifest' => $this->manifest, 'stylesheet' => $this->stylesheet, 'lang' => $this->lang, ]; $vars['manifest_assets'] = $this->buildManifestAssetsHtml(); $vars['do_copyright_license'] = sanitize_xml_attribute( wp_strip_all_tags( $this->doCopyrightLicense( $metadata ), true ) ); // Sanitize metadata for usage in XML template foreach ( $metadata as $key => $val ) { $metadata[ $key ] = sanitize_xml_attribute( $val ); } $vars['meta'] = $metadata; // Put contents \Pressbooks\Utility\put_contents( $this->tmpDir . '/book.opf', $this->loadTemplate( $this->dir . '/templates/epub201/opf.php', $vars ) ); }
php
protected function createOPF( $book_contents, $metadata ) { if ( empty( $this->manifest ) ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' ); } // Vars $vars = [ 'manifest' => $this->manifest, 'stylesheet' => $this->stylesheet, 'lang' => $this->lang, ]; $vars['manifest_assets'] = $this->buildManifestAssetsHtml(); $vars['do_copyright_license'] = sanitize_xml_attribute( wp_strip_all_tags( $this->doCopyrightLicense( $metadata ), true ) ); // Sanitize metadata for usage in XML template foreach ( $metadata as $key => $val ) { $metadata[ $key ] = sanitize_xml_attribute( $val ); } $vars['meta'] = $metadata; // Put contents \Pressbooks\Utility\put_contents( $this->tmpDir . '/book.opf', $this->loadTemplate( $this->dir . '/templates/epub201/opf.php', $vars ) ); }
[ "protected", "function", "createOPF", "(", "$", "book_contents", ",", "$", "metadata", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "manifest", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'$this->manifest cannot be empty. Did you forget to c...
Create OPF File. @param array $book_contents @param array $metadata @throws \Exception
[ "Create", "OPF", "File", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2522-L2552
pressbooks/pressbooks
inc/modules/export/epub/class-epub201.php
Epub201.buildManifestAssetsHtml
protected function buildManifestAssetsHtml() { $html = ''; $path_to_assets = $this->tmpDir . '/OEBPS/assets'; $assets = scandir( $path_to_assets ); $used_ids = []; foreach ( $assets as $asset ) { if ( '.' === $asset || '..' === $asset ) { continue; } $mimetype = $this->mediaType( "$path_to_assets/$asset" ); if ( $this->coverImage === $asset ) { $file_id = 'cover-image'; } else { $file_id = 'media-' . pathinfo( "$path_to_assets/$asset", PATHINFO_FILENAME ); $file_id = Sanitize\sanitize_xml_id( $file_id ); } // 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"; } } $file_id = $check_if_used; $html .= sprintf( '<item id="%s" href="OEBPS/assets/%s" media-type="%s" />', $file_id, $asset, $mimetype ) . "\n"; $used_ids[ $file_id ] = true; } return $html; }
php
protected function buildManifestAssetsHtml() { $html = ''; $path_to_assets = $this->tmpDir . '/OEBPS/assets'; $assets = scandir( $path_to_assets ); $used_ids = []; foreach ( $assets as $asset ) { if ( '.' === $asset || '..' === $asset ) { continue; } $mimetype = $this->mediaType( "$path_to_assets/$asset" ); if ( $this->coverImage === $asset ) { $file_id = 'cover-image'; } else { $file_id = 'media-' . pathinfo( "$path_to_assets/$asset", PATHINFO_FILENAME ); $file_id = Sanitize\sanitize_xml_id( $file_id ); } // 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"; } } $file_id = $check_if_used; $html .= sprintf( '<item id="%s" href="OEBPS/assets/%s" media-type="%s" />', $file_id, $asset, $mimetype ) . "\n"; $used_ids[ $file_id ] = true; } return $html; }
[ "protected", "function", "buildManifestAssetsHtml", "(", ")", "{", "$", "html", "=", "''", ";", "$", "path_to_assets", "=", "$", "this", "->", "tmpDir", ".", "'/OEBPS/assets'", ";", "$", "assets", "=", "scandir", "(", "$", "path_to_assets", ")", ";", "$", ...
Find all the image files, insert them into the OPF file @return string
[ "Find", "all", "the", "image", "files", "insert", "them", "into", "the", "OPF", "file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub201.php#L2559-L2595
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.getCoversFolder
public static function getCoversFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'covers/'; if ( ! file_exists( $path ) ) { mkdir( $path, 0775, true ); } $path_to_htaccess = $path . '.htaccess'; if ( ! file_exists( $path_to_htaccess ) ) { // Restrict access \Pressbooks\Utility\put_contents( $path_to_htaccess, "deny from all\n" ); } return $path; }
php
public static function getCoversFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'covers/'; if ( ! file_exists( $path ) ) { mkdir( $path, 0775, true ); } $path_to_htaccess = $path . '.htaccess'; if ( ! file_exists( $path_to_htaccess ) ) { // Restrict access \Pressbooks\Utility\put_contents( $path_to_htaccess, "deny from all\n" ); } return $path; }
[ "public", "static", "function", "getCoversFolder", "(", ")", "{", "$", "path", "=", "\\", "Pressbooks", "\\", "Utility", "\\", "get_media_prefix", "(", ")", ".", "'covers/'", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "mkdir", ...
Get the fullpath to the Covers folder. Create if not there. Create .htaccess protection if missing. @return string fullpath
[ "Get", "the", "fullpath", "to", "the", "Covers", "folder", ".", "Create", "if", "not", "there", ".", "Create", ".", "htaccess", "protection", "if", "missing", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L83-L97
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.getScssVars
protected function getScssVars() { $sass = ''; // Required foreach ( $this->requiredSassVars as $var ) { $method = $this->varToGetter( $var ); if ( ! method_exists( $this->input, $method ) ) { throw new \LogicException( "Input::{$method}() not found." ); } if ( empty( $this->input->{$method}() ) ) { throw new \InvalidArgumentException( "Input::{$method}() cannot be empty." ); } $sass .= "\${$var}: " . $this->input->{$method}() . ";\n"; } // Optional foreach ( $this->optionalSassVars as $var ) { $method = $this->varToGetter( $var ); if ( method_exists( $this->input, $method ) && ! empty( $this->input->{$method}() ) ) { $sass .= "\${$var}: " . $this->input->{$method}() . ";\n"; } } return $sass; }
php
protected function getScssVars() { $sass = ''; // Required foreach ( $this->requiredSassVars as $var ) { $method = $this->varToGetter( $var ); if ( ! method_exists( $this->input, $method ) ) { throw new \LogicException( "Input::{$method}() not found." ); } if ( empty( $this->input->{$method}() ) ) { throw new \InvalidArgumentException( "Input::{$method}() cannot be empty." ); } $sass .= "\${$var}: " . $this->input->{$method}() . ";\n"; } // Optional foreach ( $this->optionalSassVars as $var ) { $method = $this->varToGetter( $var ); if ( method_exists( $this->input, $method ) && ! empty( $this->input->{$method}() ) ) { $sass .= "\${$var}: " . $this->input->{$method}() . ";\n"; } } return $sass; }
[ "protected", "function", "getScssVars", "(", ")", "{", "$", "sass", "=", "''", ";", "// Required", "foreach", "(", "$", "this", "->", "requiredSassVars", "as", "$", "var", ")", "{", "$", "method", "=", "$", "this", "->", "varToGetter", "(", "$", "var",...
Generate SCSS vars based on Input object @throws \LogicException @throws \InvalidArgumentException @return string
[ "Generate", "SCSS", "vars", "based", "on", "Input", "object" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L122-L150
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.formGenerator
public static function formGenerator( $format ) : \Generator { wp_cache_delete( 'pressbooks_cg_options', 'options' ); // WordPress Core caches this key in the "options" group wp_cache_delete( 'alloptions', 'options' ); $cg_options = get_option( 'pressbooks_cg_options' ); yield 20 => __( 'Calculating spine width', 'pressbooks' ); if ( isset( $cg_options['pdf_pagecount'] ) ) { $pages = $cg_options['pdf_pagecount']; } else { $spine = new Spine; $pages = $spine->countPagesInMostRecentPdf(); } if ( isset( $cg_options['ppi'] ) ) { $ppi = $cg_options['ppi']; } else { $ppi = 444; } $spine = new Spine(); $spine_width = $spine->spineWidthCalculator( $pages, $ppi ); $spine_width = "{$spine_width}in"; // Inches, float to CSS string yield 30 => __( 'Creating barcode', 'pressbooks' ); // Either ISBN or SKU, not both if ( isset( $cg_options['pb_print_isbn'] ) && '' !== trim( $cg_options['pb_print_isbn'] ) ) { $isbn_url = ( new Isbn() )->createBarcode( $cg_options['pb_print_isbn'] ); } elseif ( isset( $cg_options['pb_print_sku'] ) && '' !== trim( $cg_options['pb_print_sku'] ) ) { $isbn_url = ( new Sku() )->createBarcode( $cg_options['pb_print_sku'] ); } yield 40 => __( 'Loading metadata', 'pressbooks' ); $input = new Input(); $input->setTitle( $cg_options['pb_title'] ); if ( $pages >= 48 ) { if ( isset( $cg_options['pb_title_spine'] ) && '' !== $cg_options['pb_title_spine'] ) { $input->setSpineTitle( $cg_options['pb_title_spine'] ); } else { $input->setSpineTitle( $cg_options['pb_title'] ); } } if ( isset( $cg_options['pb_subtitle'] ) && '' !== $cg_options['pb_subtitle'] ) { $input->setSubtitle( $cg_options['pb_subtitle'] ); } $input->setAuthor( $cg_options['pb_author'] ); if ( $pages >= 48 ) { if ( isset( $cg_options['pb_author_spine'] ) && '' !== $cg_options['pb_author_spine'] ) { $input->setSpineAuthor( $cg_options['pb_author_spine'] ); } else { $input->setSpineAuthor( $cg_options['pb_author'] ); } } if ( isset( $cg_options['pb_about_unlimited'] ) && '' !== $cg_options['pb_about_unlimited'] ) { $input->setAbout( $cg_options['pb_about_unlimited'] ); } if ( isset( $cg_options['text_transform'] ) && '' !== $cg_options['text_transform'] ) { $input->setTextTransform( $cg_options['text_transform'] ); } $pdf_options = get_option( 'pressbooks_theme_options_pdf' ); $input->setTrimHeight( $pdf_options['pdf_page_height'] ); $input->setTrimWidth( $pdf_options['pdf_page_width'] ); $input->setSpineWidth( $spine_width ); if ( isset( $cg_options['front_cover_text'] ) ) { $input->setFrontFontColor( $cg_options['front_cover_text'] ); } if ( isset( $cg_options['front_cover_background'] ) ) { $input->setFrontBackgroundColor( $cg_options['front_cover_background'] ); } if ( isset( $cg_options['spine_text'] ) ) { $input->setSpineFontColor( $cg_options['spine_text'] ); } if ( isset( $cg_options['spine_background'] ) ) { $input->setSpineBackgroundColor( $cg_options['spine_background'] ); } if ( isset( $cg_options['back_cover_text'] ) ) { $input->setBackFontColor( $cg_options['back_cover_text'] ); } if ( isset( $cg_options['back_cover_background'] ) ) { $input->setBackBackgroundColor( $cg_options['back_cover_background'] ); } if ( isset( $cg_options['front_background_image'] ) ) { $input->setFrontBackgroundImage( \Pressbooks\Sanitize\maybe_https( $cg_options['front_background_image'] ) ); } if ( isset( $isbn_url ) ) { $input->setIsbnImage( $isbn_url ); } yield 50 => __( 'Generating cover', 'pressbooks' ); if ( 'pdf' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) { $pdf = new DocraptorPdf( $input ); $pdf->generate(); } elseif ( 'pdf' === $format ) { $pdf = new PrincePdf( $input ); $pdf->generate(); } elseif ( 'jpg' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) { $jpg = new DocraptorJpg( $input ); $jpg->generate(); } elseif ( 'jpg' === $format ) { $jpg = new PrinceJpg( $input ); $jpg->generate(); } yield 100 => __( 'Finishing up', 'pressbooks' ); }
php
public static function formGenerator( $format ) : \Generator { wp_cache_delete( 'pressbooks_cg_options', 'options' ); // WordPress Core caches this key in the "options" group wp_cache_delete( 'alloptions', 'options' ); $cg_options = get_option( 'pressbooks_cg_options' ); yield 20 => __( 'Calculating spine width', 'pressbooks' ); if ( isset( $cg_options['pdf_pagecount'] ) ) { $pages = $cg_options['pdf_pagecount']; } else { $spine = new Spine; $pages = $spine->countPagesInMostRecentPdf(); } if ( isset( $cg_options['ppi'] ) ) { $ppi = $cg_options['ppi']; } else { $ppi = 444; } $spine = new Spine(); $spine_width = $spine->spineWidthCalculator( $pages, $ppi ); $spine_width = "{$spine_width}in"; // Inches, float to CSS string yield 30 => __( 'Creating barcode', 'pressbooks' ); // Either ISBN or SKU, not both if ( isset( $cg_options['pb_print_isbn'] ) && '' !== trim( $cg_options['pb_print_isbn'] ) ) { $isbn_url = ( new Isbn() )->createBarcode( $cg_options['pb_print_isbn'] ); } elseif ( isset( $cg_options['pb_print_sku'] ) && '' !== trim( $cg_options['pb_print_sku'] ) ) { $isbn_url = ( new Sku() )->createBarcode( $cg_options['pb_print_sku'] ); } yield 40 => __( 'Loading metadata', 'pressbooks' ); $input = new Input(); $input->setTitle( $cg_options['pb_title'] ); if ( $pages >= 48 ) { if ( isset( $cg_options['pb_title_spine'] ) && '' !== $cg_options['pb_title_spine'] ) { $input->setSpineTitle( $cg_options['pb_title_spine'] ); } else { $input->setSpineTitle( $cg_options['pb_title'] ); } } if ( isset( $cg_options['pb_subtitle'] ) && '' !== $cg_options['pb_subtitle'] ) { $input->setSubtitle( $cg_options['pb_subtitle'] ); } $input->setAuthor( $cg_options['pb_author'] ); if ( $pages >= 48 ) { if ( isset( $cg_options['pb_author_spine'] ) && '' !== $cg_options['pb_author_spine'] ) { $input->setSpineAuthor( $cg_options['pb_author_spine'] ); } else { $input->setSpineAuthor( $cg_options['pb_author'] ); } } if ( isset( $cg_options['pb_about_unlimited'] ) && '' !== $cg_options['pb_about_unlimited'] ) { $input->setAbout( $cg_options['pb_about_unlimited'] ); } if ( isset( $cg_options['text_transform'] ) && '' !== $cg_options['text_transform'] ) { $input->setTextTransform( $cg_options['text_transform'] ); } $pdf_options = get_option( 'pressbooks_theme_options_pdf' ); $input->setTrimHeight( $pdf_options['pdf_page_height'] ); $input->setTrimWidth( $pdf_options['pdf_page_width'] ); $input->setSpineWidth( $spine_width ); if ( isset( $cg_options['front_cover_text'] ) ) { $input->setFrontFontColor( $cg_options['front_cover_text'] ); } if ( isset( $cg_options['front_cover_background'] ) ) { $input->setFrontBackgroundColor( $cg_options['front_cover_background'] ); } if ( isset( $cg_options['spine_text'] ) ) { $input->setSpineFontColor( $cg_options['spine_text'] ); } if ( isset( $cg_options['spine_background'] ) ) { $input->setSpineBackgroundColor( $cg_options['spine_background'] ); } if ( isset( $cg_options['back_cover_text'] ) ) { $input->setBackFontColor( $cg_options['back_cover_text'] ); } if ( isset( $cg_options['back_cover_background'] ) ) { $input->setBackBackgroundColor( $cg_options['back_cover_background'] ); } if ( isset( $cg_options['front_background_image'] ) ) { $input->setFrontBackgroundImage( \Pressbooks\Sanitize\maybe_https( $cg_options['front_background_image'] ) ); } if ( isset( $isbn_url ) ) { $input->setIsbnImage( $isbn_url ); } yield 50 => __( 'Generating cover', 'pressbooks' ); if ( 'pdf' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) { $pdf = new DocraptorPdf( $input ); $pdf->generate(); } elseif ( 'pdf' === $format ) { $pdf = new PrincePdf( $input ); $pdf->generate(); } elseif ( 'jpg' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) { $jpg = new DocraptorJpg( $input ); $jpg->generate(); } elseif ( 'jpg' === $format ) { $jpg = new PrinceJpg( $input ); $jpg->generate(); } yield 100 => __( 'Finishing up', 'pressbooks' ); }
[ "public", "static", "function", "formGenerator", "(", "$", "format", ")", ":", "\\", "Generator", "{", "wp_cache_delete", "(", "'pressbooks_cg_options'", ",", "'options'", ")", ";", "// WordPress Core caches this key in the \"options\" group", "wp_cache_delete", "(", "'al...
Generate cover Yields an estimated percentage slice of: 20 - 100 @see pressbooks/templates/admin/generator.php @param string $format @return \Generator @throws \Exception
[ "Generate", "cover", "Yields", "an", "estimated", "percentage", "slice", "of", ":", "20", "-", "100" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L199-L302
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.formDelete
public static function formDelete() { if ( check_admin_referer( 'pb-delete-cover' ) ) { $filename = sanitize_file_name( $_POST['filename'] ); $path = static::getCoversFolder(); unlink( $path . $filename ); delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ } \Pressbooks\Redirect\location( admin_url( 'admin.php?page=pressbooks_cg' ) ); }
php
public static function formDelete() { if ( check_admin_referer( 'pb-delete-cover' ) ) { $filename = sanitize_file_name( $_POST['filename'] ); $path = static::getCoversFolder(); unlink( $path . $filename ); delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ } \Pressbooks\Redirect\location( admin_url( 'admin.php?page=pressbooks_cg' ) ); }
[ "public", "static", "function", "formDelete", "(", ")", "{", "if", "(", "check_admin_referer", "(", "'pb-delete-cover'", ")", ")", "{", "$", "filename", "=", "sanitize_file_name", "(", "$", "_POST", "[", "'filename'", "]", ")", ";", "$", "path", "=", "stat...
Delete cover @see pressbooks/templates/admin/generator.php
[ "Delete", "cover" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L310-L320
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.formDeleteAll
public static function formDeleteAll() { if ( ! empty( $_POST['delete_all_covers'] ) && check_admin_referer( 'pb-delete-all-covers' ) ) { \Pressbooks\Utility\truncate_exports( 0, static::getCoversFolder() ); delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ } \Pressbooks\Redirect\location( admin_url( 'admin.php?page=pressbooks_cg' ) ); }
php
public static function formDeleteAll() { if ( ! empty( $_POST['delete_all_covers'] ) && check_admin_referer( 'pb-delete-all-covers' ) ) { \Pressbooks\Utility\truncate_exports( 0, static::getCoversFolder() ); delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ } \Pressbooks\Redirect\location( admin_url( 'admin.php?page=pressbooks_cg' ) ); }
[ "public", "static", "function", "formDeleteAll", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "_POST", "[", "'delete_all_covers'", "]", ")", "&&", "check_admin_referer", "(", "'pb-delete-all-covers'", ")", ")", "{", "\\", "Pressbooks", "\\", "Utility", ...
Delete all covers @see pressbooks/templates/admin/generator.php
[ "Delete", "all", "covers" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L327-L335
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator._downloadCoverFile
protected static function _downloadCoverFile( $filename ) { $filepath = static::getCoversFolder() . $filename; \Pressbooks\Redirect\force_download( $filepath ); exit; }
php
protected static function _downloadCoverFile( $filename ) { $filepath = static::getCoversFolder() . $filename; \Pressbooks\Redirect\force_download( $filepath ); exit; }
[ "protected", "static", "function", "_downloadCoverFile", "(", "$", "filename", ")", "{", "$", "filepath", "=", "static", "::", "getCoversFolder", "(", ")", ".", "$", "filename", ";", "\\", "Pressbooks", "\\", "Redirect", "\\", "force_download", "(", "$", "fi...
Download an .htaccess protected file from the exports directory. @param string $filename sanitized $_GET['download_export_file']
[ "Download", "an", ".", "htaccess", "protected", "file", "from", "the", "exports", "directory", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L353-L357
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.timestampedFileName
public 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( [ '+' ], '', $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 ) { $path = static::getCoversFolder(); } else { $path = ''; } $filename = $path . $book_title_slug . '-cover-' . time() . '.' . ltrim( $extension, '.' ); return $filename; }
php
public 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( [ '+' ], '', $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 ) { $path = static::getCoversFolder(); } else { $path = ''; } $filename = $path . $book_title_slug . '-cover-' . time() . '.' . ltrim( $extension, '.' ); return $filename; }
[ "public", "function", "timestampedFileName", "(", "$", "extension", ",", "$", "fullpath", "=", "true", ")", "{", "$", "book_title", "=", "(", "get_bloginfo", "(", "'name'", ")", ")", "?", "get_bloginfo", "(", "'name'", ")", ":", "__", "(", "'book'", ",",...
Create a timestamped filename. @param string $extension @param bool $fullpath @return string
[ "Create", "a", "timestamped", "filename", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L367-L382
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.generateWithPrince
public function generateWithPrince( $pdf_profile, $pdf_output_intent, $document_content, $output_path ) { $log_file = create_tmp_file(); $prince = new \PrinceXMLPhp\PrinceWrapper( PB_PRINCE_COMMAND ); $prince->setHTML( true ); $prince->setCompress( true ); if ( defined( 'WP_ENV' ) && ( WP_ENV === 'development' ) ) { $prince->setInsecure( true ); } $prince->setLog( $log_file ); $prince->setPDFProfile( $pdf_profile ); $prince->setPDFOutputIntent( $pdf_output_intent ); $success = $prince->convert_string_to_file( $document_content, $output_path, $msg ); // Prince XML is very flexible. There could be errors but Prince will still render a PDF. // We want to log those errors but we won't alert the user. if ( is_countable( $msg ) && count( $msg ) ) { debug_error_log( \Pressbooks\Utility\get_contents( $log_file ) ); } return $success; }
php
public function generateWithPrince( $pdf_profile, $pdf_output_intent, $document_content, $output_path ) { $log_file = create_tmp_file(); $prince = new \PrinceXMLPhp\PrinceWrapper( PB_PRINCE_COMMAND ); $prince->setHTML( true ); $prince->setCompress( true ); if ( defined( 'WP_ENV' ) && ( WP_ENV === 'development' ) ) { $prince->setInsecure( true ); } $prince->setLog( $log_file ); $prince->setPDFProfile( $pdf_profile ); $prince->setPDFOutputIntent( $pdf_output_intent ); $success = $prince->convert_string_to_file( $document_content, $output_path, $msg ); // Prince XML is very flexible. There could be errors but Prince will still render a PDF. // We want to log those errors but we won't alert the user. if ( is_countable( $msg ) && count( $msg ) ) { debug_error_log( \Pressbooks\Utility\get_contents( $log_file ) ); } return $success; }
[ "public", "function", "generateWithPrince", "(", "$", "pdf_profile", ",", "$", "pdf_output_intent", ",", "$", "document_content", ",", "$", "output_path", ")", "{", "$", "log_file", "=", "create_tmp_file", "(", ")", ";", "$", "prince", "=", "new", "\\", "Pri...
@param string $pdf_profile @param $pdf_output_intent @param $document_content @param $output_path @return bool
[ "@param", "string", "$pdf_profile", "@param", "$pdf_output_intent", "@param", "$document_content", "@param", "$output_path" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L392-L413
pressbooks/pressbooks
inc/covergenerator/class-generator.php
Generator.generateWithDocraptor
public function generateWithDocraptor( $pdf_profile, $document_content, $output_path ) { // Configure service $configuration = \DocRaptor\Configuration::getDefaultConfiguration(); $configuration->setUsername( DOCRAPTOR_API_KEY ); // Save PDF as file in exports folder $docraptor = new \DocRaptor\DocApi(); $prince_options = new \DocRaptor\PrinceOptions(); $prince_options->setHttpTimeout( max( ini_get( 'max_execution_time' ), 30 ) ); $prince_options->setProfile( $pdf_profile ); $retval = false; try { $doc = new \DocRaptor\Doc(); if ( defined( 'WP_TESTS_MULTISITE' ) ) { // Unit tests $doc->setTest( true ); } elseif ( defined( 'WP_ENV' ) && ( WP_ENV === 'development' ) ) { // Localhost $doc->setTest( true ); } else { $doc->setTest( false ); } $doc->setDocumentContent( $document_content ); $doc->setName( get_bloginfo( 'name' ) . ' Cover' ); $doc->setPrinceOptions( $prince_options ); $create_response = $docraptor->createAsyncDoc( $doc ); $done = false; while ( ! $done ) { $status_response = $docraptor->getAsyncDocStatus( $create_response->getStatusId() ); switch ( $status_response->getStatus() ) { case 'completed': if ( ! function_exists( 'download_url' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $result = \download_url( $status_response->getDownloadUrl() ); if ( is_wp_error( $result ) ) { \Pressbooks\add_error( __( 'Your PDF could not be retrieved.', 'pressbooks' ) ); } else { copy( $result, $output_path ); unlink( $result ); $retval = true; } $done = true; break; case 'failed': wp_die( $status_response ); $done = true; break; default: sleep( 1 ); } } } catch ( \DocRaptor\ApiException $exception ) { $message = "<h1>{$exception->getMessage()}</h1><p>{$exception->getCode()}</p><p>{$exception->getResponseBody()}</p>"; wp_die( $message ); } return $retval; }
php
public function generateWithDocraptor( $pdf_profile, $document_content, $output_path ) { // Configure service $configuration = \DocRaptor\Configuration::getDefaultConfiguration(); $configuration->setUsername( DOCRAPTOR_API_KEY ); // Save PDF as file in exports folder $docraptor = new \DocRaptor\DocApi(); $prince_options = new \DocRaptor\PrinceOptions(); $prince_options->setHttpTimeout( max( ini_get( 'max_execution_time' ), 30 ) ); $prince_options->setProfile( $pdf_profile ); $retval = false; try { $doc = new \DocRaptor\Doc(); if ( defined( 'WP_TESTS_MULTISITE' ) ) { // Unit tests $doc->setTest( true ); } elseif ( defined( 'WP_ENV' ) && ( WP_ENV === 'development' ) ) { // Localhost $doc->setTest( true ); } else { $doc->setTest( false ); } $doc->setDocumentContent( $document_content ); $doc->setName( get_bloginfo( 'name' ) . ' Cover' ); $doc->setPrinceOptions( $prince_options ); $create_response = $docraptor->createAsyncDoc( $doc ); $done = false; while ( ! $done ) { $status_response = $docraptor->getAsyncDocStatus( $create_response->getStatusId() ); switch ( $status_response->getStatus() ) { case 'completed': if ( ! function_exists( 'download_url' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $result = \download_url( $status_response->getDownloadUrl() ); if ( is_wp_error( $result ) ) { \Pressbooks\add_error( __( 'Your PDF could not be retrieved.', 'pressbooks' ) ); } else { copy( $result, $output_path ); unlink( $result ); $retval = true; } $done = true; break; case 'failed': wp_die( $status_response ); $done = true; break; default: sleep( 1 ); } } } catch ( \DocRaptor\ApiException $exception ) { $message = "<h1>{$exception->getMessage()}</h1><p>{$exception->getCode()}</p><p>{$exception->getResponseBody()}</p>"; wp_die( $message ); } return $retval; }
[ "public", "function", "generateWithDocraptor", "(", "$", "pdf_profile", ",", "$", "document_content", ",", "$", "output_path", ")", "{", "// Configure service", "$", "configuration", "=", "\\", "DocRaptor", "\\", "Configuration", "::", "getDefaultConfiguration", "(", ...
@param string $pdf_profile @param string $document_content @param string $output_path @return bool
[ "@param", "string", "$pdf_profile", "@param", "string", "$document_content", "@param", "string", "$output_path" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-generator.php#L422-L482
pressbooks/pressbooks
inc/class-options.php
Options.sanitize
function sanitize( $input ) { $options = []; if ( ! is_array( $input ) ) { $input = []; } if ( property_exists( $this, 'booleans' ) ) { foreach ( $this->booleans as $key ) { if ( empty( $input[ $key ] ) ) { $options[ $key ] = 0; } else { $options[ $key ] = 1; } } } if ( property_exists( $this, 'strings' ) ) { foreach ( $this->strings as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = sanitize_text_field( $input[ $key ] ); } } } if ( property_exists( $this, 'urls' ) ) { foreach ( $this->urls as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $value = trim( strip_tags( stripslashes( $input[ $key ] ) ) ); if ( $value ) { $options[ $key ] = \Pressbooks\Sanitize\canonicalize_url( $value ); } else { unset( $options[ $key ] ); } } } } if ( property_exists( $this, 'integers' ) ) { foreach ( $this->integers as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = absint( $input[ $key ] ); } } } if ( property_exists( $this, 'floats' ) ) { foreach ( $this->floats as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = filter_var( $input[ $key ], FILTER_VALIDATE_FLOAT ); } } } if ( property_exists( $this, 'predefined' ) ) { foreach ( $this->predefined as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = $input[ $key ]; } } } return $options; }
php
function sanitize( $input ) { $options = []; if ( ! is_array( $input ) ) { $input = []; } if ( property_exists( $this, 'booleans' ) ) { foreach ( $this->booleans as $key ) { if ( empty( $input[ $key ] ) ) { $options[ $key ] = 0; } else { $options[ $key ] = 1; } } } if ( property_exists( $this, 'strings' ) ) { foreach ( $this->strings as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = sanitize_text_field( $input[ $key ] ); } } } if ( property_exists( $this, 'urls' ) ) { foreach ( $this->urls as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $value = trim( strip_tags( stripslashes( $input[ $key ] ) ) ); if ( $value ) { $options[ $key ] = \Pressbooks\Sanitize\canonicalize_url( $value ); } else { unset( $options[ $key ] ); } } } } if ( property_exists( $this, 'integers' ) ) { foreach ( $this->integers as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = absint( $input[ $key ] ); } } } if ( property_exists( $this, 'floats' ) ) { foreach ( $this->floats as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = filter_var( $input[ $key ], FILTER_VALIDATE_FLOAT ); } } } if ( property_exists( $this, 'predefined' ) ) { foreach ( $this->predefined as $key ) { if ( empty( $input[ $key ] ) ) { unset( $options[ $key ] ); } else { $options[ $key ] = $input[ $key ]; } } } return $options; }
[ "function", "sanitize", "(", "$", "input", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "input", ")", ")", "{", "$", "input", "=", "[", "]", ";", "}", "if", "(", "property_exists", "(", "$", "this", ",", ...
Sanitize various options (boolean, string, integer, float). @param array $input @return array $options
[ "Sanitize", "various", "options", "(", "boolean", "string", "integer", "float", ")", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L85-L158
pressbooks/pressbooks
inc/class-options.php
Options.renderColorField
static function renderColorField( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'default' => '#000', 'description' => null, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); printf( '<input id="%1$s" class="color-picker" name="%2$s[%3$s]" type="text" data-default-color="%4$s" value="%5$s" %6$s/>', $args['id'], $args['name'], $args['option'], $args['default'], $args['value'], ( ! empty( $args['disabled'] ) ) ? ' disabled' : '' ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
php
static function renderColorField( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'default' => '#000', 'description' => null, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); printf( '<input id="%1$s" class="color-picker" name="%2$s[%3$s]" type="text" data-default-color="%4$s" value="%5$s" %6$s/>', $args['id'], $args['name'], $args['option'], $args['default'], $args['value'], ( ! empty( $args['disabled'] ) ) ? ' disabled' : '' ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
[ "static", "function", "renderColorField", "(", "$", "args", ")", "{", "$", "defaults", "=", "[", "'id'", "=>", "null", ",", "'name'", "=>", "null", ",", "'option'", "=>", "null", ",", "'value'", "=>", "''", ",", "'default'", "=>", "'#000'", ",", "'desc...
Render a WordPress color picker. @param array $args { Arguments to render the color picker. @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 $default The default value of the field. @type string $description A description which will be displayed below the field. @type bool $disabled Is the field disabled? }
[ "Render", "a", "WordPress", "color", "picker", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L228-L256
pressbooks/pressbooks
inc/class-options.php
Options.renderCheckbox
static function renderCheckbox( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'label' => null, 'disabled' => false, 'description' => null, ]; $args = wp_parse_args( $args, $defaults ); printf( '<input id="%s" name="%s[%s]" type="checkbox" value="1" %s%s/><label for="%s">%s</label>', $args['id'], $args['name'], $args['option'], checked( 1, $args['value'], false ), ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $args['id'], $args['label'] ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
php
static function renderCheckbox( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'label' => null, 'disabled' => false, 'description' => null, ]; $args = wp_parse_args( $args, $defaults ); printf( '<input id="%s" name="%s[%s]" type="checkbox" value="1" %s%s/><label for="%s">%s</label>', $args['id'], $args['name'], $args['option'], checked( 1, $args['value'], false ), ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $args['id'], $args['label'] ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
[ "static", "function", "renderCheckbox", "(", "$", "args", ")", "{", "$", "defaults", "=", "[", "'id'", "=>", "null", ",", "'name'", "=>", "null", ",", "'option'", "=>", "null", ",", "'value'", "=>", "''", ",", "'label'", "=>", "null", ",", "'disabled'"...
Render a checkbox. @param array $args
[ "Render", "a", "checkbox", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L263-L292
pressbooks/pressbooks
inc/class-options.php
Options.renderRadioButtons
static function renderRadioButtons( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'choices' => [], 'custom' => false, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); $is_custom = false; if ( ! array_key_exists( $args['value'], $args['choices'] ) ) { $is_custom = true; } echo '<fieldset>'; foreach ( $args['choices'] as $key => $label ) { printf( '<label for="%s"><input type="radio" id="%s" name="%s[%s]" value="%s" %s%s/>%s</label><br />', $args['id'] . '_' . sanitize_key( $key ), $args['id'] . '_' . sanitize_key( $key ), $args['name'], $args['option'], $key, ( $args['custom'] && $is_custom && empty( $key ) ) ? 'checked' : checked( $key, $args['value'], false ), ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $label ); } echo '</fieldset>'; }
php
static function renderRadioButtons( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'choices' => [], 'custom' => false, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); $is_custom = false; if ( ! array_key_exists( $args['value'], $args['choices'] ) ) { $is_custom = true; } echo '<fieldset>'; foreach ( $args['choices'] as $key => $label ) { printf( '<label for="%s"><input type="radio" id="%s" name="%s[%s]" value="%s" %s%s/>%s</label><br />', $args['id'] . '_' . sanitize_key( $key ), $args['id'] . '_' . sanitize_key( $key ), $args['name'], $args['option'], $key, ( $args['custom'] && $is_custom && empty( $key ) ) ? 'checked' : checked( $key, $args['value'], false ), ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $label ); } echo '</fieldset>'; }
[ "static", "function", "renderRadioButtons", "(", "$", "args", ")", "{", "$", "defaults", "=", "[", "'id'", "=>", "null", ",", "'name'", "=>", "null", ",", "'option'", "=>", "null", ",", "'value'", "=>", "''", ",", "'choices'", "=>", "[", "]", ",", "'...
Render radio buttons. @param array $args
[ "Render", "radio", "buttons", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L299-L331
pressbooks/pressbooks
inc/class-options.php
Options.renderSelect
static function renderSelect( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'choices' => [], 'multiple' => false, 'disabled' => false, 'description' => null, ]; $args = wp_parse_args( $args, $defaults ); $options = ''; foreach ( $args['choices'] as $key => $label ) { $options .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $key, $args['value'], false ), $label ); } printf( '<select name="%s[%s]" id="%s" %s%s>%s</select>', $args['name'], $args['option'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
php
static function renderSelect( $args ) { $defaults = [ 'id' => null, 'name' => null, 'option' => null, 'value' => '', 'choices' => [], 'multiple' => false, 'disabled' => false, 'description' => null, ]; $args = wp_parse_args( $args, $defaults ); $options = ''; foreach ( $args['choices'] as $key => $label ) { $options .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $key, $args['value'], false ), $label ); } printf( '<select name="%s[%s]" id="%s" %s%s>%s</select>', $args['name'], $args['option'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); if ( isset( $args['description'] ) ) { printf( '<p class="description">%s</p>', $args['description'] ); } }
[ "static", "function", "renderSelect", "(", "$", "args", ")", "{", "$", "defaults", "=", "[", "'id'", "=>", "null", ",", "'name'", "=>", "null", ",", "'option'", "=>", "null", ",", "'value'", "=>", "''", ",", "'choices'", "=>", "[", "]", ",", "'multip...
Render a select element. @param array $args
[ "Render", "a", "select", "element", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L338-L376
pressbooks/pressbooks
inc/class-options.php
Options.renderCustomSelect
static function renderCustomSelect( $args ) { $defaults = [ 'id' => null, 'name' => null, 'value' => '', 'choices' => [], 'multiple' => false, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); $is_custom = false; if ( ! array_key_exists( $args['value'], $args['choices'] ) ) { $is_custom = true; } $options = ''; foreach ( $args['choices'] as $key => $label ) { $options .= sprintf( '<option value="%s" %s>%s</option>', $key, ( empty( $key ) && $is_custom ) ? ' selected' : selected( $key, $args['value'], false ), $label ); } printf( '<select name="%s" id="%s" %s%s>%s</select><br />', $args['name'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); }
php
static function renderCustomSelect( $args ) { $defaults = [ 'id' => null, 'name' => null, 'value' => '', 'choices' => [], 'multiple' => false, 'disabled' => false, ]; $args = wp_parse_args( $args, $defaults ); $is_custom = false; if ( ! array_key_exists( $args['value'], $args['choices'] ) ) { $is_custom = true; } $options = ''; foreach ( $args['choices'] as $key => $label ) { $options .= sprintf( '<option value="%s" %s>%s</option>', $key, ( empty( $key ) && $is_custom ) ? ' selected' : selected( $key, $args['value'], false ), $label ); } printf( '<select name="%s" id="%s" %s%s>%s</select><br />', $args['name'], $args['id'], ( $args['multiple'] ) ? ' multiple' : '', ( ! empty( $args['disabled'] ) ) ? ' disabled' : '', $options ); }
[ "static", "function", "renderCustomSelect", "(", "$", "args", ")", "{", "$", "defaults", "=", "[", "'id'", "=>", "null", ",", "'name'", "=>", "null", ",", "'value'", "=>", "''", ",", "'choices'", "=>", "[", "]", ",", "'multiple'", "=>", "false", ",", ...
Render a custom select element. @param array $args
[ "Render", "a", "custom", "select", "element", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-options.php#L383-L416
pressbooks/pressbooks
inc/modules/export/htmlbook/class-htmlbook.php
HTMLBook.convert
public function convert() { // Get HTMLBook $output = $this->transform( true ); if ( ! $output ) { return false; } // Save HTMLBook as file in exports folder $filename = $this->timestampedFileName( '-htmlbook.html' ); \Pressbooks\Utility\put_contents( $filename, $output ); $this->outputPath = $filename; return true; }
php
public function convert() { // Get HTMLBook $output = $this->transform( true ); if ( ! $output ) { return false; } // Save HTMLBook as file in exports folder $filename = $this->timestampedFileName( '-htmlbook.html' ); \Pressbooks\Utility\put_contents( $filename, $output ); $this->outputPath = $filename; return true; }
[ "public", "function", "convert", "(", ")", "{", "// Get HTMLBook", "$", "output", "=", "$", "this", "->", "transform", "(", "true", ")", ";", "if", "(", "!", "$", "output", ")", "{", "return", "false", ";", "}", "// Save HTMLBook as file in exports folder", ...
Create $this->outputPath @return bool
[ "Create", "$this", "-", ">", "outputPath" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/htmlbook/class-htmlbook.php#L122-L139