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/class-catalog.php
Catalog.formSubmit
static function formSubmit() { if ( empty( static::isFormSubmission() ) || empty( current_user_can( 'read' ) ) ) { // Don't do anything in this function, bail. return; } if ( static::isCurrentAction( 'add' ) ) { static::formBulk( 'add' ); } elseif ( static::isCurrentAction( 'remove' ) ) { static::formBulk( 'remove' ); } elseif ( static::isCurrentAction( 'edit_tags' ) ) { static::formTags(); } elseif ( static::isCurrentAction( 'edit_profile' ) ) { static::formProfile(); } elseif ( ! empty( $_REQUEST['add_book_by_url'] ) ) { static::formAddByUrl(); } }
php
static function formSubmit() { if ( empty( static::isFormSubmission() ) || empty( current_user_can( 'read' ) ) ) { // Don't do anything in this function, bail. return; } if ( static::isCurrentAction( 'add' ) ) { static::formBulk( 'add' ); } elseif ( static::isCurrentAction( 'remove' ) ) { static::formBulk( 'remove' ); } elseif ( static::isCurrentAction( 'edit_tags' ) ) { static::formTags(); } elseif ( static::isCurrentAction( 'edit_profile' ) ) { static::formProfile(); } elseif ( ! empty( $_REQUEST['add_book_by_url'] ) ) { static::formAddByUrl(); } }
[ "static", "function", "formSubmit", "(", ")", "{", "if", "(", "empty", "(", "static", "::", "isFormSubmission", "(", ")", ")", "||", "empty", "(", "current_user_can", "(", "'read'", ")", ")", ")", "{", "// Don't do anything in this function, bail.", "return", ...
Catch me
[ "Catch", "me" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1035-L1054
pressbooks/pressbooks
inc/class-catalog.php
Catalog.isFormSubmission
static function isFormSubmission() { if ( empty( $_REQUEST['page'] ) ) { return false; } if ( 'pb_catalog' !== $_REQUEST['page'] ) { return false; } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } if ( static::isCurrentAction( 'add' ) || static::isCurrentAction( 'remove' ) ) { return true; } return false; }
php
static function isFormSubmission() { if ( empty( $_REQUEST['page'] ) ) { return false; } if ( 'pb_catalog' !== $_REQUEST['page'] ) { return false; } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { return true; } if ( static::isCurrentAction( 'add' ) || static::isCurrentAction( 'remove' ) ) { return true; } return false; }
[ "static", "function", "isFormSubmission", "(", ")", "{", "if", "(", "empty", "(", "$", "_REQUEST", "[", "'page'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "'pb_catalog'", "!==", "$", "_REQUEST", "[", "'page'", "]", ")", "{", "retur...
Check if a user submitted something to index.php?page=pb_catalog @return bool
[ "Check", "if", "a", "user", "submitted", "something", "to", "index", ".", "php?page", "=", "pb_catalog" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1062-L1081
pressbooks/pressbooks
inc/class-catalog.php
Catalog.isCurrentAction
static function isCurrentAction( $action ) { if ( isset( $_REQUEST['action'] ) && -1 !== (int) $_REQUEST['action'] ) { $compare = $_REQUEST['action']; } elseif ( isset( $_REQUEST['action2'] ) && -1 !== (int) $_REQUEST['action2'] ) { $compare = $_REQUEST['action2']; } else { return false; } return ( $action === $compare ); }
php
static function isCurrentAction( $action ) { if ( isset( $_REQUEST['action'] ) && -1 !== (int) $_REQUEST['action'] ) { $compare = $_REQUEST['action']; } elseif ( isset( $_REQUEST['action2'] ) && -1 !== (int) $_REQUEST['action2'] ) { $compare = $_REQUEST['action2']; } else { return false; } return ( $action === $compare ); }
[ "static", "function", "isCurrentAction", "(", "$", "action", ")", "{", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'action'", "]", ")", "&&", "-", "1", "!==", "(", "int", ")", "$", "_REQUEST", "[", "'action'", "]", ")", "{", "$", "compare", "="...
Two actions are possible in a generic WP_List_Table form. The first takes precedence. @param $action @see \WP_List_Table::current_action @return bool
[ "Two", "actions", "are", "possible", "in", "a", "generic", "WP_List_Table", "form", ".", "The", "first", "takes", "precedence", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1093-L1104
pressbooks/pressbooks
inc/class-catalog.php
Catalog.deleteLogo
static function deleteLogo() { check_ajax_referer( 'pb-delete-catalog-logo' ); $image_url = $_POST['filename']; $user_id = (int) $_POST['pid']; $book = get_active_blog_for_user( $user_id ); if ( current_user_can_for_blog( $book->blog_id, 'upload_files' ) ) { switch_to_blog( $book->blog_id ); // Delete old images $old_id = \Pressbooks\Image\attachment_id_from_url( $image_url ); if ( $old_id ) { wp_delete_attachment( $old_id, true ); } update_user_meta( $user_id, 'pb_catalog_logo', \Pressbooks\Image\default_cover_url() ); restore_current_blog(); } // @see http://codex.wordpress.org/AJAX_in_Plugins#Error_Return_Values // Will append 0 to returned json string if we don't die() die(); }
php
static function deleteLogo() { check_ajax_referer( 'pb-delete-catalog-logo' ); $image_url = $_POST['filename']; $user_id = (int) $_POST['pid']; $book = get_active_blog_for_user( $user_id ); if ( current_user_can_for_blog( $book->blog_id, 'upload_files' ) ) { switch_to_blog( $book->blog_id ); // Delete old images $old_id = \Pressbooks\Image\attachment_id_from_url( $image_url ); if ( $old_id ) { wp_delete_attachment( $old_id, true ); } update_user_meta( $user_id, 'pb_catalog_logo', \Pressbooks\Image\default_cover_url() ); restore_current_blog(); } // @see http://codex.wordpress.org/AJAX_in_Plugins#Error_Return_Values // Will append 0 to returned json string if we don't die() die(); }
[ "static", "function", "deleteLogo", "(", ")", "{", "check_ajax_referer", "(", "'pb-delete-catalog-logo'", ")", ";", "$", "image_url", "=", "$", "_POST", "[", "'filename'", "]", ";", "$", "user_id", "=", "(", "int", ")", "$", "_POST", "[", "'pid'", "]", "...
WP_Ajax hook for pb_delete_catalog_logo
[ "WP_Ajax", "hook", "for", "pb_delete_catalog_logo" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1110-L1136
pressbooks/pressbooks
inc/class-catalog.php
Catalog.formBulk
protected static function formBulk( $action ) { if ( ! class_exists( '\WP_List_Table' ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); $redirect_url = Admin\Catalog_List_Table::addSearchParamsToUrl( $redirect_url ); /* Sanity check */ if ( ! empty( $_REQUEST['book'] ) ) { // Bulk check_admin_referer( 'bulk-books' ); // Nonce auto-generated by WP_List_Table $books = $_REQUEST['book']; } elseif ( ! empty( $_REQUEST['ID'] ) ) { // Single item check_admin_referer( $_REQUEST['ID'] ); $books = [ $_REQUEST['ID'] ]; } else { // Handle empty bulk submission if ( ! empty( $_REQUEST['user_id'] ) ) { $redirect_url .= '&user_id=' . $_REQUEST['user_id']; } \Pressbooks\Redirect\location( $redirect_url ); } // Make an educated guess as to who's catalog we are editing list( $user_id, $_ ) = explode( ':', $books[0] ); if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Fix redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url .= '&user_id=' . $user_id; } /* Go! */ $catalog = new static( $user_id ); foreach ( $books as $book ) { list( $_, $book_id ) = explode( ':', $book ); if ( 'add' === $action ) { $catalog->saveBook( $book_id, [] ); } elseif ( 'remove' === $action ) { $catalog->deleteBook( $book_id ); } else { // TODO: Throw Error $_SESSION['pb_errors'][] = "Invalid action: $action"; } } $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
php
protected static function formBulk( $action ) { if ( ! class_exists( '\WP_List_Table' ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); $redirect_url = Admin\Catalog_List_Table::addSearchParamsToUrl( $redirect_url ); /* Sanity check */ if ( ! empty( $_REQUEST['book'] ) ) { // Bulk check_admin_referer( 'bulk-books' ); // Nonce auto-generated by WP_List_Table $books = $_REQUEST['book']; } elseif ( ! empty( $_REQUEST['ID'] ) ) { // Single item check_admin_referer( $_REQUEST['ID'] ); $books = [ $_REQUEST['ID'] ]; } else { // Handle empty bulk submission if ( ! empty( $_REQUEST['user_id'] ) ) { $redirect_url .= '&user_id=' . $_REQUEST['user_id']; } \Pressbooks\Redirect\location( $redirect_url ); } // Make an educated guess as to who's catalog we are editing list( $user_id, $_ ) = explode( ':', $books[0] ); if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Fix redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url .= '&user_id=' . $user_id; } /* Go! */ $catalog = new static( $user_id ); foreach ( $books as $book ) { list( $_, $book_id ) = explode( ':', $book ); if ( 'add' === $action ) { $catalog->saveBook( $book_id, [] ); } elseif ( 'remove' === $action ) { $catalog->deleteBook( $book_id ); } else { // TODO: Throw Error $_SESSION['pb_errors'][] = "Invalid action: $action"; } } $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
[ "protected", "static", "function", "formBulk", "(", "$", "action", ")", "{", "if", "(", "!", "class_exists", "(", "'\\WP_List_Table'", ")", ")", "{", "require_once", "(", "ABSPATH", ".", "'wp-admin/includes/class-wp-list-table.php'", ")", ";", "}", "$", "redirec...
Save bulk actions @param $action
[ "Save", "bulk", "actions" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1144-L1206
pressbooks/pressbooks
inc/class-catalog.php
Catalog.formTags
protected static function formTags() { check_admin_referer( 'pb-user-catalog' ); if ( ! empty( $_REQUEST['ID'] ) ) { list( $user_id, $blog_id ) = explode( ':', $_REQUEST['ID'] ); } else { $user_id = ''; $blog_id = ''; } if ( ! empty( $_REQUEST['user_id'] ) ) { $user_id = absint( $_REQUEST['user_id'] ); } if ( ! empty( $_REQUEST['blog_id'] ) ) { $blog_id = absint( $_REQUEST['blog_id'] ); } if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } /* Go! */ $catalog = new static( $user_id ); $featured = ( isset( $_REQUEST['featured'] ) ) ? absint( $_REQUEST['featured'] ) : 0; $catalog->saveBook( $blog_id, [ 'featured' => $featured, ] ); // Tags for ( $i = 1; $i <= self::MAX_TAGS_GROUP; ++$i ) { $catalog->deleteTags( $blog_id, $i ); $tags = ( isset( $_REQUEST[ "tags_$i" ] ) ) ? $_REQUEST[ "tags_$i" ] : []; foreach ( $tags as $tag ) { $catalog->saveTag( $tag, $blog_id, $i ); } } $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
php
protected static function formTags() { check_admin_referer( 'pb-user-catalog' ); if ( ! empty( $_REQUEST['ID'] ) ) { list( $user_id, $blog_id ) = explode( ':', $_REQUEST['ID'] ); } else { $user_id = ''; $blog_id = ''; } if ( ! empty( $_REQUEST['user_id'] ) ) { $user_id = absint( $_REQUEST['user_id'] ); } if ( ! empty( $_REQUEST['blog_id'] ) ) { $blog_id = absint( $_REQUEST['blog_id'] ); } if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } /* Go! */ $catalog = new static( $user_id ); $featured = ( isset( $_REQUEST['featured'] ) ) ? absint( $_REQUEST['featured'] ) : 0; $catalog->saveBook( $blog_id, [ 'featured' => $featured, ] ); // Tags for ( $i = 1; $i <= self::MAX_TAGS_GROUP; ++$i ) { $catalog->deleteTags( $blog_id, $i ); $tags = ( isset( $_REQUEST[ "tags_$i" ] ) ) ? $_REQUEST[ "tags_$i" ] : []; foreach ( $tags as $tag ) { $catalog->saveTag( $tag, $blog_id, $i ); } } $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
[ "protected", "static", "function", "formTags", "(", ")", "{", "check_admin_referer", "(", "'pb-user-catalog'", ")", ";", "if", "(", "!", "empty", "(", "$", "_REQUEST", "[", "'ID'", "]", ")", ")", "{", "list", "(", "$", "user_id", ",", "$", "blog_id", "...
Save tags to database
[ "Save", "tags", "to", "database" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1212-L1265
pressbooks/pressbooks
inc/class-catalog.php
Catalog.formProfile
protected static function formProfile() { check_admin_referer( 'pb-user-catalog' ); $user_id = isset( $_REQUEST['user_id'] ) ? absint( $_REQUEST['user_id'] ) : 0; if ( empty( $user_id ) || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } /* Go! */ $catalog = new static( $user_id ); $catalog->saveProfile( $_POST ); $catalog->uploadLogo( 'pb_catalog_logo' ); $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
php
protected static function formProfile() { check_admin_referer( 'pb-user-catalog' ); $user_id = isset( $_REQUEST['user_id'] ) ? absint( $_REQUEST['user_id'] ) : 0; if ( empty( $user_id ) || ! current_user_can( 'edit_user', $user_id ) ) { wp_die( __( 'You do not have permission to do that.', 'pressbooks' ) ); } // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } /* Go! */ $catalog = new static( $user_id ); $catalog->saveProfile( $_POST ); $catalog->uploadLogo( 'pb_catalog_logo' ); $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
[ "protected", "static", "function", "formProfile", "(", ")", "{", "check_admin_referer", "(", "'pb-user-catalog'", ")", ";", "$", "user_id", "=", "isset", "(", "$", "_REQUEST", "[", "'user_id'", "]", ")", "?", "absint", "(", "$", "_REQUEST", "[", "'user_id'",...
Save catalog profile to database
[ "Save", "catalog", "profile", "to", "database" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1271-L1301
pressbooks/pressbooks
inc/class-catalog.php
Catalog.formAddByUrl
static function formAddByUrl() { check_admin_referer( 'bulk-books' ); // Nonce auto-generated by WP_List_Table $catalog = new static(); $user_id = $catalog->getUserId(); // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } $url = wp_parse_url( \Pressbooks\Sanitize\canonicalize_url( $_REQUEST['add_book_by_url'] ) ); $main = wp_parse_url( network_home_url() ); if ( strpos( $url['host'], $main['host'] ) === false ) { $_SESSION['pb_errors'][] = __( 'Invalid URL.', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } if ( $url['host'] === $main['host'] ) { // Get slug using the path $slug = str_replace( $main['path'], '', $url['path'] ); $slug = trim( $slug, '/' ); $slug = explode( '/', $slug ); $slug = $slug[0]; } else { // Get slug using host $slug = str_replace( $main['host'], '', $url['host'] ); $slug = trim( $slug, '.' ); $slug = explode( '.', $slug ); $slug = $slug[0]; } $book_id = get_id_from_blogname( $slug ); if ( ! $book_id ) { $_SESSION['pb_errors'][] = __( 'No book found.', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } $catalog->saveBook( $book_id, [] ); $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
php
static function formAddByUrl() { check_admin_referer( 'bulk-books' ); // Nonce auto-generated by WP_List_Table $catalog = new static(); $user_id = $catalog->getUserId(); // Set Redirect URL if ( get_current_user_id() !== $user_id ) { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog&user_id=' . $user_id ); } else { $redirect_url = get_admin_url( get_current_blog_id(), '/index.php?page=pb_catalog' ); } $url = wp_parse_url( \Pressbooks\Sanitize\canonicalize_url( $_REQUEST['add_book_by_url'] ) ); $main = wp_parse_url( network_home_url() ); if ( strpos( $url['host'], $main['host'] ) === false ) { $_SESSION['pb_errors'][] = __( 'Invalid URL.', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } if ( $url['host'] === $main['host'] ) { // Get slug using the path $slug = str_replace( $main['path'], '', $url['path'] ); $slug = trim( $slug, '/' ); $slug = explode( '/', $slug ); $slug = $slug[0]; } else { // Get slug using host $slug = str_replace( $main['host'], '', $url['host'] ); $slug = trim( $slug, '.' ); $slug = explode( '.', $slug ); $slug = $slug[0]; } $book_id = get_id_from_blogname( $slug ); if ( ! $book_id ) { $_SESSION['pb_errors'][] = __( 'No book found.', 'pressbooks' ); \Pressbooks\Redirect\location( $redirect_url ); } $catalog->saveBook( $book_id, [] ); $catalog->deleteCache(); // Ok! $_SESSION['pb_notices'][] = __( 'Settings saved.' ); // Redirect back to form \Pressbooks\Redirect\location( $redirect_url ); }
[ "static", "function", "formAddByUrl", "(", ")", "{", "check_admin_referer", "(", "'bulk-books'", ")", ";", "// Nonce auto-generated by WP_List_Table", "$", "catalog", "=", "new", "static", "(", ")", ";", "$", "user_id", "=", "$", "catalog", "->", "getUserId", "(...
Add Book by URL
[ "Add", "Book", "by", "URL" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-catalog.php#L1307-L1357
pressbooks/pressbooks
inc/modules/import/wordpress/class-downloads.php
Downloads.scrapeAndKneadImages
public function scrapeAndKneadImages( \DOMDocument $dom ) { $images = $dom->getElementsByTagName( 'img' ); $attachments = []; foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $src_old = $image->getAttribute( 'src' ); $attachment_id = $this->fetchAndSaveUniqueImage( $src_old ); if ( $attachment_id === -1 ) { // Do nothing because image is not hosted on the source Pb network } elseif ( $attachment_id ) { $image->setAttribute( 'src', $this->replaceImage( $attachment_id, $src_old, $image ) ); $attachments[] = $attachment_id; } else { // Tag broken image $image->setAttribute( 'src', "{$src_old}#fixme" ); } } return [ 'dom' => $dom, 'attachments' => $attachments, ]; }
php
public function scrapeAndKneadImages( \DOMDocument $dom ) { $images = $dom->getElementsByTagName( 'img' ); $attachments = []; foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $src_old = $image->getAttribute( 'src' ); $attachment_id = $this->fetchAndSaveUniqueImage( $src_old ); if ( $attachment_id === -1 ) { // Do nothing because image is not hosted on the source Pb network } elseif ( $attachment_id ) { $image->setAttribute( 'src', $this->replaceImage( $attachment_id, $src_old, $image ) ); $attachments[] = $attachment_id; } else { // Tag broken image $image->setAttribute( 'src', "{$src_old}#fixme" ); } } return [ 'dom' => $dom, 'attachments' => $attachments, ]; }
[ "public", "function", "scrapeAndKneadImages", "(", "\\", "DOMDocument", "$", "dom", ")", "{", "$", "images", "=", "$", "dom", "->", "getElementsByTagName", "(", "'img'", ")", ";", "$", "attachments", "=", "[", "]", ";", "foreach", "(", "$", "images", "as...
Parse HTML snippet, save all found <img> tags using media_handle_sideload(), return the HTML with changed <img> paths. @param \DOMDocument $dom @return array An array containing the \DOMDocument and the IDs of created attachments
[ "Parse", "HTML", "snippet", "save", "all", "found", "<img", ">", "tags", "using", "media_handle_sideload", "()", "return", "the", "HTML", "with", "changed", "<img", ">", "paths", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/wordpress/class-downloads.php#L61-L86
pressbooks/pressbooks
inc/modules/import/wordpress/class-downloads.php
Downloads.fetchAndSaveUniqueImage
public function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->wxr->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = image_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_img_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_img_location ); } else { $remote_img_location = $url; } if ( isset( $this->imageWasAlreadyDownloaded[ $remote_img_location ] ) ) { return $this->imageWasAlreadyDownloaded[ $remote_img_location ]; } /* Process */ if ( ! preg_match( $this->pregSupportedImageExtensions, $filename ) ) { // Unsupported image type $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; return 0; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; return 0; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->wxr->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 $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; unlink( $tmp_name ); return 0; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { $m = $known_media[ $attached_file ]; wp_update_post( [ 'ID' => $pid, 'post_title' => $m->title, 'post_content' => $m->description, 'post_excerpt' => $m->caption, ] ); update_post_meta( $pid, '_wp_attachment_image_alt', $m->altText ); foreach ( $m->meta as $meta_key => $meta_value ) { update_post_meta( $pid, $meta_key, $meta_value ); } // Store a transitional state $this->wxr->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->imageWasAlreadyDownloaded[ $remote_img_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
php
public function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->wxr->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = image_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_img_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_img_location ); } else { $remote_img_location = $url; } if ( isset( $this->imageWasAlreadyDownloaded[ $remote_img_location ] ) ) { return $this->imageWasAlreadyDownloaded[ $remote_img_location ]; } /* Process */ if ( ! preg_match( $this->pregSupportedImageExtensions, $filename ) ) { // Unsupported image type $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; return 0; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; return 0; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = $this->wxr->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 $this->imageWasAlreadyDownloaded[ $remote_img_location ] = ''; unlink( $tmp_name ); return 0; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { $m = $known_media[ $attached_file ]; wp_update_post( [ 'ID' => $pid, 'post_title' => $m->title, 'post_content' => $m->description, 'post_excerpt' => $m->caption, ] ); update_post_meta( $pid, '_wp_attachment_image_alt', $m->altText ); foreach ( $m->meta as $meta_key => $meta_value ) { update_post_meta( $pid, $meta_key, $meta_value ); } // Store a transitional state $this->wxr->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->imageWasAlreadyDownloaded[ $remote_img_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
[ "public", "function", "fetchAndSaveUniqueImage", "(", "$", "url", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "$", "this", "->", "sameAsSource", "(", "$", ...
Load remote url of image into WP using media_handle_sideload() Will return -1 if image is not hosted on the source Pb network, or 0 if something went wrong. @param string $url @see media_handle_sideload @return int attachment ID, -1 if image is not hosted on the source Pb network, or 0 if import failed
[ "Load", "remote", "url", "of", "image", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "-", "1", "if", "image", "is", "not", "hosted", "on", "the", "source", "Pb", "network", "or", "0", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/wordpress/class-downloads.php#L98-L185
pressbooks/pressbooks
inc/modules/import/wordpress/class-downloads.php
Downloads.replaceImage
public function replaceImage( $attachment_id, $src_old, $image ) { $known_media = $this->wxr->getKnownMedia(); $src_new = wp_get_attachment_url( $attachment_id ); if ( $this->sameAsSource( $src_old ) && isset( $known_media[ image_strip_baseurl( $src_old ) ] ) ) { $basename_old = $this->basename( $src_old ); $basename_new = $this->basename( $src_new ); $maybe_src_new = \Pressbooks\Utility\str_lreplace( $basename_new, $basename_old, $src_new ); if ( $attachment_id === attachment_id_from_url( $maybe_src_new ) ) { // Our best guess is that this is a cloned image, use old filename to preserve WP resizing $src_new = $maybe_src_new; // Update image class to new id to preserve WP Size dropdown if ( $image->hasAttribute( 'class' ) ) { $image->setAttribute( 'class', preg_replace( '/wp-image-\d+/', "wp-image-{$attachment_id}", $image->getAttribute( 'class' ) ) ); } // Update wrapper IDs if ( $image->parentNode->tagName === 'div' && strpos( $image->parentNode->getAttribute( 'id' ), 'attachment_' ) !== false ) { // <div> id $image->parentNode->setAttribute( 'id', preg_replace( '/attachment_\d+/', "attachment_{$attachment_id}", $image->parentNode->getAttribute( 'id' ) ) ); } foreach ( $image->parentNode->childNodes as $child ) { if ( $child instanceof \DOMText && strpos( $child->nodeValue, '[caption ' ) !== false && strpos( $child->nodeValue, 'attachment_' ) !== false ) { // [caption] id $child->nodeValue = preg_replace( '/attachment_\d+/', "attachment_{$attachment_id}", $child->nodeValue ); } } } } // Update srcset URLs if ( $image->hasAttribute( 'srcset' ) ) { $image->setAttribute( 'srcset', wp_get_attachment_image_srcset( $attachment_id ) ); } return $src_new; }
php
public function replaceImage( $attachment_id, $src_old, $image ) { $known_media = $this->wxr->getKnownMedia(); $src_new = wp_get_attachment_url( $attachment_id ); if ( $this->sameAsSource( $src_old ) && isset( $known_media[ image_strip_baseurl( $src_old ) ] ) ) { $basename_old = $this->basename( $src_old ); $basename_new = $this->basename( $src_new ); $maybe_src_new = \Pressbooks\Utility\str_lreplace( $basename_new, $basename_old, $src_new ); if ( $attachment_id === attachment_id_from_url( $maybe_src_new ) ) { // Our best guess is that this is a cloned image, use old filename to preserve WP resizing $src_new = $maybe_src_new; // Update image class to new id to preserve WP Size dropdown if ( $image->hasAttribute( 'class' ) ) { $image->setAttribute( 'class', preg_replace( '/wp-image-\d+/', "wp-image-{$attachment_id}", $image->getAttribute( 'class' ) ) ); } // Update wrapper IDs if ( $image->parentNode->tagName === 'div' && strpos( $image->parentNode->getAttribute( 'id' ), 'attachment_' ) !== false ) { // <div> id $image->parentNode->setAttribute( 'id', preg_replace( '/attachment_\d+/', "attachment_{$attachment_id}", $image->parentNode->getAttribute( 'id' ) ) ); } foreach ( $image->parentNode->childNodes as $child ) { if ( $child instanceof \DOMText && strpos( $child->nodeValue, '[caption ' ) !== false && strpos( $child->nodeValue, 'attachment_' ) !== false ) { // [caption] id $child->nodeValue = preg_replace( '/attachment_\d+/', "attachment_{$attachment_id}", $child->nodeValue ); } } } } // Update srcset URLs if ( $image->hasAttribute( 'srcset' ) ) { $image->setAttribute( 'srcset', wp_get_attachment_image_srcset( $attachment_id ) ); } return $src_new; }
[ "public", "function", "replaceImage", "(", "$", "attachment_id", ",", "$", "src_old", ",", "$", "image", ")", "{", "$", "known_media", "=", "$", "this", "->", "wxr", "->", "getKnownMedia", "(", ")", ";", "$", "src_new", "=", "wp_get_attachment_url", "(", ...
@param int $attachment_id @param string $src_old @param \DOMElement $image @return string
[ "@param", "int", "$attachment_id", "@param", "string", "$src_old", "@param", "\\", "DOMElement", "$image" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/wordpress/class-downloads.php#L194-L233
pressbooks/pressbooks
inc/modules/import/wordpress/class-downloads.php
Downloads.fetchAndSaveUniqueMedia
public function fetchAndSaveUniqueMedia( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->wxr->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = media_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_media_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_media_location ); } else { $remote_media_location = $url; } if ( isset( $this->mediaWasAlreadyDownloaded[ $remote_media_location ] ) ) { return $this->mediaWasAlreadyDownloaded[ $remote_media_location ]; } /* Process */ $tmp_name = download_url( $remote_media_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = 0; return 0; } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { $m = $known_media[ $attached_file ]; wp_update_post( [ 'ID' => $pid, 'post_title' => $m->title, 'post_content' => $m->description, 'post_excerpt' => $m->caption, ] ); foreach ( $m->meta as $meta_key => $meta_value ) { update_post_meta( $pid, $meta_key, $meta_value ); } // Store a transitional state $this->wxr->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
php
public function fetchAndSaveUniqueMedia( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->wxr->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = media_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_media_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_media_location ); } else { $remote_media_location = $url; } if ( isset( $this->mediaWasAlreadyDownloaded[ $remote_media_location ] ) ) { return $this->mediaWasAlreadyDownloaded[ $remote_media_location ]; } /* Process */ $tmp_name = download_url( $remote_media_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = 0; return 0; } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { $m = $known_media[ $attached_file ]; wp_update_post( [ 'ID' => $pid, 'post_title' => $m->title, 'post_content' => $m->description, 'post_excerpt' => $m->caption, ] ); foreach ( $m->meta as $meta_key => $meta_value ) { update_post_meta( $pid, $meta_key, $meta_value ); } // Store a transitional state $this->wxr->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
[ "public", "function", "fetchAndSaveUniqueMedia", "(", "$", "url", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "$", "this", "->", "sameAsSource", "(", "$", ...
Load remote media into WP using media_handle_sideload() Will return -1 if media is not hosted on the source Pb network, or 0 if something went wrong. @param string $url @see media_handle_sideload @return int attachment ID, -1 if media is not hosted on the source Pb network, or 0 if import failed
[ "Load", "remote", "media", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "-", "1", "if", "media", "is", "not", "hosted", "on", "the", "source", "Pb", "network", "or", "0", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/wordpress/class-downloads.php#L293-L357
pressbooks/pressbooks
inc/modules/import/wordpress/class-downloads.php
Downloads.basename
public function basename( $url ) { $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = explode( '#', $filename )[0]; // Remove trailing anchors $filename = sanitize_file_name( urldecode( $filename ) ); return $filename; }
php
public function basename( $url ) { $filename = explode( '?', basename( $url ) ); $filename = array_shift( $filename ); $filename = explode( '#', $filename )[0]; // Remove trailing anchors $filename = sanitize_file_name( urldecode( $filename ) ); return $filename; }
[ "public", "function", "basename", "(", "$", "url", ")", "{", "$", "filename", "=", "explode", "(", "'?'", ",", "basename", "(", "$", "url", ")", ")", ";", "$", "filename", "=", "array_shift", "(", "$", "filename", ")", ";", "$", "filename", "=", "e...
Get sanitized basename without query string or anchors @param $url @return array|mixed|string
[ "Get", "sanitized", "basename", "without", "query", "string", "or", "anchors" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/wordpress/class-downloads.php#L366-L373
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.convertGenerator
public function convertGenerator() : \Generator { yield 1 => $this->generatorPrefix . __( 'Initializing', 'pressbooks' ); yield from $this->transformGenerator(); if ( ! $this->transformOutput ) { throw new \Exception(); } yield 75 => $this->generatorPrefix . __( 'Saving file to exports folder', 'pressbooks' ); $filename = $this->timestampedFileName( '.html' ); \Pressbooks\Utility\put_contents( $filename, $this->transformOutput ); $this->outputPath = $filename; yield 80 => $this->generatorPrefix . __( 'Export successful', 'pressbooks' ); }
php
public function convertGenerator() : \Generator { yield 1 => $this->generatorPrefix . __( 'Initializing', 'pressbooks' ); yield from $this->transformGenerator(); if ( ! $this->transformOutput ) { throw new \Exception(); } yield 75 => $this->generatorPrefix . __( 'Saving file to exports folder', 'pressbooks' ); $filename = $this->timestampedFileName( '.html' ); \Pressbooks\Utility\put_contents( $filename, $this->transformOutput ); $this->outputPath = $filename; yield 80 => $this->generatorPrefix . __( 'Export successful', 'pressbooks' ); }
[ "public", "function", "convertGenerator", "(", ")", ":", "\\", "Generator", "{", "yield", "1", "=>", "$", "this", "->", "generatorPrefix", ".", "__", "(", "'Initializing'", ",", "'pressbooks'", ")", ";", "yield", "from", "$", "this", "->", "transformGenerato...
Yields an estimated percentage slice of: 1 to 80 @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "1", "to", "80" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L178-L192
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.validateGenerator
public function validateGenerator() : \Generator { yield 80 => $this->generatorPrefix . __( 'Validating file', 'pressbooks' ); // Xmllint params $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); // Is this a valid XHTML? if ( is_countable( $output ) && count( $output ) ) { $this->logError( implode( "\n", $output ) ); throw new \Exception(); } yield 100 => $this->generatorPrefix . __( 'Validation successful', 'pressbooks' ); }
php
public function validateGenerator() : \Generator { yield 80 => $this->generatorPrefix . __( 'Validating file', 'pressbooks' ); // Xmllint params $command = PB_XMLLINT_COMMAND . ' --html --valid --noout ' . escapeshellcmd( $this->outputPath ) . ' 2>&1'; // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); // Is this a valid XHTML? if ( is_countable( $output ) && count( $output ) ) { $this->logError( implode( "\n", $output ) ); throw new \Exception(); } yield 100 => $this->generatorPrefix . __( 'Validation successful', 'pressbooks' ); }
[ "public", "function", "validateGenerator", "(", ")", ":", "\\", "Generator", "{", "yield", "80", "=>", "$", "this", "->", "generatorPrefix", ".", "__", "(", "'Validating file'", ",", "'pressbooks'", ")", ";", "// Xmllint params", "$", "command", "=", "PB_XMLLI...
Yields an estimated percentage slice of: 80 to 100 @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "80", "to", "100" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L216-L234
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.transform
public function transform( $return = false ) { // Check permissions if ( ! current_user_can( 'edit_posts' ) ) { $timestamp = ( isset( $_REQUEST['timestamp'] ) ) ? absint( $_REQUEST['timestamp'] ) : 0; $hashkey = ( isset( $_REQUEST['hashkey'] ) ) ? $_REQUEST['hashkey'] : ''; if ( ! $this->verifyNonce( $timestamp, $hashkey ) ) { wp_die( __( 'Invalid permission error', 'pressbooks' ) ); } } try { foreach ( $this->transformGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return null; } if ( $return ) { return $this->transformOutput; } else { echo $this->transformOutput; return null; } }
php
public function transform( $return = false ) { // Check permissions if ( ! current_user_can( 'edit_posts' ) ) { $timestamp = ( isset( $_REQUEST['timestamp'] ) ) ? absint( $_REQUEST['timestamp'] ) : 0; $hashkey = ( isset( $_REQUEST['hashkey'] ) ) ? $_REQUEST['hashkey'] : ''; if ( ! $this->verifyNonce( $timestamp, $hashkey ) ) { wp_die( __( 'Invalid permission error', 'pressbooks' ) ); } } try { foreach ( $this->transformGenerator() as $percentage => $info ) { // Do nothing, this is a compatibility wrapper that makes the generator work like a regular function } } catch ( \Exception $e ) { return null; } if ( $return ) { return $this->transformOutput; } else { echo $this->transformOutput; return null; } }
[ "public", "function", "transform", "(", "$", "return", "=", "false", ")", "{", "// Check permissions", "if", "(", "!", "current_user_can", "(", "'edit_posts'", ")", ")", "{", "$", "timestamp", "=", "(", "isset", "(", "$", "_REQUEST", "[", "'timestamp'", "]...
Procedure for "format/xhtml" rewrite rule. Supported http (aka $_GET) params: + timestamp: (int) combines with `hashkey` to allow a 3rd party service temporary access + hashkey: (string) combines with `timestamp` to allow a 3rd party service temporary access + endnotes: (bool) move all footnotes to end of the book + style: (string) name of a user generated stylesheet you want included in the header + script: (string) name of javascript file you you want included in the header + preview: (bool) Use `Content-Disposition: inline` instead of `Content-Disposition: attachment` when passing through Export::formSubmit + optimize-for-print: (bool) Replace images with originals when possible, add class="print" to <body>, and other print specific tweaks @see \Pressbooks\Redirect\do_format @param bool $return (optional) If you would like to capture the output of transform, use the return parameter. If this parameter is set to true, transform will return its output, instead of printing it. @return mixed
[ "Procedure", "for", "format", "/", "xhtml", "rewrite", "rule", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L257-L283
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.transformGenerator
public function transformGenerator() : \Generator { do_action( 'pb_pre_export' ); // Override footnote shortcode if ( ! empty( $_GET['endnotes'] ) ) { add_shortcode( 'footnote', [ $this, 'endnoteShortcode' ] ); } else { add_shortcode( 'footnote', [ $this, 'footnoteShortcode' ] ); } // ------------------------------------------------------------------------------------------------------------ // XHTML, Start! $metadata = \Pressbooks\Book::getBookInformation(); $_unused = []; // Set two letter language code if ( isset( $metadata['pb_language'] ) ) { list( $this->lang ) = explode( '-', $metadata['pb_language'] ); } // ------------------------------------------------------------------------------------------------------------ // Buffer for Outer XHTML ob_start(); $this->echoDocType( $_unused, $_unused ); echo "<head>\n"; echo '<meta content="text/html; charset=UTF-8" http-equiv="content-type" />' . "\n"; echo '<meta http-equiv="Content-Language" content="' . $this->lang . '" />' . "\n"; echo '<meta name="generator" content="Pressbooks ' . PB_PLUGIN_VERSION . '" />' . "\n"; $this->echoMetaData( $_unused, $metadata ); echo '<title>' . get_bloginfo( 'name' ) . "</title>\n"; if ( current_user_can( 'edit_posts' ) ) { if ( ! empty( $_GET['debug'] ) ) { $assets = new Assets( 'pressbooks', 'plugin' ); $css = ( $_GET['debug'] === 'prince' ) ? $this->getLatestExportStyleUrl( 'prince' ) : false; $js = $assets->getPath( 'scripts/paged.polyfill.js' ); if ( $css ) { echo "<link rel='stylesheet' href='$css' type='text/css' />\n"; } echo "<script src='$js'></script>\n"; } } if ( ! empty( $_GET['style'] ) ) { $url = ( $_GET['style'] === 'prince' ) ? $this->getLatestExportStyleUrl( 'prince' ) : false; if ( $url ) { echo "<link rel='stylesheet' href='$url' type='text/css' />\n"; } } if ( ! empty( $_GET['script'] ) ) { $url = $this->getExportScriptUrl( clean_filename( $_GET['script'] ) ) . '/script.js'; if ( $url ) { echo "<script src='$url' type='text/javascript'></script>\n"; } } echo "</head>\n<body lang='{$this->lang}' "; if ( ! empty( $_GET['optimize-for-print'] ) ) { echo "class='print' "; } echo ">\n"; $replace_token = uniqid( 'PB_REPLACE_INNER_HTML_', true ); echo $replace_token; echo "\n</body>\n</html>"; $buffer_outer_html = ob_get_clean(); // ------------------------------------------------------------------------------------------------------------ // Buffer for Inner XHTML $my_get = $_GET; unset( $my_get['timestamp'], $my_get['hashkey'] ); $cache = get_transient( self::TRANSIENT ); if ( is_array( $cache ) && isset( $cache[0] ) && $cache[0] === md5( wp_json_encode( $my_get ) ) ) { // The $_GET parameters haven't changed since the last request so the output will be the same $buffer_inner_html = $cache[1]; } else { $book_contents = $this->preProcessBookContents( \Pressbooks\Book::getBookContents() ); ob_start(); // Before Title Page yield 10 => $this->generatorPrefix . __( 'Creating before title page', 'pressbooks' ); $this->echoBeforeTitle( $book_contents, $_unused ); // Half-title yield 15 => $this->generatorPrefix . __( 'Creating half title page', 'pressbooks' ); $this->echoHalfTitle( $_unused, $_unused ); // Cover yield 20 => $this->generatorPrefix . __( 'Creating cover', 'pressbooks' ); $this->echoCover( $book_contents, $metadata ); // Title yield 25 => $this->generatorPrefix . __( 'Creating title page', 'pressbooks' ); $this->echoTitle( $book_contents, $metadata ); // Copyright yield 30 => $this->generatorPrefix . __( 'Creating copyright page', 'pressbooks' ); $this->echoCopyright( $_unused, $metadata ); // Dedication and Epigraph (In that order!) yield 35 => $this->generatorPrefix . __( 'Creating dedication and epigraph', 'pressbooks' ); $this->echoDedicationAndEpigraph( $book_contents, $_unused ); // Table of contents yield 40 => $this->generatorPrefix . __( 'Creating table of contents', 'pressbooks' ); $this->echoToc( $book_contents, $_unused ); // Front-matter yield 50 => $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ); yield from $this->echoFrontMatterGenerator( $book_contents, $metadata ); // Promo $this->createPromo( $_unused, $_unused ); // Parts, Chapters yield 60 => $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ); yield from $this->echoPartsAndChaptersGenerator( $book_contents, $metadata ); // Back-matter yield 70 => $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ); yield from $this->echoBackMatterGenerator( $book_contents, $metadata ); $buffer_inner_html = ob_get_clean(); if ( $this->tidy ) { $buffer_inner_html = Sanitize\prettify( $buffer_inner_html ); } // Put the $_GET parameters and the buffer in a transient set_transient( self::TRANSIENT, [ md5( wp_json_encode( $my_get ) ), $buffer_inner_html ] ); } // Put inner HTML inside outer HTML $pos = strpos( $buffer_outer_html, $replace_token ); $buffer = substr_replace( $buffer_outer_html, $buffer_inner_html, $pos, strlen( $replace_token ) ); $this->transformOutput = $buffer; }
php
public function transformGenerator() : \Generator { do_action( 'pb_pre_export' ); // Override footnote shortcode if ( ! empty( $_GET['endnotes'] ) ) { add_shortcode( 'footnote', [ $this, 'endnoteShortcode' ] ); } else { add_shortcode( 'footnote', [ $this, 'footnoteShortcode' ] ); } // ------------------------------------------------------------------------------------------------------------ // XHTML, Start! $metadata = \Pressbooks\Book::getBookInformation(); $_unused = []; // Set two letter language code if ( isset( $metadata['pb_language'] ) ) { list( $this->lang ) = explode( '-', $metadata['pb_language'] ); } // ------------------------------------------------------------------------------------------------------------ // Buffer for Outer XHTML ob_start(); $this->echoDocType( $_unused, $_unused ); echo "<head>\n"; echo '<meta content="text/html; charset=UTF-8" http-equiv="content-type" />' . "\n"; echo '<meta http-equiv="Content-Language" content="' . $this->lang . '" />' . "\n"; echo '<meta name="generator" content="Pressbooks ' . PB_PLUGIN_VERSION . '" />' . "\n"; $this->echoMetaData( $_unused, $metadata ); echo '<title>' . get_bloginfo( 'name' ) . "</title>\n"; if ( current_user_can( 'edit_posts' ) ) { if ( ! empty( $_GET['debug'] ) ) { $assets = new Assets( 'pressbooks', 'plugin' ); $css = ( $_GET['debug'] === 'prince' ) ? $this->getLatestExportStyleUrl( 'prince' ) : false; $js = $assets->getPath( 'scripts/paged.polyfill.js' ); if ( $css ) { echo "<link rel='stylesheet' href='$css' type='text/css' />\n"; } echo "<script src='$js'></script>\n"; } } if ( ! empty( $_GET['style'] ) ) { $url = ( $_GET['style'] === 'prince' ) ? $this->getLatestExportStyleUrl( 'prince' ) : false; if ( $url ) { echo "<link rel='stylesheet' href='$url' type='text/css' />\n"; } } if ( ! empty( $_GET['script'] ) ) { $url = $this->getExportScriptUrl( clean_filename( $_GET['script'] ) ) . '/script.js'; if ( $url ) { echo "<script src='$url' type='text/javascript'></script>\n"; } } echo "</head>\n<body lang='{$this->lang}' "; if ( ! empty( $_GET['optimize-for-print'] ) ) { echo "class='print' "; } echo ">\n"; $replace_token = uniqid( 'PB_REPLACE_INNER_HTML_', true ); echo $replace_token; echo "\n</body>\n</html>"; $buffer_outer_html = ob_get_clean(); // ------------------------------------------------------------------------------------------------------------ // Buffer for Inner XHTML $my_get = $_GET; unset( $my_get['timestamp'], $my_get['hashkey'] ); $cache = get_transient( self::TRANSIENT ); if ( is_array( $cache ) && isset( $cache[0] ) && $cache[0] === md5( wp_json_encode( $my_get ) ) ) { // The $_GET parameters haven't changed since the last request so the output will be the same $buffer_inner_html = $cache[1]; } else { $book_contents = $this->preProcessBookContents( \Pressbooks\Book::getBookContents() ); ob_start(); // Before Title Page yield 10 => $this->generatorPrefix . __( 'Creating before title page', 'pressbooks' ); $this->echoBeforeTitle( $book_contents, $_unused ); // Half-title yield 15 => $this->generatorPrefix . __( 'Creating half title page', 'pressbooks' ); $this->echoHalfTitle( $_unused, $_unused ); // Cover yield 20 => $this->generatorPrefix . __( 'Creating cover', 'pressbooks' ); $this->echoCover( $book_contents, $metadata ); // Title yield 25 => $this->generatorPrefix . __( 'Creating title page', 'pressbooks' ); $this->echoTitle( $book_contents, $metadata ); // Copyright yield 30 => $this->generatorPrefix . __( 'Creating copyright page', 'pressbooks' ); $this->echoCopyright( $_unused, $metadata ); // Dedication and Epigraph (In that order!) yield 35 => $this->generatorPrefix . __( 'Creating dedication and epigraph', 'pressbooks' ); $this->echoDedicationAndEpigraph( $book_contents, $_unused ); // Table of contents yield 40 => $this->generatorPrefix . __( 'Creating table of contents', 'pressbooks' ); $this->echoToc( $book_contents, $_unused ); // Front-matter yield 50 => $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ); yield from $this->echoFrontMatterGenerator( $book_contents, $metadata ); // Promo $this->createPromo( $_unused, $_unused ); // Parts, Chapters yield 60 => $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ); yield from $this->echoPartsAndChaptersGenerator( $book_contents, $metadata ); // Back-matter yield 70 => $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ); yield from $this->echoBackMatterGenerator( $book_contents, $metadata ); $buffer_inner_html = ob_get_clean(); if ( $this->tidy ) { $buffer_inner_html = Sanitize\prettify( $buffer_inner_html ); } // Put the $_GET parameters and the buffer in a transient set_transient( self::TRANSIENT, [ md5( wp_json_encode( $my_get ) ), $buffer_inner_html ] ); } // Put inner HTML inside outer HTML $pos = strpos( $buffer_outer_html, $replace_token ); $buffer = substr_replace( $buffer_outer_html, $buffer_inner_html, $pos, strlen( $replace_token ) ); $this->transformOutput = $buffer; }
[ "public", "function", "transformGenerator", "(", ")", ":", "\\", "Generator", "{", "do_action", "(", "'pb_pre_export'", ")", ";", "// Override footnote shortcode", "if", "(", "!", "empty", "(", "$", "_GET", "[", "'endnotes'", "]", ")", ")", "{", "add_shortcode...
Yields an estimated percentage slice of: 10 to 75 @return \Generator @throws \Exception
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "10", "to", "75" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L291-L436
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.endnoteShortcode
function endnoteShortcode( $atts, $content = null ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, preProcessBookContents, ...] if ( ! $content ) { return ''; } $this->endnotes[ $id ][] = trim( $content ); return '<sup class="endnote">' . count( $this->endnotes[ $id ] ) . '</sup>'; }
php
function endnoteShortcode( $atts, $content = null ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, preProcessBookContents, ...] if ( ! $content ) { return ''; } $this->endnotes[ $id ][] = trim( $content ); return '<sup class="endnote">' . count( $this->endnotes[ $id ] ) . '</sup>'; }
[ "function", "endnoteShortcode", "(", "$", "atts", ",", "$", "content", "=", "null", ")", "{", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, preProcessBookContents, ...]", "if", "(", "!", "$", "content", ")", "{", "return", "''", ...
Convert footnotes to endnotes by moving them to the end of the_content() @see doEndnotes @param array $atts @param null $content @return string
[ "Convert", "footnotes", "to", "endnotes", "by", "moving", "them", "to", "the", "end", "of", "the_content", "()" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L479-L490
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.doEndnotes
function doEndnotes( $id ) { if ( ! isset( $this->endnotes[ $id ] ) || ! count( $this->endnotes[ $id ] ) ) { return ''; } $e = '<div class="endnotes">'; $e .= '<hr />'; $e .= '<h3>' . __( 'Notes', 'pressbooks' ) . '</h3>'; $e .= '<ol>'; foreach ( $this->endnotes[ $id ] as $endnote ) { $e .= "<li><span>$endnote</span></li>"; } $e .= '</ol></div>'; return $e; }
php
function doEndnotes( $id ) { if ( ! isset( $this->endnotes[ $id ] ) || ! count( $this->endnotes[ $id ] ) ) { return ''; } $e = '<div class="endnotes">'; $e .= '<hr />'; $e .= '<h3>' . __( 'Notes', 'pressbooks' ) . '</h3>'; $e .= '<ol>'; foreach ( $this->endnotes[ $id ] as $endnote ) { $e .= "<li><span>$endnote</span></li>"; } $e .= '</ol></div>'; return $e; }
[ "function", "doEndnotes", "(", "$", "id", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "endnotes", "[", "$", "id", "]", ")", "||", "!", "count", "(", "$", "this", "->", "endnotes", "[", "$", "id", "]", ")", ")", "{", "return", "...
Style endnotes. @see endnoteShortcode @param $id @return string
[ "Style", "endnotes", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L502-L518
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.removeAttributionLink
protected function removeAttributionLink( $content ) { if ( stripos( $content, '<a' ) === false ) { // There are no <a> tags to look at, skip this return $content; } $changed = false; $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $urls = $dom->getElementsByTagName( 'a' ); foreach ( $urls as $url ) { /** @var \DOMElement $url */ // Is this the the attributionUrl? if ( $url->getAttribute( 'rel' ) === 'cc:attributionURL' ) { $url->parentNode->replaceChild( $dom->createTextNode( $url->nodeValue ), $url ); $changed = true; } } if ( ! $changed ) { return $content; } else { $content = $html5->saveHTML( $dom ); $content = $this->html5ToXhtml( $content ); return $content; } }
php
protected function removeAttributionLink( $content ) { if ( stripos( $content, '<a' ) === false ) { // There are no <a> tags to look at, skip this return $content; } $changed = false; $html5 = new HtmlParser(); $dom = $html5->loadHTML( $content ); $urls = $dom->getElementsByTagName( 'a' ); foreach ( $urls as $url ) { /** @var \DOMElement $url */ // Is this the the attributionUrl? if ( $url->getAttribute( 'rel' ) === 'cc:attributionURL' ) { $url->parentNode->replaceChild( $dom->createTextNode( $url->nodeValue ), $url ); $changed = true; } } if ( ! $changed ) { return $content; } else { $content = $html5->saveHTML( $dom ); $content = $this->html5ToXhtml( $content ); return $content; } }
[ "protected", "function", "removeAttributionLink", "(", "$", "content", ")", "{", "if", "(", "stripos", "(", "$", "content", ",", "'<a'", ")", "===", "false", ")", "{", "// There are no <a> tags to look at, skip this", "return", "$", "content", ";", "}", "$", "...
Removes the CC attribution link. Returns valid xhtml. @since 4.1 @param string $content @return string
[ "Removes", "the", "CC", "attribution", "link", ".", "Returns", "valid", "xhtml", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L679-L709
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.echoFrontMatterGenerator
protected function echoFrontMatterGenerator( $book_contents, $metadata ) : \Generator { $front_matter_printf = '<div class="front-matter %1$s" id="%2$s" title="%3$s">'; $front_matter_printf .= '<div class="front-matter-title-wrap"><h3 class="front-matter-number">%4$s</h3><h1 class="front-matter-title">%5$s</h1>%6$s</div>'; $front_matter_printf .= '<div class="ugc front-matter-ugc">%7$s</div>%8$s%9$s'; $front_matter_printf .= '</div>'; $y = new PercentageYield( 50, 60, count( $book_contents['front-matter'] ) ); $i = $this->frontMatterPos; foreach ( $book_contents['front-matter'] as $front_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ) ); if ( ! $front_matter['export'] ) { continue; // Skip } $front_matter_id = $front_matter['ID']; $subclass = $this->taxonomy->getFrontMatterType( $front_matter_id ); if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } if ( $this->hasIntroduction ) { $subclass .= ' post-introduction'; } if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } $slug = "front-matter-{$front_matter['post_name']}"; $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '<span class="display-none">' . $front_matter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $front_matter['post_content']; $append_front_matter_content = apply_filters( 'pb_append_front_matter_content', '', $front_matter_id ); $short_title = trim( get_post_meta( $front_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $front_matter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $front_matter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $front_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $append_front_matter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $front_matter_id ) ); printf( $front_matter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $front_matter['post_title'] ) ), $i, Sanitize\decode( $title ), $after_title, $content, $append_front_matter_content, $this->doEndnotes( $front_matter_id ) ); echo "\n"; ++$i; } $this->frontMatterPos = $i; }
php
protected function echoFrontMatterGenerator( $book_contents, $metadata ) : \Generator { $front_matter_printf = '<div class="front-matter %1$s" id="%2$s" title="%3$s">'; $front_matter_printf .= '<div class="front-matter-title-wrap"><h3 class="front-matter-number">%4$s</h3><h1 class="front-matter-title">%5$s</h1>%6$s</div>'; $front_matter_printf .= '<div class="ugc front-matter-ugc">%7$s</div>%8$s%9$s'; $front_matter_printf .= '</div>'; $y = new PercentageYield( 50, 60, count( $book_contents['front-matter'] ) ); $i = $this->frontMatterPos; foreach ( $book_contents['front-matter'] as $front_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting front matter', 'pressbooks' ) ); if ( ! $front_matter['export'] ) { continue; // Skip } $front_matter_id = $front_matter['ID']; $subclass = $this->taxonomy->getFrontMatterType( $front_matter_id ); if ( 'dedication' === $subclass || 'epigraph' === $subclass || 'title-page' === $subclass || 'before-title' === $subclass ) { continue; // Skip } if ( $this->hasIntroduction ) { $subclass .= ' post-introduction'; } if ( 'introduction' === $subclass ) { $this->hasIntroduction = true; } $slug = "front-matter-{$front_matter['post_name']}"; $title = ( get_post_meta( $front_matter_id, 'pb_show_title', true ) ? $front_matter['post_title'] : '<span class="display-none">' . $front_matter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $front_matter['post_content']; $append_front_matter_content = apply_filters( 'pb_append_front_matter_content', '', $front_matter_id ); $short_title = trim( get_post_meta( $front_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $front_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $front_matter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $front_matter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $front_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $append_front_matter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $front_matter_id ) ); printf( $front_matter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $front_matter['post_title'] ) ), $i, Sanitize\decode( $title ), $after_title, $content, $append_front_matter_content, $this->doEndnotes( $front_matter_id ) ); echo "\n"; ++$i; } $this->frontMatterPos = $i; }
[ "protected", "function", "echoFrontMatterGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "front_matter_printf", "=", "'<div class=\"front-matter %1$s\" id=\"%2$s\" title=\"%3$s\">'", ";", "$", "front_matter_printf", ".=", ...
Yields an estimated percentage slice of: 50 to 60 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "50", "to", "60" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L1217-L1307
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.echoPartsAndChaptersGenerator
protected function echoPartsAndChaptersGenerator( $book_contents, $metadata ) : \Generator { $part_printf = '<div class="part %1$s" id="%2$s">'; $part_printf .= '<div class="part-title-wrap"><h3 class="part-number">%3$s</h3><h1 class="part-title">%4$s</h1></div>%5$s'; $part_printf .= '</div>'; $chapter_printf = '<div class="chapter %1$s" id="%2$s" title="%3$s">'; $chapter_printf .= '<div class="chapter-title-wrap"><h3 class="chapter-number">%4$s</h3><h2 class="chapter-title">%5$s</h2>%6$s</div>'; $chapter_printf .= '<div class="ugc chapter-ugc">%7$s</div>%8$s%9$s'; $chapter_printf .= '</div>'; $ticks = 0; foreach ( $book_contents['part'] as $key => $part ) { $ticks = $ticks + 1 + count( $book_contents['part'][ $key ]['chapters'] ); } $y = new PercentageYield( 60, 70, $ticks ); $i = 1; $j = 1; foreach ( $book_contents['part'] as $part ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $slug = "part-{$part['post_name']}"; $title = $part['post_title']; $part_content = trim( $part['post_content'] ); // Inject introduction class? if ( 'invisible' !== $invisibility ) { // visible if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content if ( ! $this->hasIntroduction ) { $part_printf_changed = str_replace( '<div class="part %1$s" id="', '<div class="part introduction %1$s" id="', $part_printf ); $this->hasIntroduction = true; } } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( ! $this->hasIntroduction ) { $part_printf_changed = str_replace( '<div class="part %1$s" id="', '<div class="part introduction %1$s" id="', $part_printf ); $this->hasIntroduction = true; } } } // Inject part content? if ( $part_content ) { if ( $part_printf_changed ) { $part_printf_changed = str_replace( '</h1></div>%s</div>', '</h1></div><div class="ugc part-ugc">%s</div></div>', $part_printf_changed ); } else { $part_printf_changed = str_replace( '</h1></div>%s</div>', '</h1></div><div class="ugc part-ugc">%s</div></div>', $part_printf ); } } $m = ( 'invisible' === $invisibility ) ? '' : $i; $my_part = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, \Pressbooks\L10n\romanize( $m ), Sanitize\decode( $title ), $part_content ) . "\n"; $my_chapters = ''; foreach ( $part['chapters'] as $chapter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); if ( ! $chapter['export'] ) { continue; // Skip } $chapter_id = $chapter['ID']; $subclass = $this->taxonomy->getChapterType( $chapter_id ); $slug = "chapter-{$chapter['post_name']}"; $title = ( get_post_meta( $chapter_id, 'pb_show_title', true ) ? $chapter['post_title'] : '<span class="display-none">' . $chapter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $chapter['post_content']; $append_chapter_content = apply_filters( 'pb_append_chapter_content', '', $chapter_id ); $short_title = trim( get_post_meta( $chapter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $chapter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $chapter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $chapter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $chapter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } // Inject introduction class? if ( ! $this->hasIntroduction ) { $subclass .= ' introduction'; $this->hasIntroduction = true; } $append_chapter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $chapter_id ) ); $my_chapter_number = ( strpos( $subclass, 'numberless' ) === false ) ? $j : ''; $my_chapters .= sprintf( $chapter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $chapter['post_title'] ) ), $my_chapter_number, Sanitize\decode( $title ), $after_title, $content, $append_chapter_content, $this->doEndnotes( $chapter_id ) ) . "\n"; if ( $my_chapter_number !== '' ) { ++$j; } } // Echo with parts? if ( 'invisible' !== $invisibility ) { // visible if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content echo $my_part; // show if ( $my_chapters ) { echo $my_chapters; } } else { // no content if ( $my_chapters ) { echo $my_chapters; } } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( $my_chapters ) { // has chapter echo $my_part . $my_chapters; // show } else { // no chapter if ( $part_content ) { // has content echo $my_part; // show } } } ++$i; } elseif ( 'invisible' === $invisibility ) { // invisible if ( $my_chapters ) { echo $my_chapters; } } } }
php
protected function echoPartsAndChaptersGenerator( $book_contents, $metadata ) : \Generator { $part_printf = '<div class="part %1$s" id="%2$s">'; $part_printf .= '<div class="part-title-wrap"><h3 class="part-number">%3$s</h3><h1 class="part-title">%4$s</h1></div>%5$s'; $part_printf .= '</div>'; $chapter_printf = '<div class="chapter %1$s" id="%2$s" title="%3$s">'; $chapter_printf .= '<div class="chapter-title-wrap"><h3 class="chapter-number">%4$s</h3><h2 class="chapter-title">%5$s</h2>%6$s</div>'; $chapter_printf .= '<div class="ugc chapter-ugc">%7$s</div>%8$s%9$s'; $chapter_printf .= '</div>'; $ticks = 0; foreach ( $book_contents['part'] as $key => $part ) { $ticks = $ticks + 1 + count( $book_contents['part'][ $key ]['chapters'] ); } $y = new PercentageYield( 60, 70, $ticks ); $i = 1; $j = 1; foreach ( $book_contents['part'] as $part ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); $invisibility = ( get_post_meta( $part['ID'], 'pb_part_invisible', true ) === 'on' ) ? 'invisible' : ''; $part_printf_changed = ''; $slug = "part-{$part['post_name']}"; $title = $part['post_title']; $part_content = trim( $part['post_content'] ); // Inject introduction class? if ( 'invisible' !== $invisibility ) { // visible if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content if ( ! $this->hasIntroduction ) { $part_printf_changed = str_replace( '<div class="part %1$s" id="', '<div class="part introduction %1$s" id="', $part_printf ); $this->hasIntroduction = true; } } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( ! $this->hasIntroduction ) { $part_printf_changed = str_replace( '<div class="part %1$s" id="', '<div class="part introduction %1$s" id="', $part_printf ); $this->hasIntroduction = true; } } } // Inject part content? if ( $part_content ) { if ( $part_printf_changed ) { $part_printf_changed = str_replace( '</h1></div>%s</div>', '</h1></div><div class="ugc part-ugc">%s</div></div>', $part_printf_changed ); } else { $part_printf_changed = str_replace( '</h1></div>%s</div>', '</h1></div><div class="ugc part-ugc">%s</div></div>', $part_printf ); } } $m = ( 'invisible' === $invisibility ) ? '' : $i; $my_part = sprintf( ( $part_printf_changed ? $part_printf_changed : $part_printf ), $invisibility, $slug, \Pressbooks\L10n\romanize( $m ), Sanitize\decode( $title ), $part_content ) . "\n"; $my_chapters = ''; foreach ( $part['chapters'] as $chapter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting parts and chapters', 'pressbooks' ) ); if ( ! $chapter['export'] ) { continue; // Skip } $chapter_id = $chapter['ID']; $subclass = $this->taxonomy->getChapterType( $chapter_id ); $slug = "chapter-{$chapter['post_name']}"; $title = ( get_post_meta( $chapter_id, 'pb_show_title', true ) ? $chapter['post_title'] : '<span class="display-none">' . $chapter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $chapter['post_content']; $append_chapter_content = apply_filters( 'pb_append_chapter_content', '', $chapter_id ); $short_title = trim( get_post_meta( $chapter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $chapter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $chapter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $chapter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $chapter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } // Inject introduction class? if ( ! $this->hasIntroduction ) { $subclass .= ' introduction'; $this->hasIntroduction = true; } $append_chapter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $chapter_id ) ); $my_chapter_number = ( strpos( $subclass, 'numberless' ) === false ) ? $j : ''; $my_chapters .= sprintf( $chapter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $chapter['post_title'] ) ), $my_chapter_number, Sanitize\decode( $title ), $after_title, $content, $append_chapter_content, $this->doEndnotes( $chapter_id ) ) . "\n"; if ( $my_chapter_number !== '' ) { ++$j; } } // Echo with parts? if ( 'invisible' !== $invisibility ) { // visible if ( count( $book_contents['part'] ) === 1 ) { // only part if ( $part_content ) { // has content echo $my_part; // show if ( $my_chapters ) { echo $my_chapters; } } else { // no content if ( $my_chapters ) { echo $my_chapters; } } } elseif ( count( $book_contents['part'] ) > 1 ) { // multiple parts if ( $my_chapters ) { // has chapter echo $my_part . $my_chapters; // show } else { // no chapter if ( $part_content ) { // has content echo $my_part; // show } } } ++$i; } elseif ( 'invisible' === $invisibility ) { // invisible if ( $my_chapters ) { echo $my_chapters; } } } }
[ "protected", "function", "echoPartsAndChaptersGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "part_printf", "=", "'<div class=\"part %1$s\" id=\"%2$s\">'", ";", "$", "part_printf", ".=", "'<div class=\"part-title-wrap\"...
Yields an estimated percentage slice of: 60 to 70 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "60", "to", "70" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L1330-L1503
pressbooks/pressbooks
inc/modules/export/xhtml/class-xhtml11.php
Xhtml11.echoBackMatterGenerator
protected function echoBackMatterGenerator( $book_contents, $metadata ) : \Generator { $back_matter_printf = '<div class="back-matter %1$s" id="%2$s" title="%3$s">'; $back_matter_printf .= '<div class="back-matter-title-wrap"><h3 class="back-matter-number">%4$s</h3><h1 class="back-matter-title">%5$s</h1>%6$s</div>'; $back_matter_printf .= '<div class="ugc back-matter-ugc">%7$s</div>%8$s%9$s'; $back_matter_printf .= '</div>'; $y = new PercentageYield( 70, 80, count( $book_contents['back-matter'] ) ); $i = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ) ); if ( ! $back_matter['export'] ) { continue; } $back_matter_id = $back_matter['ID']; $subclass = $this->taxonomy->getBackMatterType( $back_matter_id ); $slug = "back-matter-{$back_matter['post_name']}"; $title = ( get_post_meta( $back_matter_id, 'pb_show_title', true ) ? $back_matter['post_title'] : '<span class="display-none">' . $back_matter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $back_matter['post_content']; $append_back_matter_content = apply_filters( 'pb_append_back_matter_content', '', $back_matter_id ); $short_title = trim( get_post_meta( $back_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $back_matter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $back_matter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $back_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $append_back_matter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $back_matter_id ) ); printf( $back_matter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $back_matter['post_title'] ) ), $i, Sanitize\decode( $title ), $after_title, $content, $append_back_matter_content, $this->doEndnotes( $back_matter_id ) ); echo "\n"; ++$i; } }
php
protected function echoBackMatterGenerator( $book_contents, $metadata ) : \Generator { $back_matter_printf = '<div class="back-matter %1$s" id="%2$s" title="%3$s">'; $back_matter_printf .= '<div class="back-matter-title-wrap"><h3 class="back-matter-number">%4$s</h3><h1 class="back-matter-title">%5$s</h1>%6$s</div>'; $back_matter_printf .= '<div class="ugc back-matter-ugc">%7$s</div>%8$s%9$s'; $back_matter_printf .= '</div>'; $y = new PercentageYield( 70, 80, count( $book_contents['back-matter'] ) ); $i = 1; foreach ( $book_contents['back-matter'] as $back_matter ) { yield from $y->tick( $this->generatorPrefix . __( 'Exporting back matter', 'pressbooks' ) ); if ( ! $back_matter['export'] ) { continue; } $back_matter_id = $back_matter['ID']; $subclass = $this->taxonomy->getBackMatterType( $back_matter_id ); $slug = "back-matter-{$back_matter['post_name']}"; $title = ( get_post_meta( $back_matter_id, 'pb_show_title', true ) ? $back_matter['post_title'] : '<span class="display-none">' . $back_matter['post_title'] . '</span>' ); // Preserve auto-indexing in Prince using hidden span $after_title = ''; $content = $back_matter['post_content']; $append_back_matter_content = apply_filters( 'pb_append_back_matter_content', '', $back_matter_id ); $short_title = trim( get_post_meta( $back_matter_id, 'pb_short_title', true ) ); $subtitle = trim( get_post_meta( $back_matter_id, 'pb_subtitle', true ) ); $author = $this->contributors->get( $back_matter_id, 'pb_authors' ); if ( \Pressbooks\Modules\Export\Export::shouldParseSubsections() === true ) { if ( \Pressbooks\Book::getSubsections( $back_matter_id ) !== false ) { $content = \Pressbooks\Book::tagSubsections( $content, $back_matter_id ); $content = $this->html5ToXhtml( $content ); } } if ( $author ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-author">' . Sanitize\decode( $author ) . '</h2>' . $content; } } if ( $subtitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $after_title; } else { $content = '<h2 class="chapter-subtitle">' . Sanitize\decode( $subtitle ) . '</h2>' . $content; } } if ( $short_title && $this->outputShortTitle ) { if ( $this->wrapHeaderElements ) { $after_title = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $after_title; } else { $content = '<h6 class="short-title">' . Sanitize\decode( $short_title ) . '</h6>' . $content; } } $append_back_matter_content .= $this->removeAttributionLink( $this->doSectionLevelLicense( $metadata, $back_matter_id ) ); printf( $back_matter_printf, $subclass, $slug, ( $short_title ) ? $short_title : wp_strip_all_tags( Sanitize\decode( $back_matter['post_title'] ) ), $i, Sanitize\decode( $title ), $after_title, $content, $append_back_matter_content, $this->doEndnotes( $back_matter_id ) ); echo "\n"; ++$i; } }
[ "protected", "function", "echoBackMatterGenerator", "(", "$", "book_contents", ",", "$", "metadata", ")", ":", "\\", "Generator", "{", "$", "back_matter_printf", "=", "'<div class=\"back-matter %1$s\" id=\"%2$s\" title=\"%3$s\">'", ";", "$", "back_matter_printf", ".=", "'...
Yields an estimated percentage slice of: 70 to 80 @param array $book_contents @param array $metadata @return \Generator
[ "Yields", "an", "estimated", "percentage", "slice", "of", ":", "70", "to", "80" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/xhtml/class-xhtml11.php#L1513-L1590
pressbooks/pressbooks
inc/class-pressbooks.php
Pressbooks.registerThemeDirectories
function registerThemeDirectories() { /** * Register additional theme directories. * * Additional theme directories (e.g. those within another plugin, or custom * subdirectories of wp-content) may be registered via this action hook. * * @since 3.8.0 */ do_action( 'pressbooks_register_theme_directory' ); if ( is_admin() ) { if ( Book::isBook() ) { add_filter( 'allowed_themes', [ $this, 'allowedBookThemes' ] ); } elseif ( ! is_network_admin() ) { add_filter( 'allowed_themes', [ $this, 'allowedRootThemes' ] ); } } }
php
function registerThemeDirectories() { /** * Register additional theme directories. * * Additional theme directories (e.g. those within another plugin, or custom * subdirectories of wp-content) may be registered via this action hook. * * @since 3.8.0 */ do_action( 'pressbooks_register_theme_directory' ); if ( is_admin() ) { if ( Book::isBook() ) { add_filter( 'allowed_themes', [ $this, 'allowedBookThemes' ] ); } elseif ( ! is_network_admin() ) { add_filter( 'allowed_themes', [ $this, 'allowedRootThemes' ] ); } } }
[ "function", "registerThemeDirectories", "(", ")", "{", "/**\n\t\t * Register additional theme directories.\n\t\t *\n\t\t * Additional theme directories (e.g. those within another plugin, or custom\n\t\t * subdirectories of wp-content) may be registered via this action hook.\n\t\t *\n\t\t * @since 3.8.0\n\...
Register theme directories, set a filter that hides themes under certain conditions
[ "Register", "theme", "directories", "set", "a", "filter", "that", "hides", "themes", "under", "certain", "conditions" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-pressbooks.php#L39-L58
pressbooks/pressbooks
inc/class-pressbooks.php
Pressbooks.allowedBookThemes
function allowedBookThemes( $themes ) { $compare = search_theme_directories(); $themes = array_intersect_key( $themes, $compare ); foreach ( $compare as $key => $val ) { $stylesheet = str_replace( 'style.css', '', $val['theme_file'] ); $theme = wp_get_theme( $stylesheet, $val['theme_root'] ); // Hide any available non-book themes, as identified by checking to see if they are either pressbooks-book or a child theme of pressbooks-book. if ( 'pressbooks-book/style.css' !== $val['theme_file'] && 'pressbooks-book' !== $theme->get( 'Template' ) ) { unset( $themes[ $key ] ); } } return $themes; }
php
function allowedBookThemes( $themes ) { $compare = search_theme_directories(); $themes = array_intersect_key( $themes, $compare ); foreach ( $compare as $key => $val ) { $stylesheet = str_replace( 'style.css', '', $val['theme_file'] ); $theme = wp_get_theme( $stylesheet, $val['theme_root'] ); // Hide any available non-book themes, as identified by checking to see if they are either pressbooks-book or a child theme of pressbooks-book. if ( 'pressbooks-book/style.css' !== $val['theme_file'] && 'pressbooks-book' !== $theme->get( 'Template' ) ) { unset( $themes[ $key ] ); } } return $themes; }
[ "function", "allowedBookThemes", "(", "$", "themes", ")", "{", "$", "compare", "=", "search_theme_directories", "(", ")", ";", "$", "themes", "=", "array_intersect_key", "(", "$", "themes", ",", "$", "compare", ")", ";", "foreach", "(", "$", "compare", "as...
Used by add_filter( 'allowed_themes' ). Will hide any non-book themes. @param array $themes @return array
[ "Used", "by", "add_filter", "(", "allowed_themes", ")", ".", "Will", "hide", "any", "non", "-", "book", "themes", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-pressbooks.php#L68-L81
pressbooks/pressbooks
inc/modules/searchandreplace/types/class-content.php
Content.find
function find( $pattern, $limit, $offset, $orderby ) { global $wpdb; $results = []; $sql = "SELECT ID, post_content, post_title FROM {$wpdb->posts} WHERE post_type IN ('part','chapter','front-matter','back-matter') AND post_status NOT IN ('trash','inherit') ORDER BY ID "; $sql .= ( 'asc' === $orderby ) ? 'ASC' : 'DESC'; if ( $limit > 0 ) { $sql .= sprintf( ' LIMIT %d,%d ', $offset, $limit ); } $posts = $wpdb->get_results( $sql ); // @codingStandardsIgnoreLine if ( count( $posts ) > 0 ) { foreach ( $posts as $key => $post ) { $matches = $this->matches( $pattern, $post->post_content, $post->ID ); if ( $matches ) { foreach ( $matches as $match ) { $match->title = $post->post_title; } $results = array_merge( $results, $matches ); } unset( $posts[ $key ] ); // Reduce memory usage } } return $results; }
php
function find( $pattern, $limit, $offset, $orderby ) { global $wpdb; $results = []; $sql = "SELECT ID, post_content, post_title FROM {$wpdb->posts} WHERE post_type IN ('part','chapter','front-matter','back-matter') AND post_status NOT IN ('trash','inherit') ORDER BY ID "; $sql .= ( 'asc' === $orderby ) ? 'ASC' : 'DESC'; if ( $limit > 0 ) { $sql .= sprintf( ' LIMIT %d,%d ', $offset, $limit ); } $posts = $wpdb->get_results( $sql ); // @codingStandardsIgnoreLine if ( count( $posts ) > 0 ) { foreach ( $posts as $key => $post ) { $matches = $this->matches( $pattern, $post->post_content, $post->ID ); if ( $matches ) { foreach ( $matches as $match ) { $match->title = $post->post_title; } $results = array_merge( $results, $matches ); } unset( $posts[ $key ] ); // Reduce memory usage } } return $results; }
[ "function", "find", "(", "$", "pattern", ",", "$", "limit", ",", "$", "offset", ",", "$", "orderby", ")", "{", "global", "$", "wpdb", ";", "$", "results", "=", "[", "]", ";", "$", "sql", "=", "\"SELECT ID, post_content, post_title FROM {$wpdb->posts}\n\t\t\t...
@param $pattern @param $limit @param $offset @param $orderby @return \Pressbooks\Modules\SearchAndReplace\Result[]
[ "@param", "$pattern", "@param", "$limit", "@param", "$offset", "@param", "$orderby" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/types/class-content.php#L21-L49
pressbooks/pressbooks
inc/modules/searchandreplace/types/class-content.php
Content.getOptions
function getOptions( $result ) { $options[] = '<a href="' . get_permalink( $result->id ) . '">' . __( 'view', 'pressbooks' ) . '</a>'; if ( current_user_can( 'edit_post', $result->id ) ) { $options[] = '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/post.php?action=edit&amp;post=' . $result->id . '">' . __( 'edit', 'pressbooks' ) . '</a>'; } return $options; }
php
function getOptions( $result ) { $options[] = '<a href="' . get_permalink( $result->id ) . '">' . __( 'view', 'pressbooks' ) . '</a>'; if ( current_user_can( 'edit_post', $result->id ) ) { $options[] = '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/post.php?action=edit&amp;post=' . $result->id . '">' . __( 'edit', 'pressbooks' ) . '</a>'; } return $options; }
[ "function", "getOptions", "(", "$", "result", ")", "{", "$", "options", "[", "]", "=", "'<a href=\"'", ".", "get_permalink", "(", "$", "result", "->", "id", ")", ".", "'\">'", ".", "__", "(", "'view'", ",", "'pressbooks'", ")", ".", "'</a>'", ";", "i...
@param object $result @return array
[ "@param", "object", "$result" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/types/class-content.php#L56-L62
pressbooks/pressbooks
inc/modules/searchandreplace/types/class-content.php
Content.getContent
function getContent( $id ) { global $wpdb; $post = $wpdb->get_row( $wpdb->prepare( "SELECT post_content FROM {$wpdb->posts} WHERE id=%d", $id ) ); return $post->post_content; }
php
function getContent( $id ) { global $wpdb; $post = $wpdb->get_row( $wpdb->prepare( "SELECT post_content FROM {$wpdb->posts} WHERE id=%d", $id ) ); return $post->post_content; }
[ "function", "getContent", "(", "$", "id", ")", "{", "global", "$", "wpdb", ";", "$", "post", "=", "$", "wpdb", "->", "get_row", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT post_content FROM {$wpdb->posts} WHERE id=%d\"", ",", "$", "id", ")", ")", ";"...
@param int $id @return string
[ "@param", "int", "$id" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/types/class-content.php#L77-L81
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.regexValidate
function regexValidate( $expr ) { // evaluate expression without input and capture potential error message $regex_error = 'invalid'; $error_handler = function( $errno, $errstr, $errfile, $errline ) use ( &$regex_error ) { $regex_error = preg_replace( '/(.*?):/', '', $errstr, 1 ); }; // detect possibility to execute code: // https://bitquark.co.uk/blog/2013/07/23/the_unexpected_dangers_of_preg_replace if ( false !== strpos( $expr, "\0" ) ) { return 'Null byte in regex'; } // @codingStandardsIgnoreStart set_error_handler( $error_handler ); $valid = @preg_match( $expr, null, $matches ); restore_error_handler(); // @codingStandardsIgnoreEnd if ( false === $valid ) { if ( strpos( $regex_error, '/e modifier is no longer supported' ) !== false ) { // Print the same error for PHP 7.2 and 7.3 return 'Unknown modifier \'e\''; } return $regex_error; } $modifiers = preg_replace( '/^.*[^\\w\\s]([\\w\\s]*)$/s', '$1', $expr ); if ( false !== strpos( $modifiers, 'e' ) ) { return 'Unknown modifier \'e\''; } // expression seems valid return null; }
php
function regexValidate( $expr ) { // evaluate expression without input and capture potential error message $regex_error = 'invalid'; $error_handler = function( $errno, $errstr, $errfile, $errline ) use ( &$regex_error ) { $regex_error = preg_replace( '/(.*?):/', '', $errstr, 1 ); }; // detect possibility to execute code: // https://bitquark.co.uk/blog/2013/07/23/the_unexpected_dangers_of_preg_replace if ( false !== strpos( $expr, "\0" ) ) { return 'Null byte in regex'; } // @codingStandardsIgnoreStart set_error_handler( $error_handler ); $valid = @preg_match( $expr, null, $matches ); restore_error_handler(); // @codingStandardsIgnoreEnd if ( false === $valid ) { if ( strpos( $regex_error, '/e modifier is no longer supported' ) !== false ) { // Print the same error for PHP 7.2 and 7.3 return 'Unknown modifier \'e\''; } return $regex_error; } $modifiers = preg_replace( '/^.*[^\\w\\s]([\\w\\s]*)$/s', '$1', $expr ); if ( false !== strpos( $modifiers, 'e' ) ) { return 'Unknown modifier \'e\''; } // expression seems valid return null; }
[ "function", "regexValidate", "(", "$", "expr", ")", "{", "// evaluate expression without input and capture potential error message", "$", "regex_error", "=", "'invalid'", ";", "$", "error_handler", "=", "function", "(", "$", "errno", ",", "$", "errstr", ",", "$", "e...
@param string $expr @return null|string
[ "@param", "string", "$expr" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L52-L81
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.searchAndReplace
function searchAndReplace( $search, $replace, $limit, $offset, $orderby, $save = false ) { // escape potential backreferences when not in regex mode if ( ! $this->regex ) { $replace = str_replace( '\\', '\\\\', $replace ); $replace = str_replace( '$', '\\$', $replace ); } $this->replace = $replace; $results = $this->searchForPattern( $search, $limit, $offset, $orderby ); if ( is_array( $results ) && $save ) { $this->replace( $results ); } return $results; }
php
function searchAndReplace( $search, $replace, $limit, $offset, $orderby, $save = false ) { // escape potential backreferences when not in regex mode if ( ! $this->regex ) { $replace = str_replace( '\\', '\\\\', $replace ); $replace = str_replace( '$', '\\$', $replace ); } $this->replace = $replace; $results = $this->searchForPattern( $search, $limit, $offset, $orderby ); if ( is_array( $results ) && $save ) { $this->replace( $results ); } return $results; }
[ "function", "searchAndReplace", "(", "$", "search", ",", "$", "replace", ",", "$", "limit", ",", "$", "offset", ",", "$", "orderby", ",", "$", "save", "=", "false", ")", "{", "// escape potential backreferences when not in regex mode", "if", "(", "!", "$", "...
@param string $search @param string $replace @param int $limit @param int $offset @param string $orderby @param bool $save @return \Pressbooks\Modules\SearchAndReplace\Result[]
[ "@param", "string", "$search", "@param", "string", "$replace", "@param", "int", "$limit", "@param", "int", "$offset", "@param", "string", "$orderby", "@param", "bool", "$save" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L93-L105
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.searchForPattern
function searchForPattern( $search, $limit, $offset, $orderby ) { if ( ! in_array( $orderby, [ 'asc', 'desc' ], true ) ) { $orderby = 'asc'; } $limit = intval( $limit ); $offset = intval( $offset ); if ( strlen( $search ) > 0 ) { /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 300, 'search' ) ); // @codingStandardsIgnoreLine if ( $this->regex ) { $error = $this->regexValidate( $search ); if ( null !== $error ) { return __( 'Invalid regular expression', 'pressbooks' ) . ': ' . $error; } return $this->find( $search, $limit, $offset, $orderby ); } else { return $this->find( '@' . preg_quote( $search, '@' ) . '@', $limit, $offset, $orderby ); } } return __( 'No search pattern.', 'pressbooks' ); }
php
function searchForPattern( $search, $limit, $offset, $orderby ) { if ( ! in_array( $orderby, [ 'asc', 'desc' ], true ) ) { $orderby = 'asc'; } $limit = intval( $limit ); $offset = intval( $offset ); if ( strlen( $search ) > 0 ) { /** * Maximum execution time, in seconds. If set to zero, no time limit * Overrides PHP's max_execution_time of a Nginx->PHP-FPM->PHP configuration * See also request_terminate_timeout (PHP-FPM) and fastcgi_read_timeout (Nginx) * * @since 5.6.0 * * @param int $seconds * @param string $some_action * * @return int */ @set_time_limit( apply_filters( 'pb_set_time_limit', 300, 'search' ) ); // @codingStandardsIgnoreLine if ( $this->regex ) { $error = $this->regexValidate( $search ); if ( null !== $error ) { return __( 'Invalid regular expression', 'pressbooks' ) . ': ' . $error; } return $this->find( $search, $limit, $offset, $orderby ); } else { return $this->find( '@' . preg_quote( $search, '@' ) . '@', $limit, $offset, $orderby ); } } return __( 'No search pattern.', 'pressbooks' ); }
[ "function", "searchForPattern", "(", "$", "search", ",", "$", "limit", ",", "$", "offset", ",", "$", "orderby", ")", "{", "if", "(", "!", "in_array", "(", "$", "orderby", ",", "[", "'asc'", ",", "'desc'", "]", ",", "true", ")", ")", "{", "$", "or...
@param string $search @param int $limit @param int $offset @param string $orderby @return string|\Pressbooks\Modules\SearchAndReplace\Result[]
[ "@param", "string", "$search", "@param", "int", "$limit", "@param", "int", "$offset", "@param", "string", "$orderby" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L115-L147
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.getSearches
static function getSearches() { static $search_types = null; // Cheap cache if ( ! is_array( $search_types ) ) { $classes = []; $files = glob( __DIR__ . '/types/*.php' ); foreach ( $files as $file ) { preg_match( '/class-(.*?)\.php/', $file, $match ); $class = __NAMESPACE__ . '\Types\\' . ucfirst( $match[1] ); if ( class_exists( $class ) ) { $classes[] = new $class; } } $search_types = $classes; } return $search_types; }
php
static function getSearches() { static $search_types = null; // Cheap cache if ( ! is_array( $search_types ) ) { $classes = []; $files = glob( __DIR__ . '/types/*.php' ); foreach ( $files as $file ) { preg_match( '/class-(.*?)\.php/', $file, $match ); $class = __NAMESPACE__ . '\Types\\' . ucfirst( $match[1] ); if ( class_exists( $class ) ) { $classes[] = new $class; } } $search_types = $classes; } return $search_types; }
[ "static", "function", "getSearches", "(", ")", "{", "static", "$", "search_types", "=", "null", ";", "// Cheap cache", "if", "(", "!", "is_array", "(", "$", "search_types", ")", ")", "{", "$", "classes", "=", "[", "]", ";", "$", "files", "=", "glob", ...
Scan types/*.php directory for classes we can use @return array
[ "Scan", "types", "/", "*", ".", "php", "directory", "for", "classes", "we", "can", "use" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L154-L169
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.validSearch
static function validSearch( $class ) { $classes = Search::getSearches(); foreach ( $classes as $item ) { if ( strcasecmp( get_class( $item ), $class ) === 0 ) { return true; } } return false; }
php
static function validSearch( $class ) { $classes = Search::getSearches(); foreach ( $classes as $item ) { if ( strcasecmp( get_class( $item ), $class ) === 0 ) { return true; } } return false; }
[ "static", "function", "validSearch", "(", "$", "class", ")", "{", "$", "classes", "=", "Search", "::", "getSearches", "(", ")", ";", "foreach", "(", "$", "classes", "as", "$", "item", ")", "{", "if", "(", "strcasecmp", "(", "get_class", "(", "$", "it...
@param string $class @return bool
[ "@param", "string", "$class" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L176-L184
pressbooks/pressbooks
inc/modules/searchandreplace/class-search.php
Search.matches
function matches( $pattern, $content, $id ) { $matches = null; if ( preg_match_all( $pattern, $content, $matches, PREG_OFFSET_CAPTURE ) > 0 ) { // Reduce memory usage by doing preg_replace() for the same $pattern/$replacement combination only once $content_replace = preg_replace( $pattern, $this->replace, $content ); $results = []; foreach ( $matches[0] as $found ) { if ( empty( $found[0] ) ) { continue; // Some weird regex looking for nothing? } $result = new Result(); $result->id = $id; $result->offset = $found[1]; $result->length = strlen( $found[0] ); // Extract the context - surrounding 40 characters either side // Index 0 is the match, index 1 is the position $start = $found[1] - 40; if ( $start < 0 ) { $start = 0; } $end = $found[1] + 40; if ( $end > strlen( $content ) ) { $end = strlen( $content ); } $end -= $start; $left = ltrim( substr( $content, $start, $found[1] - $start ), " \t," ); $right = rtrim( substr( $content, $found[1] + strlen( $found[0] ), $end ), " \t," ); $result->left = $start; $result->left_length = strlen( $found[0] ) + ( $found[1] - $start ) + $end; if ( 0 !== $start ) { $result->search = '&hellip;'; } $result->search .= esc_html( $left ); $result->search .= '<del>' . esc_html( $found[0] ) . '</del>'; $result->search .= esc_html( $right ); $result->search_plain = esc_html( $left ); $result->search_plain .= esc_html( $found[0] ); $result->search_plain .= esc_html( $right ); if ( $start + $end < strlen( $content ) ) { $result->search .= '&hellip;'; } if ( ! is_null( $this->replace ) ) { // Produce preview $rep = preg_replace( $pattern, $this->replace, $found[0] ); $result->replace_string = $rep; if ( 0 !== $start ) { $result->replace = '&hellip;'; } $result->replace .= esc_html( $left ); $result->replace .= '<ins>' . esc_html( $rep ) . '</ins></a>'; $result->replace .= esc_html( $right ); $result->left_length_replace = strlen( $left ) + strlen( $rep ) + strlen( $right ) + 1; $result->replace_plain = esc_html( $left ); $result->replace_plain .= esc_html( $rep ); $result->replace_plain .= esc_html( $right ); if ( $start + $end < strlen( $content ) ) { $result->replace .= '&hellip;'; } // And the real thing $result->content = $content_replace; } $results[] = $result; } return $results; } return false; }
php
function matches( $pattern, $content, $id ) { $matches = null; if ( preg_match_all( $pattern, $content, $matches, PREG_OFFSET_CAPTURE ) > 0 ) { // Reduce memory usage by doing preg_replace() for the same $pattern/$replacement combination only once $content_replace = preg_replace( $pattern, $this->replace, $content ); $results = []; foreach ( $matches[0] as $found ) { if ( empty( $found[0] ) ) { continue; // Some weird regex looking for nothing? } $result = new Result(); $result->id = $id; $result->offset = $found[1]; $result->length = strlen( $found[0] ); // Extract the context - surrounding 40 characters either side // Index 0 is the match, index 1 is the position $start = $found[1] - 40; if ( $start < 0 ) { $start = 0; } $end = $found[1] + 40; if ( $end > strlen( $content ) ) { $end = strlen( $content ); } $end -= $start; $left = ltrim( substr( $content, $start, $found[1] - $start ), " \t," ); $right = rtrim( substr( $content, $found[1] + strlen( $found[0] ), $end ), " \t," ); $result->left = $start; $result->left_length = strlen( $found[0] ) + ( $found[1] - $start ) + $end; if ( 0 !== $start ) { $result->search = '&hellip;'; } $result->search .= esc_html( $left ); $result->search .= '<del>' . esc_html( $found[0] ) . '</del>'; $result->search .= esc_html( $right ); $result->search_plain = esc_html( $left ); $result->search_plain .= esc_html( $found[0] ); $result->search_plain .= esc_html( $right ); if ( $start + $end < strlen( $content ) ) { $result->search .= '&hellip;'; } if ( ! is_null( $this->replace ) ) { // Produce preview $rep = preg_replace( $pattern, $this->replace, $found[0] ); $result->replace_string = $rep; if ( 0 !== $start ) { $result->replace = '&hellip;'; } $result->replace .= esc_html( $left ); $result->replace .= '<ins>' . esc_html( $rep ) . '</ins></a>'; $result->replace .= esc_html( $right ); $result->left_length_replace = strlen( $left ) + strlen( $rep ) + strlen( $right ) + 1; $result->replace_plain = esc_html( $left ); $result->replace_plain .= esc_html( $rep ); $result->replace_plain .= esc_html( $right ); if ( $start + $end < strlen( $content ) ) { $result->replace .= '&hellip;'; } // And the real thing $result->content = $content_replace; } $results[] = $result; } return $results; } return false; }
[ "function", "matches", "(", "$", "pattern", ",", "$", "content", ",", "$", "id", ")", "{", "$", "matches", "=", "null", ";", "if", "(", "preg_match_all", "(", "$", "pattern", ",", "$", "content", ",", "$", "matches", ",", "PREG_OFFSET_CAPTURE", ")", ...
@param string $pattern @param string $content @param int $id @return \Pressbooks\Modules\SearchAndReplace\Result[]|false
[ "@param", "string", "$pattern", "@param", "string", "$content", "@param", "int", "$id" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/searchandreplace/class-search.php#L193-L262
pressbooks/pressbooks
inc/shortcodes/wikipublisher/class-glyphs.php
Glyphs.init
public static function init() { if ( is_null( self::$instance ) ) { self::$instance = new self(); self::hooks( self::$instance ); } return self::$instance; }
php
public static function init() { if ( is_null( self::$instance ) ) { self::$instance = new self(); self::hooks( self::$instance ); } return self::$instance; }
[ "public", "static", "function", "init", "(", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "instance", ")", ")", "{", "self", "::", "$", "instance", "=", "new", "self", "(", ")", ";", "self", "::", "hooks", "(", "self", "::", "$", "inst...
Function to init our class, set filters & hooks, set a singleton instance @deprecated @return Glyphs
[ "Function", "to", "init", "our", "class", "set", "filters", "&", "hooks", "set", "a", "singleton", "instance" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/wikipublisher/class-glyphs.php#L36-L42
pressbooks/pressbooks
inc/shortcodes/wikipublisher/class-glyphs.php
Glyphs.langShortcode
public function langShortcode( $atts, $content = null ) { $a = shortcode_atts( [ 'lang' => '', ], $atts ); if ( empty( $content ) || empty( $a['lang'] ) || ! in_array( $a['lang'], $this->supported_languages, true ) ) { // We don't support this language $_error = "*** ERROR: Unsupported pb_language attribute: {$a['lang']} -- "; $_error .= 'Valid choices, based on ISO-639-3, are: ' . implode( $this->supported_languages, ', ' ) . ') ***'; return $_error; } // Reverse WordPress' fancy formatting // We want to keep all characters such as ‘ ` " '' [...] < > should be &gt; &lt; Ie. not numeric $content = str_replace( [ '&#8216;', '&#8217;', '&lsquo;', '&rsquo;' ], "'", $content ); // Change back to ' $content = str_replace( [ '&#8220;', '&#8221;', '&ldquo;', '&rdquo;' ], '"', $content ); // Change back to " $content = str_replace( [ '<br>', '<br />', '<p>', '</p>', '</p>' ], null, $content ); // Get rid of wpautop() auto-formatting $content = htmlspecialchars( $content, ENT_NOQUOTES, 'UTF-8', false ); $language = strtolower( $a['lang'] ); if ( 'grc' === $language ) { // Ancient Greek (polytonic) $content = '<span lang="grc">' . $this->greek( $content, 'grc' ) . '</span>'; } elseif ( 'ell' === $language ) { // Modern Greek (monotonic) $content = '<span lang="el">' . $this->greek( $content, 'ell' ) . '</span>'; } elseif ( 'hbo' === $language ) { // Ancient Hebrew $content = '<span lang="he" dir="rtl">' . $this->hebrew( $content ) . '</span>'; } return $content; }
php
public function langShortcode( $atts, $content = null ) { $a = shortcode_atts( [ 'lang' => '', ], $atts ); if ( empty( $content ) || empty( $a['lang'] ) || ! in_array( $a['lang'], $this->supported_languages, true ) ) { // We don't support this language $_error = "*** ERROR: Unsupported pb_language attribute: {$a['lang']} -- "; $_error .= 'Valid choices, based on ISO-639-3, are: ' . implode( $this->supported_languages, ', ' ) . ') ***'; return $_error; } // Reverse WordPress' fancy formatting // We want to keep all characters such as ‘ ` " '' [...] < > should be &gt; &lt; Ie. not numeric $content = str_replace( [ '&#8216;', '&#8217;', '&lsquo;', '&rsquo;' ], "'", $content ); // Change back to ' $content = str_replace( [ '&#8220;', '&#8221;', '&ldquo;', '&rdquo;' ], '"', $content ); // Change back to " $content = str_replace( [ '<br>', '<br />', '<p>', '</p>', '</p>' ], null, $content ); // Get rid of wpautop() auto-formatting $content = htmlspecialchars( $content, ENT_NOQUOTES, 'UTF-8', false ); $language = strtolower( $a['lang'] ); if ( 'grc' === $language ) { // Ancient Greek (polytonic) $content = '<span lang="grc">' . $this->greek( $content, 'grc' ) . '</span>'; } elseif ( 'ell' === $language ) { // Modern Greek (monotonic) $content = '<span lang="el">' . $this->greek( $content, 'ell' ) . '</span>'; } elseif ( 'hbo' === $language ) { // Ancient Hebrew $content = '<span lang="he" dir="rtl">' . $this->hebrew( $content ) . '</span>'; } return $content; }
[ "public", "function", "langShortcode", "(", "$", "atts", ",", "$", "content", "=", "null", ")", "{", "$", "a", "=", "shortcode_atts", "(", "[", "'lang'", "=>", "''", ",", "]", ",", "$", "atts", ")", ";", "if", "(", "empty", "(", "$", "content", "...
@param $atts @param null $content @return string
[ "@param", "$atts", "@param", "null", "$content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/wikipublisher/class-glyphs.php#L70-L107
pressbooks/pressbooks
inc/shortcodes/wikipublisher/class-glyphs.php
Glyphs.greek
private function greek( $text, $lang = 'grc' ) { $monotonics = [ "'a" => '&#940;', "'e" => '&#941;', "'h" => '&#942;', "'i" => '&#943;', "'o" => '&#972;', "'u" => '&#973;', "'w" => '&#974;', "'A" => '&#902;', "'E" => '&#904;', "'H" => '&#905;', "'I" => '&#906;', "'O" => '&#908;', "'U" => '&#910;', "'W" => '&#911;', "'\"i" => '&#912;', "'\"u" => '&#944;', ]; $polytonics = [ '&gt;`a|' => '&#8066;', '&gt;`h|' => '&#8082;', '&gt;`w|' => '&#8098;', "&gt;'a|" => '&#8068;', "&gt;'h|" => '&#8084;', "&gt;'w|" => '&#8100;', '&gt;`a' => '&#7938;', '&gt;`e' => '&#7954;', '&gt;`h' => '&#7970;', '&gt;`i' => '&#7986;', '&gt;`o' => '&#8002;', '&gt;`u' => '&#8018;', '&gt;`w' => '&#8034;', "&gt;'a" => '&#7940;', "&gt;'e" => '&#7956;', "&gt;'h" => '&#7972;', "&gt;'i" => '&#7988;', "&gt;'o" => '&#8004;', "&gt;'u" => '&#8020;', "&gt;'w" => '&#8036;', '&lt;`a|' => '&#8067;', '&lt;`h|' => '&#8083;', '&lt;`w|' => '&#8099;', "&lt;'a|" => '&#8069;', "&lt;'h|" => '&#8085;', "&lt;'w|" => '&#8101;', '&lt;`a' => '&#7939;', '&lt;`e' => '&#7955;', '&lt;`h' => '&#7971;', '&lt;`i' => '&#7987;', '&lt;`o' => '&#8003;', '&lt;`u' => '&#8019;', '&lt;`w' => '&#8035;', "&lt;'a" => '&#7941;', "&lt;'e" => '&#7957;', "&lt;'h" => '&#7973;', "&lt;'i" => '&#7989;', "&lt;'o" => '&#8005;', "&lt;'u" => '&#8021;', "&lt;'w" => '&#8037;', '&gt;`A|' => '&#8074;', '&gt;`H|' => '&#8090;', '&gt;`W|' => '&#8106;', "&gt;'A|" => '&#8076;', "&gt;'H|" => '&#8092;', "&gt;'W|" => '&#8108;', '&gt;`A' => '&#7946;', '&gt;`E' => '&#7962;', '&gt;`H' => '&#7978;', '&gt;`I' => '&#7994;', '&gt;`O' => '&#8010;', '&gt;`W' => '&#8042;', "&gt;'A" => '&#7948;', "&gt;'E" => '&#7964;', "&gt;'H" => '&#7980;', "&gt;'I" => '&#7996;', "&gt;'O" => '&#8012;', "&gt;'W" => '&#8044;', '&lt;`A|' => '&#8075;', '&lt;`H|' => '&#8091;', '&lt;`W|' => '&#8107;', "&lt;'A|" => '&#8077;', "&lt;'H|" => '&#8093;', "&lt;'W|" => '&#8109;', '&lt;`A' => '&#7947;', '&lt;`E' => '&#7963;', '&lt;`H' => '&#7979;', '&lt;`I' => '&#7995;', '&lt;`O' => '&#8011;', '&lt;`U' => '&#8027;', '&lt;`W' => '&#8043;', "&lt;'A" => '&#7949;', "&lt;'E" => '&#7965;', "&lt;'H" => '&#7981;', "&lt;'I" => '&#7997;', "&lt;'O" => '&#8013;', "&lt;'U" => '&#8029;', "&lt;'W" => '&#8045;', '`a|' => '&#8114;', "'a|" => '&#8116;', '`h|' => '&#8130;', "'h|" => '&#8132;', '`w|' => '&#8178;', "'w|" => '&#8180;', "'a" => '&#8049;', "'e" => '&#8051;', "'h" => '&#8053;', "'i" => '&#8055;', "'o" => '&#8057;', "'u" => '&#8059;', "'w" => '&#8061;', '`a' => '&#8048;', '`e' => '&#8050;', '`h' => '&#8052;', '`i' => '&#8054;', '`o' => '&#8056;', '`u' => '&#8058;', '`w' => '&#8060;', "'A" => '&#8123;', "'E" => '&#8137;', "'H" => '&#8139;', "'I" => '&#8155;', "'O" => '&#8185;', "'U" => '&#8171;', "'W" => '&#8187;', '`A' => '&#8122;', '`E' => '&#8136;', '`H' => '&#8138;', '`I' => '&#8154;', '`O' => '&#8184;', '`U' => '&#8170;', '`W' => '&#8186;', '~a|' => '&#8119;', '~h|' => '&#8135;', '~w|' => '&#8183;', '~a' => '&#8118;', '~h' => '&#8134;', '~i' => '&#8150;', '~u' => '&#8166;', '~w' => '&#8182;', '~&lt;a|' => '&#8071;', '~&lt;h|' => '&#8087;', '~&lt;w|' => '&#8103;', '~&lt;A|' => '&#8079;', '~&lt;H|' => '&#8095;', '~&lt;W|' => '&#8111;', '~&lt;a' => '&#7943;', '~&lt;h' => '&#7975;', '~&lt;i' => '&#7991;', '~&lt;u' => '&#8023;', '~&lt;w' => '&#8039;', '~&lt;A' => '&#7951;', '~&lt;H' => '&#7983;', '~&lt;I' => '&#7999;', '~&lt;U' => '&#8031;', '~&lt;W' => '&#8047;', '~&gt;a|' => '&#8070;', '~&gt;h|' => '&#8086;', '~&gt;w|' => '&#8102;', '~&gt;a' => '&#7942;', '~&gt;h' => '&#7974;', '~&gt;i' => '&#7990;', '~&gt;u' => '&#8022;', '~&gt;w' => '&#8038;', '~&gt;A|' => '&#8078;', '~&gt;H|' => '&#8094;', '~&gt;W|' => '&#8110;', '~&gt;A' => '&#7950;', '~&gt;H' => '&#7982;', '~&gt;I' => '&#7998;', '~&gt;W' => '&#8046;', '&gt;a|' => '&#8064;', '&lt;a|' => '&#8065;', '&gt;h|' => '&#8080;', '&lt;h|' => '&#8081;', '&gt;w|' => '&#8096;', '&lt;w|' => '&#8097;', '&gt;A|' => '&#8072;', '&lt;A|' => '&#8073;', '&gt;H|' => '&#8088;', '&lt;H|' => '&#8089;', '&gt;W|' => '&#8104;', '&lt;W|' => '&#8105;', '&gt;a' => '&#7936;', '&lt;a' => '&#7937;', '&gt;e' => '&#7952;', '&lt;e' => '&#7953;', '&gt;h' => '&#7968;', '&lt;h' => '&#7969;', '&gt;i' => '&#7984;', '&lt;i' => '&#7985;', '&gt;o' => '&#8000;', '&lt;o' => '&#8001;', '&gt;u' => '&#8016;', '&lt;u' => '&#8017;', '&gt;w' => '&#8032;', '&lt;w' => '&#8033;', '&gt;r' => '&#8164;', '&lt;r' => '&#8165;', 'a|' => '&#8115;', 'h|' => '&#8131;', 'w|' => '&#8179;', 'A|' => '&#8124;', 'H|' => '&#8140;', 'W|' => '&#8188;', '&gt;A' => '&#7944;', '&lt;A' => '&#7945;', '&gt;E' => '&#7960;', '&lt;E' => '&#7961;', '&gt;H' => '&#7976;', '&lt;H' => '&#7977;', '&gt;I' => '&#7992;', '&lt;I' => '&#7993;', '&gt;O' => '&#8008;', '&lt;O' => '&#8009;', '&lt;U' => '&#8025;', '&gt;W' => '&#8040;', '&lt;W' => '&#8041;', '&lt;R' => '&#8172;', '~"i' => '&#8151;', '~"u' => '&#8167;', "'\"i" => '&#8147;', "'\"u" => '&#8163;', '`"i' => '&#8146;', '`"u' => '&#8162;', ]; $gr_alphabet = [ '"i' => '&#970;', '"u' => '&#971;', '"I' => '&#938;', '"U' => '&#939;', 's ' => '&#962; ', 'sv' => '&#963;', 'a' => '&#945;', 'b' => '&#946;', 'c' => '&#962;', 'd' => '&#948;', 'e' => '&#949;', 'f' => '&#966;', 'g' => '&#947;', 'h' => '&#951;', 'i' => '&#953;', 'j' => '&#952;', 'k' => '&#954;', 'l' => '&#955;', 'm' => '&#956;', 'n' => '&#957;', 'o' => '&#959;', 'p' => '&#960;', 'q' => '&#967;', 'r' => '&#961;', 's' => '&#963;', 't' => '&#964;', 'u' => '&#965;', 'v' => '', 'w' => '&#969;', 'x' => '&#958;', 'y' => '&#968;', 'z' => '&#950;', 'A' => '&#913;', 'B' => '&#914;', 'C' => '', 'D' => '&#916;', 'E' => '&#917;', 'F' => '&#934;', 'G' => '&#915;', 'H' => '&#919;', 'I' => '&#921;', 'J' => '&#920;', 'K' => '&#922;', 'L' => '&#923;', 'M' => '&#924;', 'N' => '&#925;', 'O' => '&#927;', 'P' => '&#928;', 'Q' => '&#935;', 'R' => '&#929;', 'S' => '&#931;', 'T' => '&#932;', 'U' => '&#933;', 'V' => '', 'W' => '&#937;', 'X' => '&#926;', 'Y' => '&#936;', 'Z' => '&#918;', ';;' => ';&#903;', '?' => '&#894;', "''&" => '&lsquo;&', "''" => '&rsquo;', ]; $r = ( 'grc' === $lang ) ? str_replace( array_keys( $polytonics ), array_values( $polytonics ), $text ) : str_replace( array_keys( $monotonics ), array_values( $monotonics ), $text ); return str_replace( array_keys( $gr_alphabet ), array_values( $gr_alphabet ), $r ); }
php
private function greek( $text, $lang = 'grc' ) { $monotonics = [ "'a" => '&#940;', "'e" => '&#941;', "'h" => '&#942;', "'i" => '&#943;', "'o" => '&#972;', "'u" => '&#973;', "'w" => '&#974;', "'A" => '&#902;', "'E" => '&#904;', "'H" => '&#905;', "'I" => '&#906;', "'O" => '&#908;', "'U" => '&#910;', "'W" => '&#911;', "'\"i" => '&#912;', "'\"u" => '&#944;', ]; $polytonics = [ '&gt;`a|' => '&#8066;', '&gt;`h|' => '&#8082;', '&gt;`w|' => '&#8098;', "&gt;'a|" => '&#8068;', "&gt;'h|" => '&#8084;', "&gt;'w|" => '&#8100;', '&gt;`a' => '&#7938;', '&gt;`e' => '&#7954;', '&gt;`h' => '&#7970;', '&gt;`i' => '&#7986;', '&gt;`o' => '&#8002;', '&gt;`u' => '&#8018;', '&gt;`w' => '&#8034;', "&gt;'a" => '&#7940;', "&gt;'e" => '&#7956;', "&gt;'h" => '&#7972;', "&gt;'i" => '&#7988;', "&gt;'o" => '&#8004;', "&gt;'u" => '&#8020;', "&gt;'w" => '&#8036;', '&lt;`a|' => '&#8067;', '&lt;`h|' => '&#8083;', '&lt;`w|' => '&#8099;', "&lt;'a|" => '&#8069;', "&lt;'h|" => '&#8085;', "&lt;'w|" => '&#8101;', '&lt;`a' => '&#7939;', '&lt;`e' => '&#7955;', '&lt;`h' => '&#7971;', '&lt;`i' => '&#7987;', '&lt;`o' => '&#8003;', '&lt;`u' => '&#8019;', '&lt;`w' => '&#8035;', "&lt;'a" => '&#7941;', "&lt;'e" => '&#7957;', "&lt;'h" => '&#7973;', "&lt;'i" => '&#7989;', "&lt;'o" => '&#8005;', "&lt;'u" => '&#8021;', "&lt;'w" => '&#8037;', '&gt;`A|' => '&#8074;', '&gt;`H|' => '&#8090;', '&gt;`W|' => '&#8106;', "&gt;'A|" => '&#8076;', "&gt;'H|" => '&#8092;', "&gt;'W|" => '&#8108;', '&gt;`A' => '&#7946;', '&gt;`E' => '&#7962;', '&gt;`H' => '&#7978;', '&gt;`I' => '&#7994;', '&gt;`O' => '&#8010;', '&gt;`W' => '&#8042;', "&gt;'A" => '&#7948;', "&gt;'E" => '&#7964;', "&gt;'H" => '&#7980;', "&gt;'I" => '&#7996;', "&gt;'O" => '&#8012;', "&gt;'W" => '&#8044;', '&lt;`A|' => '&#8075;', '&lt;`H|' => '&#8091;', '&lt;`W|' => '&#8107;', "&lt;'A|" => '&#8077;', "&lt;'H|" => '&#8093;', "&lt;'W|" => '&#8109;', '&lt;`A' => '&#7947;', '&lt;`E' => '&#7963;', '&lt;`H' => '&#7979;', '&lt;`I' => '&#7995;', '&lt;`O' => '&#8011;', '&lt;`U' => '&#8027;', '&lt;`W' => '&#8043;', "&lt;'A" => '&#7949;', "&lt;'E" => '&#7965;', "&lt;'H" => '&#7981;', "&lt;'I" => '&#7997;', "&lt;'O" => '&#8013;', "&lt;'U" => '&#8029;', "&lt;'W" => '&#8045;', '`a|' => '&#8114;', "'a|" => '&#8116;', '`h|' => '&#8130;', "'h|" => '&#8132;', '`w|' => '&#8178;', "'w|" => '&#8180;', "'a" => '&#8049;', "'e" => '&#8051;', "'h" => '&#8053;', "'i" => '&#8055;', "'o" => '&#8057;', "'u" => '&#8059;', "'w" => '&#8061;', '`a' => '&#8048;', '`e' => '&#8050;', '`h' => '&#8052;', '`i' => '&#8054;', '`o' => '&#8056;', '`u' => '&#8058;', '`w' => '&#8060;', "'A" => '&#8123;', "'E" => '&#8137;', "'H" => '&#8139;', "'I" => '&#8155;', "'O" => '&#8185;', "'U" => '&#8171;', "'W" => '&#8187;', '`A' => '&#8122;', '`E' => '&#8136;', '`H' => '&#8138;', '`I' => '&#8154;', '`O' => '&#8184;', '`U' => '&#8170;', '`W' => '&#8186;', '~a|' => '&#8119;', '~h|' => '&#8135;', '~w|' => '&#8183;', '~a' => '&#8118;', '~h' => '&#8134;', '~i' => '&#8150;', '~u' => '&#8166;', '~w' => '&#8182;', '~&lt;a|' => '&#8071;', '~&lt;h|' => '&#8087;', '~&lt;w|' => '&#8103;', '~&lt;A|' => '&#8079;', '~&lt;H|' => '&#8095;', '~&lt;W|' => '&#8111;', '~&lt;a' => '&#7943;', '~&lt;h' => '&#7975;', '~&lt;i' => '&#7991;', '~&lt;u' => '&#8023;', '~&lt;w' => '&#8039;', '~&lt;A' => '&#7951;', '~&lt;H' => '&#7983;', '~&lt;I' => '&#7999;', '~&lt;U' => '&#8031;', '~&lt;W' => '&#8047;', '~&gt;a|' => '&#8070;', '~&gt;h|' => '&#8086;', '~&gt;w|' => '&#8102;', '~&gt;a' => '&#7942;', '~&gt;h' => '&#7974;', '~&gt;i' => '&#7990;', '~&gt;u' => '&#8022;', '~&gt;w' => '&#8038;', '~&gt;A|' => '&#8078;', '~&gt;H|' => '&#8094;', '~&gt;W|' => '&#8110;', '~&gt;A' => '&#7950;', '~&gt;H' => '&#7982;', '~&gt;I' => '&#7998;', '~&gt;W' => '&#8046;', '&gt;a|' => '&#8064;', '&lt;a|' => '&#8065;', '&gt;h|' => '&#8080;', '&lt;h|' => '&#8081;', '&gt;w|' => '&#8096;', '&lt;w|' => '&#8097;', '&gt;A|' => '&#8072;', '&lt;A|' => '&#8073;', '&gt;H|' => '&#8088;', '&lt;H|' => '&#8089;', '&gt;W|' => '&#8104;', '&lt;W|' => '&#8105;', '&gt;a' => '&#7936;', '&lt;a' => '&#7937;', '&gt;e' => '&#7952;', '&lt;e' => '&#7953;', '&gt;h' => '&#7968;', '&lt;h' => '&#7969;', '&gt;i' => '&#7984;', '&lt;i' => '&#7985;', '&gt;o' => '&#8000;', '&lt;o' => '&#8001;', '&gt;u' => '&#8016;', '&lt;u' => '&#8017;', '&gt;w' => '&#8032;', '&lt;w' => '&#8033;', '&gt;r' => '&#8164;', '&lt;r' => '&#8165;', 'a|' => '&#8115;', 'h|' => '&#8131;', 'w|' => '&#8179;', 'A|' => '&#8124;', 'H|' => '&#8140;', 'W|' => '&#8188;', '&gt;A' => '&#7944;', '&lt;A' => '&#7945;', '&gt;E' => '&#7960;', '&lt;E' => '&#7961;', '&gt;H' => '&#7976;', '&lt;H' => '&#7977;', '&gt;I' => '&#7992;', '&lt;I' => '&#7993;', '&gt;O' => '&#8008;', '&lt;O' => '&#8009;', '&lt;U' => '&#8025;', '&gt;W' => '&#8040;', '&lt;W' => '&#8041;', '&lt;R' => '&#8172;', '~"i' => '&#8151;', '~"u' => '&#8167;', "'\"i" => '&#8147;', "'\"u" => '&#8163;', '`"i' => '&#8146;', '`"u' => '&#8162;', ]; $gr_alphabet = [ '"i' => '&#970;', '"u' => '&#971;', '"I' => '&#938;', '"U' => '&#939;', 's ' => '&#962; ', 'sv' => '&#963;', 'a' => '&#945;', 'b' => '&#946;', 'c' => '&#962;', 'd' => '&#948;', 'e' => '&#949;', 'f' => '&#966;', 'g' => '&#947;', 'h' => '&#951;', 'i' => '&#953;', 'j' => '&#952;', 'k' => '&#954;', 'l' => '&#955;', 'm' => '&#956;', 'n' => '&#957;', 'o' => '&#959;', 'p' => '&#960;', 'q' => '&#967;', 'r' => '&#961;', 's' => '&#963;', 't' => '&#964;', 'u' => '&#965;', 'v' => '', 'w' => '&#969;', 'x' => '&#958;', 'y' => '&#968;', 'z' => '&#950;', 'A' => '&#913;', 'B' => '&#914;', 'C' => '', 'D' => '&#916;', 'E' => '&#917;', 'F' => '&#934;', 'G' => '&#915;', 'H' => '&#919;', 'I' => '&#921;', 'J' => '&#920;', 'K' => '&#922;', 'L' => '&#923;', 'M' => '&#924;', 'N' => '&#925;', 'O' => '&#927;', 'P' => '&#928;', 'Q' => '&#935;', 'R' => '&#929;', 'S' => '&#931;', 'T' => '&#932;', 'U' => '&#933;', 'V' => '', 'W' => '&#937;', 'X' => '&#926;', 'Y' => '&#936;', 'Z' => '&#918;', ';;' => ';&#903;', '?' => '&#894;', "''&" => '&lsquo;&', "''" => '&rsquo;', ]; $r = ( 'grc' === $lang ) ? str_replace( array_keys( $polytonics ), array_values( $polytonics ), $text ) : str_replace( array_keys( $monotonics ), array_values( $monotonics ), $text ); return str_replace( array_keys( $gr_alphabet ), array_values( $gr_alphabet ), $r ); }
[ "private", "function", "greek", "(", "$", "text", ",", "$", "lang", "=", "'grc'", ")", "{", "$", "monotonics", "=", "[", "\"'a\"", "=>", "'&#940;'", ",", "\"'e\"", "=>", "'&#941;'", ",", "\"'h\"", "=>", "'&#942;'", ",", "\"'i\"", "=>", "'&#943;'", ",",...
@param $text @param string $lang @return string
[ "@param", "$text", "@param", "string", "$lang" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/shortcodes/wikipublisher/class-glyphs.php#L116-L421
pressbooks/pressbooks
inc/covergenerator/class-spine.php
Spine.countPagesInMostRecentPdf
public function countPagesInMostRecentPdf() { $files = \Pressbooks\Utility\group_exports(); if ( empty( $files ) ) { return 0; } foreach ( $files as $date => $exports ) { foreach ( $exports as $file ) { $file_extension = substr( strrchr( $file, '.' ), 1 ); if ( 'pdf' === $file_extension ) { $path_to_pdf = \Pressbooks\Modules\Export\Export::getExportFolder() . $file; break 2; } } } if ( empty( $path_to_pdf ) ) { return 0; } try { return $this->countPagesInPdf( $path_to_pdf ); } catch ( \Exception $e ) { return 0; } }
php
public function countPagesInMostRecentPdf() { $files = \Pressbooks\Utility\group_exports(); if ( empty( $files ) ) { return 0; } foreach ( $files as $date => $exports ) { foreach ( $exports as $file ) { $file_extension = substr( strrchr( $file, '.' ), 1 ); if ( 'pdf' === $file_extension ) { $path_to_pdf = \Pressbooks\Modules\Export\Export::getExportFolder() . $file; break 2; } } } if ( empty( $path_to_pdf ) ) { return 0; } try { return $this->countPagesInPdf( $path_to_pdf ); } catch ( \Exception $e ) { return 0; } }
[ "public", "function", "countPagesInMostRecentPdf", "(", ")", "{", "$", "files", "=", "\\", "Pressbooks", "\\", "Utility", "\\", "group_exports", "(", ")", ";", "if", "(", "empty", "(", "$", "files", ")", ")", "{", "return", "0", ";", "}", "foreach", "(...
Count the pages in the most recent PDF export @return int
[ "Count", "the", "pages", "in", "the", "most", "recent", "PDF", "export" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-spine.php#L81-L107
pressbooks/pressbooks
inc/covergenerator/class-spine.php
Spine.countPagesInPdf
public function countPagesInPdf( $path_to_pdf ) { if ( ! file_exists( $path_to_pdf ) ) { throw new \InvalidArgumentException( "File not found: $path_to_pdf" ); } $output = []; $return_var = 0; $command = PB_PDFINFO_COMMAND . ' ' . escapeshellarg( $path_to_pdf ) . ' | awk \'/Pages/ {print $2}\''; exec( $command, $output, $return_var ); // @codingStandardsIgnoreLine return (int) $output[0]; }
php
public function countPagesInPdf( $path_to_pdf ) { if ( ! file_exists( $path_to_pdf ) ) { throw new \InvalidArgumentException( "File not found: $path_to_pdf" ); } $output = []; $return_var = 0; $command = PB_PDFINFO_COMMAND . ' ' . escapeshellarg( $path_to_pdf ) . ' | awk \'/Pages/ {print $2}\''; exec( $command, $output, $return_var ); // @codingStandardsIgnoreLine return (int) $output[0]; }
[ "public", "function", "countPagesInPdf", "(", "$", "path_to_pdf", ")", "{", "if", "(", "!", "file_exists", "(", "$", "path_to_pdf", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"File not found: $path_to_pdf\"", ")", ";", "}", "$", "o...
Count the pages in a PDF file @param $path_to_pdf @return int
[ "Count", "the", "pages", "in", "a", "PDF", "file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-spine.php#L117-L129
pressbooks/pressbooks
inc/class-metadata.php
Metadata.getMetaPostId
public function getMetaPostId() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, 'fields' => 'ids', ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return 0; } return $results[0]; }
php
public function getMetaPostId() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, 'fields' => 'ids', ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return 0; } return $results[0]; }
[ "public", "function", "getMetaPostId", "(", ")", "{", "$", "args", "=", "[", "'post_type'", "=>", "'metadata'", ",", "'posts_per_page'", "=>", "1", ",", "'post_status'", "=>", "'publish'", ",", "'orderby'", "=>", "'modified'", ",", "'no_found_rows'", "=>", "tr...
Returns the latest "metadata" post ID. There should be only one per book. @return int
[ "Returns", "the", "latest", "metadata", "post", "ID", ".", "There", "should", "be", "only", "one", "per", "book", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L48-L67
pressbooks/pressbooks
inc/class-metadata.php
Metadata.getMetaPost
public function getMetaPost() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return false; } return $results[0]; }
php
public function getMetaPost() { $args = [ 'post_type' => 'metadata', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'modified', 'no_found_rows' => true, 'cache_results' => true, ]; $q = new \WP_Query(); $results = $q->query( $args ); if ( empty( $results ) ) { return false; } return $results[0]; }
[ "public", "function", "getMetaPost", "(", ")", "{", "$", "args", "=", "[", "'post_type'", "=>", "'metadata'", ",", "'posts_per_page'", "=>", "1", ",", "'post_status'", "=>", "'publish'", ",", "'orderby'", "=>", "'modified'", ",", "'no_found_rows'", "=>", "true...
Returns the latest "metadata" post. There should be only one per book. @return \WP_Post|bool
[ "Returns", "the", "latest", "metadata", "post", ".", "There", "should", "be", "only", "one", "per", "book", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L75-L94
pressbooks/pressbooks
inc/class-metadata.php
Metadata.getMidByKey
public function getMidByKey( $post_id, $meta_key ) { /** @var \wpdb $wpdb */ global $wpdb; $mid = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s LIMIT 1 ", $post_id, $meta_key ) ); if ( ! empty( $mid ) ) { return absint( $mid ); } return false; }
php
public function getMidByKey( $post_id, $meta_key ) { /** @var \wpdb $wpdb */ global $wpdb; $mid = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s LIMIT 1 ", $post_id, $meta_key ) ); if ( ! empty( $mid ) ) { return absint( $mid ); } return false; }
[ "public", "function", "getMidByKey", "(", "$", "post_id", ",", "$", "meta_key", ")", "{", "/** @var \\wpdb $wpdb */", "global", "$", "wpdb", ";", "$", "mid", "=", "$", "wpdb", "->", "get_var", "(", "$", "wpdb", "->", "prepare", "(", "\"SELECT meta_id FROM $w...
Return a database ID for a given meta key. @param int $post_id @param string $meta_key @return int|bool
[ "Return", "a", "database", "ID", "for", "a", "given", "meta", "key", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L122-L132
pressbooks/pressbooks
inc/class-metadata.php
Metadata.jsonSerialize
public function jsonSerialize() { $request = new \WP_REST_Request( 'GET', '/pressbooks/v2/metadata' ); $meta = new \Pressbooks\Api\Endpoints\Controller\Metadata(); $metadata = $meta ->get_item( $request ) ->get_data(); return apply_filters( 'pb_json_metadata', $metadata ); }
php
public function jsonSerialize() { $request = new \WP_REST_Request( 'GET', '/pressbooks/v2/metadata' ); $meta = new \Pressbooks\Api\Endpoints\Controller\Metadata(); $metadata = $meta ->get_item( $request ) ->get_data(); return apply_filters( 'pb_json_metadata', $metadata ); }
[ "public", "function", "jsonSerialize", "(", ")", "{", "$", "request", "=", "new", "\\", "WP_REST_Request", "(", "'GET'", ",", "'/pressbooks/v2/metadata'", ")", ";", "$", "meta", "=", "new", "\\", "Pressbooks", "\\", "Api", "\\", "Endpoints", "\\", "Controlle...
Returns a JSON object of the book information which can be posted to an API. @since 4.0.0 @return array
[ "Returns", "a", "JSON", "object", "of", "the", "book", "information", "which", "can", "be", "posted", "to", "an", "API", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L141-L150
pressbooks/pressbooks
inc/class-metadata.php
Metadata.upgrade
public function upgrade( $version ) { if ( $version < 1 ) { // Upgrade from version 0 (closed source service) to version 1 (initial open source offering) $this->upgradeEcommerce(); $this->upgradeBookInformation(); $this->upgradeBook(); } if ( $version < 3 ) { \Pressbooks\CustomCss::upgradeCustomCss(); } if ( $version < 4 ) { $this->fixDoubleSlashBug(); } if ( $version < 5 ) { $this->changeDefaultBookCover(); } if ( $version < 6 || $version < 7 ) { $this->makeThumbnailsForBookCover(); } if ( $version < 8 ) { $this->resetLandingPage(); } if ( $version < 10 ) { $taxonomy = Taxonomy::init(); $taxonomy->insertTerms(); flush_rewrite_rules( false ); } if ( $version < 11 ) { $this->migratePartContentToEditor(); } if ( $version < 12 ) { Container::get( 'Styles' )->initPosts(); } if ( $version < 13 ) { $this->upgradeToPressbooksFive(); } }
php
public function upgrade( $version ) { if ( $version < 1 ) { // Upgrade from version 0 (closed source service) to version 1 (initial open source offering) $this->upgradeEcommerce(); $this->upgradeBookInformation(); $this->upgradeBook(); } if ( $version < 3 ) { \Pressbooks\CustomCss::upgradeCustomCss(); } if ( $version < 4 ) { $this->fixDoubleSlashBug(); } if ( $version < 5 ) { $this->changeDefaultBookCover(); } if ( $version < 6 || $version < 7 ) { $this->makeThumbnailsForBookCover(); } if ( $version < 8 ) { $this->resetLandingPage(); } if ( $version < 10 ) { $taxonomy = Taxonomy::init(); $taxonomy->insertTerms(); flush_rewrite_rules( false ); } if ( $version < 11 ) { $this->migratePartContentToEditor(); } if ( $version < 12 ) { Container::get( 'Styles' )->initPosts(); } if ( $version < 13 ) { $this->upgradeToPressbooksFive(); } }
[ "public", "function", "upgrade", "(", "$", "version", ")", "{", "if", "(", "$", "version", "<", "1", ")", "{", "// Upgrade from version 0 (closed source service) to version 1 (initial open source offering)", "$", "this", "->", "upgradeEcommerce", "(", ")", ";", "$", ...
Upgrade metadata. @param int $version
[ "Upgrade", "metadata", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L161-L198
pressbooks/pressbooks
inc/class-metadata.php
Metadata.upgradeEcommerce
public function upgradeEcommerce() { $options = get_option( 'ecomm-url' ); $compare = $this->getDeprecatedComparisonTable( 'ecommerce' ); $new_options = []; if ( $options ) { foreach ( $options as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $new_options[ $new_meta_key ] = $meta_value; } } } update_option( 'pressbooks_ecommerce_links', $new_options ); delete_option( 'ecomm-url' ); }
php
public function upgradeEcommerce() { $options = get_option( 'ecomm-url' ); $compare = $this->getDeprecatedComparisonTable( 'ecommerce' ); $new_options = []; if ( $options ) { foreach ( $options as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $new_options[ $new_meta_key ] = $meta_value; } } } update_option( 'pressbooks_ecommerce_links', $new_options ); delete_option( 'ecomm-url' ); }
[ "public", "function", "upgradeEcommerce", "(", ")", "{", "$", "options", "=", "get_option", "(", "'ecomm-url'", ")", ";", "$", "compare", "=", "$", "this", "->", "getDeprecatedComparisonTable", "(", "'ecommerce'", ")", ";", "$", "new_options", "=", "[", "]",...
Upgrade Ecommerce metadata - from version 0 (closed source) to version 1 (first open source version, february 2013) @deprecated
[ "Upgrade", "Ecommerce", "metadata", "-", "from", "version", "0", "(", "closed", "source", ")", "to", "version", "1", "(", "first", "open", "source", "version", "february", "2013", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L206-L223
pressbooks/pressbooks
inc/class-metadata.php
Metadata.upgradeBookInformation
public function upgradeBookInformation() { // Metadata $meta_post = $this->getMetaPost(); if ( ! $meta_post ) { return; // Do nothing } $metadata = $this->getMetaPostMetadata(); $compare = $this->getDeprecatedComparisonTable( 'metadata' ); foreach ( $metadata as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $meta_post->ID, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Overrides if ( 'pb_language' === $new_meta_key ) { $meta_value = substr( strtolower( $meta_value ), 0, 2 ); } if ( 'pb_publication_date' === $new_meta_key ) { $meta_value = strtotime( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } // Force title change update_metadata( 'post', $meta_post->ID, 'pb_title', get_bloginfo( 'name' ) ); }
php
public function upgradeBookInformation() { // Metadata $meta_post = $this->getMetaPost(); if ( ! $meta_post ) { return; // Do nothing } $metadata = $this->getMetaPostMetadata(); $compare = $this->getDeprecatedComparisonTable( 'metadata' ); foreach ( $metadata as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $meta_post->ID, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Overrides if ( 'pb_language' === $new_meta_key ) { $meta_value = substr( strtolower( $meta_value ), 0, 2 ); } if ( 'pb_publication_date' === $new_meta_key ) { $meta_value = strtotime( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } // Force title change update_metadata( 'post', $meta_post->ID, 'pb_title', get_bloginfo( 'name' ) ); }
[ "public", "function", "upgradeBookInformation", "(", ")", "{", "// Metadata", "$", "meta_post", "=", "$", "this", "->", "getMetaPost", "(", ")", ";", "if", "(", "!", "$", "meta_post", ")", "{", "return", ";", "// Do nothing", "}", "$", "metadata", "=", "...
Upgrade book information - from version 0 (closed source) to version 1 (first open source version, february 2013) @deprecated
[ "Upgrade", "book", "information", "-", "from", "version", "0", "(", "closed", "source", ")", "to", "version", "1", "(", "first", "open", "source", "version", "february", "2013", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L231-L270
pressbooks/pressbooks
inc/class-metadata.php
Metadata.upgradeBook
public function upgradeBook() { $book_structure = Book::getBookStructure(); foreach ( $book_structure['__order'] as $post_id => $_ ) { $meta = get_post_meta( $post_id ); $compare = $this->getDeprecatedComparisonTable( get_post_type( $post_id ) ); foreach ( $meta as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $post_id, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } } }
php
public function upgradeBook() { $book_structure = Book::getBookStructure(); foreach ( $book_structure['__order'] as $post_id => $_ ) { $meta = get_post_meta( $post_id ); $compare = $this->getDeprecatedComparisonTable( get_post_type( $post_id ) ); foreach ( $meta as $meta_key => $meta_value ) { $new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false; if ( $new_meta_key ) { $meta_id = $this->getMidByKey( $post_id, $meta_key ); if ( $meta_id ) { if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) { $meta_value = 'on'; } elseif ( is_array( $meta_value ) ) { $meta_value = array_values( $meta_value ); $meta_value = array_pop( $meta_value ); } // Update the original $meta_key to the $new_meta_key update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key ); } } } } }
[ "public", "function", "upgradeBook", "(", ")", "{", "$", "book_structure", "=", "Book", "::", "getBookStructure", "(", ")", ";", "foreach", "(", "$", "book_structure", "[", "'__order'", "]", "as", "$", "post_id", "=>", "$", "_", ")", "{", "$", "meta", ...
Upgrade book metadata - from version 0 (closed source) to version 1 (first open source version, february 2013) @deprecated
[ "Upgrade", "book", "metadata", "-", "from", "version", "0", "(", "closed", "source", ")", "to", "version", "1", "(", "first", "open", "source", "version", "february", "2013", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L278-L304
pressbooks/pressbooks
inc/class-metadata.php
Metadata.getDeprecatedComparisonTable
public function getDeprecatedComparisonTable( $table, $new_as_keys = false ) { if ( 'chapter' === $table ) { // Chapter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'chapter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'front-matter' === $table ) { // Front Matter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'front-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'back-matter' === $table ) { // Back Matter $metadata = [ 'back-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'ecommerce' === $table ) { // Ecommerce $metadata = [ 'url1' => 'amazon', 'url2' => 'oreilly', 'url3' => 'barnesandnoble', 'url4' => 'kobo', 'url5' => 'ibooks', 'url6' => 'otherservice', ]; } elseif ( 'metadata' === $table ) { // Book Information $metadata = [ 'Title' => 'pb_title', 'Short Title' => 'pb_short_title', 'Subtitle' => 'pb_subtitle', 'Author' => 'pb_author', 'Author, file as' => 'pb_author_file_as', 'Publisher' => 'pb_publisher', 'Publication Date' => 'pb_publication_date', 'Publisher City' => 'pb_publisher_city', 'Cover Image' => 'pb_cover_image', 'Copyright Year' => 'pb_copyright_year', 'Copyright Holder' => 'pb_copyright_holder', 'Copyright Extra Info' => 'pb_custom_copyright', 'About (140 characters)' => 'pb_about_140', 'About (50 words)' => 'pb_about_50', 'About (Unlimited)' => 'pb_about_unlimited', 'Series Title' => 'pb_series_title', 'Series Number' => 'pb_series_number', 'Editor' => 'pb_editor', 'Translator' => 'pb_translator', 'Keywords/Tags' => 'pb_keywords_tags', 'Hashtag' => 'pb_hashtag', 'Print ISBN' => 'pb_print_isbn', 'Ebook ISBN' => 'pb_ebook_isbn', 'Language' => 'pb_language', 'List Price (Print)' => 'pb_list_price_print', 'List Price (PDF)' => 'pb_list_price_pdf', 'List Price (ePub)' => 'pb_list_price_epub', 'List Price (Web)' => 'pb_list_price_web', 'Bisac Subject 1' => 'pb_bisac_subject', 'Bisac Regional Theme' => 'pb_bisac_regional_theme', 'catalogue_order' => 'pb_catalogue_order', ]; } else { $metadata = []; } if ( $new_as_keys ) { $metadata = array_flip( $metadata ); } return $metadata; }
php
public function getDeprecatedComparisonTable( $table, $new_as_keys = false ) { if ( 'chapter' === $table ) { // Chapter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'chapter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'front-matter' === $table ) { // Front Matter $metadata = [ 'short-title' => 'pb_short_title', 'subtitle' => 'pb_subtitle', 'chap_author' => 'pb_section_author', 'front-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'back-matter' === $table ) { // Back Matter $metadata = [ 'back-matter-export' => 'pb_export', 'show-title' => 'pb_show_title', ]; } elseif ( 'ecommerce' === $table ) { // Ecommerce $metadata = [ 'url1' => 'amazon', 'url2' => 'oreilly', 'url3' => 'barnesandnoble', 'url4' => 'kobo', 'url5' => 'ibooks', 'url6' => 'otherservice', ]; } elseif ( 'metadata' === $table ) { // Book Information $metadata = [ 'Title' => 'pb_title', 'Short Title' => 'pb_short_title', 'Subtitle' => 'pb_subtitle', 'Author' => 'pb_author', 'Author, file as' => 'pb_author_file_as', 'Publisher' => 'pb_publisher', 'Publication Date' => 'pb_publication_date', 'Publisher City' => 'pb_publisher_city', 'Cover Image' => 'pb_cover_image', 'Copyright Year' => 'pb_copyright_year', 'Copyright Holder' => 'pb_copyright_holder', 'Copyright Extra Info' => 'pb_custom_copyright', 'About (140 characters)' => 'pb_about_140', 'About (50 words)' => 'pb_about_50', 'About (Unlimited)' => 'pb_about_unlimited', 'Series Title' => 'pb_series_title', 'Series Number' => 'pb_series_number', 'Editor' => 'pb_editor', 'Translator' => 'pb_translator', 'Keywords/Tags' => 'pb_keywords_tags', 'Hashtag' => 'pb_hashtag', 'Print ISBN' => 'pb_print_isbn', 'Ebook ISBN' => 'pb_ebook_isbn', 'Language' => 'pb_language', 'List Price (Print)' => 'pb_list_price_print', 'List Price (PDF)' => 'pb_list_price_pdf', 'List Price (ePub)' => 'pb_list_price_epub', 'List Price (Web)' => 'pb_list_price_web', 'Bisac Subject 1' => 'pb_bisac_subject', 'Bisac Regional Theme' => 'pb_bisac_regional_theme', 'catalogue_order' => 'pb_catalogue_order', ]; } else { $metadata = []; } if ( $new_as_keys ) { $metadata = array_flip( $metadata ); } return $metadata; }
[ "public", "function", "getDeprecatedComparisonTable", "(", "$", "table", ",", "$", "new_as_keys", "=", "false", ")", "{", "if", "(", "'chapter'", "===", "$", "table", ")", "{", "// Chapter", "$", "metadata", "=", "[", "'short-title'", "=>", "'pb_short_title'",...
Upgrade from version 0 (closed source) to version 1 (first open source version, february 2013) @deprecated @param string $table @param bool $new_as_keys @return array
[ "Upgrade", "from", "version", "0", "(", "closed", "source", ")", "to", "version", "1", "(", "first", "open", "source", "version", "february", "2013", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L317-L396
pressbooks/pressbooks
inc/class-metadata.php
Metadata.fixDoubleSlashBug
public function fixDoubleSlashBug() { $theme = wp_get_theme(); if ( ! $theme->exists() || ! $theme->is_allowed() ) { return; // Do nothing } else { switch_theme( $theme->get_stylesheet() ); } }
php
public function fixDoubleSlashBug() { $theme = wp_get_theme(); if ( ! $theme->exists() || ! $theme->is_allowed() ) { return; // Do nothing } else { switch_theme( $theme->get_stylesheet() ); } }
[ "public", "function", "fixDoubleSlashBug", "(", ")", "{", "$", "theme", "=", "wp_get_theme", "(", ")", ";", "if", "(", "!", "$", "theme", "->", "exists", "(", ")", "||", "!", "$", "theme", "->", "is_allowed", "(", ")", ")", "{", "return", ";", "// ...
Fix a double slash bug by reactivating theme with new settings. @see \Pressbooks\Pressbooks::registerThemeDirectories
[ "Fix", "a", "double", "slash", "bug", "by", "reactivating", "theme", "with", "new", "settings", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L403-L411
pressbooks/pressbooks
inc/class-metadata.php
Metadata.changeDefaultBookCover
public function changeDefaultBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( preg_match( '~assets/images/default-book-cover\.png$~', $pb_cover_image ) ) { update_post_meta( $post->ID, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); Book::deleteBookObjectCache(); } } }
php
public function changeDefaultBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( preg_match( '~assets/images/default-book-cover\.png$~', $pb_cover_image ) ) { update_post_meta( $post->ID, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); Book::deleteBookObjectCache(); } } }
[ "public", "function", "changeDefaultBookCover", "(", ")", "{", "$", "post", "=", "$", "this", "->", "getMetaPost", "(", ")", ";", "if", "(", "$", "post", ")", "{", "$", "pb_cover_image", "=", "get_post_meta", "(", "$", "post", "->", "ID", ",", "'pb_cov...
Change default book cover from PNG to JPG
[ "Change", "default", "book", "cover", "from", "PNG", "to", "JPG" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L417-L428
pressbooks/pressbooks
inc/class-metadata.php
Metadata.makeThumbnailsForBookCover
public function makeThumbnailsForBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( $pb_cover_image && ! \Pressbooks\Image\is_default_cover( $pb_cover_image ) ) { $path = \Pressbooks\Utility\get_media_path( $pb_cover_image ); $type = wp_check_filetype( $path ); $type = $type['type']; // Insert new image, create thumbnails $args = [ 'post_mime_type' => $type, 'post_title' => __( 'Cover Image', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', ]; include_once( ABSPATH . 'wp-admin/includes/image.php' ); $id = wp_insert_attachment( $args, $path, $post->ID ); wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $path ) ); Book::deleteBookObjectCache(); } } }
php
public function makeThumbnailsForBookCover() { $post = $this->getMetaPost(); if ( $post ) { $pb_cover_image = get_post_meta( $post->ID, 'pb_cover_image', true ); if ( $pb_cover_image && ! \Pressbooks\Image\is_default_cover( $pb_cover_image ) ) { $path = \Pressbooks\Utility\get_media_path( $pb_cover_image ); $type = wp_check_filetype( $path ); $type = $type['type']; // Insert new image, create thumbnails $args = [ 'post_mime_type' => $type, 'post_title' => __( 'Cover Image', 'pressbooks' ), 'post_content' => '', 'post_status' => 'inherit', ]; include_once( ABSPATH . 'wp-admin/includes/image.php' ); $id = wp_insert_attachment( $args, $path, $post->ID ); wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $path ) ); Book::deleteBookObjectCache(); } } }
[ "public", "function", "makeThumbnailsForBookCover", "(", ")", "{", "$", "post", "=", "$", "this", "->", "getMetaPost", "(", ")", ";", "if", "(", "$", "post", ")", "{", "$", "pb_cover_image", "=", "get_post_meta", "(", "$", "post", "->", "ID", ",", "'pb...
Generate thumbnails for a user uploaded cover
[ "Generate", "thumbnails", "for", "a", "user", "uploaded", "cover" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L434-L460
pressbooks/pressbooks
inc/class-metadata.php
Metadata.resetLandingPage
public function resetLandingPage() { /** @var $wpdb \wpdb */ global $wpdb; update_option( 'show_on_front', 'page' ); $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'cover' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_on_front', $id ); } $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'table-of-contents' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_for_posts', $id ); } }
php
public function resetLandingPage() { /** @var $wpdb \wpdb */ global $wpdb; update_option( 'show_on_front', 'page' ); $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'cover' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_on_front', $id ); } $id = $wpdb->get_var( "SELECT ID FROM {$wpdb->posts} WHERE post_name = 'table-of-contents' AND post_type = 'page' AND post_status = 'publish' " ); if ( $id ) { update_option( 'page_for_posts', $id ); } }
[ "public", "function", "resetLandingPage", "(", ")", "{", "/** @var $wpdb \\wpdb */", "global", "$", "wpdb", ";", "update_option", "(", "'show_on_front'", ",", "'page'", ")", ";", "$", "id", "=", "$", "wpdb", "->", "get_var", "(", "\"SELECT ID FROM {$wpdb->posts} W...
Fix broken landing page
[ "Fix", "broken", "landing", "page" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L466-L482
pressbooks/pressbooks
inc/class-metadata.php
Metadata.migratePartContentToEditor
public function migratePartContentToEditor() { /** @var $wpdb \wpdb */ global $wpdb; $parts = $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'part' AND post_status = 'publish' " ); foreach ( $parts as $part ) { $pb_part_content = trim( get_post_meta( $part->ID, 'pb_part_content', true ) ); if ( $pb_part_content ) { $success = wp_update_post( [ 'ID' => $part->ID, 'post_content' => $pb_part_content, 'comment_status' => 'closed', ] ); if ( $success === $part->ID ) { delete_post_meta( $part->ID, 'pb_part_content' ); } } } Book::deleteBookObjectCache(); }
php
public function migratePartContentToEditor() { /** @var $wpdb \wpdb */ global $wpdb; $parts = $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'part' AND post_status = 'publish' " ); foreach ( $parts as $part ) { $pb_part_content = trim( get_post_meta( $part->ID, 'pb_part_content', true ) ); if ( $pb_part_content ) { $success = wp_update_post( [ 'ID' => $part->ID, 'post_content' => $pb_part_content, 'comment_status' => 'closed', ] ); if ( $success === $part->ID ) { delete_post_meta( $part->ID, 'pb_part_content' ); } } } Book::deleteBookObjectCache(); }
[ "public", "function", "migratePartContentToEditor", "(", ")", "{", "/** @var $wpdb \\wpdb */", "global", "$", "wpdb", ";", "$", "parts", "=", "$", "wpdb", "->", "get_results", "(", "\"SELECT ID FROM {$wpdb->posts} WHERE post_type = 'part' AND post_status = 'publish' \"", ")",...
Migrate part content to content editor
[ "Migrate", "part", "content", "to", "content", "editor" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L488-L511
pressbooks/pressbooks
inc/class-metadata.php
Metadata.postStatiiConversion
public function postStatiiConversion( $status, $pb_export ) { if ( ! is_bool( $pb_export ) ) { return $status; // Doing it wrong... } if ( $pb_export ) { // When pb_export = true and post_status = draft, new post_status = private if ( $status === 'draft' ) { return 'private'; } // When pb_export = true and post_status = publish, new post_status = publish if ( $status === 'publish' ) { return 'publish'; } } else { // When pb_export = false and post_status = draft, new post_status = draft if ( $status === 'draft' ) { return 'draft'; } // When pb_export = false and post_status = publish, new post_status = web-only if ( $status === 'publish' ) { return 'web-only'; } } return $status; // No change }
php
public function postStatiiConversion( $status, $pb_export ) { if ( ! is_bool( $pb_export ) ) { return $status; // Doing it wrong... } if ( $pb_export ) { // When pb_export = true and post_status = draft, new post_status = private if ( $status === 'draft' ) { return 'private'; } // When pb_export = true and post_status = publish, new post_status = publish if ( $status === 'publish' ) { return 'publish'; } } else { // When pb_export = false and post_status = draft, new post_status = draft if ( $status === 'draft' ) { return 'draft'; } // When pb_export = false and post_status = publish, new post_status = web-only if ( $status === 'publish' ) { return 'web-only'; } } return $status; // No change }
[ "public", "function", "postStatiiConversion", "(", "$", "status", ",", "$", "pb_export", ")", "{", "if", "(", "!", "is_bool", "(", "$", "pb_export", ")", ")", "{", "return", "$", "status", ";", "// Doing it wrong...", "}", "if", "(", "$", "pb_export", ")...
@since 5.0.0 @param string $status @param bool $pb_export @return string
[ "@since", "5", ".", "0", ".", "0" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-metadata.php#L562-L589
pressbooks/pressbooks
inc/covergenerator/class-princepdf.php
PrincePdf.generate
public function generate() { $output_path = $this->timestampedFileName( 'pdf' ); $success = $this->generateWithPrince( $this->pdfProfile, $this->pdfOutputIntent, $this->generateHtml(), $output_path ); if ( true !== $success ) { throw new \Exception( 'Failed to create PDF file' ); } delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ return $output_path; }
php
public function generate() { $output_path = $this->timestampedFileName( 'pdf' ); $success = $this->generateWithPrince( $this->pdfProfile, $this->pdfOutputIntent, $this->generateHtml(), $output_path ); if ( true !== $success ) { throw new \Exception( 'Failed to create PDF file' ); } delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */ return $output_path; }
[ "public", "function", "generate", "(", ")", "{", "$", "output_path", "=", "$", "this", "->", "timestampedFileName", "(", "'pdf'", ")", ";", "$", "success", "=", "$", "this", "->", "generateWithPrince", "(", "$", "this", "->", "pdfProfile", ",", "$", "thi...
Generate PDF print cover @throws \Exception @return string Output path
[ "Generate", "PDF", "print", "cover" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/covergenerator/class-princepdf.php#L91-L99
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.column_file
public function column_file( $item ) { $html = '<div class="export-file">'; $html .= $this->getIcon( $item['file'] ); $html .= '<div class="export-file-name">' . esc_html( $item['file'] ) . '</div>'; $html .= '</div>'; $delete_url = sprintf( '/admin.php?page=%s&action=%s&ID=%s', $_REQUEST['page'], 'delete', $item['ID'] ); $delete_url = get_admin_url( get_current_blog_id(), $delete_url ); $delete_url = esc_url( add_query_arg( '_wpnonce', wp_create_nonce( 'bulk-files' ), $delete_url ) ); $onclick = 'onclick="if ( !confirm(\'' . esc_attr( __( 'Are you sure you want to delete this export file?', 'pressbooks' ) ) . '\') ) { return false }"'; $actions['delete'] = sprintf( '<a href="%s" aria-label="%s" ' . $onclick . '>%s</a>', $delete_url, /* translators: %s: file */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221;' ), $item['file'] ) ), _x( 'Delete', 'verb' ) ); $download_url = get_admin_url( get_current_blog_id(), "/admin.php?page=pb_export&download_export_file={$item['file']}" ); $actions['download'] = sprintf( '<a href="%s" aria-label="%s" >%s</a>', $download_url, /* translators: %s: file */ esc_attr( sprintf( __( 'Download &#8220;%s&#8221;' ), $item['file'] ) ), _x( 'Download', 'verb' ) ); $html .= $this->row_actions( $actions ); return $html; }
php
public function column_file( $item ) { $html = '<div class="export-file">'; $html .= $this->getIcon( $item['file'] ); $html .= '<div class="export-file-name">' . esc_html( $item['file'] ) . '</div>'; $html .= '</div>'; $delete_url = sprintf( '/admin.php?page=%s&action=%s&ID=%s', $_REQUEST['page'], 'delete', $item['ID'] ); $delete_url = get_admin_url( get_current_blog_id(), $delete_url ); $delete_url = esc_url( add_query_arg( '_wpnonce', wp_create_nonce( 'bulk-files' ), $delete_url ) ); $onclick = 'onclick="if ( !confirm(\'' . esc_attr( __( 'Are you sure you want to delete this export file?', 'pressbooks' ) ) . '\') ) { return false }"'; $actions['delete'] = sprintf( '<a href="%s" aria-label="%s" ' . $onclick . '>%s</a>', $delete_url, /* translators: %s: file */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221;' ), $item['file'] ) ), _x( 'Delete', 'verb' ) ); $download_url = get_admin_url( get_current_blog_id(), "/admin.php?page=pb_export&download_export_file={$item['file']}" ); $actions['download'] = sprintf( '<a href="%s" aria-label="%s" >%s</a>', $download_url, /* translators: %s: file */ esc_attr( sprintf( __( 'Download &#8220;%s&#8221;' ), $item['file'] ) ), _x( 'Download', 'verb' ) ); $html .= $this->row_actions( $actions ); return $html; }
[ "public", "function", "column_file", "(", "$", "item", ")", "{", "$", "html", "=", "'<div class=\"export-file\">'", ";", "$", "html", ".=", "$", "this", "->", "getIcon", "(", "$", "item", "[", "'file'", "]", ")", ";", "$", "html", ".=", "'<div class=\"ex...
@param array $item A singular item (one full row's worth of data) @return string Text to be placed inside the column <td>
[ "@param", "array", "$item", "A", "singular", "item", "(", "one", "full", "row", "s", "worth", "of", "data", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L66-L96
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.column_pin
public function column_pin( $item ) { $format = $this->getTinyHash( $item['format'] ); $html = "<input type='checkbox' id='pin[{$item['ID']}]' name='pin[{$item['ID']}]' value='{$format}' " . checked( $item['pin'], true, false ) . '/>'; $html .= "<label for='pin[{$item['ID']}]'>Pin this file</label>"; return $html; }
php
public function column_pin( $item ) { $format = $this->getTinyHash( $item['format'] ); $html = "<input type='checkbox' id='pin[{$item['ID']}]' name='pin[{$item['ID']}]' value='{$format}' " . checked( $item['pin'], true, false ) . '/>'; $html .= "<label for='pin[{$item['ID']}]'>Pin this file</label>"; return $html; }
[ "public", "function", "column_pin", "(", "$", "item", ")", "{", "$", "format", "=", "$", "this", "->", "getTinyHash", "(", "$", "item", "[", "'format'", "]", ")", ";", "$", "html", "=", "\"<input type='checkbox' id='pin[{$item['ID']}]' name='pin[{$item['ID']}]' va...
@param array $item A singular item (one full row's worth of data) @return string Text to be placed inside the column <td>
[ "@param", "array", "$item", "A", "singular", "item", "(", "one", "full", "row", "s", "worth", "of", "data", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L112-L117
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.prepare_items
public function prepare_items() { // Define Columns $columns = $this->get_columns(); $hidden = []; $sortable = $this->get_sortable_columns(); $this->_column_headers = [ $columns, $hidden, $sortable ]; // Data $data = $this->getLatestExports(); // Pagination $per_page = $this->get_items_per_page( 'pb_export_per_page', 50 ); $current_page = $this->get_pagenum(); $total_items = count( $data ); $orderby = ( ! empty( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : 'exported'; $order = ( ! empty( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : 'desc'; // Data slice $sort = ( $orderby === 'exported' ) ? [ $orderby => $order ] : [ $orderby => $order, 'exported' => 'desc', ]; $data = wp_list_sort( $data, $sort ); $data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page ); $this->items = $data; $this->set_pagination_args( [ 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ] ); }
php
public function prepare_items() { // Define Columns $columns = $this->get_columns(); $hidden = []; $sortable = $this->get_sortable_columns(); $this->_column_headers = [ $columns, $hidden, $sortable ]; // Data $data = $this->getLatestExports(); // Pagination $per_page = $this->get_items_per_page( 'pb_export_per_page', 50 ); $current_page = $this->get_pagenum(); $total_items = count( $data ); $orderby = ( ! empty( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : 'exported'; $order = ( ! empty( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : 'desc'; // Data slice $sort = ( $orderby === 'exported' ) ? [ $orderby => $order ] : [ $orderby => $order, 'exported' => 'desc', ]; $data = wp_list_sort( $data, $sort ); $data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page ); $this->items = $data; $this->set_pagination_args( [ 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ] ); }
[ "public", "function", "prepare_items", "(", ")", "{", "// Define Columns", "$", "columns", "=", "$", "this", "->", "get_columns", "(", ")", ";", "$", "hidden", "=", "[", "]", ";", "$", "sortable", "=", "$", "this", "->", "get_sortable_columns", "(", ")",...
Prepares the list of items for displaying.
[ "Prepares", "the", "list", "of", "items", "for", "displaying", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L159-L193
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.inlineJs
public function inlineJs() { // Process any actions first $this->processBulkActions(); $this->truncateExports(); $js = ''; // Map the export form to equivalents in latest exports table $filetypes = \Pressbooks\Modules\Export\filetypes(); $map = []; foreach ( $filetypes as $k => $v ) { $map[ "export_formats[{$k}]" ] = $this->getTinyHash( $this->getFormat( $v ) ); } $map = wp_json_encode( $map, JSON_FORCE_OBJECT ); $js .= "var _pb_export_formats_map = {$map}; "; // Pins $all_possible_pins = []; foreach ( $this->getFiles() as $filepath ) { $file = basename( $filepath ); $key = 'pin[' . $this->getTinyHash( $file ) . ']'; $all_possible_pins[ $key ] = $this->getTinyHash( $this->getFormat( $file ) ); } $pins = get_transient( self::PIN ); if ( ! is_array( $pins ) ) { $pins = []; } foreach ( $pins as $k => $v ) { if ( ! isset( $all_possible_pins[ $k ] ) ) { unset( $pins[ $k ] ); } } $pins = wp_json_encode( $pins, JSON_FORCE_OBJECT ); $js .= "var _pb_export_pins_inventory = {$pins}; "; return $js; }
php
public function inlineJs() { // Process any actions first $this->processBulkActions(); $this->truncateExports(); $js = ''; // Map the export form to equivalents in latest exports table $filetypes = \Pressbooks\Modules\Export\filetypes(); $map = []; foreach ( $filetypes as $k => $v ) { $map[ "export_formats[{$k}]" ] = $this->getTinyHash( $this->getFormat( $v ) ); } $map = wp_json_encode( $map, JSON_FORCE_OBJECT ); $js .= "var _pb_export_formats_map = {$map}; "; // Pins $all_possible_pins = []; foreach ( $this->getFiles() as $filepath ) { $file = basename( $filepath ); $key = 'pin[' . $this->getTinyHash( $file ) . ']'; $all_possible_pins[ $key ] = $this->getTinyHash( $this->getFormat( $file ) ); } $pins = get_transient( self::PIN ); if ( ! is_array( $pins ) ) { $pins = []; } foreach ( $pins as $k => $v ) { if ( ! isset( $all_possible_pins[ $k ] ) ) { unset( $pins[ $k ] ); } } $pins = wp_json_encode( $pins, JSON_FORCE_OBJECT ); $js .= "var _pb_export_pins_inventory = {$pins}; "; return $js; }
[ "public", "function", "inlineJs", "(", ")", "{", "// Process any actions first", "$", "this", "->", "processBulkActions", "(", ")", ";", "$", "this", "->", "truncateExports", "(", ")", ";", "$", "js", "=", "''", ";", "// Map the export form to equivalents in lates...
Inline JavaScript to be echoed in template before <table> Process any actions the table needs to do in here @return string
[ "Inline", "JavaScript", "to", "be", "echoed", "in", "template", "before", "<table", ">", "Process", "any", "actions", "the", "table", "needs", "to", "do", "in", "here" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L201-L236
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.getPins
protected function getPins( $reset = false ) { if ( $reset ) { $this->_pins = []; } if ( empty( $this->_pins ) ) { $pins = get_transient( self::PIN ); if ( ! is_array( $pins ) ) { $pins = []; } $this->_pins = $pins; } return $this->_pins; }
php
protected function getPins( $reset = false ) { if ( $reset ) { $this->_pins = []; } if ( empty( $this->_pins ) ) { $pins = get_transient( self::PIN ); if ( ! is_array( $pins ) ) { $pins = []; } $this->_pins = $pins; } return $this->_pins; }
[ "protected", "function", "getPins", "(", "$", "reset", "=", "false", ")", "{", "if", "(", "$", "reset", ")", "{", "$", "this", "->", "_pins", "=", "[", "]", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "_pins", ")", ")", "{", "$", "p...
@param bool $reset @return array
[ "@param", "bool", "$reset" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L259-L271
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.truncateExports
protected function truncateExports( $keep_the_last = 3 ) { // Sort files by modification time $files = []; foreach ( $this->getFiles() as $filepath ) { $files[ $filepath ] = filemtime( $filepath ); } arsort( $files ); // Group sorted files by format // Start with/prioritize pins, to to reduce likelihood of deletion $groups = []; foreach ( $files as $filepath => $timestamp ) { $id = $this->getTinyHash( basename( $filepath ) ); if ( $this->hasPin( $id ) ) { $format = $this->getFormat( $filepath ); $groups[ $format ][] = $filepath; unset( $files[ $filepath ] ); } } foreach ( $files as $filepath => $timestamp ) { $format = $this->getFormat( $filepath ); $groups[ $format ][] = $filepath; } // Delete files in group bigger than $keep_the_last foreach ( $groups as $group ) { $i = 1; foreach ( $group as $filepath ) { if ( $i > $keep_the_last ) { unlink( $filepath ); } ++$i; } } }
php
protected function truncateExports( $keep_the_last = 3 ) { // Sort files by modification time $files = []; foreach ( $this->getFiles() as $filepath ) { $files[ $filepath ] = filemtime( $filepath ); } arsort( $files ); // Group sorted files by format // Start with/prioritize pins, to to reduce likelihood of deletion $groups = []; foreach ( $files as $filepath => $timestamp ) { $id = $this->getTinyHash( basename( $filepath ) ); if ( $this->hasPin( $id ) ) { $format = $this->getFormat( $filepath ); $groups[ $format ][] = $filepath; unset( $files[ $filepath ] ); } } foreach ( $files as $filepath => $timestamp ) { $format = $this->getFormat( $filepath ); $groups[ $format ][] = $filepath; } // Delete files in group bigger than $keep_the_last foreach ( $groups as $group ) { $i = 1; foreach ( $group as $filepath ) { if ( $i > $keep_the_last ) { unlink( $filepath ); } ++$i; } } }
[ "protected", "function", "truncateExports", "(", "$", "keep_the_last", "=", "3", ")", "{", "// Sort files by modification time", "$", "files", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getFiles", "(", ")", "as", "$", "filepath", ")", "{", "$"...
Keep the last three of each specific export format @param int $keep_the_last (optional)
[ "Keep", "the", "last", "three", "of", "each", "specific", "export", "format" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L289-L323
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.getCssClass
protected function getCssClass( $file ) { $file_extension = substr( strrchr( $file, '.' ), 1 ); switch ( $file_extension ) { case 'epub': $pre_suffix = strstr( $file, '._3.epub' ); break; case 'pdf': $pre_suffix = strstr( $file, '._print.pdf' ); break; case 'html': $pre_suffix = strstr( $file, '.-htmlbook.html' ); break; case 'xml': $pre_suffix = strstr( $file, '._vanilla.xml' ); break; default: $pre_suffix = false; } if ( 'html' === $file_extension && '.-htmlbook.html' === $pre_suffix ) { $file_class = 'htmlbook'; } elseif ( 'html' === $file_extension && false === $pre_suffix ) { $file_class = 'xhtml'; } elseif ( 'xml' === $file_extension && '._vanilla.xml' === $pre_suffix ) { $file_class = 'vanillawxr'; } elseif ( 'xml' === $file_extension && false === $pre_suffix ) { $file_class = 'wxr'; } elseif ( 'epub' === $file_extension && '._3.epub' === $pre_suffix ) { $file_class = 'epub3'; } elseif ( 'pdf' === $file_extension && '._print.pdf' === $pre_suffix ) { $file_class = 'print-pdf'; } else { /** * Map custom export format file extensions to their CSS class. * * For example, here's how one might set the CSS class for a .docx file: * * add_filter( 'pb_get_export_file_class', function ( $file_extension ) { * if ( 'docx' == $file_extension ) { * return 'word'; * } * return $file_extension; * } ); * * @since 3.9.8 * * @param string $file_extension */ $file_class = apply_filters( 'pb_get_export_file_class', $file_extension ); } return $file_class; }
php
protected function getCssClass( $file ) { $file_extension = substr( strrchr( $file, '.' ), 1 ); switch ( $file_extension ) { case 'epub': $pre_suffix = strstr( $file, '._3.epub' ); break; case 'pdf': $pre_suffix = strstr( $file, '._print.pdf' ); break; case 'html': $pre_suffix = strstr( $file, '.-htmlbook.html' ); break; case 'xml': $pre_suffix = strstr( $file, '._vanilla.xml' ); break; default: $pre_suffix = false; } if ( 'html' === $file_extension && '.-htmlbook.html' === $pre_suffix ) { $file_class = 'htmlbook'; } elseif ( 'html' === $file_extension && false === $pre_suffix ) { $file_class = 'xhtml'; } elseif ( 'xml' === $file_extension && '._vanilla.xml' === $pre_suffix ) { $file_class = 'vanillawxr'; } elseif ( 'xml' === $file_extension && false === $pre_suffix ) { $file_class = 'wxr'; } elseif ( 'epub' === $file_extension && '._3.epub' === $pre_suffix ) { $file_class = 'epub3'; } elseif ( 'pdf' === $file_extension && '._print.pdf' === $pre_suffix ) { $file_class = 'print-pdf'; } else { /** * Map custom export format file extensions to their CSS class. * * For example, here's how one might set the CSS class for a .docx file: * * add_filter( 'pb_get_export_file_class', function ( $file_extension ) { * if ( 'docx' == $file_extension ) { * return 'word'; * } * return $file_extension; * } ); * * @since 3.9.8 * * @param string $file_extension */ $file_class = apply_filters( 'pb_get_export_file_class', $file_extension ); } return $file_class; }
[ "protected", "function", "getCssClass", "(", "$", "file", ")", "{", "$", "file_extension", "=", "substr", "(", "strrchr", "(", "$", "file", ",", "'.'", ")", ",", "1", ")", ";", "switch", "(", "$", "file_extension", ")", "{", "case", "'epub'", ":", "$...
@param string $file @return string
[ "@param", "string", "$file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L351-L401
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.getIcon
protected function getIcon( $file, $size = 'large' ) { $file_class = $this->getCssClass( $file ); $html = "<div class='export-file-icon {$size} {$file_class}' title='" . esc_attr( $file ) . "'></div>"; return $html; }
php
protected function getIcon( $file, $size = 'large' ) { $file_class = $this->getCssClass( $file ); $html = "<div class='export-file-icon {$size} {$file_class}' title='" . esc_attr( $file ) . "'></div>"; return $html; }
[ "protected", "function", "getIcon", "(", "$", "file", ",", "$", "size", "=", "'large'", ")", "{", "$", "file_class", "=", "$", "this", "->", "getCssClass", "(", "$", "file", ")", ";", "$", "html", "=", "\"<div class='export-file-icon {$size} {$file_class}' tit...
@param string $file @param string $size @return string
[ "@param", "string", "$file", "@param", "string", "$size" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L409-L413
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.getFormat
protected function getFormat( $file ) { $file_class = $this->getCssClass( $file ); return \Pressbooks\Modules\Export\get_name_from_filetype_slug( $file_class ); }
php
protected function getFormat( $file ) { $file_class = $this->getCssClass( $file ); return \Pressbooks\Modules\Export\get_name_from_filetype_slug( $file_class ); }
[ "protected", "function", "getFormat", "(", "$", "file", ")", "{", "$", "file_class", "=", "$", "this", "->", "getCssClass", "(", "$", "file", ")", ";", "return", "\\", "Pressbooks", "\\", "Modules", "\\", "Export", "\\", "get_name_from_filetype_slug", "(", ...
@param string $file @return string
[ "@param", "string", "$file" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L420-L423
pressbooks/pressbooks
inc/modules/export/class-table.php
Table.processBulkActions
protected function processBulkActions() { if ( 'delete' === $this->current_action() ) { check_admin_referer( 'bulk-files' ); $ids = isset( $_REQUEST['ID'] ) ? $_REQUEST['ID'] : []; if ( ! is_array( $ids ) ) { $ids = [ $ids ]; } if ( ! empty( $ids ) ) { $latest_exports = $this->getLatestExports(); foreach ( $ids as $id ) { $this->deleteFileById( $id, $latest_exports ); } } } }
php
protected function processBulkActions() { if ( 'delete' === $this->current_action() ) { check_admin_referer( 'bulk-files' ); $ids = isset( $_REQUEST['ID'] ) ? $_REQUEST['ID'] : []; if ( ! is_array( $ids ) ) { $ids = [ $ids ]; } if ( ! empty( $ids ) ) { $latest_exports = $this->getLatestExports(); foreach ( $ids as $id ) { $this->deleteFileById( $id, $latest_exports ); } } } }
[ "protected", "function", "processBulkActions", "(", ")", "{", "if", "(", "'delete'", "===", "$", "this", "->", "current_action", "(", ")", ")", "{", "check_admin_referer", "(", "'bulk-files'", ")", ";", "$", "ids", "=", "isset", "(", "$", "_REQUEST", "[", ...
Delete
[ "Delete" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/class-table.php#L428-L442
pressbooks/pressbooks
inc/interactive/class-phet.php
Phet.registerEmbedHandlerForWeb
public function registerEmbedHandlerForWeb() { wp_embed_register_handler( self::EMBED_ID, self::EMBED_URL_REGEX, function ( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '<iframe src="https://phet.colorado.edu/sims/html/%1$s" width="800" height="600" scrolling="no" allowfullscreen></iframe>', esc_attr( $matches[1] ) ); return apply_filters( 'embed_' . self::EMBED_ID, $embed, $matches, $attr, $url, $rawattr ); } ); }
php
public function registerEmbedHandlerForWeb() { wp_embed_register_handler( self::EMBED_ID, self::EMBED_URL_REGEX, function ( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '<iframe src="https://phet.colorado.edu/sims/html/%1$s" width="800" height="600" scrolling="no" allowfullscreen></iframe>', esc_attr( $matches[1] ) ); return apply_filters( 'embed_' . self::EMBED_ID, $embed, $matches, $attr, $url, $rawattr ); } ); }
[ "public", "function", "registerEmbedHandlerForWeb", "(", ")", "{", "wp_embed_register_handler", "(", "self", "::", "EMBED_ID", ",", "self", "::", "EMBED_URL_REGEX", ",", "function", "(", "$", "matches", ",", "$", "attr", ",", "$", "url", ",", "$", "rawattr", ...
Register embed handler for web
[ "Register", "embed", "handler", "for", "web" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-phet.php#L29-L41
pressbooks/pressbooks
inc/interactive/class-phet.php
Phet.registerEmbedHandlerForExport
public function registerEmbedHandlerForExport() { wp_embed_register_handler( self::EMBED_ID, self::EMBED_URL_REGEX, function ( $matches, $attr, $url, $rawattr ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $embed = $this->blade->render( 'interactive.shared', [ 'title' => get_the_title( $id ), 'url' => wp_get_shortlink( $id ), ] ); return apply_filters( 'embed_' . self::EMBED_ID, $embed, $matches, $attr, $url, $rawattr ); } ); }
php
public function registerEmbedHandlerForExport() { wp_embed_register_handler( self::EMBED_ID, self::EMBED_URL_REGEX, function ( $matches, $attr, $url, $rawattr ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] $embed = $this->blade->render( 'interactive.shared', [ 'title' => get_the_title( $id ), 'url' => wp_get_shortlink( $id ), ] ); return apply_filters( 'embed_' . self::EMBED_ID, $embed, $matches, $attr, $url, $rawattr ); } ); }
[ "public", "function", "registerEmbedHandlerForExport", "(", ")", "{", "wp_embed_register_handler", "(", "self", "::", "EMBED_ID", ",", "self", "::", "EMBED_URL_REGEX", ",", "function", "(", "$", "matches", ",", "$", "attr", ",", "$", "url", ",", "$", "rawattr"...
Register embed handler for exports
[ "Register", "embed", "handler", "for", "exports" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-phet.php#L46-L61
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.import
function import( array $current_import ) { try { $this->isValidZip( $current_import['file'] ); } catch ( \Exception $e ) { return false; } $xml = $this->getZipContent( 'content.xml' ); $meta = $this->getZipContent( 'meta.xml' ); // introduce a stylesheet $proc = new \XSLTProcessor(); $xsl = new \DOMDocument(); $xsl->load( __DIR__ . '/xsl/odt2html.xsl' ); $proc->importStylesheet( $xsl ); // throw it back into the DOM $dom_doc = $proc->transformToDoc( $xml ); if ( $meta ) { $this->parseMetaData( $meta ); } $chapter_parent = $this->getChapterParent(); foreach ( $current_import['chapters'] as $id => $chapter_title ) { // do nothing it has been omitted if ( ! $this->flaggedForImport( $id ) ) { continue; } $html = $this->parseContent( $dom_doc, $chapter_title ); $this->kneadAndInsert( $html, $chapter_title, $this->determinePostType( $id ), $chapter_parent, $current_import['default_post_status'] ); } // Done return $this->revokeCurrentImport(); }
php
function import( array $current_import ) { try { $this->isValidZip( $current_import['file'] ); } catch ( \Exception $e ) { return false; } $xml = $this->getZipContent( 'content.xml' ); $meta = $this->getZipContent( 'meta.xml' ); // introduce a stylesheet $proc = new \XSLTProcessor(); $xsl = new \DOMDocument(); $xsl->load( __DIR__ . '/xsl/odt2html.xsl' ); $proc->importStylesheet( $xsl ); // throw it back into the DOM $dom_doc = $proc->transformToDoc( $xml ); if ( $meta ) { $this->parseMetaData( $meta ); } $chapter_parent = $this->getChapterParent(); foreach ( $current_import['chapters'] as $id => $chapter_title ) { // do nothing it has been omitted if ( ! $this->flaggedForImport( $id ) ) { continue; } $html = $this->parseContent( $dom_doc, $chapter_title ); $this->kneadAndInsert( $html, $chapter_title, $this->determinePostType( $id ), $chapter_parent, $current_import['default_post_status'] ); } // Done return $this->revokeCurrentImport(); }
[ "function", "import", "(", "array", "$", "current_import", ")", "{", "try", "{", "$", "this", "->", "isValidZip", "(", "$", "current_import", "[", "'file'", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", "...
Imports content, only after options (chapters, parts) have been selected @param array $current_import @return boolean - returns false if import fails
[ "Imports", "content", "only", "after", "options", "(", "chapters", "parts", ")", "have", "been", "selected" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L54-L92
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.kneadAndInsert
protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $post_status ) { $body = $this->tidy( $html ); $body = $this->kneadHTML( $body ); $title = wp_strip_all_tags( $title ); $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 ) ); update_post_meta( $pid, 'pb_show_title', 'on' ); Book::consolidatePost( $pid, get_post( $pid ) ); // Reorder }
php
protected function kneadAndInsert( $html, $title, $post_type, $chapter_parent, $post_status ) { $body = $this->tidy( $html ); $body = $this->kneadHTML( $body ); $title = wp_strip_all_tags( $title ); $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 ) ); update_post_meta( $pid, 'pb_show_title', 'on' ); Book::consolidatePost( $pid, get_post( $pid ) ); // Reorder }
[ "protected", "function", "kneadAndInsert", "(", "$", "html", ",", "$", "title", ",", "$", "post_type", ",", "$", "chapter_parent", ",", "$", "post_status", ")", "{", "$", "body", "=", "$", "this", "->", "tidy", "(", "$", "html", ")", ";", "$", "body"...
Pummel then insert HTML into our database @param string $html @param string $title @param string $post_type (front-matter', 'chapter', 'back-matter') @param int $chapter_parent @param string $post_status
[ "Pummel", "then", "insert", "HTML", "into", "our", "database" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L118-L141
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.kneadHTML
protected function kneadHTML( $body ) { libxml_use_internal_errors( true ); $old_value = libxml_disable_entity_loader( true ); $doc = new \DOMDocument( '1.0', 'UTF-8' ); $doc->loadXML( $body ); libxml_disable_entity_loader( $old_value ); // Download images, change to relative paths $doc = $this->scrapeAndKneadImages( $doc ); $html = $doc->saveXML( $doc->documentElement ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); return $html; }
php
protected function kneadHTML( $body ) { libxml_use_internal_errors( true ); $old_value = libxml_disable_entity_loader( true ); $doc = new \DOMDocument( '1.0', 'UTF-8' ); $doc->loadXML( $body ); libxml_disable_entity_loader( $old_value ); // Download images, change to relative paths $doc = $this->scrapeAndKneadImages( $doc ); $html = $doc->saveXML( $doc->documentElement ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); return $html; }
[ "protected", "function", "kneadHTML", "(", "$", "body", ")", "{", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "old_value", "=", "libxml_disable_entity_loader", "(", "true", ")", ";", "$", "doc", "=", "new", "\\", "DOMDocument", "(", "'1.0'", ",...
Pummel the HTML into WordPress compatible dough. @param string $body @return string - modified with correct image paths
[ "Pummel", "the", "HTML", "into", "WordPress", "compatible", "dough", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L151-L169
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.scrapeAndKneadImages
protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); $new_src = $this->fetchAndSaveUniqueImage( $old_src ); if ( $new_src ) { // Replace with new image $image->setAttribute( 'src', $new_src ); } else { // Tag broken image $image->setAttribute( 'src', "{$old_src}#fixme" ); } } return $doc; }
php
protected function scrapeAndKneadImages( \DOMDocument $doc ) { $images = $doc->getElementsByTagName( 'img' ); foreach ( $images as $image ) { /** @var \DOMElement $image */ // Fetch image, change src $old_src = $image->getAttribute( 'src' ); $new_src = $this->fetchAndSaveUniqueImage( $old_src ); if ( $new_src ) { // Replace with new image $image->setAttribute( 'src', $new_src ); } else { // Tag broken image $image->setAttribute( 'src', "{$old_src}#fixme" ); } } return $doc; }
[ "protected", "function", "scrapeAndKneadImages", "(", "\\", "DOMDocument", "$", "doc", ")", "{", "$", "images", "=", "$", "doc", "->", "getElementsByTagName", "(", "'img'", ")", ";", "foreach", "(", "$", "images", "as", "$", "image", ")", "{", "/** @var \\...
Parse HTML snippet, save all found <img> tags using media_handle_sideload(), return the HTML with changed <img> paths. @param \DOMDocument $doc @return \DOMDocument
[ "Parse", "HTML", "snippet", "save", "all", "found", "<img", ">", "tags", "using", "media_handle_sideload", "()", "return", "the", "HTML", "with", "changed", "<img", ">", "paths", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L179-L197
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.fetchAndSaveUniqueImage
protected function fetchAndSaveUniqueImage( $href ) { $img_location = $href; // Cheap cache static $already_done = []; if ( isset( $already_done[ $img_location ] ) ) { return $already_done[ $img_location ]; } /* Process */ // Basename without query string $filename = explode( '?', basename( $href ) ); $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_location ] = ''; return ''; } $image_content = $this->getZipContent( $img_location, false ); if ( ! $image_content ) { $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( $href ) { $img_location = $href; // Cheap cache static $already_done = []; if ( isset( $already_done[ $img_location ] ) ) { return $already_done[ $img_location ]; } /* Process */ // Basename without query string $filename = explode( '?', basename( $href ) ); $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_location ] = ''; return ''; } $image_content = $this->getZipContent( $img_location, false ); if ( ! $image_content ) { $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", "(", "$", "href", ")", "{", "$", "img_location", "=", "$", "href", ";", "// Cheap cache", "static", "$", "already_done", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "already_done", "[", "$", "img_lo...
Extract url from zip and load into WP using media_handle_sideload() Will return an empty string if something went wrong. @param string $href original filename, with (relative) path @see media_handle_sideload @return string filename
[ "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/odf/class-odt.php#L210-L274
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.setCurrentImportOption
function setCurrentImportOption( array $upload ) { try { $this->isValidZip( $upload['file'] ); } catch ( \Exception $e ) { return false; } $option = [ 'file' => $upload['file'], 'url' => $upload['url'] ?? null, 'file_type' => $upload['type'], 'type_of' => self::TYPE_OF, 'chapters' => [], ]; $option['chapters'] = $this->getFuzzyChapterTitles(); return update_option( 'pressbooks_current_import', $option ); }
php
function setCurrentImportOption( array $upload ) { try { $this->isValidZip( $upload['file'] ); } catch ( \Exception $e ) { return false; } $option = [ 'file' => $upload['file'], 'url' => $upload['url'] ?? null, 'file_type' => $upload['type'], 'type_of' => self::TYPE_OF, 'chapters' => [], ]; $option['chapters'] = $this->getFuzzyChapterTitles(); return update_option( 'pressbooks_current_import', $option ); }
[ "function", "setCurrentImportOption", "(", "array", "$", "upload", ")", "{", "try", "{", "$", "this", "->", "isValidZip", "(", "$", "upload", "[", "'file'", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", "...
Chapter detection @param array $upload @return boolean
[ "Chapter", "detection" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L309-L328
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.getChapter
protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) { if ( empty( $chapter_title ) ) { $chapter_title = 'unknown'; } $chapter = new \DOMDocument( '1.0', 'UTF-8' ); // create a new node element $root = $chapter->createElement( 'div' ); $root->setAttribute( 'class', $chapter_title ); $chapter->appendChild( $root ); // Start at the beginning if no h1 tags are found. // In other words...bring in the whole document. ( '__UNKNOWN__' === $chapter_title ) ? $i = 0 : $i = $index; do { $node = $chapter->importNode( $dom_list->item( $i ), true ); $chapter->documentElement->appendChild( $node ); $i++; // TODO // This is problematic // DOMNodeList can be made up of DOMElement(s) // *and* DOMText(s) which do not have the property ->tagName } while ( @$dom_list->item( $i )->tagName != $this->tag && $i < $dom_list->length ); // @codingStandardsIgnoreLine // h1 tag will not be needed in the body of the html $h1 = $chapter->getElementsByTagName( $this->tag )->item( 0 ); // removeChild is quick to throw a fatal error if ( $h1 && $this->tag === $h1->nodeName && 'div' === $h1->parentNode->nodeName ) { $chapter->documentElement->removeChild( $h1 ); } $result = $chapter->saveHTML( $chapter->documentElement ); // appendChild brings over the namespace which is superfluous on every html element // the string below is from the xslt file // @see includes/modules/import/odf/xsl/odt2html.xsl $result = preg_replace( '/xmlns="http:\/\/www.w3.org\/1999\/xhtml"/', '', $result ); return $result; }
php
protected function getChapter( \DOMNodeList $dom_list, $index, $chapter_title ) { if ( empty( $chapter_title ) ) { $chapter_title = 'unknown'; } $chapter = new \DOMDocument( '1.0', 'UTF-8' ); // create a new node element $root = $chapter->createElement( 'div' ); $root->setAttribute( 'class', $chapter_title ); $chapter->appendChild( $root ); // Start at the beginning if no h1 tags are found. // In other words...bring in the whole document. ( '__UNKNOWN__' === $chapter_title ) ? $i = 0 : $i = $index; do { $node = $chapter->importNode( $dom_list->item( $i ), true ); $chapter->documentElement->appendChild( $node ); $i++; // TODO // This is problematic // DOMNodeList can be made up of DOMElement(s) // *and* DOMText(s) which do not have the property ->tagName } while ( @$dom_list->item( $i )->tagName != $this->tag && $i < $dom_list->length ); // @codingStandardsIgnoreLine // h1 tag will not be needed in the body of the html $h1 = $chapter->getElementsByTagName( $this->tag )->item( 0 ); // removeChild is quick to throw a fatal error if ( $h1 && $this->tag === $h1->nodeName && 'div' === $h1->parentNode->nodeName ) { $chapter->documentElement->removeChild( $h1 ); } $result = $chapter->saveHTML( $chapter->documentElement ); // appendChild brings over the namespace which is superfluous on every html element // the string below is from the xslt file // @see includes/modules/import/odf/xsl/odt2html.xsl $result = preg_replace( '/xmlns="http:\/\/www.w3.org\/1999\/xhtml"/', '', $result ); return $result; }
[ "protected", "function", "getChapter", "(", "\\", "DOMNodeList", "$", "dom_list", ",", "$", "index", ",", "$", "chapter_title", ")", "{", "if", "(", "empty", "(", "$", "chapter_title", ")", ")", "{", "$", "chapter_title", "=", "'unknown'", ";", "}", "$",...
Find where to start, iterate through a list, add elements to a new DomDocument, return resulting xhtml @param \DOMNodeList $dom_list @param int $index @param string $chapter_title @return string XHTML
[ "Find", "where", "to", "start", "iterate", "through", "a", "list", "add", "elements", "to", "a", "new", "DomDocument", "return", "resulting", "xhtml" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L405-L450
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.parseContent
protected function parseContent( \DomDocument $xml, $chapter_title ) { $element = $xml->documentElement; $node_list = $element->childNodes; $chapter_node = ''; $index = 0; // loop through child siblings for ( $i = 0; $i < $node_list->length; $i++ ) { $chapter_node = $this->findTheNode( $node_list->item( $i ), $chapter_title ); if ( ! empty( $chapter_node ) ) { // assumes h1 is going to be first child of parent 'html' $index = $i; break; } } if ( $chapter_node ) { $chapter_title = strtolower( preg_replace( '/\s+/', '-', $chapter_node->nodeValue ) ); } // iterate through return $this->getChapter( $node_list, $index, $chapter_title ); }
php
protected function parseContent( \DomDocument $xml, $chapter_title ) { $element = $xml->documentElement; $node_list = $element->childNodes; $chapter_node = ''; $index = 0; // loop through child siblings for ( $i = 0; $i < $node_list->length; $i++ ) { $chapter_node = $this->findTheNode( $node_list->item( $i ), $chapter_title ); if ( ! empty( $chapter_node ) ) { // assumes h1 is going to be first child of parent 'html' $index = $i; break; } } if ( $chapter_node ) { $chapter_title = strtolower( preg_replace( '/\s+/', '-', $chapter_node->nodeValue ) ); } // iterate through return $this->getChapter( $node_list, $index, $chapter_title ); }
[ "protected", "function", "parseContent", "(", "\\", "DomDocument", "$", "xml", ",", "$", "chapter_title", ")", "{", "$", "element", "=", "$", "xml", "->", "documentElement", ";", "$", "node_list", "=", "$", "element", "->", "childNodes", ";", "$", "chapter...
Find and return the identified chapter @param \DomDocument $xml @param string $chapter_title @return string XML
[ "Find", "and", "return", "the", "identified", "chapter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L461-L485
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.getFuzzyChapterTitles
protected function getFuzzyChapterTitles() { $chapters = []; $xml = $this->getZipContent( 'content.xml' ); // introduce a stylesheet $proc = new \XSLTProcessor(); $xsl = new \DOMDocument(); $xsl->load( __DIR__ . '/xsl/odt2html.xsl' ); $proc->importStylesheet( $xsl ); // throw it back into the DOM $dom_doc = $proc->transformToDoc( $xml ); // get all headings $headings = $dom_doc->getElementsByTagName( $this->tag ); // populate chapters with title names for ( $i = 0; $i < $headings->length; $i++ ) { $chapters[] = trim( $headings->item( $i )->nodeValue ); } // get rid of h1 tags with empty values $chapters = array_values( array_filter( $chapters ) ); // default chapter title if there are no h1 headings in the document if ( 0 === count( $chapters ) ) { $chapters[] = '__UNKNOWN__'; } return $chapters; }
php
protected function getFuzzyChapterTitles() { $chapters = []; $xml = $this->getZipContent( 'content.xml' ); // introduce a stylesheet $proc = new \XSLTProcessor(); $xsl = new \DOMDocument(); $xsl->load( __DIR__ . '/xsl/odt2html.xsl' ); $proc->importStylesheet( $xsl ); // throw it back into the DOM $dom_doc = $proc->transformToDoc( $xml ); // get all headings $headings = $dom_doc->getElementsByTagName( $this->tag ); // populate chapters with title names for ( $i = 0; $i < $headings->length; $i++ ) { $chapters[] = trim( $headings->item( $i )->nodeValue ); } // get rid of h1 tags with empty values $chapters = array_values( array_filter( $chapters ) ); // default chapter title if there are no h1 headings in the document if ( 0 === count( $chapters ) ) { $chapters[] = '__UNKNOWN__'; } return $chapters; }
[ "protected", "function", "getFuzzyChapterTitles", "(", ")", "{", "$", "chapters", "=", "[", "]", ";", "$", "xml", "=", "$", "this", "->", "getZipContent", "(", "'content.xml'", ")", ";", "// introduce a stylesheet", "$", "proc", "=", "new", "\\", "XSLTProces...
Returns an array of available chapters, or 'unknown' if none @return array Chapter titles
[ "Returns", "an", "array", "of", "available", "chapters", "or", "unknown", "if", "none" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L493-L525
pressbooks/pressbooks
inc/modules/import/odf/class-odt.php
Odt.getZipContent
protected function getZipContent( $file, $as_xml = true ) { // Locates an entry using its name $index = $this->zip->locateName( $file ); if ( false === $index ) { return false; } // returns the contents using its index $content = $this->zip->getFromIndex( $index ); // if it's not xml, return if ( ! $as_xml ) { return $content; } $collapsed = preg_replace( '/\s+/', '', $content ); if ( preg_match( '/<!DOCTYPE/i', $collapsed ) ) { // Invalid XML: Detected use of illegal DOCTYPE return false; } // trouble with simplexmlelement and elements with dashes // (ODT's are ripe with dashes), so giving it to the DOM $old_value = libxml_disable_entity_loader( true ); $xml = new \DOMDocument(); $xml->loadXML( $content, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING ); libxml_disable_entity_loader( $old_value ); return $xml; }
php
protected function getZipContent( $file, $as_xml = true ) { // Locates an entry using its name $index = $this->zip->locateName( $file ); if ( false === $index ) { return false; } // returns the contents using its index $content = $this->zip->getFromIndex( $index ); // if it's not xml, return if ( ! $as_xml ) { return $content; } $collapsed = preg_replace( '/\s+/', '', $content ); if ( preg_match( '/<!DOCTYPE/i', $collapsed ) ) { // Invalid XML: Detected use of illegal DOCTYPE return false; } // trouble with simplexmlelement and elements with dashes // (ODT's are ripe with dashes), so giving it to the DOM $old_value = libxml_disable_entity_loader( true ); $xml = new \DOMDocument(); $xml->loadXML( $content, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING ); libxml_disable_entity_loader( $old_value ); return $xml; }
[ "protected", "function", "getZipContent", "(", "$", "file", ",", "$", "as_xml", "=", "true", ")", "{", "// Locates an entry using its name", "$", "index", "=", "$", "this", "->", "zip", "->", "locateName", "(", "$", "file", ")", ";", "if", "(", "false", ...
Locates an entry using its name, returns the entry contents @param string $file - path to a file @param boolean $as_xml @return boolean|\DOMDocument
[ "Locates", "an", "entry", "using", "its", "name", "returns", "the", "entry", "contents" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/odf/class-odt.php#L536-L567
pressbooks/pressbooks
inc/admin/network/class-sharingandprivacyoptions.php
SharingAndPrivacyOptions.renderAllowRedistributionField
function renderAllowRedistributionField( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'allow_redistribution', 'name' => $this->getSlug(), 'option' => 'allow_redistribution', 'value' => ( isset( $options['allow_redistribution'] ) ) ? $options['allow_redistribution'] : '', 'label' => $args[0], ] ); }
php
function renderAllowRedistributionField( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'allow_redistribution', 'name' => $this->getSlug(), 'option' => 'allow_redistribution', 'value' => ( isset( $options['allow_redistribution'] ) ) ? $options['allow_redistribution'] : '', 'label' => $args[0], ] ); }
[ "function", "renderAllowRedistributionField", "(", "$", "args", ")", "{", "$", "options", "=", "get_site_option", "(", "$", "this", "->", "getSlug", "(", ")", ")", ";", "$", "this", "->", "renderCheckbox", "(", "[", "'id'", "=>", "'allow_redistribution'", ",...
Render the allow_redistribution checkbox. @param array $args
[ "Render", "the", "allow_redistribution", "checkbox", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/network/class-sharingandprivacyoptions.php#L169-L180
pressbooks/pressbooks
inc/admin/network/class-sharingandprivacyoptions.php
SharingAndPrivacyOptions.renderAllowRootApi
function renderAllowRootApi( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'enable_network_api', 'name' => $this->getSlug(), 'option' => 'enable_network_api', 'value' => ( isset( $options['enable_network_api'] ) ) ? $options['enable_network_api'] : '', 'label' => $args[0], ] ); }
php
function renderAllowRootApi( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'enable_network_api', 'name' => $this->getSlug(), 'option' => 'enable_network_api', 'value' => ( isset( $options['enable_network_api'] ) ) ? $options['enable_network_api'] : '', 'label' => $args[0], ] ); }
[ "function", "renderAllowRootApi", "(", "$", "args", ")", "{", "$", "options", "=", "get_site_option", "(", "$", "this", "->", "getSlug", "(", ")", ")", ";", "$", "this", "->", "renderCheckbox", "(", "[", "'id'", "=>", "'enable_network_api'", ",", "'name'",...
Render the enable_network_api checkbox. @param array $args
[ "Render", "the", "enable_network_api", "checkbox", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/network/class-sharingandprivacyoptions.php#L187-L198
pressbooks/pressbooks
inc/admin/network/class-sharingandprivacyoptions.php
SharingAndPrivacyOptions.renderAllowCloning
function renderAllowCloning( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'enable_cloning', 'name' => $this->getSlug(), 'option' => 'enable_cloning', 'value' => ( isset( $options['enable_cloning'] ) ) ? $options['enable_cloning'] : '', 'label' => $args[0], ] ); }
php
function renderAllowCloning( $args ) { $options = get_site_option( $this->getSlug() ); $this->renderCheckbox( [ 'id' => 'enable_cloning', 'name' => $this->getSlug(), 'option' => 'enable_cloning', 'value' => ( isset( $options['enable_cloning'] ) ) ? $options['enable_cloning'] : '', 'label' => $args[0], ] ); }
[ "function", "renderAllowCloning", "(", "$", "args", ")", "{", "$", "options", "=", "get_site_option", "(", "$", "this", "->", "getSlug", "(", ")", ")", ";", "$", "this", "->", "renderCheckbox", "(", "[", "'id'", "=>", "'enable_cloning'", ",", "'name'", "...
Render the enable_cloning checkbox. @param array $args
[ "Render", "the", "enable_cloning", "checkbox", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/network/class-sharingandprivacyoptions.php#L205-L216
pressbooks/pressbooks
inc/modules/export/prince/class-filters.php
Filters.overridePrince
public function overridePrince() { $use_hooks = true; if ( ! defined( 'DOCRAPTOR_API_KEY' ) ) { // No API key $use_hooks = false; } $plugin = 'pressbooks-docraptor/pressbooks-docraptor.php'; if ( file_exists( WP_PLUGIN_DIR . "/{$plugin}" ) && is_plugin_active( $plugin ) ) { // The old, deprecated plugin is active $use_hooks = false; } return $use_hooks; }
php
public function overridePrince() { $use_hooks = true; if ( ! defined( 'DOCRAPTOR_API_KEY' ) ) { // No API key $use_hooks = false; } $plugin = 'pressbooks-docraptor/pressbooks-docraptor.php'; if ( file_exists( WP_PLUGIN_DIR . "/{$plugin}" ) && is_plugin_active( $plugin ) ) { // The old, deprecated plugin is active $use_hooks = false; } return $use_hooks; }
[ "public", "function", "overridePrince", "(", ")", "{", "$", "use_hooks", "=", "true", ";", "if", "(", "!", "defined", "(", "'DOCRAPTOR_API_KEY'", ")", ")", "{", "// No API key", "$", "use_hooks", "=", "false", ";", "}", "$", "plugin", "=", "'pressbooks-doc...
@since 5.4.0 @return bool
[ "@since", "5", ".", "4", ".", "0" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/prince/class-filters.php#L48-L60
pressbooks/pressbooks
inc/modules/export/prince/class-filters.php
Filters.addToModules
public function addToModules( $modules ) { if ( isset( $_POST['export_formats']['docraptor'] ) && check_admin_referer( 'pb-export' ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\Docraptor'; } if ( isset( $_POST['export_formats']['docraptor_print'] ) && check_admin_referer( 'pb-export' ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\DocraptorPrint'; } return $modules; }
php
public function addToModules( $modules ) { if ( isset( $_POST['export_formats']['docraptor'] ) && check_admin_referer( 'pb-export' ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\Docraptor'; } if ( isset( $_POST['export_formats']['docraptor_print'] ) && check_admin_referer( 'pb-export' ) ) { $modules[] = '\Pressbooks\Modules\Export\Prince\DocraptorPrint'; } return $modules; }
[ "public", "function", "addToModules", "(", "$", "modules", ")", "{", "if", "(", "isset", "(", "$", "_POST", "[", "'export_formats'", "]", "[", "'docraptor'", "]", ")", "&&", "check_admin_referer", "(", "'pb-export'", ")", ")", "{", "$", "modules", "[", "...
@since 5.4.0 Add this module to the export batch currently in progress. @param array $modules an array of active export module classnames @return array $modules
[ "@since", "5", ".", "4", ".", "0" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/prince/class-filters.php#L93-L101
pressbooks/pressbooks
inc/cloner/class-downloads.php
Downloads.fetchAndSaveUniqueImage
public function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->cloner->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = image_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_img_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_img_location ); } else { $remote_img_location = $url; } if ( isset( $this->imageWasAlreadyDownloaded[ $remote_img_location ] ) ) { return $this->imageWasAlreadyDownloaded[ $remote_img_location ]; } /* Process */ if ( ! preg_match( $this->pregSupportedImageExtensions, $filename ) ) { // Unsupported image type $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; return 0; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; return 0; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = \Pressbooks\Image\proper_image_extension( $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 $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; @unlink( $tmp_name ); // @codingStandardsIgnoreLine return 0; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { // Patch $m = $known_media[ $attached_file ]; $request = new \WP_REST_Request( 'PATCH', "/wp/v2/media/{$pid}" ); $request->set_body_params( $this->createMediaPatch( $m ) ); $request->set_param( '_fields', 'id' ); rest_do_request( $request ); // Store a transitional state $this->cloner->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->imageWasAlreadyDownloaded[ $remote_img_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
php
public function fetchAndSaveUniqueImage( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->cloner->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = image_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_img_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_img_location ); } else { $remote_img_location = $url; } if ( isset( $this->imageWasAlreadyDownloaded[ $remote_img_location ] ) ) { return $this->imageWasAlreadyDownloaded[ $remote_img_location ]; } /* Process */ if ( ! preg_match( $this->pregSupportedImageExtensions, $filename ) ) { // Unsupported image type $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; return 0; } $tmp_name = download_url( $remote_img_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; return 0; } if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) { try { // changing the file name so that extension matches the mime type $filename = \Pressbooks\Image\proper_image_extension( $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 $this->imageWasAlreadyDownloaded[ $remote_img_location ] = 0; @unlink( $tmp_name ); // @codingStandardsIgnoreLine return 0; } } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { // Patch $m = $known_media[ $attached_file ]; $request = new \WP_REST_Request( 'PATCH', "/wp/v2/media/{$pid}" ); $request->set_body_params( $this->createMediaPatch( $m ) ); $request->set_param( '_fields', 'id' ); rest_do_request( $request ); // Store a transitional state $this->cloner->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->imageWasAlreadyDownloaded[ $remote_img_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
[ "public", "function", "fetchAndSaveUniqueImage", "(", "$", "url", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "$", "this", "->", "sameAsSource", "(", "$", ...
Load remote url of image into WP using media_handle_sideload() Will return -1 if image is not hosted on the source Pb network, or 0 if something went wrong. @param string $url @see \Pressbooks\Cloner\Cloner::$knownMedia @see media_handle_sideload @return int attachment ID, -1 if image is not hosted on the source Pb network, or 0 if import failed
[ "Load", "remote", "url", "of", "image", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "-", "1", "if", "image", "is", "not", "hosted", "on", "the", "source", "Pb", "network", "or", "0", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/cloner/class-downloads.php#L113-L192
pressbooks/pressbooks
inc/cloner/class-downloads.php
Downloads.createMediaPatch
public function createMediaPatch( $media ) { return [ 'title' => $media->title, 'meta' => $media->meta, 'description' => $media->description, 'caption' => $media->caption, 'alt_text' => $media->altText, ]; }
php
public function createMediaPatch( $media ) { return [ 'title' => $media->title, 'meta' => $media->meta, 'description' => $media->description, 'caption' => $media->caption, 'alt_text' => $media->altText, ]; }
[ "public", "function", "createMediaPatch", "(", "$", "media", ")", "{", "return", "[", "'title'", "=>", "$", "media", "->", "title", ",", "'meta'", "=>", "$", "media", "->", "meta", ",", "'description'", "=>", "$", "media", "->", "description", ",", "'cap...
@param \Pressbooks\Entities\Cloner\Media $media @return array
[ "@param", "\\", "Pressbooks", "\\", "Entities", "\\", "Cloner", "\\", "Media", "$media" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/cloner/class-downloads.php#L224-L232
pressbooks/pressbooks
inc/cloner/class-downloads.php
Downloads.scrapeAndKneadMedia
public function scrapeAndKneadMedia( \DOMDocument $dom, $html5 ) { $known_media = $this->cloner->getKnownMedia(); $dom_as_string = $html5->saveHTML( $dom ); $dom_as_string = \Pressbooks\Sanitize\strip_container_tags( $dom_as_string ); $attachments = []; $changed = false; foreach ( $known_media as $alt => $media ) { if ( preg_match( $this->pregSupportedImageExtensions, $this->basename( $media->sourceUrl ) ) ) { // Skip images, these are handled elsewhere continue; } if ( strpos( $dom_as_string, $media->sourceUrl ) !== false ) { $src_old = $media->sourceUrl; $attachment_id = $this->fetchAndSaveUniqueMedia( $src_old ); if ( $attachment_id === -1 ) { // Do nothing because media is not hosted on the source Pb network } elseif ( $attachment_id ) { $dom_as_string = str_replace( $src_old, wp_get_attachment_url( $attachment_id ), $dom_as_string ); $attachments[] = $attachment_id; $changed = true; } else { // Tag broken media $dom_as_string = str_replace( $src_old, "{$src_old}#fixme", $dom_as_string ); $changed = true; } } } return [ 'dom' => $changed ? $html5->loadHTML( $dom_as_string ) : $dom, 'attachments' => $attachments, ]; }
php
public function scrapeAndKneadMedia( \DOMDocument $dom, $html5 ) { $known_media = $this->cloner->getKnownMedia(); $dom_as_string = $html5->saveHTML( $dom ); $dom_as_string = \Pressbooks\Sanitize\strip_container_tags( $dom_as_string ); $attachments = []; $changed = false; foreach ( $known_media as $alt => $media ) { if ( preg_match( $this->pregSupportedImageExtensions, $this->basename( $media->sourceUrl ) ) ) { // Skip images, these are handled elsewhere continue; } if ( strpos( $dom_as_string, $media->sourceUrl ) !== false ) { $src_old = $media->sourceUrl; $attachment_id = $this->fetchAndSaveUniqueMedia( $src_old ); if ( $attachment_id === -1 ) { // Do nothing because media is not hosted on the source Pb network } elseif ( $attachment_id ) { $dom_as_string = str_replace( $src_old, wp_get_attachment_url( $attachment_id ), $dom_as_string ); $attachments[] = $attachment_id; $changed = true; } else { // Tag broken media $dom_as_string = str_replace( $src_old, "{$src_old}#fixme", $dom_as_string ); $changed = true; } } } return [ 'dom' => $changed ? $html5->loadHTML( $dom_as_string ) : $dom, 'attachments' => $attachments, ]; }
[ "public", "function", "scrapeAndKneadMedia", "(", "\\", "DOMDocument", "$", "dom", ",", "$", "html5", ")", "{", "$", "known_media", "=", "$", "this", "->", "cloner", "->", "getKnownMedia", "(", ")", ";", "$", "dom_as_string", "=", "$", "html5", "->", "sa...
Parse HTML snippet, save all found media using media_handle_sideload(), return the HTML with changed URLs. Because we clone using WordPress raw format, we have to brute force against the text because the DOM can't see shortcodes, text urls, hrefs with no identifying info, etc. @param \DOMDocument $dom @param \Masterminds\HTML5 $html5 @see \Pressbooks\Cloner\Cloner::$knownMedia @return array{dom: \DOMDocument, attachments: int[]}
[ "Parse", "HTML", "snippet", "save", "all", "found", "media", "using", "media_handle_sideload", "()", "return", "the", "HTML", "with", "changed", "URLs", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/cloner/class-downloads.php#L297-L331
pressbooks/pressbooks
inc/cloner/class-downloads.php
Downloads.fetchAndSaveUniqueMedia
public function fetchAndSaveUniqueMedia( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->cloner->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = media_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_media_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_media_location ); } else { $remote_media_location = $url; } if ( isset( $this->mediaWasAlreadyDownloaded[ $remote_media_location ] ) ) { return $this->mediaWasAlreadyDownloaded[ $remote_media_location ]; } /* Process */ $tmp_name = download_url( $remote_media_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = 0; return 0; } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { // Patch $m = $known_media[ $attached_file ]; $request = new \WP_REST_Request( 'PATCH', "/wp/v2/media/{$pid}" ); $request->set_body_params( $this->createMediaPatch( $m ) ); $request->set_param( '_fields', 'id' ); rest_do_request( $request ); // Store a transitional state $this->cloner->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
php
public function fetchAndSaveUniqueMedia( $url ) { if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return 0; } if ( ! $this->sameAsSource( $url ) ) { return -1; } $known_media = $this->cloner->getKnownMedia(); $filename = $this->basename( $url ); $attached_file = media_strip_baseurl( $url ); if ( isset( $known_media[ $attached_file ] ) ) { $remote_media_location = $known_media[ $attached_file ]->sourceUrl; $filename = basename( $remote_media_location ); } else { $remote_media_location = $url; } if ( isset( $this->mediaWasAlreadyDownloaded[ $remote_media_location ] ) ) { return $this->mediaWasAlreadyDownloaded[ $remote_media_location ]; } /* Process */ $tmp_name = download_url( $remote_media_location ); if ( is_wp_error( $tmp_name ) ) { // Download failed $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = 0; return 0; } $pid = media_handle_sideload( [ 'name' => $filename, 'tmp_name' => $tmp_name, ], 0 ); $src = wp_get_attachment_url( $pid ); if ( ! $src ) { $pid = 0; } else { if ( isset( $known_media[ $attached_file ] ) ) { // Patch $m = $known_media[ $attached_file ]; $request = new \WP_REST_Request( 'PATCH', "/wp/v2/media/{$pid}" ); $request->set_body_params( $this->createMediaPatch( $m ) ); $request->set_param( '_fields', 'id' ); rest_do_request( $request ); // Store a transitional state $this->cloner->createTransition( 'attachment', $m->id, $pid ); } // Don't download the same file again $this->mediaWasAlreadyDownloaded[ $remote_media_location ] = $pid; } @unlink( $tmp_name ); // @codingStandardsIgnoreLine return $pid; }
[ "public", "function", "fetchAndSaveUniqueMedia", "(", "$", "url", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "$", "this", "->", "sameAsSource", "(", "$", ...
Load remote media into WP using media_handle_sideload() Will return -1 if media is not hosted on the source Pb network, or 0 if something went wrong. @param string $url @see \Pressbooks\Cloner\Cloner::$knownMedia @see media_handle_sideload @return int attachment ID, -1 if media is not hosted on the source Pb network, or 0 if import failed
[ "Load", "remote", "media", "into", "WP", "using", "media_handle_sideload", "()", "Will", "return", "-", "1", "if", "media", "is", "not", "hosted", "on", "the", "source", "Pb", "network", "or", "0", "if", "something", "went", "wrong", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/cloner/class-downloads.php#L344-L402
pressbooks/pressbooks
inc/cloner/class-downloads.php
Downloads.h5p
public function h5p( $content ) { $known_h5p = $this->cloner->getKnownH5P(); $new_h5p_ids = []; $h5p_ids = $this->h5p->findAllShortcodeIds( $content ); foreach ( $h5p_ids as $h5p_id ) { if ( ! isset( $this->H5PWasAlreadyDownloaded[ $h5p_id ] ) ) { foreach ( $known_h5p as $h5p ) { if ( absint( $h5p->id ) === absint( $h5p_id ) ) { $new_h5p_id = $this->h5p->fetch( $h5p->url ); if ( $new_h5p_id ) { $new_h5p_ids[] = $new_h5p_id; $this->cloner->createTransition( 'h5p', $h5p_id, $new_h5p_id ); $this->H5PWasAlreadyDownloaded[ $h5p_id ] = $new_h5p_id; } else { // An id of 0 means there was a problem. We have to replace the broken H5P shortcode with a warning $new_h5p_ids[] = "#fixme{$h5p->id}"; } continue 2; } } } } return $new_h5p_ids; }
php
public function h5p( $content ) { $known_h5p = $this->cloner->getKnownH5P(); $new_h5p_ids = []; $h5p_ids = $this->h5p->findAllShortcodeIds( $content ); foreach ( $h5p_ids as $h5p_id ) { if ( ! isset( $this->H5PWasAlreadyDownloaded[ $h5p_id ] ) ) { foreach ( $known_h5p as $h5p ) { if ( absint( $h5p->id ) === absint( $h5p_id ) ) { $new_h5p_id = $this->h5p->fetch( $h5p->url ); if ( $new_h5p_id ) { $new_h5p_ids[] = $new_h5p_id; $this->cloner->createTransition( 'h5p', $h5p_id, $new_h5p_id ); $this->H5PWasAlreadyDownloaded[ $h5p_id ] = $new_h5p_id; } else { // An id of 0 means there was a problem. We have to replace the broken H5P shortcode with a warning $new_h5p_ids[] = "#fixme{$h5p->id}"; } continue 2; } } } } return $new_h5p_ids; }
[ "public", "function", "h5p", "(", "$", "content", ")", "{", "$", "known_h5p", "=", "$", "this", "->", "cloner", "->", "getKnownH5P", "(", ")", ";", "$", "new_h5p_ids", "=", "[", "]", ";", "$", "h5p_ids", "=", "$", "this", "->", "h5p", "->", "findAl...
Parse HTML snippet, download all found H5P, save transition states to change shortcodes in post processing step @param string $content @see \Pressbooks\Cloner\Cloner::$knownH5P @return array
[ "Parse", "HTML", "snippet", "download", "all", "found", "H5P", "save", "transition", "states", "to", "change", "shortcodes", "in", "post", "processing", "step" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/cloner/class-downloads.php#L413-L436
pressbooks/pressbooks
inc/htmlbook/class-element.php
Element.setDataType
public function setDataType( string $data_type ) { if ( ! in_array( $data_type, $this->dataTypes, true ) ) { throw new \LogicException( "Unsupported DataType: {$data_type}, valid values are: " . rtrim( implode( ',', $this->dataTypes ), ',' ) ); } $this->dataType = $data_type; }
php
public function setDataType( string $data_type ) { if ( ! in_array( $data_type, $this->dataTypes, true ) ) { throw new \LogicException( "Unsupported DataType: {$data_type}, valid values are: " . rtrim( implode( ',', $this->dataTypes ), ',' ) ); } $this->dataType = $data_type; }
[ "public", "function", "setDataType", "(", "string", "$", "data_type", ")", "{", "if", "(", "!", "in_array", "(", "$", "data_type", ",", "$", "this", "->", "dataTypes", ",", "true", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"Unsupporte...
@param string $data_type @throws \LogicException
[ "@param", "string", "$data_type" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/htmlbook/class-element.php#L196-L201
pressbooks/pressbooks
inc/htmlbook/class-element.php
Element.setContent
public function setContent( $content ) { if ( ! is_array( $content ) ) { $content = [ $content ]; } foreach ( $content as $v ) { if ( $this === $v ) { throw new \LogicException( 'Recursion problem: cannot set self as content to self' ); } } $this->content = $content; }
php
public function setContent( $content ) { if ( ! is_array( $content ) ) { $content = [ $content ]; } foreach ( $content as $v ) { if ( $this === $v ) { throw new \LogicException( 'Recursion problem: cannot set self as content to self' ); } } $this->content = $content; }
[ "public", "function", "setContent", "(", "$", "content", ")", "{", "if", "(", "!", "is_array", "(", "$", "content", ")", ")", "{", "$", "content", "=", "[", "$", "content", "]", ";", "}", "foreach", "(", "$", "content", "as", "$", "v", ")", "{", ...
@param mixed $content @throws \LogicException
[ "@param", "mixed", "$content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/htmlbook/class-element.php#L246-L256
pressbooks/pressbooks
inc/htmlbook/class-element.php
Element.isInline
public function isInline( $var ) { if ( is_object( $var ) ) { if ( $var instanceof Element ) { return ( in_array( $var->getTag(), $this->inline, true ) ); } return ( strpos( get_class( $var ), 'Pressbooks\HTMLBook\Inline\\' ) !== false ); } if ( is_string( $var ) ) { $html5 = new HTML5(); $dom = $html5->loadHTMLFragment( $var ); if ( $dom->childNodes->length !== 1 ) { return false; } return ( in_array( $dom->childNodes->item( 0 )->tagName, $this->inline, true ) ); } return false; }
php
public function isInline( $var ) { if ( is_object( $var ) ) { if ( $var instanceof Element ) { return ( in_array( $var->getTag(), $this->inline, true ) ); } return ( strpos( get_class( $var ), 'Pressbooks\HTMLBook\Inline\\' ) !== false ); } if ( is_string( $var ) ) { $html5 = new HTML5(); $dom = $html5->loadHTMLFragment( $var ); if ( $dom->childNodes->length !== 1 ) { return false; } return ( in_array( $dom->childNodes->item( 0 )->tagName, $this->inline, true ) ); } return false; }
[ "public", "function", "isInline", "(", "$", "var", ")", "{", "if", "(", "is_object", "(", "$", "var", ")", ")", "{", "if", "(", "$", "var", "instanceof", "Element", ")", "{", "return", "(", "in_array", "(", "$", "var", "->", "getTag", "(", ")", "...
@param mixed $var @return bool
[ "@param", "mixed", "$var" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/htmlbook/class-element.php#L275-L294
pressbooks/pressbooks
inc/htmlbook/class-element.php
Element.isHeading
public function isHeading( $var ) { $headings = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ]; if ( is_object( $var ) ) { if ( $var instanceof Element ) { return ( in_array( $var->getTag(), $headings, true ) ); } return is_subclass_of( $var, '\Pressbooks\HTMLBook\Heading\Headings' ); } if ( is_string( $var ) ) { $html5 = new HTML5(); $dom = $html5->loadHTMLFragment( $var ); if ( $dom->childNodes->length !== 1 ) { return false; } return ( in_array( $dom->childNodes->item( 0 )->tagName, $headings, true ) ); } return false; }
php
public function isHeading( $var ) { $headings = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ]; if ( is_object( $var ) ) { if ( $var instanceof Element ) { return ( in_array( $var->getTag(), $headings, true ) ); } return is_subclass_of( $var, '\Pressbooks\HTMLBook\Heading\Headings' ); } if ( is_string( $var ) ) { $html5 = new HTML5(); $dom = $html5->loadHTMLFragment( $var ); if ( $dom->childNodes->length !== 1 ) { return false; } return ( in_array( $dom->childNodes->item( 0 )->tagName, $headings, true ) ); } return false; }
[ "public", "function", "isHeading", "(", "$", "var", ")", "{", "$", "headings", "=", "[", "'h1'", ",", "'h2'", ",", "'h3'", ",", "'h4'", ",", "'h5'", ",", "'h6'", "]", ";", "if", "(", "is_object", "(", "$", "var", ")", ")", "{", "if", "(", "$", ...
@param mixed $var @return bool
[ "@param", "mixed", "$var" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/htmlbook/class-element.php#L328-L349
pressbooks/pressbooks
inc/class-activation.php
Activation.init
static public function init() { if ( is_null( self::$instance ) ) { $taxonomy = Taxonomy::init(); self::$instance = new self( $taxonomy ); self::hooks( self::$instance ); } return self::$instance; }
php
static public function init() { if ( is_null( self::$instance ) ) { $taxonomy = Taxonomy::init(); self::$instance = new self( $taxonomy ); self::hooks( self::$instance ); } return self::$instance; }
[ "static", "public", "function", "init", "(", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "instance", ")", ")", "{", "$", "taxonomy", "=", "Taxonomy", "::", "init", "(", ")", ";", "self", "::", "$", "instance", "=", "new", "self", "(", ...
@since 5.0.0 @return Activation
[ "@since", "5", ".", "0", ".", "0" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-activation.php#L48-L55
pressbooks/pressbooks
inc/class-activation.php
Activation.wpmuNewBlog
public function wpmuNewBlog( $new_site, $args ) { $this->blog_id = (int) $new_site->id; $this->user_id = (int) ( ! empty( $args['user_id'] ) ? $args['user_id'] : 0 ); switch_to_blog( $this->blog_id ); if ( ! $this->isBookSetup() ) { $this->wpmuActivate(); array_walk( $this->opts, function ( $v, $k ) { if ( empty( $v ) ) { delete_option( $k ); } else { update_option( $k, $v ); } } ); wp_cache_flush(); } // Set current versions to skip redundant upgrade routines update_option( 'pressbooks_metadata_version', Metadata::VERSION ); update_option( 'pressbooks_taxonomy_version', Taxonomy::VERSION ); foreach ( ( new Modules\ThemeOptions\Admin() )->getTabs() as $slug => $theme_options_class ) { update_option( "pressbooks_theme_options_{$slug}_version", $theme_options_class::VERSION, false ); } flush_rewrite_rules( false ); /** * @since 4.3.0 */ do_action( 'pb_new_blog' ); /** * @deprecated 4.3.0 Use pb_new_blog instead. */ do_action( 'pressbooks_new_blog' ); restore_current_blog(); if ( is_user_logged_in() ) { ( new \Pressbooks\Catalog() )->deleteCache(); /** * Determine whether or not to redirect the user to the new book's dashboard. * * @since 4.1.0 * * @param bool $value Whether or not to redirect the user */ if ( apply_filters( 'pb_redirect_to_new_book', true ) ) { \Pressbooks\Redirect\location( get_admin_url( $this->blog_id ) ); } } }
php
public function wpmuNewBlog( $new_site, $args ) { $this->blog_id = (int) $new_site->id; $this->user_id = (int) ( ! empty( $args['user_id'] ) ? $args['user_id'] : 0 ); switch_to_blog( $this->blog_id ); if ( ! $this->isBookSetup() ) { $this->wpmuActivate(); array_walk( $this->opts, function ( $v, $k ) { if ( empty( $v ) ) { delete_option( $k ); } else { update_option( $k, $v ); } } ); wp_cache_flush(); } // Set current versions to skip redundant upgrade routines update_option( 'pressbooks_metadata_version', Metadata::VERSION ); update_option( 'pressbooks_taxonomy_version', Taxonomy::VERSION ); foreach ( ( new Modules\ThemeOptions\Admin() )->getTabs() as $slug => $theme_options_class ) { update_option( "pressbooks_theme_options_{$slug}_version", $theme_options_class::VERSION, false ); } flush_rewrite_rules( false ); /** * @since 4.3.0 */ do_action( 'pb_new_blog' ); /** * @deprecated 4.3.0 Use pb_new_blog instead. */ do_action( 'pressbooks_new_blog' ); restore_current_blog(); if ( is_user_logged_in() ) { ( new \Pressbooks\Catalog() )->deleteCache(); /** * Determine whether or not to redirect the user to the new book's dashboard. * * @since 4.1.0 * * @param bool $value Whether or not to redirect the user */ if ( apply_filters( 'pb_redirect_to_new_book', true ) ) { \Pressbooks\Redirect\location( get_admin_url( $this->blog_id ) ); } } }
[ "public", "function", "wpmuNewBlog", "(", "$", "new_site", ",", "$", "args", ")", "{", "$", "this", "->", "blog_id", "=", "(", "int", ")", "$", "new_site", "->", "id", ";", "$", "this", "->", "user_id", "=", "(", "int", ")", "(", "!", "empty", "(...
Runs activation function and sets up default WP options for new blog, a.k.a. when a registered user creates a new blog @param \WP_Site $new_site New site object. @param array $args Arguments for the initialization. @see add_action( 'wp_initialize_site', ... )
[ "Runs", "activation", "function", "and", "sets", "up", "default", "WP", "options", "for", "new", "blog", "a", ".", "k", ".", "a", ".", "when", "a", "registered", "user", "creates", "a", "new", "blog" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-activation.php#L85-L142
pressbooks/pressbooks
inc/class-activation.php
Activation.isBookSetup
private function isBookSetup() { $act = get_option( 'pb_activated' ); $pof = get_option( 'page_on_front' ); $pop = get_option( 'page_for_posts' ); if ( empty( $act ) ) { return false; } if ( ( get_option( 'template' ) !== 'pressbooks-book' ) || ( get_option( 'stylesheet' ) !== 'pressbooks-book' ) ) { return false; } if ( ( get_option( 'show_on_front' ) !== 'page' ) || ( ( ! is_int( $pof ) ) || ( ! get_post( $pof ) ) ) || ( ( ! is_int( $pop ) ) || ( ! get_post( $pop ) ) ) ) { return false; } if ( ( wp_count_posts()->publish < 3 ) || ( wp_count_posts( 'page' )->publish < 3 ) || ( count( get_all_category_ids() ) < 3 ) ) { return false; } return true; }
php
private function isBookSetup() { $act = get_option( 'pb_activated' ); $pof = get_option( 'page_on_front' ); $pop = get_option( 'page_for_posts' ); if ( empty( $act ) ) { return false; } if ( ( get_option( 'template' ) !== 'pressbooks-book' ) || ( get_option( 'stylesheet' ) !== 'pressbooks-book' ) ) { return false; } if ( ( get_option( 'show_on_front' ) !== 'page' ) || ( ( ! is_int( $pof ) ) || ( ! get_post( $pof ) ) ) || ( ( ! is_int( $pop ) ) || ( ! get_post( $pop ) ) ) ) { return false; } if ( ( wp_count_posts()->publish < 3 ) || ( wp_count_posts( 'page' )->publish < 3 ) || ( count( get_all_category_ids() ) < 3 ) ) { return false; } return true; }
[ "private", "function", "isBookSetup", "(", ")", "{", "$", "act", "=", "get_option", "(", "'pb_activated'", ")", ";", "$", "pof", "=", "get_option", "(", "'page_on_front'", ")", ";", "$", "pop", "=", "get_option", "(", "'page_for_posts'", ")", ";", "if", ...
Determine if book is set up or not to avoid duplication (i.e. if activation functions have run and default options set) @return bool
[ "Determine", "if", "book", "is", "set", "up", "or", "not", "to", "avoid", "duplication", "(", "i", ".", "e", ".", "if", "activation", "functions", "have", "run", "and", "default", "options", "set", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-activation.php#L151-L170
pressbooks/pressbooks
inc/class-activation.php
Activation.wpmuActivate
private function wpmuActivate() { /** @var $wpdb \wpdb */ global $wpdb; $this->taxonomy->insertTerms(); $posts = [ // Parts, Chapters, Front-Matter, Back-Matter 'main-body' => [ 'post_title' => __( 'Main Body', 'pressbooks' ), 'post_name' => 'main-body', 'post_type' => 'part', 'menu_order' => 1, ], 'introduction' => [ 'post_title' => __( 'Introduction', 'pressbooks' ), 'post_name' => 'introduction', 'post_content' => __( 'This is where you can write your introduction.', 'pressbooks' ), 'post_type' => 'front-matter', 'menu_order' => 1, ], 'chapter-1' => [ 'post_title' => __( 'Chapter 1', 'pressbooks' ), 'post_name' => 'chapter-1', 'post_content' => __( 'This is the first chapter in the main body of the text. You can change the text, rename the chapter, add new chapters, and add new parts.', 'pressbooks' ), 'post_type' => 'chapter', 'menu_order' => 1, ], 'appendix' => [ 'post_title' => __( 'Appendix', 'pressbooks' ), 'post_name' => 'appendix', 'post_content' => __( 'This is where you can add appendices or other back matter.', 'pressbooks' ), 'post_type' => 'back-matter', 'menu_order' => 1, ], // Pages 'authors' => [ 'post_title' => __( 'Authors', 'pressbooks' ), 'post_name' => 'authors', 'post_type' => 'page', ], 'cover' => [ 'post_title' => __( 'Cover', 'pressbooks' ), 'post_name' => 'cover', 'post_type' => 'page', ], 'table-of-contents' => [ 'post_title' => __( 'Table of Contents', 'pressbooks' ), 'post_name' => 'table-of-contents', 'post_type' => 'page', ], 'about' => [ 'post_title' => __( 'About', 'pressbooks' ), 'post_name' => 'about', 'post_type' => 'page', ], 'buy' => [ 'post_title' => __( 'Buy', 'pressbooks' ), 'post_name' => 'buy', 'post_type' => 'page', ], 'access-denied' => [ 'post_title' => __( 'Access Denied', 'pressbooks' ), 'post_name' => 'access-denied', 'post_content' => __( 'This book is private, and accessible only to registered users. If you have an account you can login <a href="/wp-login.php">here</a>. You can also set up your own Pressbooks book at: <a href="http://pressbooks.com">Pressbooks.com</a>.', 'pressbooks' ), 'post_type' => 'page', ], // Custom CSS (deprecated) 'custom-css-epub' => [ 'post_title' => __( 'Custom CSS for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-css', ], 'custom-css-prince' => [ 'post_title' => __( 'Custom CSS for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-css', ], 'custom-css-web' => [ 'post_title' => __( 'Custom CSS for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-css', ], // Book Information [ 'post_title' => __( 'Book Information', 'pressbooks' ), 'post_name' => 'book-information', 'post_type' => 'metadata', ], ]; /** * Filter the default content for new books. * * @since 4.1.0 * * @param array $posts The default book content. */ $posts = apply_filters( 'pb_default_book_content', $posts ); $part = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'post_author' => $this->user_id, ]; $post = [ 'post_status' => 'publish', 'comment_status' => 'open', 'post_author' => $this->user_id, ]; $page = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => '<!-- Here be dragons. -->', 'post_author' => $this->user_id, 'tags_input' => __( 'Default Data', 'pressbooks' ), ]; $meta = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'post_author' => $this->user_id, ]; /** * Allow the default description of a new book to be customized. * * @since 3.9.7 * * @param string $value Default description ('Simple Book Publishing'). */ update_option( 'blogdescription', apply_filters( 'pb_book_description', __( 'Simple Book Publishing', 'pressbooks' ) ) ); $parent_part = 0; $intro = 0; $appendix = 0; $chapter1 = 0; 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 ) ) { if ( 'page' === $item['post_type'] ) { $data = array_merge( $item, $page ); } elseif ( 'part' === $item['post_type'] ) { $data = array_merge( $item, $part ); } elseif ( 'metadata' === $item['post_type'] ) { $data = array_merge( $item, $meta ); } else { $data = array_merge( $item, $post ); } $newpost = wp_insert_post( $data, true ); if ( ! is_wp_error( $newpost ) ) { switch ( $item['post_name'] ) { case 'cover': $this->opts['page_on_front'] = (int) $newpost; break; case 'table-of-contents': $this->opts['page_for_posts'] = (int) $newpost; break; } if ( 'part' === $item['post_type'] ) { $parent_part = $newpost; } elseif ( 'chapter' === $item['post_type'] ) { $my_post = []; $my_post['ID'] = $newpost; $my_post['post_parent'] = $parent_part; wp_update_post( $my_post ); // Apply 'standard' chapter type to 'chapter 1' post wp_set_object_terms( $newpost, 'standard', 'chapter-type' ); } elseif ( 'front-matter' === $item['post_type'] ) { // Apply 'introduction' front matter type to 'introduction' post wp_set_object_terms( $newpost, 'introduction', 'front-matter-type' ); } elseif ( 'back-matter' === $item['post_type'] ) { // Apply 'appendix' front matter type to 'appendix' post wp_set_object_terms( $newpost, 'appendix', 'back-matter-type' ); } elseif ( 'metadata' === $item['post_type'] ) { $metadata_id = $newpost; if ( 0 !== get_current_user_id() ) { // Add initial contributor $user_info = get_userdata( get_current_user_id() ); $contributors = new Contributors(); $term = $contributors->addBlogUser( $user_info->ID ); if ( $term !== false ) { $contributors->link( $term['term_id'], $metadata_id, 'pb_authors' ); } } $locale = get_option( 'WPLANG' ); if ( ! empty( $locale ) ) { $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes(), true ); } elseif ( get_site_option( 'WPLANG' ) ) { $locale = array_search( get_site_option( 'WPLANG' ), \Pressbooks\L10n\wplang_codes(), true ); } else { $locale = 'en'; } update_post_meta( $metadata_id, 'pb_title', get_option( 'blogname' ) ); update_post_meta( $metadata_id, 'pb_language', $locale ); update_post_meta( $metadata_id, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); } } else { trigger_error( $newpost->get_error_message(), E_USER_ERROR ); } } } // Custom Styles Container::get( 'Styles' )->initPosts(); // Remove content generated by wp_install_defaults if ( ! wp_delete_post( 1, true ) ) { return; } if ( ! wp_delete_post( 2, true ) ) { return; } if ( ! wp_delete_comment( 1, true ) ) { return; } $this->opts['pb_activated'] = time(); refresh_blog_details( $this->blog_id ); }
php
private function wpmuActivate() { /** @var $wpdb \wpdb */ global $wpdb; $this->taxonomy->insertTerms(); $posts = [ // Parts, Chapters, Front-Matter, Back-Matter 'main-body' => [ 'post_title' => __( 'Main Body', 'pressbooks' ), 'post_name' => 'main-body', 'post_type' => 'part', 'menu_order' => 1, ], 'introduction' => [ 'post_title' => __( 'Introduction', 'pressbooks' ), 'post_name' => 'introduction', 'post_content' => __( 'This is where you can write your introduction.', 'pressbooks' ), 'post_type' => 'front-matter', 'menu_order' => 1, ], 'chapter-1' => [ 'post_title' => __( 'Chapter 1', 'pressbooks' ), 'post_name' => 'chapter-1', 'post_content' => __( 'This is the first chapter in the main body of the text. You can change the text, rename the chapter, add new chapters, and add new parts.', 'pressbooks' ), 'post_type' => 'chapter', 'menu_order' => 1, ], 'appendix' => [ 'post_title' => __( 'Appendix', 'pressbooks' ), 'post_name' => 'appendix', 'post_content' => __( 'This is where you can add appendices or other back matter.', 'pressbooks' ), 'post_type' => 'back-matter', 'menu_order' => 1, ], // Pages 'authors' => [ 'post_title' => __( 'Authors', 'pressbooks' ), 'post_name' => 'authors', 'post_type' => 'page', ], 'cover' => [ 'post_title' => __( 'Cover', 'pressbooks' ), 'post_name' => 'cover', 'post_type' => 'page', ], 'table-of-contents' => [ 'post_title' => __( 'Table of Contents', 'pressbooks' ), 'post_name' => 'table-of-contents', 'post_type' => 'page', ], 'about' => [ 'post_title' => __( 'About', 'pressbooks' ), 'post_name' => 'about', 'post_type' => 'page', ], 'buy' => [ 'post_title' => __( 'Buy', 'pressbooks' ), 'post_name' => 'buy', 'post_type' => 'page', ], 'access-denied' => [ 'post_title' => __( 'Access Denied', 'pressbooks' ), 'post_name' => 'access-denied', 'post_content' => __( 'This book is private, and accessible only to registered users. If you have an account you can login <a href="/wp-login.php">here</a>. You can also set up your own Pressbooks book at: <a href="http://pressbooks.com">Pressbooks.com</a>.', 'pressbooks' ), 'post_type' => 'page', ], // Custom CSS (deprecated) 'custom-css-epub' => [ 'post_title' => __( 'Custom CSS for Ebook', 'pressbooks' ), 'post_name' => 'epub', 'post_type' => 'custom-css', ], 'custom-css-prince' => [ 'post_title' => __( 'Custom CSS for PDF', 'pressbooks' ), 'post_name' => 'prince', 'post_type' => 'custom-css', ], 'custom-css-web' => [ 'post_title' => __( 'Custom CSS for Web', 'pressbooks' ), 'post_name' => 'web', 'post_type' => 'custom-css', ], // Book Information [ 'post_title' => __( 'Book Information', 'pressbooks' ), 'post_name' => 'book-information', 'post_type' => 'metadata', ], ]; /** * Filter the default content for new books. * * @since 4.1.0 * * @param array $posts The default book content. */ $posts = apply_filters( 'pb_default_book_content', $posts ); $part = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'post_author' => $this->user_id, ]; $post = [ 'post_status' => 'publish', 'comment_status' => 'open', 'post_author' => $this->user_id, ]; $page = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => '<!-- Here be dragons. -->', 'post_author' => $this->user_id, 'tags_input' => __( 'Default Data', 'pressbooks' ), ]; $meta = [ 'post_status' => 'publish', 'comment_status' => 'closed', 'post_author' => $this->user_id, ]; /** * Allow the default description of a new book to be customized. * * @since 3.9.7 * * @param string $value Default description ('Simple Book Publishing'). */ update_option( 'blogdescription', apply_filters( 'pb_book_description', __( 'Simple Book Publishing', 'pressbooks' ) ) ); $parent_part = 0; $intro = 0; $appendix = 0; $chapter1 = 0; 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 ) ) { if ( 'page' === $item['post_type'] ) { $data = array_merge( $item, $page ); } elseif ( 'part' === $item['post_type'] ) { $data = array_merge( $item, $part ); } elseif ( 'metadata' === $item['post_type'] ) { $data = array_merge( $item, $meta ); } else { $data = array_merge( $item, $post ); } $newpost = wp_insert_post( $data, true ); if ( ! is_wp_error( $newpost ) ) { switch ( $item['post_name'] ) { case 'cover': $this->opts['page_on_front'] = (int) $newpost; break; case 'table-of-contents': $this->opts['page_for_posts'] = (int) $newpost; break; } if ( 'part' === $item['post_type'] ) { $parent_part = $newpost; } elseif ( 'chapter' === $item['post_type'] ) { $my_post = []; $my_post['ID'] = $newpost; $my_post['post_parent'] = $parent_part; wp_update_post( $my_post ); // Apply 'standard' chapter type to 'chapter 1' post wp_set_object_terms( $newpost, 'standard', 'chapter-type' ); } elseif ( 'front-matter' === $item['post_type'] ) { // Apply 'introduction' front matter type to 'introduction' post wp_set_object_terms( $newpost, 'introduction', 'front-matter-type' ); } elseif ( 'back-matter' === $item['post_type'] ) { // Apply 'appendix' front matter type to 'appendix' post wp_set_object_terms( $newpost, 'appendix', 'back-matter-type' ); } elseif ( 'metadata' === $item['post_type'] ) { $metadata_id = $newpost; if ( 0 !== get_current_user_id() ) { // Add initial contributor $user_info = get_userdata( get_current_user_id() ); $contributors = new Contributors(); $term = $contributors->addBlogUser( $user_info->ID ); if ( $term !== false ) { $contributors->link( $term['term_id'], $metadata_id, 'pb_authors' ); } } $locale = get_option( 'WPLANG' ); if ( ! empty( $locale ) ) { $locale = array_search( $locale, \Pressbooks\L10n\wplang_codes(), true ); } elseif ( get_site_option( 'WPLANG' ) ) { $locale = array_search( get_site_option( 'WPLANG' ), \Pressbooks\L10n\wplang_codes(), true ); } else { $locale = 'en'; } update_post_meta( $metadata_id, 'pb_title', get_option( 'blogname' ) ); update_post_meta( $metadata_id, 'pb_language', $locale ); update_post_meta( $metadata_id, 'pb_cover_image', \Pressbooks\Image\default_cover_url() ); } } else { trigger_error( $newpost->get_error_message(), E_USER_ERROR ); } } } // Custom Styles Container::get( 'Styles' )->initPosts(); // Remove content generated by wp_install_defaults if ( ! wp_delete_post( 1, true ) ) { return; } if ( ! wp_delete_post( 2, true ) ) { return; } if ( ! wp_delete_comment( 1, true ) ) { return; } $this->opts['pb_activated'] = time(); refresh_blog_details( $this->blog_id ); }
[ "private", "function", "wpmuActivate", "(", ")", "{", "/** @var $wpdb \\wpdb */", "global", "$", "wpdb", ";", "$", "this", "->", "taxonomy", "->", "insertTerms", "(", ")", ";", "$", "posts", "=", "[", "// Parts, Chapters, Front-Matter, Back-Matter", "'main-body'", ...
Set up default terms for Front Matter and Back Matter Insert default part, chapter, front matter, and back matter Insert default pages (Authors, Cover, TOC, About, Buy, and Access Denied) Remove content generated by wp_install_defaults Anything which needs to run on blog activation must go in this function
[ "Set", "up", "default", "terms", "for", "Front", "Matter", "and", "Back", "Matter", "Insert", "default", "part", "chapter", "front", "matter", "and", "back", "matter", "Insert", "default", "pages", "(", "Authors", "Cover", "TOC", "About", "Buy", "and", "Acce...
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-activation.php#L180-L412
pressbooks/pressbooks
inc/class-activation.php
Activation.forcePbColors
public function forcePbColors( $id, $user = null ) { if ( is_numeric( $id ) ) { $user_id = $id; } elseif ( $user instanceof \WP_User ) { $user_id = $user->ID; } else { return; } update_user_option( $user_id, 'admin_color', 'pb_colors', true ); }
php
public function forcePbColors( $id, $user = null ) { if ( is_numeric( $id ) ) { $user_id = $id; } elseif ( $user instanceof \WP_User ) { $user_id = $user->ID; } else { return; } update_user_option( $user_id, 'admin_color', 'pb_colors', true ); }
[ "public", "function", "forcePbColors", "(", "$", "id", ",", "$", "user", "=", "null", ")", "{", "if", "(", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "user_id", "=", "$", "id", ";", "}", "elseif", "(", "$", "user", "instanceof", "\\", "WP_...
Change [ Your Profile > Admin Color Scheme ] to Pressbooks default colors @param int $id @param object $user (optional)
[ "Change", "[", "Your", "Profile", ">", "Admin", "Color", "Scheme", "]", "to", "Pressbooks", "default", "colors" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/class-activation.php#L420-L431
pressbooks/pressbooks
inc/modules/import/api/class-api.php
Api.isSourceCloneable
protected function isSourceCloneable( $section_id, $post_type ) { $metadata = $this->cloner->retrieveSectionMetadata( $section_id, $post_type ); $is_source_clonable = $this->cloner->isSourceCloneable( $metadata['license'] ?? $this->cloner->getSourceBookMetadata()['license'] ); return $is_source_clonable; }
php
protected function isSourceCloneable( $section_id, $post_type ) { $metadata = $this->cloner->retrieveSectionMetadata( $section_id, $post_type ); $is_source_clonable = $this->cloner->isSourceCloneable( $metadata['license'] ?? $this->cloner->getSourceBookMetadata()['license'] ); return $is_source_clonable; }
[ "protected", "function", "isSourceCloneable", "(", "$", "section_id", ",", "$", "post_type", ")", "{", "$", "metadata", "=", "$", "this", "->", "cloner", "->", "retrieveSectionMetadata", "(", "$", "section_id", ",", "$", "post_type", ")", ";", "$", "is_sourc...
Is the section license OK? The global license is for the 'collection' and within that collection you have stuff with licenses that differ from the global one... @param int $section_id The ID of the section within the source book. @param string $post_type The post type of the section. @return bool
[ "Is", "the", "section", "license", "OK?", "The", "global", "license", "is", "for", "the", "collection", "and", "within", "that", "collection", "you", "have", "stuff", "with", "licenses", "that", "differ", "from", "the", "global", "one", "..." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/api/class-api.php#L232-L236
pressbooks/pressbooks
inc/modules/import/api/class-api.php
Api.updatePost
protected function updatePost( $post_id, $status ) { $post = get_post( $post_id, 'ARRAY_A' ); if ( empty( $post ) ) { return; } global $wpdb; $menu_order = $wpdb->get_var( $wpdb->prepare( "SELECT MAX(menu_order) FROM {$wpdb->posts} WHERE post_type = %s AND post_parent = %d AND ID != %d ", $post['post_type'], $post['post_parent'], $post_id ) ); if ( $menu_order !== null ) { $post['menu_order'] = $menu_order + 1; } $post['post_status'] = $status; wp_update_post( $post ); }
php
protected function updatePost( $post_id, $status ) { $post = get_post( $post_id, 'ARRAY_A' ); if ( empty( $post ) ) { return; } global $wpdb; $menu_order = $wpdb->get_var( $wpdb->prepare( "SELECT MAX(menu_order) FROM {$wpdb->posts} WHERE post_type = %s AND post_parent = %d AND ID != %d ", $post['post_type'], $post['post_parent'], $post_id ) ); if ( $menu_order !== null ) { $post['menu_order'] = $menu_order + 1; } $post['post_status'] = $status; wp_update_post( $post ); }
[ "protected", "function", "updatePost", "(", "$", "post_id", ",", "$", "status", ")", "{", "$", "post", "=", "get_post", "(", "$", "post_id", ",", "'ARRAY_A'", ")", ";", "if", "(", "empty", "(", "$", "post", ")", ")", "{", "return", ";", "}", "globa...
Update post status @param int $post_id @param string $status
[ "Update", "post", "status" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/api/class-api.php#L244-L267
pressbooks/pressbooks
inc/modules/export/odt/class-odt.php
Odt.convert
function convert() { // Set logfile $this->logfile = $this->createTmpFile(); // Set filename $this->outputPath = $this->timestampedFileName( '.odt' ); // Set temp folder $this->tmpDir = $this->createTmpDir(); $source = $this->tmpDir . '/source.xhtml'; if ( defined( 'WP_TESTS_MULTISITE' ) ) { \Pressbooks\Utility\put_contents( $source, \Pressbooks\Utility\get_contents( $this->url ) ); } else { \Pressbooks\Utility\put_contents( $source, $this->queryXhtml() ); } $xslt = PB_PLUGIN_DIR . 'inc/modules/export/odt/xhtml2odt.xsl'; $content = $this->tmpDir . '/content.xml'; $mimetype = $this->tmpDir . '/mimetype'; $metafolder = $this->tmpDir . '/META-INF'; $meta = $this->tmpDir . '/meta.xml'; $settings = $this->tmpDir . '/settings.xml'; $styles = $this->tmpDir . '/styles.xml'; $mediafolder = $this->tmpDir . '/media/'; $urlcontent = \Pressbooks\Utility\get_contents( $source ); $urlcontent = preg_replace( '/xmlns\="http\:\/\/www\.w3\.org\/1999\/xhtml"/i', '', $urlcontent ); if ( empty( $urlcontent ) ) { $this->logError( 'source.xhtml is empty' ); return false; } libxml_use_internal_errors( true ); $old_value = libxml_disable_entity_loader( true ); $doc = new \DOMDocument(); $doc->recover = true; // Try to parse non-well formed documents $doc->loadXML( $urlcontent, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING ); libxml_disable_entity_loader( $old_value ); $xpath = new \DOMXPath( $doc ); $tables = $xpath->query( '//table' ); foreach ( $tables as $table ) { /** @var \DOMElement $table */ $columncount = 0; $columns = $xpath->query( '//tr[1]/*', $table ); foreach ( $columns as $column ) { /** @var \DOMElement $column */ if ( $column->hasAttribute( 'colspan' ) ) { $columncount = $columncount + (int) $column->getAttribute( 'colspan' ); } else { $columncount++; } } $table->setAttribute( 'colcount', $columncount ); } if ( ! file_exists( $metafolder ) ) { mkdir( $metafolder ); } $images = $xpath->query( '//img' ); $coverimages = $xpath->query( '//meta[@name="pb-cover-image"]' ); if ( ( $images->length > 0 ) || ( $coverimages->length > 0 ) ) { if ( ! file_exists( $mediafolder ) ) { mkdir( $mediafolder ); } } foreach ( $images as $image ) { /** @var \DOMElement $image */ $src = $image->getAttribute( 'src' ); $image_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $image_filename ) { // Replace with new image $image->setAttribute( 'src', $image_filename ); } } foreach ( $coverimages as $coverimage ) { /** @var \DOMElement $coverimage */ $src = $coverimage->getAttribute( 'content' ); $cover_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $cover_filename ) { // Replace with new image $coverimage->setAttribute( 'src', $cover_filename ); } } \Pressbooks\Utility\put_contents( $source, $doc->saveXML() ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); $output = []; $command = PB_SAXON_COMMAND . ' -xsl:' . escapeshellcmd( $xslt ) . ' -s:' . escapeshellcmd( $source ) . ' -o:' . escapeshellcmd( $content ) . ' 2>&1'; exec( $command, $output ); $files = [ 'content' => $content, 'mimetype' => $mimetype, 'meta' => $meta, 'settings' => $settings, 'styles' => $styles, 'metafolder' => $metafolder, ]; $msg = ''; foreach ( $files as $key => $file ) { if ( ! file_exists( $file ) ) { $msg .= ' [ ' . $key . ' ]'; } } if ( ! empty( $msg ) ) { $this->logError( "Transformation failed, encountered a problem with $msg \n\n" . implode( "\n", $output ) ); return false; } $zip = new \PclZip( $this->outputPath ); if ( $images->length > 0 ) { $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $mediafolder . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $this->tmpDir . '/' ); } else { $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $this->tmpDir . '/' ); } if ( 0 === absint( $list ) ) { $this->logError( $zip->errorInfo( true ) ); return false; } return true; }
php
function convert() { // Set logfile $this->logfile = $this->createTmpFile(); // Set filename $this->outputPath = $this->timestampedFileName( '.odt' ); // Set temp folder $this->tmpDir = $this->createTmpDir(); $source = $this->tmpDir . '/source.xhtml'; if ( defined( 'WP_TESTS_MULTISITE' ) ) { \Pressbooks\Utility\put_contents( $source, \Pressbooks\Utility\get_contents( $this->url ) ); } else { \Pressbooks\Utility\put_contents( $source, $this->queryXhtml() ); } $xslt = PB_PLUGIN_DIR . 'inc/modules/export/odt/xhtml2odt.xsl'; $content = $this->tmpDir . '/content.xml'; $mimetype = $this->tmpDir . '/mimetype'; $metafolder = $this->tmpDir . '/META-INF'; $meta = $this->tmpDir . '/meta.xml'; $settings = $this->tmpDir . '/settings.xml'; $styles = $this->tmpDir . '/styles.xml'; $mediafolder = $this->tmpDir . '/media/'; $urlcontent = \Pressbooks\Utility\get_contents( $source ); $urlcontent = preg_replace( '/xmlns\="http\:\/\/www\.w3\.org\/1999\/xhtml"/i', '', $urlcontent ); if ( empty( $urlcontent ) ) { $this->logError( 'source.xhtml is empty' ); return false; } libxml_use_internal_errors( true ); $old_value = libxml_disable_entity_loader( true ); $doc = new \DOMDocument(); $doc->recover = true; // Try to parse non-well formed documents $doc->loadXML( $urlcontent, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING ); libxml_disable_entity_loader( $old_value ); $xpath = new \DOMXPath( $doc ); $tables = $xpath->query( '//table' ); foreach ( $tables as $table ) { /** @var \DOMElement $table */ $columncount = 0; $columns = $xpath->query( '//tr[1]/*', $table ); foreach ( $columns as $column ) { /** @var \DOMElement $column */ if ( $column->hasAttribute( 'colspan' ) ) { $columncount = $columncount + (int) $column->getAttribute( 'colspan' ); } else { $columncount++; } } $table->setAttribute( 'colcount', $columncount ); } if ( ! file_exists( $metafolder ) ) { mkdir( $metafolder ); } $images = $xpath->query( '//img' ); $coverimages = $xpath->query( '//meta[@name="pb-cover-image"]' ); if ( ( $images->length > 0 ) || ( $coverimages->length > 0 ) ) { if ( ! file_exists( $mediafolder ) ) { mkdir( $mediafolder ); } } foreach ( $images as $image ) { /** @var \DOMElement $image */ $src = $image->getAttribute( 'src' ); $image_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $image_filename ) { // Replace with new image $image->setAttribute( 'src', $image_filename ); } } foreach ( $coverimages as $coverimage ) { /** @var \DOMElement $coverimage */ $src = $coverimage->getAttribute( 'content' ); $cover_filename = $this->fetchAndSaveUniqueImage( $src, $mediafolder ); if ( $cover_filename ) { // Replace with new image $coverimage->setAttribute( 'src', $cover_filename ); } } \Pressbooks\Utility\put_contents( $source, $doc->saveXML() ); $errors = libxml_get_errors(); // TODO: Handle errors gracefully libxml_clear_errors(); $output = []; $command = PB_SAXON_COMMAND . ' -xsl:' . escapeshellcmd( $xslt ) . ' -s:' . escapeshellcmd( $source ) . ' -o:' . escapeshellcmd( $content ) . ' 2>&1'; exec( $command, $output ); $files = [ 'content' => $content, 'mimetype' => $mimetype, 'meta' => $meta, 'settings' => $settings, 'styles' => $styles, 'metafolder' => $metafolder, ]; $msg = ''; foreach ( $files as $key => $file ) { if ( ! file_exists( $file ) ) { $msg .= ' [ ' . $key . ' ]'; } } if ( ! empty( $msg ) ) { $this->logError( "Transformation failed, encountered a problem with $msg \n\n" . implode( "\n", $output ) ); return false; } $zip = new \PclZip( $this->outputPath ); if ( $images->length > 0 ) { $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $mediafolder . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $this->tmpDir . '/' ); } else { $list = $zip->add( $mimetype . ',' . $content . ',' . $meta . ',' . $settings . ',' . $styles . ',' . $metafolder, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $this->tmpDir . '/' ); } if ( 0 === absint( $list ) ) { $this->logError( $zip->errorInfo( true ) ); return false; } return true; }
[ "function", "convert", "(", ")", "{", "// Set logfile", "$", "this", "->", "logfile", "=", "$", "this", "->", "createTmpFile", "(", ")", ";", "// Set filename", "$", "this", "->", "outputPath", "=", "$", "this", "->", "timestampedFileName", "(", "'.odt'", ...
Create $this->outputPath @return bool
[ "Create", "$this", "-", ">", "outputPath" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/odt/class-odt.php#L87-L221
pressbooks/pressbooks
inc/modules/export/odt/class-odt.php
Odt.queryXhtml
protected function queryXhtml() { $args = [ 'timeout' => $this->timeout, ]; $response = wp_remote_get( $this->url, $args ); // WordPress error? if ( is_wp_error( $response ) ) { $this->logError( $response->get_error_message() ); return false; } // Server error? if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { $this->logError( wp_remote_retrieve_response_message( $response ) ); return false; } return wp_remote_retrieve_body( $response ); }
php
protected function queryXhtml() { $args = [ 'timeout' => $this->timeout, ]; $response = wp_remote_get( $this->url, $args ); // WordPress error? if ( is_wp_error( $response ) ) { $this->logError( $response->get_error_message() ); return false; } // Server error? if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { $this->logError( wp_remote_retrieve_response_message( $response ) ); return false; } return wp_remote_retrieve_body( $response ); }
[ "protected", "function", "queryXhtml", "(", ")", "{", "$", "args", "=", "[", "'timeout'", "=>", "$", "this", "->", "timeout", ",", "]", ";", "$", "response", "=", "wp_remote_get", "(", "$", "this", "->", "url", ",", "$", "args", ")", ";", "// WordPre...
Query the access protected "format/xhtml" URL, return the results. @return bool|string
[ "Query", "the", "access", "protected", "format", "/", "xhtml", "URL", "return", "the", "results", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/export/odt/class-odt.php#L228-L250