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/export/odt/class-odt.php
Odt.validate
function validate() { // Is this an ODT? if ( ! $this->isOdt( $this->outputPath ) ) { $this->logError( \Pressbooks\Utility\get_contents( $this->logfile ) ); return false; } return true; }
php
function validate() { // Is this an ODT? if ( ! $this->isOdt( $this->outputPath ) ) { $this->logError( \Pressbooks\Utility\get_contents( $this->logfile ) ); return false; } return true; }
[ "function", "validate", "(", ")", "{", "// Is this an ODT?", "if", "(", "!", "$", "this", "->", "isOdt", "(", "$", "this", "->", "outputPath", ")", ")", "{", "$", "this", "->", "logError", "(", "\\", "Pressbooks", "\\", "Utility", "\\", "get_contents", "(", "$", "this", "->", "logfile", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
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/odt/class-odt.php#L257-L268
pressbooks/pressbooks
inc/modules/export/odt/class-odt.php
Odt.fetchAndSaveUniqueImage
protected function fetchAndSaveUniqueImage( $url, $fullpath ) { // Cheap cache static $already_done = []; if ( isset( $already_done[ $url ] ) ) { return $already_done[ $url ]; } $response = wp_remote_get( $url, [ 'timeout' => $this->timeout, ] ); // WordPress error? if ( is_wp_error( $response ) ) { // TODO: Better handling in the event of $response->get_error_message(); $already_done[ $url ] = ''; return ''; } // Basename without query string $filename = explode( '?', basename( $url ) ); // 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 = \Pressbooks\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-odt-', 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 ) ) { $already_done[ $url ] = ''; fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not an image } if ( $this->compressImages ) { $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 $already_done[ $url ] = $filename; return $filename; }
php
protected function fetchAndSaveUniqueImage( $url, $fullpath ) { // Cheap cache static $already_done = []; if ( isset( $already_done[ $url ] ) ) { return $already_done[ $url ]; } $response = wp_remote_get( $url, [ 'timeout' => $this->timeout, ] ); // WordPress error? if ( is_wp_error( $response ) ) { // TODO: Better handling in the event of $response->get_error_message(); $already_done[ $url ] = ''; return ''; } // Basename without query string $filename = explode( '?', basename( $url ) ); // 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 = \Pressbooks\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-odt-', 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 ) ) { $already_done[ $url ] = ''; fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not an image } if ( $this->compressImages ) { $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 $already_done[ $url ] = $filename; return $filename; }
[ "protected", "function", "fetchAndSaveUniqueImage", "(", "$", "url", ",", "$", "fullpath", ")", "{", "// Cheap cache", "static", "$", "already_done", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "already_done", "[", "$", "url", "]", ")", ")", "{", "return", "$", "already_done", "[", "$", "url", "]", ";", "}", "$", "response", "=", "wp_remote_get", "(", "$", "url", ",", "[", "'timeout'", "=>", "$", "this", "->", "timeout", ",", "]", ")", ";", "// WordPress error?", "if", "(", "is_wp_error", "(", "$", "response", ")", ")", "{", "// TODO: Better handling in the event of $response->get_error_message();", "$", "already_done", "[", "$", "url", "]", "=", "''", ";", "return", "''", ";", "}", "// Basename without query string", "$", "filename", "=", "explode", "(", "'?'", ",", "basename", "(", "$", "url", ")", ")", ";", "// 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", "=", "\\", "Pressbooks", "\\", "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-odt-'", ",", "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", ")", ")", "{", "$", "already_done", "[", "$", "url", "]", "=", "''", ";", "fclose", "(", "$", "GLOBALS", "[", "$", "resource_key", "]", ")", ";", "// @codingStandardsIgnoreLine", "return", "''", ";", "// Not an image", "}", "if", "(", "$", "this", "->", "compressImages", ")", "{", "$", "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", "$", "already_done", "[", "$", "url", "]", "=", "$", "filename", ";", "return", "$", "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. @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/odt/class-odt.php#L308-L380
pressbooks/pressbooks
inc/modules/export/odt/class-odt.php
Odt.deleteTmpDir
protected function deleteTmpDir() { // Cleanup temporary directory, if any if ( ! empty( $this->tmpDir ) ) { \Pressbooks\Utility\rmrdir( $this->tmpDir ); } // Cleanup deprecated junk, if any $exports_folder = untrailingslashit( pathinfo( $this->outputPath, PATHINFO_DIRNAME ) ); if ( ! empty( $exports_folder ) ) { \Pressbooks\Utility\rmrdir( "{$exports_folder}/META-INF" ); \Pressbooks\Utility\rmrdir( "{$exports_folder}/media" ); } }
php
protected function deleteTmpDir() { // Cleanup temporary directory, if any if ( ! empty( $this->tmpDir ) ) { \Pressbooks\Utility\rmrdir( $this->tmpDir ); } // Cleanup deprecated junk, if any $exports_folder = untrailingslashit( pathinfo( $this->outputPath, PATHINFO_DIRNAME ) ); if ( ! empty( $exports_folder ) ) { \Pressbooks\Utility\rmrdir( "{$exports_folder}/META-INF" ); \Pressbooks\Utility\rmrdir( "{$exports_folder}/media" ); } }
[ "protected", "function", "deleteTmpDir", "(", ")", "{", "// Cleanup temporary directory, if any", "if", "(", "!", "empty", "(", "$", "this", "->", "tmpDir", ")", ")", "{", "\\", "Pressbooks", "\\", "Utility", "\\", "rmrdir", "(", "$", "this", "->", "tmpDir", ")", ";", "}", "// Cleanup deprecated junk, if any", "$", "exports_folder", "=", "untrailingslashit", "(", "pathinfo", "(", "$", "this", "->", "outputPath", ",", "PATHINFO_DIRNAME", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "exports_folder", ")", ")", "{", "\\", "Pressbooks", "\\", "Utility", "\\", "rmrdir", "(", "\"{$exports_folder}/META-INF\"", ")", ";", "\\", "Pressbooks", "\\", "Utility", "\\", "rmrdir", "(", "\"{$exports_folder}/media\"", ")", ";", "}", "}" ]
Delete temporary directories
[ "Delete", "temporary", "directories" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/odt/class-odt.php#L385-L396
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.getProperties
protected function getProperties( $html_file ) { $html = \Pressbooks\Utility\get_contents( $html_file ); $properties = []; if ( empty( $html ) ) { throw new \Exception( 'File contents empty for getProperties' ); } if ( $this->isMathML( $html ) ) { $properties['mathml'] = 1; } if ( $this->isScripted( $html ) ) { $properties['scripted'] = 1; } // TODO: Check for remote resources return $properties; }
php
protected function getProperties( $html_file ) { $html = \Pressbooks\Utility\get_contents( $html_file ); $properties = []; if ( empty( $html ) ) { throw new \Exception( 'File contents empty for getProperties' ); } if ( $this->isMathML( $html ) ) { $properties['mathml'] = 1; } if ( $this->isScripted( $html ) ) { $properties['scripted'] = 1; } // TODO: Check for remote resources return $properties; }
[ "protected", "function", "getProperties", "(", "$", "html_file", ")", "{", "$", "html", "=", "\\", "Pressbooks", "\\", "Utility", "\\", "get_contents", "(", "$", "html_file", ")", ";", "$", "properties", "=", "[", "]", ";", "if", "(", "empty", "(", "$", "html", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'File contents empty for getProperties'", ")", ";", "}", "if", "(", "$", "this", "->", "isMathML", "(", "$", "html", ")", ")", "{", "$", "properties", "[", "'mathml'", "]", "=", "1", ";", "}", "if", "(", "$", "this", "->", "isScripted", "(", "$", "html", ")", ")", "{", "$", "properties", "[", "'scripted'", "]", "=", "1", ";", "}", "// TODO: Check for remote resources", "return", "$", "properties", ";", "}" ]
Check for existence of properties attributes @param string $html_file @return array $properties @throws \Exception
[ "Check", "for", "existence", "of", "properties", "attributes" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L189-L209
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.isMathML
protected function isMathML( $html ) { foreach ( $this->MathMLTags as $tag ) { if ( false !== stripos( $html, "<$tag>" ) ) { return true; } } return false; }
php
protected function isMathML( $html ) { foreach ( $this->MathMLTags as $tag ) { if ( false !== stripos( $html, "<$tag>" ) ) { return true; } } return false; }
[ "protected", "function", "isMathML", "(", "$", "html", ")", "{", "foreach", "(", "$", "this", "->", "MathMLTags", "as", "$", "tag", ")", "{", "if", "(", "false", "!==", "stripos", "(", "$", "html", ",", "\"<$tag>\"", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check for existence of scripting MathML elements @param string $html @return bool
[ "Check", "for", "existence", "of", "scripting", "MathML", "elements" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L218-L227
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.isScripted
protected function isScripted( $html ) { if ( preg_match( '/<script[^>]*>.*?<\/script>/is', $html ) ) { return true; } try { $html5 = new HtmlParser( true ); $doc = $html5->loadHTML( $html ); foreach ( $doc->getElementsByTagname( '*' ) as $element ) { foreach ( iterator_to_array( $element->attributes ) as $name => $attribute ) { if ( in_array( $name, $this->javaScriptEvents, true ) ) { return true; } } } } catch ( \Exception $e ) { debug_error_log( $e ); } return false; }
php
protected function isScripted( $html ) { if ( preg_match( '/<script[^>]*>.*?<\/script>/is', $html ) ) { return true; } try { $html5 = new HtmlParser( true ); $doc = $html5->loadHTML( $html ); foreach ( $doc->getElementsByTagname( '*' ) as $element ) { foreach ( iterator_to_array( $element->attributes ) as $name => $attribute ) { if ( in_array( $name, $this->javaScriptEvents, true ) ) { return true; } } } } catch ( \Exception $e ) { debug_error_log( $e ); } return false; }
[ "protected", "function", "isScripted", "(", "$", "html", ")", "{", "if", "(", "preg_match", "(", "'/<script[^>]*>.*?<\\/script>/is'", ",", "$", "html", ")", ")", "{", "return", "true", ";", "}", "try", "{", "$", "html5", "=", "new", "HtmlParser", "(", "true", ")", ";", "$", "doc", "=", "$", "html5", "->", "loadHTML", "(", "$", "html", ")", ";", "foreach", "(", "$", "doc", "->", "getElementsByTagname", "(", "'*'", ")", "as", "$", "element", ")", "{", "foreach", "(", "iterator_to_array", "(", "$", "element", "->", "attributes", ")", "as", "$", "name", "=>", "$", "attribute", ")", "{", "if", "(", "in_array", "(", "$", "name", ",", "$", "this", "->", "javaScriptEvents", ",", "true", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "debug_error_log", "(", "$", "e", ")", ";", "}", "return", "false", ";", "}" ]
Check for existence of scripting elements @param string $html @return bool
[ "Check", "for", "existence", "of", "scripting", "elements" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L237-L258
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.tidy
protected function tidy( $html ) { // Venn diagram join between XTHML + HTML5 Deprecated Attributes // // Our $spec is artisanally hand crafted based on squinting very hard while reading the following docs: // // + 2.3 - Extra HTML specifications using the $spec parameter // + 3.4.6 - Transformation of deprecated attributes // + 3.3.2 - Tag-transformation for better compliance with standards // + HTML5 - Deprecated Tags & Attributes // // That is we do not remove deprecated attributes that are already transformed by htmLawed // // More info: // + http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/beta/htmLawed_README.htm // + http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_epub3', 'tidy' => -1, 'make_tag_strict' => 2, 'comment' => 1, ]; $spec = ''; $spec .= 'a=,-charset,-coords,-rev,-shape;'; $spec .= 'area=-nohref;'; $spec .= 'col=-align,-char,-charoff,-valign,-width;'; $spec .= 'colgroup=-align,-char,-charoff,-valign,-width;'; $spec .= 'div=-align;'; $spec .= 'iframe=-align,-frameborder,-longdesc,-marginheight,-marginwidth,-scrolling;'; $spec .= 'img=-longdesc,-srcset;'; $spec .= 'link=-charset,-rev,-target;'; $spec .= 'menu=-compact;'; $spec .= 'object=-archive,-classid,-codebase,-codetype,-declare,-standby;'; $spec .= 'param=-type,-valuetype;'; $spec .= 't=-abbr,-axis;'; $spec .= 'table=-border,-cellpadding,-frame,-rules;'; $spec .= 'tbody=-align,-char,-charoff,-valign;'; $spec .= 'td=-axis,-abbr,-align,-char,-charoff,-scope,-valign;'; $spec .= 'tfoot=-align,-char,-charoff,-valign;'; $spec .= 'th=-align,-char,-charoff,-valign;'; $spec .= 'thead=-align,-char,-charoff,-valign;'; $spec .= 'tr=-align,-char,-charoff,-valign;'; $spec .= 'ul=-type;'; // Reset on each htmLawed invocation unset( $GLOBALS['hl_Ids'] ); if ( ! empty( $this->fixme ) ) { $GLOBALS['hl_Ids'] = $this->fixme; } $html = HtmLawed::filter( $html, $config, $spec ); return $html; }
php
protected function tidy( $html ) { // Venn diagram join between XTHML + HTML5 Deprecated Attributes // // Our $spec is artisanally hand crafted based on squinting very hard while reading the following docs: // // + 2.3 - Extra HTML specifications using the $spec parameter // + 3.4.6 - Transformation of deprecated attributes // + 3.3.2 - Tag-transformation for better compliance with standards // + HTML5 - Deprecated Tags & Attributes // // That is we do not remove deprecated attributes that are already transformed by htmLawed // // More info: // + http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/beta/htmLawed_README.htm // + http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm $config = [ 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'unique_ids' => 'fixme-', 'hook' => '\Pressbooks\Sanitize\html5_to_epub3', 'tidy' => -1, 'make_tag_strict' => 2, 'comment' => 1, ]; $spec = ''; $spec .= 'a=,-charset,-coords,-rev,-shape;'; $spec .= 'area=-nohref;'; $spec .= 'col=-align,-char,-charoff,-valign,-width;'; $spec .= 'colgroup=-align,-char,-charoff,-valign,-width;'; $spec .= 'div=-align;'; $spec .= 'iframe=-align,-frameborder,-longdesc,-marginheight,-marginwidth,-scrolling;'; $spec .= 'img=-longdesc,-srcset;'; $spec .= 'link=-charset,-rev,-target;'; $spec .= 'menu=-compact;'; $spec .= 'object=-archive,-classid,-codebase,-codetype,-declare,-standby;'; $spec .= 'param=-type,-valuetype;'; $spec .= 't=-abbr,-axis;'; $spec .= 'table=-border,-cellpadding,-frame,-rules;'; $spec .= 'tbody=-align,-char,-charoff,-valign;'; $spec .= 'td=-axis,-abbr,-align,-char,-charoff,-scope,-valign;'; $spec .= 'tfoot=-align,-char,-charoff,-valign;'; $spec .= 'th=-align,-char,-charoff,-valign;'; $spec .= 'thead=-align,-char,-charoff,-valign;'; $spec .= 'tr=-align,-char,-charoff,-valign;'; $spec .= 'ul=-type;'; // Reset on each htmLawed invocation unset( $GLOBALS['hl_Ids'] ); if ( ! empty( $this->fixme ) ) { $GLOBALS['hl_Ids'] = $this->fixme; } $html = HtmLawed::filter( $html, $config, $spec ); return $html; }
[ "protected", "function", "tidy", "(", "$", "html", ")", "{", "// Venn diagram join between XTHML + HTML5 Deprecated Attributes", "//", "// Our $spec is artisanally hand crafted based on squinting very hard while reading the following docs:", "//", "// + 2.3 - Extra HTML specifications using the $spec parameter", "// + 3.4.6 - Transformation of deprecated attributes", "// + 3.3.2 - Tag-transformation for better compliance with standards", "// + HTML5 - Deprecated Tags & Attributes", "//", "// That is we do not remove deprecated attributes that are already transformed by htmLawed", "//", "// More info:", "// + http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/beta/htmLawed_README.htm", "// + http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm", "$", "config", "=", "[", "'valid_xhtml'", "=>", "1", ",", "'no_deprecated_attr'", "=>", "2", ",", "'unique_ids'", "=>", "'fixme-'", ",", "'hook'", "=>", "'\\Pressbooks\\Sanitize\\html5_to_epub3'", ",", "'tidy'", "=>", "-", "1", ",", "'make_tag_strict'", "=>", "2", ",", "'comment'", "=>", "1", ",", "]", ";", "$", "spec", "=", "''", ";", "$", "spec", ".=", "'a=,-charset,-coords,-rev,-shape;'", ";", "$", "spec", ".=", "'area=-nohref;'", ";", "$", "spec", ".=", "'col=-align,-char,-charoff,-valign,-width;'", ";", "$", "spec", ".=", "'colgroup=-align,-char,-charoff,-valign,-width;'", ";", "$", "spec", ".=", "'div=-align;'", ";", "$", "spec", ".=", "'iframe=-align,-frameborder,-longdesc,-marginheight,-marginwidth,-scrolling;'", ";", "$", "spec", ".=", "'img=-longdesc,-srcset;'", ";", "$", "spec", ".=", "'link=-charset,-rev,-target;'", ";", "$", "spec", ".=", "'menu=-compact;'", ";", "$", "spec", ".=", "'object=-archive,-classid,-codebase,-codetype,-declare,-standby;'", ";", "$", "spec", ".=", "'param=-type,-valuetype;'", ";", "$", "spec", ".=", "'t=-abbr,-axis;'", ";", "$", "spec", ".=", "'table=-border,-cellpadding,-frame,-rules;'", ";", "$", "spec", ".=", "'tbody=-align,-char,-charoff,-valign;'", ";", "$", "spec", ".=", "'td=-axis,-abbr,-align,-char,-charoff,-scope,-valign;'", ";", "$", "spec", ".=", "'tfoot=-align,-char,-charoff,-valign;'", ";", "$", "spec", ".=", "'th=-align,-char,-charoff,-valign;'", ";", "$", "spec", ".=", "'thead=-align,-char,-charoff,-valign;'", ";", "$", "spec", ".=", "'tr=-align,-char,-charoff,-valign;'", ";", "$", "spec", ".=", "'ul=-type;'", ";", "// Reset on each htmLawed invocation", "unset", "(", "$", "GLOBALS", "[", "'hl_Ids'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "fixme", ")", ")", "{", "$", "GLOBALS", "[", "'hl_Ids'", "]", "=", "$", "this", "->", "fixme", ";", "}", "$", "html", "=", "HtmLawed", "::", "filter", "(", "$", "html", ",", "$", "config", ",", "$", "spec", ")", ";", "return", "$", "html", ";", "}" ]
Tidy HTML @param string $html @return string
[ "Tidy", "HTML" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L267-L325
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.fetchAndSaveUniqueMedia
protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { if ( isset( $this->fetchedMediaCache[ $url ] ) ) { return $this->fetchedMediaCache[ $url ]; } $response = wp_remote_get( $url, [ 'timeout' => $this->timeout, ] ); // 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, [ 'timeout' => $this->timeout, ] ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } } catch ( \Exception $exc ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub3\fetchAndSaveUniqueMedia wp_error on wp_remote_get() - ' . $response->get_error_message() . ' - ' . $exc->getMessage() ); return ''; } } // Basename without query string $filename = explode( '?', basename( $url ) ); $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 media 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\Media\is_valid_media( $tmp_file, $filename ) ) { $this->fetchedMediaCache[ $url ] = ''; fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not a valid media type } // 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->fetchedMediaCache[ $url ] = $filename; return $filename; }
php
protected function fetchAndSaveUniqueMedia( $url, $fullpath ) { if ( isset( $this->fetchedMediaCache[ $url ] ) ) { return $this->fetchedMediaCache[ $url ]; } $response = wp_remote_get( $url, [ 'timeout' => $this->timeout, ] ); // 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, [ 'timeout' => $this->timeout, ] ); if ( is_wp_error( $response ) ) { throw new \Exception( 'Bad URL: ' . $url ); } } catch ( \Exception $exc ) { $this->fetchedImageCache[ $url ] = ''; debug_error_log( '\PressBooks\Export\Epub3\fetchAndSaveUniqueMedia wp_error on wp_remote_get() - ' . $response->get_error_message() . ' - ' . $exc->getMessage() ); return ''; } } // Basename without query string $filename = explode( '?', basename( $url ) ); $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 media 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\Media\is_valid_media( $tmp_file, $filename ) ) { $this->fetchedMediaCache[ $url ] = ''; fclose( $GLOBALS[ $resource_key ] ); // @codingStandardsIgnoreLine return ''; // Not a valid media type } // 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->fetchedMediaCache[ $url ] = $filename; return $filename; }
[ "protected", "function", "fetchAndSaveUniqueMedia", "(", "$", "url", ",", "$", "fullpath", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "fetchedMediaCache", "[", "$", "url", "]", ")", ")", "{", "return", "$", "this", "->", "fetchedMediaCache", "[", "$", "url", "]", ";", "}", "$", "response", "=", "wp_remote_get", "(", "$", "url", ",", "[", "'timeout'", "=>", "$", "this", "->", "timeout", ",", "]", ")", ";", "// 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", ",", "[", "'timeout'", "=>", "$", "this", "->", "timeout", ",", "]", ")", ";", "if", "(", "is_wp_error", "(", "$", "response", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Bad URL: '", ".", "$", "url", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "exc", ")", "{", "$", "this", "->", "fetchedImageCache", "[", "$", "url", "]", "=", "''", ";", "debug_error_log", "(", "'\\PressBooks\\Export\\Epub3\\fetchAndSaveUniqueMedia wp_error on wp_remote_get() - '", ".", "$", "response", "->", "get_error_message", "(", ")", ".", "' - '", ".", "$", "exc", "->", "getMessage", "(", ")", ")", ";", "return", "''", ";", "}", "}", "// Basename without query string", "$", "filename", "=", "explode", "(", "'?'", ",", "basename", "(", "$", "url", ")", ")", ";", "$", "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 media 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", "\\", "Media", "\\", "is_valid_media", "(", "$", "tmp_file", ",", "$", "filename", ")", ")", "{", "$", "this", "->", "fetchedMediaCache", "[", "$", "url", "]", "=", "''", ";", "fclose", "(", "$", "GLOBALS", "[", "$", "resource_key", "]", ")", ";", "// @codingStandardsIgnoreLine", "return", "''", ";", "// Not a valid media type", "}", "// 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", "->", "fetchedMediaCache", "[", "$", "url", "]", "=", "$", "filename", ";", "return", "$", "filename", ";", "}" ]
Fetch a url with wp_remote_get(), save it to $fullpath with a unique name. Will return an empty string if something went wrong. @param string $url @param string $fullpath @return string|array
[ "Fetch", "a", "url", "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-epub3.php#L336-L406
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.scrapeAndKneadMedia
protected function scrapeAndKneadMedia( \DOMDocument $doc ) { $fullpath = $this->tmpDir . '/OEBPS/assets'; $tags = [ 'source', 'audio', 'video' ]; foreach ( $tags as $tag ) { $sources = $doc->getElementsByTagName( $tag ); foreach ( $sources as $source ) { /** @var $source \DOMElement */ if ( ! empty( $source->getAttribute( 'src' ) ) ) { // Fetch the audio file $url = $source->getAttribute( 'src' ); $filename = $this->fetchAndSaveUniqueMedia( $url, $fullpath ); if ( $filename ) { // Change src to new relative path $source->setAttribute( 'src', 'assets/' . $filename ); } else { // Tag broken media $source->setAttribute( 'src', "{$url}#fixme" ); } } } } return $doc; }
php
protected function scrapeAndKneadMedia( \DOMDocument $doc ) { $fullpath = $this->tmpDir . '/OEBPS/assets'; $tags = [ 'source', 'audio', 'video' ]; foreach ( $tags as $tag ) { $sources = $doc->getElementsByTagName( $tag ); foreach ( $sources as $source ) { /** @var $source \DOMElement */ if ( ! empty( $source->getAttribute( 'src' ) ) ) { // Fetch the audio file $url = $source->getAttribute( 'src' ); $filename = $this->fetchAndSaveUniqueMedia( $url, $fullpath ); if ( $filename ) { // Change src to new relative path $source->setAttribute( 'src', 'assets/' . $filename ); } else { // Tag broken media $source->setAttribute( 'src', "{$url}#fixme" ); } } } } return $doc; }
[ "protected", "function", "scrapeAndKneadMedia", "(", "\\", "DOMDocument", "$", "doc", ")", "{", "$", "fullpath", "=", "$", "this", "->", "tmpDir", ".", "'/OEBPS/assets'", ";", "$", "tags", "=", "[", "'source'", ",", "'audio'", ",", "'video'", "]", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "sources", "=", "$", "doc", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "foreach", "(", "$", "sources", "as", "$", "source", ")", "{", "/** @var $source \\DOMElement */", "if", "(", "!", "empty", "(", "$", "source", "->", "getAttribute", "(", "'src'", ")", ")", ")", "{", "// Fetch the audio file", "$", "url", "=", "$", "source", "->", "getAttribute", "(", "'src'", ")", ";", "$", "filename", "=", "$", "this", "->", "fetchAndSaveUniqueMedia", "(", "$", "url", ",", "$", "fullpath", ")", ";", "if", "(", "$", "filename", ")", "{", "// Change src to new relative path", "$", "source", "->", "setAttribute", "(", "'src'", ",", "'assets/'", ".", "$", "filename", ")", ";", "}", "else", "{", "// Tag broken media", "$", "source", "->", "setAttribute", "(", "'src'", ",", "\"{$url}#fixme\"", ")", ";", "}", "}", "}", "}", "return", "$", "doc", ";", "}" ]
Parse HTML snippet, download all found <audio>, <video> and <source> tags into /OEBPS/assets/, return the HTML with changed 'src' paths. @param \DOMDocument $doc @return \DOMDocument
[ "Parse", "HTML", "snippet", "download", "all", "found", "<audio", ">", "<video", ">", "and", "<source", ">", "tags", "into", "/", "OEBPS", "/", "assets", "/", "return", "the", "HTML", "with", "changed", "src", "paths", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L416-L443
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.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 = [ '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 ) ); // Loop through the html files for the manifest and assemble them. Assign properties based on their content. $html = ''; foreach ( $this->manifest as $k => $v ) { $properties = $this->getProperties( $this->tmpDir . '/OEBPS/' . $v['filename'] ); array_key_exists( 'mathml', $properties ) ? $mathml = 'properties="mathml" ' : $mathml = ''; array_key_exists( 'scripted', $properties ) ? $scripted = 'properties="scripted" ' : $scripted = ''; $html .= sprintf( '<item id="%s" href="OEBPS/%s" %s%smedia-type="application/xhtml+xml" />', $k, $v['filename'], $mathml, $scripted ) . "\n\t\t"; } $vars['manifest_filelist'] = $html; // 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/epub3/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 = [ '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 ) ); // Loop through the html files for the manifest and assemble them. Assign properties based on their content. $html = ''; foreach ( $this->manifest as $k => $v ) { $properties = $this->getProperties( $this->tmpDir . '/OEBPS/' . $v['filename'] ); array_key_exists( 'mathml', $properties ) ? $mathml = 'properties="mathml" ' : $mathml = ''; array_key_exists( 'scripted', $properties ) ? $scripted = 'properties="scripted" ' : $scripted = ''; $html .= sprintf( '<item id="%s" href="OEBPS/%s" %s%smedia-type="application/xhtml+xml" />', $k, $v['filename'], $mathml, $scripted ) . "\n\t\t"; } $vars['manifest_filelist'] = $html; // 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/epub3/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 call $this->createOEBPS() ?'", ")", ";", "}", "$", "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", ")", ")", ";", "// Loop through the html files for the manifest and assemble them. Assign properties based on their content.", "$", "html", "=", "''", ";", "foreach", "(", "$", "this", "->", "manifest", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "properties", "=", "$", "this", "->", "getProperties", "(", "$", "this", "->", "tmpDir", ".", "'/OEBPS/'", ".", "$", "v", "[", "'filename'", "]", ")", ";", "array_key_exists", "(", "'mathml'", ",", "$", "properties", ")", "?", "$", "mathml", "=", "'properties=\"mathml\" '", ":", "$", "mathml", "=", "''", ";", "array_key_exists", "(", "'scripted'", ",", "$", "properties", ")", "?", "$", "scripted", "=", "'properties=\"scripted\" '", ":", "$", "scripted", "=", "''", ";", "$", "html", ".=", "sprintf", "(", "'<item id=\"%s\" href=\"OEBPS/%s\" %s%smedia-type=\"application/xhtml+xml\" />'", ",", "$", "k", ",", "$", "v", "[", "'filename'", "]", ",", "$", "mathml", ",", "$", "scripted", ")", ".", "\"\\n\\t\\t\"", ";", "}", "$", "vars", "[", "'manifest_filelist'", "]", "=", "$", "html", ";", "// 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/epub3/opf.php'", ",", "$", "vars", ")", ")", ";", "}" ]
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-epub3.php#L453-L494
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.createNCX
protected function createNCX( $book_contents, $metadata ) { if ( empty( $this->manifest ) ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' ); } // Sanitize variables for usage in XML template $vars = [ 'author' => ! \Pressbooks\Utility\empty_space( $metadata['pb_authors'] ) ? sanitize_xml_attribute( oxford_comma_explode( $metadata['pb_authors'] )[0] ) : '', 'manifest' => $this->manifest, 'dtd_uid' => ! empty( $metadata['pb_ebook_isbn'] ) ? sanitize_xml_attribute( $metadata['pb_ebook_isbn'] ) : sanitize_xml_attribute( get_bloginfo( 'url' ) ), 'enable_external_identifier' => false, 'lang' => $this->lang, ]; \Pressbooks\Utility\put_contents( $this->tmpDir . '/toc.xhtml', $this->loadTemplate( $this->dir . '/templates/epub3/toc.php', $vars ) ); // For backwards compatibility \Pressbooks\Utility\put_contents( $this->tmpDir . '/toc.ncx', $this->loadTemplate( $this->dir . '/templates/epub201/ncx.php', $vars ) ); }
php
protected function createNCX( $book_contents, $metadata ) { if ( empty( $this->manifest ) ) { throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' ); } // Sanitize variables for usage in XML template $vars = [ 'author' => ! \Pressbooks\Utility\empty_space( $metadata['pb_authors'] ) ? sanitize_xml_attribute( oxford_comma_explode( $metadata['pb_authors'] )[0] ) : '', 'manifest' => $this->manifest, 'dtd_uid' => ! empty( $metadata['pb_ebook_isbn'] ) ? sanitize_xml_attribute( $metadata['pb_ebook_isbn'] ) : sanitize_xml_attribute( get_bloginfo( 'url' ) ), 'enable_external_identifier' => false, 'lang' => $this->lang, ]; \Pressbooks\Utility\put_contents( $this->tmpDir . '/toc.xhtml', $this->loadTemplate( $this->dir . '/templates/epub3/toc.php', $vars ) ); // For backwards compatibility \Pressbooks\Utility\put_contents( $this->tmpDir . '/toc.ncx', $this->loadTemplate( $this->dir . '/templates/epub201/ncx.php', $vars ) ); }
[ "protected", "function", "createNCX", "(", "$", "book_contents", ",", "$", "metadata", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "manifest", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?'", ")", ";", "}", "// Sanitize variables for usage in XML template", "$", "vars", "=", "[", "'author'", "=>", "!", "\\", "Pressbooks", "\\", "Utility", "\\", "empty_space", "(", "$", "metadata", "[", "'pb_authors'", "]", ")", "?", "sanitize_xml_attribute", "(", "oxford_comma_explode", "(", "$", "metadata", "[", "'pb_authors'", "]", ")", "[", "0", "]", ")", ":", "''", ",", "'manifest'", "=>", "$", "this", "->", "manifest", ",", "'dtd_uid'", "=>", "!", "empty", "(", "$", "metadata", "[", "'pb_ebook_isbn'", "]", ")", "?", "sanitize_xml_attribute", "(", "$", "metadata", "[", "'pb_ebook_isbn'", "]", ")", ":", "sanitize_xml_attribute", "(", "get_bloginfo", "(", "'url'", ")", ")", ",", "'enable_external_identifier'", "=>", "false", ",", "'lang'", "=>", "$", "this", "->", "lang", ",", "]", ";", "\\", "Pressbooks", "\\", "Utility", "\\", "put_contents", "(", "$", "this", "->", "tmpDir", ".", "'/toc.xhtml'", ",", "$", "this", "->", "loadTemplate", "(", "$", "this", "->", "dir", ".", "'/templates/epub3/toc.php'", ",", "$", "vars", ")", ")", ";", "// For backwards compatibility", "\\", "Pressbooks", "\\", "Utility", "\\", "put_contents", "(", "$", "this", "->", "tmpDir", ".", "'/toc.ncx'", ",", "$", "this", "->", "loadTemplate", "(", "$", "this", "->", "dir", ".", "'/templates/epub201/ncx.php'", ",", "$", "vars", ")", ")", ";", "}" ]
Create NCX file. @param array $book_contents @param array $metadata @throws \Exception
[ "Create", "NCX", "file", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L504-L529
pressbooks/pressbooks
inc/modules/export/epub/class-epub3.php
Epub3.loadTemplate
protected function loadTemplate( $path, array $vars = [] ) { $search = '/templates/epub201/'; $replace = '/templates/epub3/'; $pos = strpos( $path, $search ); if ( false !== $pos ) { $new_path = substr_replace( $path, $replace, $pos, strlen( $search ) ); if ( file_exists( $new_path ) ) { $path = $new_path; } } return parent::loadTemplate( $path, $vars ); }
php
protected function loadTemplate( $path, array $vars = [] ) { $search = '/templates/epub201/'; $replace = '/templates/epub3/'; $pos = strpos( $path, $search ); if ( false !== $pos ) { $new_path = substr_replace( $path, $replace, $pos, strlen( $search ) ); if ( file_exists( $new_path ) ) { $path = $new_path; } } return parent::loadTemplate( $path, $vars ); }
[ "protected", "function", "loadTemplate", "(", "$", "path", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "$", "search", "=", "'/templates/epub201/'", ";", "$", "replace", "=", "'/templates/epub3/'", ";", "$", "pos", "=", "strpos", "(", "$", "path", ",", "$", "search", ")", ";", "if", "(", "false", "!==", "$", "pos", ")", "{", "$", "new_path", "=", "substr_replace", "(", "$", "path", ",", "$", "replace", ",", "$", "pos", ",", "strlen", "(", "$", "search", ")", ")", ";", "if", "(", "file_exists", "(", "$", "new_path", ")", ")", "{", "$", "path", "=", "$", "new_path", ";", "}", "}", "return", "parent", "::", "loadTemplate", "(", "$", "path", ",", "$", "vars", ")", ";", "}" ]
Override load template function Switch path from /epub201 to /epub3 when possible. @param string $path @param array $vars (optional) @return string @throws \Exception
[ "Override", "load", "template", "function", "Switch", "path", "from", "/", "epub201", "to", "/", "epub3", "when", "possible", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/epub/class-epub3.php#L542-L556
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.register_routes
public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, [ [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_items' ], 'permission_callback' => [ $this, 'get_items_permissions_check' ], 'args' => $this->get_collection_params(), ], 'schema' => [ $this, 'get_public_item_schema' ], ] ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', [ 'args' => [ 'id' => [ 'description' => __( 'Unique identifier for the object.' ), 'type' => 'integer', ], ], [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_item' ], 'permission_callback' => [ $this, 'get_item_permissions_check' ], 'args' => [ 'context' => $this->get_context_param( [ 'default' => 'view', ] ), ], ], ] ); }
php
public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, [ [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_items' ], 'permission_callback' => [ $this, 'get_items_permissions_check' ], 'args' => $this->get_collection_params(), ], 'schema' => [ $this, 'get_public_item_schema' ], ] ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', [ 'args' => [ 'id' => [ 'description' => __( 'Unique identifier for the object.' ), 'type' => 'integer', ], ], [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_item' ], 'permission_callback' => [ $this, 'get_item_permissions_check' ], 'args' => [ 'context' => $this->get_context_param( [ 'default' => 'view', ] ), ], ], ] ); }
[ "public", "function", "register_routes", "(", ")", "{", "register_rest_route", "(", "$", "this", "->", "namespace", ",", "'/'", ".", "$", "this", "->", "rest_base", ",", "[", "[", "'methods'", "=>", "\\", "WP_REST_Server", "::", "READABLE", ",", "'callback'", "=>", "[", "$", "this", ",", "'get_items'", "]", ",", "'permission_callback'", "=>", "[", "$", "this", ",", "'get_items_permissions_check'", "]", ",", "'args'", "=>", "$", "this", "->", "get_collection_params", "(", ")", ",", "]", ",", "'schema'", "=>", "[", "$", "this", ",", "'get_public_item_schema'", "]", ",", "]", ")", ";", "register_rest_route", "(", "$", "this", "->", "namespace", ",", "'/'", ".", "$", "this", "->", "rest_base", ".", "'/(?P<id>[\\d]+)'", ",", "[", "'args'", "=>", "[", "'id'", "=>", "[", "'description'", "=>", "__", "(", "'Unique identifier for the object.'", ")", ",", "'type'", "=>", "'integer'", ",", "]", ",", "]", ",", "[", "'methods'", "=>", "\\", "WP_REST_Server", "::", "READABLE", ",", "'callback'", "=>", "[", "$", "this", ",", "'get_item'", "]", ",", "'permission_callback'", "=>", "[", "$", "this", ",", "'get_item_permissions_check'", "]", ",", "'args'", "=>", "[", "'context'", "=>", "$", "this", "->", "get_context_param", "(", "[", "'default'", "=>", "'view'", ",", "]", ")", ",", "]", ",", "]", ",", "]", ")", ";", "}" ]
Registers routes for Books
[ "Registers", "routes", "for", "Books" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L63-L99
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.get_item_permissions_check
public function get_item_permissions_check( $request ) { if ( $request['id'] === get_network()->site_id ) { return false; } $allowed = false; switch_to_blog( $request['id'] ); if ( 1 === absint( get_option( 'blog_public' ) ) ) { $allowed = true; } restore_current_blog(); return $allowed; }
php
public function get_item_permissions_check( $request ) { if ( $request['id'] === get_network()->site_id ) { return false; } $allowed = false; switch_to_blog( $request['id'] ); if ( 1 === absint( get_option( 'blog_public' ) ) ) { $allowed = true; } restore_current_blog(); return $allowed; }
[ "public", "function", "get_item_permissions_check", "(", "$", "request", ")", "{", "if", "(", "$", "request", "[", "'id'", "]", "===", "get_network", "(", ")", "->", "site_id", ")", "{", "return", "false", ";", "}", "$", "allowed", "=", "false", ";", "switch_to_blog", "(", "$", "request", "[", "'id'", "]", ")", ";", "if", "(", "1", "===", "absint", "(", "get_option", "(", "'blog_public'", ")", ")", ")", "{", "$", "allowed", "=", "true", ";", "}", "restore_current_blog", "(", ")", ";", "return", "$", "allowed", ";", "}" ]
@param \WP_REST_Request $request @return bool
[ "@param", "\\", "WP_REST_Request", "$request" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L180-L197
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.get_items
public function get_items( $request ) { // Register missing routes $this->registerRouteDependencies(); if ( ! empty( $request['search'] ) ) { $response = rest_ensure_response( $this->searchBooks( $request ) ); $this->addNextSearchLinks( $request, $response ); } else { $response = rest_ensure_response( $this->listBooks( $request ) ); $this->addPreviousNextLinks( $request, $response ); } return $response; }
php
public function get_items( $request ) { // Register missing routes $this->registerRouteDependencies(); if ( ! empty( $request['search'] ) ) { $response = rest_ensure_response( $this->searchBooks( $request ) ); $this->addNextSearchLinks( $request, $response ); } else { $response = rest_ensure_response( $this->listBooks( $request ) ); $this->addPreviousNextLinks( $request, $response ); } return $response; }
[ "public", "function", "get_items", "(", "$", "request", ")", "{", "// Register missing routes", "$", "this", "->", "registerRouteDependencies", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "request", "[", "'search'", "]", ")", ")", "{", "$", "response", "=", "rest_ensure_response", "(", "$", "this", "->", "searchBooks", "(", "$", "request", ")", ")", ";", "$", "this", "->", "addNextSearchLinks", "(", "$", "request", ",", "$", "response", ")", ";", "}", "else", "{", "$", "response", "=", "rest_ensure_response", "(", "$", "this", "->", "listBooks", "(", "$", "request", ")", ")", ";", "$", "this", "->", "addPreviousNextLinks", "(", "$", "request", ",", "$", "response", ")", ";", "}", "return", "$", "response", ";", "}" ]
@param \WP_REST_Request $request @return \WP_REST_Response
[ "@param", "\\", "WP_REST_Request", "$request" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L204-L218
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.get_item
public function get_item( $request ) { // Register missing routes $this->registerRouteDependencies(); $result = $this->renderBook( $request['id'] ); $response = rest_ensure_response( $result ); $response->add_links( $this->linkCollector ); return $response; }
php
public function get_item( $request ) { // Register missing routes $this->registerRouteDependencies(); $result = $this->renderBook( $request['id'] ); $response = rest_ensure_response( $result ); $response->add_links( $this->linkCollector ); return $response; }
[ "public", "function", "get_item", "(", "$", "request", ")", "{", "// Register missing routes", "$", "this", "->", "registerRouteDependencies", "(", ")", ";", "$", "result", "=", "$", "this", "->", "renderBook", "(", "$", "request", "[", "'id'", "]", ")", ";", "$", "response", "=", "rest_ensure_response", "(", "$", "result", ")", ";", "$", "response", "->", "add_links", "(", "$", "this", "->", "linkCollector", ")", ";", "return", "$", "response", ";", "}" ]
@param \WP_REST_Request $request @return \WP_REST_Response
[ "@param", "\\", "WP_REST_Request", "$request" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L225-L235
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.renderBook
protected function renderBook( $id, $search = null ) { switch_to_blog( $id ); // Search if ( ! empty( $search ) ) { if ( ! $this->find( $search ) ) { restore_current_blog(); return []; } } $request_metadata = new \WP_REST_Request( 'GET', '/pressbooks/v2/metadata' ); $response_metadata = rest_do_request( $request_metadata ); $request_toc = new \WP_REST_Request( 'GET', '/pressbooks/v2/toc' ); $response_toc = rest_do_request( $request_toc ); $item = [ 'id' => $id, 'link' => get_blogaddress_by_id( $id ), 'metadata' => $this->prepare_response_for_collection( $response_metadata ), 'toc' => $this->prepare_response_for_collection( $response_toc ), ]; $this->linkCollector['api'][] = [ 'href' => get_rest_url( $id ), ]; restore_current_blog(); $this->linkCollector['metadata'][] = [ 'href' => $item['metadata']['_links']['self'][0]['href'], ]; unset( $item['metadata']['_links'] ); $this->linkCollector['toc'][] = [ 'href' => $item['toc']['_links']['self'][0]['href'], ]; foreach ( $item['toc']['_links']['metadata'] as $v ) { $this->linkCollector['metadata'][] = [ 'href' => $v['href'], ]; } unset( $item['toc']['_links'] ); $this->linkCollector['self'][] = [ 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ), ]; return $item; }
php
protected function renderBook( $id, $search = null ) { switch_to_blog( $id ); // Search if ( ! empty( $search ) ) { if ( ! $this->find( $search ) ) { restore_current_blog(); return []; } } $request_metadata = new \WP_REST_Request( 'GET', '/pressbooks/v2/metadata' ); $response_metadata = rest_do_request( $request_metadata ); $request_toc = new \WP_REST_Request( 'GET', '/pressbooks/v2/toc' ); $response_toc = rest_do_request( $request_toc ); $item = [ 'id' => $id, 'link' => get_blogaddress_by_id( $id ), 'metadata' => $this->prepare_response_for_collection( $response_metadata ), 'toc' => $this->prepare_response_for_collection( $response_toc ), ]; $this->linkCollector['api'][] = [ 'href' => get_rest_url( $id ), ]; restore_current_blog(); $this->linkCollector['metadata'][] = [ 'href' => $item['metadata']['_links']['self'][0]['href'], ]; unset( $item['metadata']['_links'] ); $this->linkCollector['toc'][] = [ 'href' => $item['toc']['_links']['self'][0]['href'], ]; foreach ( $item['toc']['_links']['metadata'] as $v ) { $this->linkCollector['metadata'][] = [ 'href' => $v['href'], ]; } unset( $item['toc']['_links'] ); $this->linkCollector['self'][] = [ 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ), ]; return $item; }
[ "protected", "function", "renderBook", "(", "$", "id", ",", "$", "search", "=", "null", ")", "{", "switch_to_blog", "(", "$", "id", ")", ";", "// Search", "if", "(", "!", "empty", "(", "$", "search", ")", ")", "{", "if", "(", "!", "$", "this", "->", "find", "(", "$", "search", ")", ")", "{", "restore_current_blog", "(", ")", ";", "return", "[", "]", ";", "}", "}", "$", "request_metadata", "=", "new", "\\", "WP_REST_Request", "(", "'GET'", ",", "'/pressbooks/v2/metadata'", ")", ";", "$", "response_metadata", "=", "rest_do_request", "(", "$", "request_metadata", ")", ";", "$", "request_toc", "=", "new", "\\", "WP_REST_Request", "(", "'GET'", ",", "'/pressbooks/v2/toc'", ")", ";", "$", "response_toc", "=", "rest_do_request", "(", "$", "request_toc", ")", ";", "$", "item", "=", "[", "'id'", "=>", "$", "id", ",", "'link'", "=>", "get_blogaddress_by_id", "(", "$", "id", ")", ",", "'metadata'", "=>", "$", "this", "->", "prepare_response_for_collection", "(", "$", "response_metadata", ")", ",", "'toc'", "=>", "$", "this", "->", "prepare_response_for_collection", "(", "$", "response_toc", ")", ",", "]", ";", "$", "this", "->", "linkCollector", "[", "'api'", "]", "[", "]", "=", "[", "'href'", "=>", "get_rest_url", "(", "$", "id", ")", ",", "]", ";", "restore_current_blog", "(", ")", ";", "$", "this", "->", "linkCollector", "[", "'metadata'", "]", "[", "]", "=", "[", "'href'", "=>", "$", "item", "[", "'metadata'", "]", "[", "'_links'", "]", "[", "'self'", "]", "[", "0", "]", "[", "'href'", "]", ",", "]", ";", "unset", "(", "$", "item", "[", "'metadata'", "]", "[", "'_links'", "]", ")", ";", "$", "this", "->", "linkCollector", "[", "'toc'", "]", "[", "]", "=", "[", "'href'", "=>", "$", "item", "[", "'toc'", "]", "[", "'_links'", "]", "[", "'self'", "]", "[", "0", "]", "[", "'href'", "]", ",", "]", ";", "foreach", "(", "$", "item", "[", "'toc'", "]", "[", "'_links'", "]", "[", "'metadata'", "]", "as", "$", "v", ")", "{", "$", "this", "->", "linkCollector", "[", "'metadata'", "]", "[", "]", "=", "[", "'href'", "=>", "$", "v", "[", "'href'", "]", ",", "]", ";", "}", "unset", "(", "$", "item", "[", "'toc'", "]", "[", "'_links'", "]", ")", ";", "$", "this", "->", "linkCollector", "[", "'self'", "]", "[", "]", "=", "[", "'href'", "=>", "rest_url", "(", "sprintf", "(", "'%s/%s/%d'", ",", "$", "this", "->", "namespace", ",", "$", "this", "->", "rest_base", ",", "$", "id", ")", ")", ",", "]", ";", "return", "$", "item", ";", "}" ]
Switches to a book, renders it for use in JSON response if found @param int $id @param mixed $search (optional) @return array
[ "Switches", "to", "a", "book", "renders", "it", "for", "use", "in", "JSON", "response", "if", "found" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L272-L323
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.listBooks
protected function listBooks( $request ) { $results = []; $book_ids = $this->listBookIds( $request ); foreach ( $book_ids as $id ) { $response = rest_ensure_response( $this->renderBook( $id ) ); $response->add_links( $this->linkCollector ); $results[] = $this->prepare_response_for_collection( $response ); $this->linkCollector = []; // re-initialize $this->lastKnownBookId = $id; } return $results; }
php
protected function listBooks( $request ) { $results = []; $book_ids = $this->listBookIds( $request ); foreach ( $book_ids as $id ) { $response = rest_ensure_response( $this->renderBook( $id ) ); $response->add_links( $this->linkCollector ); $results[] = $this->prepare_response_for_collection( $response ); $this->linkCollector = []; // re-initialize $this->lastKnownBookId = $id; } return $results; }
[ "protected", "function", "listBooks", "(", "$", "request", ")", "{", "$", "results", "=", "[", "]", ";", "$", "book_ids", "=", "$", "this", "->", "listBookIds", "(", "$", "request", ")", ";", "foreach", "(", "$", "book_ids", "as", "$", "id", ")", "{", "$", "response", "=", "rest_ensure_response", "(", "$", "this", "->", "renderBook", "(", "$", "id", ")", ")", ";", "$", "response", "->", "add_links", "(", "$", "this", "->", "linkCollector", ")", ";", "$", "results", "[", "]", "=", "$", "this", "->", "prepare_response_for_collection", "(", "$", "response", ")", ";", "$", "this", "->", "linkCollector", "=", "[", "]", ";", "// re-initialize", "$", "this", "->", "lastKnownBookId", "=", "$", "id", ";", "}", "return", "$", "results", ";", "}" ]
@param \WP_REST_Request @return array
[ "@param", "\\", "WP_REST_Request" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L330-L341
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.listBookIds
protected function listBookIds( $request ) { global $wpdb; $limit = ! empty( $request['per_page'] ) ? $request['per_page'] : $this->limit; $offset = ! empty( $request['page'] ) ? ( $request['page'] - 1 ) * $limit : 0; $blogs = $wpdb->get_col( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} WHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d ORDER BY blog_id LIMIT %d, %d ", get_network()->site_id, $offset, $limit ) ); $this->totalBooks = $wpdb->get_var( 'SELECT FOUND_ROWS()' ); return $blogs; }
php
protected function listBookIds( $request ) { global $wpdb; $limit = ! empty( $request['per_page'] ) ? $request['per_page'] : $this->limit; $offset = ! empty( $request['page'] ) ? ( $request['page'] - 1 ) * $limit : 0; $blogs = $wpdb->get_col( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} WHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d ORDER BY blog_id LIMIT %d, %d ", get_network()->site_id, $offset, $limit ) ); $this->totalBooks = $wpdb->get_var( 'SELECT FOUND_ROWS()' ); return $blogs; }
[ "protected", "function", "listBookIds", "(", "$", "request", ")", "{", "global", "$", "wpdb", ";", "$", "limit", "=", "!", "empty", "(", "$", "request", "[", "'per_page'", "]", ")", "?", "$", "request", "[", "'per_page'", "]", ":", "$", "this", "->", "limit", ";", "$", "offset", "=", "!", "empty", "(", "$", "request", "[", "'page'", "]", ")", "?", "(", "$", "request", "[", "'page'", "]", "-", "1", ")", "*", "$", "limit", ":", "0", ";", "$", "blogs", "=", "$", "wpdb", "->", "get_col", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} \n\t\t\t\tWHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d \n\t\t\t\tORDER BY blog_id LIMIT %d, %d \"", ",", "get_network", "(", ")", "->", "site_id", ",", "$", "offset", ",", "$", "limit", ")", ")", ";", "$", "this", "->", "totalBooks", "=", "$", "wpdb", "->", "get_var", "(", "'SELECT FOUND_ROWS()'", ")", ";", "return", "$", "blogs", ";", "}" ]
Count all books, update $this->>totalBooks, return a paginated subset of book ids @param \WP_REST_Request @return array blog ids
[ "Count", "all", "books", "update", "$this", "-", ">>", "totalBooks", "return", "a", "paginated", "subset", "of", "book", "ids" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L350-L368
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.addPreviousNextLinks
protected function addPreviousNextLinks( $request, $response ) { $page = (int) $request['page']; $max_pages = (int) ceil( $this->totalBooks / (int) $request['per_page'] ); $response->header( 'X-WP-Total', (int) $this->totalBooks ); $response->header( 'X-WP-TotalPages', $max_pages ); $request_params = $request->get_query_params(); $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); if ( $page > 1 ) { $prev_page = $page - 1; if ( $prev_page > $max_pages ) { $prev_page = $max_pages; } $prev_link = add_query_arg( 'page', $prev_page, $base ); $response->link_header( 'prev', $prev_link ); } if ( $max_pages > $page ) { $next_page = $page + 1; $next_link = add_query_arg( 'page', $next_page, $base ); $response->link_header( 'next', $next_link ); } }
php
protected function addPreviousNextLinks( $request, $response ) { $page = (int) $request['page']; $max_pages = (int) ceil( $this->totalBooks / (int) $request['per_page'] ); $response->header( 'X-WP-Total', (int) $this->totalBooks ); $response->header( 'X-WP-TotalPages', $max_pages ); $request_params = $request->get_query_params(); $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); if ( $page > 1 ) { $prev_page = $page - 1; if ( $prev_page > $max_pages ) { $prev_page = $max_pages; } $prev_link = add_query_arg( 'page', $prev_page, $base ); $response->link_header( 'prev', $prev_link ); } if ( $max_pages > $page ) { $next_page = $page + 1; $next_link = add_query_arg( 'page', $next_page, $base ); $response->link_header( 'next', $next_link ); } }
[ "protected", "function", "addPreviousNextLinks", "(", "$", "request", ",", "$", "response", ")", "{", "$", "page", "=", "(", "int", ")", "$", "request", "[", "'page'", "]", ";", "$", "max_pages", "=", "(", "int", ")", "ceil", "(", "$", "this", "->", "totalBooks", "/", "(", "int", ")", "$", "request", "[", "'per_page'", "]", ")", ";", "$", "response", "->", "header", "(", "'X-WP-Total'", ",", "(", "int", ")", "$", "this", "->", "totalBooks", ")", ";", "$", "response", "->", "header", "(", "'X-WP-TotalPages'", ",", "$", "max_pages", ")", ";", "$", "request_params", "=", "$", "request", "->", "get_query_params", "(", ")", ";", "$", "base", "=", "add_query_arg", "(", "$", "request_params", ",", "rest_url", "(", "sprintf", "(", "'%s/%s'", ",", "$", "this", "->", "namespace", ",", "$", "this", "->", "rest_base", ")", ")", ")", ";", "if", "(", "$", "page", ">", "1", ")", "{", "$", "prev_page", "=", "$", "page", "-", "1", ";", "if", "(", "$", "prev_page", ">", "$", "max_pages", ")", "{", "$", "prev_page", "=", "$", "max_pages", ";", "}", "$", "prev_link", "=", "add_query_arg", "(", "'page'", ",", "$", "prev_page", ",", "$", "base", ")", ";", "$", "response", "->", "link_header", "(", "'prev'", ",", "$", "prev_link", ")", ";", "}", "if", "(", "$", "max_pages", ">", "$", "page", ")", "{", "$", "next_page", "=", "$", "page", "+", "1", ";", "$", "next_link", "=", "add_query_arg", "(", "'page'", ",", "$", "next_page", ",", "$", "base", ")", ";", "$", "response", "->", "link_header", "(", "'next'", ",", "$", "next_link", ")", ";", "}", "}" ]
Add previous/next links like it's done in WP-API @param \WP_REST_Request $request @param \WP_REST_Response $response
[ "Add", "previous", "/", "next", "links", "like", "it", "s", "done", "in", "WP", "-", "API" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L376-L400
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.find
public function find( $search ) { if ( ! is_array( $search ) ) { $search = (array) $search; } foreach ( $search as $val ) { if ( $this->fulltextSearchInPost( $val ) !== false ) { return true; } if ( $this->fulltextSearchInMeta( $val ) !== false ) { return true; } } return false; }
php
public function find( $search ) { if ( ! is_array( $search ) ) { $search = (array) $search; } foreach ( $search as $val ) { if ( $this->fulltextSearchInPost( $val ) !== false ) { return true; } if ( $this->fulltextSearchInMeta( $val ) !== false ) { return true; } } return false; }
[ "public", "function", "find", "(", "$", "search", ")", "{", "if", "(", "!", "is_array", "(", "$", "search", ")", ")", "{", "$", "search", "=", "(", "array", ")", "$", "search", ";", "}", "foreach", "(", "$", "search", "as", "$", "val", ")", "{", "if", "(", "$", "this", "->", "fulltextSearchInPost", "(", "$", "val", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "if", "(", "$", "this", "->", "fulltextSearchInMeta", "(", "$", "val", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Overridable find method for how to search a book @param mixed $search @return bool
[ "Overridable", "find", "method", "for", "how", "to", "search", "a", "book" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L413-L429
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.fulltextSearchInPost
protected function fulltextSearchInPost( $search ) { $s = $this->searchArgs( $search ); $q = new \WP_Query( $s ); // @codingStandardsIgnoreStart // // SELECT wp_2_posts.ID FROM wp_2_posts // WHERE 1=1 AND (((wp_2_posts.post_title LIKE '%Foo%') OR (wp_2_posts.post_excerpt LIKE '%Foo%') OR (wp_2_posts.post_content LIKE '%Foo%'))) // AND (wp_2_posts.post_password = '') AND wp_2_posts.post_type IN ('front-matter', 'back-matter', 'part', 'chapter') AND (wp_2_posts.post_status = 'publish') // ORDER BY wp_2_posts.post_title LIKE '%Vikings%' DESC, wp_2_posts.post_date DESC LIMIT 0, 10 // // @codingStandardsIgnoreEnd if ( $q->post_count > 0 ) { return true; } else { return false; } }
php
protected function fulltextSearchInPost( $search ) { $s = $this->searchArgs( $search ); $q = new \WP_Query( $s ); // @codingStandardsIgnoreStart // // SELECT wp_2_posts.ID FROM wp_2_posts // WHERE 1=1 AND (((wp_2_posts.post_title LIKE '%Foo%') OR (wp_2_posts.post_excerpt LIKE '%Foo%') OR (wp_2_posts.post_content LIKE '%Foo%'))) // AND (wp_2_posts.post_password = '') AND wp_2_posts.post_type IN ('front-matter', 'back-matter', 'part', 'chapter') AND (wp_2_posts.post_status = 'publish') // ORDER BY wp_2_posts.post_title LIKE '%Vikings%' DESC, wp_2_posts.post_date DESC LIMIT 0, 10 // // @codingStandardsIgnoreEnd if ( $q->post_count > 0 ) { return true; } else { return false; } }
[ "protected", "function", "fulltextSearchInPost", "(", "$", "search", ")", "{", "$", "s", "=", "$", "this", "->", "searchArgs", "(", "$", "search", ")", ";", "$", "q", "=", "new", "\\", "WP_Query", "(", "$", "s", ")", ";", "// @codingStandardsIgnoreStart", "//", "// SELECT wp_2_posts.ID FROM wp_2_posts", "// WHERE 1=1 AND (((wp_2_posts.post_title LIKE '%Foo%') OR (wp_2_posts.post_excerpt LIKE '%Foo%') OR (wp_2_posts.post_content LIKE '%Foo%')))", "// AND (wp_2_posts.post_password = '') AND wp_2_posts.post_type IN ('front-matter', 'back-matter', 'part', 'chapter') AND (wp_2_posts.post_status = 'publish')", "// ORDER BY wp_2_posts.post_title LIKE '%Vikings%' DESC, wp_2_posts.post_date DESC LIMIT 0, 10", "//", "// @codingStandardsIgnoreEnd", "if", "(", "$", "q", "->", "post_count", ">", "0", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Fulltext search entire book @param string $search @return bool
[ "Fulltext", "search", "entire", "book" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L458-L477
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.fulltextSearchInMeta
protected function fulltextSearchInMeta( $search ) { $meta = new \Pressbooks\Metadata(); $data = $meta->getMetaPostMetadata(); foreach ( $data as $key => $haystack ) { // Skip anything not prefixed with pb_ if ( ! preg_match( '/^pb_/', $key ) ) { continue; } if ( is_array( $haystack ) ) { $haystack = implode( ' ', $haystack ); } if ( stripos( $haystack, $search ) !== false ) { return true; } } return false; }
php
protected function fulltextSearchInMeta( $search ) { $meta = new \Pressbooks\Metadata(); $data = $meta->getMetaPostMetadata(); foreach ( $data as $key => $haystack ) { // Skip anything not prefixed with pb_ if ( ! preg_match( '/^pb_/', $key ) ) { continue; } if ( is_array( $haystack ) ) { $haystack = implode( ' ', $haystack ); } if ( stripos( $haystack, $search ) !== false ) { return true; } } return false; }
[ "protected", "function", "fulltextSearchInMeta", "(", "$", "search", ")", "{", "$", "meta", "=", "new", "\\", "Pressbooks", "\\", "Metadata", "(", ")", ";", "$", "data", "=", "$", "meta", "->", "getMetaPostMetadata", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "haystack", ")", "{", "// Skip anything not prefixed with pb_", "if", "(", "!", "preg_match", "(", "'/^pb_/'", ",", "$", "key", ")", ")", "{", "continue", ";", "}", "if", "(", "is_array", "(", "$", "haystack", ")", ")", "{", "$", "haystack", "=", "implode", "(", "' '", ",", "$", "haystack", ")", ";", "}", "if", "(", "stripos", "(", "$", "haystack", ",", "$", "search", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Fulltext search all `pb_` prefixed meta keys in metadata post @param string $search @return bool
[ "Fulltext", "search", "all", "pb_", "prefixed", "meta", "keys", "in", "metadata", "post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L486-L504
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.searchBooks
protected function searchBooks( $request ) { if ( ! empty( $request['next'] ) ) { $this->lastKnownBookId = $request['next']; } $start_time = time(); $searched_books = 0; $found_books = 0; $results = []; while ( $found_books < $request['per_page'] ) { $book_ids = $this->searchBookIds( $request ); foreach ( $book_ids as $id ) { $node = $this->renderBook( $id, $request['search'] ); if ( ! empty( $node ) ) { $response = rest_ensure_response( $node ); $response->add_links( $this->linkCollector ); $results[] = $this->prepare_response_for_collection( $response ); $this->linkCollector = []; // re-initialize ++$found_books; } ++$searched_books; $this->lastKnownBookId = $id; if ( time() - $start_time > $this->maxSearchTime ) { break 2; } } if ( $searched_books >= $this->totalBooks ) { break; } } if ( ! $searched_books ) { $this->lastKnownBookId = 0; } return $results; }
php
protected function searchBooks( $request ) { if ( ! empty( $request['next'] ) ) { $this->lastKnownBookId = $request['next']; } $start_time = time(); $searched_books = 0; $found_books = 0; $results = []; while ( $found_books < $request['per_page'] ) { $book_ids = $this->searchBookIds( $request ); foreach ( $book_ids as $id ) { $node = $this->renderBook( $id, $request['search'] ); if ( ! empty( $node ) ) { $response = rest_ensure_response( $node ); $response->add_links( $this->linkCollector ); $results[] = $this->prepare_response_for_collection( $response ); $this->linkCollector = []; // re-initialize ++$found_books; } ++$searched_books; $this->lastKnownBookId = $id; if ( time() - $start_time > $this->maxSearchTime ) { break 2; } } if ( $searched_books >= $this->totalBooks ) { break; } } if ( ! $searched_books ) { $this->lastKnownBookId = 0; } return $results; }
[ "protected", "function", "searchBooks", "(", "$", "request", ")", "{", "if", "(", "!", "empty", "(", "$", "request", "[", "'next'", "]", ")", ")", "{", "$", "this", "->", "lastKnownBookId", "=", "$", "request", "[", "'next'", "]", ";", "}", "$", "start_time", "=", "time", "(", ")", ";", "$", "searched_books", "=", "0", ";", "$", "found_books", "=", "0", ";", "$", "results", "=", "[", "]", ";", "while", "(", "$", "found_books", "<", "$", "request", "[", "'per_page'", "]", ")", "{", "$", "book_ids", "=", "$", "this", "->", "searchBookIds", "(", "$", "request", ")", ";", "foreach", "(", "$", "book_ids", "as", "$", "id", ")", "{", "$", "node", "=", "$", "this", "->", "renderBook", "(", "$", "id", ",", "$", "request", "[", "'search'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "node", ")", ")", "{", "$", "response", "=", "rest_ensure_response", "(", "$", "node", ")", ";", "$", "response", "->", "add_links", "(", "$", "this", "->", "linkCollector", ")", ";", "$", "results", "[", "]", "=", "$", "this", "->", "prepare_response_for_collection", "(", "$", "response", ")", ";", "$", "this", "->", "linkCollector", "=", "[", "]", ";", "// re-initialize", "++", "$", "found_books", ";", "}", "++", "$", "searched_books", ";", "$", "this", "->", "lastKnownBookId", "=", "$", "id", ";", "if", "(", "time", "(", ")", "-", "$", "start_time", ">", "$", "this", "->", "maxSearchTime", ")", "{", "break", "2", ";", "}", "}", "if", "(", "$", "searched_books", ">=", "$", "this", "->", "totalBooks", ")", "{", "break", ";", "}", "}", "if", "(", "!", "$", "searched_books", ")", "{", "$", "this", "->", "lastKnownBookId", "=", "0", ";", "}", "return", "$", "results", ";", "}" ]
Fulltext search @param \WP_REST_Request $request @return array
[ "Fulltext", "search" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L513-L550
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.searchBookIds
protected function searchBookIds( $request ) { global $wpdb; $limit = ! empty( $request['per_page'] ) ? $request['per_page'] : $this->limit; $blogs = $wpdb->get_col( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} WHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d AND blog_id > %d ORDER BY blog_id LIMIT %d ", get_network()->site_id, $this->lastKnownBookId, $limit ) ); $this->totalBooks = $wpdb->get_var( 'SELECT FOUND_ROWS()' ); return $blogs; }
php
protected function searchBookIds( $request ) { global $wpdb; $limit = ! empty( $request['per_page'] ) ? $request['per_page'] : $this->limit; $blogs = $wpdb->get_col( $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} WHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d AND blog_id > %d ORDER BY blog_id LIMIT %d ", get_network()->site_id, $this->lastKnownBookId, $limit ) ); $this->totalBooks = $wpdb->get_var( 'SELECT FOUND_ROWS()' ); return $blogs; }
[ "protected", "function", "searchBookIds", "(", "$", "request", ")", "{", "global", "$", "wpdb", ";", "$", "limit", "=", "!", "empty", "(", "$", "request", "[", "'per_page'", "]", ")", "?", "$", "request", "[", "'per_page'", "]", ":", "$", "this", "->", "limit", ";", "$", "blogs", "=", "$", "wpdb", "->", "get_col", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT SQL_CALC_FOUND_ROWS blog_id FROM {$wpdb->blogs} \n\t\t\t\t WHERE public = 1 AND archived = 0 AND spam = 0 AND deleted = 0 AND blog_id != %d AND blog_id > %d \n\t\t\t\t ORDER BY blog_id LIMIT %d \"", ",", "get_network", "(", ")", "->", "site_id", ",", "$", "this", "->", "lastKnownBookId", ",", "$", "limit", ")", ")", ";", "$", "this", "->", "totalBooks", "=", "$", "wpdb", "->", "get_var", "(", "'SELECT FOUND_ROWS()'", ")", ";", "return", "$", "blogs", ";", "}" ]
Count all books, update $this->>totalBooks, return a paginated subset of book ids @param \WP_REST_Request @return array blog ids
[ "Count", "all", "books", "update", "$this", "-", ">>", "totalBooks", "return", "a", "paginated", "subset", "of", "book", "ids" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L559-L576
pressbooks/pressbooks
inc/api/endpoints/controller/class-books.php
Books.addNextSearchLinks
protected function addNextSearchLinks( $request, $response ) { $max_pages = (int) ceil( $this->totalBooks / (int) $request['per_page'] ); $response->header( 'X-WP-Total', (int) $this->totalBooks ); $response->header( 'X-WP-TotalPages', $max_pages ); if ( $this->lastKnownBookId ) { unset( $request['page'] ); $request_params = $request->get_query_params(); $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); $next_link = add_query_arg( 'next', $this->lastKnownBookId, $base ); $response->link_header( 'next', $next_link ); } }
php
protected function addNextSearchLinks( $request, $response ) { $max_pages = (int) ceil( $this->totalBooks / (int) $request['per_page'] ); $response->header( 'X-WP-Total', (int) $this->totalBooks ); $response->header( 'X-WP-TotalPages', $max_pages ); if ( $this->lastKnownBookId ) { unset( $request['page'] ); $request_params = $request->get_query_params(); $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); $next_link = add_query_arg( 'next', $this->lastKnownBookId, $base ); $response->link_header( 'next', $next_link ); } }
[ "protected", "function", "addNextSearchLinks", "(", "$", "request", ",", "$", "response", ")", "{", "$", "max_pages", "=", "(", "int", ")", "ceil", "(", "$", "this", "->", "totalBooks", "/", "(", "int", ")", "$", "request", "[", "'per_page'", "]", ")", ";", "$", "response", "->", "header", "(", "'X-WP-Total'", ",", "(", "int", ")", "$", "this", "->", "totalBooks", ")", ";", "$", "response", "->", "header", "(", "'X-WP-TotalPages'", ",", "$", "max_pages", ")", ";", "if", "(", "$", "this", "->", "lastKnownBookId", ")", "{", "unset", "(", "$", "request", "[", "'page'", "]", ")", ";", "$", "request_params", "=", "$", "request", "->", "get_query_params", "(", ")", ";", "$", "base", "=", "add_query_arg", "(", "$", "request_params", ",", "rest_url", "(", "sprintf", "(", "'%s/%s'", ",", "$", "this", "->", "namespace", ",", "$", "this", "->", "rest_base", ")", ")", ")", ";", "$", "next_link", "=", "add_query_arg", "(", "'next'", ",", "$", "this", "->", "lastKnownBookId", ",", "$", "base", ")", ";", "$", "response", "->", "link_header", "(", "'next'", ",", "$", "next_link", ")", ";", "}", "}" ]
Add a next link for search results @param \WP_REST_Request $request @param \WP_REST_Response $response
[ "Add", "a", "next", "link", "for", "search", "results" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-books.php#L584-L598
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.registerTaxonomies
public function registerTaxonomies() { register_extended_taxonomy( 'front-matter-type', 'front-matter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'back-matter-type', 'back-matter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'chapter-type', 'chapter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'contributor', [ 'metadata', 'chapter', 'part', 'front-matter', 'back-matter' ], [ 'meta_box' => false, 'hierarchical' => false, 'capabilities' => [ 'manage_terms' => 'manage_options', 'edit_terms' => 'manage_options', 'delete_terms' => 'manage_options', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'license', [ 'metadata', 'chapter', 'part', 'front-matter', 'back-matter' ], [ 'meta_box' => false, 'hierarchical' => false, 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'glossary-type', 'glossary', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); }
php
public function registerTaxonomies() { register_extended_taxonomy( 'front-matter-type', 'front-matter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'back-matter-type', 'back-matter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'chapter-type', 'chapter', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'contributor', [ 'metadata', 'chapter', 'part', 'front-matter', 'back-matter' ], [ 'meta_box' => false, 'hierarchical' => false, 'capabilities' => [ 'manage_terms' => 'manage_options', 'edit_terms' => 'manage_options', 'delete_terms' => 'manage_options', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'license', [ 'metadata', 'chapter', 'part', 'front-matter', 'back-matter' ], [ 'meta_box' => false, 'hierarchical' => false, 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); register_extended_taxonomy( 'glossary-type', 'glossary', [ 'meta_box' => 'dropdown', 'meta_box_sanitize_cb' => 'taxonomy_meta_box_sanitize_cb_input', 'capabilities' => [ 'manage_terms' => 'manage_sites', 'edit_terms' => 'manage_sites', 'delete_terms' => 'manage_sites', 'assign_terms' => 'edit_posts', ], 'show_in_rest' => true, ] ); }
[ "public", "function", "registerTaxonomies", "(", ")", "{", "register_extended_taxonomy", "(", "'front-matter-type'", ",", "'front-matter'", ",", "[", "'meta_box'", "=>", "'dropdown'", ",", "'meta_box_sanitize_cb'", "=>", "'taxonomy_meta_box_sanitize_cb_input'", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_sites'", ",", "'edit_terms'", "=>", "'manage_sites'", ",", "'delete_terms'", "=>", "'manage_sites'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "register_extended_taxonomy", "(", "'back-matter-type'", ",", "'back-matter'", ",", "[", "'meta_box'", "=>", "'dropdown'", ",", "'meta_box_sanitize_cb'", "=>", "'taxonomy_meta_box_sanitize_cb_input'", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_sites'", ",", "'edit_terms'", "=>", "'manage_sites'", ",", "'delete_terms'", "=>", "'manage_sites'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "register_extended_taxonomy", "(", "'chapter-type'", ",", "'chapter'", ",", "[", "'meta_box'", "=>", "'dropdown'", ",", "'meta_box_sanitize_cb'", "=>", "'taxonomy_meta_box_sanitize_cb_input'", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_sites'", ",", "'edit_terms'", "=>", "'manage_sites'", ",", "'delete_terms'", "=>", "'manage_sites'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "register_extended_taxonomy", "(", "'contributor'", ",", "[", "'metadata'", ",", "'chapter'", ",", "'part'", ",", "'front-matter'", ",", "'back-matter'", "]", ",", "[", "'meta_box'", "=>", "false", ",", "'hierarchical'", "=>", "false", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_options'", ",", "'edit_terms'", "=>", "'manage_options'", ",", "'delete_terms'", "=>", "'manage_options'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "register_extended_taxonomy", "(", "'license'", ",", "[", "'metadata'", ",", "'chapter'", ",", "'part'", ",", "'front-matter'", ",", "'back-matter'", "]", ",", "[", "'meta_box'", "=>", "false", ",", "'hierarchical'", "=>", "false", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_sites'", ",", "'edit_terms'", "=>", "'manage_sites'", ",", "'delete_terms'", "=>", "'manage_sites'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "register_extended_taxonomy", "(", "'glossary-type'", ",", "'glossary'", ",", "[", "'meta_box'", "=>", "'dropdown'", ",", "'meta_box_sanitize_cb'", "=>", "'taxonomy_meta_box_sanitize_cb_input'", ",", "'capabilities'", "=>", "[", "'manage_terms'", "=>", "'manage_sites'", ",", "'edit_terms'", "=>", "'manage_sites'", ",", "'delete_terms'", "=>", "'manage_sites'", ",", "'assign_terms'", "=>", "'edit_posts'", ",", "]", ",", "'show_in_rest'", "=>", "true", ",", "]", ")", ";", "}" ]
Register taxonomies
[ "Register", "taxonomies" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L83-L180
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.insertTerms
public function insertTerms() { if ( ! taxonomy_exists( 'front-matter-type' ) ) { $this->registerTaxonomies(); } // Front Matter wp_insert_term( 'Abstract', 'front-matter-type', [ 'slug' => 'abstracts', ] ); wp_insert_term( 'Acknowledgements', 'front-matter-type', [ 'slug' => 'acknowledgements', ] ); wp_insert_term( 'Before Title Page', 'front-matter-type', [ 'slug' => 'before-title', ] ); wp_insert_term( 'Chronology, Timeline', 'front-matter-type', [ 'slug' => 'chronology-timeline', ] ); wp_insert_term( 'Dedication', 'front-matter-type', [ 'slug' => 'dedication', ] ); wp_insert_term( 'Disclaimer', 'front-matter-type', [ 'slug' => 'disclaimer', ] ); wp_insert_term( 'Epigraph', 'front-matter-type', [ 'slug' => 'epigraph', ] ); wp_insert_term( 'Foreword', 'front-matter-type', [ 'slug' => 'foreword', ] ); wp_insert_term( 'Genealogy, Family Tree', 'front-matter-type', [ 'slug' => 'genealogy-family-tree', ] ); wp_insert_term( 'Image credits', 'front-matter-type', [ 'slug' => 'image-credits', ] ); wp_insert_term( 'Introduction', 'front-matter-type', [ 'slug' => 'introduction', ] ); wp_insert_term( 'List of Abbreviations', 'front-matter-type', [ 'slug' => 'list-of-abbreviations', ] ); wp_insert_term( 'List of Characters', 'front-matter-type', [ 'slug' => 'list-of-characters', ] ); wp_insert_term( 'List of Illustrations', 'front-matter-type', [ 'slug' => 'list-of-illustrations', ] ); wp_insert_term( 'List of Tables', 'front-matter-type', [ 'slug' => 'list-of-tables', ] ); wp_insert_term( 'Miscellaneous', 'front-matter-type', [ 'slug' => 'miscellaneous', ] ); wp_insert_term( 'Other Books by Author', 'front-matter-type', [ 'slug' => 'other-books', ] ); wp_insert_term( 'Preface', 'front-matter-type', [ 'slug' => 'preface', ] ); wp_insert_term( 'Prologue', 'front-matter-type', [ 'slug' => 'prologue', ] ); wp_insert_term( 'Recommended citation', 'front-matter-type', [ 'slug' => 'recommended-citation', ] ); wp_insert_term( 'Title Page', 'front-matter-type', [ 'slug' => 'title-page', ] ); // Back Matter wp_insert_term( 'About the Author', 'back-matter-type', [ 'slug' => 'about-the-author', ] ); wp_insert_term( 'About the Publisher', 'back-matter-type', [ 'slug' => 'about-the-publisher', ] ); wp_insert_term( 'Acknowledgements', 'back-matter-type', [ 'slug' => 'acknowledgements', ] ); wp_insert_term( 'Afterword', 'back-matter-type', [ 'slug' => 'afterword', ] ); wp_insert_term( 'Appendix', 'back-matter-type', [ 'slug' => 'appendix', ] ); wp_insert_term( "Author's Note", 'back-matter-type', [ 'slug' => 'authors-note', ] ); wp_insert_term( 'Back of Book Ad', 'back-matter-type', [ 'slug' => 'back-of-book-ad', ] ); wp_insert_term( 'Bibliography', 'back-matter-type', [ 'slug' => 'bibliography', ] ); wp_insert_term( 'Biographical Note', 'back-matter-type', [ 'slug' => 'biographical-note', ] ); wp_insert_term( 'Colophon', 'back-matter-type', [ 'slug' => 'colophon', ] ); wp_insert_term( 'Conclusion', 'back-matter-type', [ 'slug' => 'conclusion', ] ); wp_insert_term( 'Credits', 'back-matter-type', [ 'slug' => 'credits', ] ); wp_insert_term( 'Dedication', 'back-matter-type', [ 'slug' => 'dedication', ] ); wp_insert_term( 'Epilogue', 'back-matter-type', [ 'slug' => 'epilogue', ] ); wp_insert_term( 'Glossary', 'back-matter-type', [ 'slug' => 'glossary', ] ); wp_insert_term( 'Index', 'back-matter-type', [ 'slug' => 'index', ] ); wp_insert_term( 'Miscellaneous', 'back-matter-type', [ 'slug' => 'miscellaneous', ] ); wp_insert_term( 'Notes', 'back-matter-type', [ 'slug' => 'notes', ] ); wp_insert_term( 'Other Books by Author', 'back-matter-type', [ 'slug' => 'other-books', ] ); wp_insert_term( 'Permissions', 'back-matter-type', [ 'slug' => 'permissions', ] ); wp_insert_term( 'Reading Group Guide', 'back-matter-type', [ 'slug' => 'reading-group-guide', ] ); wp_insert_term( 'Resources', 'back-matter-type', [ 'slug' => 'resources', ] ); wp_insert_term( 'Sources', 'back-matter-type', [ 'slug' => 'sources', ] ); wp_insert_term( 'Suggested Reading', 'back-matter-type', [ 'slug' => 'suggested-reading', ] ); // Chapter wp_insert_term( 'Standard', 'chapter-type', [ 'slug' => 'standard', ] ); wp_insert_term( 'Numberless', 'chapter-type', [ 'slug' => 'numberless', ] ); // Glossary wp_insert_term( 'Miscellaneous', 'glossary-type', [ 'slug' => 'miscellaneous', ] ); foreach ( $this->licensing->getSupportedTypes( true, true ) as $key => $val ) { wp_insert_term( $val['desc'], Licensing::TAXONOMY, [ 'slug' => $key, ] ); } }
php
public function insertTerms() { if ( ! taxonomy_exists( 'front-matter-type' ) ) { $this->registerTaxonomies(); } // Front Matter wp_insert_term( 'Abstract', 'front-matter-type', [ 'slug' => 'abstracts', ] ); wp_insert_term( 'Acknowledgements', 'front-matter-type', [ 'slug' => 'acknowledgements', ] ); wp_insert_term( 'Before Title Page', 'front-matter-type', [ 'slug' => 'before-title', ] ); wp_insert_term( 'Chronology, Timeline', 'front-matter-type', [ 'slug' => 'chronology-timeline', ] ); wp_insert_term( 'Dedication', 'front-matter-type', [ 'slug' => 'dedication', ] ); wp_insert_term( 'Disclaimer', 'front-matter-type', [ 'slug' => 'disclaimer', ] ); wp_insert_term( 'Epigraph', 'front-matter-type', [ 'slug' => 'epigraph', ] ); wp_insert_term( 'Foreword', 'front-matter-type', [ 'slug' => 'foreword', ] ); wp_insert_term( 'Genealogy, Family Tree', 'front-matter-type', [ 'slug' => 'genealogy-family-tree', ] ); wp_insert_term( 'Image credits', 'front-matter-type', [ 'slug' => 'image-credits', ] ); wp_insert_term( 'Introduction', 'front-matter-type', [ 'slug' => 'introduction', ] ); wp_insert_term( 'List of Abbreviations', 'front-matter-type', [ 'slug' => 'list-of-abbreviations', ] ); wp_insert_term( 'List of Characters', 'front-matter-type', [ 'slug' => 'list-of-characters', ] ); wp_insert_term( 'List of Illustrations', 'front-matter-type', [ 'slug' => 'list-of-illustrations', ] ); wp_insert_term( 'List of Tables', 'front-matter-type', [ 'slug' => 'list-of-tables', ] ); wp_insert_term( 'Miscellaneous', 'front-matter-type', [ 'slug' => 'miscellaneous', ] ); wp_insert_term( 'Other Books by Author', 'front-matter-type', [ 'slug' => 'other-books', ] ); wp_insert_term( 'Preface', 'front-matter-type', [ 'slug' => 'preface', ] ); wp_insert_term( 'Prologue', 'front-matter-type', [ 'slug' => 'prologue', ] ); wp_insert_term( 'Recommended citation', 'front-matter-type', [ 'slug' => 'recommended-citation', ] ); wp_insert_term( 'Title Page', 'front-matter-type', [ 'slug' => 'title-page', ] ); // Back Matter wp_insert_term( 'About the Author', 'back-matter-type', [ 'slug' => 'about-the-author', ] ); wp_insert_term( 'About the Publisher', 'back-matter-type', [ 'slug' => 'about-the-publisher', ] ); wp_insert_term( 'Acknowledgements', 'back-matter-type', [ 'slug' => 'acknowledgements', ] ); wp_insert_term( 'Afterword', 'back-matter-type', [ 'slug' => 'afterword', ] ); wp_insert_term( 'Appendix', 'back-matter-type', [ 'slug' => 'appendix', ] ); wp_insert_term( "Author's Note", 'back-matter-type', [ 'slug' => 'authors-note', ] ); wp_insert_term( 'Back of Book Ad', 'back-matter-type', [ 'slug' => 'back-of-book-ad', ] ); wp_insert_term( 'Bibliography', 'back-matter-type', [ 'slug' => 'bibliography', ] ); wp_insert_term( 'Biographical Note', 'back-matter-type', [ 'slug' => 'biographical-note', ] ); wp_insert_term( 'Colophon', 'back-matter-type', [ 'slug' => 'colophon', ] ); wp_insert_term( 'Conclusion', 'back-matter-type', [ 'slug' => 'conclusion', ] ); wp_insert_term( 'Credits', 'back-matter-type', [ 'slug' => 'credits', ] ); wp_insert_term( 'Dedication', 'back-matter-type', [ 'slug' => 'dedication', ] ); wp_insert_term( 'Epilogue', 'back-matter-type', [ 'slug' => 'epilogue', ] ); wp_insert_term( 'Glossary', 'back-matter-type', [ 'slug' => 'glossary', ] ); wp_insert_term( 'Index', 'back-matter-type', [ 'slug' => 'index', ] ); wp_insert_term( 'Miscellaneous', 'back-matter-type', [ 'slug' => 'miscellaneous', ] ); wp_insert_term( 'Notes', 'back-matter-type', [ 'slug' => 'notes', ] ); wp_insert_term( 'Other Books by Author', 'back-matter-type', [ 'slug' => 'other-books', ] ); wp_insert_term( 'Permissions', 'back-matter-type', [ 'slug' => 'permissions', ] ); wp_insert_term( 'Reading Group Guide', 'back-matter-type', [ 'slug' => 'reading-group-guide', ] ); wp_insert_term( 'Resources', 'back-matter-type', [ 'slug' => 'resources', ] ); wp_insert_term( 'Sources', 'back-matter-type', [ 'slug' => 'sources', ] ); wp_insert_term( 'Suggested Reading', 'back-matter-type', [ 'slug' => 'suggested-reading', ] ); // Chapter wp_insert_term( 'Standard', 'chapter-type', [ 'slug' => 'standard', ] ); wp_insert_term( 'Numberless', 'chapter-type', [ 'slug' => 'numberless', ] ); // Glossary wp_insert_term( 'Miscellaneous', 'glossary-type', [ 'slug' => 'miscellaneous', ] ); foreach ( $this->licensing->getSupportedTypes( true, true ) as $key => $val ) { wp_insert_term( $val['desc'], Licensing::TAXONOMY, [ 'slug' => $key, ] ); } }
[ "public", "function", "insertTerms", "(", ")", "{", "if", "(", "!", "taxonomy_exists", "(", "'front-matter-type'", ")", ")", "{", "$", "this", "->", "registerTaxonomies", "(", ")", ";", "}", "// Front Matter", "wp_insert_term", "(", "'Abstract'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'abstracts'", ",", "]", ")", ";", "wp_insert_term", "(", "'Acknowledgements'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'acknowledgements'", ",", "]", ")", ";", "wp_insert_term", "(", "'Before Title Page'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'before-title'", ",", "]", ")", ";", "wp_insert_term", "(", "'Chronology, Timeline'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'chronology-timeline'", ",", "]", ")", ";", "wp_insert_term", "(", "'Dedication'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'dedication'", ",", "]", ")", ";", "wp_insert_term", "(", "'Disclaimer'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'disclaimer'", ",", "]", ")", ";", "wp_insert_term", "(", "'Epigraph'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'epigraph'", ",", "]", ")", ";", "wp_insert_term", "(", "'Foreword'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'foreword'", ",", "]", ")", ";", "wp_insert_term", "(", "'Genealogy, Family Tree'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'genealogy-family-tree'", ",", "]", ")", ";", "wp_insert_term", "(", "'Image credits'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'image-credits'", ",", "]", ")", ";", "wp_insert_term", "(", "'Introduction'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'introduction'", ",", "]", ")", ";", "wp_insert_term", "(", "'List of Abbreviations'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'list-of-abbreviations'", ",", "]", ")", ";", "wp_insert_term", "(", "'List of Characters'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'list-of-characters'", ",", "]", ")", ";", "wp_insert_term", "(", "'List of Illustrations'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'list-of-illustrations'", ",", "]", ")", ";", "wp_insert_term", "(", "'List of Tables'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'list-of-tables'", ",", "]", ")", ";", "wp_insert_term", "(", "'Miscellaneous'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'miscellaneous'", ",", "]", ")", ";", "wp_insert_term", "(", "'Other Books by Author'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'other-books'", ",", "]", ")", ";", "wp_insert_term", "(", "'Preface'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'preface'", ",", "]", ")", ";", "wp_insert_term", "(", "'Prologue'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'prologue'", ",", "]", ")", ";", "wp_insert_term", "(", "'Recommended citation'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'recommended-citation'", ",", "]", ")", ";", "wp_insert_term", "(", "'Title Page'", ",", "'front-matter-type'", ",", "[", "'slug'", "=>", "'title-page'", ",", "]", ")", ";", "// Back Matter", "wp_insert_term", "(", "'About the Author'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'about-the-author'", ",", "]", ")", ";", "wp_insert_term", "(", "'About the Publisher'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'about-the-publisher'", ",", "]", ")", ";", "wp_insert_term", "(", "'Acknowledgements'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'acknowledgements'", ",", "]", ")", ";", "wp_insert_term", "(", "'Afterword'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'afterword'", ",", "]", ")", ";", "wp_insert_term", "(", "'Appendix'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'appendix'", ",", "]", ")", ";", "wp_insert_term", "(", "\"Author's Note\"", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'authors-note'", ",", "]", ")", ";", "wp_insert_term", "(", "'Back of Book Ad'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'back-of-book-ad'", ",", "]", ")", ";", "wp_insert_term", "(", "'Bibliography'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'bibliography'", ",", "]", ")", ";", "wp_insert_term", "(", "'Biographical Note'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'biographical-note'", ",", "]", ")", ";", "wp_insert_term", "(", "'Colophon'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'colophon'", ",", "]", ")", ";", "wp_insert_term", "(", "'Conclusion'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'conclusion'", ",", "]", ")", ";", "wp_insert_term", "(", "'Credits'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'credits'", ",", "]", ")", ";", "wp_insert_term", "(", "'Dedication'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'dedication'", ",", "]", ")", ";", "wp_insert_term", "(", "'Epilogue'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'epilogue'", ",", "]", ")", ";", "wp_insert_term", "(", "'Glossary'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'glossary'", ",", "]", ")", ";", "wp_insert_term", "(", "'Index'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'index'", ",", "]", ")", ";", "wp_insert_term", "(", "'Miscellaneous'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'miscellaneous'", ",", "]", ")", ";", "wp_insert_term", "(", "'Notes'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'notes'", ",", "]", ")", ";", "wp_insert_term", "(", "'Other Books by Author'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'other-books'", ",", "]", ")", ";", "wp_insert_term", "(", "'Permissions'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'permissions'", ",", "]", ")", ";", "wp_insert_term", "(", "'Reading Group Guide'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'reading-group-guide'", ",", "]", ")", ";", "wp_insert_term", "(", "'Resources'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'resources'", ",", "]", ")", ";", "wp_insert_term", "(", "'Sources'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'sources'", ",", "]", ")", ";", "wp_insert_term", "(", "'Suggested Reading'", ",", "'back-matter-type'", ",", "[", "'slug'", "=>", "'suggested-reading'", ",", "]", ")", ";", "// Chapter", "wp_insert_term", "(", "'Standard'", ",", "'chapter-type'", ",", "[", "'slug'", "=>", "'standard'", ",", "]", ")", ";", "wp_insert_term", "(", "'Numberless'", ",", "'chapter-type'", ",", "[", "'slug'", "=>", "'numberless'", ",", "]", ")", ";", "// Glossary", "wp_insert_term", "(", "'Miscellaneous'", ",", "'glossary-type'", ",", "[", "'slug'", "=>", "'miscellaneous'", ",", "]", ")", ";", "foreach", "(", "$", "this", "->", "licensing", "->", "getSupportedTypes", "(", "true", ",", "true", ")", "as", "$", "key", "=>", "$", "val", ")", "{", "wp_insert_term", "(", "$", "val", "[", "'desc'", "]", ",", "Licensing", "::", "TAXONOMY", ",", "[", "'slug'", "=>", "$", "key", ",", "]", ")", ";", "}", "}" ]
Insert terms If the term already exists on the same hierarchical level, or the term slug and name are not unique, wp_insert_term() returns a WP_Error and we ignore it.
[ "Insert", "terms" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L188-L449
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.getFrontMatterType
public function getFrontMatterType( $id ) { $terms = get_the_terms( $id, 'front-matter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
php
public function getFrontMatterType( $id ) { $terms = get_the_terms( $id, 'front-matter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
[ "public", "function", "getFrontMatterType", "(", "$", "id", ")", "{", "$", "terms", "=", "get_the_terms", "(", "$", "id", ",", "'front-matter-type'", ")", ";", "if", "(", "$", "terms", "&&", "!", "is_wp_error", "(", "$", "terms", ")", ")", "{", "foreach", "(", "$", "terms", "as", "$", "term", ")", "{", "return", "$", "term", "->", "slug", ";", "}", "}", "return", "'miscellaneous'", ";", "}" ]
Return the first (and only) front-matter-type for a specific post @param int $id Post ID @return string
[ "Return", "the", "first", "(", "and", "only", ")", "front", "-", "matter", "-", "type", "for", "a", "specific", "post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L458-L468
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.getBackMatterType
public function getBackMatterType( $id ) { $terms = get_the_terms( $id, 'back-matter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
php
public function getBackMatterType( $id ) { $terms = get_the_terms( $id, 'back-matter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
[ "public", "function", "getBackMatterType", "(", "$", "id", ")", "{", "$", "terms", "=", "get_the_terms", "(", "$", "id", ",", "'back-matter-type'", ")", ";", "if", "(", "$", "terms", "&&", "!", "is_wp_error", "(", "$", "terms", ")", ")", "{", "foreach", "(", "$", "terms", "as", "$", "term", ")", "{", "return", "$", "term", "->", "slug", ";", "}", "}", "return", "'miscellaneous'", ";", "}" ]
Return the first (and only) back-matter-type for a specific post @param int $id Post ID @return string
[ "Return", "the", "first", "(", "and", "only", ")", "back", "-", "matter", "-", "type", "for", "a", "specific", "post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L477-L487
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.getChapterType
public function getChapterType( $id ) { $terms = get_the_terms( $id, 'chapter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { if ( 'type-1' === $term->slug ) { return 'standard'; } else { return $term->slug; } } } return 'standard'; }
php
public function getChapterType( $id ) { $terms = get_the_terms( $id, 'chapter-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { if ( 'type-1' === $term->slug ) { return 'standard'; } else { return $term->slug; } } } return 'standard'; }
[ "public", "function", "getChapterType", "(", "$", "id", ")", "{", "$", "terms", "=", "get_the_terms", "(", "$", "id", ",", "'chapter-type'", ")", ";", "if", "(", "$", "terms", "&&", "!", "is_wp_error", "(", "$", "terms", ")", ")", "{", "foreach", "(", "$", "terms", "as", "$", "term", ")", "{", "if", "(", "'type-1'", "===", "$", "term", "->", "slug", ")", "{", "return", "'standard'", ";", "}", "else", "{", "return", "$", "term", "->", "slug", ";", "}", "}", "}", "return", "'standard'", ";", "}" ]
Return the first (and only) chapter-type for a specific post @param int $id Post ID @return string
[ "Return", "the", "first", "(", "and", "only", ")", "chapter", "-", "type", "for", "a", "specific", "post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L496-L510
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.getGlossaryType
public function getGlossaryType( $id ) { $terms = get_the_terms( $id, 'glossary-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
php
public function getGlossaryType( $id ) { $terms = get_the_terms( $id, 'glossary-type' ); if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { return $term->slug; } } return 'miscellaneous'; }
[ "public", "function", "getGlossaryType", "(", "$", "id", ")", "{", "$", "terms", "=", "get_the_terms", "(", "$", "id", ",", "'glossary-type'", ")", ";", "if", "(", "$", "terms", "&&", "!", "is_wp_error", "(", "$", "terms", ")", ")", "{", "foreach", "(", "$", "terms", "as", "$", "term", ")", "{", "return", "$", "term", "->", "slug", ";", "}", "}", "return", "'miscellaneous'", ";", "}" ]
Return the first (and only) glossary-type for a specific post @param $id @return string
[ "Return", "the", "first", "(", "and", "only", ")", "glossary", "-", "type", "for", "a", "specific", "post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L519-L529
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.maybeUpgrade
public function maybeUpgrade() { $taxonomy_version = get_option( 'pressbooks_taxonomy_version', 0 ); if ( $taxonomy_version < self::VERSION ) { $this->upgrade( $taxonomy_version ); update_option( 'pressbooks_taxonomy_version', self::VERSION ); } }
php
public function maybeUpgrade() { $taxonomy_version = get_option( 'pressbooks_taxonomy_version', 0 ); if ( $taxonomy_version < self::VERSION ) { $this->upgrade( $taxonomy_version ); update_option( 'pressbooks_taxonomy_version', self::VERSION ); } }
[ "public", "function", "maybeUpgrade", "(", ")", "{", "$", "taxonomy_version", "=", "get_option", "(", "'pressbooks_taxonomy_version'", ",", "0", ")", ";", "if", "(", "$", "taxonomy_version", "<", "self", "::", "VERSION", ")", "{", "$", "this", "->", "upgrade", "(", "$", "taxonomy_version", ")", ";", "update_option", "(", "'pressbooks_taxonomy_version'", ",", "self", "::", "VERSION", ")", ";", "}", "}" ]
Is it time to upgrade?
[ "Is", "it", "time", "to", "upgrade?" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L538-L544
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.upgrade
public function upgrade( $version ) { if ( $version < 1 ) { // Upgrade from version 0 (prior to Pressbooks\Taxonomy class) to version 1 (simplified chapter types) $this->upgradeChapterTypes(); flush_rewrite_rules( false ); } if ( $version < 2 ) { $this->insertTerms(); // Re-trigger } if ( $version < 3 ) { $this->upgradeLicenses(); } if ( $version < 4 ) { $this->differentiatePublicDomain(); } }
php
public function upgrade( $version ) { if ( $version < 1 ) { // Upgrade from version 0 (prior to Pressbooks\Taxonomy class) to version 1 (simplified chapter types) $this->upgradeChapterTypes(); flush_rewrite_rules( false ); } if ( $version < 2 ) { $this->insertTerms(); // Re-trigger } if ( $version < 3 ) { $this->upgradeLicenses(); } if ( $version < 4 ) { $this->differentiatePublicDomain(); } }
[ "public", "function", "upgrade", "(", "$", "version", ")", "{", "if", "(", "$", "version", "<", "1", ")", "{", "// Upgrade from version 0 (prior to Pressbooks\\Taxonomy class) to version 1 (simplified chapter types)", "$", "this", "->", "upgradeChapterTypes", "(", ")", ";", "flush_rewrite_rules", "(", "false", ")", ";", "}", "if", "(", "$", "version", "<", "2", ")", "{", "$", "this", "->", "insertTerms", "(", ")", ";", "// Re-trigger", "}", "if", "(", "$", "version", "<", "3", ")", "{", "$", "this", "->", "upgradeLicenses", "(", ")", ";", "}", "if", "(", "$", "version", "<", "4", ")", "{", "$", "this", "->", "differentiatePublicDomain", "(", ")", ";", "}", "}" ]
Upgrade @param int $version
[ "Upgrade" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L551-L567
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.upgradeChapterTypes
protected function upgradeChapterTypes() { $type_1 = get_term_by( 'slug', 'type-1', 'chapter-type' ); $type_2 = get_term_by( 'slug', 'type-2', 'chapter-type' ); $type_3 = get_term_by( 'slug', 'type-3', 'chapter-type' ); $type_4 = get_term_by( 'slug', 'type-4', 'chapter-type' ); $type_5 = get_term_by( 'slug', 'type-5', 'chapter-type' ); if ( $type_1 ) { wp_update_term( $type_1->term_id, 'chapter-type', [ 'name' => 'Standard', 'slug' => 'standard', ] ); } if ( $type_2 ) { wp_delete_term( $type_2->term_id, 'chapter-type' ); } if ( $type_3 ) { wp_delete_term( $type_3->term_id, 'chapter-type' ); } if ( $type_4 ) { wp_delete_term( $type_4->term_id, 'chapter-type' ); } if ( $type_5 ) { wp_delete_term( $type_5->term_id, 'chapter-type' ); } }
php
protected function upgradeChapterTypes() { $type_1 = get_term_by( 'slug', 'type-1', 'chapter-type' ); $type_2 = get_term_by( 'slug', 'type-2', 'chapter-type' ); $type_3 = get_term_by( 'slug', 'type-3', 'chapter-type' ); $type_4 = get_term_by( 'slug', 'type-4', 'chapter-type' ); $type_5 = get_term_by( 'slug', 'type-5', 'chapter-type' ); if ( $type_1 ) { wp_update_term( $type_1->term_id, 'chapter-type', [ 'name' => 'Standard', 'slug' => 'standard', ] ); } if ( $type_2 ) { wp_delete_term( $type_2->term_id, 'chapter-type' ); } if ( $type_3 ) { wp_delete_term( $type_3->term_id, 'chapter-type' ); } if ( $type_4 ) { wp_delete_term( $type_4->term_id, 'chapter-type' ); } if ( $type_5 ) { wp_delete_term( $type_5->term_id, 'chapter-type' ); } }
[ "protected", "function", "upgradeChapterTypes", "(", ")", "{", "$", "type_1", "=", "get_term_by", "(", "'slug'", ",", "'type-1'", ",", "'chapter-type'", ")", ";", "$", "type_2", "=", "get_term_by", "(", "'slug'", ",", "'type-2'", ",", "'chapter-type'", ")", ";", "$", "type_3", "=", "get_term_by", "(", "'slug'", ",", "'type-3'", ",", "'chapter-type'", ")", ";", "$", "type_4", "=", "get_term_by", "(", "'slug'", ",", "'type-4'", ",", "'chapter-type'", ")", ";", "$", "type_5", "=", "get_term_by", "(", "'slug'", ",", "'type-5'", ",", "'chapter-type'", ")", ";", "if", "(", "$", "type_1", ")", "{", "wp_update_term", "(", "$", "type_1", "->", "term_id", ",", "'chapter-type'", ",", "[", "'name'", "=>", "'Standard'", ",", "'slug'", "=>", "'standard'", ",", "]", ")", ";", "}", "if", "(", "$", "type_2", ")", "{", "wp_delete_term", "(", "$", "type_2", "->", "term_id", ",", "'chapter-type'", ")", ";", "}", "if", "(", "$", "type_3", ")", "{", "wp_delete_term", "(", "$", "type_3", "->", "term_id", ",", "'chapter-type'", ")", ";", "}", "if", "(", "$", "type_4", ")", "{", "wp_delete_term", "(", "$", "type_4", "->", "term_id", ",", "'chapter-type'", ")", ";", "}", "if", "(", "$", "type_5", ")", "{", "wp_delete_term", "(", "$", "type_5", "->", "term_id", ",", "'chapter-type'", ")", ";", "}", "}" ]
Upgrade Chapter Types.
[ "Upgrade", "Chapter", "Types", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L611-L642
pressbooks/pressbooks
inc/class-taxonomy.php
Taxonomy.upgradeToContributorTaxonomy
public function upgradeToContributorTaxonomy( $meta_id, $object_id, $meta_key, $meta_value ) { return $this->contributors->convert( $meta_key, $meta_value, $object_id ); }
php
public function upgradeToContributorTaxonomy( $meta_id, $object_id, $meta_key, $meta_value ) { return $this->contributors->convert( $meta_key, $meta_value, $object_id ); }
[ "public", "function", "upgradeToContributorTaxonomy", "(", "$", "meta_id", ",", "$", "object_id", ",", "$", "meta_key", ",", "$", "meta_value", ")", "{", "return", "$", "this", "->", "contributors", "->", "convert", "(", "$", "meta_key", ",", "$", "meta_value", ",", "$", "object_id", ")", ";", "}" ]
If some plugin is still saving to the old/deprecated contributor slugs, then upgrade to Pressbooks Five Data Model @since 5.0.0 @param int $meta_id ID of updated metadata entry. @param int $object_id Post ID. @param string $meta_key Meta key. @param mixed $meta_value Meta value. @return array|false An array containing the `term_id` and `term_taxonomy_id`, false otherwise.
[ "If", "some", "plugin", "is", "still", "saving", "to", "the", "old", "/", "deprecated", "contributor", "slugs", "then", "upgrade", "to", "Pressbooks", "Five", "Data", "Model" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-taxonomy.php#L656-L658
pressbooks/pressbooks
inc/interactive/class-content.php
Content.deleteIframesNotOnWhitelist
public function deleteIframesNotOnWhitelist( $content, $allowed_html ) { // Check if this is a post, bail if it isn't if ( ! is_array( $allowed_html ) ) { $allowed_html = [ $allowed_html ]; } if ( in_array( 'post', $allowed_html, true ) === false ) { return $content; } // Check for iframe HTML code, bail if there isn't any if ( stripos( $content, '<iframe' ) === false ) { return $content; } /** * @param array $value * * @since 5.1.0 */ $whitelist = apply_filters( 'pb_whitelisted_domains', $this->whitelistedDomains ); $changed = false; $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $elements = $dom->getElementsByTagName( 'iframe' ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $src = $iframe->getAttribute( 'src' ); $iframe_url = wp_parse_url( $src ); $is_in_whitelist = false; foreach ( $whitelist as $wl ) { if ( str_starts_with( $wl, '//' ) ) { $wl_url = wp_parse_url( $wl ); if ( $iframe_url['host'] === $wl_url['host'] && str_starts_with( $iframe_url['path'], $wl_url['path'] ) ) { $is_in_whitelist = true; break; } } elseif ( $iframe_url['host'] === $wl ) { $is_in_whitelist = true; break; } } if ( ! $is_in_whitelist ) { $src = $iframe->getAttribute( 'src' ); $fragment = $html5->parser->loadHTMLFragment( "[embed]{$src}[/embed]" ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); $changed = true; } } if ( ! $changed ) { // Nothing was changed, return as is return $content; } else { $s = $html5->saveHTML( $dom ); return $s; } }
php
public function deleteIframesNotOnWhitelist( $content, $allowed_html ) { // Check if this is a post, bail if it isn't if ( ! is_array( $allowed_html ) ) { $allowed_html = [ $allowed_html ]; } if ( in_array( 'post', $allowed_html, true ) === false ) { return $content; } // Check for iframe HTML code, bail if there isn't any if ( stripos( $content, '<iframe' ) === false ) { return $content; } /** * @param array $value * * @since 5.1.0 */ $whitelist = apply_filters( 'pb_whitelisted_domains', $this->whitelistedDomains ); $changed = false; $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $elements = $dom->getElementsByTagName( 'iframe' ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $src = $iframe->getAttribute( 'src' ); $iframe_url = wp_parse_url( $src ); $is_in_whitelist = false; foreach ( $whitelist as $wl ) { if ( str_starts_with( $wl, '//' ) ) { $wl_url = wp_parse_url( $wl ); if ( $iframe_url['host'] === $wl_url['host'] && str_starts_with( $iframe_url['path'], $wl_url['path'] ) ) { $is_in_whitelist = true; break; } } elseif ( $iframe_url['host'] === $wl ) { $is_in_whitelist = true; break; } } if ( ! $is_in_whitelist ) { $src = $iframe->getAttribute( 'src' ); $fragment = $html5->parser->loadHTMLFragment( "[embed]{$src}[/embed]" ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); $changed = true; } } if ( ! $changed ) { // Nothing was changed, return as is return $content; } else { $s = $html5->saveHTML( $dom ); return $s; } }
[ "public", "function", "deleteIframesNotOnWhitelist", "(", "$", "content", ",", "$", "allowed_html", ")", "{", "// Check if this is a post, bail if it isn't", "if", "(", "!", "is_array", "(", "$", "allowed_html", ")", ")", "{", "$", "allowed_html", "=", "[", "$", "allowed_html", "]", ";", "}", "if", "(", "in_array", "(", "'post'", ",", "$", "allowed_html", ",", "true", ")", "===", "false", ")", "{", "return", "$", "content", ";", "}", "// Check for iframe HTML code, bail if there isn't any", "if", "(", "stripos", "(", "$", "content", ",", "'<iframe'", ")", "===", "false", ")", "{", "return", "$", "content", ";", "}", "/**\n\t\t * @param array $value\n\t\t *\n\t\t * @since 5.1.0\n\t\t */", "$", "whitelist", "=", "apply_filters", "(", "'pb_whitelisted_domains'", ",", "$", "this", "->", "whitelistedDomains", ")", ";", "$", "changed", "=", "false", ";", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "content", ")", ";", "$", "elements", "=", "$", "dom", "->", "getElementsByTagName", "(", "'iframe'", ")", ";", "for", "(", "$", "i", "=", "$", "elements", "->", "length", ";", "--", "$", "i", ">=", "0", ";", ")", "{", "// If you're deleting elements from within a loop, you need to loop backwards", "$", "iframe", "=", "$", "elements", "->", "item", "(", "$", "i", ")", ";", "$", "src", "=", "$", "iframe", "->", "getAttribute", "(", "'src'", ")", ";", "$", "iframe_url", "=", "wp_parse_url", "(", "$", "src", ")", ";", "$", "is_in_whitelist", "=", "false", ";", "foreach", "(", "$", "whitelist", "as", "$", "wl", ")", "{", "if", "(", "str_starts_with", "(", "$", "wl", ",", "'//'", ")", ")", "{", "$", "wl_url", "=", "wp_parse_url", "(", "$", "wl", ")", ";", "if", "(", "$", "iframe_url", "[", "'host'", "]", "===", "$", "wl_url", "[", "'host'", "]", "&&", "str_starts_with", "(", "$", "iframe_url", "[", "'path'", "]", ",", "$", "wl_url", "[", "'path'", "]", ")", ")", "{", "$", "is_in_whitelist", "=", "true", ";", "break", ";", "}", "}", "elseif", "(", "$", "iframe_url", "[", "'host'", "]", "===", "$", "wl", ")", "{", "$", "is_in_whitelist", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "is_in_whitelist", ")", "{", "$", "src", "=", "$", "iframe", "->", "getAttribute", "(", "'src'", ")", ";", "$", "fragment", "=", "$", "html5", "->", "parser", "->", "loadHTMLFragment", "(", "\"[embed]{$src}[/embed]\"", ")", ";", "$", "iframe", "->", "parentNode", "->", "replaceChild", "(", "$", "dom", "->", "importNode", "(", "$", "fragment", ",", "true", ")", ",", "$", "iframe", ")", ";", "$", "changed", "=", "true", ";", "}", "}", "if", "(", "!", "$", "changed", ")", "{", "// Nothing was changed, return as is", "return", "$", "content", ";", "}", "else", "{", "$", "s", "=", "$", "html5", "->", "saveHTML", "(", "$", "dom", ")", ";", "return", "$", "s", ";", "}", "}" ]
Delete <iframe> sources not on our whitelist Content is expected to be raw, e.g. before the_content filters have been run Hooked into `pre_kses` filter @param string $content Content to run through kses. @param array $allowed_html Allowed HTML elements. @return string
[ "Delete", "<iframe", ">", "sources", "not", "on", "our", "whitelist", "Content", "is", "expected", "to", "be", "raw", "e", ".", "g", ".", "before", "the_content", "filters", "have", "been", "run", "Hooked", "into", "pre_kses", "filter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L114-L170
pressbooks/pressbooks
inc/interactive/class-content.php
Content.replaceIframes
public function replaceIframes( $content ) { // Check for iframe HTML code, bail if there isn't any if ( stripos( $content, '<iframe' ) === false ) { return $content; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $html = $this->blade->render( 'interactive.shared', [ 'title' => $this->getTitle( $id ), 'url' => wp_get_shortlink( $id ), ] ); $fragment = $html5->parser->loadHTMLFragment( $html ); $elements = $dom->getElementsByTagName( 'iframe' ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); } $s = $html5->saveHTML( $dom ); return $s; }
php
public function replaceIframes( $content ) { // Check for iframe HTML code, bail if there isn't any if ( stripos( $content, '<iframe' ) === false ) { return $content; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $html = $this->blade->render( 'interactive.shared', [ 'title' => $this->getTitle( $id ), 'url' => wp_get_shortlink( $id ), ] ); $fragment = $html5->parser->loadHTMLFragment( $html ); $elements = $dom->getElementsByTagName( 'iframe' ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); } $s = $html5->saveHTML( $dom ); return $s; }
[ "public", "function", "replaceIframes", "(", "$", "content", ")", "{", "// Check for iframe HTML code, bail if there isn't any", "if", "(", "stripos", "(", "$", "content", ",", "'<iframe'", ")", "===", "false", ")", "{", "return", "$", "content", ";", "}", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "content", ")", ";", "$", "html", "=", "$", "this", "->", "blade", "->", "render", "(", "'interactive.shared'", ",", "[", "'title'", "=>", "$", "this", "->", "getTitle", "(", "$", "id", ")", ",", "'url'", "=>", "wp_get_shortlink", "(", "$", "id", ")", ",", "]", ")", ";", "$", "fragment", "=", "$", "html5", "->", "parser", "->", "loadHTMLFragment", "(", "$", "html", ")", ";", "$", "elements", "=", "$", "dom", "->", "getElementsByTagName", "(", "'iframe'", ")", ";", "for", "(", "$", "i", "=", "$", "elements", "->", "length", ";", "--", "$", "i", ">=", "0", ";", ")", "{", "// If you're deleting elements from within a loop, you need to loop backwards", "$", "iframe", "=", "$", "elements", "->", "item", "(", "$", "i", ")", ";", "$", "iframe", "->", "parentNode", "->", "replaceChild", "(", "$", "dom", "->", "importNode", "(", "$", "fragment", ",", "true", ")", ",", "$", "iframe", ")", ";", "}", "$", "s", "=", "$", "html5", "->", "saveHTML", "(", "$", "dom", ")", ";", "return", "$", "s", ";", "}" ]
Replace <iframe> with standard text Content is expected to be rendered, e.g. after the_content filters have been run Hooked into `the_content` filter @param string $content @return string
[ "Replace", "<iframe", ">", "with", "standard", "text", "Content", "is", "expected", "to", "be", "rendered", "e", ".", "g", ".", "after", "the_content", "filters", "have", "been", "run", "Hooked", "into", "the_content", "filter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L181-L208
pressbooks/pressbooks
inc/interactive/class-content.php
Content.allowIframesInHtml
public function allowIframesInHtml( $allowed, $context ) { if ( $context !== 'post' ) { return $allowed; } if ( current_user_can( 'publish_posts' ) === false ) { return $allowed; } $allowed['iframe'] = [ 'src' => true, 'width' => true, 'height' => true, 'frameborder' => true, 'marginwidth' => true, 'marginheight' => true, 'scrolling' => true, 'title' => true, ]; return $allowed; }
php
public function allowIframesInHtml( $allowed, $context ) { if ( $context !== 'post' ) { return $allowed; } if ( current_user_can( 'publish_posts' ) === false ) { return $allowed; } $allowed['iframe'] = [ 'src' => true, 'width' => true, 'height' => true, 'frameborder' => true, 'marginwidth' => true, 'marginheight' => true, 'scrolling' => true, 'title' => true, ]; return $allowed; }
[ "public", "function", "allowIframesInHtml", "(", "$", "allowed", ",", "$", "context", ")", "{", "if", "(", "$", "context", "!==", "'post'", ")", "{", "return", "$", "allowed", ";", "}", "if", "(", "current_user_can", "(", "'publish_posts'", ")", "===", "false", ")", "{", "return", "$", "allowed", ";", "}", "$", "allowed", "[", "'iframe'", "]", "=", "[", "'src'", "=>", "true", ",", "'width'", "=>", "true", ",", "'height'", "=>", "true", ",", "'frameborder'", "=>", "true", ",", "'marginwidth'", "=>", "true", ",", "'marginheight'", "=>", "true", ",", "'scrolling'", "=>", "true", ",", "'title'", "=>", "true", ",", "]", ";", "return", "$", "allowed", ";", "}" ]
Add <iframe> to allowed post tags in wp_kses @param array $allowed @param string $context @return array
[ "Add", "<iframe", ">", "to", "allowed", "post", "tags", "in", "wp_kses" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L218-L237
pressbooks/pressbooks
inc/interactive/class-content.php
Content.replaceOembed
public function replaceOembed( $return, $data, $url ) { // Check for iframe HTML code, bail if there isn't any if ( stripos( $return, '<iframe' ) === false ) { return $return; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $title = $data->title ?? $this->getTitle( $id ); $img_src = $data->thumbnail_url ?? null; $provider_name = $data->provider_name ?? null; $url = wp_get_shortlink( $id ); $html = $this->blade->render( 'interactive.oembed', [ 'title' => $title, 'img_src' => $img_src, 'provider_name' => $provider_name, 'url' => $url, ] ); return $html; }
php
public function replaceOembed( $return, $data, $url ) { // Check for iframe HTML code, bail if there isn't any if ( stripos( $return, '<iframe' ) === false ) { return $return; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $title = $data->title ?? $this->getTitle( $id ); $img_src = $data->thumbnail_url ?? null; $provider_name = $data->provider_name ?? null; $url = wp_get_shortlink( $id ); $html = $this->blade->render( 'interactive.oembed', [ 'title' => $title, 'img_src' => $img_src, 'provider_name' => $provider_name, 'url' => $url, ] ); return $html; }
[ "public", "function", "replaceOembed", "(", "$", "return", ",", "$", "data", ",", "$", "url", ")", "{", "// Check for iframe HTML code, bail if there isn't any", "if", "(", "stripos", "(", "$", "return", ",", "'<iframe'", ")", "===", "false", ")", "{", "return", "$", "return", ";", "}", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "$", "title", "=", "$", "data", "->", "title", "??", "$", "this", "->", "getTitle", "(", "$", "id", ")", ";", "$", "img_src", "=", "$", "data", "->", "thumbnail_url", "??", "null", ";", "$", "provider_name", "=", "$", "data", "->", "provider_name", "??", "null", ";", "$", "url", "=", "wp_get_shortlink", "(", "$", "id", ")", ";", "$", "html", "=", "$", "this", "->", "blade", "->", "render", "(", "'interactive.oembed'", ",", "[", "'title'", "=>", "$", "title", ",", "'img_src'", "=>", "$", "img_src", ",", "'provider_name'", "=>", "$", "provider_name", ",", "'url'", "=>", "$", "url", ",", "]", ")", ";", "return", "$", "html", ";", "}" ]
Filters the returned oEmbed HTML. Hooked into `oembed_dataparse` filter @param string $return The returned oEmbed HTML. @param object $data A data object result from an oEmbed provider. See Response Parameters in https://oembed.com/ specification @param string $url The URL of the content to be embedded. @return string
[ "Filters", "the", "returned", "oEmbed", "HTML", ".", "Hooked", "into", "oembed_dataparse", "filter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L249-L273
pressbooks/pressbooks
inc/interactive/class-content.php
Content.replaceInteractiveTags
public function replaceInteractiveTags( $html ) { $tags = [ 'audio', 'video', ]; // Check for HTML tags, bail if there isn't any $found = false; foreach ( $tags as $tag ) { if ( stripos( $html, "<{$tag}" ) !== false ) { $found = true; break; } } if ( ! $found ) { return $html; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html ); foreach ( $tags as $tag ) { // Load blade template based on $tag $html = $this->blade->render( "interactive.{$tag}", [ 'title' => $this->getTitle( $id ), 'url' => wp_get_shortlink( $id ), ] ); $fragment = $html5->parser->loadHTMLFragment( $html ); // Replace $elements = $dom->getElementsByTagName( $tag ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); } } $s = $html5->saveHTML( $dom ); return $s; }
php
public function replaceInteractiveTags( $html ) { $tags = [ 'audio', 'video', ]; // Check for HTML tags, bail if there isn't any $found = false; foreach ( $tags as $tag ) { if ( stripos( $html, "<{$tag}" ) !== false ) { $found = true; break; } } if ( ! $found ) { return $html; } global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html ); foreach ( $tags as $tag ) { // Load blade template based on $tag $html = $this->blade->render( "interactive.{$tag}", [ 'title' => $this->getTitle( $id ), 'url' => wp_get_shortlink( $id ), ] ); $fragment = $html5->parser->loadHTMLFragment( $html ); // Replace $elements = $dom->getElementsByTagName( $tag ); for ( $i = $elements->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $iframe = $elements->item( $i ); $iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe ); } } $s = $html5->saveHTML( $dom ); return $s; }
[ "public", "function", "replaceInteractiveTags", "(", "$", "html", ")", "{", "$", "tags", "=", "[", "'audio'", ",", "'video'", ",", "]", ";", "// Check for HTML tags, bail if there isn't any", "$", "found", "=", "false", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "if", "(", "stripos", "(", "$", "html", ",", "\"<{$tag}\"", ")", "!==", "false", ")", "{", "$", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "found", ")", "{", "return", "$", "html", ";", "}", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "html", ")", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "// Load blade template based on $tag", "$", "html", "=", "$", "this", "->", "blade", "->", "render", "(", "\"interactive.{$tag}\"", ",", "[", "'title'", "=>", "$", "this", "->", "getTitle", "(", "$", "id", ")", ",", "'url'", "=>", "wp_get_shortlink", "(", "$", "id", ")", ",", "]", ")", ";", "$", "fragment", "=", "$", "html5", "->", "parser", "->", "loadHTMLFragment", "(", "$", "html", ")", ";", "// Replace", "$", "elements", "=", "$", "dom", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "for", "(", "$", "i", "=", "$", "elements", "->", "length", ";", "--", "$", "i", ">=", "0", ";", ")", "{", "// If you're deleting elements from within a loop, you need to loop backwards", "$", "iframe", "=", "$", "elements", "->", "item", "(", "$", "i", ")", ";", "$", "iframe", "->", "parentNode", "->", "replaceChild", "(", "$", "dom", "->", "importNode", "(", "$", "fragment", ",", "true", ")", ",", "$", "iframe", ")", ";", "}", "}", "$", "s", "=", "$", "html5", "->", "saveHTML", "(", "$", "dom", ")", ";", "return", "$", "s", ";", "}" ]
Replace interactive tags such as <audio>, <video> @param string $html @return string
[ "Replace", "interactive", "tags", "such", "as", "<audio", ">", "<video", ">" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L282-L325
pressbooks/pressbooks
inc/interactive/class-content.php
Content.addExtraOembedProviders
public function addExtraOembedProviders( $providers ) { // Format (string), Provider (string), Is format a regular expression? (bool) $providers['#https?://mathembed\.com/latex\?inputText=.*#i'] = [ 'https://mathembed.com/oembed', true ]; $providers['#https?://www\.openassessments\.org/assessments/.*#i'] = [ 'https://www.openassessments.org/oembed.json', true ]; $providers['://cdn.knightlab.com/libs/timeline*'] = [ 'https://oembed.knightlab.com/timeline/', false ]; $providers['://uploads.knightlab.com/storymapjs/*/index.html'] = [ 'https://oembed.knightlab.com/storymap/', false ]; return $providers; }
php
public function addExtraOembedProviders( $providers ) { // Format (string), Provider (string), Is format a regular expression? (bool) $providers['#https?://mathembed\.com/latex\?inputText=.*#i'] = [ 'https://mathembed.com/oembed', true ]; $providers['#https?://www\.openassessments\.org/assessments/.*#i'] = [ 'https://www.openassessments.org/oembed.json', true ]; $providers['://cdn.knightlab.com/libs/timeline*'] = [ 'https://oembed.knightlab.com/timeline/', false ]; $providers['://uploads.knightlab.com/storymapjs/*/index.html'] = [ 'https://oembed.knightlab.com/storymap/', false ]; return $providers; }
[ "public", "function", "addExtraOembedProviders", "(", "$", "providers", ")", "{", "// Format (string), Provider (string), Is format a regular expression? (bool)", "$", "providers", "[", "'#https?://mathembed\\.com/latex\\?inputText=.*#i'", "]", "=", "[", "'https://mathembed.com/oembed'", ",", "true", "]", ";", "$", "providers", "[", "'#https?://www\\.openassessments\\.org/assessments/.*#i'", "]", "=", "[", "'https://www.openassessments.org/oembed.json'", ",", "true", "]", ";", "$", "providers", "[", "'://cdn.knightlab.com/libs/timeline*'", "]", "=", "[", "'https://oembed.knightlab.com/timeline/'", ",", "false", "]", ";", "$", "providers", "[", "'://uploads.knightlab.com/storymapjs/*/index.html'", "]", "=", "[", "'https://oembed.knightlab.com/storymap/'", ",", "false", "]", ";", "return", "$", "providers", ";", "}" ]
Add oEmbed providers Hooked into `oembed_providers` filter @see \WP_oEmbed @see https://oembed.com/ @see https://github.com/iamcal/oembed/tree/master/providers @param array $providers @return array
[ "Add", "oEmbed", "providers", "Hooked", "into", "oembed_providers", "filter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L339-L348
pressbooks/pressbooks
inc/interactive/class-content.php
Content.deleteOembedCaches
public function deleteOembedCaches( $post_id = 0 ) { if ( $post_id ) { global $wp_embed; $wp_embed->delete_oembed_caches( $post_id ); } else { global $wpdb; $post_metas = $wpdb->get_results( "SELECT post_id, meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE '_oembed_%' " ); foreach ( $post_metas as $post_meta ) { delete_post_meta( $post_meta->post_id, $post_meta->meta_key ); } } }
php
public function deleteOembedCaches( $post_id = 0 ) { if ( $post_id ) { global $wp_embed; $wp_embed->delete_oembed_caches( $post_id ); } else { global $wpdb; $post_metas = $wpdb->get_results( "SELECT post_id, meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE '_oembed_%' " ); foreach ( $post_metas as $post_meta ) { delete_post_meta( $post_meta->post_id, $post_meta->meta_key ); } } }
[ "public", "function", "deleteOembedCaches", "(", "$", "post_id", "=", "0", ")", "{", "if", "(", "$", "post_id", ")", "{", "global", "$", "wp_embed", ";", "$", "wp_embed", "->", "delete_oembed_caches", "(", "$", "post_id", ")", ";", "}", "else", "{", "global", "$", "wpdb", ";", "$", "post_metas", "=", "$", "wpdb", "->", "get_results", "(", "\"SELECT post_id, meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE '_oembed_%' \"", ")", ";", "foreach", "(", "$", "post_metas", "as", "$", "post_meta", ")", "{", "delete_post_meta", "(", "$", "post_meta", "->", "post_id", ",", "$", "post_meta", "->", "meta_key", ")", ";", "}", "}", "}" ]
Delete all oEmbed caches @param int $post_id
[ "Delete", "all", "oEmbed", "caches" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L355-L366
pressbooks/pressbooks
inc/interactive/class-content.php
Content.beforeExport
public function beforeExport() { $this->overrideH5P(); $this->overridePhet(); $this->overrideIframes(); $this->overrideEmbeds(); $this->overrideVideo(); $this->overrideAudio(); }
php
public function beforeExport() { $this->overrideH5P(); $this->overridePhet(); $this->overrideIframes(); $this->overrideEmbeds(); $this->overrideVideo(); $this->overrideAudio(); }
[ "public", "function", "beforeExport", "(", ")", "{", "$", "this", "->", "overrideH5P", "(", ")", ";", "$", "this", "->", "overridePhet", "(", ")", ";", "$", "this", "->", "overrideIframes", "(", ")", ";", "$", "this", "->", "overrideEmbeds", "(", ")", ";", "$", "this", "->", "overrideVideo", "(", ")", ";", "$", "this", "->", "overrideAudio", "(", ")", ";", "}" ]
Hooked into `pb_pre_export` action
[ "Hooked", "into", "pb_pre_export", "action" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L380-L387
pressbooks/pressbooks
inc/interactive/class-content.php
Content.overrideIframes
protected function overrideIframes() { if ( self::$instance ) { remove_filter( 'pre_kses', [ self::$instance, 'deleteIframesNotOnWhitelist' ] ); remove_filter( 'wp_kses_allowed_html', [ self::$instance, 'allowIframesInHtml' ] ); } add_filter( 'the_content', [ $this, 'replaceIframes' ], 999 ); // Priority equals 999 because this should go last }
php
protected function overrideIframes() { if ( self::$instance ) { remove_filter( 'pre_kses', [ self::$instance, 'deleteIframesNotOnWhitelist' ] ); remove_filter( 'wp_kses_allowed_html', [ self::$instance, 'allowIframesInHtml' ] ); } add_filter( 'the_content', [ $this, 'replaceIframes' ], 999 ); // Priority equals 999 because this should go last }
[ "protected", "function", "overrideIframes", "(", ")", "{", "if", "(", "self", "::", "$", "instance", ")", "{", "remove_filter", "(", "'pre_kses'", ",", "[", "self", "::", "$", "instance", ",", "'deleteIframesNotOnWhitelist'", "]", ")", ";", "remove_filter", "(", "'wp_kses_allowed_html'", ",", "[", "self", "::", "$", "instance", ",", "'allowIframesInHtml'", "]", ")", ";", "}", "add_filter", "(", "'the_content'", ",", "[", "$", "this", ",", "'replaceIframes'", "]", ",", "999", ")", ";", "// Priority equals 999 because this should go last", "}" ]
Override any <iframe> code found in HTML
[ "Override", "any", "<iframe", ">", "code", "found", "in", "HTML" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L409-L416
pressbooks/pressbooks
inc/interactive/class-content.php
Content.overrideEmbeds
protected function overrideEmbeds() { global $wp_embed; $wp_embed->usecache = false; add_filter( 'oembed_ttl', '__return_zero', 999 ); add_filter( 'embed_defaults', function ( $attr ) { // Embed cache keys are created by doing `md5( $url . serialize( $attr ) )` // By adding an HTML5 Data Attribute we change the MD5, thereby busting the cache when exporting $attr['data-pb-export'] = 'true'; return $attr; } ); add_filter( 'oembed_dataparse', [ $this, 'replaceOembed' ], 1, 3 ); }
php
protected function overrideEmbeds() { global $wp_embed; $wp_embed->usecache = false; add_filter( 'oembed_ttl', '__return_zero', 999 ); add_filter( 'embed_defaults', function ( $attr ) { // Embed cache keys are created by doing `md5( $url . serialize( $attr ) )` // By adding an HTML5 Data Attribute we change the MD5, thereby busting the cache when exporting $attr['data-pb-export'] = 'true'; return $attr; } ); add_filter( 'oembed_dataparse', [ $this, 'replaceOembed' ], 1, 3 ); }
[ "protected", "function", "overrideEmbeds", "(", ")", "{", "global", "$", "wp_embed", ";", "$", "wp_embed", "->", "usecache", "=", "false", ";", "add_filter", "(", "'oembed_ttl'", ",", "'__return_zero'", ",", "999", ")", ";", "add_filter", "(", "'embed_defaults'", ",", "function", "(", "$", "attr", ")", "{", "// Embed cache keys are created by doing `md5( $url . serialize( $attr ) )`", "// By adding an HTML5 Data Attribute we change the MD5, thereby busting the cache when exporting", "$", "attr", "[", "'data-pb-export'", "]", "=", "'true'", ";", "return", "$", "attr", ";", "}", ")", ";", "add_filter", "(", "'oembed_dataparse'", ",", "[", "$", "this", ",", "'replaceOembed'", "]", ",", "1", ",", "3", ")", ";", "}" ]
Override WordPress Embeds
[ "Override", "WordPress", "Embeds" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L421-L434
pressbooks/pressbooks
inc/interactive/class-content.php
Content.overrideVideo
protected function overrideVideo() { /** * @param string $output Video shortcode HTML output. * @param array $atts Array of video shortcode attributes. * @param string $video Video file. */ add_filter( 'wp_video_shortcode', function ( $output, $atts, $video ) { $src_attributes = array_merge( [ 'src' ], wp_get_video_extensions() ); foreach ( $src_attributes as $attribute ) { if ( ! empty( $atts[ $attribute ] ) ) { $src = $atts[ $attribute ]; break; } } if ( empty( $src ) ) { $src = $video; } $type = wp_check_filetype( $src, wp_get_mime_types() )['type']; $output = "<video class='wp-video-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></video>"; return $output; }, 10, 3 ); }
php
protected function overrideVideo() { /** * @param string $output Video shortcode HTML output. * @param array $atts Array of video shortcode attributes. * @param string $video Video file. */ add_filter( 'wp_video_shortcode', function ( $output, $atts, $video ) { $src_attributes = array_merge( [ 'src' ], wp_get_video_extensions() ); foreach ( $src_attributes as $attribute ) { if ( ! empty( $atts[ $attribute ] ) ) { $src = $atts[ $attribute ]; break; } } if ( empty( $src ) ) { $src = $video; } $type = wp_check_filetype( $src, wp_get_mime_types() )['type']; $output = "<video class='wp-video-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></video>"; return $output; }, 10, 3 ); }
[ "protected", "function", "overrideVideo", "(", ")", "{", "/**\n\t\t * @param string $output Video shortcode HTML output.\n\t\t * @param array $atts Array of video shortcode attributes.\n\t\t * @param string $video Video file.\n\t\t */", "add_filter", "(", "'wp_video_shortcode'", ",", "function", "(", "$", "output", ",", "$", "atts", ",", "$", "video", ")", "{", "$", "src_attributes", "=", "array_merge", "(", "[", "'src'", "]", ",", "wp_get_video_extensions", "(", ")", ")", ";", "foreach", "(", "$", "src_attributes", "as", "$", "attribute", ")", "{", "if", "(", "!", "empty", "(", "$", "atts", "[", "$", "attribute", "]", ")", ")", "{", "$", "src", "=", "$", "atts", "[", "$", "attribute", "]", ";", "break", ";", "}", "}", "if", "(", "empty", "(", "$", "src", ")", ")", "{", "$", "src", "=", "$", "video", ";", "}", "$", "type", "=", "wp_check_filetype", "(", "$", "src", ",", "wp_get_mime_types", "(", ")", ")", "[", "'type'", "]", ";", "$", "output", "=", "\"<video class='wp-video-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></video>\"", ";", "return", "$", "output", ";", "}", ",", "10", ",", "3", ")", ";", "}" ]
Override Video @see https://codex.wordpress.org/Video_Shortcode
[ "Override", "Video" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L441-L464
pressbooks/pressbooks
inc/interactive/class-content.php
Content.overrideAudio
protected function overrideAudio() { /** * @param string $output Audio shortcode HTML output. * @param array $atts Array of Audio shortcode attributes. * @param string $audio Audio file. */ add_filter( 'wp_audio_shortcode', function ( $output, $atts, $audio ) { $src_attributes = array_merge( [ 'src' ], wp_get_audio_extensions() ); foreach ( $src_attributes as $attribute ) { if ( ! empty( $atts[ $attribute ] ) ) { $src = $atts[ $attribute ]; break; } } if ( empty( $src ) ) { $src = $audio; } $type = wp_check_filetype( $src, wp_get_mime_types() )['type']; $output = "<audio class='wp-audio-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></audio>"; return $output; }, 10, 3 ); }
php
protected function overrideAudio() { /** * @param string $output Audio shortcode HTML output. * @param array $atts Array of Audio shortcode attributes. * @param string $audio Audio file. */ add_filter( 'wp_audio_shortcode', function ( $output, $atts, $audio ) { $src_attributes = array_merge( [ 'src' ], wp_get_audio_extensions() ); foreach ( $src_attributes as $attribute ) { if ( ! empty( $atts[ $attribute ] ) ) { $src = $atts[ $attribute ]; break; } } if ( empty( $src ) ) { $src = $audio; } $type = wp_check_filetype( $src, wp_get_mime_types() )['type']; $output = "<audio class='wp-audio-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></audio>"; return $output; }, 10, 3 ); }
[ "protected", "function", "overrideAudio", "(", ")", "{", "/**\n\t\t * @param string $output Audio shortcode HTML output.\n\t\t * @param array $atts Array of Audio shortcode attributes.\n\t\t * @param string $audio Audio file.\n\t\t */", "add_filter", "(", "'wp_audio_shortcode'", ",", "function", "(", "$", "output", ",", "$", "atts", ",", "$", "audio", ")", "{", "$", "src_attributes", "=", "array_merge", "(", "[", "'src'", "]", ",", "wp_get_audio_extensions", "(", ")", ")", ";", "foreach", "(", "$", "src_attributes", "as", "$", "attribute", ")", "{", "if", "(", "!", "empty", "(", "$", "atts", "[", "$", "attribute", "]", ")", ")", "{", "$", "src", "=", "$", "atts", "[", "$", "attribute", "]", ";", "break", ";", "}", "}", "if", "(", "empty", "(", "$", "src", ")", ")", "{", "$", "src", "=", "$", "audio", ";", "}", "$", "type", "=", "wp_check_filetype", "(", "$", "src", ",", "wp_get_mime_types", "(", ")", ")", "[", "'type'", "]", ";", "$", "output", "=", "\"<audio class='wp-audio-shortcode' controls='controls'><source type='{$type}' src='{$src}' /><a href='{$src}'>{$src}</a></audio>\"", ";", "return", "$", "output", ";", "}", ",", "10", ",", "3", ")", ";", "}" ]
Override Audio @see https://codex.wordpress.org/Audio_Shortcode
[ "Override", "Audio" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L471-L494
pressbooks/pressbooks
inc/interactive/class-content.php
Content.getTitle
protected function getTitle( $post_id ) { $title = get_the_title( $post_id ); if ( empty( $title ) ) { $title = get_bloginfo( 'name' ); } return $title; }
php
protected function getTitle( $post_id ) { $title = get_the_title( $post_id ); if ( empty( $title ) ) { $title = get_bloginfo( 'name' ); } return $title; }
[ "protected", "function", "getTitle", "(", "$", "post_id", ")", "{", "$", "title", "=", "get_the_title", "(", "$", "post_id", ")", ";", "if", "(", "empty", "(", "$", "title", ")", ")", "{", "$", "title", "=", "get_bloginfo", "(", "'name'", ")", ";", "}", "return", "$", "title", ";", "}" ]
@param int $post_id @return string
[ "@param", "int", "$post_id" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L501-L507
pressbooks/pressbooks
inc/interactive/class-content.php
Content.adjustOembeds
public function adjustOembeds( $html, $url, $args ) { if ( ! strpos( $html, 'youtube' ) === false ) { return str_replace( '?feature=oembed', '?feature=oembed&rel=0', $html ); } return $html; }
php
public function adjustOembeds( $html, $url, $args ) { if ( ! strpos( $html, 'youtube' ) === false ) { return str_replace( '?feature=oembed', '?feature=oembed&rel=0', $html ); } return $html; }
[ "public", "function", "adjustOembeds", "(", "$", "html", ",", "$", "url", ",", "$", "args", ")", "{", "if", "(", "!", "strpos", "(", "$", "html", ",", "'youtube'", ")", "===", "false", ")", "{", "return", "str_replace", "(", "'?feature=oembed'", ",", "'?feature=oembed&rel=0'", ",", "$", "html", ")", ";", "}", "return", "$", "html", ";", "}" ]
@param string $html @param string $url @param array $args @return string
[ "@param", "string", "$html", "@param", "string", "$url", "@param", "array", "$args" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-content.php#L516-L521
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.kneadAndInsert
function kneadAndInsert( $html, $post_type, $chapter_parent, $domain, $post_status ) { $matches = []; $meta = $this->getLicenseAttribution( $html ); $author = ( isset( $meta['authors'] ) ) ? $meta['authors'] : $this->getAuthors( $html ); $license = ( isset( $meta['license'] ) ) ? $this->extractCCLicense( $meta['license'] ) : ''; // get the title, preference to title set by PB preg_match( '/<h2 class="entry-title">(.*)<\/h2>/', $html, $matches ); if ( ! empty( $matches[1] ) ) { $title = wp_strip_all_tags( $matches[1] ); } else { preg_match( '/<title>(.+)<\/title>/', $html, $matches ); $title = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '__UNKNOWN__' ); } // just get the body preg_match( '/(?:<body[^>]*>)(.*)<\/body>/isU', $html, $matches ); // get rid of stuff we don't need $body = $this->regexSearchReplace( $matches[1] ); // clean it up $xhtml = $this->tidy( $body ); $body = $this->kneadHtml( $xhtml, $post_type, $domain ); $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, ]; if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } $pid = wp_insert_post( add_magic_quotes( $new_post ) ); if ( ! empty( $author ) ) { ( new Contributors() )->insert( $author, $pid, 'pb_authors' ); } if ( ! empty( $license ) ) { update_post_meta( $pid, 'pb_section_license', $license ); } update_post_meta( $pid, 'pb_show_title', 'on' ); Book::consolidatePost( $pid, get_post( $pid ) ); // Reorder }
php
function kneadAndInsert( $html, $post_type, $chapter_parent, $domain, $post_status ) { $matches = []; $meta = $this->getLicenseAttribution( $html ); $author = ( isset( $meta['authors'] ) ) ? $meta['authors'] : $this->getAuthors( $html ); $license = ( isset( $meta['license'] ) ) ? $this->extractCCLicense( $meta['license'] ) : ''; // get the title, preference to title set by PB preg_match( '/<h2 class="entry-title">(.*)<\/h2>/', $html, $matches ); if ( ! empty( $matches[1] ) ) { $title = wp_strip_all_tags( $matches[1] ); } else { preg_match( '/<title>(.+)<\/title>/', $html, $matches ); $title = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '__UNKNOWN__' ); } // just get the body preg_match( '/(?:<body[^>]*>)(.*)<\/body>/isU', $html, $matches ); // get rid of stuff we don't need $body = $this->regexSearchReplace( $matches[1] ); // clean it up $xhtml = $this->tidy( $body ); $body = $this->kneadHtml( $xhtml, $post_type, $domain ); $new_post = [ 'post_title' => $title, 'post_content' => $body, 'post_type' => $post_type, 'post_status' => $post_status, ]; if ( 'chapter' === $post_type ) { $new_post['post_parent'] = $chapter_parent; } $pid = wp_insert_post( add_magic_quotes( $new_post ) ); if ( ! empty( $author ) ) { ( new Contributors() )->insert( $author, $pid, 'pb_authors' ); } if ( ! empty( $license ) ) { update_post_meta( $pid, 'pb_section_license', $license ); } update_post_meta( $pid, 'pb_show_title', 'on' ); Book::consolidatePost( $pid, get_post( $pid ) ); // Reorder }
[ "function", "kneadAndInsert", "(", "$", "html", ",", "$", "post_type", ",", "$", "chapter_parent", ",", "$", "domain", ",", "$", "post_status", ")", "{", "$", "matches", "=", "[", "]", ";", "$", "meta", "=", "$", "this", "->", "getLicenseAttribution", "(", "$", "html", ")", ";", "$", "author", "=", "(", "isset", "(", "$", "meta", "[", "'authors'", "]", ")", ")", "?", "$", "meta", "[", "'authors'", "]", ":", "$", "this", "->", "getAuthors", "(", "$", "html", ")", ";", "$", "license", "=", "(", "isset", "(", "$", "meta", "[", "'license'", "]", ")", ")", "?", "$", "this", "->", "extractCCLicense", "(", "$", "meta", "[", "'license'", "]", ")", ":", "''", ";", "// get the title, preference to title set by PB", "preg_match", "(", "'/<h2 class=\"entry-title\">(.*)<\\/h2>/'", ",", "$", "html", ",", "$", "matches", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "$", "title", "=", "wp_strip_all_tags", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "else", "{", "preg_match", "(", "'/<title>(.+)<\\/title>/'", ",", "$", "html", ",", "$", "matches", ")", ";", "$", "title", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", "?", "wp_strip_all_tags", "(", "$", "matches", "[", "1", "]", ")", ":", "'__UNKNOWN__'", ")", ";", "}", "// just get the body", "preg_match", "(", "'/(?:<body[^>]*>)(.*)<\\/body>/isU'", ",", "$", "html", ",", "$", "matches", ")", ";", "// get rid of stuff we don't need", "$", "body", "=", "$", "this", "->", "regexSearchReplace", "(", "$", "matches", "[", "1", "]", ")", ";", "// clean it up", "$", "xhtml", "=", "$", "this", "->", "tidy", "(", "$", "body", ")", ";", "$", "body", "=", "$", "this", "->", "kneadHtml", "(", "$", "xhtml", ",", "$", "post_type", ",", "$", "domain", ")", ";", "$", "new_post", "=", "[", "'post_title'", "=>", "$", "title", ",", "'post_content'", "=>", "$", "body", ",", "'post_type'", "=>", "$", "post_type", ",", "'post_status'", "=>", "$", "post_status", ",", "]", ";", "if", "(", "'chapter'", "===", "$", "post_type", ")", "{", "$", "new_post", "[", "'post_parent'", "]", "=", "$", "chapter_parent", ";", "}", "$", "pid", "=", "wp_insert_post", "(", "add_magic_quotes", "(", "$", "new_post", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "author", ")", ")", "{", "(", "new", "Contributors", "(", ")", ")", "->", "insert", "(", "$", "author", ",", "$", "pid", ",", "'pb_authors'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "license", ")", ")", "{", "update_post_meta", "(", "$", "pid", ",", "'pb_section_license'", ",", "$", "license", ")", ";", "}", "update_post_meta", "(", "$", "pid", ",", "'pb_show_title'", ",", "'on'", ")", ";", "Book", "::", "consolidatePost", "(", "$", "pid", ",", "get_post", "(", "$", "pid", ")", ")", ";", "// Reorder", "}" ]
Pummel then insert HTML into our database @param string $html @param string $post_type @param int $chapter_parent @param string $domain domain name of the web page @param string $post_status
[ "Pummel", "then", "insert", "HTML", "into", "our", "database" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L81-L132
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.extractCCLicense
protected function extractCCLicense( $url ) { $license = ''; // evaluate that it's a url if ( ! is_string( $url ) ) { return $license; } // look for creativecommons domain $parts = wp_parse_url( $url ); if ( 'http' === $parts['scheme'] && 'creativecommons.org' === $parts['host'] ) { // extract the license information from it $split = explode( '/', $parts['path'] ); if ( 'zero' === $split[2] ) { $license = 'cc0'; } else { $license = 'cc-' . $split[2]; } } return $license; }
php
protected function extractCCLicense( $url ) { $license = ''; // evaluate that it's a url if ( ! is_string( $url ) ) { return $license; } // look for creativecommons domain $parts = wp_parse_url( $url ); if ( 'http' === $parts['scheme'] && 'creativecommons.org' === $parts['host'] ) { // extract the license information from it $split = explode( '/', $parts['path'] ); if ( 'zero' === $split[2] ) { $license = 'cc0'; } else { $license = 'cc-' . $split[2]; } } return $license; }
[ "protected", "function", "extractCCLicense", "(", "$", "url", ")", "{", "$", "license", "=", "''", ";", "// evaluate that it's a url", "if", "(", "!", "is_string", "(", "$", "url", ")", ")", "{", "return", "$", "license", ";", "}", "// look for creativecommons domain", "$", "parts", "=", "wp_parse_url", "(", "$", "url", ")", ";", "if", "(", "'http'", "===", "$", "parts", "[", "'scheme'", "]", "&&", "'creativecommons.org'", "===", "$", "parts", "[", "'host'", "]", ")", "{", "// extract the license information from it", "$", "split", "=", "explode", "(", "'/'", ",", "$", "parts", "[", "'path'", "]", ")", ";", "if", "(", "'zero'", "===", "$", "split", "[", "2", "]", ")", "{", "$", "license", "=", "'cc0'", ";", "}", "else", "{", "$", "license", "=", "'cc-'", ".", "$", "split", "[", "2", "]", ";", "}", "}", "return", "$", "license", ";", "}" ]
Expects a URL string with Creative Commons domain similar in form to: http://creativecommons.org/licenses/by-sa/4.0/ @param string $url @return string license meta value
[ "Expects", "a", "URL", "string", "with", "Creative", "Commons", "domain", "similar", "in", "form", "to", ":", "http", ":", "//", "creativecommons", ".", "org", "/", "licenses", "/", "by", "-", "sa", "/", "4", ".", "0", "/" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L142-L163
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.getLicenseAttribution
protected function getLicenseAttribution( $html ) { $meta = []; // get license attribution statement if it exists preg_match( '/(?:<div class="license-attribution[^>]*>)(.*)(<\/div>)/isU', $html, $matches ); if ( ! empty( $matches[1] ) ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $matches[1] ); $meta = $this->scrapeAndKneadMeta( $dom ); } return $meta; }
php
protected function getLicenseAttribution( $html ) { $meta = []; // get license attribution statement if it exists preg_match( '/(?:<div class="license-attribution[^>]*>)(.*)(<\/div>)/isU', $html, $matches ); if ( ! empty( $matches[1] ) ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $matches[1] ); $meta = $this->scrapeAndKneadMeta( $dom ); } return $meta; }
[ "protected", "function", "getLicenseAttribution", "(", "$", "html", ")", "{", "$", "meta", "=", "[", "]", ";", "// get license attribution statement if it exists", "preg_match", "(", "'/(?:<div class=\"license-attribution[^>]*>)(.*)(<\\/div>)/isU'", ",", "$", "html", ",", "$", "matches", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "meta", "=", "$", "this", "->", "scrapeAndKneadMeta", "(", "$", "dom", ")", ";", "}", "return", "$", "meta", ";", "}" ]
Looks for div class created by the license module in PB, returns author and license information. @param string $html @return array $meta
[ "Looks", "for", "div", "class", "created", "by", "the", "license", "module", "in", "PB", "returns", "author", "and", "license", "information", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L173-L185
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.getAuthors
protected function getAuthors( $html ) { // go for the book metadata set in PB <head> preg_match( '/(<meta itemprop="copyrightHolder" content=")(.+)(" id="copyrightHolder")>/is', $html, $matches ); if ( empty( $matches[2] ) ) { // grab the authors, if copyrightHolders is empty preg_match( '/(<meta itemprop="author" content=")(.+)(" id="author")>/is', $html, $matches ); } $authors = isset( $matches[2] ) ? $matches[2] : ''; // final attempt, must not be a PB html page if ( empty( $authors ) ) { preg_match( '/(<meta name="author" content=")(.+)">/isU', $html, $matches ); // get the copyright name, if author is empty if ( empty( $matches[1] ) ) { preg_match( '/(<meta name="copyright" content=")(.+)">/isU', $html, $matches ); } $authors = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '' ); } return $authors; }
php
protected function getAuthors( $html ) { // go for the book metadata set in PB <head> preg_match( '/(<meta itemprop="copyrightHolder" content=")(.+)(" id="copyrightHolder")>/is', $html, $matches ); if ( empty( $matches[2] ) ) { // grab the authors, if copyrightHolders is empty preg_match( '/(<meta itemprop="author" content=")(.+)(" id="author")>/is', $html, $matches ); } $authors = isset( $matches[2] ) ? $matches[2] : ''; // final attempt, must not be a PB html page if ( empty( $authors ) ) { preg_match( '/(<meta name="author" content=")(.+)">/isU', $html, $matches ); // get the copyright name, if author is empty if ( empty( $matches[1] ) ) { preg_match( '/(<meta name="copyright" content=")(.+)">/isU', $html, $matches ); } $authors = ( ! empty( $matches[1] ) ? wp_strip_all_tags( $matches[1] ) : '' ); } return $authors; }
[ "protected", "function", "getAuthors", "(", "$", "html", ")", "{", "// go for the book metadata set in PB <head>", "preg_match", "(", "'/(<meta itemprop=\"copyrightHolder\" content=\")(.+)(\" id=\"copyrightHolder\")>/is'", ",", "$", "html", ",", "$", "matches", ")", ";", "if", "(", "empty", "(", "$", "matches", "[", "2", "]", ")", ")", "{", "// grab the authors, if copyrightHolders is empty", "preg_match", "(", "'/(<meta itemprop=\"author\" content=\")(.+)(\" id=\"author\")>/is'", ",", "$", "html", ",", "$", "matches", ")", ";", "}", "$", "authors", "=", "isset", "(", "$", "matches", "[", "2", "]", ")", "?", "$", "matches", "[", "2", "]", ":", "''", ";", "// final attempt, must not be a PB html page", "if", "(", "empty", "(", "$", "authors", ")", ")", "{", "preg_match", "(", "'/(<meta name=\"author\" content=\")(.+)\">/isU'", ",", "$", "html", ",", "$", "matches", ")", ";", "// get the copyright name, if author is empty", "if", "(", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "preg_match", "(", "'/(<meta name=\"copyright\" content=\")(.+)\">/isU'", ",", "$", "html", ",", "$", "matches", ")", ";", "}", "$", "authors", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", "?", "wp_strip_all_tags", "(", "$", "matches", "[", "1", "]", ")", ":", "''", ")", ";", "}", "return", "$", "authors", ";", "}" ]
Looks for meta data in the <head> section of an HTML document. Priority is given to PB generated meta data. @param string $html @return string $authors
[ "Looks", "for", "meta", "data", "in", "the", "<head", ">", "section", "of", "an", "HTML", "document", ".", "Priority", "is", "given", "to", "PB", "generated", "meta", "data", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L195-L218
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.regexSearchReplace
protected function regexSearchReplace( $html ) { /* cherry pick likely content areas */ // HTML5, ungreedy preg_match( '/(?:<main[^>]*>)(.*)<\/main>/isU', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // WP content area, greedy preg_match( '/(?:<div id="main"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // general content area, greedy preg_match( '/(?:<div id="content"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // specific PB content area, greedy preg_match( '/(?:<div class="entry-content"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; /* cull */ // get rid of script tags, ungreedy $result = preg_replace( '/(?:<script[^>]*>)(.*)<\/script>/isU', '', $html ); // get rid of forms, ungreedy $result = preg_replace( '/(?:<form[^>]*>)(.*)<\/form>/isU', '', $result ); // get rid of html5 nav content, ungreedy $result = preg_replace( '/(?:<nav[^>]*>)(.*)<\/nav>/isU', '', $result ); // get rid of PB nav, next/previous $result = preg_replace( '/(?:<div class="nav"[^>]*>)(.*)<\/div>/isU', '', $result ); // get rid of PB share buttons $result = preg_replace( '/(?:<div class="share-wrap-single"[^>]*>)(.*)<\/div>/isU', '', $result ); // get rid of html5 footer content, ungreedy $result = preg_replace( '/(?:<footer[^>]*>)(.*)<\/footer>/isU', '', $result ); // get rid of sidebar content, greedy $result = preg_replace( '/(?:<div id="sidebar\d{0,}"[^>]*>)(.*)<\/div>/is', '', $result ); // get rid of comments, greedy $result = preg_replace( '/(?:<div id="comments"[^>]*>)(.*)<\/div>/is', '', $result ); return $result; }
php
protected function regexSearchReplace( $html ) { /* cherry pick likely content areas */ // HTML5, ungreedy preg_match( '/(?:<main[^>]*>)(.*)<\/main>/isU', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // WP content area, greedy preg_match( '/(?:<div id="main"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // general content area, greedy preg_match( '/(?:<div id="content"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; // specific PB content area, greedy preg_match( '/(?:<div class="entry-content"[^>]*>)(.*)<\/div>/is', $html, $matches ); $html = ( ! empty( $matches[1] ) ) ? $matches[1] : $html; /* cull */ // get rid of script tags, ungreedy $result = preg_replace( '/(?:<script[^>]*>)(.*)<\/script>/isU', '', $html ); // get rid of forms, ungreedy $result = preg_replace( '/(?:<form[^>]*>)(.*)<\/form>/isU', '', $result ); // get rid of html5 nav content, ungreedy $result = preg_replace( '/(?:<nav[^>]*>)(.*)<\/nav>/isU', '', $result ); // get rid of PB nav, next/previous $result = preg_replace( '/(?:<div class="nav"[^>]*>)(.*)<\/div>/isU', '', $result ); // get rid of PB share buttons $result = preg_replace( '/(?:<div class="share-wrap-single"[^>]*>)(.*)<\/div>/isU', '', $result ); // get rid of html5 footer content, ungreedy $result = preg_replace( '/(?:<footer[^>]*>)(.*)<\/footer>/isU', '', $result ); // get rid of sidebar content, greedy $result = preg_replace( '/(?:<div id="sidebar\d{0,}"[^>]*>)(.*)<\/div>/is', '', $result ); // get rid of comments, greedy $result = preg_replace( '/(?:<div id="comments"[^>]*>)(.*)<\/div>/is', '', $result ); return $result; }
[ "protected", "function", "regexSearchReplace", "(", "$", "html", ")", "{", "/* cherry pick likely content areas */", "// HTML5, ungreedy", "preg_match", "(", "'/(?:<main[^>]*>)(.*)<\\/main>/isU'", ",", "$", "html", ",", "$", "matches", ")", ";", "$", "html", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "?", "$", "matches", "[", "1", "]", ":", "$", "html", ";", "// WP content area, greedy", "preg_match", "(", "'/(?:<div id=\"main\"[^>]*>)(.*)<\\/div>/is'", ",", "$", "html", ",", "$", "matches", ")", ";", "$", "html", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "?", "$", "matches", "[", "1", "]", ":", "$", "html", ";", "// general content area, greedy", "preg_match", "(", "'/(?:<div id=\"content\"[^>]*>)(.*)<\\/div>/is'", ",", "$", "html", ",", "$", "matches", ")", ";", "$", "html", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "?", "$", "matches", "[", "1", "]", ":", "$", "html", ";", "// specific PB content area, greedy", "preg_match", "(", "'/(?:<div class=\"entry-content\"[^>]*>)(.*)<\\/div>/is'", ",", "$", "html", ",", "$", "matches", ")", ";", "$", "html", "=", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "?", "$", "matches", "[", "1", "]", ":", "$", "html", ";", "/* cull */", "// get rid of script tags, ungreedy", "$", "result", "=", "preg_replace", "(", "'/(?:<script[^>]*>)(.*)<\\/script>/isU'", ",", "''", ",", "$", "html", ")", ";", "// get rid of forms, ungreedy", "$", "result", "=", "preg_replace", "(", "'/(?:<form[^>]*>)(.*)<\\/form>/isU'", ",", "''", ",", "$", "result", ")", ";", "// get rid of html5 nav content, ungreedy", "$", "result", "=", "preg_replace", "(", "'/(?:<nav[^>]*>)(.*)<\\/nav>/isU'", ",", "''", ",", "$", "result", ")", ";", "// get rid of PB nav, next/previous", "$", "result", "=", "preg_replace", "(", "'/(?:<div class=\"nav\"[^>]*>)(.*)<\\/div>/isU'", ",", "''", ",", "$", "result", ")", ";", "// get rid of PB share buttons", "$", "result", "=", "preg_replace", "(", "'/(?:<div class=\"share-wrap-single\"[^>]*>)(.*)<\\/div>/isU'", ",", "''", ",", "$", "result", ")", ";", "// get rid of html5 footer content, ungreedy", "$", "result", "=", "preg_replace", "(", "'/(?:<footer[^>]*>)(.*)<\\/footer>/isU'", ",", "''", ",", "$", "result", ")", ";", "// get rid of sidebar content, greedy", "$", "result", "=", "preg_replace", "(", "'/(?:<div id=\"sidebar\\d{0,}\"[^>]*>)(.*)<\\/div>/is'", ",", "''", ",", "$", "result", ")", ";", "// get rid of comments, greedy", "$", "result", "=", "preg_replace", "(", "'/(?:<div id=\"comments\"[^>]*>)(.*)<\\/div>/is'", ",", "''", ",", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Cherry pick likely content areas, then cull known, unwanted content areas @param string $html @return string $html
[ "Cherry", "pick", "likely", "content", "areas", "then", "cull", "known", "unwanted", "content", "areas" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L227-L265
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.kneadHtml
function kneadHtml( $html, $type, $domain ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html ); // Download images, change relative paths to absolute $dom = $this->scrapeAndKneadImages( $dom, $domain ); $html = $html5->saveHTML( $dom ); return $html; }
php
function kneadHtml( $html, $type, $domain ) { $html5 = new HtmlParser(); $dom = $html5->loadHTML( $html ); // Download images, change relative paths to absolute $dom = $this->scrapeAndKneadImages( $dom, $domain ); $html = $html5->saveHTML( $dom ); return $html; }
[ "function", "kneadHtml", "(", "$", "html", ",", "$", "type", ",", "$", "domain", ")", "{", "$", "html5", "=", "new", "HtmlParser", "(", ")", ";", "$", "dom", "=", "$", "html5", "->", "loadHTML", "(", "$", "html", ")", ";", "// Download images, change relative paths to absolute", "$", "dom", "=", "$", "this", "->", "scrapeAndKneadImages", "(", "$", "dom", ",", "$", "domain", ")", ";", "$", "html", "=", "$", "html5", "->", "saveHTML", "(", "$", "dom", ")", ";", "return", "$", "html", ";", "}" ]
Pummel the HTML into WordPress compatible dough. @param string $html @param string $type front-matter, part, chapter, back-matter, ... @param string $domain domain name of the web page @return string
[ "Pummel", "the", "HTML", "into", "WordPress", "compatible", "dough", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L276-L286
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.scrapeAndKneadMeta
protected function scrapeAndKneadMeta( \DOMDocument $doc ) { $meta = []; $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $anchor ) { /** @var \DOMElement $anchor */ $license = $anchor->getAttribute( 'rel' ); $property = $anchor->getAttribute( 'property' ); // expecting to find <a href="http://creativecommons.org/licenses/by/4.0/" rel="license"> if ( 'license' === $license ) { $meta['license'] = $anchor->getAttribute( 'href' ); } // expecting to find <a rel="cc:attributionURL" property="cc:attributionName" href="http://opentextbc.ca/geography/front-matter/about-the-book/" xmlns:cc="http://creativecommons.org/ns#"> // Arthur Green, Britta Ricker, Siobhan McPhee, Aviv Ettya, Cristina Temenos</a> if ( 'cc:attributionName' === $property ) { $meta['authors'] = $anchor->nodeValue; } } return $meta; }
php
protected function scrapeAndKneadMeta( \DOMDocument $doc ) { $meta = []; $urls = $doc->getElementsByTagName( 'a' ); foreach ( $urls as $anchor ) { /** @var \DOMElement $anchor */ $license = $anchor->getAttribute( 'rel' ); $property = $anchor->getAttribute( 'property' ); // expecting to find <a href="http://creativecommons.org/licenses/by/4.0/" rel="license"> if ( 'license' === $license ) { $meta['license'] = $anchor->getAttribute( 'href' ); } // expecting to find <a rel="cc:attributionURL" property="cc:attributionName" href="http://opentextbc.ca/geography/front-matter/about-the-book/" xmlns:cc="http://creativecommons.org/ns#"> // Arthur Green, Britta Ricker, Siobhan McPhee, Aviv Ettya, Cristina Temenos</a> if ( 'cc:attributionName' === $property ) { $meta['authors'] = $anchor->nodeValue; } } return $meta; }
[ "protected", "function", "scrapeAndKneadMeta", "(", "\\", "DOMDocument", "$", "doc", ")", "{", "$", "meta", "=", "[", "]", ";", "$", "urls", "=", "$", "doc", "->", "getElementsByTagName", "(", "'a'", ")", ";", "foreach", "(", "$", "urls", "as", "$", "anchor", ")", "{", "/** @var \\DOMElement $anchor */", "$", "license", "=", "$", "anchor", "->", "getAttribute", "(", "'rel'", ")", ";", "$", "property", "=", "$", "anchor", "->", "getAttribute", "(", "'property'", ")", ";", "// expecting to find <a href=\"http://creativecommons.org/licenses/by/4.0/\" rel=\"license\">", "if", "(", "'license'", "===", "$", "license", ")", "{", "$", "meta", "[", "'license'", "]", "=", "$", "anchor", "->", "getAttribute", "(", "'href'", ")", ";", "}", "// expecting to find <a rel=\"cc:attributionURL\" property=\"cc:attributionName\" href=\"http://opentextbc.ca/geography/front-matter/about-the-book/\" xmlns:cc=\"http://creativecommons.org/ns#\">", "// Arthur Green, Britta Ricker, Siobhan McPhee, Aviv Ettya, Cristina Temenos</a>", "if", "(", "'cc:attributionName'", "===", "$", "property", ")", "{", "$", "meta", "[", "'authors'", "]", "=", "$", "anchor", "->", "nodeValue", ";", "}", "}", "return", "$", "meta", ";", "}" ]
Extracts section/book author and section/book license if they exist. Focus is given to CreativeCommons license information generated by PB @param \DOMDocument $doc @return array $meta
[ "Extracts", "section", "/", "book", "author", "and", "section", "/", "book", "license", "if", "they", "exist", ".", "Focus", "is", "given", "to", "CreativeCommons", "license", "information", "generated", "by", "PB" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L296-L319
pressbooks/pressbooks
inc/modules/import/html/class-xhtml.php
Xhtml.fetchAndSaveUniqueImage
protected function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return ''; } $remote_img_location = $url; // Cheap cache static $already_done = []; if ( isset( $already_done[ $remote_img_location ] ) ) { return $already_done[ $remote_img_location ]; } /* Process */ // Basename without query string $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); if ( ! preg_match( '/\.(jpe?g|gif|png)$/i', $filename ) ) { // Unsupported image type $already_done[ $remote_img_location ] = ''; return ''; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $already_done[ $remote_img_location ] = ''; return ''; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->properImageExtension( $tmp_name, $filename ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { throw new \Exception( 'Image is corrupt, and file extension matches the mime type' ); } } catch ( \Exception $exc ) { // Garbage, don't import $already_done[ $remote_img_location ] = ''; unlink( $tmp_name ); return ''; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $src = ''; // Change false to empty string } $already_done[ $remote_img_location ] = $src; @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $src; }
php
protected function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return ''; } $remote_img_location = $url; // Cheap cache static $already_done = []; if ( isset( $already_done[ $remote_img_location ] ) ) { return $already_done[ $remote_img_location ]; } /* Process */ // Basename without query string $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); if ( ! preg_match( '/\.(jpe?g|gif|png)$/i', $filename ) ) { // Unsupported image type $already_done[ $remote_img_location ] = ''; return ''; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $already_done[ $remote_img_location ] = ''; return ''; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->properImageExtension( $tmp_name, $filename ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { throw new \Exception( 'Image is corrupt, and file extension matches the mime type' ); } } catch ( \Exception $exc ) { // Garbage, don't import $already_done[ $remote_img_location ] = ''; unlink( $tmp_name ); return ''; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $src = ''; // Change false to empty string } $already_done[ $remote_img_location ] = $src; @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $src; }
[ "protected", "function", "fetchAndSaveUniqueImage", "(", "$", "url", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "''", ";", "}", "$", "remote_img_location", "=", "$", "url", ";", "// Cheap cache", "static", "$", "already_done", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "already_done", "[", "$", "remote_img_location", "]", ")", ")", "{", "return", "$", "already_done", "[", "$", "remote_img_location", "]", ";", "}", "/* Process */", "// Basename without query string", "$", "filename", "=", "explode", "(", "'?'", ",", "basename", "(", "$", "url", ")", ")", ";", "$", "filename", "=", "array_shift", "(", "$", "filename", ")", ";", "$", "filename", "=", "sanitize_file_name", "(", "urldecode", "(", "$", "filename", ")", ")", ";", "if", "(", "!", "preg_match", "(", "'/\\.(jpe?g|gif|png)$/i'", ",", "$", "filename", ")", ")", "{", "// Unsupported image type", "$", "already_done", "[", "$", "remote_img_location", "]", "=", "''", ";", "return", "''", ";", "}", "$", "tmp_name", "=", "download_url", "(", "$", "remote_img_location", ")", ";", "if", "(", "is_wp_error", "(", "$", "tmp_name", ")", ")", "{", "// Download failed", "$", "already_done", "[", "$", "remote_img_location", "]", "=", "''", ";", "return", "''", ";", "}", "if", "(", "!", "\\", "Pressbooks", "\\", "Image", "\\", "is_valid_image", "(", "$", "tmp_name", ",", "$", "filename", ")", ")", "{", "try", "{", "// changing the file name so that extension matches the mime type", "$", "filename", "=", "$", "this", "->", "properImageExtension", "(", "$", "tmp_name", ",", "$", "filename", ")", ";", "if", "(", "!", "\\", "Pressbooks", "\\", "Image", "\\", "is_valid_image", "(", "$", "tmp_name", ",", "$", "filename", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Image is corrupt, and file extension matches the mime type'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "exc", ")", "{", "// Garbage, don't import", "$", "already_done", "[", "$", "remote_img_location", "]", "=", "''", ";", "unlink", "(", "$", "tmp_name", ")", ";", "return", "''", ";", "}", "}", "$", "pid", "=", "media_handle_sideload", "(", "[", "'name'", "=>", "$", "filename", ",", "'tmp_name'", "=>", "$", "tmp_name", ",", "]", ",", "0", ")", ";", "$", "src", "=", "wp_get_attachment_url", "(", "$", "pid", ")", ";", "if", "(", "!", "$", "src", ")", "{", "$", "src", "=", "''", ";", "// Change false to empty string", "}", "$", "already_done", "[", "$", "remote_img_location", "]", "=", "$", "src", ";", "@", "unlink", "(", "$", "tmp_name", ")", ";", "// @codingStandardsIgnoreLine", "return", "$", "src", ";", "}" ]
Extract url and load into WP using media_handle_sideload() Will return an empty string if something went wrong. @param string $url @see media_handle_sideload @return string $src
[ "Extract", "url", "and", "load", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "an", "empty", "string", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/html/class-xhtml.php#L366-L431
pressbooks/pressbooks
inc/class-eventstreams.php
EventStreams.emit
public function emit( \Generator $generator, $auto_complete = false ) { $this->setupHeaders(); try { foreach ( $generator as $percentage => $info ) { $data = [ 'action' => 'updateStatusBar', 'percentage' => $percentage, 'info' => $info, ]; $this->emitMessage( $data ); } } catch ( \Exception $e ) { $error = [ 'action' => 'complete', 'error' => $e->getMessage(), ]; } flush(); if ( ! empty( $error ) ) { // Something went wrong $this->emitMessage( $error ); return false; } elseif ( $auto_complete ) { $this->emitComplete(); } // No errors return true; }
php
public function emit( \Generator $generator, $auto_complete = false ) { $this->setupHeaders(); try { foreach ( $generator as $percentage => $info ) { $data = [ 'action' => 'updateStatusBar', 'percentage' => $percentage, 'info' => $info, ]; $this->emitMessage( $data ); } } catch ( \Exception $e ) { $error = [ 'action' => 'complete', 'error' => $e->getMessage(), ]; } flush(); if ( ! empty( $error ) ) { // Something went wrong $this->emitMessage( $error ); return false; } elseif ( $auto_complete ) { $this->emitComplete(); } // No errors return true; }
[ "public", "function", "emit", "(", "\\", "Generator", "$", "generator", ",", "$", "auto_complete", "=", "false", ")", "{", "$", "this", "->", "setupHeaders", "(", ")", ";", "try", "{", "foreach", "(", "$", "generator", "as", "$", "percentage", "=>", "$", "info", ")", "{", "$", "data", "=", "[", "'action'", "=>", "'updateStatusBar'", ",", "'percentage'", "=>", "$", "percentage", ",", "'info'", "=>", "$", "info", ",", "]", ";", "$", "this", "->", "emitMessage", "(", "$", "data", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "error", "=", "[", "'action'", "=>", "'complete'", ",", "'error'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "]", ";", "}", "flush", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "error", ")", ")", "{", "// Something went wrong", "$", "this", "->", "emitMessage", "(", "$", "error", ")", ";", "return", "false", ";", "}", "elseif", "(", "$", "auto_complete", ")", "{", "$", "this", "->", "emitComplete", "(", ")", ";", "}", "// No errors", "return", "true", ";", "}" ]
This method accepts a generator that yields a key/value pair The key is an integer between 1-100 that represents percentage completed The value is a string of information for the user Emits event-stream responses (SSE) @param \Generator $generator @param bool $auto_complete @return bool
[ "This", "method", "accepts", "a", "generator", "that", "yields", "a", "key", "/", "value", "pair", "The", "key", "is", "an", "integer", "between", "1", "-", "100", "that", "represents", "percentage", "completed", "The", "value", "is", "a", "string", "of", "information", "for", "the", "user", "Emits", "event", "-", "stream", "responses", "(", "SSE", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-eventstreams.php#L62-L90
pressbooks/pressbooks
inc/class-eventstreams.php
EventStreams.emitMessage
private function emitMessage( $data ) { $msg = "event: message\n"; $msg .= 'data: ' . wp_json_encode( $data ) . "\n\n"; $msg .= ':' . str_repeat( ' ', 2048 ) . "\n\n"; // Buffers are nested. While one buffer is active, flushing from child buffers are not really sent to the browser, // but rather to the parent buffer. Only when there is no parent buffer are contents sent to the browser. if ( ob_get_level() ) { // Keep for later $this->msgStack[] = $msg; } else { // Flush to browser foreach ( $this->msgStack as $stack ) { echo $stack; } $this->msgStack = []; // Reset echo $msg; flush(); } }
php
private function emitMessage( $data ) { $msg = "event: message\n"; $msg .= 'data: ' . wp_json_encode( $data ) . "\n\n"; $msg .= ':' . str_repeat( ' ', 2048 ) . "\n\n"; // Buffers are nested. While one buffer is active, flushing from child buffers are not really sent to the browser, // but rather to the parent buffer. Only when there is no parent buffer are contents sent to the browser. if ( ob_get_level() ) { // Keep for later $this->msgStack[] = $msg; } else { // Flush to browser foreach ( $this->msgStack as $stack ) { echo $stack; } $this->msgStack = []; // Reset echo $msg; flush(); } }
[ "private", "function", "emitMessage", "(", "$", "data", ")", "{", "$", "msg", "=", "\"event: message\\n\"", ";", "$", "msg", ".=", "'data: '", ".", "wp_json_encode", "(", "$", "data", ")", ".", "\"\\n\\n\"", ";", "$", "msg", ".=", "':'", ".", "str_repeat", "(", "' '", ",", "2048", ")", ".", "\"\\n\\n\"", ";", "// Buffers are nested. While one buffer is active, flushing from child buffers are not really sent to the browser,", "// but rather to the parent buffer. Only when there is no parent buffer are contents sent to the browser.", "if", "(", "ob_get_level", "(", ")", ")", "{", "// Keep for later", "$", "this", "->", "msgStack", "[", "]", "=", "$", "msg", ";", "}", "else", "{", "// Flush to browser", "foreach", "(", "$", "this", "->", "msgStack", "as", "$", "stack", ")", "{", "echo", "$", "stack", ";", "}", "$", "this", "->", "msgStack", "=", "[", "]", ";", "// Reset", "echo", "$", "msg", ";", "flush", "(", ")", ";", "}", "}" ]
Emit a Server-Sent Events message. @param mixed $data Data to be JSON-encoded and sent in the message.
[ "Emit", "a", "Server", "-", "Sent", "Events", "message", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-eventstreams.php#L97-L115
pressbooks/pressbooks
inc/class-eventstreams.php
EventStreams.cloneBook
public function cloneBook() { check_admin_referer( 'pb-cloner' ); $source_url = $_GET['source_book_url'] ?? ''; $target_url = Cloner::validateNewBookName( $_GET['target_book_url'] ); if ( is_wp_error( $target_url ) ) { $this->emitOneTimeError( $target_url->get_error_message() ); return; } $target_title = $_GET['target_book_title'] ?? ''; $cloner = new Cloner( $source_url, $target_url, $target_title ); $everything_ok = $this->emit( $cloner->cloneBookGenerator() ); if ( $everything_ok ) { $cloned_items = $cloner->getClonedItems(); $notice = sprintf( __( 'Cloning succeeded! Cloned %1$s, %2$s, %3$s, %4$s, %5$s, %6$s, %7$s, and %8$s to %9$s.', 'pressbooks' ), sprintf( _n( '%s term', '%s terms', count( getset( $cloned_items, 'terms', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'terms', [] ) ) ), sprintf( _n( '%s front matter', '%s front matter', count( getset( $cloned_items, 'front-matter', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'front-matter', [] ) ) ), sprintf( _n( '%s part', '%s parts', count( getset( $cloned_items, 'parts', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'parts', [] ) ) ), sprintf( _n( '%s chapter', '%s chapters', count( getset( $cloned_items, 'chapters', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'chapters', [] ) ) ), sprintf( _n( '%s back matter', '%s back matter', count( getset( $cloned_items, 'back-matter', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'back-matter', [] ) ) ), sprintf( _n( '%s media attachment', '%s media attachments', count( getset( $cloned_items, 'media', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'media', [] ) ) ), sprintf( _n( '%s H5P element', '%s H5P elements', count( getset( $cloned_items, 'h5p', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'h5p', [] ) ) ), sprintf( _n( '%s glossary term', '%s glossary terms', count( getset( $cloned_items, 'glossary', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'glossary', [] ) ) ), sprintf( '<a href="%1$s"><em>%2$s</em></a>', trailingslashit( $cloner->getTargetBookUrl() ) . 'wp-admin/', $cloner->getTargetBookTitle() ) ); \Pressbooks\add_notice( $notice ); } // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
php
public function cloneBook() { check_admin_referer( 'pb-cloner' ); $source_url = $_GET['source_book_url'] ?? ''; $target_url = Cloner::validateNewBookName( $_GET['target_book_url'] ); if ( is_wp_error( $target_url ) ) { $this->emitOneTimeError( $target_url->get_error_message() ); return; } $target_title = $_GET['target_book_title'] ?? ''; $cloner = new Cloner( $source_url, $target_url, $target_title ); $everything_ok = $this->emit( $cloner->cloneBookGenerator() ); if ( $everything_ok ) { $cloned_items = $cloner->getClonedItems(); $notice = sprintf( __( 'Cloning succeeded! Cloned %1$s, %2$s, %3$s, %4$s, %5$s, %6$s, %7$s, and %8$s to %9$s.', 'pressbooks' ), sprintf( _n( '%s term', '%s terms', count( getset( $cloned_items, 'terms', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'terms', [] ) ) ), sprintf( _n( '%s front matter', '%s front matter', count( getset( $cloned_items, 'front-matter', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'front-matter', [] ) ) ), sprintf( _n( '%s part', '%s parts', count( getset( $cloned_items, 'parts', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'parts', [] ) ) ), sprintf( _n( '%s chapter', '%s chapters', count( getset( $cloned_items, 'chapters', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'chapters', [] ) ) ), sprintf( _n( '%s back matter', '%s back matter', count( getset( $cloned_items, 'back-matter', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'back-matter', [] ) ) ), sprintf( _n( '%s media attachment', '%s media attachments', count( getset( $cloned_items, 'media', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'media', [] ) ) ), sprintf( _n( '%s H5P element', '%s H5P elements', count( getset( $cloned_items, 'h5p', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'h5p', [] ) ) ), sprintf( _n( '%s glossary term', '%s glossary terms', count( getset( $cloned_items, 'glossary', [] ) ), 'pressbooks' ), count( getset( $cloned_items, 'glossary', [] ) ) ), sprintf( '<a href="%1$s"><em>%2$s</em></a>', trailingslashit( $cloner->getTargetBookUrl() ) . 'wp-admin/', $cloner->getTargetBookTitle() ) ); \Pressbooks\add_notice( $notice ); } // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
[ "public", "function", "cloneBook", "(", ")", "{", "check_admin_referer", "(", "'pb-cloner'", ")", ";", "$", "source_url", "=", "$", "_GET", "[", "'source_book_url'", "]", "??", "''", ";", "$", "target_url", "=", "Cloner", "::", "validateNewBookName", "(", "$", "_GET", "[", "'target_book_url'", "]", ")", ";", "if", "(", "is_wp_error", "(", "$", "target_url", ")", ")", "{", "$", "this", "->", "emitOneTimeError", "(", "$", "target_url", "->", "get_error_message", "(", ")", ")", ";", "return", ";", "}", "$", "target_title", "=", "$", "_GET", "[", "'target_book_title'", "]", "??", "''", ";", "$", "cloner", "=", "new", "Cloner", "(", "$", "source_url", ",", "$", "target_url", ",", "$", "target_title", ")", ";", "$", "everything_ok", "=", "$", "this", "->", "emit", "(", "$", "cloner", "->", "cloneBookGenerator", "(", ")", ")", ";", "if", "(", "$", "everything_ok", ")", "{", "$", "cloned_items", "=", "$", "cloner", "->", "getClonedItems", "(", ")", ";", "$", "notice", "=", "sprintf", "(", "__", "(", "'Cloning succeeded! Cloned %1$s, %2$s, %3$s, %4$s, %5$s, %6$s, %7$s, and %8$s to %9$s.'", ",", "'pressbooks'", ")", ",", "sprintf", "(", "_n", "(", "'%s term'", ",", "'%s terms'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'terms'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'terms'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s front matter'", ",", "'%s front matter'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'front-matter'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'front-matter'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s part'", ",", "'%s parts'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'parts'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'parts'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s chapter'", ",", "'%s chapters'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'chapters'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'chapters'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s back matter'", ",", "'%s back matter'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'back-matter'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'back-matter'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s media attachment'", ",", "'%s media attachments'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'media'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'media'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s H5P element'", ",", "'%s H5P elements'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'h5p'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'h5p'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "_n", "(", "'%s glossary term'", ",", "'%s glossary terms'", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'glossary'", ",", "[", "]", ")", ")", ",", "'pressbooks'", ")", ",", "count", "(", "getset", "(", "$", "cloned_items", ",", "'glossary'", ",", "[", "]", ")", ")", ")", ",", "sprintf", "(", "'<a href=\"%1$s\"><em>%2$s</em></a>'", ",", "trailingslashit", "(", "$", "cloner", "->", "getTargetBookUrl", "(", ")", ")", ".", "'wp-admin/'", ",", "$", "cloner", "->", "getTargetBookTitle", "(", ")", ")", ")", ";", "\\", "Pressbooks", "\\", "add_notice", "(", "$", "notice", ")", ";", "}", "// Tell the browser to stop reconnecting.", "$", "this", "->", "emitComplete", "(", ")", ";", "status_header", "(", "204", ")", ";", "if", "(", "!", "defined", "(", "'WP_TESTS_MULTISITE'", ")", ")", "{", "exit", ";", "// Short circuit wp_die(0);", "}", "}" ]
Clone a book
[ "Clone", "a", "book" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-eventstreams.php#L178-L218
pressbooks/pressbooks
inc/class-eventstreams.php
EventStreams.exportBook
public function exportBook() { check_admin_referer( 'pb-export' ); if ( ! is_array( getset( '_GET', 'export_formats' ) ) ) { $this->emitOneTimeError( __( 'No export format was selected.', 'pressbooks' ) ); return; } // Backwards compatibility with older plugins foreach ( $_GET['export_formats'] as $k => $v ) { $_POST['export_formats'][ $k ] = $v; } Export::preExport(); $this->emit( Export::exportGenerator( Export::modules() ) ); Export::postExport(); // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
php
public function exportBook() { check_admin_referer( 'pb-export' ); if ( ! is_array( getset( '_GET', 'export_formats' ) ) ) { $this->emitOneTimeError( __( 'No export format was selected.', 'pressbooks' ) ); return; } // Backwards compatibility with older plugins foreach ( $_GET['export_formats'] as $k => $v ) { $_POST['export_formats'][ $k ] = $v; } Export::preExport(); $this->emit( Export::exportGenerator( Export::modules() ) ); Export::postExport(); // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
[ "public", "function", "exportBook", "(", ")", "{", "check_admin_referer", "(", "'pb-export'", ")", ";", "if", "(", "!", "is_array", "(", "getset", "(", "'_GET'", ",", "'export_formats'", ")", ")", ")", "{", "$", "this", "->", "emitOneTimeError", "(", "__", "(", "'No export format was selected.'", ",", "'pressbooks'", ")", ")", ";", "return", ";", "}", "// Backwards compatibility with older plugins", "foreach", "(", "$", "_GET", "[", "'export_formats'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "_POST", "[", "'export_formats'", "]", "[", "$", "k", "]", "=", "$", "v", ";", "}", "Export", "::", "preExport", "(", ")", ";", "$", "this", "->", "emit", "(", "Export", "::", "exportGenerator", "(", "Export", "::", "modules", "(", ")", ")", ")", ";", "Export", "::", "postExport", "(", ")", ";", "// Tell the browser to stop reconnecting.", "$", "this", "->", "emitComplete", "(", ")", ";", "status_header", "(", "204", ")", ";", "if", "(", "!", "defined", "(", "'WP_TESTS_MULTISITE'", ")", ")", "{", "exit", ";", "// Short circuit wp_die(0);", "}", "}" ]
Export book
[ "Export", "book" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-eventstreams.php#L223-L247
pressbooks/pressbooks
inc/class-eventstreams.php
EventStreams.importBook
public function importBook() { check_admin_referer( 'pb-import' ); // Backwards compatibility with older plugins $at_least_one = false; foreach ( $_GET['chapters'] as $k => $v ) { $_POST['chapters'][ $k ] = $v; if ( is_array( $v ) && ! empty( $v['import'] ) ) { $at_least_one = true; } } $_POST['show_imports_in_web'] = $_GET['show_imports_in_web'] ?? 0; if ( ! $at_least_one ) { $this->emitOneTimeError( __( 'No chapters were selected for import.', 'pressbooks' ) ); return; } $current_import = get_option( 'pressbooks_current_import' ); if ( is_array( $current_import ) ) { Import::preImport(); $this->emit( Import::doImportGenerator( $current_import ) ); Import::postImport(); } // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
php
public function importBook() { check_admin_referer( 'pb-import' ); // Backwards compatibility with older plugins $at_least_one = false; foreach ( $_GET['chapters'] as $k => $v ) { $_POST['chapters'][ $k ] = $v; if ( is_array( $v ) && ! empty( $v['import'] ) ) { $at_least_one = true; } } $_POST['show_imports_in_web'] = $_GET['show_imports_in_web'] ?? 0; if ( ! $at_least_one ) { $this->emitOneTimeError( __( 'No chapters were selected for import.', 'pressbooks' ) ); return; } $current_import = get_option( 'pressbooks_current_import' ); if ( is_array( $current_import ) ) { Import::preImport(); $this->emit( Import::doImportGenerator( $current_import ) ); Import::postImport(); } // Tell the browser to stop reconnecting. $this->emitComplete(); status_header( 204 ); if ( ! defined( 'WP_TESTS_MULTISITE' ) ) { exit; // Short circuit wp_die(0); } }
[ "public", "function", "importBook", "(", ")", "{", "check_admin_referer", "(", "'pb-import'", ")", ";", "// Backwards compatibility with older plugins", "$", "at_least_one", "=", "false", ";", "foreach", "(", "$", "_GET", "[", "'chapters'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "_POST", "[", "'chapters'", "]", "[", "$", "k", "]", "=", "$", "v", ";", "if", "(", "is_array", "(", "$", "v", ")", "&&", "!", "empty", "(", "$", "v", "[", "'import'", "]", ")", ")", "{", "$", "at_least_one", "=", "true", ";", "}", "}", "$", "_POST", "[", "'show_imports_in_web'", "]", "=", "$", "_GET", "[", "'show_imports_in_web'", "]", "??", "0", ";", "if", "(", "!", "$", "at_least_one", ")", "{", "$", "this", "->", "emitOneTimeError", "(", "__", "(", "'No chapters were selected for import.'", ",", "'pressbooks'", ")", ")", ";", "return", ";", "}", "$", "current_import", "=", "get_option", "(", "'pressbooks_current_import'", ")", ";", "if", "(", "is_array", "(", "$", "current_import", ")", ")", "{", "Import", "::", "preImport", "(", ")", ";", "$", "this", "->", "emit", "(", "Import", "::", "doImportGenerator", "(", "$", "current_import", ")", ")", ";", "Import", "::", "postImport", "(", ")", ";", "}", "// Tell the browser to stop reconnecting.", "$", "this", "->", "emitComplete", "(", ")", ";", "status_header", "(", "204", ")", ";", "if", "(", "!", "defined", "(", "'WP_TESTS_MULTISITE'", ")", ")", "{", "exit", ";", "// Short circuit wp_die(0);", "}", "}" ]
Import book
[ "Import", "book" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-eventstreams.php#L252-L284
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.getIDs
protected function getIDs( \DOMDocument $dom_doc, $tag = 'footnoteReference', $attr = 'w:id' ) { $fn_ids = []; $doc_elem = $dom_doc->documentElement; $tags_fn_ref = $doc_elem->getElementsByTagName( $tag ); // if footnotes are in the document, get the ids if ( $tags_fn_ref->length > 0 ) { foreach ( $tags_fn_ref as $id ) { /** @var \DOMElement $id */ if ( '' !== $id->getAttribute( $attr ) ) { // don't add if its empty $fn_ids[] = $id->getAttribute( $attr ); } } } return $fn_ids; }
php
protected function getIDs( \DOMDocument $dom_doc, $tag = 'footnoteReference', $attr = 'w:id' ) { $fn_ids = []; $doc_elem = $dom_doc->documentElement; $tags_fn_ref = $doc_elem->getElementsByTagName( $tag ); // if footnotes are in the document, get the ids if ( $tags_fn_ref->length > 0 ) { foreach ( $tags_fn_ref as $id ) { /** @var \DOMElement $id */ if ( '' !== $id->getAttribute( $attr ) ) { // don't add if its empty $fn_ids[] = $id->getAttribute( $attr ); } } } return $fn_ids; }
[ "protected", "function", "getIDs", "(", "\\", "DOMDocument", "$", "dom_doc", ",", "$", "tag", "=", "'footnoteReference'", ",", "$", "attr", "=", "'w:id'", ")", "{", "$", "fn_ids", "=", "[", "]", ";", "$", "doc_elem", "=", "$", "dom_doc", "->", "documentElement", ";", "$", "tags_fn_ref", "=", "$", "doc_elem", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "// if footnotes are in the document, get the ids", "if", "(", "$", "tags_fn_ref", "->", "length", ">", "0", ")", "{", "foreach", "(", "$", "tags_fn_ref", "as", "$", "id", ")", "{", "/** @var \\DOMElement $id */", "if", "(", "''", "!==", "$", "id", "->", "getAttribute", "(", "$", "attr", ")", ")", "{", "// don't add if its empty", "$", "fn_ids", "[", "]", "=", "$", "id", "->", "getAttribute", "(", "$", "attr", ")", ";", "}", "}", "}", "return", "$", "fn_ids", ";", "}" ]
Given a documentElement, it will return an array of ids @param \DOMDocument $dom_doc @param string $tag @param string $attr @return array
[ "Given", "a", "documentElement", "it", "will", "return", "an", "array", "of", "ids" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L168-L185
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.getRelationshipPart
protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { $footnotes = []; $tag_name = rtrim( $tag, 's' ); // get the path for the footnotes switch ( $tag ) { case 'endnotes': $target_path = $this->getTargetPath( self::ENDNOTES_SCHEMA, $tag ); break; case 'hyperlink': $target_path = $this->getTargetPath( self::HYPERLINK_SCHEMA, $tag ); break; default: $target_path = $this->getTargetPath( self::FOOTNOTES_SCHEMA, $tag ); break; } // safety — if there are no footnotes, return if ( empty( $target_path ) ) { return false; } // if they are hyperlinks if ( is_array( $target_path ) ) { return $target_path; } $limit = count( $ids ); // set it up $dom_doc = $this->getZipContent( $target_path ); $doc_elem = $dom_doc->documentElement; // grab all the footnotes $text_tags = $doc_elem->getElementsByTagName( $tag_name ); // TODO // could be more sophisticated if ( $text_tags->length !== $limit + 2 ) { throw new \Exception( 'mismatch between length of FootnoteReference array number of footnotes available' ); } // get all the footnote ids // +2 to the domlist skips over two default nodes that don't contain end/footnotes for ( $i = 0; $i < $limit; $i++ ) { $footnotes[ $ids[ $i ] ] = $text_tags->item( $i + 2 )->nodeValue; } return $footnotes; }
php
protected function getRelationshipPart( array $ids, $tag = 'footnotes' ) { $footnotes = []; $tag_name = rtrim( $tag, 's' ); // get the path for the footnotes switch ( $tag ) { case 'endnotes': $target_path = $this->getTargetPath( self::ENDNOTES_SCHEMA, $tag ); break; case 'hyperlink': $target_path = $this->getTargetPath( self::HYPERLINK_SCHEMA, $tag ); break; default: $target_path = $this->getTargetPath( self::FOOTNOTES_SCHEMA, $tag ); break; } // safety — if there are no footnotes, return if ( empty( $target_path ) ) { return false; } // if they are hyperlinks if ( is_array( $target_path ) ) { return $target_path; } $limit = count( $ids ); // set it up $dom_doc = $this->getZipContent( $target_path ); $doc_elem = $dom_doc->documentElement; // grab all the footnotes $text_tags = $doc_elem->getElementsByTagName( $tag_name ); // TODO // could be more sophisticated if ( $text_tags->length !== $limit + 2 ) { throw new \Exception( 'mismatch between length of FootnoteReference array number of footnotes available' ); } // get all the footnote ids // +2 to the domlist skips over two default nodes that don't contain end/footnotes for ( $i = 0; $i < $limit; $i++ ) { $footnotes[ $ids[ $i ] ] = $text_tags->item( $i + 2 )->nodeValue; } return $footnotes; }
[ "protected", "function", "getRelationshipPart", "(", "array", "$", "ids", ",", "$", "tag", "=", "'footnotes'", ")", "{", "$", "footnotes", "=", "[", "]", ";", "$", "tag_name", "=", "rtrim", "(", "$", "tag", ",", "'s'", ")", ";", "// get the path for the footnotes", "switch", "(", "$", "tag", ")", "{", "case", "'endnotes'", ":", "$", "target_path", "=", "$", "this", "->", "getTargetPath", "(", "self", "::", "ENDNOTES_SCHEMA", ",", "$", "tag", ")", ";", "break", ";", "case", "'hyperlink'", ":", "$", "target_path", "=", "$", "this", "->", "getTargetPath", "(", "self", "::", "HYPERLINK_SCHEMA", ",", "$", "tag", ")", ";", "break", ";", "default", ":", "$", "target_path", "=", "$", "this", "->", "getTargetPath", "(", "self", "::", "FOOTNOTES_SCHEMA", ",", "$", "tag", ")", ";", "break", ";", "}", "// safety — if there are no footnotes, return", "if", "(", "empty", "(", "$", "target_path", ")", ")", "{", "return", "false", ";", "}", "// if they are hyperlinks", "if", "(", "is_array", "(", "$", "target_path", ")", ")", "{", "return", "$", "target_path", ";", "}", "$", "limit", "=", "count", "(", "$", "ids", ")", ";", "// set it up", "$", "dom_doc", "=", "$", "this", "->", "getZipContent", "(", "$", "target_path", ")", ";", "$", "doc_elem", "=", "$", "dom_doc", "->", "documentElement", ";", "// grab all the footnotes", "$", "text_tags", "=", "$", "doc_elem", "->", "getElementsByTagName", "(", "$", "tag_name", ")", ";", "// TODO", "// could be more sophisticated", "if", "(", "$", "text_tags", "->", "length", "!==", "$", "limit", "+", "2", ")", "{", "throw", "new", "\\", "Exception", "(", "'mismatch between length of FootnoteReference array number of footnotes available'", ")", ";", "}", "// get all the footnote ids", "// +2 to the domlist skips over two default nodes that don't contain end/footnotes", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "limit", ";", "$", "i", "++", ")", "{", "$", "footnotes", "[", "$", "ids", "[", "$", "i", "]", "]", "=", "$", "text_tags", "->", "item", "(", "$", "i", "+", "2", ")", "->", "nodeValue", ";", "}", "return", "$", "footnotes", ";", "}" ]
Give this some ids and it returns an associative array of footnotes @param array $ids @param string $tag @return array|bool @throws \Exception if there is discrepancy between the number of footnotes in document.xml and footnotes.xml
[ "Give", "this", "some", "ids", "and", "it", "returns", "an", "associative", "array", "of", "footnotes" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L196-L246
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.fetchAndSaveUniqueImage
protected function fetchAndSaveUniqueImage( $img_id ) { // Cheap cache static $already_done = []; if ( isset( $already_done[ $img_id ] ) ) { return $already_done[ $img_id ]; } /* Process */ // Get target path $img_location = $this->getTargetPath( self::IMAGE_SCHEMA, $img_id ); // Basename without query string $filename = explode( '?', basename( $img_location ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); if ( ! preg_match( '/\.(jpe?g|gif|png)$/i', $filename ) ) { // Unsupported image type $already_done[ $img_id ] = ''; return ''; } $image_content = $this->getZipContent( $img_location, false ); if ( ! $image_content ) { // try a different directory in the zip container try { $alt_img_location = 'word/' . $img_location; $image_content = $this->getZipContent( $alt_img_location, false ); if ( ! $image_content ) { throw new \Exception( 'Image could not be retrieved in the DOCX file with Pressbooks\Import\Ooxml\fetchAndSaveUniqueImage()' ); } } catch ( \Exception $exc ) { $this->log( $exc->getMessage() ); $already_done[ $img_location ] = ''; return ''; } } $tmp_name = $this->createTmpFile(); \Pressbooks\Utility\put_contents( $tmp_name, $image_content ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->properImageExtension( $tmp_name, $filename ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { throw new \Exception( 'Image is corrupt, and file extension matches the mime type' ); } } catch ( \Exception $exc ) { // Garbage, Don't import $already_done[ $img_location ] = ''; return ''; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $src = ''; // Change false to empty string } $already_done[ $img_location ] = $src; return $src; }
php
protected function fetchAndSaveUniqueImage( $img_id ) { // Cheap cache static $already_done = []; if ( isset( $already_done[ $img_id ] ) ) { return $already_done[ $img_id ]; } /* Process */ // Get target path $img_location = $this->getTargetPath( self::IMAGE_SCHEMA, $img_id ); // Basename without query string $filename = explode( '?', basename( $img_location ) ); $filename = array_shift( $filename ); $filename = sanitize_file_name( urldecode( $filename ) ); if ( ! preg_match( '/\.(jpe?g|gif|png)$/i', $filename ) ) { // Unsupported image type $already_done[ $img_id ] = ''; return ''; } $image_content = $this->getZipContent( $img_location, false ); if ( ! $image_content ) { // try a different directory in the zip container try { $alt_img_location = 'word/' . $img_location; $image_content = $this->getZipContent( $alt_img_location, false ); if ( ! $image_content ) { throw new \Exception( 'Image could not be retrieved in the DOCX file with Pressbooks\Import\Ooxml\fetchAndSaveUniqueImage()' ); } } catch ( \Exception $exc ) { $this->log( $exc->getMessage() ); $already_done[ $img_location ] = ''; return ''; } } $tmp_name = $this->createTmpFile(); \Pressbooks\Utility\put_contents( $tmp_name, $image_content ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->properImageExtension( $tmp_name, $filename ); if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { throw new \Exception( 'Image is corrupt, and file extension matches the mime type' ); } } catch ( \Exception $exc ) { // Garbage, Don't import $already_done[ $img_location ] = ''; return ''; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $src = ''; // Change false to empty string } $already_done[ $img_location ] = $src; return $src; }
[ "protected", "function", "fetchAndSaveUniqueImage", "(", "$", "img_id", ")", "{", "// Cheap cache", "static", "$", "already_done", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "already_done", "[", "$", "img_id", "]", ")", ")", "{", "return", "$", "already_done", "[", "$", "img_id", "]", ";", "}", "/* Process */", "// Get target path", "$", "img_location", "=", "$", "this", "->", "getTargetPath", "(", "self", "::", "IMAGE_SCHEMA", ",", "$", "img_id", ")", ";", "// Basename without query string", "$", "filename", "=", "explode", "(", "'?'", ",", "basename", "(", "$", "img_location", ")", ")", ";", "$", "filename", "=", "array_shift", "(", "$", "filename", ")", ";", "$", "filename", "=", "sanitize_file_name", "(", "urldecode", "(", "$", "filename", ")", ")", ";", "if", "(", "!", "preg_match", "(", "'/\\.(jpe?g|gif|png)$/i'", ",", "$", "filename", ")", ")", "{", "// Unsupported image type", "$", "already_done", "[", "$", "img_id", "]", "=", "''", ";", "return", "''", ";", "}", "$", "image_content", "=", "$", "this", "->", "getZipContent", "(", "$", "img_location", ",", "false", ")", ";", "if", "(", "!", "$", "image_content", ")", "{", "// try a different directory in the zip container", "try", "{", "$", "alt_img_location", "=", "'word/'", ".", "$", "img_location", ";", "$", "image_content", "=", "$", "this", "->", "getZipContent", "(", "$", "alt_img_location", ",", "false", ")", ";", "if", "(", "!", "$", "image_content", ")", "{", "throw", "new", "\\", "Exception", "(", "'Image could not be retrieved in the DOCX file with Pressbooks\\Import\\Ooxml\\fetchAndSaveUniqueImage()'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "exc", ")", "{", "$", "this", "->", "log", "(", "$", "exc", "->", "getMessage", "(", ")", ")", ";", "$", "already_done", "[", "$", "img_location", "]", "=", "''", ";", "return", "''", ";", "}", "}", "$", "tmp_name", "=", "$", "this", "->", "createTmpFile", "(", ")", ";", "\\", "Pressbooks", "\\", "Utility", "\\", "put_contents", "(", "$", "tmp_name", ",", "$", "image_content", ")", ";", "if", "(", "!", "\\", "Pressbooks", "\\", "Image", "\\", "is_valid_image", "(", "$", "tmp_name", ",", "$", "filename", ")", ")", "{", "try", "{", "// changing the file name so that extension matches the mime type", "$", "filename", "=", "$", "this", "->", "properImageExtension", "(", "$", "tmp_name", ",", "$", "filename", ")", ";", "if", "(", "!", "\\", "Pressbooks", "\\", "Image", "\\", "is_valid_image", "(", "$", "tmp_name", ",", "$", "filename", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Image is corrupt, and file extension matches the mime type'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "exc", ")", "{", "// Garbage, Don't import", "$", "already_done", "[", "$", "img_location", "]", "=", "''", ";", "return", "''", ";", "}", "}", "$", "pid", "=", "media_handle_sideload", "(", "[", "'name'", "=>", "$", "filename", ",", "'tmp_name'", "=>", "$", "tmp_name", ",", "]", ",", "0", ")", ";", "$", "src", "=", "wp_get_attachment_url", "(", "$", "pid", ")", ";", "if", "(", "!", "$", "src", ")", "{", "$", "src", "=", "''", ";", "// Change false to empty string", "}", "$", "already_done", "[", "$", "img_location", "]", "=", "$", "src", ";", "return", "$", "src", ";", "}" ]
Extract url from zip and load into WP using media_handle_sideload() Will return an empty string if something went wrong. @param string $img_id @return string
[ "Extract", "url", "from", "zip", "and", "load", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "an", "empty", "string", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L344-L420
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.addHyperlinks
protected function addHyperlinks( \DOMDocument $chapter ) { $ln = $chapter->getElementsByTagName( 'a' ); for ( $i = $ln->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $link = $ln->item( $i ); if ( $link->hasAttribute( 'name' ) && in_array( $link->getAttribute( 'name' ), [ '_GoBack' ], true ) ) { // Delete hidden Shift+F5 editing bookmark $link->parentNode->removeChild( $link ); continue; } if ( $link->hasAttribute( 'class' ) ) { $ln_id = $link->getAttribute( 'class' ); if ( array_key_exists( $ln_id, $this->ln ) ) { // Add external hyperlink $link->setAttribute( 'href', $this->ln[ $ln_id ] ); } } } return $chapter; }
php
protected function addHyperlinks( \DOMDocument $chapter ) { $ln = $chapter->getElementsByTagName( 'a' ); for ( $i = $ln->length; --$i >= 0; ) { // If you're deleting elements from within a loop, you need to loop backwards $link = $ln->item( $i ); if ( $link->hasAttribute( 'name' ) && in_array( $link->getAttribute( 'name' ), [ '_GoBack' ], true ) ) { // Delete hidden Shift+F5 editing bookmark $link->parentNode->removeChild( $link ); continue; } if ( $link->hasAttribute( 'class' ) ) { $ln_id = $link->getAttribute( 'class' ); if ( array_key_exists( $ln_id, $this->ln ) ) { // Add external hyperlink $link->setAttribute( 'href', $this->ln[ $ln_id ] ); } } } return $chapter; }
[ "protected", "function", "addHyperlinks", "(", "\\", "DOMDocument", "$", "chapter", ")", "{", "$", "ln", "=", "$", "chapter", "->", "getElementsByTagName", "(", "'a'", ")", ";", "for", "(", "$", "i", "=", "$", "ln", "->", "length", ";", "--", "$", "i", ">=", "0", ";", ")", "{", "// If you're deleting elements from within a loop, you need to loop backwards", "$", "link", "=", "$", "ln", "->", "item", "(", "$", "i", ")", ";", "if", "(", "$", "link", "->", "hasAttribute", "(", "'name'", ")", "&&", "in_array", "(", "$", "link", "->", "getAttribute", "(", "'name'", ")", ",", "[", "'_GoBack'", "]", ",", "true", ")", ")", "{", "// Delete hidden Shift+F5 editing bookmark", "$", "link", "->", "parentNode", "->", "removeChild", "(", "$", "link", ")", ";", "continue", ";", "}", "if", "(", "$", "link", "->", "hasAttribute", "(", "'class'", ")", ")", "{", "$", "ln_id", "=", "$", "link", "->", "getAttribute", "(", "'class'", ")", ";", "if", "(", "array_key_exists", "(", "$", "ln_id", ",", "$", "this", "->", "ln", ")", ")", "{", "// Add external hyperlink", "$", "link", "->", "setAttribute", "(", "'href'", ",", "$", "this", "->", "ln", "[", "$", "ln_id", "]", ")", ";", "}", "}", "}", "return", "$", "chapter", ";", "}" ]
adds external hyperlinks, if they are present in a chapter @param \DOMDocument $chapter @return \DOMDocument
[ "adds", "external", "hyperlinks", "if", "they", "are", "present", "in", "a", "chapter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L522-L545
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.addFootnotes
protected function addFootnotes( \DOMDocument $chapter ) { $fn_candidates = $chapter->getelementsByTagName( 'a' ); $fn_ids = []; foreach ( $fn_candidates as $fn_candidate ) { /** @var \DOMElement $fn_candidate */ $href = $fn_candidate->getAttribute( 'href' ); if ( ! empty( $href ) ) { $fn_matches = null; if ( preg_match( self::FOOTNOTE_HREF_PATTERN, $href, $fn_matches ) ) { $fn_ids[] = $fn_matches[1]; } } } // TODO either/or is not sufficient, needs to be built to // cover a use case where both are present. $notes = []; if ( ! empty( $this->fn ) ) { $notes = $this->fn; } if ( ! empty( $this->en ) ) { $notes = $this->en; } foreach ( $fn_ids as $id ) { if ( array_key_exists( $id, $notes ) ) { $grandparent = $chapter->createElement( 'div' ); $grandparent->setAttribute( 'id', "sdfootnote{$id}sym" ); $parent = $chapter->createElement( 'span' ); $child = $chapter->createElement( 'a', $id ); $child->setAttribute( 'href', "#sdfootnote{$id}anc" ); $child->setAttribute( 'name', "sdfootnote{$id}sym" ); $text = $chapter->createTextNode( $notes[ $id ] ); // attach $grandparent->appendChild( $parent ); $parent->appendChild( $child ); $parent->appendChild( $text ); $chapter->documentElement->appendChild( $grandparent ); } } return $chapter; }
php
protected function addFootnotes( \DOMDocument $chapter ) { $fn_candidates = $chapter->getelementsByTagName( 'a' ); $fn_ids = []; foreach ( $fn_candidates as $fn_candidate ) { /** @var \DOMElement $fn_candidate */ $href = $fn_candidate->getAttribute( 'href' ); if ( ! empty( $href ) ) { $fn_matches = null; if ( preg_match( self::FOOTNOTE_HREF_PATTERN, $href, $fn_matches ) ) { $fn_ids[] = $fn_matches[1]; } } } // TODO either/or is not sufficient, needs to be built to // cover a use case where both are present. $notes = []; if ( ! empty( $this->fn ) ) { $notes = $this->fn; } if ( ! empty( $this->en ) ) { $notes = $this->en; } foreach ( $fn_ids as $id ) { if ( array_key_exists( $id, $notes ) ) { $grandparent = $chapter->createElement( 'div' ); $grandparent->setAttribute( 'id', "sdfootnote{$id}sym" ); $parent = $chapter->createElement( 'span' ); $child = $chapter->createElement( 'a', $id ); $child->setAttribute( 'href', "#sdfootnote{$id}anc" ); $child->setAttribute( 'name', "sdfootnote{$id}sym" ); $text = $chapter->createTextNode( $notes[ $id ] ); // attach $grandparent->appendChild( $parent ); $parent->appendChild( $child ); $parent->appendChild( $text ); $chapter->documentElement->appendChild( $grandparent ); } } return $chapter; }
[ "protected", "function", "addFootnotes", "(", "\\", "DOMDocument", "$", "chapter", ")", "{", "$", "fn_candidates", "=", "$", "chapter", "->", "getelementsByTagName", "(", "'a'", ")", ";", "$", "fn_ids", "=", "[", "]", ";", "foreach", "(", "$", "fn_candidates", "as", "$", "fn_candidate", ")", "{", "/** @var \\DOMElement $fn_candidate */", "$", "href", "=", "$", "fn_candidate", "->", "getAttribute", "(", "'href'", ")", ";", "if", "(", "!", "empty", "(", "$", "href", ")", ")", "{", "$", "fn_matches", "=", "null", ";", "if", "(", "preg_match", "(", "self", "::", "FOOTNOTE_HREF_PATTERN", ",", "$", "href", ",", "$", "fn_matches", ")", ")", "{", "$", "fn_ids", "[", "]", "=", "$", "fn_matches", "[", "1", "]", ";", "}", "}", "}", "// TODO either/or is not sufficient, needs to be built to", "// cover a use case where both are present.", "$", "notes", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "fn", ")", ")", "{", "$", "notes", "=", "$", "this", "->", "fn", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "en", ")", ")", "{", "$", "notes", "=", "$", "this", "->", "en", ";", "}", "foreach", "(", "$", "fn_ids", "as", "$", "id", ")", "{", "if", "(", "array_key_exists", "(", "$", "id", ",", "$", "notes", ")", ")", "{", "$", "grandparent", "=", "$", "chapter", "->", "createElement", "(", "'div'", ")", ";", "$", "grandparent", "->", "setAttribute", "(", "'id'", ",", "\"sdfootnote{$id}sym\"", ")", ";", "$", "parent", "=", "$", "chapter", "->", "createElement", "(", "'span'", ")", ";", "$", "child", "=", "$", "chapter", "->", "createElement", "(", "'a'", ",", "$", "id", ")", ";", "$", "child", "->", "setAttribute", "(", "'href'", ",", "\"#sdfootnote{$id}anc\"", ")", ";", "$", "child", "->", "setAttribute", "(", "'name'", ",", "\"sdfootnote{$id}sym\"", ")", ";", "$", "text", "=", "$", "chapter", "->", "createTextNode", "(", "$", "notes", "[", "$", "id", "]", ")", ";", "// attach", "$", "grandparent", "->", "appendChild", "(", "$", "parent", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "child", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "text", ")", ";", "$", "chapter", "->", "documentElement", "->", "appendChild", "(", "$", "grandparent", ")", ";", "}", "}", "return", "$", "chapter", ";", "}" ]
adds footnotes, if they are present in the chapter @param \DOMDocument $chapter @return \DOMDocument
[ "adds", "footnotes", "if", "they", "are", "present", "in", "the", "chapter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L554-L598
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.findTheNode
protected function findTheNode( \DOMNode $node, $chapter_name ) { if ( XML_ELEMENT_NODE !== $node->nodeType ) { return ''; } $current_tag = $node->tagName; $current_value = trim( $node->nodeValue ); if ( $chapter_name === $current_value && $this->tag === $current_tag ) { return $node; } // test if ( $node->hasChildNodes() ) { $node_list = $node->childNodes; for ( $i = 0; $i < $node_list->length; $i++ ) { if ( $node_list->item( $i )->nodeType !== XML_ELEMENT_NODE ) { continue; } if ( $chapter_name !== $node_list->item( $i )->nodeValue && $this->tag !== $node_list->item( $i )->tagName ) { // recursive return $this->findTheNode( $node_list->item( $i ), $chapter_name ); } } } return ''; }
php
protected function findTheNode( \DOMNode $node, $chapter_name ) { if ( XML_ELEMENT_NODE !== $node->nodeType ) { return ''; } $current_tag = $node->tagName; $current_value = trim( $node->nodeValue ); if ( $chapter_name === $current_value && $this->tag === $current_tag ) { return $node; } // test if ( $node->hasChildNodes() ) { $node_list = $node->childNodes; for ( $i = 0; $i < $node_list->length; $i++ ) { if ( $node_list->item( $i )->nodeType !== XML_ELEMENT_NODE ) { continue; } if ( $chapter_name !== $node_list->item( $i )->nodeValue && $this->tag !== $node_list->item( $i )->tagName ) { // recursive return $this->findTheNode( $node_list->item( $i ), $chapter_name ); } } } return ''; }
[ "protected", "function", "findTheNode", "(", "\\", "DOMNode", "$", "node", ",", "$", "chapter_name", ")", "{", "if", "(", "XML_ELEMENT_NODE", "!==", "$", "node", "->", "nodeType", ")", "{", "return", "''", ";", "}", "$", "current_tag", "=", "$", "node", "->", "tagName", ";", "$", "current_value", "=", "trim", "(", "$", "node", "->", "nodeValue", ")", ";", "if", "(", "$", "chapter_name", "===", "$", "current_value", "&&", "$", "this", "->", "tag", "===", "$", "current_tag", ")", "{", "return", "$", "node", ";", "}", "// test", "if", "(", "$", "node", "->", "hasChildNodes", "(", ")", ")", "{", "$", "node_list", "=", "$", "node", "->", "childNodes", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "node_list", "->", "length", ";", "$", "i", "++", ")", "{", "if", "(", "$", "node_list", "->", "item", "(", "$", "i", ")", "->", "nodeType", "!==", "XML_ELEMENT_NODE", ")", "{", "continue", ";", "}", "if", "(", "$", "chapter_name", "!==", "$", "node_list", "->", "item", "(", "$", "i", ")", "->", "nodeValue", "&&", "$", "this", "->", "tag", "!==", "$", "node_list", "->", "item", "(", "$", "i", ")", "->", "tagName", ")", "{", "// recursive", "return", "$", "this", "->", "findTheNode", "(", "$", "node_list", "->", "item", "(", "$", "i", ")", ",", "$", "chapter_name", ")", ";", "}", "}", "}", "return", "''", ";", "}" ]
Recursive iterator to locate and return a specific node, targeting child nodes @param \DOMNode $node @param string $chapter_name @return \DOMNode|mixed
[ "Recursive", "iterator", "to", "locate", "and", "return", "a", "specific", "node", "targeting", "child", "nodes" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L608-L638
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.isValidZip
protected function isValidZip( $fullpath ) { $result = $this->zip->open( $fullpath ); if ( true !== $result ) { throw new \Exception( 'Opening docx file failed' ); } // check if a document.xml exists $path = $this->getTargetPath( self::DOCUMENT_SCHEMA ); $ok = $this->getZipContent( $path ); if ( ! $ok ) { throw new \Exception( 'Bad or corrupted _rels/.rels' ); } }
php
protected function isValidZip( $fullpath ) { $result = $this->zip->open( $fullpath ); if ( true !== $result ) { throw new \Exception( 'Opening docx file failed' ); } // check if a document.xml exists $path = $this->getTargetPath( self::DOCUMENT_SCHEMA ); $ok = $this->getZipContent( $path ); if ( ! $ok ) { throw new \Exception( 'Bad or corrupted _rels/.rels' ); } }
[ "protected", "function", "isValidZip", "(", "$", "fullpath", ")", "{", "$", "result", "=", "$", "this", "->", "zip", "->", "open", "(", "$", "fullpath", ")", ";", "if", "(", "true", "!==", "$", "result", ")", "{", "throw", "new", "\\", "Exception", "(", "'Opening docx file failed'", ")", ";", "}", "// check if a document.xml exists", "$", "path", "=", "$", "this", "->", "getTargetPath", "(", "self", "::", "DOCUMENT_SCHEMA", ")", ";", "$", "ok", "=", "$", "this", "->", "getZipContent", "(", "$", "path", ")", ";", "if", "(", "!", "$", "ok", ")", "{", "throw", "new", "\\", "Exception", "(", "'Bad or corrupted _rels/.rels'", ")", ";", "}", "}" ]
Checks for standard DOCX file structure @param string $fullpath @throws \Exception
[ "Checks", "for", "standard", "DOCX", "file", "structure" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L724-L739
pressbooks/pressbooks
inc/modules/import/ooxml/class-docx.php
Docx.getTargetPath
protected function getTargetPath( $schema, $id = '' ) { // The subfolder name "_rels", the file extension ".rels" are // reserved names in an OPC package if ( empty( $id ) ) { $path_to_rel_doc = '_rels/.rels'; } else { $path_to_rel_doc = 'word/_rels/document.xml.rels'; } $relations = simplexml_load_string( $this->zip->getFromName( $path_to_rel_doc ) ); $path = ( $id === 'hyperlink' ) ? [] : ''; foreach ( $relations->Relationship as $rel ) { // must be cast as a string to avoid returning SimpleXml Object. $rel_type = (string) $rel['Type']; $rel_id = (string) $rel['Id']; $rel_target = (string) $rel['Target']; if ( $rel_type === $schema ) { switch ( (string) $id ) { // Array case 'hyperlink': $path[ $rel_id ] = $rel_target; break; // String case 'footnotes': case 'endnotes': case '_styles': $path = 'word/' . $rel_target; break; default: if ( $rel_type === self::IMAGE_SCHEMA ) { if ( $id === $rel_id ) { $path = $rel_target; break 2; // Unique id was found, break out of foreach } } else { $path = $rel_target; } break; } } } return $path; }
php
protected function getTargetPath( $schema, $id = '' ) { // The subfolder name "_rels", the file extension ".rels" are // reserved names in an OPC package if ( empty( $id ) ) { $path_to_rel_doc = '_rels/.rels'; } else { $path_to_rel_doc = 'word/_rels/document.xml.rels'; } $relations = simplexml_load_string( $this->zip->getFromName( $path_to_rel_doc ) ); $path = ( $id === 'hyperlink' ) ? [] : ''; foreach ( $relations->Relationship as $rel ) { // must be cast as a string to avoid returning SimpleXml Object. $rel_type = (string) $rel['Type']; $rel_id = (string) $rel['Id']; $rel_target = (string) $rel['Target']; if ( $rel_type === $schema ) { switch ( (string) $id ) { // Array case 'hyperlink': $path[ $rel_id ] = $rel_target; break; // String case 'footnotes': case 'endnotes': case '_styles': $path = 'word/' . $rel_target; break; default: if ( $rel_type === self::IMAGE_SCHEMA ) { if ( $id === $rel_id ) { $path = $rel_target; break 2; // Unique id was found, break out of foreach } } else { $path = $rel_target; } break; } } } return $path; }
[ "protected", "function", "getTargetPath", "(", "$", "schema", ",", "$", "id", "=", "''", ")", "{", "// The subfolder name \"_rels\", the file extension \".rels\" are", "// reserved names in an OPC package", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "$", "path_to_rel_doc", "=", "'_rels/.rels'", ";", "}", "else", "{", "$", "path_to_rel_doc", "=", "'word/_rels/document.xml.rels'", ";", "}", "$", "relations", "=", "simplexml_load_string", "(", "$", "this", "->", "zip", "->", "getFromName", "(", "$", "path_to_rel_doc", ")", ")", ";", "$", "path", "=", "(", "$", "id", "===", "'hyperlink'", ")", "?", "[", "]", ":", "''", ";", "foreach", "(", "$", "relations", "->", "Relationship", "as", "$", "rel", ")", "{", "// must be cast as a string to avoid returning SimpleXml Object.", "$", "rel_type", "=", "(", "string", ")", "$", "rel", "[", "'Type'", "]", ";", "$", "rel_id", "=", "(", "string", ")", "$", "rel", "[", "'Id'", "]", ";", "$", "rel_target", "=", "(", "string", ")", "$", "rel", "[", "'Target'", "]", ";", "if", "(", "$", "rel_type", "===", "$", "schema", ")", "{", "switch", "(", "(", "string", ")", "$", "id", ")", "{", "// Array", "case", "'hyperlink'", ":", "$", "path", "[", "$", "rel_id", "]", "=", "$", "rel_target", ";", "break", ";", "// String", "case", "'footnotes'", ":", "case", "'endnotes'", ":", "case", "'_styles'", ":", "$", "path", "=", "'word/'", ".", "$", "rel_target", ";", "break", ";", "default", ":", "if", "(", "$", "rel_type", "===", "self", "::", "IMAGE_SCHEMA", ")", "{", "if", "(", "$", "id", "===", "$", "rel_id", ")", "{", "$", "path", "=", "$", "rel_target", ";", "break", "2", ";", "// Unique id was found, break out of foreach", "}", "}", "else", "{", "$", "path", "=", "$", "rel_target", ";", "}", "break", ";", "}", "}", "}", "return", "$", "path", ";", "}" ]
Give it a schema, get back a path(s) that points to a resource @param string $schema @param string $id @return string|array
[ "Give", "it", "a", "schema", "get", "back", "a", "path", "(", "s", ")", "that", "points", "to", "a", "resource" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/ooxml/class-docx.php#L749-L795
pressbooks/pressbooks
inc/api/endpoints/controller/class-posts.php
Posts.overrideUsingFilterAndActions
protected function overrideUsingFilterAndActions() { // The post type must have custom-fields support otherwise the meta fields will not appear in the REST API. add_post_type_support( $this->post_type, 'custom-fields' ); add_filter( "rest_{$this->post_type}_query", [ $this, 'overrideQueryArgs' ] ); add_filter( "rest_prepare_{$this->post_type}", [ $this, 'overrideResponse' ], 10, 3 ); add_filter( "rest_{$this->post_type}_trashable", [ $this, 'overrideTrashable' ], 10, 2 ); }
php
protected function overrideUsingFilterAndActions() { // The post type must have custom-fields support otherwise the meta fields will not appear in the REST API. add_post_type_support( $this->post_type, 'custom-fields' ); add_filter( "rest_{$this->post_type}_query", [ $this, 'overrideQueryArgs' ] ); add_filter( "rest_prepare_{$this->post_type}", [ $this, 'overrideResponse' ], 10, 3 ); add_filter( "rest_{$this->post_type}_trashable", [ $this, 'overrideTrashable' ], 10, 2 ); }
[ "protected", "function", "overrideUsingFilterAndActions", "(", ")", "{", "// The post type must have custom-fields support otherwise the meta fields will not appear in the REST API.", "add_post_type_support", "(", "$", "this", "->", "post_type", ",", "'custom-fields'", ")", ";", "add_filter", "(", "\"rest_{$this->post_type}_query\"", ",", "[", "$", "this", ",", "'overrideQueryArgs'", "]", ")", ";", "add_filter", "(", "\"rest_prepare_{$this->post_type}\"", ",", "[", "$", "this", ",", "'overrideResponse'", "]", ",", "10", ",", "3", ")", ";", "add_filter", "(", "\"rest_{$this->post_type}_trashable\"", ",", "[", "$", "this", ",", "'overrideTrashable'", "]", ",", "10", ",", "2", ")", ";", "}" ]
Use object inheritance as little as possible to future-proof against WP API changes With the exception of the abstract \WP_REST_Controller class, the WordPress API documentation strongly suggests not overriding controllers. Instead we are encouraged to create an entirely separate controller class for each end point. Hooks, actions, and `register_rest_field` are fair game. @see https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/#overview-the-future
[ "Use", "object", "inheritance", "as", "little", "as", "possible", "to", "future", "-", "proof", "against", "WP", "API", "changes" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-posts.php#L28-L36
pressbooks/pressbooks
inc/api/endpoints/controller/class-posts.php
Posts.overrideResponse
public function overrideResponse( $response, $post, $request ) { if ( $post->post_type === 'chapter' ) { // Add rest link to associated part $response->add_link( 'part', trailingslashit( rest_url( sprintf( '%s/%s', $this->namespace, 'parts' ) ) ) . $post->post_parent ); } if ( in_array( $post->post_type, [ 'front-matter', 'chapter', 'back-matter', 'glossary' ], true ) ) { // Add rest link to metadata $response->add_link( 'metadata', trailingslashit( rest_url( sprintf( '%s/%s/%d/metadata', $this->namespace, $this->rest_base, $post->ID ) ) ) ); } // Check that we are in view/embed context (and) // Check that content is password protected (and) // Check that content is empty (if not then API has already verified that the user can_access_password_content) if ( in_array( $request['context'], [ 'view', 'embed' ], true ) ) { if ( ! empty( $response->data['content'] ) ) { if ( $response->data['content']['protected'] && empty( $response->data['content']['rendered'] ) ) { // Hide raw data $response->data['content']['raw'] = ''; } } if ( ! empty( $response->data['excerpt'] ) ) { if ( $response->data['excerpt']['protected'] && empty( $response->data['excerpt']['rendered'] ) ) { // Hide raw data $response->data['excerpt']['raw'] = ''; } } } return $response; }
php
public function overrideResponse( $response, $post, $request ) { if ( $post->post_type === 'chapter' ) { // Add rest link to associated part $response->add_link( 'part', trailingslashit( rest_url( sprintf( '%s/%s', $this->namespace, 'parts' ) ) ) . $post->post_parent ); } if ( in_array( $post->post_type, [ 'front-matter', 'chapter', 'back-matter', 'glossary' ], true ) ) { // Add rest link to metadata $response->add_link( 'metadata', trailingslashit( rest_url( sprintf( '%s/%s/%d/metadata', $this->namespace, $this->rest_base, $post->ID ) ) ) ); } // Check that we are in view/embed context (and) // Check that content is password protected (and) // Check that content is empty (if not then API has already verified that the user can_access_password_content) if ( in_array( $request['context'], [ 'view', 'embed' ], true ) ) { if ( ! empty( $response->data['content'] ) ) { if ( $response->data['content']['protected'] && empty( $response->data['content']['rendered'] ) ) { // Hide raw data $response->data['content']['raw'] = ''; } } if ( ! empty( $response->data['excerpt'] ) ) { if ( $response->data['excerpt']['protected'] && empty( $response->data['excerpt']['rendered'] ) ) { // Hide raw data $response->data['excerpt']['raw'] = ''; } } } return $response; }
[ "public", "function", "overrideResponse", "(", "$", "response", ",", "$", "post", ",", "$", "request", ")", "{", "if", "(", "$", "post", "->", "post_type", "===", "'chapter'", ")", "{", "// Add rest link to associated part", "$", "response", "->", "add_link", "(", "'part'", ",", "trailingslashit", "(", "rest_url", "(", "sprintf", "(", "'%s/%s'", ",", "$", "this", "->", "namespace", ",", "'parts'", ")", ")", ")", ".", "$", "post", "->", "post_parent", ")", ";", "}", "if", "(", "in_array", "(", "$", "post", "->", "post_type", ",", "[", "'front-matter'", ",", "'chapter'", ",", "'back-matter'", ",", "'glossary'", "]", ",", "true", ")", ")", "{", "// Add rest link to metadata", "$", "response", "->", "add_link", "(", "'metadata'", ",", "trailingslashit", "(", "rest_url", "(", "sprintf", "(", "'%s/%s/%d/metadata'", ",", "$", "this", "->", "namespace", ",", "$", "this", "->", "rest_base", ",", "$", "post", "->", "ID", ")", ")", ")", ")", ";", "}", "// Check that we are in view/embed context (and)", "// Check that content is password protected (and)", "// Check that content is empty (if not then API has already verified that the user can_access_password_content)", "if", "(", "in_array", "(", "$", "request", "[", "'context'", "]", ",", "[", "'view'", ",", "'embed'", "]", ",", "true", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "response", "->", "data", "[", "'content'", "]", ")", ")", "{", "if", "(", "$", "response", "->", "data", "[", "'content'", "]", "[", "'protected'", "]", "&&", "empty", "(", "$", "response", "->", "data", "[", "'content'", "]", "[", "'rendered'", "]", ")", ")", "{", "// Hide raw data", "$", "response", "->", "data", "[", "'content'", "]", "[", "'raw'", "]", "=", "''", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "response", "->", "data", "[", "'excerpt'", "]", ")", ")", "{", "if", "(", "$", "response", "->", "data", "[", "'excerpt'", "]", "[", "'protected'", "]", "&&", "empty", "(", "$", "response", "->", "data", "[", "'excerpt'", "]", "[", "'rendered'", "]", ")", ")", "{", "// Hide raw data", "$", "response", "->", "data", "[", "'excerpt'", "]", "[", "'raw'", "]", "=", "''", ";", "}", "}", "}", "return", "$", "response", ";", "}" ]
Override the response object @param \WP_REST_Response $response @param \WP_Post $post @param \WP_REST_Request $request @return mixed
[ "Override", "the", "response", "object" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-posts.php#L66-L97
pressbooks/pressbooks
inc/api/endpoints/controller/class-posts.php
Posts.overrideTrashable
public function overrideTrashable( $supports_trash, $post ) { global $wpdb; if ( $post->post_type === 'part' && $supports_trash ) { // Don't delete a part if it has chapters $pids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND (post_status != 'trash' AND post_status != 'inherit') LIMIT 1 ", $post->ID ) ); if ( ! empty( $pids ) ) { $supports_trash = false; } } return $supports_trash; }
php
public function overrideTrashable( $supports_trash, $post ) { global $wpdb; if ( $post->post_type === 'part' && $supports_trash ) { // Don't delete a part if it has chapters $pids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND (post_status != 'trash' AND post_status != 'inherit') LIMIT 1 ", $post->ID ) ); if ( ! empty( $pids ) ) { $supports_trash = false; } } return $supports_trash; }
[ "public", "function", "overrideTrashable", "(", "$", "supports_trash", ",", "$", "post", ")", "{", "global", "$", "wpdb", ";", "if", "(", "$", "post", "->", "post_type", "===", "'part'", "&&", "$", "supports_trash", ")", "{", "// Don't delete a part if it has chapters", "$", "pids", "=", "$", "wpdb", "->", "get_col", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND (post_status != 'trash' AND post_status != 'inherit') LIMIT 1 \"", ",", "$", "post", "->", "ID", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "pids", ")", ")", "{", "$", "supports_trash", "=", "false", ";", "}", "}", "return", "$", "supports_trash", ";", "}" ]
@param bool $supports_trash @param \WP_Post $post @return bool
[ "@param", "bool", "$supports_trash", "@param", "\\", "WP_Post", "$post" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-posts.php#L105-L120
pressbooks/pressbooks
inc/api/endpoints/controller/class-posts.php
Posts.get_items_permissions_check
public function get_items_permissions_check( $request ) { if ( current_user_can( 'edit_posts' ) ) { return true; } if ( 1 !== absint( get_option( 'blog_public' ) ) ) { return false; } return parent::get_items_permissions_check( $request ); }
php
public function get_items_permissions_check( $request ) { if ( current_user_can( 'edit_posts' ) ) { return true; } if ( 1 !== absint( get_option( 'blog_public' ) ) ) { return false; } return parent::get_items_permissions_check( $request ); }
[ "public", "function", "get_items_permissions_check", "(", "$", "request", ")", "{", "if", "(", "current_user_can", "(", "'edit_posts'", ")", ")", "{", "return", "true", ";", "}", "if", "(", "1", "!==", "absint", "(", "get_option", "(", "'blog_public'", ")", ")", ")", "{", "return", "false", ";", "}", "return", "parent", "::", "get_items_permissions_check", "(", "$", "request", ")", ";", "}" ]
@param \WP_REST_Request $request Full details about the request. @return bool|\WP_Error True if the request has read access, WP_Error object otherwise.
[ "@param", "\\", "WP_REST_Request", "$request", "Full", "details", "about", "the", "request", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/api/endpoints/controller/class-posts.php#L131-L142
pressbooks/pressbooks
inc/class-customcss.php
CustomCss.getCustomCssFolder
static function getCustomCssFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'custom-css/'; if ( ! file_exists( $path ) ) { wp_mkdir_p( $path ); } return $path; }
php
static function getCustomCssFolder() { $path = \Pressbooks\Utility\get_media_prefix() . 'custom-css/'; if ( ! file_exists( $path ) ) { wp_mkdir_p( $path ); } return $path; }
[ "static", "function", "getCustomCssFolder", "(", ")", "{", "$", "path", "=", "\\", "Pressbooks", "\\", "Utility", "\\", "get_media_prefix", "(", ")", ".", "'custom-css/'", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "wp_mkdir_p", "(", "$", "path", ")", ";", "}", "return", "$", "path", ";", "}" ]
Get the fullpath to the Custom CSS folder Create if not there. @return string fullpath
[ "Get", "the", "fullpath", "to", "the", "Custom", "CSS", "folder", "Create", "if", "not", "there", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-customcss.php#L23-L31
pressbooks/pressbooks
inc/class-customcss.php
CustomCss.getBaseTheme
static function getBaseTheme( $slug ) { $filename = static::getCustomCssFolder() . sanitize_file_name( $slug . '.css' ); if ( ! file_exists( $filename ) ) { return false; } $theme = get_file_data( $filename, [ 'ThemeURI' => 'Theme URI', ] ); $theme_slug = str_replace( [ 'http://pressbooks.com/themes/', 'https://pressbooks.com/themes/' ], [ '', '' ], $theme['ThemeURI'] ); return untrailingslashit( $theme_slug ); }
php
static function getBaseTheme( $slug ) { $filename = static::getCustomCssFolder() . sanitize_file_name( $slug . '.css' ); if ( ! file_exists( $filename ) ) { return false; } $theme = get_file_data( $filename, [ 'ThemeURI' => 'Theme URI', ] ); $theme_slug = str_replace( [ 'http://pressbooks.com/themes/', 'https://pressbooks.com/themes/' ], [ '', '' ], $theme['ThemeURI'] ); return untrailingslashit( $theme_slug ); }
[ "static", "function", "getBaseTheme", "(", "$", "slug", ")", "{", "$", "filename", "=", "static", "::", "getCustomCssFolder", "(", ")", ".", "sanitize_file_name", "(", "$", "slug", ".", "'.css'", ")", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "{", "return", "false", ";", "}", "$", "theme", "=", "get_file_data", "(", "$", "filename", ",", "[", "'ThemeURI'", "=>", "'Theme URI'", ",", "]", ")", ";", "$", "theme_slug", "=", "str_replace", "(", "[", "'http://pressbooks.com/themes/'", ",", "'https://pressbooks.com/themes/'", "]", ",", "[", "''", ",", "''", "]", ",", "$", "theme", "[", "'ThemeURI'", "]", ")", ";", "return", "untrailingslashit", "(", "$", "theme_slug", ")", ";", "}" ]
Determine base theme that was used for the selected Custom CSS. @param $slug string @return string
[ "Determine", "base", "theme", "that", "was", "used", "for", "the", "selected", "Custom", "CSS", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-customcss.php#L66-L79
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.hooks
static public function hooks( Complex $obj ) { add_shortcode( 'anchor', [ $obj, 'anchorShortCodeHandler' ] ); add_shortcode( 'columns', [ $obj, 'columnsShortCodeHandler' ] ); add_shortcode( 'email', [ $obj, 'emailShortCodeHandler' ] ); add_shortcode( 'equation', [ $obj, 'equationShortCodeHandler' ] ); add_shortcode( 'media', [ $obj, 'mediaShortCodeHandler' ] ); }
php
static public function hooks( Complex $obj ) { add_shortcode( 'anchor', [ $obj, 'anchorShortCodeHandler' ] ); add_shortcode( 'columns', [ $obj, 'columnsShortCodeHandler' ] ); add_shortcode( 'email', [ $obj, 'emailShortCodeHandler' ] ); add_shortcode( 'equation', [ $obj, 'equationShortCodeHandler' ] ); add_shortcode( 'media', [ $obj, 'mediaShortCodeHandler' ] ); }
[ "static", "public", "function", "hooks", "(", "Complex", "$", "obj", ")", "{", "add_shortcode", "(", "'anchor'", ",", "[", "$", "obj", ",", "'anchorShortCodeHandler'", "]", ")", ";", "add_shortcode", "(", "'columns'", ",", "[", "$", "obj", ",", "'columnsShortCodeHandler'", "]", ")", ";", "add_shortcode", "(", "'email'", ",", "[", "$", "obj", ",", "'emailShortCodeHandler'", "]", ")", ";", "add_shortcode", "(", "'equation'", ",", "[", "$", "obj", ",", "'equationShortCodeHandler'", "]", ")", ";", "add_shortcode", "(", "'media'", ",", "[", "$", "obj", ",", "'mediaShortCodeHandler'", "]", ")", ";", "}" ]
Shortcode registration hooks. @param Complex $obj
[ "Shortcode", "registration", "hooks", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L35-L41
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.anchorShortCodeHandler
public function anchorShortCodeHandler( $atts, $content, $shortcode ) { if ( ! isset( $atts['id'] ) ) { return ''; } $atts = shortcode_atts( [ 'class' => null, 'id' => null, ], $atts, $shortcode ); return sprintf( '<a id="%1$s"%2$s%3$s></a>', sanitize_title( $atts['id'] ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '', ( $content ) ? sprintf( ' title="%s"', $content ) : '' ); }
php
public function anchorShortCodeHandler( $atts, $content, $shortcode ) { if ( ! isset( $atts['id'] ) ) { return ''; } $atts = shortcode_atts( [ 'class' => null, 'id' => null, ], $atts, $shortcode ); return sprintf( '<a id="%1$s"%2$s%3$s></a>', sanitize_title( $atts['id'] ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '', ( $content ) ? sprintf( ' title="%s"', $content ) : '' ); }
[ "public", "function", "anchorShortCodeHandler", "(", "$", "atts", ",", "$", "content", ",", "$", "shortcode", ")", "{", "if", "(", "!", "isset", "(", "$", "atts", "[", "'id'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "atts", "=", "shortcode_atts", "(", "[", "'class'", "=>", "null", ",", "'id'", "=>", "null", ",", "]", ",", "$", "atts", ",", "$", "shortcode", ")", ";", "return", "sprintf", "(", "'<a id=\"%1$s\"%2$s%3$s></a>'", ",", "sanitize_title", "(", "$", "atts", "[", "'id'", "]", ")", ",", "(", "isset", "(", "$", "atts", "[", "'class'", "]", ")", ")", "?", "sprintf", "(", "' class=\"%s\"'", ",", "$", "atts", "[", "'class'", "]", ")", ":", "''", ",", "(", "$", "content", ")", "?", "sprintf", "(", "' title=\"%s\"'", ",", "$", "content", ")", ":", "''", ")", ";", "}" ]
Shortcode handler for [anchor]. @param array $atts Shortcode attributes. @param string $content Shortcode content. @param string $shortcode Shortcode name. @return string
[ "Shortcode", "handler", "for", "[", "anchor", "]", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L58-L78
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.columnsShortCodeHandler
public function columnsShortCodeHandler( $atts, $content, $shortcode ) { if ( ! $content ) { return ''; } $atts = shortcode_atts( [ 'class' => null, 'count' => 2, ], $atts, $shortcode ); $classes = $atts['class'] ?? ''; switch ( $atts['count'] ) { case 2: $classes .= ' twocolumn'; break; case 3: $classes .= ' threecolumn'; break; default: $classes .= ' twocolumn'; } return sprintf( '<div class="%1$s">%2$s</div>', trim( $classes ), wpautop( trim( $content ) ) ); }
php
public function columnsShortCodeHandler( $atts, $content, $shortcode ) { if ( ! $content ) { return ''; } $atts = shortcode_atts( [ 'class' => null, 'count' => 2, ], $atts, $shortcode ); $classes = $atts['class'] ?? ''; switch ( $atts['count'] ) { case 2: $classes .= ' twocolumn'; break; case 3: $classes .= ' threecolumn'; break; default: $classes .= ' twocolumn'; } return sprintf( '<div class="%1$s">%2$s</div>', trim( $classes ), wpautop( trim( $content ) ) ); }
[ "public", "function", "columnsShortCodeHandler", "(", "$", "atts", ",", "$", "content", ",", "$", "shortcode", ")", "{", "if", "(", "!", "$", "content", ")", "{", "return", "''", ";", "}", "$", "atts", "=", "shortcode_atts", "(", "[", "'class'", "=>", "null", ",", "'count'", "=>", "2", ",", "]", ",", "$", "atts", ",", "$", "shortcode", ")", ";", "$", "classes", "=", "$", "atts", "[", "'class'", "]", "??", "''", ";", "switch", "(", "$", "atts", "[", "'count'", "]", ")", "{", "case", "2", ":", "$", "classes", ".=", "' twocolumn'", ";", "break", ";", "case", "3", ":", "$", "classes", ".=", "' threecolumn'", ";", "break", ";", "default", ":", "$", "classes", ".=", "' twocolumn'", ";", "}", "return", "sprintf", "(", "'<div class=\"%1$s\">%2$s</div>'", ",", "trim", "(", "$", "classes", ")", ",", "wpautop", "(", "trim", "(", "$", "content", ")", ")", ")", ";", "}" ]
Shortcode handler for [columns]. @param array $atts Shortcode attributes. @param string $content Shortcode content. @param string $shortcode Shortcode name. @return string
[ "Shortcode", "handler", "for", "[", "columns", "]", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L89-L121
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.emailShortCodeHandler
public function emailShortCodeHandler( $atts, $content, $shortcode ) { $atts = shortcode_atts( [ 'class' => null, 'address' => null, ], $atts, $shortcode ); $address = $atts['address'] ?? $content; if ( ! is_email( $address ) ) { return ''; } if ( $address === $content ) { return sprintf( '<a href="mailto:%1$s"%2$s>%1$s</a>', antispambot( $address ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '' ); } else { return sprintf( '<a href="mailto:%1$s"%2$s>%3$s</a>', antispambot( $address ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '', ( $content ) ? $content : antispambot( $address ) ); } }
php
public function emailShortCodeHandler( $atts, $content, $shortcode ) { $atts = shortcode_atts( [ 'class' => null, 'address' => null, ], $atts, $shortcode ); $address = $atts['address'] ?? $content; if ( ! is_email( $address ) ) { return ''; } if ( $address === $content ) { return sprintf( '<a href="mailto:%1$s"%2$s>%1$s</a>', antispambot( $address ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '' ); } else { return sprintf( '<a href="mailto:%1$s"%2$s>%3$s</a>', antispambot( $address ), ( isset( $atts['class'] ) ) ? sprintf( ' class="%s"', $atts['class'] ) : '', ( $content ) ? $content : antispambot( $address ) ); } }
[ "public", "function", "emailShortCodeHandler", "(", "$", "atts", ",", "$", "content", ",", "$", "shortcode", ")", "{", "$", "atts", "=", "shortcode_atts", "(", "[", "'class'", "=>", "null", ",", "'address'", "=>", "null", ",", "]", ",", "$", "atts", ",", "$", "shortcode", ")", ";", "$", "address", "=", "$", "atts", "[", "'address'", "]", "??", "$", "content", ";", "if", "(", "!", "is_email", "(", "$", "address", ")", ")", "{", "return", "''", ";", "}", "if", "(", "$", "address", "===", "$", "content", ")", "{", "return", "sprintf", "(", "'<a href=\"mailto:%1$s\"%2$s>%1$s</a>'", ",", "antispambot", "(", "$", "address", ")", ",", "(", "isset", "(", "$", "atts", "[", "'class'", "]", ")", ")", "?", "sprintf", "(", "' class=\"%s\"'", ",", "$", "atts", "[", "'class'", "]", ")", ":", "''", ")", ";", "}", "else", "{", "return", "sprintf", "(", "'<a href=\"mailto:%1$s\"%2$s>%3$s</a>'", ",", "antispambot", "(", "$", "address", ")", ",", "(", "isset", "(", "$", "atts", "[", "'class'", "]", ")", ")", "?", "sprintf", "(", "' class=\"%s\"'", ",", "$", "atts", "[", "'class'", "]", ")", ":", "''", ",", "(", "$", "content", ")", "?", "$", "content", ":", "antispambot", "(", "$", "address", ")", ")", ";", "}", "}" ]
Shortcode handler for [email]. @param array $atts Shortcode attributes. @param string $content Shortcode content. @param string $shortcode Shortcode name. @return string
[ "Shortcode", "handler", "for", "[", "email", "]", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L132-L162
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.equationShortCodeHandler
public function equationShortCodeHandler( $atts, $content, $shortcode ) { if ( ! $content ) { return ''; } $atts = shortcode_atts( [ 'size' => 0, 'color' => false, 'background' => false, ], $atts ); return do_shortcode_by_tags( sprintf( '<p>[latex%1$s]%2$s[/latex]' . "</p>\n", ( $atts['size'] !== 0 ) ? sprintf( ' size="%1$s" color="%2$s" background="%3$s"', $atts['size'], $atts['color'], $atts['background'] ) : sprintf( ' color="%1$s" background="%2$s"', $atts['color'], $atts['background'] ), $content ), [ 'latex' ] ); }
php
public function equationShortCodeHandler( $atts, $content, $shortcode ) { if ( ! $content ) { return ''; } $atts = shortcode_atts( [ 'size' => 0, 'color' => false, 'background' => false, ], $atts ); return do_shortcode_by_tags( sprintf( '<p>[latex%1$s]%2$s[/latex]' . "</p>\n", ( $atts['size'] !== 0 ) ? sprintf( ' size="%1$s" color="%2$s" background="%3$s"', $atts['size'], $atts['color'], $atts['background'] ) : sprintf( ' color="%1$s" background="%2$s"', $atts['color'], $atts['background'] ), $content ), [ 'latex' ] ); }
[ "public", "function", "equationShortCodeHandler", "(", "$", "atts", ",", "$", "content", ",", "$", "shortcode", ")", "{", "if", "(", "!", "$", "content", ")", "{", "return", "''", ";", "}", "$", "atts", "=", "shortcode_atts", "(", "[", "'size'", "=>", "0", ",", "'color'", "=>", "false", ",", "'background'", "=>", "false", ",", "]", ",", "$", "atts", ")", ";", "return", "do_shortcode_by_tags", "(", "sprintf", "(", "'<p>[latex%1$s]%2$s[/latex]'", ".", "\"</p>\\n\"", ",", "(", "$", "atts", "[", "'size'", "]", "!==", "0", ")", "?", "sprintf", "(", "' size=\"%1$s\" color=\"%2$s\" background=\"%3$s\"'", ",", "$", "atts", "[", "'size'", "]", ",", "$", "atts", "[", "'color'", "]", ",", "$", "atts", "[", "'background'", "]", ")", ":", "sprintf", "(", "' color=\"%1$s\" background=\"%2$s\"'", ",", "$", "atts", "[", "'color'", "]", ",", "$", "atts", "[", "'background'", "]", ")", ",", "$", "content", ")", ",", "[", "'latex'", "]", ")", ";", "}" ]
Shortcode handler for [equation]. @param array $atts Shortcode attributes. @param string $content Shortcode content. @param string $shortcode Shortcode name. @return string
[ "Shortcode", "handler", "for", "[", "equation", "]", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L173-L204
pressbooks/pressbooks
inc/shortcodes/complex/class-complex.php
Complex.mediaShortCodeHandler
public function mediaShortCodeHandler( $atts, $content, $shortcode ) { global $wp_embed; $atts = shortcode_atts( [ 'caption' => null, 'src' => null, ], $atts ); $src = $atts['src'] ?? $content; if ( str_starts_with( $src, '“' ) || str_starts_with( $src, '”' ) || str_starts_with( $src, '‘' ) || str_starts_with( $src, '’' ) ) { $src = trim( $src, '“”‘’' ); // Trim fancy quotes, for MS-Word compatibility } $src = esc_url_raw( $src ); if ( ! filter_var( $src, FILTER_VALIDATE_URL ) ) { return ''; } // Can't use `do_shortcode_by_tags` because the default callback for 'embed' is `__return_false` - @see \WP_Embed::__construct $e = $wp_embed->run_shortcode( sprintf( '[embed src="%s"]', $src ) ); if ( $atts['caption'] ) { return sprintf( '<figure class="embed">%1$s<figcaption>%2$s</figcaption></figure>', str_replace( [ '<p>', '</p>' ], '', $e ), $atts['caption'] ); } else { return $e; } }
php
public function mediaShortCodeHandler( $atts, $content, $shortcode ) { global $wp_embed; $atts = shortcode_atts( [ 'caption' => null, 'src' => null, ], $atts ); $src = $atts['src'] ?? $content; if ( str_starts_with( $src, '“' ) || str_starts_with( $src, '”' ) || str_starts_with( $src, '‘' ) || str_starts_with( $src, '’' ) ) { $src = trim( $src, '“”‘’' ); // Trim fancy quotes, for MS-Word compatibility } $src = esc_url_raw( $src ); if ( ! filter_var( $src, FILTER_VALIDATE_URL ) ) { return ''; } // Can't use `do_shortcode_by_tags` because the default callback for 'embed' is `__return_false` - @see \WP_Embed::__construct $e = $wp_embed->run_shortcode( sprintf( '[embed src="%s"]', $src ) ); if ( $atts['caption'] ) { return sprintf( '<figure class="embed">%1$s<figcaption>%2$s</figcaption></figure>', str_replace( [ '<p>', '</p>' ], '', $e ), $atts['caption'] ); } else { return $e; } }
[ "public", "function", "mediaShortCodeHandler", "(", "$", "atts", ",", "$", "content", ",", "$", "shortcode", ")", "{", "global", "$", "wp_embed", ";", "$", "atts", "=", "shortcode_atts", "(", "[", "'caption'", "=>", "null", ",", "'src'", "=>", "null", ",", "]", ",", "$", "atts", ")", ";", "$", "src", "=", "$", "atts", "[", "'src'", "]", "??", "$", "content", ";", "if", "(", "str_starts_with", "(", "$", "src", ",", "'“' )", "|", " s", "r_starts_with( ", "$", "r", "c, ", "'", "' ) |", " ", "tr", "starts_with( $s", "r", ",", " '‘", "'", ") || ", "t", "_s", "arts_with( $src", ",", "'", "’' ", ")", ") {", "", "", "", "$", "src", "=", "trim", "(", "$", "src", ",", "'“”‘’' ); // T", "i", "m", "fancy quotes, for MS-Word compatibility", "}", "$", "src", "=", "esc_url_raw", "(", "$", "src", ")", ";", "if", "(", "!", "filter_var", "(", "$", "src", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "''", ";", "}", "// Can't use `do_shortcode_by_tags` because the default callback for 'embed' is `__return_false` - @see \\WP_Embed::__construct", "$", "e", "=", "$", "wp_embed", "->", "run_shortcode", "(", "sprintf", "(", "'[embed src=\"%s\"]'", ",", "$", "src", ")", ")", ";", "if", "(", "$", "atts", "[", "'caption'", "]", ")", "{", "return", "sprintf", "(", "'<figure class=\"embed\">%1$s<figcaption>%2$s</figcaption></figure>'", ",", "str_replace", "(", "[", "'<p>'", ",", "'</p>'", "]", ",", "''", ",", "$", "e", ")", ",", "$", "atts", "[", "'caption'", "]", ")", ";", "}", "else", "{", "return", "$", "e", ";", "}", "}" ]
Shortcode handler for [media]. @param array $atts Shortcode attributes. @param string $content Shortcode content. @param string $shortcode Shortcode name. @return string
[ "Shortcode", "handler", "for", "[", "media", "]", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/complex/class-complex.php#L215-L242
pressbooks/pressbooks
inc/modules/themeoptions/class-ebookoptions.php
EbookOptions.init
function init() { $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_page = $_option; $_section = $this->getSlug() . '_options_section'; if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), [ $this, 'display' ], $_page ); add_settings_field( 'ebook_start_point', __( 'Ebook Start Point', 'pressbooks' ), [ $this, 'renderEbookStartPointField' ], $_page, $_section, [ __( 'Note: This designated ebook start book may be overridden by some ereader devices.', 'pressbooks' ), 'label_for' => 'ebook_start_point', ] ); add_settings_field( 'ebook_paragraph_separation', __( 'Paragraph Separation', 'pressbooks' ), [ $this, 'renderParagraphSeparationField' ], $_page, $_section, [ 'indent' => __( 'Indent paragraphs', 'pressbooks' ), 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), ] ); add_settings_field( 'ebook_compress_images', __( 'Compress Images', 'pressbooks' ), [ $this, 'renderCompressImagesField' ], $_page, $_section, [ __( 'Reduce image size and quality', 'pressbooks' ), ] ); /** * Add custom settings fields. * * @since 3.9.7 * * @param string $arg1 * @param string $arg2 */ do_action( 'pb_theme_options_ebook_add_settings_fields', $_page, $_section ); register_setting( $_option, $_option, [ $this, 'sanitize' ] ); }
php
function init() { $_option = 'pressbooks_theme_options_' . $this->getSlug(); $_page = $_option; $_section = $this->getSlug() . '_options_section'; if ( false === get_option( $_option ) ) { add_option( $_option, $this->defaults ); } add_settings_section( $_section, $this->getTitle(), [ $this, 'display' ], $_page ); add_settings_field( 'ebook_start_point', __( 'Ebook Start Point', 'pressbooks' ), [ $this, 'renderEbookStartPointField' ], $_page, $_section, [ __( 'Note: This designated ebook start book may be overridden by some ereader devices.', 'pressbooks' ), 'label_for' => 'ebook_start_point', ] ); add_settings_field( 'ebook_paragraph_separation', __( 'Paragraph Separation', 'pressbooks' ), [ $this, 'renderParagraphSeparationField' ], $_page, $_section, [ 'indent' => __( 'Indent paragraphs', 'pressbooks' ), 'skiplines' => __( 'Skip lines between paragraphs', 'pressbooks' ), ] ); add_settings_field( 'ebook_compress_images', __( 'Compress Images', 'pressbooks' ), [ $this, 'renderCompressImagesField' ], $_page, $_section, [ __( 'Reduce image size and quality', 'pressbooks' ), ] ); /** * Add custom settings fields. * * @since 3.9.7 * * @param string $arg1 * @param string $arg2 */ do_action( 'pb_theme_options_ebook_add_settings_fields', $_page, $_section ); register_setting( $_option, $_option, [ $this, 'sanitize' ] ); }
[ "function", "init", "(", ")", "{", "$", "_option", "=", "'pressbooks_theme_options_'", ".", "$", "this", "->", "getSlug", "(", ")", ";", "$", "_page", "=", "$", "_option", ";", "$", "_section", "=", "$", "this", "->", "getSlug", "(", ")", ".", "'_options_section'", ";", "if", "(", "false", "===", "get_option", "(", "$", "_option", ")", ")", "{", "add_option", "(", "$", "_option", ",", "$", "this", "->", "defaults", ")", ";", "}", "add_settings_section", "(", "$", "_section", ",", "$", "this", "->", "getTitle", "(", ")", ",", "[", "$", "this", ",", "'display'", "]", ",", "$", "_page", ")", ";", "add_settings_field", "(", "'ebook_start_point'", ",", "__", "(", "'Ebook Start Point'", ",", "'pressbooks'", ")", ",", "[", "$", "this", ",", "'renderEbookStartPointField'", "]", ",", "$", "_page", ",", "$", "_section", ",", "[", "__", "(", "'Note: This designated ebook start book may be overridden by some ereader devices.'", ",", "'pressbooks'", ")", ",", "'label_for'", "=>", "'ebook_start_point'", ",", "]", ")", ";", "add_settings_field", "(", "'ebook_paragraph_separation'", ",", "__", "(", "'Paragraph Separation'", ",", "'pressbooks'", ")", ",", "[", "$", "this", ",", "'renderParagraphSeparationField'", "]", ",", "$", "_page", ",", "$", "_section", ",", "[", "'indent'", "=>", "__", "(", "'Indent paragraphs'", ",", "'pressbooks'", ")", ",", "'skiplines'", "=>", "__", "(", "'Skip lines between paragraphs'", ",", "'pressbooks'", ")", ",", "]", ")", ";", "add_settings_field", "(", "'ebook_compress_images'", ",", "__", "(", "'Compress Images'", ",", "'pressbooks'", ")", ",", "[", "$", "this", ",", "'renderCompressImagesField'", "]", ",", "$", "_page", ",", "$", "_section", ",", "[", "__", "(", "'Reduce image size and quality'", ",", "'pressbooks'", ")", ",", "]", ")", ";", "/**\n\t\t * Add custom settings fields.\n\t\t *\n\t\t * @since 3.9.7\n\t\t *\n\t\t * @param string $arg1\n\t\t * @param string $arg2\n\t\t */", "do_action", "(", "'pb_theme_options_ebook_add_settings_fields'", ",", "$", "_page", ",", "$", "_section", ")", ";", "register_setting", "(", "$", "_option", ",", "$", "_option", ",", "[", "$", "this", ",", "'sanitize'", "]", ")", ";", "}" ]
Configure the ebook options tab using the settings API.
[ "Configure", "the", "ebook", "options", "tab", "using", "the", "settings", "API", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/themeoptions/class-ebookoptions.php#L57-L123
pressbooks/pressbooks
inc/modules/themeoptions/class-ebookoptions.php
EbookOptions.setEbookStartPoint
function setEbookStartPoint() { $_option = $this->getSlug(); $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); $struct = \Pressbooks\Book::getBookStructure(); foreach ( $struct['front-matter'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } if ( ! isset( $options['ebook_start_point'] ) ) { foreach ( $struct['part'] as $key => $value ) { foreach ( $value['chapters'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } } } if ( ! isset( $options['ebook_start_point'] ) ) { foreach ( $struct['back-matter'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } } update_option( 'pressbooks_theme_options_' . $_option, $options ); }
php
function setEbookStartPoint() { $_option = $this->getSlug(); $options = get_option( 'pressbooks_theme_options_' . $_option, $this->defaults ); $struct = \Pressbooks\Book::getBookStructure(); foreach ( $struct['front-matter'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } if ( ! isset( $options['ebook_start_point'] ) ) { foreach ( $struct['part'] as $key => $value ) { foreach ( $value['chapters'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } } } if ( ! isset( $options['ebook_start_point'] ) ) { foreach ( $struct['back-matter'] as $k => $v ) { if ( get_post_meta( $v['ID'], 'pb_ebook_start', true ) ) { $options['ebook_start_point'] = $v['ID']; break; } } } update_option( 'pressbooks_theme_options_' . $_option, $options ); }
[ "function", "setEbookStartPoint", "(", ")", "{", "$", "_option", "=", "$", "this", "->", "getSlug", "(", ")", ";", "$", "options", "=", "get_option", "(", "'pressbooks_theme_options_'", ".", "$", "_option", ",", "$", "this", "->", "defaults", ")", ";", "$", "struct", "=", "\\", "Pressbooks", "\\", "Book", "::", "getBookStructure", "(", ")", ";", "foreach", "(", "$", "struct", "[", "'front-matter'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "get_post_meta", "(", "$", "v", "[", "'ID'", "]", ",", "'pb_ebook_start'", ",", "true", ")", ")", "{", "$", "options", "[", "'ebook_start_point'", "]", "=", "$", "v", "[", "'ID'", "]", ";", "break", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "options", "[", "'ebook_start_point'", "]", ")", ")", "{", "foreach", "(", "$", "struct", "[", "'part'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "$", "value", "[", "'chapters'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "get_post_meta", "(", "$", "v", "[", "'ID'", "]", ",", "'pb_ebook_start'", ",", "true", ")", ")", "{", "$", "options", "[", "'ebook_start_point'", "]", "=", "$", "v", "[", "'ID'", "]", ";", "break", ";", "}", "}", "}", "}", "if", "(", "!", "isset", "(", "$", "options", "[", "'ebook_start_point'", "]", ")", ")", "{", "foreach", "(", "$", "struct", "[", "'back-matter'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "get_post_meta", "(", "$", "v", "[", "'ID'", "]", ",", "'pb_ebook_start'", ",", "true", ")", ")", "{", "$", "options", "[", "'ebook_start_point'", "]", "=", "$", "v", "[", "'ID'", "]", ";", "break", ";", "}", "}", "}", "update_option", "(", "'pressbooks_theme_options_'", ".", "$", "_option", ",", "$", "options", ")", ";", "}" ]
Update values to human-readable equivalents within Ebook options.
[ "Update", "values", "to", "human", "-", "readable", "equivalents", "within", "Ebook", "options", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/themeoptions/class-ebookoptions.php#L171-L205
pressbooks/pressbooks
inc/modules/themeoptions/class-ebookoptions.php
EbookOptions.renderEbookStartPointField
function renderEbookStartPointField( $args ) { unset( $args['label_for'], $args['class'] ); $options = [ '' => '--', ]; $struct = \Pressbooks\Book::getBookStructure(); foreach ( $struct['front-matter'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } foreach ( $struct['part'] as $key => $value ) { foreach ( $value['chapters'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } } foreach ( $struct['back-matter'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } $this->renderSelect( [ 'id' => 'ebook_start_point', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_start_point', 'value' => ( isset( $this->options['ebook_start_point'] ) ) ? $this->options['ebook_start_point'] : '', 'choices' => $options, 'description' => $args[0], ] ); }
php
function renderEbookStartPointField( $args ) { unset( $args['label_for'], $args['class'] ); $options = [ '' => '--', ]; $struct = \Pressbooks\Book::getBookStructure(); foreach ( $struct['front-matter'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } foreach ( $struct['part'] as $key => $value ) { foreach ( $value['chapters'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } } foreach ( $struct['back-matter'] as $k => $v ) { $options[ $v['ID'] ] = $v['post_title']; } $this->renderSelect( [ 'id' => 'ebook_start_point', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_start_point', 'value' => ( isset( $this->options['ebook_start_point'] ) ) ? $this->options['ebook_start_point'] : '', 'choices' => $options, 'description' => $args[0], ] ); }
[ "function", "renderEbookStartPointField", "(", "$", "args", ")", "{", "unset", "(", "$", "args", "[", "'label_for'", "]", ",", "$", "args", "[", "'class'", "]", ")", ";", "$", "options", "=", "[", "''", "=>", "'--'", ",", "]", ";", "$", "struct", "=", "\\", "Pressbooks", "\\", "Book", "::", "getBookStructure", "(", ")", ";", "foreach", "(", "$", "struct", "[", "'front-matter'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "options", "[", "$", "v", "[", "'ID'", "]", "]", "=", "$", "v", "[", "'post_title'", "]", ";", "}", "foreach", "(", "$", "struct", "[", "'part'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "$", "value", "[", "'chapters'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "options", "[", "$", "v", "[", "'ID'", "]", "]", "=", "$", "v", "[", "'post_title'", "]", ";", "}", "}", "foreach", "(", "$", "struct", "[", "'back-matter'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "options", "[", "$", "v", "[", "'ID'", "]", "]", "=", "$", "v", "[", "'post_title'", "]", ";", "}", "$", "this", "->", "renderSelect", "(", "[", "'id'", "=>", "'ebook_start_point'", ",", "'name'", "=>", "'pressbooks_theme_options_'", ".", "$", "this", "->", "getSlug", "(", ")", ",", "'option'", "=>", "'ebook_start_point'", ",", "'value'", "=>", "(", "isset", "(", "$", "this", "->", "options", "[", "'ebook_start_point'", "]", ")", ")", "?", "$", "this", "->", "options", "[", "'ebook_start_point'", "]", ":", "''", ",", "'choices'", "=>", "$", "options", ",", "'description'", "=>", "$", "args", "[", "0", "]", ",", "]", ")", ";", "}" ]
Render the ebook_start_point dropdown. @param array $args
[ "Render", "the", "ebook_start_point", "dropdown", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/themeoptions/class-ebookoptions.php#L212-L241
pressbooks/pressbooks
inc/modules/themeoptions/class-ebookoptions.php
EbookOptions.renderParagraphSeparationField
function renderParagraphSeparationField( $args ) { unset( $args['label_for'], $args['class'] ); $this->renderRadioButtons( [ 'id' => 'ebook_paragraph_separation', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_paragraph_separation', 'value' => ( isset( $this->options['ebook_paragraph_separation'] ) ) ? $this->options['ebook_paragraph_separation'] : '', 'choices' => $args, ] ); }
php
function renderParagraphSeparationField( $args ) { unset( $args['label_for'], $args['class'] ); $this->renderRadioButtons( [ 'id' => 'ebook_paragraph_separation', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_paragraph_separation', 'value' => ( isset( $this->options['ebook_paragraph_separation'] ) ) ? $this->options['ebook_paragraph_separation'] : '', 'choices' => $args, ] ); }
[ "function", "renderParagraphSeparationField", "(", "$", "args", ")", "{", "unset", "(", "$", "args", "[", "'label_for'", "]", ",", "$", "args", "[", "'class'", "]", ")", ";", "$", "this", "->", "renderRadioButtons", "(", "[", "'id'", "=>", "'ebook_paragraph_separation'", ",", "'name'", "=>", "'pressbooks_theme_options_'", ".", "$", "this", "->", "getSlug", "(", ")", ",", "'option'", "=>", "'ebook_paragraph_separation'", ",", "'value'", "=>", "(", "isset", "(", "$", "this", "->", "options", "[", "'ebook_paragraph_separation'", "]", ")", ")", "?", "$", "this", "->", "options", "[", "'ebook_paragraph_separation'", "]", ":", "''", ",", "'choices'", "=>", "$", "args", ",", "]", ")", ";", "}" ]
Render the ebook_paragraph_separation radio buttons. @param array $args
[ "Render", "the", "ebook_paragraph_separation", "radio", "buttons", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/themeoptions/class-ebookoptions.php#L248-L259
pressbooks/pressbooks
inc/modules/themeoptions/class-ebookoptions.php
EbookOptions.renderCompressImagesField
function renderCompressImagesField( $args ) { unset( $args['label_for'], $args['class'] ); $this->renderCheckbox( [ 'id' => 'ebook_compress_images', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_compress_images', 'value' => ( isset( $this->options['ebook_compress_images'] ) ) ? $this->options['ebook_compress_images'] : '', 'label' => $args[0], ] ); }
php
function renderCompressImagesField( $args ) { unset( $args['label_for'], $args['class'] ); $this->renderCheckbox( [ 'id' => 'ebook_compress_images', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'ebook_compress_images', 'value' => ( isset( $this->options['ebook_compress_images'] ) ) ? $this->options['ebook_compress_images'] : '', 'label' => $args[0], ] ); }
[ "function", "renderCompressImagesField", "(", "$", "args", ")", "{", "unset", "(", "$", "args", "[", "'label_for'", "]", ",", "$", "args", "[", "'class'", "]", ")", ";", "$", "this", "->", "renderCheckbox", "(", "[", "'id'", "=>", "'ebook_compress_images'", ",", "'name'", "=>", "'pressbooks_theme_options_'", ".", "$", "this", "->", "getSlug", "(", ")", ",", "'option'", "=>", "'ebook_compress_images'", ",", "'value'", "=>", "(", "isset", "(", "$", "this", "->", "options", "[", "'ebook_compress_images'", "]", ")", ")", "?", "$", "this", "->", "options", "[", "'ebook_compress_images'", "]", ":", "''", ",", "'label'", "=>", "$", "args", "[", "0", "]", ",", "]", ")", ";", "}" ]
Render the ebook_compress_images checkbox. @param array $args
[ "Render", "the", "ebook_compress_images", "checkbox", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/themeoptions/class-ebookoptions.php#L266-L277
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getSupportedTypes
public function getSupportedTypes( $disable_translation = false, $disable_custom = false ) { if ( $disable_translation ) { add_filter( 'gettext', [ $this, 'disableTranslation' ], 999, 3 ); } // Supported $supported = [ 'public-domain' => [ 'api' => [ 'license' => 'mark', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/publicdomain/mark/1.0/', 'desc' => __( 'Public Domain', 'pressbooks' ), ], 'cc-zero' => [ 'api' => [ 'license' => 'zero', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/', 'desc' => __( 'CC0 (Creative Commons Zero)', 'pressbooks' ), ], 'cc-by' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/licenses/by/4.0/', 'desc' => __( 'CC BY (Attribution)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution 4.0 International License', 'pressbooks' ), ], 'cc-by-sa' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'sa', ], 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/', 'desc' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-ShareAlike 4.0 International License', 'pressbooks' ), ], 'cc-by-nd' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'n', ], 'url' => 'https://creativecommons.org/licenses/by-nd/4.0/', 'desc' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NoDerivatives 4.0 International License', 'pressbooks' ), ], 'cc-by-nc' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/licenses/by-nc/4.0/', 'desc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial 4.0 International License', 'pressbooks' ), ], 'cc-by-nc-sa' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'sa', ], 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/', 'desc' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License', 'pressbooks' ), ], 'cc-by-nc-nd' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'n', ], 'url' => 'https://creativecommons.org/licenses/by-nc-nd/4.0/', 'desc' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License', 'pressbooks' ), ], 'all-rights-reserved' => [ 'api' => [], // Not supported 'url' => 'https://choosealicense.com/no-license/', 'desc' => __( 'All Rights Reserved', 'pressbooks' ), ], ]; // Custom if ( ! $disable_custom ) { $custom = get_terms( [ 'taxonomy' => self::TAXONOMY, 'hide_empty' => false, ] ); if ( is_array( $custom ) ) { foreach ( $custom as $custom_term ) { if ( ! isset( $supported[ $custom_term->slug ] ) ) { $supported[ $custom_term->slug ] = [ 'api' => [], // Not supported 'url' => "https://choosealicense.com/no-license/#{$custom_term->slug}", 'desc' => $custom_term->name, ]; } } } } if ( $disable_translation ) { remove_filter( 'gettext', [ $this, 'disableTranslation' ], 999 ); } return $supported; }
php
public function getSupportedTypes( $disable_translation = false, $disable_custom = false ) { if ( $disable_translation ) { add_filter( 'gettext', [ $this, 'disableTranslation' ], 999, 3 ); } // Supported $supported = [ 'public-domain' => [ 'api' => [ 'license' => 'mark', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/publicdomain/mark/1.0/', 'desc' => __( 'Public Domain', 'pressbooks' ), ], 'cc-zero' => [ 'api' => [ 'license' => 'zero', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/', 'desc' => __( 'CC0 (Creative Commons Zero)', 'pressbooks' ), ], 'cc-by' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/licenses/by/4.0/', 'desc' => __( 'CC BY (Attribution)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution 4.0 International License', 'pressbooks' ), ], 'cc-by-sa' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'sa', ], 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/', 'desc' => __( 'CC BY-SA (Attribution ShareAlike)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-ShareAlike 4.0 International License', 'pressbooks' ), ], 'cc-by-nd' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'y', 'derivatives' => 'n', ], 'url' => 'https://creativecommons.org/licenses/by-nd/4.0/', 'desc' => __( 'CC BY-ND (Attribution NoDerivatives)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NoDerivatives 4.0 International License', 'pressbooks' ), ], 'cc-by-nc' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'y', ], 'url' => 'https://creativecommons.org/licenses/by-nc/4.0/', 'desc' => __( 'CC BY-NC (Attribution NonCommercial)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial 4.0 International License', 'pressbooks' ), ], 'cc-by-nc-sa' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'sa', ], 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/', 'desc' => __( 'CC BY-NC-SA (Attribution NonCommercial ShareAlike)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License', 'pressbooks' ), ], 'cc-by-nc-nd' => [ 'api' => [ 'license' => 'standard', 'commercial' => 'n', 'derivatives' => 'n', ], 'url' => 'https://creativecommons.org/licenses/by-nc-nd/4.0/', 'desc' => __( 'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)', 'pressbooks' ), 'longdesc' => __( 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License', 'pressbooks' ), ], 'all-rights-reserved' => [ 'api' => [], // Not supported 'url' => 'https://choosealicense.com/no-license/', 'desc' => __( 'All Rights Reserved', 'pressbooks' ), ], ]; // Custom if ( ! $disable_custom ) { $custom = get_terms( [ 'taxonomy' => self::TAXONOMY, 'hide_empty' => false, ] ); if ( is_array( $custom ) ) { foreach ( $custom as $custom_term ) { if ( ! isset( $supported[ $custom_term->slug ] ) ) { $supported[ $custom_term->slug ] = [ 'api' => [], // Not supported 'url' => "https://choosealicense.com/no-license/#{$custom_term->slug}", 'desc' => $custom_term->name, ]; } } } } if ( $disable_translation ) { remove_filter( 'gettext', [ $this, 'disableTranslation' ], 999 ); } return $supported; }
[ "public", "function", "getSupportedTypes", "(", "$", "disable_translation", "=", "false", ",", "$", "disable_custom", "=", "false", ")", "{", "if", "(", "$", "disable_translation", ")", "{", "add_filter", "(", "'gettext'", ",", "[", "$", "this", ",", "'disableTranslation'", "]", ",", "999", ",", "3", ")", ";", "}", "// Supported", "$", "supported", "=", "[", "'public-domain'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'mark'", ",", "'commercial'", "=>", "'y'", ",", "'derivatives'", "=>", "'y'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/publicdomain/mark/1.0/'", ",", "'desc'", "=>", "__", "(", "'Public Domain'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-zero'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'zero'", ",", "'commercial'", "=>", "'y'", ",", "'derivatives'", "=>", "'y'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/publicdomain/zero/1.0/'", ",", "'desc'", "=>", "__", "(", "'CC0 (Creative Commons Zero)'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'y'", ",", "'derivatives'", "=>", "'y'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY (Attribution)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by-sa'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'y'", ",", "'derivatives'", "=>", "'sa'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by-sa/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY-SA (Attribution ShareAlike)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution-ShareAlike 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by-nd'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'y'", ",", "'derivatives'", "=>", "'n'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by-nd/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY-ND (Attribution NoDerivatives)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution-NoDerivatives 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by-nc'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'n'", ",", "'derivatives'", "=>", "'y'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by-nc/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY-NC (Attribution NonCommercial)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution-NonCommercial 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by-nc-sa'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'n'", ",", "'derivatives'", "=>", "'sa'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by-nc-sa/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY-NC-SA (Attribution NonCommercial ShareAlike)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'cc-by-nc-nd'", "=>", "[", "'api'", "=>", "[", "'license'", "=>", "'standard'", ",", "'commercial'", "=>", "'n'", ",", "'derivatives'", "=>", "'n'", ",", "]", ",", "'url'", "=>", "'https://creativecommons.org/licenses/by-nc-nd/4.0/'", ",", "'desc'", "=>", "__", "(", "'CC BY-NC-ND (Attribution NonCommercial NoDerivatives)'", ",", "'pressbooks'", ")", ",", "'longdesc'", "=>", "__", "(", "'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License'", ",", "'pressbooks'", ")", ",", "]", ",", "'all-rights-reserved'", "=>", "[", "'api'", "=>", "[", "]", ",", "// Not supported", "'url'", "=>", "'https://choosealicense.com/no-license/'", ",", "'desc'", "=>", "__", "(", "'All Rights Reserved'", ",", "'pressbooks'", ")", ",", "]", ",", "]", ";", "// Custom", "if", "(", "!", "$", "disable_custom", ")", "{", "$", "custom", "=", "get_terms", "(", "[", "'taxonomy'", "=>", "self", "::", "TAXONOMY", ",", "'hide_empty'", "=>", "false", ",", "]", ")", ";", "if", "(", "is_array", "(", "$", "custom", ")", ")", "{", "foreach", "(", "$", "custom", "as", "$", "custom_term", ")", "{", "if", "(", "!", "isset", "(", "$", "supported", "[", "$", "custom_term", "->", "slug", "]", ")", ")", "{", "$", "supported", "[", "$", "custom_term", "->", "slug", "]", "=", "[", "'api'", "=>", "[", "]", ",", "// Not supported", "'url'", "=>", "\"https://choosealicense.com/no-license/#{$custom_term->slug}\"", ",", "'desc'", "=>", "$", "custom_term", "->", "name", ",", "]", ";", "}", "}", "}", "}", "if", "(", "$", "disable_translation", ")", "{", "remove_filter", "(", "'gettext'", ",", "[", "$", "this", ",", "'disableTranslation'", "]", ",", "999", ")", ";", "}", "return", "$", "supported", ";", "}" ]
Returns supported license types in array that looks like: slug => api[], url, desc, @param bool $disable_translation (optional) @param bool $disable_custom (optional) @return array
[ "Returns", "supported", "license", "types", "in", "array", "that", "looks", "like", ":" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L40-L159
pressbooks/pressbooks
inc/class-licensing.php
Licensing.doLicense
public function doLicense( $metadata, $post_id = 0, $title = '' ) { if ( ! empty( $title ) ) { _doing_it_wrong( __METHOD__, __( '$title is deprecated. Method will automatically determine title from licenses', 'pressbooks' ), 'Pressbooks 5.7.0' ); } $book_license = isset( $metadata['pb_book_license'] ) ? $metadata['pb_book_license'] : ''; if ( empty( $post_id ) ) { // if no post $id given, set empty strings $section_license = ''; $section_author = ''; } else { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); $section_author = ( new Contributors() )->get( $post_id, 'pb_authors' ); } // Copyright license, set in order of precedence if ( ! empty( $section_license ) ) { // section copyright higher priority than book $license = $section_license; } elseif ( ! empty( $book_license ) ) { // book is the fallback, default $license = $book_license; } else { $license = 'all-rights-reserved'; } if ( ! $this->isSupportedType( $license ) ) { // License not supported, bail return ''; } // Unless section is licensed differently, it should display the book license statement if ( $section_license === $book_license || empty( $section_license ) ) { $title = get_bloginfo( 'name' ); $link = get_bloginfo( 'url' ); } else { $post = get_post( $post_id ); $title = $post ? $post->post_title : get_bloginfo( 'name' ); $link = get_permalink( $post_id ); } // Copyright holder, set in order of precedence if ( ! empty( $section_author ) ) { // section author higher priority than book author, copyrightholder $copyright_holder = $section_author; } elseif ( isset( $metadata['pb_copyright_holder'] ) ) { // book copyright holder higher priority than book author $copyright_holder = $metadata['pb_copyright_holder']; } elseif ( isset( $metadata['pb_authors'] ) ) { // book author is the fallback, default $copyright_holder = $metadata['pb_authors']; } else { $copyright_holder = ''; } if ( ! empty( $metadata['pb_copyright_year'] ) ) { $copyright_year = $metadata['pb_copyright_year']; } elseif ( ! empty( $metadata['pb_publication_date'] ) ) { $copyright_year = strftime( '%Y', absint( $metadata['pb_publication_date'] ) ); } else { $copyright_year = 0; } $html = $this->getLicense( $license, $copyright_holder, $link, $title, $copyright_year ); return $html; }
php
public function doLicense( $metadata, $post_id = 0, $title = '' ) { if ( ! empty( $title ) ) { _doing_it_wrong( __METHOD__, __( '$title is deprecated. Method will automatically determine title from licenses', 'pressbooks' ), 'Pressbooks 5.7.0' ); } $book_license = isset( $metadata['pb_book_license'] ) ? $metadata['pb_book_license'] : ''; if ( empty( $post_id ) ) { // if no post $id given, set empty strings $section_license = ''; $section_author = ''; } else { $section_license = get_post_meta( $post_id, 'pb_section_license', true ); $section_author = ( new Contributors() )->get( $post_id, 'pb_authors' ); } // Copyright license, set in order of precedence if ( ! empty( $section_license ) ) { // section copyright higher priority than book $license = $section_license; } elseif ( ! empty( $book_license ) ) { // book is the fallback, default $license = $book_license; } else { $license = 'all-rights-reserved'; } if ( ! $this->isSupportedType( $license ) ) { // License not supported, bail return ''; } // Unless section is licensed differently, it should display the book license statement if ( $section_license === $book_license || empty( $section_license ) ) { $title = get_bloginfo( 'name' ); $link = get_bloginfo( 'url' ); } else { $post = get_post( $post_id ); $title = $post ? $post->post_title : get_bloginfo( 'name' ); $link = get_permalink( $post_id ); } // Copyright holder, set in order of precedence if ( ! empty( $section_author ) ) { // section author higher priority than book author, copyrightholder $copyright_holder = $section_author; } elseif ( isset( $metadata['pb_copyright_holder'] ) ) { // book copyright holder higher priority than book author $copyright_holder = $metadata['pb_copyright_holder']; } elseif ( isset( $metadata['pb_authors'] ) ) { // book author is the fallback, default $copyright_holder = $metadata['pb_authors']; } else { $copyright_holder = ''; } if ( ! empty( $metadata['pb_copyright_year'] ) ) { $copyright_year = $metadata['pb_copyright_year']; } elseif ( ! empty( $metadata['pb_publication_date'] ) ) { $copyright_year = strftime( '%Y', absint( $metadata['pb_publication_date'] ) ); } else { $copyright_year = 0; } $html = $this->getLicense( $license, $copyright_holder, $link, $title, $copyright_year ); return $html; }
[ "public", "function", "doLicense", "(", "$", "metadata", ",", "$", "post_id", "=", "0", ",", "$", "title", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "title", ")", ")", "{", "_doing_it_wrong", "(", "__METHOD__", ",", "__", "(", "'$title is deprecated. Method will automatically determine title from licenses'", ",", "'pressbooks'", ")", ",", "'Pressbooks 5.7.0'", ")", ";", "}", "$", "book_license", "=", "isset", "(", "$", "metadata", "[", "'pb_book_license'", "]", ")", "?", "$", "metadata", "[", "'pb_book_license'", "]", ":", "''", ";", "if", "(", "empty", "(", "$", "post_id", ")", ")", "{", "// if no post $id given, set empty strings", "$", "section_license", "=", "''", ";", "$", "section_author", "=", "''", ";", "}", "else", "{", "$", "section_license", "=", "get_post_meta", "(", "$", "post_id", ",", "'pb_section_license'", ",", "true", ")", ";", "$", "section_author", "=", "(", "new", "Contributors", "(", ")", ")", "->", "get", "(", "$", "post_id", ",", "'pb_authors'", ")", ";", "}", "// Copyright license, set in order of precedence", "if", "(", "!", "empty", "(", "$", "section_license", ")", ")", "{", "// section copyright higher priority than book", "$", "license", "=", "$", "section_license", ";", "}", "elseif", "(", "!", "empty", "(", "$", "book_license", ")", ")", "{", "// book is the fallback, default", "$", "license", "=", "$", "book_license", ";", "}", "else", "{", "$", "license", "=", "'all-rights-reserved'", ";", "}", "if", "(", "!", "$", "this", "->", "isSupportedType", "(", "$", "license", ")", ")", "{", "// License not supported, bail", "return", "''", ";", "}", "// Unless section is licensed differently, it should display the book license statement", "if", "(", "$", "section_license", "===", "$", "book_license", "||", "empty", "(", "$", "section_license", ")", ")", "{", "$", "title", "=", "get_bloginfo", "(", "'name'", ")", ";", "$", "link", "=", "get_bloginfo", "(", "'url'", ")", ";", "}", "else", "{", "$", "post", "=", "get_post", "(", "$", "post_id", ")", ";", "$", "title", "=", "$", "post", "?", "$", "post", "->", "post_title", ":", "get_bloginfo", "(", "'name'", ")", ";", "$", "link", "=", "get_permalink", "(", "$", "post_id", ")", ";", "}", "// Copyright holder, set in order of precedence", "if", "(", "!", "empty", "(", "$", "section_author", ")", ")", "{", "// section author higher priority than book author, copyrightholder", "$", "copyright_holder", "=", "$", "section_author", ";", "}", "elseif", "(", "isset", "(", "$", "metadata", "[", "'pb_copyright_holder'", "]", ")", ")", "{", "// book copyright holder higher priority than book author", "$", "copyright_holder", "=", "$", "metadata", "[", "'pb_copyright_holder'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "metadata", "[", "'pb_authors'", "]", ")", ")", "{", "// book author is the fallback, default", "$", "copyright_holder", "=", "$", "metadata", "[", "'pb_authors'", "]", ";", "}", "else", "{", "$", "copyright_holder", "=", "''", ";", "}", "if", "(", "!", "empty", "(", "$", "metadata", "[", "'pb_copyright_year'", "]", ")", ")", "{", "$", "copyright_year", "=", "$", "metadata", "[", "'pb_copyright_year'", "]", ";", "}", "elseif", "(", "!", "empty", "(", "$", "metadata", "[", "'pb_publication_date'", "]", ")", ")", "{", "$", "copyright_year", "=", "strftime", "(", "'%Y'", ",", "absint", "(", "$", "metadata", "[", "'pb_publication_date'", "]", ")", ")", ";", "}", "else", "{", "$", "copyright_year", "=", "0", ";", "}", "$", "html", "=", "$", "this", "->", "getLicense", "(", "$", "license", ",", "$", "copyright_holder", ",", "$", "link", ",", "$", "title", ",", "$", "copyright_year", ")", ";", "return", "$", "html", ";", "}" ]
Will create an html blob of copyright information, returns empty string if license not supported @param array $metadata \Pressbooks\Book::getBookInformation @param int $post_id (optional) @param string $title (@deprecated) @return string
[ "Will", "create", "an", "html", "blob", "of", "copyright", "information", "returns", "empty", "string", "if", "license", "not", "supported" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L193-L258
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getLicenseXml
public function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang = '', $year = 0 ) { $endpoint = 'https://api.creativecommons.org/rest/1.5/'; $lang = ( ! empty( $lang ) ) ? substr( $lang, 0, 2 ) : ''; $expected = $this->getSupportedTypes(); if ( ! array_key_exists( $type, $expected ) ) { // nothing meaningful to hit the api with, so bail return ''; } if ( $type !== 'all-rights-reserved' && empty( $expected[ $type ]['api'] ) ) { // We don't know what to do with a custom license, use "all-rights-reserved" for now $type = 'all-rights-reserved'; } switch ( $type ) { // api doesn't have an 'all-rights-reserved' endpoint, so manual build necessary case 'all-rights-reserved': $xml = '<result><html>' . "<span property='dct:title'>" . Sanitize\sanitize_xml_attribute( $title ) . '</span> ' . __( 'Copyright', 'pressbooks' ) . ' &#169; '; if ( $year ) { $xml .= Sanitize\sanitize_xml_attribute( $year ) . ' ' . __( 'by', 'pressbooks' ) . ' '; } $xml .= Sanitize\sanitize_xml_attribute( $copyright_holder ); $xml .= '. ' . __( 'All Rights Reserved', 'pressbooks' ) . '.</html></result>'; break; default: $key = array_keys( $expected[ $type ]['api'] ); $val = array_values( $expected[ $type ]['api'] ); $url = $endpoint . $key[0] . '/' . $val[0] . '/get?' . $key[1] . '=' . $val[1] . '&' . $key[2] . '=' . $val[2] . '&creator=' . rawurlencode( $copyright_holder ) . '&attribution_url=' . rawurlencode( $src_url ) . '&title=' . rawurlencode( $title ) . '&locale=' . $lang; if ( $year ) { $url .= '&year=' . (int) $year; } $xml = wp_remote_get( $url ); $ok = wp_remote_retrieve_response_code( $xml ); if ( absint( $ok ) === 200 && is_wp_error( $xml ) === false ) { $xml = $xml['body']; } else { // Something went wrong, try to log it if ( is_wp_error( $xml ) ) { $error_message = $xml->get_error_message(); } elseif ( is_array( $xml ) && ! empty( $xml['body'] ) ) { $error_message = wp_strip_all_tags( $xml['body'] ); } else { $error_message = 'An unknown error occurred'; } debug_error_log( '\Pressbooks\Licensing::getLicenseXml() error: ' . $error_message ); $xml = ''; // Set empty string } break; } return $xml; }
php
public function getLicenseXml( $type, $copyright_holder, $src_url, $title, $lang = '', $year = 0 ) { $endpoint = 'https://api.creativecommons.org/rest/1.5/'; $lang = ( ! empty( $lang ) ) ? substr( $lang, 0, 2 ) : ''; $expected = $this->getSupportedTypes(); if ( ! array_key_exists( $type, $expected ) ) { // nothing meaningful to hit the api with, so bail return ''; } if ( $type !== 'all-rights-reserved' && empty( $expected[ $type ]['api'] ) ) { // We don't know what to do with a custom license, use "all-rights-reserved" for now $type = 'all-rights-reserved'; } switch ( $type ) { // api doesn't have an 'all-rights-reserved' endpoint, so manual build necessary case 'all-rights-reserved': $xml = '<result><html>' . "<span property='dct:title'>" . Sanitize\sanitize_xml_attribute( $title ) . '</span> ' . __( 'Copyright', 'pressbooks' ) . ' &#169; '; if ( $year ) { $xml .= Sanitize\sanitize_xml_attribute( $year ) . ' ' . __( 'by', 'pressbooks' ) . ' '; } $xml .= Sanitize\sanitize_xml_attribute( $copyright_holder ); $xml .= '. ' . __( 'All Rights Reserved', 'pressbooks' ) . '.</html></result>'; break; default: $key = array_keys( $expected[ $type ]['api'] ); $val = array_values( $expected[ $type ]['api'] ); $url = $endpoint . $key[0] . '/' . $val[0] . '/get?' . $key[1] . '=' . $val[1] . '&' . $key[2] . '=' . $val[2] . '&creator=' . rawurlencode( $copyright_holder ) . '&attribution_url=' . rawurlencode( $src_url ) . '&title=' . rawurlencode( $title ) . '&locale=' . $lang; if ( $year ) { $url .= '&year=' . (int) $year; } $xml = wp_remote_get( $url ); $ok = wp_remote_retrieve_response_code( $xml ); if ( absint( $ok ) === 200 && is_wp_error( $xml ) === false ) { $xml = $xml['body']; } else { // Something went wrong, try to log it if ( is_wp_error( $xml ) ) { $error_message = $xml->get_error_message(); } elseif ( is_array( $xml ) && ! empty( $xml['body'] ) ) { $error_message = wp_strip_all_tags( $xml['body'] ); } else { $error_message = 'An unknown error occurred'; } debug_error_log( '\Pressbooks\Licensing::getLicenseXml() error: ' . $error_message ); $xml = ''; // Set empty string } break; } return $xml; }
[ "public", "function", "getLicenseXml", "(", "$", "type", ",", "$", "copyright_holder", ",", "$", "src_url", ",", "$", "title", ",", "$", "lang", "=", "''", ",", "$", "year", "=", "0", ")", "{", "$", "endpoint", "=", "'https://api.creativecommons.org/rest/1.5/'", ";", "$", "lang", "=", "(", "!", "empty", "(", "$", "lang", ")", ")", "?", "substr", "(", "$", "lang", ",", "0", ",", "2", ")", ":", "''", ";", "$", "expected", "=", "$", "this", "->", "getSupportedTypes", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "$", "expected", ")", ")", "{", "// nothing meaningful to hit the api with, so bail", "return", "''", ";", "}", "if", "(", "$", "type", "!==", "'all-rights-reserved'", "&&", "empty", "(", "$", "expected", "[", "$", "type", "]", "[", "'api'", "]", ")", ")", "{", "// We don't know what to do with a custom license, use \"all-rights-reserved\" for now", "$", "type", "=", "'all-rights-reserved'", ";", "}", "switch", "(", "$", "type", ")", "{", "// api doesn't have an 'all-rights-reserved' endpoint, so manual build necessary", "case", "'all-rights-reserved'", ":", "$", "xml", "=", "'<result><html>'", ".", "\"<span property='dct:title'>\"", ".", "Sanitize", "\\", "sanitize_xml_attribute", "(", "$", "title", ")", ".", "'</span> '", ".", "__", "(", "'Copyright'", ",", "'pressbooks'", ")", ".", "' &#169; '", ";", "if", "(", "$", "year", ")", "{", "$", "xml", ".=", "Sanitize", "\\", "sanitize_xml_attribute", "(", "$", "year", ")", ".", "' '", ".", "__", "(", "'by'", ",", "'pressbooks'", ")", ".", "' '", ";", "}", "$", "xml", ".=", "Sanitize", "\\", "sanitize_xml_attribute", "(", "$", "copyright_holder", ")", ";", "$", "xml", ".=", "'. '", ".", "__", "(", "'All Rights Reserved'", ",", "'pressbooks'", ")", ".", "'.</html></result>'", ";", "break", ";", "default", ":", "$", "key", "=", "array_keys", "(", "$", "expected", "[", "$", "type", "]", "[", "'api'", "]", ")", ";", "$", "val", "=", "array_values", "(", "$", "expected", "[", "$", "type", "]", "[", "'api'", "]", ")", ";", "$", "url", "=", "$", "endpoint", ".", "$", "key", "[", "0", "]", ".", "'/'", ".", "$", "val", "[", "0", "]", ".", "'/get?'", ".", "$", "key", "[", "1", "]", ".", "'='", ".", "$", "val", "[", "1", "]", ".", "'&'", ".", "$", "key", "[", "2", "]", ".", "'='", ".", "$", "val", "[", "2", "]", ".", "'&creator='", ".", "rawurlencode", "(", "$", "copyright_holder", ")", ".", "'&attribution_url='", ".", "rawurlencode", "(", "$", "src_url", ")", ".", "'&title='", ".", "rawurlencode", "(", "$", "title", ")", ".", "'&locale='", ".", "$", "lang", ";", "if", "(", "$", "year", ")", "{", "$", "url", ".=", "'&year='", ".", "(", "int", ")", "$", "year", ";", "}", "$", "xml", "=", "wp_remote_get", "(", "$", "url", ")", ";", "$", "ok", "=", "wp_remote_retrieve_response_code", "(", "$", "xml", ")", ";", "if", "(", "absint", "(", "$", "ok", ")", "===", "200", "&&", "is_wp_error", "(", "$", "xml", ")", "===", "false", ")", "{", "$", "xml", "=", "$", "xml", "[", "'body'", "]", ";", "}", "else", "{", "// Something went wrong, try to log it", "if", "(", "is_wp_error", "(", "$", "xml", ")", ")", "{", "$", "error_message", "=", "$", "xml", "->", "get_error_message", "(", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "xml", ")", "&&", "!", "empty", "(", "$", "xml", "[", "'body'", "]", ")", ")", "{", "$", "error_message", "=", "wp_strip_all_tags", "(", "$", "xml", "[", "'body'", "]", ")", ";", "}", "else", "{", "$", "error_message", "=", "'An unknown error occurred'", ";", "}", "debug_error_log", "(", "'\\Pressbooks\\Licensing::getLicenseXml() error: '", ".", "$", "error_message", ")", ";", "$", "xml", "=", "''", ";", "// Set empty string", "}", "break", ";", "}", "return", "$", "xml", ";", "}" ]
Takes a known string from metadata, builds a url to hit an api which returns an xml response @see https://api.creativecommons.org/docs/readme_15.html @deprecated 5.3.0 @deprecated No longer used by internal code and no longer recommended. @param string $type license type @param string $copyright_holder of the page @param string $src_url of the page @param string $title of the page @param string $lang (optional) @param int $year (optional) @return string $xml response
[ "Takes", "a", "known", "string", "from", "metadata", "builds", "a", "url", "to", "hit", "an", "api", "which", "returns", "an", "xml", "response" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L277-L337
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getLicenseHtml
public function getLicenseHtml( \SimpleXMLElement $response, $except_where_otherwise_noted = true ) { $content = $response->asXML(); $content = trim( str_replace( [ '<p xmlns:dct="http://purl.org/dc/terms/">', '</p>', '<html>', '</html>' ], '', $content ) ); $content = preg_replace( '/http:\/\/i.creativecommons/iU', 'https://i.creativecommons', $content ); $html = '<div class="license-attribution" xmlns:cc="http://creativecommons.org/ns#"><p xmlns:dct="http://purl.org/dc/terms/">'; if ( $except_where_otherwise_noted ) { $html .= rtrim( $content, '.' ) . ', ' . __( 'except where otherwise noted.', 'pressbooks' ); } else { $html .= $content; } $html .= '</p></div>'; return html_entity_decode( $html, ENT_XHTML, 'UTF-8' ); }
php
public function getLicenseHtml( \SimpleXMLElement $response, $except_where_otherwise_noted = true ) { $content = $response->asXML(); $content = trim( str_replace( [ '<p xmlns:dct="http://purl.org/dc/terms/">', '</p>', '<html>', '</html>' ], '', $content ) ); $content = preg_replace( '/http:\/\/i.creativecommons/iU', 'https://i.creativecommons', $content ); $html = '<div class="license-attribution" xmlns:cc="http://creativecommons.org/ns#"><p xmlns:dct="http://purl.org/dc/terms/">'; if ( $except_where_otherwise_noted ) { $html .= rtrim( $content, '.' ) . ', ' . __( 'except where otherwise noted.', 'pressbooks' ); } else { $html .= $content; } $html .= '</p></div>'; return html_entity_decode( $html, ENT_XHTML, 'UTF-8' ); }
[ "public", "function", "getLicenseHtml", "(", "\\", "SimpleXMLElement", "$", "response", ",", "$", "except_where_otherwise_noted", "=", "true", ")", "{", "$", "content", "=", "$", "response", "->", "asXML", "(", ")", ";", "$", "content", "=", "trim", "(", "str_replace", "(", "[", "'<p xmlns:dct=\"http://purl.org/dc/terms/\">'", ",", "'</p>'", ",", "'<html>'", ",", "'</html>'", "]", ",", "''", ",", "$", "content", ")", ")", ";", "$", "content", "=", "preg_replace", "(", "'/http:\\/\\/i.creativecommons/iU'", ",", "'https://i.creativecommons'", ",", "$", "content", ")", ";", "$", "html", "=", "'<div class=\"license-attribution\" xmlns:cc=\"http://creativecommons.org/ns#\"><p xmlns:dct=\"http://purl.org/dc/terms/\">'", ";", "if", "(", "$", "except_where_otherwise_noted", ")", "{", "$", "html", ".=", "rtrim", "(", "$", "content", ",", "'.'", ")", ".", "', '", ".", "__", "(", "'except where otherwise noted.'", ",", "'pressbooks'", ")", ";", "}", "else", "{", "$", "html", ".=", "$", "content", ";", "}", "$", "html", ".=", "'</p></div>'", ";", "return", "html_entity_decode", "(", "$", "html", ",", "ENT_XHTML", ",", "'UTF-8'", ")", ";", "}" ]
Returns an HTML blob if given an XML object @deprecated 5.3.0 @deprecated No longer used by internal code and no longer recommended. @param \SimpleXMLElement $response @param $except_where_otherwise_noted bool (optional) @return string $html blob of copyright information
[ "Returns", "an", "HTML", "blob", "if", "given", "an", "XML", "object" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L350-L365
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getLicense
public function getLicense( $license, $copyright_holder, $link, $title, $copyright_year ) { if ( ! $this->isSupportedType( $license ) ) { return sprintf( '<div class="license-attribution"><p>%s</p></div>', sprintf( __( '%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.', 'pressbooks' ), $title, ( $copyright_year ) ? ' ' . $copyright_year : '', $copyright_holder ) ); } elseif ( $this->isSupportedType( $license ) ) { $name = $this->getNameForLicense( $license ); $url = $this->getUrlForLicense( $license ); if ( \Pressbooks\Utility\str_starts_with( $license, 'cc' ) && $license !== 'cc-zero' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s', 'pressbooks' ), $name ) ), sprintf( __( '%1$s by %2$s is licensed under a %3$s, except where otherwise noted.', 'pressbooks' ), sprintf( '<a rel="cc:attributionURL" href="%1$s" property="dc:title">%2$s</a>', $link, $title ), sprintf( '<span property="cc:attributionName">%1$s</span>', $copyright_holder ), sprintf( '<a rel="license" href="%1$s">%2$s</a>', $url, $name ) ) ); } elseif ( $license === 'all-rights-reserved' ) { return sprintf( '<div class="license-attribution"><p>%s</p></div>', sprintf( __( '%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.', 'pressbooks' ), sprintf( '<a href="%1$s" property="dc:title">%2$s</a>', $link, $title ), ( $copyright_year ) ? ' ' . $copyright_year : '', $copyright_holder ) ); } elseif ( $license === 'public-domain' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s license', 'pressbooks' ), $name ) ), sprintf( __( 'This work (%1$s by %2$s) is free of known copyright restrictions.', 'pressbooks' ), sprintf( '<a href="%1$s">%2$s</a>', $link, $title ), $copyright_holder ) ); } elseif ( $license === 'cc-zero' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s license', 'pressbooks' ), $name ) ), sprintf( translate_nooped_plural( _n_noop( 'To the extent possible under law, %1$s has waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.', 'To the extent possible under law, %1$s have waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.', 'pressbooks-book' ), count( oxford_comma_explode( $copyright_holder ) ), 'pressbooks' ), $copyright_holder, sprintf( '<a href="%1$s">%2$s</a>', $link, $title ) ) ); } } }
php
public function getLicense( $license, $copyright_holder, $link, $title, $copyright_year ) { if ( ! $this->isSupportedType( $license ) ) { return sprintf( '<div class="license-attribution"><p>%s</p></div>', sprintf( __( '%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.', 'pressbooks' ), $title, ( $copyright_year ) ? ' ' . $copyright_year : '', $copyright_holder ) ); } elseif ( $this->isSupportedType( $license ) ) { $name = $this->getNameForLicense( $license ); $url = $this->getUrlForLicense( $license ); if ( \Pressbooks\Utility\str_starts_with( $license, 'cc' ) && $license !== 'cc-zero' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s', 'pressbooks' ), $name ) ), sprintf( __( '%1$s by %2$s is licensed under a %3$s, except where otherwise noted.', 'pressbooks' ), sprintf( '<a rel="cc:attributionURL" href="%1$s" property="dc:title">%2$s</a>', $link, $title ), sprintf( '<span property="cc:attributionName">%1$s</span>', $copyright_holder ), sprintf( '<a rel="license" href="%1$s">%2$s</a>', $url, $name ) ) ); } elseif ( $license === 'all-rights-reserved' ) { return sprintf( '<div class="license-attribution"><p>%s</p></div>', sprintf( __( '%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.', 'pressbooks' ), sprintf( '<a href="%1$s" property="dc:title">%2$s</a>', $link, $title ), ( $copyright_year ) ? ' ' . $copyright_year : '', $copyright_holder ) ); } elseif ( $license === 'public-domain' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s license', 'pressbooks' ), $name ) ), sprintf( __( 'This work (%1$s by %2$s) is free of known copyright restrictions.', 'pressbooks' ), sprintf( '<a href="%1$s">%2$s</a>', $link, $title ), $copyright_holder ) ); } elseif ( $license === 'cc-zero' ) { return sprintf( '<div class="license-attribution"><p>%1$s</p><p>%2$s</p></div>', sprintf( '<img src="%1$s" alt="%2$s" />', get_template_directory_uri() . '/packages/buckram/assets/images/' . $license . '.svg', sprintf( __( 'Icon for the %s license', 'pressbooks' ), $name ) ), sprintf( translate_nooped_plural( _n_noop( 'To the extent possible under law, %1$s has waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.', 'To the extent possible under law, %1$s have waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.', 'pressbooks-book' ), count( oxford_comma_explode( $copyright_holder ) ), 'pressbooks' ), $copyright_holder, sprintf( '<a href="%1$s">%2$s</a>', $link, $title ) ) ); } } }
[ "public", "function", "getLicense", "(", "$", "license", ",", "$", "copyright_holder", ",", "$", "link", ",", "$", "title", ",", "$", "copyright_year", ")", "{", "if", "(", "!", "$", "this", "->", "isSupportedType", "(", "$", "license", ")", ")", "{", "return", "sprintf", "(", "'<div class=\"license-attribution\"><p>%s</p></div>'", ",", "sprintf", "(", "__", "(", "'%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.'", ",", "'pressbooks'", ")", ",", "$", "title", ",", "(", "$", "copyright_year", ")", "?", "' '", ".", "$", "copyright_year", ":", "''", ",", "$", "copyright_holder", ")", ")", ";", "}", "elseif", "(", "$", "this", "->", "isSupportedType", "(", "$", "license", ")", ")", "{", "$", "name", "=", "$", "this", "->", "getNameForLicense", "(", "$", "license", ")", ";", "$", "url", "=", "$", "this", "->", "getUrlForLicense", "(", "$", "license", ")", ";", "if", "(", "\\", "Pressbooks", "\\", "Utility", "\\", "str_starts_with", "(", "$", "license", ",", "'cc'", ")", "&&", "$", "license", "!==", "'cc-zero'", ")", "{", "return", "sprintf", "(", "'<div class=\"license-attribution\"><p>%1$s</p><p>%2$s</p></div>'", ",", "sprintf", "(", "'<img src=\"%1$s\" alt=\"%2$s\" />'", ",", "get_template_directory_uri", "(", ")", ".", "'/packages/buckram/assets/images/'", ".", "$", "license", ".", "'.svg'", ",", "sprintf", "(", "__", "(", "'Icon for the %s'", ",", "'pressbooks'", ")", ",", "$", "name", ")", ")", ",", "sprintf", "(", "__", "(", "'%1$s by %2$s is licensed under a %3$s, except where otherwise noted.'", ",", "'pressbooks'", ")", ",", "sprintf", "(", "'<a rel=\"cc:attributionURL\" href=\"%1$s\" property=\"dc:title\">%2$s</a>'", ",", "$", "link", ",", "$", "title", ")", ",", "sprintf", "(", "'<span property=\"cc:attributionName\">%1$s</span>'", ",", "$", "copyright_holder", ")", ",", "sprintf", "(", "'<a rel=\"license\" href=\"%1$s\">%2$s</a>'", ",", "$", "url", ",", "$", "name", ")", ")", ")", ";", "}", "elseif", "(", "$", "license", "===", "'all-rights-reserved'", ")", "{", "return", "sprintf", "(", "'<div class=\"license-attribution\"><p>%s</p></div>'", ",", "sprintf", "(", "__", "(", "'%1$s Copyright &copy;%2$s by %3$s. All Rights Reserved.'", ",", "'pressbooks'", ")", ",", "sprintf", "(", "'<a href=\"%1$s\" property=\"dc:title\">%2$s</a>'", ",", "$", "link", ",", "$", "title", ")", ",", "(", "$", "copyright_year", ")", "?", "' '", ".", "$", "copyright_year", ":", "''", ",", "$", "copyright_holder", ")", ")", ";", "}", "elseif", "(", "$", "license", "===", "'public-domain'", ")", "{", "return", "sprintf", "(", "'<div class=\"license-attribution\"><p>%1$s</p><p>%2$s</p></div>'", ",", "sprintf", "(", "'<img src=\"%1$s\" alt=\"%2$s\" />'", ",", "get_template_directory_uri", "(", ")", ".", "'/packages/buckram/assets/images/'", ".", "$", "license", ".", "'.svg'", ",", "sprintf", "(", "__", "(", "'Icon for the %s license'", ",", "'pressbooks'", ")", ",", "$", "name", ")", ")", ",", "sprintf", "(", "__", "(", "'This work (%1$s by %2$s) is free of known copyright restrictions.'", ",", "'pressbooks'", ")", ",", "sprintf", "(", "'<a href=\"%1$s\">%2$s</a>'", ",", "$", "link", ",", "$", "title", ")", ",", "$", "copyright_holder", ")", ")", ";", "}", "elseif", "(", "$", "license", "===", "'cc-zero'", ")", "{", "return", "sprintf", "(", "'<div class=\"license-attribution\"><p>%1$s</p><p>%2$s</p></div>'", ",", "sprintf", "(", "'<img src=\"%1$s\" alt=\"%2$s\" />'", ",", "get_template_directory_uri", "(", ")", ".", "'/packages/buckram/assets/images/'", ".", "$", "license", ".", "'.svg'", ",", "sprintf", "(", "__", "(", "'Icon for the %s license'", ",", "'pressbooks'", ")", ",", "$", "name", ")", ")", ",", "sprintf", "(", "translate_nooped_plural", "(", "_n_noop", "(", "'To the extent possible under law, %1$s has waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.'", ",", "'To the extent possible under law, %1$s have waived all copyright and related or neighboring rights to %2$s, except where otherwise noted.'", ",", "'pressbooks-book'", ")", ",", "count", "(", "oxford_comma_explode", "(", "$", "copyright_holder", ")", ")", ",", "'pressbooks'", ")", ",", "$", "copyright_holder", ",", "sprintf", "(", "'<a href=\"%1$s\">%2$s</a>'", ",", "$", "link", ",", "$", "title", ")", ")", ")", ";", "}", "}", "}" ]
Returns an HTML blob for a supported license. @since 5.3.0 @param string $license license type @param string $copyright_holder of the page @param string $link of the page @param string $title of the page @param int $copyright_year (optional) @return string $html License blob.
[ "Returns", "an", "HTML", "blob", "for", "a", "supported", "license", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L380-L445
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getLicenseFromUrl
public function getLicenseFromUrl( $url ) { $licenses = $this->getSupportedTypes(); foreach ( $licenses as $license => $v ) { if ( $url === $v['url'] ) { return $license; } } return 'all-rights-reserved'; }
php
public function getLicenseFromUrl( $url ) { $licenses = $this->getSupportedTypes(); foreach ( $licenses as $license => $v ) { if ( $url === $v['url'] ) { return $license; } } return 'all-rights-reserved'; }
[ "public", "function", "getLicenseFromUrl", "(", "$", "url", ")", "{", "$", "licenses", "=", "$", "this", "->", "getSupportedTypes", "(", ")", ";", "foreach", "(", "$", "licenses", "as", "$", "license", "=>", "$", "v", ")", "{", "if", "(", "$", "url", "===", "$", "v", "[", "'url'", "]", ")", "{", "return", "$", "license", ";", "}", "}", "return", "'all-rights-reserved'", ";", "}" ]
Returns Book Information-compatible license value from URL. @since 4.1.0 @param string @return string
[ "Returns", "Book", "Information", "-", "compatible", "license", "value", "from", "URL", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L473-L482
pressbooks/pressbooks
inc/class-licensing.php
Licensing.getNameForLicense
public function getNameForLicense( $license ) { $types = $this->getSupportedTypes(); if ( $this->isSupportedType( $license ) ) { if ( isset( $types[ $license ]['longdesc'] ) ) { return $types[ $license ]['longdesc']; } else { return $types[ $license ]['desc']; } } else { return $types['all-rights-reserved']['desc']; } }
php
public function getNameForLicense( $license ) { $types = $this->getSupportedTypes(); if ( $this->isSupportedType( $license ) ) { if ( isset( $types[ $license ]['longdesc'] ) ) { return $types[ $license ]['longdesc']; } else { return $types[ $license ]['desc']; } } else { return $types['all-rights-reserved']['desc']; } }
[ "public", "function", "getNameForLicense", "(", "$", "license", ")", "{", "$", "types", "=", "$", "this", "->", "getSupportedTypes", "(", ")", ";", "if", "(", "$", "this", "->", "isSupportedType", "(", "$", "license", ")", ")", "{", "if", "(", "isset", "(", "$", "types", "[", "$", "license", "]", "[", "'longdesc'", "]", ")", ")", "{", "return", "$", "types", "[", "$", "license", "]", "[", "'longdesc'", "]", ";", "}", "else", "{", "return", "$", "types", "[", "$", "license", "]", "[", "'desc'", "]", ";", "}", "}", "else", "{", "return", "$", "types", "[", "'all-rights-reserved'", "]", "[", "'desc'", "]", ";", "}", "}" ]
Returns long description for saved license value. @since 5.3.0 @param string @return string
[ "Returns", "long", "description", "for", "saved", "license", "value", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-licensing.php#L493-L505
pressbooks/pressbooks
inc/class-styles.php
Styles.init
public function init() { if ( ! Book::isBook() ) { // Not a book, disable return; } if ( class_exists( '\Pressbooks\CustomCss' ) && CustomCss::isCustomCss() ) { // Uses old Custom CSS Editor, disable return; } // Code Mirror if ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === $this::PAGE ) { add_action( 'admin_enqueue_scripts', function () { wp_enqueue_script( 'wp-codemirror' ); wp_enqueue_script( 'csslint' ); wp_enqueue_style( 'wp-codemirror' ); } ); } add_action( 'init', function () { // Admin Menu add_action( 'admin_menu', function () { add_theme_page( __( 'Custom Styles', 'pressbooks' ), __( 'Custom Styles', 'pressbooks' ), 'edit_others_posts', $this::PAGE, [ $this, 'editor' ] ); }, 11 ); // Register Post Types $this->registerPosts(); } ); // Catch form submission add_action( 'init', [ $this, 'formSubmit' ], 50 ); }
php
public function init() { if ( ! Book::isBook() ) { // Not a book, disable return; } if ( class_exists( '\Pressbooks\CustomCss' ) && CustomCss::isCustomCss() ) { // Uses old Custom CSS Editor, disable return; } // Code Mirror if ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === $this::PAGE ) { add_action( 'admin_enqueue_scripts', function () { wp_enqueue_script( 'wp-codemirror' ); wp_enqueue_script( 'csslint' ); wp_enqueue_style( 'wp-codemirror' ); } ); } add_action( 'init', function () { // Admin Menu add_action( 'admin_menu', function () { add_theme_page( __( 'Custom Styles', 'pressbooks' ), __( 'Custom Styles', 'pressbooks' ), 'edit_others_posts', $this::PAGE, [ $this, 'editor' ] ); }, 11 ); // Register Post Types $this->registerPosts(); } ); // Catch form submission add_action( 'init', [ $this, 'formSubmit' ], 50 ); }
[ "public", "function", "init", "(", ")", "{", "if", "(", "!", "Book", "::", "isBook", "(", ")", ")", "{", "// Not a book, disable", "return", ";", "}", "if", "(", "class_exists", "(", "'\\Pressbooks\\CustomCss'", ")", "&&", "CustomCss", "::", "isCustomCss", "(", ")", ")", "{", "// Uses old Custom CSS Editor, disable", "return", ";", "}", "// Code Mirror", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'page'", "]", ")", "&&", "$", "_REQUEST", "[", "'page'", "]", "===", "$", "this", "::", "PAGE", ")", "{", "add_action", "(", "'admin_enqueue_scripts'", ",", "function", "(", ")", "{", "wp_enqueue_script", "(", "'wp-codemirror'", ")", ";", "wp_enqueue_script", "(", "'csslint'", ")", ";", "wp_enqueue_style", "(", "'wp-codemirror'", ")", ";", "}", ")", ";", "}", "add_action", "(", "'init'", ",", "function", "(", ")", "{", "// Admin Menu", "add_action", "(", "'admin_menu'", ",", "function", "(", ")", "{", "add_theme_page", "(", "__", "(", "'Custom Styles'", ",", "'pressbooks'", ")", ",", "__", "(", "'Custom Styles'", ",", "'pressbooks'", ")", ",", "'edit_others_posts'", ",", "$", "this", "::", "PAGE", ",", "[", "$", "this", ",", "'editor'", "]", ")", ";", "}", ",", "11", ")", ";", "// Register Post Types", "$", "this", "->", "registerPosts", "(", ")", ";", "}", ")", ";", "// Catch form submission", "add_action", "(", "'init'", ",", "[", "$", "this", ",", "'formSubmit'", "]", ",", "50", ")", ";", "}" ]
Set filters & hooks
[ "Set", "filters", "&", "hooks" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-styles.php#L63-L100
pressbooks/pressbooks
inc/class-styles.php
Styles.initPosts
public function initPosts() { /** @var $wpdb \wpdb */ global $wpdb; $posts = [ [ 'post_title' => __( 'Custom Style for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-style', ], [ 'post_title' => __( 'Custom Style for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-style', ], [ 'post_title' => __( 'Custom Style for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-style', ], ]; $post = [ 'post_status' => 'publish', 'post_author' => wp_get_current_user()->ID, ]; foreach ( $posts as $item ) { $exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", [ $item['post_title'], $item['post_type'], $item['post_name'] ] ) ); if ( empty( $exists ) ) { $data = array_merge( $item, $post ); wp_insert_post( $data ); } } }
php
public function initPosts() { /** @var $wpdb \wpdb */ global $wpdb; $posts = [ [ 'post_title' => __( 'Custom Style for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-style', ], [ 'post_title' => __( 'Custom Style for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-style', ], [ 'post_title' => __( 'Custom Style for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-style', ], ]; $post = [ 'post_status' => 'publish', 'post_author' => wp_get_current_user()->ID, ]; foreach ( $posts as $item ) { $exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' ", [ $item['post_title'], $item['post_type'], $item['post_name'] ] ) ); if ( empty( $exists ) ) { $data = array_merge( $item, $post ); wp_insert_post( $data ); } } }
[ "public", "function", "initPosts", "(", ")", "{", "/** @var $wpdb \\wpdb */", "global", "$", "wpdb", ";", "$", "posts", "=", "[", "[", "'post_title'", "=>", "__", "(", "'Custom Style for Ebook'", ",", "'pressbooks'", ")", ",", "'post_name'", "=>", "'epub'", ",", "'post_type'", "=>", "'custom-style'", ",", "]", ",", "[", "'post_title'", "=>", "__", "(", "'Custom Style for PDF'", ",", "'pressbooks'", ")", ",", "'post_name'", "=>", "'prince'", ",", "'post_type'", "=>", "'custom-style'", ",", "]", ",", "[", "'post_title'", "=>", "__", "(", "'Custom Style for Web'", ",", "'pressbooks'", ")", ",", "'post_name'", "=>", "'web'", ",", "'post_type'", "=>", "'custom-style'", ",", "]", ",", "]", ";", "$", "post", "=", "[", "'post_status'", "=>", "'publish'", ",", "'post_author'", "=>", "wp_get_current_user", "(", ")", "->", "ID", ",", "]", ";", "foreach", "(", "$", "posts", "as", "$", "item", ")", "{", "$", "exists", "=", "$", "wpdb", "->", "get_var", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = %s AND post_name = %s AND post_status = 'publish' \"", ",", "[", "$", "item", "[", "'post_title'", "]", ",", "$", "item", "[", "'post_type'", "]", ",", "$", "item", "[", "'post_name'", "]", "]", ")", ")", ";", "if", "(", "empty", "(", "$", "exists", ")", ")", "{", "$", "data", "=", "array_merge", "(", "$", "item", ",", "$", "post", ")", ";", "wp_insert_post", "(", "$", "data", ")", ";", "}", "}", "}" ]
Custom style rules will be saved in a custom post type: custom-style
[ "Custom", "style", "rules", "will", "be", "saved", "in", "a", "custom", "post", "type", ":", "custom", "-", "style" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-styles.php#L105-L145
pressbooks/pressbooks
inc/class-styles.php
Styles.registerPosts
public function registerPosts() { $args = [ 'exclude_from_search' => true, 'public' => false, 'publicly_queryable' => false, 'show_ui' => false, 'supports' => [ 'revisions' ], 'label' => 'Custom Style', 'can_export' => false, 'rewrite' => false, 'capability_type' => 'page', 'capabilities' => [ 'edit_post' => 'edit_others_posts', 'read_post' => 'read', 'delete_post' => 'edit_others_posts', 'edit_posts' => 'edit_others_posts', 'edit_others_posts' => 'edit_others_posts', 'publish_posts' => 'edit_others_posts', 'read_private_posts' => 'read', ], ]; register_post_type( 'custom-style', $args ); }
php
public function registerPosts() { $args = [ 'exclude_from_search' => true, 'public' => false, 'publicly_queryable' => false, 'show_ui' => false, 'supports' => [ 'revisions' ], 'label' => 'Custom Style', 'can_export' => false, 'rewrite' => false, 'capability_type' => 'page', 'capabilities' => [ 'edit_post' => 'edit_others_posts', 'read_post' => 'read', 'delete_post' => 'edit_others_posts', 'edit_posts' => 'edit_others_posts', 'edit_others_posts' => 'edit_others_posts', 'publish_posts' => 'edit_others_posts', 'read_private_posts' => 'read', ], ]; register_post_type( 'custom-style', $args ); }
[ "public", "function", "registerPosts", "(", ")", "{", "$", "args", "=", "[", "'exclude_from_search'", "=>", "true", ",", "'public'", "=>", "false", ",", "'publicly_queryable'", "=>", "false", ",", "'show_ui'", "=>", "false", ",", "'supports'", "=>", "[", "'revisions'", "]", ",", "'label'", "=>", "'Custom Style'", ",", "'can_export'", "=>", "false", ",", "'rewrite'", "=>", "false", ",", "'capability_type'", "=>", "'page'", ",", "'capabilities'", "=>", "[", "'edit_post'", "=>", "'edit_others_posts'", ",", "'read_post'", "=>", "'read'", ",", "'delete_post'", "=>", "'edit_others_posts'", ",", "'edit_posts'", "=>", "'edit_others_posts'", ",", "'edit_others_posts'", "=>", "'edit_others_posts'", ",", "'publish_posts'", "=>", "'edit_others_posts'", ",", "'read_private_posts'", "=>", "'read'", ",", "]", ",", "]", ";", "register_post_type", "(", "'custom-style'", ",", "$", "args", ")", ";", "}" ]
Custom style rules will be saved in a custom post type: custom-style
[ "Custom", "style", "rules", "will", "be", "saved", "in", "a", "custom", "post", "type", ":", "custom", "-", "style" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-styles.php#L150-L172
pressbooks/pressbooks
inc/class-styles.php
Styles.getPost
public function getPost( $slug ) { // Supported post names (ie. slugs) $supported = array_keys( $this->supported ); if ( ! in_array( $slug, $supported, true ) ) { return false; } $args = [ 'name' => $slug, 'post_type' => 'custom-style', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return false; } return $results[0]; }
php
public function getPost( $slug ) { // Supported post names (ie. slugs) $supported = array_keys( $this->supported ); if ( ! in_array( $slug, $supported, true ) ) { return false; } $args = [ 'name' => $slug, 'post_type' => 'custom-style', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return false; } return $results[0]; }
[ "public", "function", "getPost", "(", "$", "slug", ")", "{", "// Supported post names (ie. slugs)", "$", "supported", "=", "array_keys", "(", "$", "this", "->", "supported", ")", ";", "if", "(", "!", "in_array", "(", "$", "slug", ",", "$", "supported", ",", "true", ")", ")", "{", "return", "false", ";", "}", "$", "args", "=", "[", "'name'", "=>", "$", "slug", ",", "'post_type'", "=>", "'custom-style'", ",", "'posts_per_page'", "=>", "1", ",", "'post_status'", "=>", "'publish'", ",", "'orderby'", "=>", "'modified'", ",", "'no_found_rows'", "=>", "true", ",", "'cache_results'", "=>", "true", ",", "]", ";", "$", "q", "=", "new", "\\", "WP_Query", "(", ")", ";", "$", "results", "=", "$", "q", "->", "query", "(", "$", "args", ")", ";", "if", "(", "empty", "(", "$", "results", ")", ")", "{", "return", "false", ";", "}", "return", "$", "results", "[", "0", "]", ";", "}" ]
@param string $slug post_name @return \WP_Post|false
[ "@param", "string", "$slug", "post_name" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-styles.php#L200-L226
pressbooks/pressbooks
inc/class-styles.php
Styles.getPathToScss
public function getPathToScss( $type, $theme = null ) { if ( null === $theme ) { $theme = wp_get_theme(); } if ( $this->isCurrentThemeCompatible( 1, $theme ) ) { if ( 'web' === $type ) { $path_to_style = realpath( $this->getDir( $theme ) . '/style.scss' ); } else { $path_to_style = realpath( $this->getDir( $theme ) . "/export/$type/style.scss" ); } } elseif ( $this->isCurrentThemeCompatible( 2, $theme ) ) { $path_to_style = realpath( $this->getDir( $theme ) . "/assets/styles/$type/style.scss" ); } else { $path_to_style = false; } return $path_to_style; }
php
public function getPathToScss( $type, $theme = null ) { if ( null === $theme ) { $theme = wp_get_theme(); } if ( $this->isCurrentThemeCompatible( 1, $theme ) ) { if ( 'web' === $type ) { $path_to_style = realpath( $this->getDir( $theme ) . '/style.scss' ); } else { $path_to_style = realpath( $this->getDir( $theme ) . "/export/$type/style.scss" ); } } elseif ( $this->isCurrentThemeCompatible( 2, $theme ) ) { $path_to_style = realpath( $this->getDir( $theme ) . "/assets/styles/$type/style.scss" ); } else { $path_to_style = false; } return $path_to_style; }
[ "public", "function", "getPathToScss", "(", "$", "type", ",", "$", "theme", "=", "null", ")", "{", "if", "(", "null", "===", "$", "theme", ")", "{", "$", "theme", "=", "wp_get_theme", "(", ")", ";", "}", "if", "(", "$", "this", "->", "isCurrentThemeCompatible", "(", "1", ",", "$", "theme", ")", ")", "{", "if", "(", "'web'", "===", "$", "type", ")", "{", "$", "path_to_style", "=", "realpath", "(", "$", "this", "->", "getDir", "(", "$", "theme", ")", ".", "'/style.scss'", ")", ";", "}", "else", "{", "$", "path_to_style", "=", "realpath", "(", "$", "this", "->", "getDir", "(", "$", "theme", ")", ".", "\"/export/$type/style.scss\"", ")", ";", "}", "}", "elseif", "(", "$", "this", "->", "isCurrentThemeCompatible", "(", "2", ",", "$", "theme", ")", ")", "{", "$", "path_to_style", "=", "realpath", "(", "$", "this", "->", "getDir", "(", "$", "theme", ")", ".", "\"/assets/styles/$type/style.scss\"", ")", ";", "}", "else", "{", "$", "path_to_style", "=", "false", ";", "}", "return", "$", "path_to_style", ";", "}" ]
Fullpath to SCSS file @param string $type @param \WP_Theme $theme (optional) @return string|false
[ "Fullpath", "to", "SCSS", "file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-styles.php#L295-L314