Dataset Viewer
Auto-converted to Parquet Duplicate
idx
int64
0
60.3k
question
stringlengths
99
4.85k
target
stringlengths
5
718
0
public function getLockData ( ) { $ json = \ Pressbooks \ Utility \ get_contents ( $ this -> getLockDir ( false ) . '/lock.json' ) ; $ output = json_decode ( $ json , true ) ; return $ output ; }
Load data from the lockfile .
1
public function restrictThemeManagement ( ) { $ locked = $ this -> isLocked ( ) ; if ( $ locked ) { $ data = $ this -> getLockData ( ) ; $ check_against_url = wp_parse_url ( ( is_ssl ( ) ? 'http://' : 'https://' ) . $ _SERVER [ 'HTTP_HOST' ] . $ _SERVER [ 'REQUEST_URI' ] , PHP_URL_PATH ) ; $ redirect_url = get_site_url ( get_current_blog_id ( ) , '/wp-admin/' ) ; $ restricted = [ 'themes' , ] ; $ expr = '~/wp-admin/(' . implode ( '|' , $ restricted ) . ')\.php$~' ; if ( preg_match ( $ expr , $ check_against_url ) ) { $ _SESSION [ 'pb_errors' ] [ ] = sprintf ( __ ( 'Your book&rsquo;s theme, %1$s, was locked in its current state as of %2$s at %3$s. To select a new theme or change your theme options, please %4$s.' , 'pressbooks' ) , $ data [ 'name' ] , strftime ( '%x' , $ data [ 'timestamp' ] ) , strftime ( '%X' , $ data [ 'timestamp' ] ) , sprintf ( '<a href="%s">%s</a>' , admin_url ( 'options-general.php?page=pressbooks_export_options' ) , 'unlock your theme' ) ) ; \ Pressbooks \ Redirect \ location ( $ redirect_url ) ; } } }
Restrict access to Themes and Theme Options .
2
public function getTabs ( ) { $ tabs = [ 'global' => '\Pressbooks\Modules\ThemeOptions\GlobalOptions' , 'web' => '\Pressbooks\Modules\ThemeOptions\WebOptions' , 'pdf' => '\Pressbooks\Modules\ThemeOptions\PDFOptions' , 'ebook' => '\Pressbooks\Modules\ThemeOptions\EbookOptions' , ] ; if ( false === get_site_transient ( 'pb_pdf_compatible' ) && false === \ Pressbooks \ Modules \ Export \ Prince \ Filters :: hasDependencies ( ) ) { unset ( $ tabs [ 'pdf' ] ) ; } else { set_site_transient ( 'pb_pdf_compatible' , true ) ; } if ( false === get_site_transient ( 'pb_epub_compatible' ) && false === \ Pressbooks \ Modules \ Export \ Epub \ Epub201 :: hasDependencies ( ) ) { unset ( $ tabs [ 'ebook' ] ) ; } else { set_site_transient ( 'pb_epub_compatible' , true ) ; } return apply_filters ( 'pb_theme_options_tabs' , $ tabs ) ; }
Returns a filtered array of tabs that we should be loading .
3
public function render ( ) { ?> <div class="wrap"> <h1> <?php echo wp_get_theme ( ) ; ?> <?php _e ( 'Theme Options' , 'pressbooks' ) ; ?> </h1> <?php settings_errors ( ) ; ?> <?php $ active_tab = isset ( $ _GET [ 'tab' ] ) ? $ _GET [ 'tab' ] : 'global' ; ?> <h2 class="nav-tab-wrapper"> <?php foreach ( $ this -> getTabs ( ) as $ slug => $ subclass ) { ?> <a href=" <?php echo admin_url ( '/themes.php' ) ; ?> ?page=pressbooks_theme_options&tab= <?php echo $ slug ; ?> " class="nav-tab <?php echo $ active_tab === $ slug ? 'nav-tab-active' : '' ; ?> "> <?php echo $ subclass :: getTitle ( ) ; ?> </a> <?php } ?> </h2> <form method="post" action="options.php"> <?php do_action ( 'pb_before_themeoptions_settings_fields' ) ; settings_fields ( 'pressbooks_theme_options_' . $ active_tab ) ; do_settings_sections ( 'pressbooks_theme_options_' . $ active_tab ) ; submit_button ( ) ; ?> </form> </div> <?php }
Render the theme options page and load the appropriate tab .
4
public function afterSwitchTheme ( ) { $ this -> clearCache ( ) ; foreach ( $ this -> getTabs ( ) as $ slug => $ subclass ) { $ current_options = get_option ( "pressbooks_theme_options_{$slug}" , [ ] ) ; if ( ! empty ( $ current_options ) ) { update_option ( "pressbooks_theme_options_{$slug}" , $ subclass :: filterDefaults ( $ current_options ) ) ; } } }
Override saved options with filtered defaults when switching theme
5
protected function registerRouteDependencies ( ) { $ this -> frontMatterMetadata -> register_routes ( ) ; $ this -> backMatterMetadata -> register_routes ( ) ; $ this -> chapterMetadata -> register_routes ( ) ; }
Define route dependencies . Toc content is built by querying section metadata but those API routes may not exist at the root level .
6
function init ( ) { $ _option = $ this -> getSlug ( ) ; $ _page = $ _option ; $ _section = $ this -> getSlug ( ) . '_section' ; add_settings_section ( $ _section , '' , [ $ this , 'display' ] , $ _page ) ; add_settings_field ( 'amazon' , __ ( 'Amazon URL' , 'pressbooks' ) , [ $ this , 'renderAmazonField' ] , $ _page , $ _section ) ; add_settings_field ( 'oreilly' , __ ( 'O\'Reilly URL' , 'pressbooks' ) , [ $ this , 'renderOReillyField' ] , $ _page , $ _section ) ; add_settings_field ( 'barnesandnoble' , __ ( 'Barnes and Noble URL' , 'pressbooks' ) , [ $ this , 'renderBarnesAndNobleField' ] , $ _page , $ _section ) ; add_settings_field ( 'kobo' , __ ( 'Kobo URL' , 'pressbooks' ) , [ $ this , 'renderKoboField' ] , $ _page , $ _section ) ; add_settings_field ( 'ibooks' , __ ( 'iBooks URL' , 'pressbooks' ) , [ $ this , 'renderiBooksField' ] , $ _page , $ _section ) ; add_settings_field ( 'otherservice' , __ ( 'Other Service URL' , 'pressbooks' ) , [ $ this , 'renderOtherServiceField' ] , $ _page , $ _section ) ; register_setting ( $ _page , $ _option , [ $ this , 'sanitize' ] ) ; }
Configure the publish options page using the settings API .
7
function display ( ) { ob_start ( ) ; ?> <p> <?php _e ( 'Once your book is finished, you can download the files and submit them to ebookstores and print-on-demand providers.' , 'pressbooks' ) ; ?> </p> <div class="postbox"> <div class="inside"> <h3> <?php _e ( 'Ebook Stores' , 'pressbooks' ) ; ?> </h3> <p> <?php printf ( __ ( 'Once you have downloaded your files, you can either submit them to ebookstores yourself, or use a third-party distributor. Recommended self-serve ebookstores are <a href="%1$1s">Kindle</a>, <a href="%2$2s">Kobo</a>, and <a href="%3$3s">Nook</a>. Other ebook stores include Apple iBooks and Google.' , 'pressbooks' ) , 'https://kdp.amazon.com' , 'https://www.kobo.com/writinglife' , 'https://www.nookpress.com' ) ; ?> </p> <p> <?php printf ( __ ( 'If you do not wish to submit your ebooks yourself, we recommend using a third-party distribution service such as <a href="%1s">IngramSpark</a>, which can also make your books available online in print.' , 'pressbooks' ) , 'https://ingramspark.com' ) ; ?> </p> <h3> <?php _e ( 'Print-on-Demand' , 'pressbooks' ) ; ?> </h3> <p> <?php printf ( __ ( 'If you wish to sell your printed books online, we recommend going through <a href="%1$1s">IngramSpark</a> or Amazon\'s <a href="%2$2s">CreateSpace</a>.' , 'pressbooks' ) , 'https://ingramspark.com' , 'https://www.createspace.com' ) ; ?> </p> </div> </div> <h3> <?php _e ( 'Adding BUY Links to Your Pressbooks Web Book' , 'pressbooks' ) ; ?> </h3> <p> <?php _e ( 'If you would like to add <strong>BUY</strong> links to your Pressbooks web book, add the links to your book at the different retailers below:' , 'pressbooks' ) ; ?> </p> <?php $ output = ob_get_contents ( ) ; ob_end_clean ( ) ; echo apply_filters ( 'pb_publish_page' , apply_filters ( 'pressbooks_publish_page' , $ output ) ) ; }
Display the publish options page description .
8
function renderAmazonField ( ) { $ this -> renderField ( [ 'id' => 'amazon' , 'name' => $ this -> getSlug ( ) , 'option' => 'amazon' , 'value' => ( isset ( $ this -> options [ 'amazon' ] ) ) ? $ this -> options [ 'amazon' ] : '' , 'type' => 'url' , 'class' => 'regular-text code' , ] ) ; }
Render the amazon field .
9
function renderOReillyField ( ) { $ this -> renderField ( [ 'id' => 'oreilly' , 'name' => $ this -> getSlug ( ) , 'option' => 'oreilly' , 'value' => ( isset ( $ this -> options [ 'oreilly' ] ) ) ? $ this -> options [ 'oreilly' ] : '' , 'type' => 'url' , 'class' => 'regular-text code' , ] ) ; }
Render the oreilly field .
10
function init ( ) { $ _option = $ this -> getSlug ( ) ; $ _page = $ _option ; $ _section = $ this -> getSlug ( ) . '_section' ; add_settings_section ( $ _section , '' , [ $ this , 'display' ] , $ _page ) ; add_settings_field ( 'email_validation_logs' , __ ( 'Email Validation Logs' , 'pressbooks' ) , [ $ this , 'renderEmailValidationLogsField' ] , $ _page , $ _section , [ '0' => __ ( 'No. Ignore validation errors.' , 'pressbooks' ) , '1' => __ ( 'Yes.' , 'pressbooks' ) . ' ' . __ ( 'Email me validation error logs on export.' , 'pressbooks' ) , ] ) ; if ( ! \ Pressbooks \ CustomCss :: isCustomCss ( ) ) { add_settings_field ( 'theme_lock' , __ ( 'Lock Theme' , 'pressbooks' ) , [ $ this , 'renderThemeLockField' ] , $ _page , $ _section , [ __ ( 'Lock your theme at its current version.' , 'pressbooks' ) , ] ) ; } register_setting ( $ _page , $ _option , [ $ this , 'sanitize' ] ) ; }
Configure the export options page using the settings API .
11
function renderEmailValidationLogsField ( $ args ) { $ this -> renderRadioButtons ( [ 'id' => 'email_validation_logs' , 'name' => $ this -> getSlug ( ) , 'option' => 'email_validation_logs' , 'value' => ( isset ( $ this -> options [ 'email_validation_logs' ] ) ) ? $ this -> options [ 'email_validation_logs' ] : '' , 'choices' => $ args , ] ) ; }
Render the email_validation_logs radio buttons .
12
function renderThemeLockField ( $ args ) { $ this -> renderCheckbox ( [ 'id' => 'theme_lock' , 'name' => $ this -> getSlug ( ) , 'option' => 'theme_lock' , 'value' => ( isset ( $ this -> options [ 'theme_lock' ] ) ) ? $ this -> options [ 'theme_lock' ] : '' , 'label' => $ args [ 0 ] , 'description' => __ ( 'This will prevent any changes to your book&rsquo;s appearance and page count when themes are updated.' , 'pressbooks' ) , ] ) ; }
Render the lock_theme checkbox .
13
static function getBookContents ( ) { global $ blog_id ; $ cache_id = "book-cnt-$blog_id" ; if ( static :: useCache ( ) ) { $ book_contents = wp_cache_get ( $ cache_id , 'pb' ) ; if ( $ book_contents ) { return $ book_contents ; } } $ book_contents = static :: getBookStructure ( ) ; foreach ( $ book_contents as $ type => $ struct ) { if ( preg_match ( '/^__/' , $ type ) ) { continue ; } if ( 'part' === $ type ) { foreach ( $ struct as $ i => $ part ) { $ book_contents [ $ type ] [ $ i ] = $ part + get_post ( $ part [ 'ID' ] , ARRAY_A ) ; foreach ( $ part [ 'chapters' ] as $ j => $ chapter ) { $ book_contents [ $ type ] [ $ i ] [ 'chapters' ] [ $ j ] = $ chapter + get_post ( $ chapter [ 'ID' ] , ARRAY_A ) ; } } } else { foreach ( $ struct as $ i => $ val ) { $ book_contents [ $ type ] [ $ i ] = $ val + get_post ( $ val [ 'ID' ] , ARRAY_A ) ; } } } if ( static :: useCache ( ) ) { wp_cache_set ( $ cache_id , $ book_contents , 'pb' , DAY_IN_SECONDS ) ; } return $ book_contents ; }
Returns an array representing the entire structure of a book in correct order with a maximum amount of fields . Data is raw and must be post - processed .
14
static function getSubsections ( $ id ) { $ parent = get_post ( $ id ) ; if ( empty ( $ parent ) ) { return false ; } $ has_shortcode = has_shortcode ( $ parent -> post_content , 'heading' ) ; if ( stripos ( $ parent -> post_content , '<h1' ) === false && $ has_shortcode === false ) { return false ; } $ type = $ parent -> post_type ; $ content = ( $ has_shortcode ) ? apply_filters ( 'the_content' , $ parent -> post_content ) : $ parent -> post_content ; $ content = strip_tags ( $ content , '<h1>' ) ; $ output = [ ] ; $ s = 1 ; $ doc = new HtmlParser ( true ) ; $ dom = $ doc -> loadHTML ( $ content ) ; $ sections = $ dom -> getElementsByTagName ( 'h1' ) ; foreach ( $ sections as $ section ) { $ output [ $ type . '-' . $ id . '-section-' . $ s ] = wptexturize ( $ section -> textContent ) ; $ s ++ ; } if ( empty ( $ output ) ) { return false ; } return $ output ; }
Returns an array of subsections in front matter back matter or chapters .
15
static function getAllSubsections ( $ book_structure ) { if ( Export :: shouldParseSubsections ( ) ) { $ book_subsections_transient = \ Pressbooks \ Book :: SUBSECTIONS_TRANSIENT ; $ subsection_processing_transient = \ Pressbooks \ Book :: SUBSECTION_PROCESSING_TRANSIENT ; $ book_subsections = get_transient ( $ book_subsections_transient ) ; if ( ! $ book_subsections ) { $ book_subsections = [ ] ; if ( ! get_transient ( $ subsection_processing_transient ) ) { set_transient ( $ subsection_processing_transient , 1 , 5 * MINUTE_IN_SECONDS ) ; foreach ( $ book_structure [ 'front-matter' ] as $ section ) { $ subsections = \ Pressbooks \ Book :: getSubsections ( $ section [ 'ID' ] ) ; if ( $ subsections ) { $ book_subsections [ 'front-matter' ] [ $ section [ 'ID' ] ] = $ subsections ; } } foreach ( $ book_structure [ 'part' ] as $ key => $ part ) { if ( ! empty ( $ part [ 'chapters' ] ) ) { foreach ( $ part [ 'chapters' ] as $ section ) { $ subsections = \ Pressbooks \ Book :: getSubsections ( $ section [ 'ID' ] ) ; if ( $ subsections ) { $ book_subsections [ 'chapters' ] [ $ section [ 'ID' ] ] = $ subsections ; } } } } foreach ( $ book_structure [ 'back-matter' ] as $ section ) { $ subsections = \ Pressbooks \ Book :: getSubsections ( $ section [ 'ID' ] ) ; if ( $ subsections ) { $ book_subsections [ 'back-matter' ] [ $ section [ 'ID' ] ] = $ subsections ; } } delete_transient ( $ subsection_processing_transient ) ; } } set_transient ( $ book_subsections_transient , $ book_subsections ) ; return $ book_subsections ; } return [ ] ; }
Returns an array of front matter chapters and back matter which contain subsections .
16
static function tagSubsections ( $ content , $ id ) { $ parent = get_post ( $ id ) ; if ( empty ( $ parent ) ) { return false ; } if ( stripos ( $ content , '<h1' ) === false ) { return false ; } $ type = $ parent -> post_type ; $ s = 1 ; $ doc = new HtmlParser ( ) ; $ dom = $ doc -> loadHTML ( $ content ) ; $ sections = $ dom -> getElementsByTagName ( 'h1' ) ; foreach ( $ sections as $ section ) { $ old_id = $ section -> getAttribute ( 'id' ) ; $ old_class = $ section -> getAttribute ( 'class' ) ; $ new_id = "{$type}-{$id}-section-" . $ s ++ ; $ new_class = trim ( "section-header {$old_class} {$old_id}" ) ; $ section -> setAttribute ( 'id' , $ new_id ) ; $ section -> setAttribute ( 'class' , $ new_class ) ; } return $ doc -> saveHTML ( $ dom ) ; }
Returns chapter front or back matter content with section ID and classes added .
17
static function get ( $ what = 'next' , $ return_post_id = false , $ admin_mode = false ) { if ( 'first' === $ what ) { return static :: getFirst ( $ return_post_id , $ admin_mode ) ; } global $ blog_id ; global $ post ; $ current_post_id = $ post -> ID ; $ book_structure = static :: getBookStructure ( ) ; $ order = $ book_structure [ '__order' ] ; $ pos = array_keys ( $ order ) ; $ what = ( 'next' === $ what ? 'next' : 'prev' ) ; reset ( $ pos ) ; while ( $ find_me = current ( $ pos ) ) { if ( ( int ) $ find_me === ( int ) $ current_post_id ) { break ; } else { next ( $ pos ) ; } } $ what ( $ pos ) ; while ( $ post_id = current ( $ pos ) ) { if ( $ admin_mode ) { if ( current_user_can ( 'edit_post' , $ post_id ) ) { break ; } else { $ what ( $ pos ) ; } } else { if ( in_array ( $ order [ $ post_id ] [ 'post_status' ] , [ 'publish' , 'web-only' ] , true ) ) { break ; } elseif ( current_user_can_for_blog ( $ blog_id , 'read_private_posts' ) ) { break ; } elseif ( get_option ( 'permissive_private_content' ) && current_user_can_for_blog ( $ blog_id , 'read' ) ) { break ; } else { $ what ( $ pos ) ; } } } if ( $ return_post_id ) { return ( int ) $ post_id ; } else { return ( empty ( $ post_id ) ) ? '/' : get_permalink ( $ post_id ) ; } }
Fetch next previous or first post
18
static function getFirst ( $ return_post_id = false , $ admin_mode = false ) { global $ blog_id ; $ book_structure = static :: getBookStructure ( ) ; $ order = $ book_structure [ '__order' ] ; $ pos = array_keys ( $ order ) ; reset ( $ pos ) ; while ( $ first_id = current ( $ pos ) ) { if ( $ admin_mode ) { if ( current_user_can ( 'edit_post' , $ first_id ) ) { break ; } else { next ( $ pos ) ; } } else { if ( in_array ( $ order [ $ first_id ] [ 'post_status' ] , [ 'publish' , 'web-only' ] , true ) ) { break ; } elseif ( current_user_can_for_blog ( $ blog_id , 'read_private_posts' ) ) { break ; } elseif ( get_option ( 'permissive_private_content' ) && current_user_can_for_blog ( $ blog_id , 'read' ) ) { break ; } else { next ( $ pos ) ; } } } if ( $ return_post_id ) { return ( int ) $ first_id ; } else { return ( empty ( $ first_id ) ) ? '/' : get_permalink ( $ first_id ) ; } }
Select the very first post in a book . May be a chapter or a front matter post
19
static protected function getPostsIdsToExport ( ) { $ post_ids_to_export = [ ] ; global $ wpdb ; $ results = $ wpdb -> get_results ( $ wpdb -> prepare ( "SELECT ID FROM {$wpdb->posts} WHERE post_status IN (%s, %s) AND post_type IN (%s, %s, %s, %s, %s)" , [ 'private' , 'publish' , 'front-matter' , 'part' , 'chapter' , 'back-matter' , 'glossary' ] ) , ARRAY_A ) ; foreach ( $ results as $ val ) { $ post_ids_to_export [ $ val [ 'ID' ] ] = 'on' ; } return $ post_ids_to_export ; }
Fetch all pb_export meta values for this book
20
function shortcodeHandler ( $ atts , $ content = '' ) { global $ id ; $ a = shortcode_atts ( [ 'numbered' => 'yes' , 'symbol' => '*' , 'suptext' => ' ' , ] , $ atts ) ; if ( ! $ content ) { return '' ; } if ( ! isset ( $ this -> footnotes [ $ id ] ) ) { $ this -> footnotes [ $ id ] = [ ] ; if ( 'no' === $ a [ 'numbered' ] ) { $ this -> numbered [ $ id ] = false ; } else { $ this -> numbered [ $ id ] = true ; } } $ this -> footnotes [ $ id ] [ ] = $ content ; $ footnotes = $ this -> footnotes [ $ id ] ; $ num = count ( $ footnotes ) ; $ numlabel = "$id-$num" ; $ retval = '<a class="footnote" title="' . \ Pressbooks \ Sanitize \ sanitize_xml_attribute ( wp_strip_all_tags ( $ content ) ) . '" id="return-footnote-' . $ numlabel . '" href="#footnote-' . $ numlabel . '"><sup class="footnote">[' ; if ( $ this -> numbered [ $ id ] ) { $ retval .= $ num ; } else { $ retval .= $ a [ 'symbol' ] ; } if ( trim ( $ a [ 'suptext' ] ) ) { if ( $ this -> numbered [ $ id ] ) { $ retval .= '. ' ; } $ retval .= $ a [ 'suptext' ] ; } $ retval .= ']</sup></a>' ; return $ retval ; }
Pre - process footnote shortcode
21
function footnoteContent ( $ content ) { global $ id ; if ( ! empty ( $ this -> footnotes ) && isset ( $ this -> footnotes [ $ id ] ) ) { $ footnotes = $ this -> footnotes [ $ id ] ; } else { return $ content ; } if ( $ this -> numbered [ $ id ] ) { $ content .= '<hr class="before-footnotes" /><div class="footnotes"><ol>' ; } else { $ content .= '<hr class="before-footnotes" /><div class="footnotes"><ul>' ; } foreach ( $ footnotes as $ num => $ footnote ) { $ num ++ ; $ numlabel = "$id-$num" ; $ content .= '<li id="footnote-' . $ numlabel . '">' . make_clickable ( $ footnote ) . ' <a href="#return-footnote-' . $ numlabel . '" class="return-footnote">&crarr;</a></li>' ; } if ( $ this -> numbered [ $ id ] ) { $ content .= '</ol></div>' ; } else { $ content .= '</ul></div>' ; } unset ( $ this -> footnotes [ $ id ] ) ; return $ content ; }
Post - process footnote shortcode
22
public static function createLambda ( $ closure , string $ closureArgs , $ default = null ) { if ( $ closure === null ) { if ( $ default === null ) throw new \ InvalidArgumentException ( self :: ERROR_CLOSURE_NULL ) ; return $ default ; } if ( $ closure instanceof \ Closure ) return $ closure ; if ( is_string ( $ closure ) && ( $ function = self :: createLambdaFromString ( $ closure , $ closureArgs ) ) ) return $ function ; if ( is_callable ( $ closure ) ) return $ closure ; throw new \ InvalidArgumentException ( self :: ERROR_CLOSURE_NOT_CALLABLE ) ; }
Convert string lambda to callable function . If callable is passed return as is .
23
public static function createComparer ( $ closure , $ sortOrder , & $ isReversed ) { if ( $ closure === null ) { $ isReversed = false ; return $ sortOrder === SORT_DESC ? Functions :: $ compareStrictReversed : Functions :: $ compareStrict ; } elseif ( is_int ( $ closure ) ) { switch ( $ closure ) { case SORT_REGULAR : return Functions :: $ compareStrict ; case SORT_NUMERIC : $ isReversed = false ; return $ sortOrder === SORT_DESC ? Functions :: $ compareIntReversed : Functions :: $ compareInt ; case SORT_STRING : return 'strcmp' ; case SORT_STRING | SORT_FLAG_CASE : return 'strcasecmp' ; case SORT_LOCALE_STRING : return 'strcoll' ; case SORT_NATURAL : return 'strnatcmp' ; case SORT_NATURAL | SORT_FLAG_CASE : return 'strnatcasecmp' ; default : throw new \ InvalidArgumentException ( "Unexpected sort flag: {$closure}." ) ; } } return self :: createLambda ( $ closure , 'a,b' ) ; }
Convert string lambda or SORT_ flags to callable function . Sets isReversed to false if descending is reversed .
24
public static function lambdaToSortFlagsAndOrder ( $ closure , & $ sortOrder ) { if ( $ sortOrder !== SORT_ASC && $ sortOrder !== SORT_DESC ) $ sortOrder = $ sortOrder ? SORT_DESC : SORT_ASC ; if ( is_int ( $ closure ) ) return $ closure ; elseif ( ( $ closure === null || is_string ( $ closure ) ) && isset ( self :: $ compareFunctionToSortFlags [ $ closure ] ) ) return self :: $ compareFunctionToSortFlags [ $ closure ] ; else return null ; }
Convert string lambda to SORT_ flags . Convert sortOrder from bool to SORT_ order .
25
private static function createLambdaFromString ( string $ closure , string $ closureArgs ) { $ posDollar = strpos ( $ closure , '$' ) ; if ( $ posDollar !== false ) { if ( isset ( self :: $ lambdaCache [ $ closure ] [ $ closureArgs ] ) ) return self :: $ lambdaCache [ $ closure ] [ $ closureArgs ] ; $ posArrow = strpos ( $ closure , '==>' , $ posDollar ) ; if ( $ posArrow !== false ) { $ args = trim ( substr ( $ closure , 0 , $ posArrow ) , "() \r\n\t" ) ; $ code = substr ( $ closure , $ posArrow + 3 ) ; } else { $ args = '$' . str_replace ( ',' , '=null,$' , $ closureArgs ) . '=null' ; $ code = $ closure ; } $ code = trim ( $ code , " \r\n\t" ) ; if ( strlen ( $ code ) > 0 && $ code [ 0 ] != '{' ) $ code = "return {$code};" ; $ fun = @ create_function ( $ args , $ code ) ; if ( ! $ fun ) throw new \ InvalidArgumentException ( self :: ERROR_CANNOT_PARSE_LAMBDA ) ; self :: $ lambdaCache [ $ closure ] [ $ closureArgs ] = $ fun ; return $ fun ; } return null ; }
Convert string lambda to callable function .
26
public function getColumnClassName ( $ options ) { $ model = $ this -> config -> getDataModel ( ) ; $ namespace = __NAMESPACE__ . '\\' ; if ( $ method = $ this -> validator -> arrayGet ( $ options , 'relationship' ) ) { if ( method_exists ( $ model , $ method ) ) { $ relationship = $ model -> { $ method } ( ) ; if ( is_a ( $ relationship , self :: BELONGS_TO_MANY ) ) { return $ namespace . 'Relationships\BelongsToMany' ; } else if ( is_a ( $ relationship , self :: HAS_ONE ) || is_a ( $ relationship , self :: HAS_MANY ) ) { return $ namespace . 'Relationships\HasOneOrMany' ; } } return $ namespace . 'Relationships\BelongsTo' ; } return $ namespace . 'Column' ; }
Gets the column class name depending on whether or not it s a relationship and what type of relationship it is
27
public function getColumnOptions ( ) { if ( ! sizeof ( $ this -> columnOptions ) ) { foreach ( $ this -> getColumns ( ) as $ column ) { $ this -> columnOptions [ ] = $ column -> getOptions ( ) ; } } return $ this -> columnOptions ; }
Gets the column objects as an integer - indexed array
28
public function getRelatedColumns ( ) { if ( ! sizeof ( $ this -> relatedColumns ) ) { foreach ( $ this -> getColumns ( ) as $ column ) { if ( $ column -> getOption ( 'is_related' ) ) { $ this -> relatedColumns [ $ column -> getOption ( 'column_name' ) ] = $ column -> getOption ( 'column_name' ) ; } } } return $ this -> relatedColumns ; }
Gets the columns that are relationship columns
29
public function getComputedColumns ( ) { if ( ! sizeof ( $ this -> computedColumns ) ) { foreach ( $ this -> getColumns ( ) as $ column ) { if ( ! $ column -> getOption ( 'is_related' ) && $ column -> getOption ( 'is_computed' ) ) { $ this -> computedColumns [ $ column -> getOption ( 'column_name' ) ] = $ column -> getOption ( 'column_name' ) ; } } } return $ this -> computedColumns ; }
Gets the columns that are computed
30
public static function open ( $ input , $ rules , $ path , $ random = true ) { return new Multup ( $ input , $ rules , $ path , $ random ) ; }
Static call Laravel style . Returns a new Multup object allowing for chainable calls
31
public function customModelAction ( $ modelName ) { $ config = app ( 'itemconfig' ) ; $ actionFactory = app ( 'admin_action_factory' ) ; $ actionName = $ this -> request -> input ( 'action_name' , false ) ; $ dataTable = app ( 'admin_datatable' ) ; $ page = $ this -> request -> input ( 'page' , 1 ) ; $ sortOptions = $ this -> request -> input ( 'sortOptions' , array ( ) ) ; $ filters = $ this -> request -> input ( 'filters' , array ( ) ) ; $ prepared = $ dataTable -> prepareQuery ( app ( 'db' ) , $ page , $ sortOptions , $ filters ) ; $ action = $ actionFactory -> getByName ( $ actionName , true ) ; $ result = $ action -> perform ( $ prepared [ 'query' ] ) ; if ( is_string ( $ result ) ) { return response ( ) -> json ( array ( 'success' => false , 'error' => $ result ) ) ; } else if ( ! $ result ) { $ messages = $ action -> getOption ( 'messages' ) ; return response ( ) -> json ( array ( 'success' => false , 'error' => $ messages [ 'error' ] ) ) ; } else { $ response = array ( 'success' => true ) ; if ( is_a ( $ result , 'Symfony\Component\HttpFoundation\BinaryFileResponse' ) ) { $ file = $ result -> getFile ( ) -> getRealPath ( ) ; $ headers = $ result -> headers -> all ( ) ; $ this -> session -> put ( 'administrator_download_response' , array ( 'file' => $ file , 'headers' => $ headers ) ) ; $ response [ 'download' ] = route ( 'admin_file_download' ) ; } else if ( is_a ( $ result , '\Illuminate\Http\RedirectResponse' ) ) { $ response [ 'redirect' ] = $ result -> getTargetUrl ( ) ; } return response ( ) -> json ( $ response ) ; } }
POST method for handling custom model actions
32
public function displayFile ( ) { $ path = $ this -> request -> input ( 'path' ) ; $ data = File :: get ( $ path ) ; $ file = new SFile ( $ path ) ; $ headers = array ( 'Content-Type' => $ file -> getMimeType ( ) , 'Content-Length' => $ file -> getSize ( ) , 'Content-Disposition' => 'attachment; filename="' . $ file -> getFilename ( ) . '"' ) ; return response ( ) -> make ( $ data , 200 , $ headers ) ; }
The GET method that displays a file field s file
33
protected function resolveDynamicFormRequestErrors ( Request $ request ) { try { $ config = app ( 'itemconfig' ) ; $ fieldFactory = app ( 'admin_field_factory' ) ; } catch ( \ ReflectionException $ e ) { return null ; } if ( array_key_exists ( 'form_request' , $ config -> getOptions ( ) ) ) { try { $ model = $ config -> getFilledDataModel ( $ request , $ fieldFactory -> getEditFields ( ) , $ request -> id ) ; $ request -> merge ( $ model -> toArray ( ) ) ; $ formRequestClass = $ config -> getOption ( 'form_request' ) ; app ( $ formRequestClass ) ; } catch ( HttpResponseException $ e ) { $ errorMessages = $ e -> getResponse ( ) -> getContent ( ) ; $ errorsArray = json_decode ( $ errorMessages ) ; if ( ! $ errorsArray && is_string ( $ errorMessages ) ) { return $ errorMessages ; } if ( $ errorsArray ) { return implode ( "." , array_dot ( $ errorsArray ) ) ; } } } return null ; }
POST method to capture any form request errors
34
public function getGlobalActions ( $ override = false ) { if ( ! sizeof ( $ this -> globalActions ) || $ override ) { $ this -> globalActions = array ( ) ; foreach ( $ this -> config -> getOption ( 'global_actions' ) as $ name => $ options ) { $ this -> globalActions [ ] = $ this -> make ( $ name , $ options ) ; } } return $ this -> globalActions ; }
Gets all global actions
35
public function getGlobalActionsOptions ( $ override = false ) { if ( ! sizeof ( $ this -> globalActionsOptions ) || $ override ) { $ this -> globalActionsOptions = array ( ) ; foreach ( $ this -> getGlobalActions ( $ override ) as $ name => $ action ) { $ this -> globalActionsOptions [ ] = $ action -> getOptions ( ) ; } } return $ this -> globalActionsOptions ; }
Gets all actions as arrays of options
36
public function getActionPermissions ( $ override = false ) { if ( ! sizeof ( $ this -> actionPermissions ) || $ override ) { $ this -> actionPermissions = array ( ) ; $ model = $ this -> config -> getDataModel ( ) ; $ options = $ this -> config -> getOption ( 'action_permissions' ) ; $ defaults = $ this -> actionPermissionsDefaults ; $ permissions = array_merge ( $ defaults , $ options ) ; foreach ( $ permissions as $ action => $ callback ) { if ( is_callable ( $ callback ) ) { $ this -> actionPermissions [ $ action ] = ( bool ) $ callback ( $ model ) ; } else { $ this -> actionPermissions [ $ action ] = ( bool ) $ callback ; } } } return $ this -> actionPermissions ; }
Gets all action permissions
37
public function constrainQuery ( EloquentBuilder & $ query , $ relatedModel , $ constraint ) { if ( ! $ this -> validator -> isJoined ( $ query , $ this -> getOption ( 'table' ) ) ) { $ query -> join ( $ this -> getOption ( 'table' ) , $ relatedModel -> getTable ( ) . '.' . $ relatedModel -> getKeyName ( ) , '=' , $ this -> getOption ( 'column2' ) ) ; } $ query -> where ( $ this -> getOption ( 'table' ) . '.' . $ this -> getOption ( 'column' ) , '=' , $ constraint ) ; }
Constrains a query by a given set of constraints
38
public function getDateString ( DateTime $ time ) { if ( $ this -> getOption ( 'type' ) === 'date' ) { return $ time -> format ( 'Y-m-d' ) ; } else if ( $ this -> getOption ( 'type' ) === 'datetime' ) { return $ time -> format ( 'Y-m-d H:i:s' ) ; } else { return $ time -> format ( 'H:i:s' ) ; } }
Get a date format from a time depending on the type of time field this is
39
public function getDataModel ( ) { if ( ! $ this -> model ) { $ name = $ this -> getOption ( 'model' ) ; $ this -> model = new $ name ; } return $ this -> model ; }
Fetches the data model for a config
40
protected function getRelationshipInputs ( \ Illuminate \ Http \ Request $ request , array $ fields ) { $ inputs = array ( ) ; foreach ( $ fields as $ name => $ field ) { if ( $ field -> getOption ( 'external' ) ) { $ inputs [ $ name ] = $ this -> formatRelationshipInput ( $ request -> get ( $ name , NULL ) , $ field ) ; } } return $ inputs ; }
Gets the relationship inputs
41
public function getRelationshipKey ( $ field ) { $ model = $ this -> config -> getDataModel ( ) ; $ invalidArgument = new \ InvalidArgumentException ( "The '" . $ field . "' relationship field you supplied for " . $ this -> config -> getOption ( 'name' ) . " is not a valid relationship method name on the supplied Eloquent model" ) ; if ( ! method_exists ( $ model , $ field ) ) { throw $ invalidArgument ; } $ related_model = $ model -> { $ field } ( ) ; if ( is_a ( $ related_model , $ this -> relationshipBase . 'BelongsTo' ) ) { return 'belongs_to' ; } else if ( is_a ( $ related_model , $ this -> relationshipBase . 'BelongsToMany' ) ) { return 'belongs_to_many' ; } else if ( is_a ( $ related_model , $ this -> relationshipBase . 'HasOne' ) ) { return 'has_one' ; } else if ( is_a ( $ related_model , $ this -> relationshipBase . 'HasMany' ) ) { return 'has_many' ; } else { throw $ invalidArgument ; } }
Given a field name returns the type key or false
42
public function findField ( $ field ) { $ fields = $ this -> getEditFields ( ) ; if ( ! isset ( $ fields [ $ field ] ) ) { throw new \ InvalidArgumentException ( "The " . $ field . " field does not exist on the " . $ this -> config -> getOption ( 'name' ) . " model" ) ; } return $ fields [ $ field ] ; }
Given a field name this returns the field object from the edit fields array
43
public function findFilter ( $ field ) { $ filters = $ this -> getFilters ( ) ; if ( ! isset ( $ filters [ $ field ] ) ) { throw new \ InvalidArgumentException ( "The " . $ field . " filter does not exist on the " . $ this -> config -> getOption ( 'name' ) . " model" ) ; } return $ filters [ $ field ] ; }
Given a field name this returns the field object from the filters array
44
public function getEditFields ( $ loadRelationships = true , $ override = false ) { if ( ! sizeof ( $ this -> editFields ) || $ override ) { $ this -> editFields = array ( ) ; foreach ( $ this -> config -> getOption ( 'edit_fields' ) as $ name => $ options ) { $ fieldObject = $ this -> make ( $ name , $ options , $ loadRelationships ) ; $ this -> editFields [ $ fieldObject -> getOption ( 'field_name' ) ] = $ fieldObject ; } } return $ this -> editFields ; }
Creates the edit fields as Field objects
45
public function filterQuery ( & $ selects ) { $ model = $ this -> config -> getDataModel ( ) ; $ joins = $ where = '' ; $ columnName = $ this -> getOption ( 'column_name' ) ; $ nested = $ this -> getOption ( 'nested' ) ; $ num_pieces = sizeof ( $ nested [ 'pieces' ] ) ; if ( $ num_pieces > 1 ) { for ( $ i = 1 ; $ i < $ num_pieces ; $ i ++ ) { $ model = $ nested [ 'models' ] [ $ i ] ; $ relationship = $ model -> { $ nested [ 'pieces' ] [ $ i ] } ( ) ; $ relationship_model = $ relationship -> getRelated ( ) ; $ table = $ this -> tablePrefix . $ relationship_model -> getTable ( ) ; $ alias = $ columnName . '_' . $ table ; $ last_alias = $ columnName . '_' . $ this -> tablePrefix . $ model -> getTable ( ) ; $ joins .= ' LEFT JOIN ' . $ table . ' AS ' . $ alias . ' ON ' . $ alias . '.' . $ relationship -> getOtherKey ( ) . ' = ' . $ last_alias . '.' . $ relationship -> getForeignKey ( ) ; } } $ first_model = $ nested [ 'models' ] [ 0 ] ; $ first_piece = $ nested [ 'pieces' ] [ 0 ] ; $ first_relationship = $ first_model -> { $ first_piece } ( ) ; $ relationship_model = $ first_relationship -> getRelated ( ) ; $ from_table = $ this -> tablePrefix . $ relationship_model -> getTable ( ) ; $ field_table = $ columnName . '_' . $ from_table ; $ where = $ this -> tablePrefix . $ first_model -> getTable ( ) . '.' . $ first_relationship -> getForeignKey ( ) . ' = ' . $ field_table . '.' . $ first_relationship -> getOtherKey ( ) ; $ selects [ ] = $ this -> db -> raw ( "(SELECT " . $ this -> getOption ( 'select' ) . " FROM " . $ from_table . " AS " . $ field_table . ' ' . $ joins . " WHERE " . $ where . ") AS " . $ this -> db -> getQueryGrammar ( ) -> wrap ( $ columnName ) ) ; }
Adds selects to a query
46
private function get_optimal_crop ( $ new_width , $ new_height ) { $ height_ratio = $ this -> height / $ new_height ; $ width_ratio = $ this -> width / $ new_width ; if ( $ height_ratio < $ width_ratio ) { $ optimal_ratio = $ height_ratio ; } else { $ optimal_ratio = $ width_ratio ; } $ optimal_height = $ this -> height / $ optimal_ratio ; $ optimal_width = $ this -> width / $ optimal_ratio ; return array ( 'optimal_width' => $ optimal_width , 'optimal_height' => $ optimal_height ) ; }
Attempts to find the best way to crop . Whether crop is based on the image being portrait or landscape .
47
public function validateOptions ( ) { $ this -> validator -> override ( $ this -> suppliedOptions , $ this -> rules ) ; if ( $ this -> validator -> fails ( ) ) { throw new \ InvalidArgumentException ( "There are problems with your '" . $ this -> suppliedOptions [ 'action_name' ] . "' action in the " . $ this -> config -> getOption ( 'name' ) . " model: " . implode ( '. ' , $ this -> validator -> messages ( ) -> all ( ) ) ) ; } }
Validates the supplied options
48
public function buildStringOrCallable ( array & $ options , array $ keys ) { $ model = $ this -> config -> getDataModel ( ) ; foreach ( $ keys as $ key ) { $ suppliedValue = $ this -> validator -> arrayGet ( $ options , $ key ) ; if ( is_string ( $ suppliedValue ) ) { $ options [ $ key ] = $ suppliedValue ; } else if ( is_callable ( $ suppliedValue ) ) { $ options [ $ key ] = $ suppliedValue ( $ model ) ; } } }
Sets up the values of all the options that can be either strings or closures
49
public function listDirectory ( $ directory , $ recursive = false ) { $ results = $ this -> scanDirectory ( $ directory , $ recursive ) ; if ( false === $ results ) { throw new \ RuntimeException ( sprintf ( 'Unable to list directory "%s", maybe it is not a directory ' . 'or it does not exist.' , $ directory ) ) ; } return array ( 'files' => $ results [ 0 ] , 'directories' => $ results [ 1 ] ) ; }
Lists files and directories of the specified directory
50
private function scanDirectory ( $ directory , $ recursive ) { if ( ! $ results = @ scandir ( $ this -> getUrl ( $ directory ) ) ) { return false ; } $ files = array ( ) ; $ directories = array ( ) ; foreach ( $ results as $ result ) { if ( in_array ( $ result , array ( '.' , '..' ) ) ) { continue ; } $ filename = sprintf ( '%s/%s' , $ directory , $ result ) ; if ( false === @ scandir ( $ this -> getUrl ( $ filename ) ) ) { $ files [ ] = $ filename ; } else { $ directories [ ] = $ filename ; if ( $ recursive ) { $ children = $ this -> scanDirectory ( $ filename , $ recursive ) ; if ( is_array ( $ children ) ) { $ files = array_merge ( $ files , $ children [ 0 ] ) ; $ directories = array_merge ( $ directories , $ children [ 1 ] ) ; } } } } return array ( $ files , $ directories ) ; }
Scans a directory
51
public function setAuthentication ( Authentication $ authentication ) { $ firstAuthentication = null === $ this -> authentication ; $ this -> authentication = $ authentication ; if ( $ firstAuthentication && is_resource ( $ this -> resource ) ) { $ this -> authenticate ( ) ; } }
Defines the authentication . If the
52
public function getSubsystem ( $ name ) { if ( ! isset ( $ this -> subsystems [ $ name ] ) ) { $ this -> createSubsystem ( $ name ) ; } return $ this -> subsystems [ $ name ] ; }
Returns the specified subsystem
53
protected function createSubsystem ( $ name ) { switch ( $ name ) { case 'sftp' : $ subsystem = new Sftp ( $ this ) ; break ; case 'publickey' : $ subsystem = new Publickey ( $ this ) ; break ; case 'exec' : $ subsystem = new Exec ( $ this ) ; break ; default : throw new InvalidArgumentException ( sprintf ( 'The subsystem \'%s\' is not supported.' , $ name ) ) ; } $ this -> subsystems [ $ name ] = $ subsystem ; }
Creates the specified subsystem
54
protected function createResource ( ) { $ resource = $ this -> connect ( $ this -> configuration -> asArguments ( ) ) ; if ( ! is_resource ( $ resource ) ) { throw new RuntimeException ( 'The SSH connection failed.' ) ; } $ this -> resource = $ resource ; if ( null !== $ this -> authentication ) { $ this -> authenticate ( ) ; } }
Creates the session resource
55
protected function parseSshConfigFile ( $ file ) { if ( ! file_exists ( $ file ) || ! is_readable ( $ file ) ) { throw new RuntimeException ( "The file '$file' does not exist or is not readable" ) ; } $ contents = file_get_contents ( $ file ) ; $ configs = array ( ) ; $ lineNumber = 1 ; foreach ( explode ( PHP_EOL , $ contents ) as $ line ) { $ line = trim ( $ line ) ; if ( $ line == '' || $ line [ 0 ] == '#' ) { continue ; } $ pos = strpos ( $ line , '=' ) ; if ( $ pos !== false ) { $ key = strtolower ( trim ( substr ( $ line , 0 , $ pos ) ) ) ; $ value = trim ( substr ( $ line , $ pos + 1 , strlen ( $ line ) ) ) ; } else { $ i = 0 ; while ( $ i < strlen ( $ line ) ) { if ( $ line [ $ i ] == ' ' ) { break ; } $ i ++ ; } if ( $ i == strlen ( $ line ) ) { throw new RuntimeException ( "The file '$file' is not parsable at line '$lineNumber'" ) ; } $ key = strtolower ( trim ( substr ( $ line , 0 , $ i ) ) ) ; $ value = trim ( substr ( $ line , $ i + 1 , strlen ( $ line ) ) ) ; } if ( $ key == 'host' ) { $ this -> configs = array_merge ( $ this -> configs , $ configs ) ; $ configs = array ( ) ; $ hosts = explode ( ' ' , $ value ) ; foreach ( $ hosts as $ host ) { $ configs [ ] = array ( 'host' => $ host ) ; } } else { foreach ( $ configs as $ host => $ config ) { $ configs [ $ host ] [ $ key ] = $ value ; } } $ lineNumber ++ ; } $ this -> configs = array_merge ( $ this -> configs , $ configs ) ; }
Parses the ssh config file into an array of configs for later matching against hosts
56
public function getConfigForHost ( $ host ) { $ matches = array ( ) ; foreach ( $ this -> configs as $ config ) { if ( fnmatch ( $ config [ 'host' ] , $ host ) ) { $ matches [ ] = $ config ; } } if ( count ( $ matches ) == 0 ) { throw new RuntimeException ( "Unable to find configuration for host '{$host}'" ) ; } usort ( $ matches , function ( $ a , $ b ) { return strlen ( $ a [ 'host' ] ) > strlen ( $ b [ 'host' ] ) ; } ) ; $ result = array ( ) ; foreach ( $ matches as $ match ) { $ result = array_merge ( $ result , $ match ) ; } unset ( $ result [ 'host' ] ) ; if ( isset ( $ result [ 'identityfile' ] ) ) { $ result [ 'identityfile' ] = $ this -> processPath ( $ result [ 'identityfile' ] ) ; } else if ( file_exists ( $ file = $ this -> processPath ( $ this -> getIdentity ( ) ) ) ) { $ result [ 'identityfile' ] = $ file ; } return $ result ; }
Merges matches of the host in the config file using fnmatch and a length comparison
57
public function getAuthentication ( $ passphrase = null , $ user = null ) { if ( is_null ( $ user ) && ! isset ( $ this -> config [ 'user' ] ) ) { throw new RuntimeException ( "Can not authenticate for '{$this->host}' could not find user to authenticate as" ) ; } $ user = $ user ? : $ this -> config [ 'user' ] ; if ( isset ( $ this -> config [ 'identityfile' ] ) ) { return new Authentication \ PublicKeyFile ( $ user , $ this -> config [ 'identityfile' ] . '.pub' , $ this -> config [ 'identityfile' ] , $ passphrase ) ; } else { return new Authentication \ None ( $ user ) ; } }
Return an authentication mechanism based on the configuration file
58
public function add ( $ algoname , $ blob , $ overwrite = false , array $ attributes = array ( ) ) { return ssh2_publickey_add ( $ this -> getResource ( ) , $ algoname , $ blob , $ overwrite , $ attributes ) ; }
Adds an authorized publickey
59
function difference ( Set $ that ) { $ difference = $ this -> cloneEmpty ( ) ; if ( $ that === $ this ) { return $ difference ; } $ this -> addIf ( $ difference , $ this , negate ( [ $ that , 'has' ] ) ) ; $ this -> addIf ( $ difference , $ that , negate ( [ $ this , 'has' ] ) ) ; return $ difference ; }
Creates the set that contains the items in the current set that are not contained in the provided set as well as items that are in the provided set that are not in the current set .
60
function intersection ( Set $ that ) { $ intersection = $ this -> cloneEmpty ( ) ; $ this -> addIf ( $ intersection , $ this , [ $ that , 'has' ] ) ; return $ intersection ; }
Creates a new set that contains the items that are in current set that are also contained in the provided set .
61
function complement ( Set $ that ) { $ complement = $ this -> cloneEmpty ( ) ; if ( $ that === $ this ) { return $ complement ; } $ this -> addIf ( $ complement , $ that , negate ( [ $ this , 'has' ] ) ) ; return $ complement ; }
Creates a new set which contains the items that exist in the provided set and do not exist in the current set .
62
function union ( Set $ that ) { $ union = $ this -> cloneEmpty ( ) ; $ this -> for_each ( $ this , [ $ union , 'add' ] ) ; $ this -> for_each ( $ that , [ $ union , 'add' ] ) ; return $ union ; }
Creates a new set that contains the items of the current set and the items of the provided set .
63
function tail ( ) { assert ( ! $ this -> isEmpty ( ) ) ; return $ this -> copyFromContext ( $ this -> head -> next ( ) -> next ( ) ) ; }
Extract the elements after the first of a list which must be non - empty .
64
function inOrderPredecessor ( ) { $ current = $ this -> left ( ) ; while ( $ current -> right ( ) !== null ) { $ current = $ current -> right ( ) ; } return $ current ; }
Note that this function is only safe to call when it has a predecessor .
65
public function getCaptchaCode ( array & $ options ) { $ this -> builder -> setPhrase ( $ this -> getPhrase ( $ options ) ) ; if ( $ options [ 'as_file' ] ) { $ this -> imageFileHandler -> collectGarbage ( ) ; return $ this -> generate ( $ options ) ; } if ( $ options [ 'as_url' ] ) { return $ this -> router -> generate ( 'gregwar_captcha.generate_captcha' , array ( 'key' => $ options [ 'session_key' ] , 'n' => md5 ( microtime ( true ) . mt_rand ( ) ) ) ) ; } return 'data:image/jpeg;base64,' . base64_encode ( $ this -> generate ( $ options ) ) ; }
Get the captcha URL stream or filename that will go in the image s src attribute
66
protected function getExpectedCode ( ) { $ options = $ this -> session -> get ( $ this -> key , array ( ) ) ; if ( is_array ( $ options ) && isset ( $ options [ 'phrase' ] ) ) { return $ options [ 'phrase' ] ; } return null ; }
Retrieve the expected CAPTCHA code
67
protected function updateHumanity ( $ newValue ) { if ( $ newValue > 0 ) { $ this -> session -> set ( $ this -> key . '_humanity' , $ newValue ) ; } else { $ this -> session -> remove ( $ this -> key . '_humanity' ) ; } return null ; }
Updates the humanity
68
protected function compare ( $ code , $ expectedCode ) { return ( $ expectedCode !== null && is_string ( $ expectedCode ) && $ this -> niceize ( $ code ) == $ this -> niceize ( $ expectedCode ) ) ; }
Run a match comparison on the provided code and the expected code
69
public function generateCaptchaAction ( $ key ) { $ options = $ this -> container -> getParameter ( 'gregwar_captcha.config' ) ; $ session = $ this -> get ( 'session' ) ; $ whitelistKey = $ options [ 'whitelist_key' ] ; $ isOk = false ; if ( $ session -> has ( $ whitelistKey ) ) { $ keys = $ session -> get ( $ whitelistKey ) ; if ( is_array ( $ keys ) && in_array ( $ key , $ keys ) ) { $ isOk = true ; } } if ( ! $ isOk ) { return $ this -> error ( $ options ) ; } $ generator = $ this -> container -> get ( 'gregwar_captcha.generator' ) ; $ persistedOptions = $ session -> get ( $ key , array ( ) ) ; $ options = array_merge ( $ options , $ persistedOptions ) ; $ phrase = $ generator -> getPhrase ( $ options ) ; $ generator -> setPhrase ( $ phrase ) ; $ persistedOptions [ 'phrase' ] = $ phrase ; $ session -> set ( $ key , $ persistedOptions ) ; $ response = new Response ( $ generator -> generate ( $ options ) ) ; $ response -> headers -> set ( 'Content-type' , 'image/jpeg' ) ; $ response -> headers -> set ( 'Pragma' , 'no-cache' ) ; $ response -> headers -> set ( 'Cache-Control' , 'no-cache' ) ; return $ response ; }
Action that is used to generate the captcha save its code and stream the image
70
protected function error ( $ options ) { $ generator = $ this -> container -> get ( 'gregwar_captcha.generator' ) ; $ generator -> setPhrase ( '' ) ; $ response = new Response ( $ generator -> generate ( $ options ) ) ; $ response -> setStatusCode ( 428 ) ; $ response -> headers -> set ( 'Content-type' , 'image/jpeg' ) ; $ response -> headers -> set ( 'Pragma' , 'no-cache' ) ; $ response -> headers -> set ( 'Cache-Control' , 'no-cache' ) ; return $ response ; }
Returns an empty image with status code 428 Precondition Required
71
public function executeArrayLabel ( $ sheetData ) { $ keys = ArrayHelper :: remove ( $ sheetData , '1' ) ; $ new_data = [ ] ; foreach ( $ sheetData as $ values ) { $ new_data [ ] = array_combine ( $ keys , $ values ) ; } return $ new_data ; }
Setting label or keys on every record if setFirstRecordAsKeys is true .
72
public function executeLeaveRecords ( $ sheetData = [ ] , $ index = [ ] ) { foreach ( $ sheetData as $ key => $ data ) { if ( in_array ( $ key , $ index ) ) { unset ( $ sheetData [ $ key ] ) ; } } return $ sheetData ; }
Leave record with same index number .
73
public function executeGetOnlyRecords ( $ sheetData = [ ] , $ index = [ ] ) { foreach ( $ sheetData as $ key => $ data ) { if ( ! in_array ( $ key , $ index ) ) { unset ( $ sheetData [ $ key ] ) ; } } return $ sheetData ; }
Read record with same index number .
74
public function executeGetColumnData ( $ model , $ params = [ ] ) { $ value = null ; if ( isset ( $ params [ 'value' ] ) && $ params [ 'value' ] !== null ) { if ( is_string ( $ params [ 'value' ] ) ) { $ value = ArrayHelper :: getValue ( $ model , $ params [ 'value' ] ) ; } else { $ value = call_user_func ( $ params [ 'value' ] , $ model , $ this ) ; } } elseif ( isset ( $ params [ 'attribute' ] ) && $ params [ 'attribute' ] !== null ) { $ value = ArrayHelper :: getValue ( $ model , $ params [ 'attribute' ] ) ; } if ( isset ( $ params [ 'format' ] ) && $ params [ 'format' ] != null ) $ value = $ this -> formatter ( ) -> format ( $ value , $ params [ 'format' ] ) ; return $ value ; }
Getting column value .
75
public function populateColumns ( $ columns = [ ] ) { $ _columns = [ ] ; foreach ( $ columns as $ key => $ value ) { if ( is_string ( $ value ) ) { $ value_log = explode ( ':' , $ value ) ; $ _columns [ $ key ] = [ 'attribute' => $ value_log [ 0 ] ] ; if ( isset ( $ value_log [ 1 ] ) && $ value_log [ 1 ] !== null ) { $ _columns [ $ key ] [ 'format' ] = $ value_log [ 1 ] ; } if ( isset ( $ value_log [ 2 ] ) && $ value_log [ 2 ] !== null ) { $ _columns [ $ key ] [ 'header' ] = $ value_log [ 2 ] ; } } elseif ( is_array ( $ value ) ) { if ( ! isset ( $ value [ 'attribute' ] ) && ! isset ( $ value [ 'value' ] ) ) { throw new \ InvalidArgumentException ( 'Attribute or Value must be defined.' ) ; } $ _columns [ $ key ] = $ value ; } } return $ _columns ; }
Populating columns for checking the column is string or array . if is string this will be checking have a formatter or header .
76
public function formatter ( ) { if ( ! isset ( $ this -> formatter ) ) $ this -> formatter = \ Yii :: $ app -> getFormatter ( ) ; return $ this -> formatter ; }
Formatter for i18n .
77
public function getFileName ( ) { $ fileName = 'exports.xlsx' ; if ( isset ( $ this -> fileName ) ) { $ fileName = $ this -> fileName ; if ( strpos ( $ fileName , '.xlsx' ) === false ) $ fileName .= '.xlsx' ; } return $ fileName ; }
Getting the file name of exporting xls file
78
public function properties ( & $ objectExcel , $ properties = [ ] ) { foreach ( $ properties as $ key => $ value ) { $ keyname = "set" . ucfirst ( $ key ) ; $ objectExcel -> getProperties ( ) -> { $ keyname } ( $ value ) ; } }
Setting properties for excel file
79
public function writeFile ( $ sheet ) { if ( ! isset ( $ this -> format ) ) $ this -> format = 'Xlsx' ; $ objectwriter = \ PhpOffice \ PhpSpreadsheet \ IOFactory :: createWriter ( $ sheet , $ this -> format ) ; $ path = 'php://output' ; if ( isset ( $ this -> savePath ) && $ this -> savePath != null ) { $ path = $ this -> savePath . '/' . $ this -> getFileName ( ) ; } $ objectwriter -> setOffice2003Compatibility ( $ this -> compatibilityOffice2003 ) ; $ objectwriter -> setPreCalculateFormulas ( $ this -> preCalculationFormula ) ; $ objectwriter -> save ( $ path ) ; if ( $ path == 'php://output' ) exit ( ) ; return true ; }
saving the xls file to download or to path
80
public static function import ( $ fileName , $ config = [ ] ) { $ config = ArrayHelper :: merge ( [ 'mode' => 'import' , 'fileName' => $ fileName , 'asArray' => true ] , $ config ) ; return self :: widget ( $ config ) ; }
Import file excel and return into an array .
81
public function commentAsUser ( ? Model $ user , string $ comment ) { $ commentClass = config ( 'comments.comment_class' ) ; $ comment = new $ commentClass ( [ 'comment' => $ comment , 'is_approved' => ( $ user instanceof Commentator ) ? ! $ user -> needsCommentApproval ( $ this ) : false , 'user_id' => is_null ( $ user ) ? null : $ user -> getKey ( ) , 'commentable_id' => $ this -> getKey ( ) , 'commentable_type' => get_class ( ) , ] ) ; return $ this -> comments ( ) -> save ( $ comment ) ; }
Attach a comment to this model as a specific user .
82
protected function makeEntityProxy ( $ entity , $ relation , $ class ) { $ proxyPath = Manager :: getInstance ( ) -> getProxyPath ( ) ; if ( $ proxyPath !== null ) { $ proxyConfig = new Configuration ( ) ; $ proxyConfig -> setProxiesTargetDir ( $ proxyPath ) ; $ factory = new LazyLoadingValueHolderFactory ( $ proxyConfig ) ; } else { $ factory = new LazyLoadingValueHolderFactory ( ) ; } $ initializer = function ( & $ wrappedObject , LazyLoadingInterface $ proxy , $ method , array $ parameters , & $ initializer ) use ( $ entity , $ relation ) { $ entityMap = Manager :: getMapper ( $ entity ) -> getEntityMap ( ) ; $ wrappedObject = $ entityMap -> $ relation ( $ entity ) -> getResults ( $ relation ) ; $ initializer = null ; return true ; } ; return $ factory -> createProxy ( $ class , $ initializer ) ; }
Create an instance of a proxy object extending the actual related class .
83
protected function getManagedProperties ( ) : array { $ properties = $ this -> entityMap -> getProperties ( ) ; $ attributesName = $ this -> entityMap -> getAttributesArrayName ( ) ; return $ attributesName == null ? $ properties : array_merge ( $ properties , [ $ attributesName ] ) ; }
Return properties that will be extracted from the entity .
84
protected function attributesFromProperties ( array $ properties ) : array { $ managedProperties = $ this -> getManagedProperties ( ) ; $ properties = array_only ( $ properties , $ managedProperties ) ; if ( ! $ this -> entityMap -> usesAttributesArray ( ) ) { return $ properties ; } $ arrayName = $ this -> entityMap -> getAttributesArrayName ( ) ; if ( ! array_key_exists ( $ arrayName , $ properties ) ) { throw new MappingException ( "Property $arrayName not set on object of type " . $ this -> getEntityClass ( ) ) ; } if ( ! is_array ( $ properties [ $ arrayName ] ) ) { throw new MappingException ( "Property $arrayName should be an array." ) ; } $ attributes = $ properties [ $ arrayName ] ; unset ( $ properties [ $ arrayName ] ) ; return $ properties + $ attributes ; }
Convert object s properties to analogue s internal attributes representation .
85
protected function propertiesFromAttributes ( ) : array { $ propertyNames = $ this -> entityMap -> getProperties ( ) ; $ propertyAttributes = array_only ( $ this -> attributes , $ propertyNames ) ; $ attributesArray = array_except ( $ this -> attributes , $ propertyNames ) ; $ attributesArrayName = $ this -> entityMap -> getAttributesArrayName ( ) ; if ( $ attributesArrayName ) { $ propertyAttributes [ $ attributesArrayName ] = $ attributesArray ; } return $ propertyAttributes ; }
Convert internal representation of attributes to an array of properties that can hydrate the actual object .
86
public function setProxies ( array $ relations = null ) { $ attributes = $ this -> getEntityAttributes ( ) ; $ proxies = [ ] ; $ relations = $ this -> getRelationsToProxy ( ) ; foreach ( $ relations as $ relation ) { $ this -> setEntityAttribute ( $ relation , null ) ; } foreach ( $ relations as $ relation ) { if ( array_key_exists ( $ relation , $ attributes ) && ! is_null ( $ attributes [ $ relation ] ) ) { continue ; } if ( ! $ this -> relationNeedsProxy ( $ relation , $ attributes ) ) { $ proxies [ $ relation ] = $ this -> entityMap -> getEmptyValueForRelationship ( $ relation ) ; } else { $ targetClass = $ this -> getClassToProxy ( $ relation , $ attributes ) ; $ proxies [ $ relation ] = $ this -> proxyFactory -> make ( $ this -> getObject ( ) , $ relation , $ targetClass ) ; } } foreach ( $ proxies as $ key => $ value ) { $ this -> setEntityAttribute ( $ key , $ value ) ; } }
Set the lazy loading proxies on the wrapped entity objet .
87
protected function getClassToProxy ( $ relation , array $ attributes ) { if ( $ this -> entityMap -> isPolymorphic ( $ relation ) ) { $ localTypeAttribute = $ this -> entityMap -> getLocalKeys ( $ relation ) [ 'type' ] ; return $ attributes [ $ localTypeAttribute ] ; } return $ this -> entityMap -> getTargettedClass ( $ relation ) ; }
Get Target class to proxy for a one to one .
88
protected function getRelationsToProxy ( ) { $ proxies = [ ] ; $ attributes = $ this -> getEntityAttributes ( ) ; foreach ( $ this -> entityMap -> getNonEmbeddedRelationships ( ) as $ relation ) { if ( ! array_key_exists ( $ relation , $ attributes ) || is_null ( $ attributes [ $ relation ] ) ) { $ proxies [ ] = $ relation ; } } return $ proxies ; }
Determine which relations we have to build proxy for by parsing attributes and finding methods that aren t set .
89
protected function relationNeedsProxy ( $ relation , $ attributes ) { if ( in_array ( $ relation , $ this -> entityMap -> getRelationshipsWithoutProxy ( ) ) ) { return false ; } $ localKey = $ this -> entityMap -> getLocalKeys ( $ relation ) ; if ( is_null ( $ localKey ) ) { return true ; } if ( is_array ( $ localKey ) ) { $ localKey = $ localKey [ 'id' ] ; } if ( ! isset ( $ attributes [ $ localKey ] ) || is_null ( $ attributes [ $ localKey ] ) ) { return false ; } return true ; }
Determine if the relation needs a proxy or not .
90
public function findMany ( $ id , $ columns = [ '*' ] ) { if ( empty ( $ id ) ) { return new EntityCollection ( ) ; } $ this -> query -> whereIn ( $ this -> entityMap -> getKeyName ( ) , $ id ) ; return $ this -> get ( $ columns ) ; }
Find many entities by their primary keys .
91
protected function ungroupedPaginate ( $ paginator , $ perPage , $ columns ) { $ total = $ this -> query -> getPaginationCount ( ) ; $ page = $ paginator -> getCurrentPage ( $ total ) ; $ this -> query -> forPage ( $ page , $ perPage ) ; return $ paginator -> make ( $ this -> get ( $ columns ) -> all ( ) , $ total , $ perPage ) ; }
Get a paginator for an ungrouped statement .
92
protected function enforceIdColumn ( $ columns ) { if ( ! in_array ( $ this -> entityMap -> getKeyName ( ) , $ columns ) ) { $ columns [ ] = $ this -> entityMap -> getKeyName ( ) ; } return $ columns ; }
Add the Entity primary key if not in requested columns .
93
protected function getEmbeddedObjectAttributes ( ) : array { $ entityMap = $ this -> getRelatedMapper ( ) -> getEntityMap ( ) ; $ attributes = $ entityMap -> getAttributes ( ) ; $ properties = $ entityMap -> getProperties ( ) ; return array_merge ( $ attributes , $ properties ) ; }
Get the embedded object s attributes that will be hydrated using parent s entity attributes .
94
protected function getMappedParentAttribute ( string $ key ) : string { if ( array_key_exists ( $ key , $ this -> columnMap ) ) { return $ this -> columnMap [ $ key ] ; } else { return $ key ; } }
Get attribute name from the parent if a map has been defined .
95
protected function buildEmbeddedObject ( array $ attributes ) { $ resultBuilder = new ResultBuilder ( $ this -> getRelatedMapper ( ) , true ) ; $ eagerLoads = [ ] ; return $ resultBuilder -> build ( [ $ attributes ] , $ eagerLoads ) [ 0 ] ; }
Build an embedded object instance .
96
public function getAttributeNameForColumn ( $ columnName ) { if ( ! empty ( $ this -> mappings ) ) { if ( isset ( $ this -> mappings [ $ columnName ] ) ) { return $ this -> mappings [ $ columnName ] ; } } return $ columnName ; }
Gets the entity attribute name of a given column in a table .
97
public function getColumnNameForAttribute ( $ attributeName ) { if ( ! empty ( $ this -> mappings ) ) { $ flipped = array_flip ( $ this -> mappings ) ; if ( isset ( $ flipped [ $ attributeName ] ) ) { return $ flipped [ $ attributeName ] ; } } return $ attributeName ; }
Gets the column name of a given entity attribute .
98
protected function cacheResults ( array $ results ) { $ mapper = $ this -> mapper ; if ( $ mapper -> getEntityMap ( ) -> getKeyName ( ) !== null ) { $ mapper -> getEntityCache ( ) -> add ( $ results ) ; } }
Cache result set .
99
protected function buildEmbeddedRelationships ( array $ results ) : array { $ entityMap = $ this -> entityMap ; $ instance = $ this -> mapper -> newInstance ( ) ; $ embeddeds = $ entityMap -> getEmbeddedRelationships ( ) ; foreach ( $ embeddeds as $ embedded ) { $ results = $ entityMap -> $ embedded ( $ instance ) -> match ( $ results , $ embedded ) ; } return $ results ; }
Build embedded objects and match them to the result set .
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
-