idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
60,200
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 ) ; if ( ! empty ( $ _REQUEST [ 'book' ] ) ) { check_admin_referer ( 'bulk-books' ) ; $ books = $ _REQUEST [ 'book' ] ; } elseif ( ! empty ( $ _REQUEST [ 'ID' ] ) ) { check_admin_referer ( $ _REQUEST [ 'ID' ] ) ; $ books = [ $ _REQUEST [ 'ID' ] ] ; } else { if ( ! empty ( $ _REQUEST [ 'user_id' ] ) ) { $ redirect_url .= '&user_id=' . $ _REQUEST [ 'user_id' ] ; } \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; } 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' ) ) ; } if ( get_current_user_id ( ) !== $ user_id ) { $ redirect_url .= '&user_id=' . $ user_id ; } $ 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 { $ _SESSION [ 'pb_errors' ] [ ] = "Invalid action: $action" ; } } $ catalog -> deleteCache ( ) ; $ _SESSION [ 'pb_notices' ] [ ] = __ ( 'Settings saved.' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; }
Save bulk actions
60,201
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' ) ) ; } 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' ) ; } $ catalog = new static ( $ user_id ) ; $ featured = ( isset ( $ _REQUEST [ 'featured' ] ) ) ? absint ( $ _REQUEST [ 'featured' ] ) : 0 ; $ catalog -> saveBook ( $ blog_id , [ 'featured' => $ featured , ] ) ; 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 ( ) ; $ _SESSION [ 'pb_notices' ] [ ] = __ ( 'Settings saved.' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; }
Save tags to database
60,202
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' ) ) ; } 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' ) ; } $ catalog = new static ( $ user_id ) ; $ catalog -> saveProfile ( $ _POST ) ; $ catalog -> uploadLogo ( 'pb_catalog_logo' ) ; $ catalog -> deleteCache ( ) ; $ _SESSION [ 'pb_notices' ] [ ] = __ ( 'Settings saved.' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; }
Save catalog profile to database
60,203
static function formAddByUrl ( ) { check_admin_referer ( 'bulk-books' ) ; $ catalog = new static ( ) ; $ user_id = $ catalog -> getUserId ( ) ; 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' ] ) { $ slug = str_replace ( $ main [ 'path' ] , '' , $ url [ 'path' ] ) ; $ slug = trim ( $ slug , '/' ) ; $ slug = explode ( '/' , $ slug ) ; $ slug = $ slug [ 0 ] ; } else { $ 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 ( ) ; $ _SESSION [ 'pb_notices' ] [ ] = __ ( 'Settings saved.' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; }
Add Book by URL
60,204
public function basename ( $ url ) { $ filename = explode ( '?' , basename ( $ url ) ) ; $ filename = array_shift ( $ filename ) ; $ filename = explode ( '#' , $ filename ) [ 0 ] ; $ filename = sanitize_file_name ( urldecode ( $ filename ) ) ; return $ filename ; }
Get sanitized basename without query string or anchors
60,205
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 ; }
Style endnotes .
60,206
protected function removeAttributionLink ( $ content ) { if ( stripos ( $ content , '<a' ) === false ) { return $ content ; } $ changed = false ; $ html5 = new HtmlParser ( ) ; $ dom = $ html5 -> loadHTML ( $ content ) ; $ urls = $ dom -> getElementsByTagName ( 'a' ) ; foreach ( $ urls as $ url ) { 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 ; } }
Removes the CC attribution link . Returns valid xhtml .
60,207
function registerThemeDirectories ( ) { 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' ] ) ; } } }
Register theme directories set a filter that hides themes under certain conditions
60,208
public static function init ( ) { if ( is_null ( self :: $ instance ) ) { self :: $ instance = new self ( ) ; self :: hooks ( self :: $ instance ) ; } return self :: $ instance ; }
Function to init our class set filters & hooks set a singleton instance
60,209
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 ; } }
Count the pages in the most recent PDF export
60,210
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 ) ; return ( int ) $ output [ 0 ] ; }
Count the pages in a PDF file
60,211
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 ] ; }
Returns the latest metadata post ID . There should be only one per book .
60,212
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 ] ; }
Returns the latest metadata post . There should be only one per book .
60,213
public function getMidByKey ( $ post_id , $ meta_key ) { 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 ; }
Return a database ID for a given meta key .
60,214
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 ) ; }
Returns a JSON object of the book information which can be posted to an API .
60,215
public function upgrade ( $ version ) { if ( $ version < 1 ) { $ 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 ( ) ; } }
Upgrade metadata .
60,216
public function fixDoubleSlashBug ( ) { $ theme = wp_get_theme ( ) ; if ( ! $ theme -> exists ( ) || ! $ theme -> is_allowed ( ) ) { return ; } else { switch_theme ( $ theme -> get_stylesheet ( ) ) ; } }
Fix a double slash bug by reactivating theme with new settings .
60,217
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 ( ) ; } } }
Change default book cover from PNG to JPG
60,218
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' ] ; $ 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 ( ) ; } } }
Generate thumbnails for a user uploaded cover
60,219
public function resetLandingPage ( ) { 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 ) ; } }
Fix broken landing page
60,220
public function migratePartContentToEditor ( ) { 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 ( ) ; }
Migrate part content to content editor
60,221
public function prepare_items ( ) { $ columns = $ this -> get_columns ( ) ; $ hidden = [ ] ; $ sortable = $ this -> get_sortable_columns ( ) ; $ this -> _column_headers = [ $ columns , $ hidden , $ sortable ] ; $ data = $ this -> getLatestExports ( ) ; $ 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' ; $ 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 ) , ] ) ; }
Prepares the list of items for displaying .
60,222
protected function truncateExports ( $ keep_the_last = 3 ) { $ files = [ ] ; foreach ( $ this -> getFiles ( ) as $ filepath ) { $ files [ $ filepath ] = filemtime ( $ filepath ) ; } arsort ( $ files ) ; $ 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 ; } foreach ( $ groups as $ group ) { $ i = 1 ; foreach ( $ group as $ filepath ) { if ( $ i > $ keep_the_last ) { unlink ( $ filepath ) ; } ++ $ i ; } } }
Keep the last three of each specific export format
60,223
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 ) ; } ) ; }
Register embed handler for web
60,224
public function registerEmbedHandlerForExport ( ) { wp_embed_register_handler ( self :: EMBED_ID , self :: EMBED_URL_REGEX , function ( $ matches , $ attr , $ url , $ rawattr ) { global $ id ; $ 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 ) ; } ) ; }
Register embed handler for exports
60,225
protected function getChapter ( \ DOMNodeList $ dom_list , $ index , $ chapter_title ) { if ( empty ( $ chapter_title ) ) { $ chapter_title = 'unknown' ; } $ chapter = new \ DOMDocument ( '1.0' , 'UTF-8' ) ; $ root = $ chapter -> createElement ( 'div' ) ; $ root -> setAttribute ( 'class' , $ chapter_title ) ; $ chapter -> appendChild ( $ root ) ; ( '__UNKNOWN__' === $ chapter_title ) ? $ i = 0 : $ i = $ index ; do { $ node = $ chapter -> importNode ( $ dom_list -> item ( $ i ) , true ) ; $ chapter -> documentElement -> appendChild ( $ node ) ; $ i ++ ; } while ( @ $ dom_list -> item ( $ i ) -> tagName != $ this -> tag && $ i < $ dom_list -> length ) ; $ h1 = $ chapter -> getElementsByTagName ( $ this -> tag ) -> item ( 0 ) ; if ( $ h1 && $ this -> tag === $ h1 -> nodeName && 'div' === $ h1 -> parentNode -> nodeName ) { $ chapter -> documentElement -> removeChild ( $ h1 ) ; } $ result = $ chapter -> saveHTML ( $ chapter -> documentElement ) ; $ result = preg_replace ( '/xmlns="http:\/\/www.w3.org\/1999\/xhtml"/' , '' , $ result ) ; return $ result ; }
Find where to start iterate through a list add elements to a new DomDocument return resulting xhtml
60,226
protected function parseContent ( \ DomDocument $ xml , $ chapter_title ) { $ element = $ xml -> documentElement ; $ node_list = $ element -> childNodes ; $ chapter_node = '' ; $ index = 0 ; for ( $ i = 0 ; $ i < $ node_list -> length ; $ i ++ ) { $ chapter_node = $ this -> findTheNode ( $ node_list -> item ( $ i ) , $ chapter_title ) ; if ( ! empty ( $ chapter_node ) ) { $ index = $ i ; break ; } } if ( $ chapter_node ) { $ chapter_title = strtolower ( preg_replace ( '/\s+/' , '-' , $ chapter_node -> nodeValue ) ) ; } return $ this -> getChapter ( $ node_list , $ index , $ chapter_title ) ; }
Find and return the identified chapter
60,227
protected function getFuzzyChapterTitles ( ) { $ chapters = [ ] ; $ xml = $ this -> getZipContent ( 'content.xml' ) ; $ proc = new \ XSLTProcessor ( ) ; $ xsl = new \ DOMDocument ( ) ; $ xsl -> load ( __DIR__ . '/xsl/odt2html.xsl' ) ; $ proc -> importStylesheet ( $ xsl ) ; $ dom_doc = $ proc -> transformToDoc ( $ xml ) ; $ headings = $ dom_doc -> getElementsByTagName ( $ this -> tag ) ; for ( $ i = 0 ; $ i < $ headings -> length ; $ i ++ ) { $ chapters [ ] = trim ( $ headings -> item ( $ i ) -> nodeValue ) ; } $ chapters = array_values ( array_filter ( $ chapters ) ) ; if ( 0 === count ( $ chapters ) ) { $ chapters [ ] = '__UNKNOWN__' ; } return $ chapters ; }
Returns an array of available chapters or unknown if none
60,228
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 ] , ] ) ; }
Render the allow_redistribution checkbox .
60,229
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 ] , ] ) ; }
Render the enable_network_api checkbox .
60,230
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 ] , ] ) ; }
Render the enable_cloning checkbox .
60,231
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 { $ new_h5p_ids [ ] = "#fixme{$h5p->id}" ; } continue 2 ; } } } } return $ new_h5p_ids ; }
Parse HTML snippet download all found H5P save transition states to change shortcodes in post processing step
60,232
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 ( ) ; } 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 ) ; do_action ( 'pb_new_blog' ) ; do_action ( 'pressbooks_new_blog' ) ; restore_current_blog ( ) ; if ( is_user_logged_in ( ) ) { ( new \ Pressbooks \ Catalog ( ) ) -> deleteCache ( ) ; if ( apply_filters ( 'pb_redirect_to_new_book' , true ) ) { \ Pressbooks \ Redirect \ location ( get_admin_url ( $ this -> blog_id ) ) ; } } }
Runs activation function and sets up default WP options for new blog a . k . a . when a registered user creates a new blog
60,233
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 ; }
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 ...
60,234
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 ) ; }
Update post status
60,235
protected function deleteTmpDir ( ) { if ( ! empty ( $ this -> tmpDir ) ) { \ Pressbooks \ Utility \ rmrdir ( $ this -> tmpDir ) ; } $ exports_folder = untrailingslashit ( pathinfo ( $ this -> outputPath , PATHINFO_DIRNAME ) ) ; if ( ! empty ( $ exports_folder ) ) { \ Pressbooks \ Utility \ rmrdir ( "{$exports_folder}/META-INF" ) ; \ Pressbooks \ Utility \ rmrdir ( "{$exports_folder}/media" ) ; } }
Delete temporary directories
60,236
protected function getProperties ( $ html_file ) { $ html = \ Pressbooks \ Utility \ get_contents ( $ html_file ) ; $ properties = [ ] ; if ( empty ( $ html ) ) { throw new \ Exception ( 'File contents empty for getProperties' ) ; } if ( $ this -> isMathML ( $ html ) ) { $ properties [ 'mathml' ] = 1 ; } if ( $ this -> isScripted ( $ html ) ) { $ properties [ 'scripted' ] = 1 ; } return $ properties ; }
Check for existence of properties attributes
60,237
protected function isMathML ( $ html ) { foreach ( $ this -> MathMLTags as $ tag ) { if ( false !== stripos ( $ html , "<$tag>" ) ) { return true ; } } return false ; }
Check for existence of scripting MathML elements
60,238
protected function isScripted ( $ html ) { if ( preg_match ( '/<script[^>]*>.*?<\/script>/is' , $ html ) ) { return true ; } try { $ html5 = new HtmlParser ( true ) ; $ doc = $ html5 -> loadHTML ( $ html ) ; foreach ( $ doc -> getElementsByTagname ( '*' ) as $ element ) { foreach ( iterator_to_array ( $ element -> attributes ) as $ name => $ attribute ) { if ( in_array ( $ name , $ this -> javaScriptEvents , true ) ) { return true ; } } } } catch ( \ Exception $ e ) { debug_error_log ( $ e ) ; } return false ; }
Check for existence of scripting elements
60,239
protected function createNCX ( $ book_contents , $ metadata ) { if ( empty ( $ this -> manifest ) ) { throw new \ Exception ( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' ) ; } $ vars = [ 'author' => ! \ Pressbooks \ Utility \ empty_space ( $ metadata [ 'pb_authors' ] ) ? sanitize_xml_attribute ( oxford_comma_explode ( $ metadata [ 'pb_authors' ] ) [ 0 ] ) : '' , 'manifest' => $ this -> manifest , 'dtd_uid' => ! empty ( $ metadata [ 'pb_ebook_isbn' ] ) ? sanitize_xml_attribute ( $ metadata [ 'pb_ebook_isbn' ] ) : sanitize_xml_attribute ( get_bloginfo ( 'url' ) ) , 'enable_external_identifier' => false , 'lang' => $ this -> lang , ] ; \ Pressbooks \ Utility \ put_contents ( $ this -> tmpDir . '/toc.xhtml' , $ this -> loadTemplate ( $ this -> dir . '/templates/epub3/toc.php' , $ vars ) ) ; \ Pressbooks \ Utility \ put_contents ( $ this -> tmpDir . '/toc.ncx' , $ this -> loadTemplate ( $ this -> dir . '/templates/epub201/ncx.php' , $ vars ) ) ; }
Create NCX file .
60,240
protected function renderBook ( $ id , $ search = null ) { switch_to_blog ( $ id ) ; if ( ! empty ( $ search ) ) { if ( ! $ this -> find ( $ search ) ) { restore_current_blog ( ) ; return [ ] ; } } $ request_metadata = new \ WP_REST_Request ( 'GET' , '/pressbooks/v2/metadata' ) ; $ response_metadata = rest_do_request ( $ request_metadata ) ; $ request_toc = new \ WP_REST_Request ( 'GET' , '/pressbooks/v2/toc' ) ; $ response_toc = rest_do_request ( $ request_toc ) ; $ item = [ 'id' => $ id , 'link' => get_blogaddress_by_id ( $ id ) , 'metadata' => $ this -> prepare_response_for_collection ( $ response_metadata ) , 'toc' => $ this -> prepare_response_for_collection ( $ response_toc ) , ] ; $ this -> linkCollector [ 'api' ] [ ] = [ 'href' => get_rest_url ( $ id ) , ] ; restore_current_blog ( ) ; $ this -> linkCollector [ 'metadata' ] [ ] = [ 'href' => $ item [ 'metadata' ] [ '_links' ] [ 'self' ] [ 0 ] [ 'href' ] , ] ; unset ( $ item [ 'metadata' ] [ '_links' ] ) ; $ this -> linkCollector [ 'toc' ] [ ] = [ 'href' => $ item [ 'toc' ] [ '_links' ] [ 'self' ] [ 0 ] [ 'href' ] , ] ; foreach ( $ item [ 'toc' ] [ '_links' ] [ 'metadata' ] as $ v ) { $ this -> linkCollector [ 'metadata' ] [ ] = [ 'href' => $ v [ 'href' ] , ] ; } unset ( $ item [ 'toc' ] [ '_links' ] ) ; $ this -> linkCollector [ 'self' ] [ ] = [ 'href' => rest_url ( sprintf ( '%s/%s/%d' , $ this -> namespace , $ this -> rest_base , $ id ) ) , ] ; return $ item ; }
Switches to a book renders it for use in JSON response if found
60,241
protected function fulltextSearchInPost ( $ search ) { $ s = $ this -> searchArgs ( $ search ) ; $ q = new \ WP_Query ( $ s ) ; if ( $ q -> post_count > 0 ) { return true ; } else { return false ; } }
Fulltext search entire book
60,242
protected function fulltextSearchInMeta ( $ search ) { $ meta = new \ Pressbooks \ Metadata ( ) ; $ data = $ meta -> getMetaPostMetadata ( ) ; foreach ( $ data as $ key => $ haystack ) { if ( ! preg_match ( '/^pb_/' , $ key ) ) { continue ; } if ( is_array ( $ haystack ) ) { $ haystack = implode ( ' ' , $ haystack ) ; } if ( stripos ( $ haystack , $ search ) !== false ) { return true ; } } return false ; }
Fulltext search all pb_ prefixed meta keys in metadata post
60,243
protected function addNextSearchLinks ( $ request , $ response ) { $ max_pages = ( int ) ceil ( $ this -> totalBooks / ( int ) $ request [ 'per_page' ] ) ; $ response -> header ( 'X-WP-Total' , ( int ) $ this -> totalBooks ) ; $ response -> header ( 'X-WP-TotalPages' , $ max_pages ) ; if ( $ this -> lastKnownBookId ) { unset ( $ request [ 'page' ] ) ; $ request_params = $ request -> get_query_params ( ) ; $ base = add_query_arg ( $ request_params , rest_url ( sprintf ( '%s/%s' , $ this -> namespace , $ this -> rest_base ) ) ) ; $ next_link = add_query_arg ( 'next' , $ this -> lastKnownBookId , $ base ) ; $ response -> link_header ( 'next' , $ next_link ) ; } }
Add a next link for search results
60,244
public function maybeUpgrade ( ) { $ taxonomy_version = get_option ( 'pressbooks_taxonomy_version' , 0 ) ; if ( $ taxonomy_version < self :: VERSION ) { $ this -> upgrade ( $ taxonomy_version ) ; update_option ( 'pressbooks_taxonomy_version' , self :: VERSION ) ; } }
Is it time to upgrade?
60,245
protected function upgradeChapterTypes ( ) { $ type_1 = get_term_by ( 'slug' , 'type-1' , 'chapter-type' ) ; $ type_2 = get_term_by ( 'slug' , 'type-2' , 'chapter-type' ) ; $ type_3 = get_term_by ( 'slug' , 'type-3' , 'chapter-type' ) ; $ type_4 = get_term_by ( 'slug' , 'type-4' , 'chapter-type' ) ; $ type_5 = get_term_by ( 'slug' , 'type-5' , 'chapter-type' ) ; if ( $ type_1 ) { wp_update_term ( $ type_1 -> term_id , 'chapter-type' , [ 'name' => 'Standard' , 'slug' => 'standard' , ] ) ; } if ( $ type_2 ) { wp_delete_term ( $ type_2 -> term_id , 'chapter-type' ) ; } if ( $ type_3 ) { wp_delete_term ( $ type_3 -> term_id , 'chapter-type' ) ; } if ( $ type_4 ) { wp_delete_term ( $ type_4 -> term_id , 'chapter-type' ) ; } if ( $ type_5 ) { wp_delete_term ( $ type_5 -> term_id , 'chapter-type' ) ; } }
Upgrade Chapter Types .
60,246
public function replaceOembed ( $ return , $ data , $ url ) { if ( stripos ( $ return , '<iframe' ) === false ) { return $ return ; } global $ id ; $ title = $ data -> title ?? $ this -> getTitle ( $ id ) ; $ img_src = $ data -> thumbnail_url ?? null ; $ provider_name = $ data -> provider_name ?? null ; $ url = wp_get_shortlink ( $ id ) ; $ html = $ this -> blade -> render ( 'interactive.oembed' , [ 'title' => $ title , 'img_src' => $ img_src , 'provider_name' => $ provider_name , 'url' => $ url , ] ) ; return $ html ; }
Filters the returned oEmbed HTML . Hooked into oembed_dataparse filter
60,247
public function addExtraOembedProviders ( $ providers ) { $ providers [ '#https?://mathembed\.com/latex\?inputText=.*#i' ] = [ 'https://mathembed.com/oembed' , true ] ; $ providers [ '#https?://www\.openassessments\.org/assessments/.*#i' ] = [ 'https://www.openassessments.org/oembed.json' , true ] ; $ providers [ '://cdn.knightlab.com/libs/timeline*' ] = [ 'https://oembed.knightlab.com/timeline/' , false ] ; $ providers [ '://uploads.knightlab.com/storymapjs/*/index.html' ] = [ 'https://oembed.knightlab.com/storymap/' , false ] ; return $ providers ; }
Add oEmbed providers Hooked into oembed_providers filter
60,248
public function deleteOembedCaches ( $ post_id = 0 ) { if ( $ post_id ) { global $ wp_embed ; $ wp_embed -> delete_oembed_caches ( $ post_id ) ; } else { global $ wpdb ; $ post_metas = $ wpdb -> get_results ( "SELECT post_id, meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE '_oembed_%' " ) ; foreach ( $ post_metas as $ post_meta ) { delete_post_meta ( $ post_meta -> post_id , $ post_meta -> meta_key ) ; } } }
Delete all oEmbed caches
60,249
public function beforeExport ( ) { $ this -> overrideH5P ( ) ; $ this -> overridePhet ( ) ; $ this -> overrideIframes ( ) ; $ this -> overrideEmbeds ( ) ; $ this -> overrideVideo ( ) ; $ this -> overrideAudio ( ) ; }
Hooked into pb_pre_export action
60,250
protected function overrideEmbeds ( ) { global $ wp_embed ; $ wp_embed -> usecache = false ; add_filter ( 'oembed_ttl' , '__return_zero' , 999 ) ; add_filter ( 'embed_defaults' , function ( $ attr ) { $ attr [ 'data-pb-export' ] = 'true' ; return $ attr ; } ) ; add_filter ( 'oembed_dataparse' , [ $ this , 'replaceOembed' ] , 1 , 3 ) ; }
Override WordPress Embeds
60,251
protected function getLicenseAttribution ( $ html ) { $ meta = [ ] ; preg_match ( '/(?:<div class="license-attribution[^>]*>)(.*)(<\/div>)/isU' , $ html , $ matches ) ; if ( ! empty ( $ matches [ 1 ] ) ) { $ html5 = new HtmlParser ( ) ; $ dom = $ html5 -> loadHTML ( $ matches [ 1 ] ) ; $ meta = $ this -> scrapeAndKneadMeta ( $ dom ) ; } return $ meta ; }
Looks for div class created by the license module in PB returns author and license information .
60,252
protected function regexSearchReplace ( $ html ) { preg_match ( '/(?:<main[^>]*>)(.*)<\/main>/isU' , $ html , $ matches ) ; $ html = ( ! empty ( $ matches [ 1 ] ) ) ? $ matches [ 1 ] : $ html ; preg_match ( '/(?:<div id="main"[^>]*>)(.*)<\/div>/is' , $ html , $ matches ) ; $ html = ( ! empty ( $ matches [ 1 ] ) ) ? $ matches [ 1 ] : $ html ; preg_match ( '/(?:<div id="content"[^>]*>)(.*)<\/div>/is' , $ html , $ matches ) ; $ html = ( ! empty ( $ matches [ 1 ] ) ) ? $ matches [ 1 ] : $ html ; preg_match ( '/(?:<div class="entry-content"[^>]*>)(.*)<\/div>/is' , $ html , $ matches ) ; $ html = ( ! empty ( $ matches [ 1 ] ) ) ? $ matches [ 1 ] : $ html ; $ result = preg_replace ( '/(?:<script[^>]*>)(.*)<\/script>/isU' , '' , $ html ) ; $ result = preg_replace ( '/(?:<form[^>]*>)(.*)<\/form>/isU' , '' , $ result ) ; $ result = preg_replace ( '/(?:<nav[^>]*>)(.*)<\/nav>/isU' , '' , $ result ) ; $ result = preg_replace ( '/(?:<div class="nav"[^>]*>)(.*)<\/div>/isU' , '' , $ result ) ; $ result = preg_replace ( '/(?:<div class="share-wrap-single"[^>]*>)(.*)<\/div>/isU' , '' , $ result ) ; $ result = preg_replace ( '/(?:<footer[^>]*>)(.*)<\/footer>/isU' , '' , $ result ) ; $ result = preg_replace ( '/(?:<div id="sidebar\d{0,}"[^>]*>)(.*)<\/div>/is' , '' , $ result ) ; $ result = preg_replace ( '/(?:<div id="comments"[^>]*>)(.*)<\/div>/is' , '' , $ result ) ; return $ result ; }
Cherry pick likely content areas then cull known unwanted content areas
60,253
private function emitMessage ( $ data ) { $ msg = "event: message\n" ; $ msg .= 'data: ' . wp_json_encode ( $ data ) . "\n\n" ; $ msg .= ':' . str_repeat ( ' ' , 2048 ) . "\n\n" ; if ( ob_get_level ( ) ) { $ this -> msgStack [ ] = $ msg ; } else { foreach ( $ this -> msgStack as $ stack ) { echo $ stack ; } $ this -> msgStack = [ ] ; echo $ msg ; flush ( ) ; } }
Emit a Server - Sent Events message .
60,254
protected function getIDs ( \ DOMDocument $ dom_doc , $ tag = 'footnoteReference' , $ attr = 'w:id' ) { $ fn_ids = [ ] ; $ doc_elem = $ dom_doc -> documentElement ; $ tags_fn_ref = $ doc_elem -> getElementsByTagName ( $ tag ) ; if ( $ tags_fn_ref -> length > 0 ) { foreach ( $ tags_fn_ref as $ id ) { if ( '' !== $ id -> getAttribute ( $ attr ) ) { $ fn_ids [ ] = $ id -> getAttribute ( $ attr ) ; } } } return $ fn_ids ; }
Given a documentElement it will return an array of ids
60,255
protected function getRelationshipPart ( array $ ids , $ tag = 'footnotes' ) { $ footnotes = [ ] ; $ tag_name = rtrim ( $ tag , 's' ) ; switch ( $ tag ) { case 'endnotes' : $ target_path = $ this -> getTargetPath ( self :: ENDNOTES_SCHEMA , $ tag ) ; break ; case 'hyperlink' : $ target_path = $ this -> getTargetPath ( self :: HYPERLINK_SCHEMA , $ tag ) ; break ; default : $ target_path = $ this -> getTargetPath ( self :: FOOTNOTES_SCHEMA , $ tag ) ; break ; } if ( empty ( $ target_path ) ) { return false ; } if ( is_array ( $ target_path ) ) { return $ target_path ; } $ limit = count ( $ ids ) ; $ dom_doc = $ this -> getZipContent ( $ target_path ) ; $ doc_elem = $ dom_doc -> documentElement ; $ text_tags = $ doc_elem -> getElementsByTagName ( $ tag_name ) ; if ( $ text_tags -> length !== $ limit + 2 ) { throw new \ Exception ( 'mismatch between length of FootnoteReference array number of footnotes available' ) ; } for ( $ i = 0 ; $ i < $ limit ; $ i ++ ) { $ footnotes [ $ ids [ $ i ] ] = $ text_tags -> item ( $ i + 2 ) -> nodeValue ; } return $ footnotes ; }
Give this some ids and it returns an associative array of footnotes
60,256
protected function addHyperlinks ( \ DOMDocument $ chapter ) { $ ln = $ chapter -> getElementsByTagName ( 'a' ) ; for ( $ i = $ ln -> length ; -- $ i >= 0 ; ) { $ link = $ ln -> item ( $ i ) ; if ( $ link -> hasAttribute ( 'name' ) && in_array ( $ link -> getAttribute ( 'name' ) , [ '_GoBack' ] , true ) ) { $ link -> parentNode -> removeChild ( $ link ) ; continue ; } if ( $ link -> hasAttribute ( 'class' ) ) { $ ln_id = $ link -> getAttribute ( 'class' ) ; if ( array_key_exists ( $ ln_id , $ this -> ln ) ) { $ link -> setAttribute ( 'href' , $ this -> ln [ $ ln_id ] ) ; } } } return $ chapter ; }
adds external hyperlinks if they are present in a chapter
60,257
protected function addFootnotes ( \ DOMDocument $ chapter ) { $ fn_candidates = $ chapter -> getelementsByTagName ( 'a' ) ; $ fn_ids = [ ] ; foreach ( $ fn_candidates as $ fn_candidate ) { $ href = $ fn_candidate -> getAttribute ( 'href' ) ; if ( ! empty ( $ href ) ) { $ fn_matches = null ; if ( preg_match ( self :: FOOTNOTE_HREF_PATTERN , $ href , $ fn_matches ) ) { $ fn_ids [ ] = $ fn_matches [ 1 ] ; } } } $ notes = [ ] ; if ( ! empty ( $ this -> fn ) ) { $ notes = $ this -> fn ; } if ( ! empty ( $ this -> en ) ) { $ notes = $ this -> en ; } foreach ( $ fn_ids as $ id ) { if ( array_key_exists ( $ id , $ notes ) ) { $ grandparent = $ chapter -> createElement ( 'div' ) ; $ grandparent -> setAttribute ( 'id' , "sdfootnote{$id}sym" ) ; $ parent = $ chapter -> createElement ( 'span' ) ; $ child = $ chapter -> createElement ( 'a' , $ id ) ; $ child -> setAttribute ( 'href' , "#sdfootnote{$id}anc" ) ; $ child -> setAttribute ( 'name' , "sdfootnote{$id}sym" ) ; $ text = $ chapter -> createTextNode ( $ notes [ $ id ] ) ; $ grandparent -> appendChild ( $ parent ) ; $ parent -> appendChild ( $ child ) ; $ parent -> appendChild ( $ text ) ; $ chapter -> documentElement -> appendChild ( $ grandparent ) ; } } return $ chapter ; }
adds footnotes if they are present in the chapter
60,258
protected function findTheNode ( \ DOMNode $ node , $ chapter_name ) { if ( XML_ELEMENT_NODE !== $ node -> nodeType ) { return '' ; } $ current_tag = $ node -> tagName ; $ current_value = trim ( $ node -> nodeValue ) ; if ( $ chapter_name === $ current_value && $ this -> tag === $ current_tag ) { return $ node ; } if ( $ node -> hasChildNodes ( ) ) { $ node_list = $ node -> childNodes ; for ( $ i = 0 ; $ i < $ node_list -> length ; $ i ++ ) { if ( $ node_list -> item ( $ i ) -> nodeType !== XML_ELEMENT_NODE ) { continue ; } if ( $ chapter_name !== $ node_list -> item ( $ i ) -> nodeValue && $ this -> tag !== $ node_list -> item ( $ i ) -> tagName ) { return $ this -> findTheNode ( $ node_list -> item ( $ i ) , $ chapter_name ) ; } } } return '' ; }
Recursive iterator to locate and return a specific node targeting child nodes
60,259
protected function isValidZip ( $ fullpath ) { $ result = $ this -> zip -> open ( $ fullpath ) ; if ( true !== $ result ) { throw new \ Exception ( 'Opening docx file failed' ) ; } $ path = $ this -> getTargetPath ( self :: DOCUMENT_SCHEMA ) ; $ ok = $ this -> getZipContent ( $ path ) ; if ( ! $ ok ) { throw new \ Exception ( 'Bad or corrupted _rels/.rels' ) ; } }
Checks for standard DOCX file structure
60,260
protected function overrideUsingFilterAndActions ( ) { add_post_type_support ( $ this -> post_type , 'custom-fields' ) ; add_filter ( "rest_{$this->post_type}_query" , [ $ this , 'overrideQueryArgs' ] ) ; add_filter ( "rest_prepare_{$this->post_type}" , [ $ this , 'overrideResponse' ] , 10 , 3 ) ; add_filter ( "rest_{$this->post_type}_trashable" , [ $ this , 'overrideTrashable' ] , 10 , 2 ) ; }
Use object inheritance as little as possible to future - proof against WP API changes
60,261
public function overrideResponse ( $ response , $ post , $ request ) { if ( $ post -> post_type === 'chapter' ) { $ response -> add_link ( 'part' , trailingslashit ( rest_url ( sprintf ( '%s/%s' , $ this -> namespace , 'parts' ) ) ) . $ post -> post_parent ) ; } if ( in_array ( $ post -> post_type , [ 'front-matter' , 'chapter' , 'back-matter' , 'glossary' ] , true ) ) { $ response -> add_link ( 'metadata' , trailingslashit ( rest_url ( sprintf ( '%s/%s/%d/metadata' , $ this -> namespace , $ this -> rest_base , $ post -> ID ) ) ) ) ; } if ( in_array ( $ request [ 'context' ] , [ 'view' , 'embed' ] , true ) ) { if ( ! empty ( $ response -> data [ 'content' ] ) ) { if ( $ response -> data [ 'content' ] [ 'protected' ] && empty ( $ response -> data [ 'content' ] [ 'rendered' ] ) ) { $ response -> data [ 'content' ] [ 'raw' ] = '' ; } } if ( ! empty ( $ response -> data [ 'excerpt' ] ) ) { if ( $ response -> data [ 'excerpt' ] [ 'protected' ] && empty ( $ response -> data [ 'excerpt' ] [ 'rendered' ] ) ) { $ response -> data [ 'excerpt' ] [ 'raw' ] = '' ; } } } return $ response ; }
Override the response object
60,262
static function getCustomCssFolder ( ) { $ path = \ Pressbooks \ Utility \ get_media_prefix ( ) . 'custom-css/' ; if ( ! file_exists ( $ path ) ) { wp_mkdir_p ( $ path ) ; } return $ path ; }
Get the fullpath to the Custom CSS folder Create if not there .
60,263
static function getBaseTheme ( $ slug ) { $ filename = static :: getCustomCssFolder ( ) . sanitize_file_name ( $ slug . '.css' ) ; if ( ! file_exists ( $ filename ) ) { return false ; } $ theme = get_file_data ( $ filename , [ 'ThemeURI' => 'Theme URI' , ] ) ; $ theme_slug = str_replace ( [ 'http://pressbooks.com/themes/' , 'https://pressbooks.com/themes/' ] , [ '' , '' ] , $ theme [ 'ThemeURI' ] ) ; return untrailingslashit ( $ theme_slug ) ; }
Determine base theme that was used for the selected Custom CSS .
60,264
static public function hooks ( Complex $ obj ) { add_shortcode ( 'anchor' , [ $ obj , 'anchorShortCodeHandler' ] ) ; add_shortcode ( 'columns' , [ $ obj , 'columnsShortCodeHandler' ] ) ; add_shortcode ( 'email' , [ $ obj , 'emailShortCodeHandler' ] ) ; add_shortcode ( 'equation' , [ $ obj , 'equationShortCodeHandler' ] ) ; add_shortcode ( 'media' , [ $ obj , 'mediaShortCodeHandler' ] ) ; }
Shortcode registration hooks .
60,265
function init ( ) { $ _option = 'pressbooks_theme_options_' . $ this -> getSlug ( ) ; $ _page = $ _option ; $ _section = $ this -> getSlug ( ) . '_options_section' ; if ( false === get_option ( $ _option ) ) { add_option ( $ _option , $ this -> defaults ) ; } add_settings_section ( $ _section , $ this -> getTitle ( ) , [ $ this , 'display' ] , $ _page ) ; add_settings_field ( 'ebook_start_point' , __ ( 'Ebook Start Point' , 'pressbooks' ) , [ $ this , 'renderEbookStartPointField' ] , $ _page , $ _section , [ __ ( 'Note: This designated ebook start book may be overridden by some ereader devices.' , 'pressbooks' ) , 'label_for' => 'ebook_start_point' , ] ) ; add_settings_field ( 'ebook_paragraph_separation' , __ ( 'Paragraph Separation' , 'pressbooks' ) , [ $ this , 'renderParagraphSeparationField' ] , $ _page , $ _section , [ 'indent' => __ ( 'Indent paragraphs' , 'pressbooks' ) , 'skiplines' => __ ( 'Skip lines between paragraphs' , 'pressbooks' ) , ] ) ; add_settings_field ( 'ebook_compress_images' , __ ( 'Compress Images' , 'pressbooks' ) , [ $ this , 'renderCompressImagesField' ] , $ _page , $ _section , [ __ ( 'Reduce image size and quality' , 'pressbooks' ) , ] ) ; do_action ( 'pb_theme_options_ebook_add_settings_fields' , $ _page , $ _section ) ; register_setting ( $ _option , $ _option , [ $ this , 'sanitize' ] ) ; }
Configure the ebook options tab using the settings API .
60,266
function setEbookStartPoint ( ) { $ _option = $ this -> getSlug ( ) ; $ options = get_option ( 'pressbooks_theme_options_' . $ _option , $ this -> defaults ) ; $ struct = \ Pressbooks \ Book :: getBookStructure ( ) ; foreach ( $ struct [ 'front-matter' ] as $ k => $ v ) { if ( get_post_meta ( $ v [ 'ID' ] , 'pb_ebook_start' , true ) ) { $ options [ 'ebook_start_point' ] = $ v [ 'ID' ] ; break ; } } if ( ! isset ( $ options [ 'ebook_start_point' ] ) ) { foreach ( $ struct [ 'part' ] as $ key => $ value ) { foreach ( $ value [ 'chapters' ] as $ k => $ v ) { if ( get_post_meta ( $ v [ 'ID' ] , 'pb_ebook_start' , true ) ) { $ options [ 'ebook_start_point' ] = $ v [ 'ID' ] ; break ; } } } } if ( ! isset ( $ options [ 'ebook_start_point' ] ) ) { foreach ( $ struct [ 'back-matter' ] as $ k => $ v ) { if ( get_post_meta ( $ v [ 'ID' ] , 'pb_ebook_start' , true ) ) { $ options [ 'ebook_start_point' ] = $ v [ 'ID' ] ; break ; } } } update_option ( 'pressbooks_theme_options_' . $ _option , $ options ) ; }
Update values to human - readable equivalents within Ebook options .
60,267
function renderEbookStartPointField ( $ args ) { unset ( $ args [ 'label_for' ] , $ args [ 'class' ] ) ; $ options = [ '' => '--' , ] ; $ struct = \ Pressbooks \ Book :: getBookStructure ( ) ; foreach ( $ struct [ 'front-matter' ] as $ k => $ v ) { $ options [ $ v [ 'ID' ] ] = $ v [ 'post_title' ] ; } foreach ( $ struct [ 'part' ] as $ key => $ value ) { foreach ( $ value [ 'chapters' ] as $ k => $ v ) { $ options [ $ v [ 'ID' ] ] = $ v [ 'post_title' ] ; } } foreach ( $ struct [ 'back-matter' ] as $ k => $ v ) { $ options [ $ v [ 'ID' ] ] = $ v [ 'post_title' ] ; } $ this -> renderSelect ( [ 'id' => 'ebook_start_point' , 'name' => 'pressbooks_theme_options_' . $ this -> getSlug ( ) , 'option' => 'ebook_start_point' , 'value' => ( isset ( $ this -> options [ 'ebook_start_point' ] ) ) ? $ this -> options [ 'ebook_start_point' ] : '' , 'choices' => $ options , 'description' => $ args [ 0 ] , ] ) ; }
Render the ebook_start_point dropdown .
60,268
function renderParagraphSeparationField ( $ args ) { unset ( $ args [ 'label_for' ] , $ args [ 'class' ] ) ; $ this -> renderRadioButtons ( [ 'id' => 'ebook_paragraph_separation' , 'name' => 'pressbooks_theme_options_' . $ this -> getSlug ( ) , 'option' => 'ebook_paragraph_separation' , 'value' => ( isset ( $ this -> options [ 'ebook_paragraph_separation' ] ) ) ? $ this -> options [ 'ebook_paragraph_separation' ] : '' , 'choices' => $ args , ] ) ; }
Render the ebook_paragraph_separation radio buttons .
60,269
function renderCompressImagesField ( $ args ) { unset ( $ args [ 'label_for' ] , $ args [ 'class' ] ) ; $ this -> renderCheckbox ( [ 'id' => 'ebook_compress_images' , 'name' => 'pressbooks_theme_options_' . $ this -> getSlug ( ) , 'option' => 'ebook_compress_images' , 'value' => ( isset ( $ this -> options [ 'ebook_compress_images' ] ) ) ? $ this -> options [ 'ebook_compress_images' ] : '' , 'label' => $ args [ 0 ] , ] ) ; }
Render the ebook_compress_images checkbox .
60,270
public function doLicense ( $ metadata , $ post_id = 0 , $ title = '' ) { if ( ! empty ( $ title ) ) { _doing_it_wrong ( __METHOD__ , __ ( '$title is deprecated. Method will automatically determine title from licenses' , 'pressbooks' ) , 'Pressbooks 5.7.0' ) ; } $ book_license = isset ( $ metadata [ 'pb_book_license' ] ) ? $ metadata [ 'pb_book_license' ] : '' ; if ( empty ( $ post_id ) ) { $ section_license = '' ; $ section_author = '' ; } else { $ section_license = get_post_meta ( $ post_id , 'pb_section_license' , true ) ; $ section_author = ( new Contributors ( ) ) -> get ( $ post_id , 'pb_authors' ) ; } if ( ! empty ( $ section_license ) ) { $ license = $ section_license ; } elseif ( ! empty ( $ book_license ) ) { $ license = $ book_license ; } else { $ license = 'all-rights-reserved' ; } if ( ! $ this -> isSupportedType ( $ license ) ) { return '' ; } if ( $ section_license === $ book_license || empty ( $ section_license ) ) { $ title = get_bloginfo ( 'name' ) ; $ link = get_bloginfo ( 'url' ) ; } else { $ post = get_post ( $ post_id ) ; $ title = $ post ? $ post -> post_title : get_bloginfo ( 'name' ) ; $ link = get_permalink ( $ post_id ) ; } if ( ! empty ( $ section_author ) ) { $ copyright_holder = $ section_author ; } elseif ( isset ( $ metadata [ 'pb_copyright_holder' ] ) ) { $ copyright_holder = $ metadata [ 'pb_copyright_holder' ] ; } elseif ( isset ( $ metadata [ 'pb_authors' ] ) ) { $ copyright_holder = $ metadata [ 'pb_authors' ] ; } else { $ copyright_holder = '' ; } if ( ! empty ( $ metadata [ 'pb_copyright_year' ] ) ) { $ copyright_year = $ metadata [ 'pb_copyright_year' ] ; } elseif ( ! empty ( $ metadata [ 'pb_publication_date' ] ) ) { $ copyright_year = strftime ( '%Y' , absint ( $ metadata [ 'pb_publication_date' ] ) ) ; } else { $ copyright_year = 0 ; } $ html = $ this -> getLicense ( $ license , $ copyright_holder , $ link , $ title , $ copyright_year ) ; return $ html ; }
Will create an html blob of copyright information returns empty string if license not supported
60,271
public function getLicenseXml ( $ type , $ copyright_holder , $ src_url , $ title , $ lang = '' , $ year = 0 ) { $ endpoint = 'https://api.creativecommons.org/rest/1.5/' ; $ lang = ( ! empty ( $ lang ) ) ? substr ( $ lang , 0 , 2 ) : '' ; $ expected = $ this -> getSupportedTypes ( ) ; if ( ! array_key_exists ( $ type , $ expected ) ) { return '' ; } if ( $ type !== 'all-rights-reserved' && empty ( $ expected [ $ type ] [ 'api' ] ) ) { $ type = 'all-rights-reserved' ; } switch ( $ type ) { case 'all-rights-reserved' : $ xml = '<result><html>' . "<span property='dct:title'>" . Sanitize \ sanitize_xml_attribute ( $ title ) . '</span> ' . __ ( 'Copyright' , 'pressbooks' ) . ' &#169; ' ; if ( $ year ) { $ xml .= Sanitize \ sanitize_xml_attribute ( $ year ) . ' ' . __ ( 'by' , 'pressbooks' ) . ' ' ; } $ xml .= Sanitize \ sanitize_xml_attribute ( $ copyright_holder ) ; $ xml .= '. ' . __ ( 'All Rights Reserved' , 'pressbooks' ) . '.</html></result>' ; break ; default : $ key = array_keys ( $ expected [ $ type ] [ 'api' ] ) ; $ val = array_values ( $ expected [ $ type ] [ 'api' ] ) ; $ url = $ endpoint . $ key [ 0 ] . '/' . $ val [ 0 ] . '/get?' . $ key [ 1 ] . '=' . $ val [ 1 ] . '&' . $ key [ 2 ] . '=' . $ val [ 2 ] . '&creator=' . rawurlencode ( $ copyright_holder ) . '&attribution_url=' . rawurlencode ( $ src_url ) . '&title=' . rawurlencode ( $ title ) . '&locale=' . $ lang ; if ( $ year ) { $ url .= '&year=' . ( int ) $ year ; } $ xml = wp_remote_get ( $ url ) ; $ ok = wp_remote_retrieve_response_code ( $ xml ) ; if ( absint ( $ ok ) === 200 && is_wp_error ( $ xml ) === false ) { $ xml = $ xml [ 'body' ] ; } else { if ( is_wp_error ( $ xml ) ) { $ error_message = $ xml -> get_error_message ( ) ; } elseif ( is_array ( $ xml ) && ! empty ( $ xml [ 'body' ] ) ) { $ error_message = wp_strip_all_tags ( $ xml [ 'body' ] ) ; } else { $ error_message = 'An unknown error occurred' ; } debug_error_log ( '\Pressbooks\Licensing::getLicenseXml() error: ' . $ error_message ) ; $ xml = '' ; } break ; } return $ xml ; }
Takes a known string from metadata builds a url to hit an api which returns an xml response
60,272
public function getLicenseHtml ( \ SimpleXMLElement $ response , $ except_where_otherwise_noted = true ) { $ content = $ response -> asXML ( ) ; $ content = trim ( str_replace ( [ '<p xmlns:dct="http://purl.org/dc/terms/">' , '</p>' , '<html>' , '</html>' ] , '' , $ content ) ) ; $ content = preg_replace ( '/http:\/\/i.creativecommons/iU' , 'https://i.creativecommons' , $ content ) ; $ html = '<div class="license-attribution" xmlns:cc="http://creativecommons.org/ns#"><p xmlns:dct="http://purl.org/dc/terms/">' ; if ( $ except_where_otherwise_noted ) { $ html .= rtrim ( $ content , '.' ) . ', ' . __ ( 'except where otherwise noted.' , 'pressbooks' ) ; } else { $ html .= $ content ; } $ html .= '</p></div>' ; return html_entity_decode ( $ html , ENT_XHTML , 'UTF-8' ) ; }
Returns an HTML blob if given an XML object
60,273
public function getLicenseFromUrl ( $ url ) { $ licenses = $ this -> getSupportedTypes ( ) ; foreach ( $ licenses as $ license => $ v ) { if ( $ url === $ v [ 'url' ] ) { return $ license ; } } return 'all-rights-reserved' ; }
Returns Book Information - compatible license value from URL .
60,274
public function getNameForLicense ( $ license ) { $ types = $ this -> getSupportedTypes ( ) ; if ( $ this -> isSupportedType ( $ license ) ) { if ( isset ( $ types [ $ license ] [ 'longdesc' ] ) ) { return $ types [ $ license ] [ 'longdesc' ] ; } else { return $ types [ $ license ] [ 'desc' ] ; } } else { return $ types [ 'all-rights-reserved' ] [ 'desc' ] ; } }
Returns long description for saved license value .
60,275
public function init ( ) { if ( ! Book :: isBook ( ) ) { return ; } if ( class_exists ( '\Pressbooks\CustomCss' ) && CustomCss :: isCustomCss ( ) ) { return ; } if ( isset ( $ _REQUEST [ 'page' ] ) && $ _REQUEST [ 'page' ] === $ this :: PAGE ) { add_action ( 'admin_enqueue_scripts' , function ( ) { wp_enqueue_script ( 'wp-codemirror' ) ; wp_enqueue_script ( 'csslint' ) ; wp_enqueue_style ( 'wp-codemirror' ) ; } ) ; } add_action ( 'init' , function ( ) { add_action ( 'admin_menu' , function ( ) { add_theme_page ( __ ( 'Custom Styles' , 'pressbooks' ) , __ ( 'Custom Styles' , 'pressbooks' ) , 'edit_others_posts' , $ this :: PAGE , [ $ this , 'editor' ] ) ; } , 11 ) ; $ this -> registerPosts ( ) ; } ) ; add_action ( 'init' , [ $ this , 'formSubmit' ] , 50 ) ; }
Set filters & hooks
60,276
public function getPathToScss ( $ type , $ theme = null ) { if ( null === $ theme ) { $ theme = wp_get_theme ( ) ; } if ( $ this -> isCurrentThemeCompatible ( 1 , $ theme ) ) { if ( 'web' === $ type ) { $ path_to_style = realpath ( $ this -> getDir ( $ theme ) . '/style.scss' ) ; } else { $ path_to_style = realpath ( $ this -> getDir ( $ theme ) . "/export/$type/style.scss" ) ; } } elseif ( $ this -> isCurrentThemeCompatible ( 2 , $ theme ) ) { $ path_to_style = realpath ( $ this -> getDir ( $ theme ) . "/assets/styles/$type/style.scss" ) ; } else { $ path_to_style = false ; } return $ path_to_style ; }
Fullpath to SCSS file
60,277
public function isCurrentThemeCompatible ( $ version = 1 , $ theme = null ) { if ( null === $ theme ) { $ theme = wp_get_theme ( ) ; } $ basepath = $ this -> getDir ( $ theme ) ; $ types = [ 'prince' , 'epub' , 'web' , ] ; foreach ( $ types as $ type ) { $ path = '' ; if ( 1 === $ version && 'web' !== $ type ) { $ path = $ basepath . "/export/$type/style.scss" ; } elseif ( 1 === $ version && 'web' === $ type ) { $ path = $ basepath . '/style.scss' ; } if ( 2 === $ version ) { $ path = $ basepath . "/assets/styles/$type/style.scss" ; } $ fullpath = realpath ( $ path ) ; if ( ! is_file ( $ fullpath ) ) { return false ; } } return true ; }
Are the current theme s stylesheets SCSS compatible?
60,278
public function getBuckramVersion ( ) { $ fullpath = realpath ( $ this -> sass -> pathToGlobals ( ) . 'buckram.scss' ) ; if ( is_file ( $ fullpath ) ) { return get_file_data ( $ fullpath , [ 'version' => 'Version' , ] ) [ 'version' ] ; } return false ; }
Get the version of Buckram for the current install or locked theme .
60,279
public function customize ( $ type , $ scss , $ overrides = [ ] ) { $ scss = $ this -> applyOverrides ( $ scss , $ overrides ) ; if ( $ type === 'prince' ) { $ scss = apply_filters ( 'pb_pdf_css_override' , $ scss ) ; } else { $ scss = apply_filters ( "pb_{$type}_css_override" , $ scss ) ; } if ( $ this -> isCurrentThemeCompatible ( 1 ) ) { $ css = $ this -> sass -> compile ( $ scss , [ $ this -> sass -> pathToUserGeneratedSass ( ) , $ this -> sass -> pathToPartials ( ) , $ this -> sass -> pathToFonts ( ) , $ this -> getDir ( ) , ] ) ; } elseif ( $ this -> isCurrentThemeCompatible ( 2 ) ) { $ css = $ this -> sass -> compile ( $ scss , $ this -> sass -> defaultIncludePaths ( $ type ) ) ; } elseif ( CustomCss :: isCustomCss ( ) ) { $ custom_css_includes = $ this -> sass -> defaultIncludePaths ( $ type , wp_get_theme ( 'pressbooks-book' ) ) ; $ custom_css_includes [ ] = $ this -> sass -> pathToPartials ( ) ; $ css = $ this -> sass -> compile ( $ scss , $ custom_css_includes ) ; } else { $ css = $ this -> injectHouseStyles ( $ scss ) ; } return $ css ; }
Transpile SCSS based on theme compatibility
60,280
public function applyOverrides ( $ scss , $ overrides = [ ] ) { if ( ! is_array ( $ overrides ) ) { $ overrides = ( array ) $ overrides ; } $ overrides = implode ( "\n" , $ overrides ) ; if ( $ this -> isCurrentThemeCompatible ( 2 ) ) { $ scss = $ overrides . "\n" . $ scss ; } else { $ scss .= "\n" . $ overrides ; } return $ scss ; }
Prepend or append SCSS overrides depending on which version of the theme architecture is in use .
60,281
public function injectHouseStyles ( $ css ) { $ scan = [ '/*__INSERT_PDF_HOUSE_STYLE__*/' => get_theme_root ( 'pressbooks-book' ) . '/pressbooks-book/assets/legacy/styles/_pdf-house-style.scss' , '/*__INSERT_EPUB_HOUSE_STYLE__*/' => get_theme_root ( 'pressbooks-book' ) . '/pressbooks-book/assets/legacy/styles/_epub-house-style.scss' , '/*__INSERT_MOBI_HOUSE_STYLE__*/' => get_theme_root ( 'pressbooks-book' ) . '/pressbooks-book/assets/legacy/styles/_mobi-house-style.scss' , ] ; foreach ( $ scan as $ token => $ replace_with ) { if ( is_file ( $ replace_with ) ) { $ css = str_replace ( $ token , \ Pressbooks \ Utility \ get_contents ( $ replace_with ) , $ css ) ; } } return $ css ; }
Inject house styles into CSS
60,282
public function updateWebBookStyleSheet ( $ stylesheet = null ) { if ( CustomCss :: isCustomCss ( ) ) { $ theme = wp_get_theme ( 'pressbooks-book' ) ; } else { $ theme = wp_get_theme ( $ stylesheet ) ; } $ overrides = [ '$url-base: "' . $ theme -> get_stylesheet_directory_uri ( ) . '";' ] ; if ( $ this -> isCurrentThemeCompatible ( 1 ) ) { $ scss = \ Pressbooks \ Utility \ get_contents ( realpath ( $ this -> getDir ( $ theme ) . '/style.scss' ) ) ; } elseif ( $ this -> isCurrentThemeCompatible ( 2 ) || CustomCss :: isCustomCss ( ) ) { $ scss = \ Pressbooks \ Utility \ get_contents ( realpath ( $ this -> getDir ( $ theme ) . '/assets/styles/web/style.scss' ) ) ; } else { return ; } $ custom_styles = $ this -> getWebPost ( ) ; if ( $ custom_styles && ! empty ( $ custom_styles -> post_content ) ) { $ scss .= "\n" . $ custom_styles -> post_content ; } $ css = $ this -> customize ( 'web' , $ scss , $ overrides ) ; $ css = normalize_css_urls ( $ css ) ; $ css_file = $ this -> sass -> pathToUserGeneratedCss ( ) . '/style.css' ; \ Pressbooks \ Utility \ put_contents ( $ css_file , $ css ) ; }
Update and save the supplementary webBook stylesheet which incorporates user options etc .
60,283
public function maybeUpdateStylesheets ( ) { if ( wp_doing_ajax ( ) || wp_doing_cron ( ) || is_404 ( ) ) { return false ; } $ current_buckram_version = $ this -> getBuckramVersion ( ) ; $ last_buckram_version = get_option ( 'pressbooks_buckram_version' ) ; $ buckram_updated = version_compare ( $ current_buckram_version , $ last_buckram_version ) > 0 ; $ theme = wp_get_theme ( ) ; $ current_theme_version = $ theme -> get ( 'Version' ) ; $ last_theme_version = get_option ( 'pressbooks_theme_version' ) ; $ theme_updated = version_compare ( $ current_theme_version , $ last_theme_version ) > 0 ; if ( $ buckram_updated || $ theme_updated ) { if ( ! get_transient ( 'pressbooks_updating_stylesheet' ) ) { set_transient ( 'pressbooks_updating_stylesheet' , 1 , 5 * MINUTE_IN_SECONDS ) ; ( new Modules \ ThemeOptions \ Admin ( ) ) -> clearCache ( ) ; $ this -> updateWebBookStyleSheet ( ) ; update_editor_style ( ) ; if ( $ buckram_updated ) { update_option ( 'pressbooks_buckram_version' , $ current_buckram_version ) ; } if ( $ theme_updated ) { update_option ( 'pressbooks_theme_version' , $ current_theme_version ) ; } delete_transient ( 'pressbooks_updating_stylesheet' ) ; return true ; } } return false ; }
If the current theme s version or Buckram s version has increased do SCSS stuff
60,284
public function renderDropdownForSlugs ( $ slug ) { $ select_name = 'slug' ; $ select_id = $ select_name ; $ redirect_url = get_admin_url ( get_current_blog_id ( ) , '/themes.php?page=' . $ this :: PAGE . '&slug=' ) ; $ html = '' ; $ html .= " <script type='text/javascript'> // <![CDATA[ jQuery.noConflict(); jQuery(function ($) { $('#" . $ select_id . "').change(function() { window.location = '" . $ redirect_url . "' + $(this).val(); }); }); // ]]> </script>" ; $ html .= '<select id="' . $ select_id . '" name="' . $ select_name . '">' ; foreach ( $ this -> supported as $ key => $ val ) { $ html .= '<option value="' . $ key . '"' ; if ( $ key === $ slug ) { $ html .= ' selected="selected"' ; } if ( 'Web' === $ val ) { $ val = __ ( 'Web' , 'pressbooks' ) ; } $ html .= '>' . $ val . '</option>' ; } $ html .= '</select>' ; return $ html ; }
Render dropdown and JavaScript for slugs .
60,285
public function renderRevisionsTable ( $ slug , $ post_id ) { $ args = [ 'posts_per_page' => 10 , 'post_type' => 'revision' , 'post_status' => 'inherit' , 'post_parent' => $ post_id , 'orderby' => 'date' , 'order' => 'DESC' , ] ; $ q = new \ WP_Query ( ) ; $ results = $ q -> query ( $ args ) ; $ html = '<table class="widefat fixed">' ; $ html .= '<thead><tr><th>' . __ ( 'Last 10 Revisions' , 'pressbooks' ) . ' <em>(' . $ this -> supported [ $ slug ] . ')</em> </th></tr></thead><tbody>' ; foreach ( $ results as $ post ) { $ html .= '<tr><td>' . wp_post_revision_title ( $ post ) . ' ' ; $ html .= __ ( 'by' , 'pressbooks' ) . ' ' . get_userdata ( $ post -> post_author ) -> user_login . '</td></tr>' ; } $ html .= '</tbody></table>' ; return $ html ; }
Render table for revisions .
60,286
public function formSubmit ( ) { if ( empty ( $ this -> isFormSubmission ( ) ) || empty ( current_user_can ( 'edit_others_posts' ) ) ) { return ; } if ( isset ( $ _GET [ 'custom_styles' ] ) && $ _GET [ 'custom_styles' ] === 'yes' && isset ( $ _POST [ 'your_styles' ] ) && check_admin_referer ( 'pb-custom-styles' ) ) { $ slug = isset ( $ _POST [ 'slug' ] ) ? $ _POST [ 'slug' ] : 'web' ; $ redirect_url = get_admin_url ( get_current_blog_id ( ) , '/themes.php?page=' . $ this :: PAGE . '&slug=' . $ slug ) ; if ( ! isset ( $ _POST [ 'post_id' ] , $ _POST [ 'post_id_integrity' ] ) ) { debug_error_log ( __METHOD__ . ' error: Missing post ID' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url . '&custom_styles_error=true' ) ; } if ( md5 ( NONCE_KEY . $ _POST [ 'post_id' ] ) !== $ _POST [ 'post_id_integrity' ] ) { debug_error_log ( __METHOD__ . ' error: unexpected value for post_id_integrity' ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url . '&custom_styles_error=true' ) ; } remove_filter ( 'content_save_pre' , 'wp_filter_post_kses' ) ; remove_filter ( 'content_filtered_save_pre' , 'wp_filter_post_kses' ) ; remove_all_filters ( 'content_save_pre' ) ; $ my_post = [ 'ID' => absint ( $ _POST [ 'post_id' ] ) , 'post_content' => \ Pressbooks \ Sanitize \ cleanup_css ( $ _POST [ 'your_styles' ] ) , ] ; $ response = wp_update_post ( $ my_post , true ) ; if ( is_wp_error ( $ response ) ) { debug_error_log ( __METHOD__ . ' error, wp_update_post(): ' . $ response -> get_error_message ( ) ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url . '&custom_styles_error=true' ) ; } if ( $ slug === 'web' ) { $ this -> updateWebBookStyleSheet ( ) ; } \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; } }
Save custom styles to database
60,287
public function loadShortcodes ( ) { add_action ( 'tablepress_run' , function ( ) { if ( \ Pressbooks \ Modules \ Export \ Export :: isFormSubmission ( ) ) { \ TablePress :: $ model_options = \ TablePress :: load_model ( 'options' ) ; \ TablePress :: $ model_table = \ TablePress :: load_model ( 'table' ) ; $ GLOBALS [ 'tablepress_frontend_controller' ] = \ TablePress :: load_controller ( 'frontend' ) ; } } ) ; add_filter ( 'tablepress_edit_link_below_table' , function ( $ show ) { if ( \ Pressbooks \ Modules \ Export \ Export :: isFormSubmission ( ) ) { return false ; } return $ show ; } ) ; }
Add actions and filters to TablePress to load shortcodes in the admin context .
60,288
protected function getDetailedLog ( $ id ) { $ response = wp_remote_get ( esc_url ( 'https://docraptor.com/doc_logs.json?per_page=25&user_credentials=' . DOCRAPTOR_API_KEY ) ) ; if ( is_wp_error ( $ response ) ) { return $ response -> get_error_message ( ) ; } $ logs = json_decode ( $ response [ 'body' ] ) ; if ( $ logs ) { foreach ( $ logs as $ log ) { if ( $ log -> status_id == $ id ) { return $ log -> generation_log ; } } } return '' ; }
When given a DocRaptor async status ID return the document generation log for the relevant job .
60,289
public function defaultIncludePaths ( $ type , $ theme = null ) { if ( null === $ theme ) { $ theme = wp_get_theme ( ) ; } return [ $ this -> pathToUserGeneratedSass ( ) , $ this -> pathToGlobals ( ) , $ this -> pathToFonts ( ) , Container :: get ( 'Styles' ) -> getDir ( $ theme ) . "/assets/styles/$type/" , ] ; }
Get default include paths
60,290
public function compile ( $ scss , $ includes = [ ] ) { $ scss = $ this -> prependLocalizedVars ( $ scss ) ; try { $ css = '/* Silence is golden. */' ; $ scssphp = new \ Leafo \ ScssPhp \ Compiler ; if ( ! empty ( $ scss ) || ! empty ( $ this -> vars ) ) { $ scssphp -> setVariables ( $ this -> vars ) ; $ scssphp -> setImportPaths ( $ includes ) ; $ css = $ scssphp -> compile ( $ scss ) ; $ this -> vars = [ ] ; } } catch ( \ Exception $ e ) { $ error_message = print_r ( $ scssphp -> getParsedFiles ( ) , true ) ; $ _SESSION [ 'pb_errors' ] [ ] = sprintf ( __ ( 'There was a problem with SASS. Contact your site administrator. Error: %1$s %2$s' , 'pressbooks' ) , $ e -> getMessage ( ) , "<pre>{$error_message}</pre>" ) ; $ this -> logException ( $ e ) ; if ( WP_DEBUG ) { $ this -> debug ( "/* {$e->getMessage()} */" , $ scss , 'last-thrown-exception' ) ; } return '' ; } return $ css ; }
Returns the compiled CSS from SCSS input
60,291
public function prependLocalizedVars ( $ scss ) { $ strings = $ this -> getStringsToLocalize ( ) ; $ localizations = '' ; foreach ( $ strings as $ var => $ string ) { $ localizations .= "\$$var: '$string';\n" ; } if ( WP_DEBUG ) { $ this -> debug ( '/* Silence is golden. */' , $ localizations , 'localizations' ) ; } return $ localizations . $ scss ; }
Prepend localized version of content string variables .
60,292
public function parseVariables ( $ scss ) { $ output = [ ] ; $ parser = new \ Leafo \ ScssPhp \ Parser ( null ) ; $ tree = $ parser -> parse ( $ scss ) ; foreach ( $ tree -> children as $ item ) { if ( $ item [ 0 ] === \ Leafo \ ScssPhp \ Type :: T_ASSIGN && $ item [ 1 ] [ 0 ] === \ Leafo \ ScssPhp \ Type :: T_VARIABLE && ! str_starts_with ( $ item [ 1 ] [ 1 ] , '_' ) ) { $ key = $ item [ 1 ] [ 1 ] ; switch ( $ item [ 2 ] [ 0 ] ) { case \ Leafo \ ScssPhp \ Type :: T_VARIABLE : $ val = '$' . $ item [ 2 ] [ 1 ] ; break ; case \ Leafo \ ScssPhp \ Type :: T_FUNCTION_CALL : $ fncall = $ item [ 2 ] [ 1 ] ; $ fncall_params = '' ; foreach ( $ item [ 2 ] [ 2 ] as $ param ) { $ fncall_params .= $ param [ 1 ] [ 1 ] . ', ' ; } $ fncall_params = rtrim ( $ fncall_params , ', ' ) ; $ val = "{$fncall}({$fncall_params})" ; break ; default : $ val = @ ( new \ Leafo \ ScssPhp \ Compiler ( ) ) -> compileValue ( $ item [ 2 ] ) ; } $ output [ $ key ] = $ val ; } } return $ output ; }
Parse an SCSS file into an array of variables .
60,293
public function debug ( $ css , $ scss , $ filename ) { $ debug_dir = $ this -> pathToDebugDir ( ) ; $ css_debug_file = $ debug_dir . "/{$filename}.css" ; \ Pressbooks \ Utility \ put_contents ( $ css_debug_file , $ css ) ; $ scss_debug_file = $ debug_dir . "/{$filename}.scss" ; \ Pressbooks \ Utility \ put_contents ( $ scss_debug_file , $ scss ) ; }
Write CSS to a a debug dir
60,294
private function deleteNode ( $ node ) { $ this -> deleteChildren ( $ node ) ; $ parent = $ node -> parentNode ; $ oldnode = $ parent -> removeChild ( $ node ) ; }
deletes a node and all of its children
60,295
private function deleteChildren ( $ node ) { while ( isset ( $ node -> firstChild ) ) { $ this -> deleteChildren ( $ node -> firstChild ) ; $ node -> removeChild ( $ node -> firstChild ) ; } }
recursive function to delete all children of a node
60,296
protected function pbCheck ( array $ xml ) { $ pt = 0 ; $ ch = 0 ; $ fm = 0 ; $ bm = 0 ; $ meta = 0 ; foreach ( $ xml [ 'posts' ] as $ p ) { if ( 'part' === $ p [ 'post_type' ] ) { $ pt = 1 ; } elseif ( 'chapter' === $ p [ 'post_type' ] ) { $ ch = 1 ; } elseif ( 'front-matter' === $ p [ 'post_type' ] ) { $ fm = 1 ; } elseif ( 'back-matter' === $ p [ 'post_type' ] ) { $ bm = 1 ; } elseif ( 'metadata' === $ p [ 'post_type' ] ) { $ meta = 1 ; } if ( $ pt + $ ch + $ fm + $ bm + $ meta >= 2 ) { $ this -> isPbWxr = true ; break ; } } }
Is it a WXR generated by PB?
60,297
protected function customNestedSort ( $ xml ) { $ array = [ ] ; usort ( $ xml , function ( $ a , $ b ) { return ( $ a [ 'menu_order' ] - $ b [ 'menu_order' ] ) ; } ) ; foreach ( $ xml as $ p ) { if ( 'metadata' === $ p [ 'post_type' ] ) { $ array [ ] = $ p ; break ; } } foreach ( $ xml as $ p ) { if ( 'front-matter' === $ p [ 'post_type' ] ) { $ array [ ] = $ p ; } } foreach ( $ xml as $ p ) { if ( 'part' === $ p [ 'post_type' ] ) { $ array [ ] = $ p ; foreach ( $ xml as $ psub ) { if ( 'chapter' === $ psub [ 'post_type' ] && $ psub [ 'post_parent' ] === $ p [ 'post_id' ] ) { $ array [ ] = $ psub ; } } } } foreach ( $ xml as $ p ) { if ( 'back-matter' === $ p [ 'post_type' ] ) { $ array [ ] = $ p ; } } foreach ( $ xml as $ p ) { if ( 'glossary' === $ p [ 'post_type' ] ) { $ array [ ] = $ p ; } } $ custom_post_types = apply_filters ( 'pb_import_custom_post_types' , [ ] ) ; foreach ( $ xml as $ p ) { if ( in_array ( $ p [ 'post_type' ] , $ custom_post_types , true ) ) { $ array [ ] = $ p ; } } return $ array ; }
Custom sort for the xml posts to put them in correct nested order
60,298
protected function bookInfoPid ( ) { $ post = ( new Metadata ( ) ) -> getMetaPost ( ) ; if ( empty ( $ post -> ID ) ) { $ new_post = [ 'post_title' => __ ( 'Book Info' , 'pressbooks' ) , 'post_type' => 'metadata' , 'post_status' => 'publish' , ] ; $ pid = wp_insert_post ( add_magic_quotes ( $ new_post ) ) ; } else { $ pid = $ post -> ID ; } return $ pid ; }
Get existing Meta Post if none exists create one
60,299
protected function insertNewPost ( $ post_type , $ p , $ html , $ chapter_parent , $ post_status ) { $ new_post = [ 'post_title' => wp_strip_all_tags ( $ p [ 'post_title' ] ) , 'post_name' => $ p [ 'post_name' ] , 'post_type' => $ post_type , 'post_status' => ( 'part' === $ post_type ) ? 'publish' : $ post_status , 'post_content' => $ html , ] ; if ( 'chapter' === $ post_type ) { $ new_post [ 'post_parent' ] = $ chapter_parent ; } $ pid = wp_insert_post ( add_magic_quotes ( $ new_post ) ) ; return $ pid ; }
Insert a new post