Plugin Directory

Changeset 2719681


Ignore:
Timestamp:
05/06/2022 10:31:51 PM (4 years ago)
Author:
amit
Message:

Updated to v5.1

Location:
igsyntax-hiliter/trunk
Files:
1 deleted
16 edited

Legend:

Unmodified
Added
Removed
  • igsyntax-hiliter/trunk/README.md

    r1213537 r2719681  
    1 ## **iG:Syntax Hiliter v5.0**
     1## **iG:Syntax Hiliter v5.1**
    22---------------------------------
    33
     
    55
    66##### **Minimum Requirements**
    7 - WordPress 4.1 or above
    8 - PHP 5.3 or above
     7- WordPress 5.4 or above
     8- PHP 7.4.0 or above
    99
    1010**WordPress.org:** [https://wordpress.org/plugins/igsyntax-hiliter/](https://wordpress.org/plugins/igsyntax-hiliter/)
    1111
    12 **iG:Syntax Hiliter** allows you to post source code to your site with syntax highlighting and formatting  (as seen in code editors, IDEs). You can paste the code as is from your code editor or IDE and this plugin will take care of all the code colouring and preserve your formatting. It uses the [GeSHi library](http://qbnz.com/highlighter/) to colourize your code and supports over a 100 programming languages. Most common languages are included with the plugin and it includes drop in support for more languages used by GeSHi.
     12**iG:Syntax Hiliter** allows you to post source code to your site with syntax highlighting and formatting  (as seen in code editors, IDEs). You can paste the code as is from your code editor or IDE and this plugin will take care of all the code colouring and preserve your formatting. It uses the [GeSHi library](http://qbnz.com/highlighter/) to colourise your code and supports over a 100 programming languages. Most common languages are included with the plugin and it includes drop in support for more languages used by GeSHi.
    1313
    14 **NOTE :** For fast results and less load on your server, you should have a cache plugin installed. That way the plugin won't have to parse the code blocks on a post every time its loaded in browser.
     14**NOTE :** For fast results and less load on your server, you should have a cache plugin installed. That way the plugin won't have to parse the code blocks on a post every time it is loaded in browser.
    1515
     16### **[Changelog](CHANGELOG.md)**
    1617
    1718### **Installation**
    1819
    1920#### **Upgrading from v4.0 or later**
    20 Just click `update now` link below the plugin listing on the plugins page in your `wp-admin`. That's quite easy!!
     21Just click `update now` link below the plugin listing on the plugins page in your `wp-admin`. The plugin will handle any settings migration if needed. Easy peasy!!
    2122
    2223#### **Upgrading from v3.x**
    23 Just deactivate plugin in WordPress admin, delete the `syntax_hilite.php` file & `ig_syntax_hilite` directory from plugins folder and follow the installation process below. That's quite easy!!
     24Deactivate plugin in WordPress admin, delete the `syntax_hilite.php` file & `ig_syntax_hilite` directory from plugins folder and follow the installation process below.
    2425
    2526#### **Upgrading from v2.1 or lower**
    26 Just deactivate plugin in WordPress admin, delete the `syntax_hilite.php` and `geshi.php` files & `geshi` directory from plugins folder and follow the installation process below. That's quite easy!!
     27Deactivate plugin in WordPress admin, delete the `syntax_hilite.php` and `geshi.php` files & `geshi` directory from plugins folder and follow the installation process below.
    2728
    2829#### **Installing The Plugin**
    29301. Login to your WordPress `wp-admin` area.
    30312. Click `Add New` in the `Plugins` menu on left.
    31 3. Enter `iG:Syntax Hiliter` in the search bar on the right on the page that opens and press Enter key.
     323. Enter `iG:Syntax Hiliter` in the search bar on the right of the page that opens and press Enter key.
    32334. WordPress would show the **iG:Syntax Hiliter** plugin with install button, click that to install the plugin.
    33345. Click on `Activate Plugin` link on the page that opens after the plugin has been installed successfully.
    3435
    35 **See Also:** ["Installing Plugins" article on the WP Codex](http://codex.wordpress.org/Managing_Plugins#Installing_Plugins)
     36**See Also:** ["Finding and Installing Plugins" article on the WordPress Support](https://wordpress.org/support/article/managing-plugins/#finding-and-installing-plugins)
    3637
    3738
     
    6667HTML entities need not be escaped, you can post your code as is and the plugin takes care of it all.
    6768
    68 **Important :** Do not forget to close the tags, as your code will not be hilited if you don't close your tags. Also, *don't nest tags*. Nesting of tags don't work, so don't try it, it'll ruin your output.
     69**Important :** Do not forget to close the tags, as your code will not be highlighted if you don't close your tags. Also, *don't nest tags*. Nesting of tags don't work, so don't try it, it'll ruin your output.
    6970
    70 Also a WYSIWYG editor (like the one bundled with WordPress) will probably mess up your code when you paste it in the editor. So if you are having that issue, then please don't report it as a bug. WYSIWYG editors are just not supported at present.
     71**Important :** A WYSIWYG editor (like the one bundled with WordPress) will likely mess up your code when you paste it in the editor. If you are having that issue, then please don't report it as a bug. WYSIWYG editors are just not supported at present.
     72
     73***Similarly, Gutenberg Editor is not supported at present either.***
    7174
    7275#### **(Optional) Plugin Attributes**
     
    107110Configuring **iG:Syntax Hiliter** is a piece of cake. Login to your WordPress admin section & under the `Settings` menu you'll see `iG:Syntax Hiliter` in the sub-menu.
    108111
    109 When you click the `iG:Syntax Hiliter` configuration page, you are offered 10 configuration settings which you can set to your liking. Lets go through each of them.
     112When you click the `iG:Syntax Hiliter` configuration page, you are offered some configuration settings which you can set to your liking. Lets go through each of them.
    110113
    111 **Use plugin CSS for styling? :** This option allows you to tell the plugin whether it should use its own CSS for styling the code box (not the hilited code, just code box) or not. If you want to use your own styling for the code box, tool-bar etc then you can set it to `NO`. By default its set to `YES`.
     114**Use plugin CSS for styling? :** This option allows you to tell the plugin whether it should use its own CSS for styling the code box (not the highlighted code, just code box) or not. If you want to use your own styling for the code box, tool-bar etc then you can set it to `NO`. By default its set to `YES`.
    112115
    113 **GeSHi Strict Mode? :** This option allows you to tell the plugin the [strict mode](http://qbnz.com/highlighter/geshi-doc.html#using-strict-mode) setting to use with GeSHi. Strict mode can be set to be always on or off or you can set it to `MAYBE` to have GeSHi decide on its own using the language file of the language whose code you're hiliting. *If you don't have any clue about this then leave it at default setting.* By default its set to `MAYBE`. This option can be overridden for any code block using `strict_mode` attribute in the tag.
     116**GeSHi Strict Mode? :** This option allows you to tell the plugin the [strict mode](http://qbnz.com/highlighter/geshi-doc.html#using-strict-mode) setting to use with GeSHi. Strict mode can be set to be always on or off or you can set it to `MAYBE` to have GeSHi decide on its own using the language file of the language whose code you're highlighting. *If you don't have any clue about this then leave it at default setting.* By default its set to `MAYBE`. This option can be overridden for any code block using `strict_mode` attribute in the tag.
    114117
    115118**Languages where GeSHi strict mode is disabled :** This option lets you specify a comma separated list of languages where the GeSHi strict mode should always be disabled. Strict mode is disabled for PHP by default.
     
    121124**Show line numbers in code? :** This option allows you to tell the plugin whether to show the line numbers along with code in the code boxes or not. Line numbers along with code look great, are a great help when referring to some code from a code box. This option can be overridden for any code block using `gutter` attribute in the tag.
    122125
    123 **Hilite code in comments? :** This option allows you to tell the plugin whether to hilite code posted in comments or not. If this is enabled, code posted in the comments will be hilited as it is in the posts.
     126**Hilite code in comments? :** This option allows you to tell the plugin whether to highlight code posted in comments or not. If this is enabled, code posted in the comments will be highlighted as it is in the posts.
    124127
    125128**Link keywords/function names to Manual? :** This option allows you to tell the plugin whether to link keywords, function names etc to that language's online manual or not. This works only if this feature is enabled for that particular language in GeSHi language file.
     
    143146
    144147**A:** Please feel free to suggest a new feature. Its inclusion might be speedier if you can provide the code to make it work.
    145 
    146 
    147 ### **Changelog**
    148 
    149 ##### **v5.0**
    150 
    151 * Minimum required PHP version bumped to 5.3.0. The plugin simply won't load its code on lower versions.
    152 * Major re-write of plugin for cleaner, modular & better performing code.
    153 * Assets are enqueued only if needed.
    154 * NEW: You can now disable plugin stylesheet which styles code boxes. People who have their own styling don't need it anyway.
    155 * NEW: 2 new options allow more control on GeSHi behaviour.
    156 * BUGFIX: Language name cache was not re-building automatically.
    157 
    158 ##### **v4.3**
    159 
    160 * BUGFIX: some language file names got snipped when building language name cache
    161 
    162 ##### **v4.2**
    163 
    164 * BUGFIX: Shorthand tags for all languages supported now - props to Karol Kuczmarski for spotting it
    165 * NEW: Added C++ language file
    166 
    167 ##### **v4.1**
    168 
    169 * BUGFIX: Github Gist URL XSS security hole
    170 * BUGFIX: `__dir__` doesn't work below PHP 5.3 - props to Karol Kuczmarski for spotting it
    171 * NEW: Added "lang" as shorthand for "language" attribute
    172 * NEW: Additional GeSHi language files can be put in "geshi" directory in theme, which will prevent their deletion on plugin upgrade
    173 * IMPROVED: If a code block is repeated with same attributes then its parsed only once and output is reused
    174 
    175 ##### **v4.0**
    176 
    177 * NEW: Ability to embed Github Gist in post and comments (configurable)
    178 * NEW: Ability to highlight one or multiple lines in a code block to show them as different
    179 * NEW: New code box layout
    180 * NEW: Ability to escape plugin tags to prevent their processing
    181 * NEW: New GeSHi core (v 1.0.8.11)
    182 * IMPROVED: Removed quirks from plain text view & its now much more smoother
    183 * IMPROVED: Handling of how code is prevented from beautification. The rest of the post/comment text is not affected as wptexturize is not removed anymore.
    184 * IMPROVED: Simpler and faster options page in wp-admin
    185 
    186 ##### **v3.5**
    187 
    188 * BUGFIX: BB Tags except the ones of iG:Syntax Hiliter are allowed. The language file's existence is checked before parsing the code. If the language file does not exist then the code is not parsed.
    189 * BUGFIX: 'C' code hiliting is now fixed.
    190 * BUGFIX: 'Plain Text' has been improved to strip the extra blank lines and spaces in Opera and FireFox.
    191 * The latest stable GeSHi core(v1.0.7.6).
    192 * NEW: Code Hiliting for Comments has been implemented. This feature can be Enabled/Disabled from the admin interface for iG:Syntax Hiliter. The tags are same for hiliting the code.
    193 * NEW: A cross-browser Colour Picker(tested in IE6, FireFox1.5 and Opera8.5) is now available to easily set the line colours displayed in the code box.
    194 * NEW: A new type of view implemented for seeing "Plain Text" code. Besides opening the plain text code in a new window, you can have it displayed in the code box itself with an option to display the hilited HTML code back again. The "Plain Text" view type can be set in the admin interface.
    195 * The language file for Ruby that I created a while back is now bundled with the plugin and its also a part of the default GeSHi package.
    196 
    197 ##### **v3.1**
    198 
    199 * BUGFIX: Critical bug, which broke the plugin when the square brackets([ & ]) were used in the posts in places other than tags, has been fixed.
    200 * BUGFIX: Another bug, which allowed any attribute in the tags besides the 'num' and also allowed any attribute value for it, affecting the processing. Now only the 'num' attribute is accepted and if you specify the 'num' attribute then its value must be a positive number otherwise your code won't be hilited. The 'num' attribute is optional and you can leave it out without any problems.
    201 * BUGFIX: Fixed the unclosed <select> tags in the Plugin GUI code.
    202 * GeSHi BUGFIX: Fixed a bug in GeSHi where the first line colour was not used when using FANCY LINE NUMBERS thus resulting in just one colour being used for the alternate lines.
    203 * There's a problem in WordPress due to which the starting delimiters of ASP, PHP were not displayed correctly, as whitespace was inserted between the '<' and the rest of the delimiter. This has been patched so that its displayed correctly, but its not saved in the database, so the database still contains the delimiters as formatted by WordPress.
    204 
    205 ##### **v3.0**
    206 
    207 * Complete re-write of the plugin resulting in reduction of code from 750+ lines to about 400 Lines.
    208 * New GeSHi Core(v1.0.7) which has some bug-fixes, please see GeSHi Website for its changelog.
    209 * New languages added are C#, Delphi, Smarty & VB.NET.
    210 * ASP language file structure updated & more keywords added.
    211 * Drag-n-Drop usage of new languages. The plugin now supports all languages that GeSHi(v1.0.7) supports. You just need to drop the language file in the "geshi" directory & use the filename as the tag for the language(like if file is "pascal.php", then the filename is "pascal" & the tags will be [pascal] & [/pascal]).
    212 * Language name which is displayed in the Code-Box can now be turned ON or OFF easily.
    213 * No more need to set the physical-path to the "geshi" directory if you are doing a default installation.
    214 * Plain-Text View of the code hilited in the code-box is now possible. This feature can be enabled/disabled easily in the Configuration Interface in WordPress Administration.
    215 * NO NEED TO EDIT THE PLUGIN FILE ANYMORE. You can now configure the plugin settings from a GUI located under the OPTIONS menu in your WordPress Administration(WordPress 1.5 & above only).
    216 
    217 ##### **v2.01**
    218 
    219 * BUGFIX: Fixed a bug by removing a <br /> tag from the function pFix() which lead to closing of an unnecessary <p> tag making the code not xHTML valid(as per my desires).
    220 
    221 ##### **v2.0 Final**
    222 
    223 * Implemented the new version of GeSHi core, v1.0.2 which has some bug fixes & which uses OL(Ordered Lists) for Line Numbering and supports starting of a Line Number from any given number.
    224 * The ASP(Active Server Pages) language file has been updated to the new Language File structure of GeSHi as well as more keywords added & hiliting is more effective now.
    225 * iG:Syntax Hiliter now also supports ActionScript, C, C++, JavaScript, Perl, Python, Visual Basic & XML.
    226 * The whole plugin has been re-written & all the hiliting code is now in a class. You can just use the class anywhere else too for hiliting the code. But to also use the Code Tags to wrap your code & then hilite them, you will need to use all other functions. You can remove the WordPress Filter calls at the end of the plugin & use the rest of the code as you want somewhere else.
    227 * BUGFIX: The issue of multi-line comments not being hilited properly in v2.0 Preview has been sorted out.
    228 
    229 ##### **v2.0 Preview**
    230 
    231 * Implemented the new version of GeSHi core, v1.0.1 which has some bug fixes including the extra quote(") bug that broke the xHTML validation of the code.
    232 * I've created a new language file for ASP(Active Server Pages) which has been added to this release & will also be a part of the next GeSHi release.
    233 * Line numbering is now done through Ordered Lists(<OL>) & the code is xHTML compliant.
    234 * Auto-Formatting disabled for posts that contain the iG:Syntax Hiliter code tags so that your code is good for copy-paste operations.
    235 
    236 ##### **v1.1**
    237 
    238 * Implemented the line numbering of code.
    239 * The code box is now of fixed dimensions without word-wrap & with scrollbars(if required).
    240 
    241 ##### **v1.0**
    242 
    243 * Hilites code between the special tags, all of them differently.
    244 * Uses GeSHi for syntax hiliting.
    245 * Supports HTML, CSS, PHP, JAVA & SQL codes.
  • igsyntax-hiliter/trunk/classes/admin.php

    r1213540 r2719681  
    1212
    1313    /**
    14      * protected constructor, singleton pattern implemented
     14     * Class constructor
    1515     */
    1616    protected function __construct() {
     17
    1718        parent::__construct();
    1819
    1920        $this->_setup_hooks();
    20     }
    21 
    22     protected function _setup_hooks() {
    23         //call function to add options menu item
    24         add_action( 'admin_menu', array( $this, 'add_menu' ) );
    25 
    26         //setup our style/script enqueuing for wp-admin
    27         add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_stuff' ) );
    28 
    29         //setup callback for AJAX on admin page
    30         add_action( 'wp_ajax_ig-sh-save-options', array( $this, 'save_plugin_options' ) );
    31 
    32         //callback to show any migration messages
    33         add_action( 'admin_notices', array( $this, 'show_migration_message' ) );
     21
     22    }
     23
     24    /**
     25     * Method to set up listeners to WP hooks
     26     *
     27     * @return void
     28     */
     29    protected function _setup_hooks() : void {
     30
     31        /*
     32         * Actions
     33         */
     34        add_action( 'admin_menu', [ $this, 'add_menu' ] );
     35        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_stuff' ] );
     36        add_action( 'wp_ajax_ig-sh-save-options', [ $this, 'save_plugin_options' ] );
     37        add_action( 'admin_notices', [ $this, 'maybe_show_migration_message' ] );
     38
     39        /*
     40         * Filters
     41         */
     42        add_filter( 'plugin_action_links', [ $this, 'get_action_links' ], 10, 2 );
     43
    3444    }
    3545
     
    3949     * admin page and then deletes the older version number from DB.
    4050     */
    41     public function show_migration_message() {
     51    public function maybe_show_migration_message() : void {
     52
    4253        if ( get_current_screen()->id !== sprintf( 'settings_page_%s-page', parent::PLUGIN_ID ) ) {
    4354            //not our admin page, bail out
    44             return false;
     55            return;
    4556        }
    4657
    4758        $old_version = round( floatval( get_option( parent::PLUGIN_ID . '-migrated-from', 0 ) ), 1 );
    4859
    49         if ( $old_version > 0 ) {
    50 
    51             if ( $old_version < floatval( IG_SYNTAX_HILITER_VERSION ) ) {
    52 
    53                 printf( '<div class="updated fade"><p>Options migrated successfully from v%f</p></div>', $old_version );
    54 
     60        if ( 0 < $old_version ) {
     61
     62            if ( floatval( IG_SYNTAX_HILITER_VERSION ) > $old_version ) {
     63                printf(
     64                    '<div class="updated fade"><p>Options migrated successfully from v%f</p></div>',
     65                    $old_version
     66                );
    5567            }
    5668
     
    6072        }
    6173
    62         unset( $old_version );
    63     }
    64 
    65     /**
    66      * This function adds plugin's admin page in the Settings menu
    67      */
    68     public function add_menu() {
    69         add_options_page( parent::PLUGIN_NAME . ' Options', parent::PLUGIN_NAME, 'manage_options', parent::PLUGIN_ID . '-page', array( $this, 'admin_page' ) );
    70     }
    71 
    72     /**
    73      * This function constructs the UI for the plugin admin page
    74      */
    75     public function admin_page() {
    76 
    77         echo Helper::render_template( IG_SYNTAX_HILITER_ROOT . '/templates/plugin-options-page.php', array(
    78             'plugin_name'      => parent::PLUGIN_NAME,
    79             'options'          => $this->_option->get_all(),
    80             'strict_mode_opts' => Validate::$strict_mode_values,
    81             'human_time_diff'  => Helper::human_time_diff( time(), ( $this->_get_language_cache_build_time() + parent::LANGUAGES_CACHE_LIFE ) ),
    82         ) );
    83 
    84     }
    85 
    86     /**
    87      * This function is called by WP to handle our AJAX requests
    88      */
    89     public function save_plugin_options() {
     74    }
     75
     76    /**
     77     * Method to add plugin settings page in the Settings menu
     78     *
     79     * @return void
     80     */
     81    public function add_menu() : void {
     82        add_options_page(
     83            sprintf( '%s Options', parent::PLUGIN_NAME ),
     84            parent::PLUGIN_NAME,
     85            'manage_options',
     86            sprintf( '%s-page', parent::PLUGIN_ID ),
     87            [ $this, 'admin_page' ]
     88        );
     89    }
     90
     91    /**
     92     * Method to construct the UI for the plugin settings page
     93     *
     94     * @return void
     95     */
     96    public function admin_page() : void {
     97
     98        Helper::render_template(
     99            sprintf( '%s/templates/plugin-options-page.php', untrailingslashit( IG_SYNTAX_HILITER_ROOT ) ),
     100            [
     101                'plugin_name'      => parent::PLUGIN_NAME,
     102                'options'          => $this->_option->get_all(),
     103                'strict_mode_opts' => Validate::$strict_mode_values,
     104                'human_time_diff'  => Helper::human_time_diff( time(), ( $this->_get_language_cache_build_time() + parent::LANGUAGES_CACHE_LIFE ) ),
     105            ],
     106            true
     107        );
     108
     109    }
     110
     111    /**
     112     * Method to handle our AJAX requests
     113     *
     114     * @return void
     115     */
     116    public function save_plugin_options() : void {
    90117
    91118        if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
    92             return false;
     119            return;
    93120        }
    94121
    95122        $response = new Ajax_Response();
    96123
    97         $response->add_nonce( parent::PLUGIN_ID . '-nonce' );
     124        $response->add_nonce( sprintf( '%s-nonce', parent::PLUGIN_ID ) );
    98125
    99126        //check & see if we have the values
     127        $option_name  = Helper::filter_input( INPUT_POST, 'option_name', FILTER_SANITIZE_STRING );
     128        $option_value = Helper::filter_input( INPUT_POST, 'option_value', FILTER_SANITIZE_STRING );
     129
    100130        if (
    101131            ! check_ajax_referer( parent::PLUGIN_ID . '-nonce', '_ig_sh_nonce', false )
    102             || ! isset( $_POST['option_name'] ) || ! isset( $_POST['option_value'] )
     132            || empty( $option_name ) || empty( $option_value )
    103133        ) {
    104134            $response->add_error( 'Invalid request sent, please refresh the page and try again' );
     
    106136        }
    107137
    108         $input = array(
    109             'option_name'  => sanitize_text_field( strtolower( trim( $_POST['option_name'] ) ) ),
    110             'option_value' => sanitize_text_field( strtolower( trim( $_POST['option_value'] ) ) ),
    111         );
    112 
    113         if ( $input['option_name'] == 'igsh_refresh_languages' && $input['option_value'] == 'rebuild' ) {
     138        $option_name  = sanitize_text_field( strtolower( trim( $option_name ) ) );
     139        $option_value = sanitize_text_field( strtolower( trim( $option_value ) ) );
     140
     141        if ( 'igsh_refresh_languages' === $option_name && 'rebuild' === $option_value ) {
    114142
    115143            //rebuild language file list
     
    119147            $response->add( 'time', Helper::human_time_diff( time(), ( $this->_get_language_cache_build_time() + parent::LANGUAGES_CACHE_LIFE ) ) );
    120148
    121         } elseif ( $this->_option->get( $input['option_name'] ) !== false ) {
    122 
    123             $response->add_success( 'Option Saved successfully' );  //assume option saved successfully
    124 
    125             switch ( $input['option_name'] ) {
     149        } elseif ( $this->_option->get( $option_name ) !== false ) {
     150
     151            $response->add_success( 'Option Saved successfully' );    //assume option saved successfully
     152
     153            switch ( $option_name ) {
     154
    126155                case 'strict_mode':
    127                     $this->_option->save( $input['option_name'], $this->_validate->sanitize_strict_mode_values( $input['option_value'] ) );
     156                    $this->_option->save(
     157                        $option_name,
     158                        $this->_validate->sanitize_strict_mode_values( $option_value )
     159                    );
    128160                    break;
     161
    129162                case 'non_strict_mode':
    130                     $sanitized_language_names = $this->_validate->languages( explode( ',', $input['option_value'] ), array_values( $this->get_languages() ) );
    131                     $this->_option->save( $input['option_name'], $sanitized_language_names );
     163                    $sanitized_language_names = $this->_validate->languages(
     164                        explode( ',', $option_value ),
     165                        array_values( $this->get_languages() )
     166                    );
     167
     168                    $this->_option->save( $option_name, $sanitized_language_names );
    132169
    133170                    unset( $sanitized_language_names );
    134171                    break;
     172
    135173                default:
    136                     if ( ! $this->_validate->is_yesno( $input['option_value'] ) ) {
     174                    if ( ! $this->_validate->is_yesno( $option_value ) ) {
    137175                        $response->add_error( 'Invalid request sent, please refresh the page and try again' );
    138176                        $response->send();
    139177                    } else {
    140                         $this->_option->save( $input['option_name'], $input['option_value'] );
     178                        $this->_option->save( $option_name, $option_value );
    141179                    }
     180
    142181                    break;
     182
    143183            }
    144184
     
    147187        $response->send();
    148188
    149     }   //end save_plugin_options()
    150 
    151     /**
    152      * function to enqueue stuff in wp-admin head
    153      */
    154     public function enqueue_stuff( $hook ) {
     189    }    //end save_plugin_options()
     190
     191    /**
     192     * Method to load assets on settings page in wp-admin
     193     *
     194     * @return void
     195     */
     196    public function enqueue_stuff( $hook ) : void {
    155197
    156198        if ( ! is_admin() || $hook !== sprintf( 'settings_page_%s-page', parent::PLUGIN_ID ) ) {
    157199            //page is not in wp-admin or not our settings page, so bail out
    158             return false;
     200            return;
    159201        }
    160202
    161203        //load stylesheet
    162         wp_enqueue_style( parent::PLUGIN_ID . '-admin', plugins_url( 'assets/css/admin.css', __DIR__ ), false, IG_SYNTAX_HILITER_VERSION );
     204        wp_enqueue_style(
     205            sprintf( '%s-admin', parent::PLUGIN_ID ),
     206            plugins_url( '/assets/css/admin.css', __DIR__ ),
     207            false,
     208            IG_SYNTAX_HILITER_VERSION
     209        );
     210
    163211        //load jQuery::msg stylesheet
    164         wp_enqueue_style( parent::PLUGIN_ID . '-jquery-msg', plugins_url( 'assets/css/jquery.msg.css', __DIR__ ), false, IG_SYNTAX_HILITER_VERSION );
     212        wp_enqueue_style(
     213            sprintf( '%s-jquery-msg', parent::PLUGIN_ID ),
     214            plugins_url( '/assets/css/jquery.msg.css', __DIR__ ),
     215            false,
     216            IG_SYNTAX_HILITER_VERSION
     217        );
    165218
    166219        //load jQuery::center script
    167         wp_enqueue_script( parent::PLUGIN_ID . '-jquery-center', plugins_url( 'assets/js/jquery.center.min.js', __DIR__ ), array( 'jquery' ), IG_SYNTAX_HILITER_VERSION );
     220        wp_enqueue_script(
     221            sprintf( '%s-jquery-center', parent::PLUGIN_ID ),
     222            plugins_url( '/assets/js/jquery.center.min.js', __DIR__ ),
     223            [ 'jquery' ],
     224            IG_SYNTAX_HILITER_VERSION
     225        );
     226
    168227        //load jQuery::msg script
    169         wp_enqueue_script( parent::PLUGIN_ID . '-jquery-msg', plugins_url( 'assets/js/jquery.msg.min.js', __DIR__ ), array( parent::PLUGIN_ID . '-jquery-center' ), IG_SYNTAX_HILITER_VERSION );
     228        wp_enqueue_script(
     229            sprintf( '%s-jquery-msg', parent::PLUGIN_ID ),
     230            plugins_url( '/assets/js/jquery.msg.min.js', __DIR__ ),
     231            [ sprintf( '%s-jquery-center', parent::PLUGIN_ID ) ],
     232            IG_SYNTAX_HILITER_VERSION
     233        );
     234
    170235        //load our script
    171         wp_enqueue_script( parent::PLUGIN_ID . '-admin', plugins_url( 'assets/js/admin.js', __DIR__ ), array( parent::PLUGIN_ID . '-jquery-msg' ), IG_SYNTAX_HILITER_VERSION );
     236        wp_enqueue_script(
     237            sprintf( '%s-admin', parent::PLUGIN_ID ),
     238            plugins_url( '/assets/js/admin.js', __DIR__ ),
     239            [ sprintf( '%s-jquery-msg', parent::PLUGIN_ID ) ],
     240            IG_SYNTAX_HILITER_VERSION
     241        );
    172242
    173243        //some vars in JS that we'll need
    174         wp_localize_script( parent::PLUGIN_ID . '-admin', 'ig_sh', array(
    175             'plugins_url' => untrailingslashit( plugins_url( '', __DIR__ ) ) . '/',
    176             'nonce' => wp_create_nonce( parent::PLUGIN_ID . '-nonce' ),
    177         ) );
    178 
    179     }
    180 
    181 }   //end of class
    182 
     244        wp_localize_script(
     245            sprintf( '%s-admin', parent::PLUGIN_ID ),
     246            'ig_sh',
     247            [
     248                'plugins_url' => plugins_url( '/', __DIR__ ),
     249                'nonce'       => wp_create_nonce( sprintf( '%s-nonce', parent::PLUGIN_ID ) ),
     250            ]
     251        );
     252
     253    }
     254
     255    /**
     256     * Method to add link to plugin settings page in the plugin listing once plugin has been activated.
     257     *
     258     * @param array  $links
     259     * @param string $file
     260     *
     261     * @return array
     262     */
     263    public function get_action_links( array $links, string $file ) : array {
     264
     265        if ( IG_SYNTAX_HILITER_BASENAME !== $file ) {
     266            return $links;
     267        }
     268
     269        $settings_page_slug = sprintf(
     270            'options-general.php?page=%s-page',
     271            parent::PLUGIN_ID
     272        );
     273
     274        $settings_link = sprintf(
     275            '<a href="%s" aria-label="Configure %s">Settings</a>',
     276            esc_url( admin_url( $settings_page_slug ) ),
     277            esc_attr( parent::PLUGIN_NAME )
     278        );
     279
     280        array_unshift( $links, $settings_link );
     281
     282        return $links;
     283
     284    }
     285
     286}    //end of class
    183287
    184288//EOF
  • igsyntax-hiliter/trunk/classes/ajax-response.php

    r1213527 r2719681  
    33 * Class for creating and sending an AJAX response
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 *
    77 * @since 2015-07-22
     
    2020     * @var array Array of data to be sent to browser
    2121     */
    22     protected $_response = array(
     22    protected $_response = [
    2323        'nonce' => '',
    24         'error' => 1,   //lets assume there's error
     24        'error' => 1,    //lets assume there's error
    2525        'msg'   => '',
    26     );
     26    ];
    2727
    2828    /**
    29      * constructor
     29     * Class constructor
    3030     */
    3131    public function __construct() {}
    3232
    3333    /**
    34      * Function to add data to be sent to browser
     34     * Method to add data to be sent to browser
    3535     *
    36      * @param string $key Key name to identify data
    37      * @param string $value Data value
     36     * @param string $key   Key name to identify data
     37     * @param mixed  $value Data value
     38     *
    3839     * @return void
    3940     */
    40     public function add( $key, $value ) {
     41    public function add( string $key, $value ) : void {
    4142        $this->_response[ sanitize_key( $key ) ] = $value;
    4243    }
    4344
    4445    /**
    45      * Function to nonce to be sent to browser
     46     * Method to generate nonce to be sent to browser
    4647     *
    4748     * @param string $key Key to generate nonce
     49     *
    4850     * @return void
    4951     */
    50     public function add_nonce( $key ) {
    51         if ( empty( $key ) || ! is_string( $key ) ) {
     52    public function add_nonce( string $key ) : void {
     53
     54        if ( empty( $key ) ) {
    5255            return;
    5356        }
    5457
    5558        $this->add( 'nonce', wp_create_nonce( $key ) );
     59
    5660    }
    5761
    5862    /**
    59      * Function to add a message to be sent to browser
     63     * Method to add a message to be sent to browser
    6064     *
    6165     * @param string $message
    62      * @param string $type Type of message, either SUCCESS or ERROR
    63      * @return boolean Returns TRUE if message added successfully else FALSE
     66     * @param string $type    Type of message, either SUCCESS or ERROR
     67     *
     68     * @return bool Returns TRUE if message added successfully else FALSE
    6469     */
    65     public function add_message( $message, $type = 'success' ) {
    66         if ( empty( $message ) || ! is_string( $message ) ) {
     70    public function add_message( string $message, string $type = 'success' ) : bool {
     71
     72        if ( empty( $message ) ) {
    6773            return false;
    6874        }
    6975
    70         $type = ( strtolower( trim( $type ) ) === 'success' ) ? 'success' : 'error';    //type can only be either one
     76        $type = ( strtolower( trim( $type ) ) === 'success' ) ? 'success' : 'error';    //type can only be either one
    7177
    72         $this->add( 'msg', sprintf( self::MESSAGE_TEMPLATE, esc_attr( $type ), esc_html( $message ) ) );
     78        $this->add(
     79            'msg',
     80            sprintf(
     81                self::MESSAGE_TEMPLATE,
     82                esc_attr( $type ),
     83                esc_html( $message ) )
     84        );
    7385
    7486        return true;
     87
    7588    }
    7689
    7790    /**
    78      * Function to add error message to be sent to browser
     91     * Method to add error message to be sent to browser
    7992     *
    8093     * @param string $message
     94     *
    8195     * @return void
    8296     */
    83     public function add_error( $message ) {
     97    public function add_error( string $message ) : void {
    8498        if ( $this->add_message( $message, 'error' ) ) {
    8599            $this->add( 'error', 1 );
     
    88102
    89103    /**
    90      * Function to add success message to be sent to browser
     104     * Method to add success message to be sent to browser
    91105     *
    92106     * @param string $message
     107     *
    93108     * @return void
    94109     */
    95     public function add_success( $message ) {
     110    public function add_success( string $message ) : void {
    96111        if ( $this->add_message( $message, 'success' ) ) {
    97112            $this->add( 'error', 0 );
     
    100115
    101116    /**
    102      * Function to send data to browser
     117     * Method to send data to browser
    103118     *
    104119     * @return void
    105120     */
    106     public function send() {
     121    public function send() : void {
     122
    107123        header( "Content-Type: application/json" );
    108124
    109         echo json_encode( $this->_response );       //we want json
     125        echo wp_json_encode( $this->_response );    //we want json
    110126
    111         wp_die( '', '', 200 );  //send 200 HTTP Status back
     127        wp_die( '', '', 200 );    //send 200 HTTP Status back
     128
    112129    }
    113130
    114 }   //end of class
    115 
     131}    //end of class
    116132
    117133//EOF
  • igsyntax-hiliter/trunk/classes/base.php

    r1213527 r2719681  
    55 * inherited, on its own it doesn't do anything
    66 *
    7  * @author Amit Gupta <http://amitgupta.in/>
     7 * @author Amit Gupta <https://amitgupta.in/>
    88 */
    99
    1010namespace iG\Syntax_Hiliter;
    1111
    12 abstract class Base extends Singleton {
     12use \iG\Syntax_Hiliter\Traits\Singleton;
     13
     14abstract class Base {
     15
     16    use Singleton;
    1317
    1418    /**
    1519     * @var const Class constant containing unique plugin ID
    1620     */
    17     const PLUGIN_ID = "ig-syntax-hiliter";
     21    const PLUGIN_ID = 'ig-syntax-hiliter';
     22
    1823    /**
    1924     * @var const Class constant containing plugin name for display
    2025     */
    21     const PLUGIN_NAME = "iG:Syntax Hiliter";
     26    const PLUGIN_NAME = 'iG:Syntax Hiliter';
     27
    2228    /**
    2329     * @var const Class constant containing life of language name cache in seconds
    2430     */
    25     const LANGUAGES_CACHE_LIFE = WEEK_IN_SECONDS;   //1 week
    26     /**
    27      * @var String Static var containing path to GeSHi language file folder
    28      */
    29     protected static $__dirs;
    30 
    31     /**
    32      * @var iG\Syntax_Hiliter\Option
     31    const LANGUAGES_CACHE_LIFE = WEEK_IN_SECONDS;    // 1 week
     32
     33    /**
     34     * @var array Array containing paths to GeSHi language file folders
     35     */
     36    protected $__dirs;
     37
     38    /**
     39     * @var \iG\Syntax_Hiliter\Option
    3340     */
    3441    protected $_option;
    35     /**
    36      * @var iG\Syntax_Hiliter\Validate
     42
     43    /**
     44     * @var \iG\Syntax_Hiliter\Validate
    3745     */
    3846    protected $_validate;
     
    4250     */
    4351    protected function __construct() {
     52
    4453        $this->_setup_dir_paths();
    4554
     
    6069         */
    6170        $this->get_languages();
    62     }
    63 
    64     /**
    65      * This function scans the validated language file directories, retrieves the
    66      * names of all files with .php extension and returns an array with unique
    67      * file names
    68      */
    69     public function build_language_list() {
    70         if ( empty( self::$__dirs ) ) {
    71             return false;
    72         }
    73 
    74         $tags = array();
    75 
    76         foreach ( self::$__dirs as $dir ) {
    77             $tags = array_merge( $tags, glob( $dir . "/*.php" ) );
    78         }
    79 
    80         $tags = array_unique( array_filter( array_map( array( $this, '_file_to_tag_name' ), $tags ) ) );
     71
     72    }
     73
     74    /**
     75     * This method scans the validated language file directories, retrieves the
     76     * names of all language files and returns an array with unique file names.
     77     *
     78     * @return array
     79     */
     80    public function get_uncached_languages() : array {
     81
     82        $tags = [];
     83
     84        if ( empty( $this->__dirs ) ) {
     85            return $tags;
     86        }
     87
     88        foreach ( $this->__dirs as $dir ) {
     89            $pattern = sprintf(
     90                '%s/*.php',
     91                untrailingslashit( $dir )
     92            );
     93
     94            $tags = array_merge( $tags, glob( $pattern ) );
     95        }
     96
     97        $tags = array_unique(
     98            array_filter(
     99                array_map( [ $this, '_file_to_tag_name' ], $tags )
     100            )
     101        );
    81102
    82103        sort( $tags );
    83104
    84         $this->_set_language_cache_build_time();    //set language list built time
     105        $this->_set_language_cache_build_time();    //set language list built time
    85106
    86107        return $tags;
    87     }
    88 
    89     /**
    90      * This function uses WP TLC class to fetch the language file names from supported directories
    91      * and schedules a refresh of the transient cache. It also allows a force rebuild of
    92      * transient cache via the optional $force_rebuild parameter.
    93      */
    94     public function get_languages( $force_rebuild = 'no' ) {
     108
     109    }
     110
     111    /**
     112     * Method to get cached array of language file names from supported directories.
     113     *
     114     * @param string $force_rebuild Optional parameter to force rebuild the cache
     115     *
     116     * @return array
     117     *
     118     * @throws \ErrorException
     119     */
     120    public function get_languages( string $force_rebuild = 'no' ) : array {
     121
    95122        $force_rebuild = ( ! $this->_validate->is_yesno( $force_rebuild ) ) ? 'no' : strtolower( $force_rebuild );
    96123
    97         $cache = new Cache( self::PLUGIN_ID . '-languages' );
    98 
    99         if ( $force_rebuild == 'yes' ) {
    100             $cache->delete();   //delete existing cache so we'll get fresh one below
    101         }
    102 
    103         $languages = $cache->updates_with( array( $this, 'build_language_list' ) )
     124        $cache = Cache::create( self::PLUGIN_ID . '-languages' );
     125
     126        if ( 'yes' === $force_rebuild ) {
     127            $cache->delete();    //delete existing cache so we'll get fresh one below
     128        }
     129
     130        $languages = $cache->updates_with( [ $this, 'get_uncached_languages' ] )
    104131                            ->expires_in( self::LANGUAGES_CACHE_LIFE )
    105132                            ->get();
    106133
    107134        if ( empty( $languages ) ) {
    108             return;
     135            return [];
    109136        }
    110137
    111138        return array_combine( $languages, $languages );
     139
    112140    }
    113141
     
    115143     * Returns the timestamp when language file name cache was last built. If no timestamp
    116144     * found then it sets current timestamp and returns that.
    117      */
    118     protected function _get_language_cache_build_time() {
     145     *
     146     * @return int
     147     */
     148    protected function _get_language_cache_build_time() : int {
     149
    119150        $time = get_option( self::PLUGIN_ID . '-lang-time' );
    120151
    121         if ( $time === false ) {
     152        if ( false === $time ) {
    122153            return $this->_set_language_cache_build_time();
    123154        }
    124155
    125156        return $time;
     157
    126158    }
    127159
    128160    /**
    129161     * Sets the timestamp to mark when language file name cache was built
    130      */
    131     protected function _set_language_cache_build_time() {
     162     *
     163     * @return int
     164     */
     165    protected function _set_language_cache_build_time() : int {
     166
    132167        $time = time();
    133168
     
    135170
    136171        return $time;
     172
    137173    }
    138174
    139175    /**
    140176     * Returns the file name of a php file from the physical file path
    141      */
    142     protected function _file_to_tag_name( $file_path ) {
    143 
    144         $file_path = str_replace( '\\', '/', $file_path );
    145 
    146         if ( empty( $file_path ) || strpos( $file_path, '.php' ) === false ) {
    147 
    148             $file_path = '';
    149 
     177     *
     178     * @return string
     179     */
     180    protected function _file_to_tag_name( string $path ) : string {
     181
     182        $path = str_replace( '\\', '/', $path );
     183
     184        if ( empty( $path ) || substr( $path, -4 ) !== '.php' ) {
     185            $path = '';
    150186        } else {
    151187
    152             $file_path = explode( '/', $file_path );
    153             $file_path = explode( '.', array_pop( $file_path ) );
    154 
    155             array_pop( $file_path );
    156 
    157             $file_path = implode( '.', $file_path );
    158 
    159         }
    160 
    161         return $file_path;
     188            $path = explode( '/', $path );
     189            $path = explode( '.', array_pop( $path ) );
     190
     191            array_pop( $path );
     192
     193            $path = implode( '.', $path );
     194
     195        }
     196
     197        return $path;
    162198
    163199    }
     
    169205     * @return void
    170206     */
    171     protected function _maybe_migrate_older_settings() {
     207    protected function _maybe_migrate_older_settings() : void {
    172208        Migrate::get_instance()->settings( $this );
    173209    }
     
    178214     * and child theme directories, and whichever exists is stored.
    179215     */
    180     protected function _setup_dir_paths() {
    181 
    182         self::$__dirs['geshi'] = dirname( __DIR__ ) . "/geshi";                 //setup geshi dir path
    183         self::$__dirs['theme'] = get_template_directory() . "/geshi";           //setup geshi dir path in current theme folder
    184         self::$__dirs['child_theme'] = get_stylesheet_directory() . "/geshi";   //setup geshi dir path in child theme folder
    185 
    186         if ( ! is_dir( self::$__dirs['child_theme'] ) || self::$__dirs['theme'] == self::$__dirs['child_theme'] ) {
    187 
    188             unset( self::$__dirs['child_theme'] );  //no geshi dir in child theme
    189 
    190         }
    191 
    192         if ( ! is_dir( self::$__dirs['theme'] ) ) {
    193 
    194             unset( self::$__dirs['theme'] );    //no geshi dir in current theme
    195 
    196         }
    197 
    198     }
    199 
    200 }   //end of class
    201 
     216    protected function _setup_dir_paths() : void {
     217
     218        //setup geshi dir path
     219        $this->__dirs['geshi'] = sprintf(
     220            '%s/geshi',
     221            untrailingslashit( IG_SYNTAX_HILITER_ROOT )
     222        );
     223
     224        $theme_path = sprintf(
     225            '%s/geshi',
     226            untrailingslashit( get_template_directory() )
     227        );
     228
     229        $child_theme_path =sprintf(
     230            '%s/geshi',
     231            untrailingslashit( get_stylesheet_directory() )
     232        );
     233
     234        //setup geshi dir path in current theme folder
     235        if ( is_dir( $theme_path ) ) {
     236            $this->__dirs['theme'] = $theme_path;
     237        }
     238
     239        //setup geshi dir path in child theme folder
     240        if ( $theme_path !== $child_theme_path && is_dir( $child_theme_path ) ) {
     241            $this->__dirs['child_theme'] = $child_theme_path;
     242        }
     243
     244        unset( $child_theme_path, $theme_path );
     245
     246    }
     247
     248}    //end of class
    202249
    203250//EOF
  • igsyntax-hiliter/trunk/classes/cache.php

    r1213527 r2719681  
    88namespace iG\Syntax_Hiliter;
    99
     10use \Exception;
    1011use \ErrorException;
    1112
     
    1415    const KEY_PREFIX = 'igsh-cache-';
    1516
     17    const MIN_EXPIRY = 120;    // 2 minutes
     18
    1619    protected $_key;
    17     protected $_expiry = 1800;  //30 minutes, default expiry
     20
     21    protected $_expiry = 1800;    // 30 minutes, default expiry
     22
    1823    protected $_callback;
    19     protected $_params = array();
     24
     25    protected $_params = [];
    2026
    2127    protected $_cache;
    2228
    23     protected $_default_storage_format = array(
    24         'expiry'   => 0,
    25         'callback' => '',
    26         'params'   => array(),
    27         'data'     => '',
    28     );
    29 
    30     /**
    31      * @param String $cache_key A mixed character string for use as unique identifier for current dataset stored in cache
    32      */
    33     public function __construct( $cache_key ) {
    34 
    35         if ( empty( $cache_key ) || ! is_string( $cache_key ) ) {
    36 
    37             throw new ErrorException( 'Cache key is required to create ' . __CLASS__ . ' object' );
     29    protected $_default_storage_format = [
     30        'expiry' => 0,
     31        'data'   => '',
     32    ];
     33
     34    /**
     35     * Class constructor
     36     *
     37     * @param string $cache_key A string for use as unique identifier for current dataset stored in cache
     38     *
     39     * @throws \ErrorException
     40     */
     41    public function __construct( string $cache_key ) {
     42
     43        if ( empty( $cache_key ) ) {
     44
     45            throw new ErrorException(
     46                sprintf(
     47                    'Cache key is required to create %s object',
     48                    __CLASS__
     49                )
     50            );
    3851
    3952        }
     
    4659     * Factory method to facilitate single call data fetch using method chaining
    4760     *
    48      * @param String $cache_key A mixed character string for use as unique identifier for current dataset stored in cache
    49      * @return iG\Syntax_Hiliter\Cache
    50      */
    51     public static function create( $cache_key ) {
    52         $class = __CLASS__;
    53 
    54         return new $class( $cache_key );
     61     * @param string $cache_key A string for use as unique identifier for current dataset stored in cache
     62     *
     63     * @return \iG\Syntax_Hiliter\Cache
     64     *
     65     * @throws \ErrorException
     66     */
     67    public static function create( string $cache_key ) : self {
     68        return new self( $cache_key );
    5569    }
    5670
     
    5872     * This function is for deleting the cache
    5973     *
    60      * @return iG\Syntax_Hiliter\Cache
    61      */
    62     public function delete() {
     74     * @return \iG\Syntax_Hiliter\Cache
     75     */
     76    public function delete() : self {
    6377        delete_option( $this->_key );
    6478
     
    6983     * This function accepts the cache expiry
    7084     *
    71      * @return iG\Syntax_Hiliter\Cache
    72      */
    73     public function expires_in( $expiry ) {
    74         $expiry = intval( $expiry );
    75 
    76         if ( $expiry > 0 ) {
    77             $this->_expiry = $expiry;
    78         }
    79 
    80         unset( $expiry );
     85     * @return \iG\Syntax_Hiliter\Cache
     86     */
     87    public function expires_in( int $expiry ) : self {
     88
     89        if ( 0 < $expiry ) {
     90            $this->_expiry = max( $expiry, self::MIN_EXPIRY );
     91        }
    8192
    8293        return $this;
     94
    8395    }
    8496
     
    8698     * This function accepts the callback from which data is to be received
    8799     *
    88      * @return iG\Syntax_Hiliter\Cache
    89      */
    90     public function updates_with( $callback, array $params = array() ) {
    91 
    92         if ( empty( $callback ) || ! is_callable( $callback ) ) {
    93 
     100     * @param callable $callback
     101     * @param array    $params
     102     *
     103     * @return \iG\Syntax_Hiliter\Cache
     104     *
     105     * @throws \ErrorException
     106     */
     107    public function updates_with( callable $callback, array $params = [] ) : self {
     108
     109        if ( empty( $callback ) ) {
    94110            throw new ErrorException( 'Callback passed is not callable' );
    95 
    96111        }
    97112
    98113        $this->_callback = $callback;
    99         $this->_params = $params;
     114        $this->_params   = $params;
    100115
    101116        return $this;
     
    125140    }
    126141
    127     protected function _get_cache() {
    128 
    129         if ( is_bool( $this->_cache ) || ( is_array( $this->_cache ) && ! empty( $this->_cache ) ) ) {
     142    /**
     143     * Method to grab the cache array from storage
     144     *
     145     * @return array
     146     */
     147    protected function _get_cache() : array {
     148
     149        if ( is_array( $this->_cache ) && ! empty( $this->_cache ) ) {
    130150            return $this->_cache;
    131151        }
     
    137157        }
    138158
    139         return false;
    140 
    141     }
    142 
    143     protected function _set_cache() {
     159        return [];
     160
     161    }
     162
     163    /**
     164     * Method to save cache array in storage
     165     *
     166     * @return void
     167     */
     168    protected function _set_cache() : void {
     169
     170        if ( ! is_array( $this->_cache ) || empty( $this->_cache ) ) {
     171            return;
     172        }
     173
    144174        //delete existing cache
    145175        $this->delete();
     
    148178        //we want it autoloaded hence the use of update_option()
    149179        update_option( $this->_key, $this->_cache );
    150     }
    151 
    152     protected function _has_expired() {
     180
     181    }
     182
     183    /**
     184     * Method to check if cache has expired or not
     185     *
     186     * @return bool
     187     */
     188    protected function _has_expired() : bool {
     189
    153190        $cache = $this->_get_cache();
    154191
    155         if ( is_array( $cache ) && ! empty( $cache ) ) {
    156 
    157             if ( ! empty( $cache['expiry'] ) && time() < intval( $cache['expiry'] ) ) {
    158                 //cache has not expired, yet
    159                 return false;
    160             }
    161 
     192        if ( isset( $cache['expiry'] ) && time() < intval( $cache['expiry'] ) ) {
     193            //cache has not expired, yet
     194            return false;
    162195        }
    163196
    164197        //cache has expired
    165198        return true;
    166     }
    167 
    168     protected function _refresh_cache() {
    169         $cache = array(
    170             'expiry'   => ( time() + $this->_expiry ),
    171             'callback' => $this->_callback,
    172             'params'   => $this->_params,
    173             'data'     => '',
    174         );
     199
     200    }
     201
     202    /**
     203     * Method which refreshes cached data
     204     *
     205     * @return void
     206     *
     207     * @throws \ErrorException
     208     */
     209    protected function _refresh_cache() : void {
     210
     211        $cache = [
     212            'expiry' => ( time() + $this->_expiry ),
     213            'data'   => '',
     214        ];
    175215
    176216        /*
     
    185225        try {
    186226            $cache['data'] = call_user_func_array( $this->_callback, $this->_params );
    187         } catch( \Exception $e ) {
    188             $cache['data'] = false;
     227        } catch( Exception $e ) {
     228            $cache['data'] = '';
    189229        }
    190230
     
    193233        $this->_set_cache();
    194234
    195         unset( $cache );
    196     }
    197 
    198 }   //end of class
    199 
     235    }
     236
     237}    //end of class
    200238
    201239//EOF
  • igsyntax-hiliter/trunk/classes/frontend.php

    r1213527 r2719681  
    44 * for the plugin, hilite code etc.
    55 *
    6  * @author Amit Gupta <http://amitgupta.in/>
     6 * @author Amit Gupta <https://amitgupta.in/>
    77 */
    88
     
    1414
    1515    /**
    16      * @var Constant Class constant contains the template for generating tokens for hilited code
     16     * @var const Class constant contains the template for generating tokens for hilited code
    1717     */
    1818    const TOKEN = '<pre class="igsh-token" id="%s"></pre>';
    19     /**
    20      * @var Constant Class constant contains the max length allowed for a file's path
     19
     20    /**
     21     * @var const Class constant contains the max length allowed for a file's path
    2122     */
    2223    const FILE_PATH_LENGTH = 30;
     
    2526     * @var array Contains hilited code blocks associated to unique tokens
    2627     */
    27     protected $__hilited_code = array();
     28    protected $__hilited_code = [];
    2829
    2930    /**
    3031     * @var array Contains IDs/labels etc for use in code boxes
    3132     */
    32     protected $__code_box = array(
     33    protected $__code_box = [
    3334        'counter'   => 0,
    3435        'id_prefix' => 'ig-sh-',
    3536        'plain'     => 'plain text',
    3637        'html'      => 'hilited code',
    37     );
    38 
    39     /**
    40      * @var Array Contains filters on which code hiliting is not allowed & code blocks are to be stripped
    41      */
    42     protected $__no_code_hilite_filters = array(
    43         'excerpt_save_pre', 'get_the_excerpt', 'the_excerpt', 'the_excerpt_rss'
    44     );
    45 
    46     /**
    47      * @var Array Contains filters on which code hiliting is allowed
    48      */
    49     protected $__code_hilite_filters = array(
    50         'the_content'
    51     );
    52 
    53     /**
    54      * @var Array Contains filters on which Github Gist is not allowed & code blocks are to be stripped
    55      */
    56     protected $__no_github_gist_filters = array(
    57         'excerpt_save_pre', 'get_the_excerpt', 'the_excerpt', 'the_excerpt_rss'
    58     );
    59 
    60     /**
    61      * @var Array Contains filters on which Github Gist is allowed
    62      */
    63     protected $__github_gist_filters = array(
    64         'the_content'
    65     );
    66 
    67     /**
    68      * @var Array Contains file names for GeSHi language files associated with expected tag names
    69      */
    70     protected $__geshi_language = array(
     38    ];
     39
     40    /**
     41     * @var array Contains filters on which code hiliting is not allowed & code blocks are to be stripped
     42     */
     43    protected $__no_code_hilite_filters = [
     44        'excerpt_save_pre',
     45        'get_the_excerpt',
     46        'the_excerpt',
     47        'the_excerpt_rss',
     48    ];
     49
     50    /**
     51     * @var array Contains filters on which code hiliting is allowed
     52     */
     53    protected $__code_hilite_filters = [
     54        'the_content',
     55    ];
     56
     57    /**
     58     * @var array Contains filters on which Github Gist is not allowed & code blocks are to be stripped
     59     */
     60    protected $__no_github_gist_filters = [
     61        'excerpt_save_pre',
     62        'get_the_excerpt',
     63        'the_excerpt',
     64        'the_excerpt_rss',
     65    ];
     66
     67    /**
     68     * @var array Contains filters on which Github Gist is allowed
     69     */
     70    protected $__github_gist_filters = [
     71        'the_content',
     72    ];
     73
     74    /**
     75     * @var array Contains file names for GeSHi language files associated with expected tag names
     76     */
     77    protected $__languages = [
    7178        'as'   => 'actionscript',
    7279        'html' => 'html4strict',
    7380        'js'   => 'javascript',
    74     );
    75 
    76     /**
    77      * @var Array Contains display names for some languages, like C# for csharp, VB.NET for vbnet
    78      */
    79     protected $__geshi_language_display = array(
     81    ];
     82
     83    /**
     84     * @var array Contains display names for some languages, like C# for csharp, VB.NET for vbnet
     85     */
     86    protected $__language_display_names = [
    8087        'cpp'         => 'C++',
    8188        'cfm'         => 'Cold Fusion',
     
    8693        'html'        => 'HTML',
    8794        'html4strict' => 'HTML4',
    88     );
    89 
    90     /**
    91      * @var boolean Flag to determine whether CSS & JS assets are to be enqueued or not
     95    ];
     96
     97    /**
     98     * @var bool Flag to determine whether CSS & JS assets are to be enqueued or not
    9299     */
    93100    protected $__enqueue_assets = false;
    94101
    95102    /**
    96      * @var boolean Flag to determine whether JS assets are to be enqueued or not
     103     * @var bool Flag to determine whether JS assets are to be enqueued or not
    97104     */
    98105    protected $__enqueue_js_assets = false;
    99106
    100107    /**
    101      * protected constructor, singleton pattern implemented
     108     * Class constructor
    102109     */
    103110    protected function __construct() {
     111
    104112        parent::__construct();
    105113
    106114        $this->_build_tags_array();
     115        $this->_determine_filters();
     116
    107117        $this->_setup_hooks();
     118
    108119    }
    109120
    110     protected function _setup_hooks() {
    111 
    112         //setup our style/script enqueuing for front-end
    113         add_action( 'wp_footer', array( $this, 'enqueue_stuff' ), 1 );
     121    /**
     122     * Method to separate out filters on which hiliting of code is to be set up or not
     123     *
     124     * @return void
     125     */
     126    protected function _determine_filters() : void {
    114127
    115128        //setup code hilite handling for comments
    116         if ( $this->_option->get( 'hilite_comments' ) == 'yes' ) {
     129        if ( $this->_option->get( 'hilite_comments' ) === 'yes' ) {
    117130            //gotta hilite
    118131            $this->__code_hilite_filters[] = 'comment_text';
     
    123136
    124137        //setup Github Gist embed in comments
    125         if ( $this->_option->get( 'gist_in_comments' ) == 'yes' ) {
     138        if ( $this->_option->get( 'gist_in_comments' ) === 'yes' ) {
    126139            //gotta embed
    127140            $this->__github_gist_filters[] = 'comment_text';
     
    131144        }
    132145
     146    }
     147
     148    /**
     149     * Method to set up listeners to WP hooks
     150     *
     151     * @return void
     152     */
     153    protected function _setup_hooks() : void {
     154
     155        // set on 'wp_footer' hook because we won't know whether to enqueue assets
     156        // or not before post content is parsed
     157        add_action( 'wp_footer', [ $this, 'enqueue_stuff' ], 1 );
     158
    133159        //queue up calls for code hiliting
    134160        foreach ( $this->__code_hilite_filters as $filter ) {
     161
    135162            //to grab code blocks to be hilited & replace them with tokens
    136             add_filter( $filter, array( $this, 'parse_shortcodes' ), 2 );
     163            add_filter( $filter, [ $this, 'parse_shortcodes' ], 3 );
     164
    137165            //replace code block tokens with hilited code
    138             add_filter( $filter, array( $this, 'add_hilited_code_blocks' ), 100 );
     166            add_filter( $filter, [ $this, 'replace_tokens_with_code_blocks' ], 99 );
     167
    139168        }
    140169
    141170        //queue up calls for stripping out code blocks
    142171        foreach ( $this->__no_code_hilite_filters as $filter ) {
    143             add_filter( $filter, array( $this, 'parse_shortcodes' ), 2 );
     172            add_filter( $filter, [ $this, 'parse_shortcodes' ], 2 );
    144173        }
    145174
    146175        //queue up calls for Github Gist embed
    147176        foreach ( $this->__github_gist_filters as $filter ) {
    148             add_filter( $filter, array( $this, 'parse_github_gist_tags' ), 9 );
     177            add_filter( $filter, [ $this, 'parse_github_shortcodes' ], 10 );
    149178        }
    150179
    151180        //queue up calls for stripping out Github Gist code blocks
    152181        foreach ( $this->__no_github_gist_filters as $filter ) {
    153             add_filter( $filter, array( $this, 'parse_github_gist_tags' ), 9 );
    154         }
    155 
    156     }   //end _setup_hooks()
    157 
    158     /**
    159      * function to enqueue stuff in front-end head
    160      */
    161     public function enqueue_stuff() {
     182            add_filter( $filter, [ $this, 'parse_github_shortcodes' ], 9 );
     183        }
     184
     185    }    //end _setup_hooks()
     186
     187    /**
     188     * Method to enqueue assets on front-end
     189     *
     190     * @return void
     191     */
     192    public function enqueue_stuff() : void {
    162193
    163194        if ( is_admin() || ! $this->__enqueue_assets ) {
    164             //page is in wp-admin, so bail out
    165             return false;
    166         }
    167 
    168         if ( $this->_option->get( 'fe-styles' ) == 'yes' ) {
     195            // page is in wp-admin or it has no code blocks to hilite
     196            // bail out
     197            return;
     198        }
     199
     200        if ( $this->_option->get( 'fe-styles' ) === 'yes' ) {
    169201            //load stylesheet
    170             wp_enqueue_style( parent::PLUGIN_ID, plugins_url( 'assets/css/front-end.css', __DIR__ ), false, IG_SYNTAX_HILITER_VERSION );
    171         }
    172 
    173         if ( $this->__enqueue_js_assets === true ) {
     202            wp_enqueue_style(
     203                parent::PLUGIN_ID,
     204                Helper::get_asset_url( '/css/front-end.css' ),
     205                false,
     206                IG_SYNTAX_HILITER_VERSION
     207            );
     208        }
     209
     210        if ( true === $this->__enqueue_js_assets ) {
    174211
    175212            //load utility lib
    176             wp_enqueue_script( 'igeek-utils', plugins_url( 'assets/js/igeek-utils.js', __DIR__ ), array(), IG_SYNTAX_HILITER_VERSION );
     213            wp_enqueue_script(
     214                'igeek-utils',
     215                Helper::get_asset_url( '/js/igeek-utils.js' ),
     216                [],
     217                IG_SYNTAX_HILITER_VERSION
     218            );
     219
    177220            //load script
    178             wp_enqueue_script( parent::PLUGIN_ID, plugins_url( 'assets/js/front-end.js', __DIR__ ), array( 'igeek-utils', 'jquery' ), IG_SYNTAX_HILITER_VERSION );
     221            wp_enqueue_script(
     222                parent::PLUGIN_ID,
     223                Helper::get_asset_url( '/js/front-end.js' ),
     224                [ 'igeek-utils', 'jquery' ],
     225                IG_SYNTAX_HILITER_VERSION
     226            );
    179227
    180228            //vars for front-end js
    181             wp_localize_script( parent::PLUGIN_ID, 'ig_syntax_hiliter', array(
    182                 'label' => array(
    183                     'plain' => $this->__code_box['plain'],
    184                     'html'  => $this->__code_box['html']
    185                 )
    186             ) );
     229            wp_localize_script(
     230                parent::PLUGIN_ID,
     231                'ig_syntax_hiliter',
     232                [
     233                    'label' => [
     234                        'plain' => $this->__code_box['plain'],
     235                        'html'  => $this->__code_box['html'],
     236                    ],
     237                ]
     238            );
    187239
    188240        }
     
    191243
    192244    /**
    193      * This function builds the array for shorthand tags for all language files
     245     * Method to build the array for shorthand tags for all language files
    194246     * available in supported directories
    195      */
    196     protected function _build_tags_array() {
     247     *
     248     * @return void
     249     *
     250     * @throws \ErrorException
     251     */
     252    protected function _build_tags_array() : void {
     253
    197254        $languages = $this->get_languages();
    198255
     
    201258        }
    202259
    203         $keys = array_unique( array_merge( array_keys( $this->__geshi_language ), array_keys( $languages ) ) );
    204 
    205         $tags = array();
     260        $keys = array_unique(
     261            array_merge(
     262                array_keys( $this->__languages ),
     263                array_keys( $languages )
     264            )
     265        );
     266
     267        $tags = [];
    206268
    207269        foreach( $keys as $key ) {
    208             if ( array_key_exists( $key, $this->__geshi_language ) ) {
    209                 $tags[$key] = $this->__geshi_language[$key];
     270
     271            if ( array_key_exists( $key, $this->__languages ) ) {
     272                $tags[ $key ] = $this->__languages[ $key ];
    210273                continue;
    211274            }
    212275
    213276            if ( array_key_exists( $key, $languages ) ) {
    214                 $tags[$key] = $languages[$key];
     277                $tags[ $key ] = $languages[ $key ];
    215278                continue;
    216279            }
     280
    217281        }
    218282
    219283        ksort( $tags );
    220284
    221         $this->__geshi_language = $tags;
    222 
    223         unset( $tags, $keys, $languages );
     285        $this->__languages = $tags;
     286
    224287    }
    225288
    226289    /**
    227      * This function is used to truncate file path to required length
    228      *
    229      * @param string $path Path to file
    230      * @param int $length Length in number of characters
     290     * Method to truncate file path to required length
     291     *
     292     * @param string $path   Path to file
     293     * @param int    $length Length in number of characters
     294     *
    231295     * @return string Truncated file path
    232296     */
    233     protected function _snip_file_path( $path, $length ) {
    234 
    235         $length = intval( $length );
    236         $length = ( $length < 0 || $length > self::FILE_PATH_LENGTH ) ? self::FILE_PATH_LENGTH : $length;
     297    protected function _snip_file_path( string $path, int $length ) : string {
     298
     299        $length = abs( $length );
     300        $length = min( self::FILE_PATH_LENGTH, $length );
    237301
    238302        if ( strlen( $path ) <= $length ) {
     
    240304        }
    241305
    242         $path = "&hellip;" . substr( $path, intval( 2 - $length ) );
     306        $path = sprintf(
     307            '&hellip;%s',
     308            substr( $path, ( 2 - $length ) )
     309        );
    243310
    244311        return $path;
     
    247314
    248315    /**
    249      * This function is used to put hilited code in a presentable box
    250      */
    251     protected function _get_code_in_box( $code, $attrs ) {
     316     * Method to put hilited code in a presentable box
     317     *
     318     * @param string $code
     319     * @param array  $attrs
     320     *
     321     * @return string
     322     *
     323     * @throws \ErrorException
     324     */
     325    protected function _get_code_in_box( string $code, array $attrs = [] ) : string {
     326
    252327        if ( empty( $code ) ) {
    253             return;
    254         }
    255 
    256         $code_box = '';
     328            return '';
     329        }
     330
     331        $attrs['file'] = ( empty( $attrs['file'] ) ) ? '' : $attrs['file'];
     332
    257333        $this->__code_box['counter']++;
    258334
    259         return Helper::render_template( IG_SYNTAX_HILITER_ROOT . '/templates/frontend-code-box.php', array(
    260             'id_prefix'  => $this->__code_box['id_prefix'],
    261             'counter'    => $this->__code_box['counter'],
    262             'plain_text' => $this->__code_box['plain'],
    263             'file_path'  => $this->_snip_file_path( $attrs['file'], self::FILE_PATH_LENGTH ),
    264             'attrs'      => $attrs,
    265             'code'       => $code,
    266         ) );
     335        return Helper::render_template(
     336            sprintf( '%s/templates/frontend-code-box.php', untrailingslashit( IG_SYNTAX_HILITER_ROOT ) ),
     337            [
     338                'id_prefix'  => $this->__code_box['id_prefix'],
     339                'counter'    => $this->__code_box['counter'],
     340                'plain_text' => $this->__code_box['plain'],
     341                'file_path'  => $this->_snip_file_path( $attrs['file'], self::FILE_PATH_LENGTH ),
     342                'attrs'      => $attrs,
     343                'code'       => $code,
     344            ]
     345        );
     346
    267347    }
    268348
    269349    /**
    270      * This function is used to hilite code using Geshi
    271      */
    272     protected function _get_hilited_code( $attrs = array(), $code = '' ) {
    273 
    274         if ( ( empty( $code ) || ! is_string( $code ) ) ) {
    275             return;
    276         }
    277 
    278         extract( shortcode_atts( array(
    279             'strict_mode' => '',
    280             'language'    => '',
    281             'firstline'   => 1,
    282             'highlight'   => 0,
    283             'file'        => '',
    284             'gutter'      => '',
    285             'plaintext'   => '',
    286             'toolbar'     => '',
    287             'lang'        => 'code',
    288             'num'         => 1,
    289         ), $attrs ) );
    290 
    291         $num = intval( $num );
    292         $firstline = ( intval( $firstline ) < 1 ) ? 1 : intval( $firstline );
    293         $firstline = ( $num > $firstline ) ? $num : $firstline;
    294 
    295         $language = ( empty( $language ) ) ? $lang : $language;
     350     * Method to hilite code using Geshi and get the HTML
     351     *
     352     * @param array  $attrs
     353     * @param string $code
     354     *
     355     * @return string
     356     *
     357     * @throws \ErrorException
     358     */
     359    protected function _get_hilited_code( array $attrs = [], string $code = '' ) : string {
     360
     361        if ( empty( $code ) ) {
     362            return '';
     363        }
     364
     365        extract(
     366            shortcode_atts(
     367                [
     368                    'strict_mode' => '',
     369                    'language'    => 'code',
     370                    'firstline'   => 1,
     371                    'highlight'   => 0,
     372                    'file'        => '',
     373                    'gutter'      => '',
     374                    'plaintext'   => '',
     375                    'toolbar'     => '',
     376                    'lang'        => 'code',
     377                    'num'         => 1,
     378                ],
     379                $attrs
     380            )
     381        );
     382
     383        $num       = absint( $num );
     384        $firstline = absint( $firstline );
     385        $firstline = max( 1, $num, $firstline );
     386        $language  = ( empty( $language ) && ! empty( $lang ) ) ? $lang : $language;
     387
    296388        unset( $lang );
    297389
    298         $language = sanitize_title( $language );
    299         $language_display = ( array_key_exists( $language, $this->__geshi_language_display ) ) ? $this->__geshi_language_display[ $language ] : $language;
    300         $language = ( array_key_exists( $language, $this->__geshi_language ) ) ? $this->__geshi_language[ $language ] : $language;
     390        $language         = sanitize_title( $language );
     391        $language_display = $this->__language_display_names[ $language ] ?? $language;
     392        $language         = $this->__languages[ $language ] ?? $language;
    301393
    302394        $non_strict_mode_languages = $this->_option->get( 'non_strict_mode' );
     
    304396        if ( ! empty( $strict_mode ) ) {
    305397            $strict_mode = strtolower( trim( $strict_mode ) );
    306         } elseif ( in_array( $language, $non_strict_mode_languages ) ) {
     398        } elseif ( in_array( $language, $non_strict_mode_languages, true ) ) {
    307399            $strict_mode = 'never';
    308400        } else {
     
    325417        unset( $strict_mode );
    326418
    327         $file = strip_tags( $file );
    328         $gutter = ( ! $this->_validate->is_yesno( $gutter ) ) ? '' : strtolower( trim( $gutter ) );
    329 
     419        $file      = sanitize_text_field( wp_strip_all_tags( $file ) );
     420        $gutter    = ( ! $this->_validate->is_yesno( $gutter ) ) ? '' : strtolower( trim( $gutter ) );
    330421        $plaintext = ( ! $this->_validate->is_yesno( $plaintext ) ) ? '' : strtolower( trim( $plaintext ) );
    331         $toolbar = ( ! $this->_validate->is_yesno( $toolbar ) ) ? '' : strtolower( trim( $toolbar ) );
     422        $toolbar   = ( ! $this->_validate->is_yesno( $toolbar ) ) ? '' : strtolower( trim( $toolbar ) );
    332423
    333424        $code = trim( $code );
     
    335426        if ( strpos( $highlight, ',' ) === false && strpos( $highlight, '-' ) === false ) {
    336427
    337             $highlight = ( intval( $highlight ) < 0 ) ? 0 : array( intval( $highlight ) );
     428            $highlight = [ absint( $highlight ) ];
    338429
    339430        } else {
    340431
    341432            $highlight = explode( ',', $highlight );
    342 
    343             $ranges = array();
     433            $ranges    = [];
    344434
    345435            foreach ( $highlight as $num ) {
    346436
    347437                if ( strpos( $num, '-' ) === false ) {
    348                     $ranges[] = $num;
     438                    $ranges[] = absint( $num );
    349439                    continue;
    350440                }
    351441
    352                 $range = explode( '-', $num );
    353                 $range_start = intval( $range[0] );
    354                 $range_end = intval( $range[1] );
    355 
    356                 if ( $range_end == $range_start ) {
     442                $range       = explode( '-', $num );
     443                $range_start = absint( $range[0] );
     444                $range_end   = absint( $range[1] );
     445
     446                if ( $range_end === $range_start ) {
    357447                    $ranges[] = $range_start;
    358448                    continue;
    359449                } elseif ( $range_end < $range_start ) {
    360                     $range_start = intval( $range[1] );
    361                     $range_end = intval( $range[0] );
     450                    $range_start = absint( $range[1] );
     451                    $range_end   = absint( $range[0] );
    362452                }
    363453
    364                 $range = range( $range_start, $range_end );
     454                $range  = range( $range_start, $range_end );
    365455                $ranges = array_merge( $ranges, $range );
    366456
     
    375465            unset( $ranges );
    376466
    377             $highlight = array_unique( array_map( 'intval', $highlight ) ); //make 'em all int & vaporize duplicates
     467            //make 'em all int & vaporize duplicates
     468            $highlight = array_unique( array_map( 'intval', $highlight ) );
     469
    378470            sort( $highlight, SORT_NUMERIC );
    379471
    380472        }
    381473
    382         $is_language = true;    //assume we have a valid language
    383         $dir_path = parent::$__dirs['geshi'];       //set default path to our geshi dir
    384 
    385         if ( function_exists( 'file_exists' ) ) {
    386 
    387             foreach ( parent::$__dirs as $key => $dir ) {
    388 
    389                 if ( file_exists( $dir . '/' . $language . '.php' ) ) {
    390                     $is_language = true;    //language file exists
    391                     $dir_path = $dir;   //set language file dir
    392                     break;
    393                 }
    394 
    395                 $is_language = false;   //language file doesn't exist
    396 
     474        $is_language = true;    //assume we have a valid language
     475        $dir_path    = $this->__dirs['geshi'];    //set default path to our geshi dir
     476
     477        foreach ( $this->__dirs as $key => $dir ) {
     478
     479            $language_file_path = sprintf(
     480                '%s/%s.php',
     481                untrailingslashit( $dir ),
     482                $language
     483            );
     484
     485            if ( Helper::is_file_path_valid( $language_file_path ) ) {
     486                $is_language = true;    //language file exists
     487                $dir_path    = $dir;    //set language file dir
     488                break;
    397489            }
    398490
    399         }
    400 
    401         if ( $is_language !== true ) {
     491            $is_language = false;    //language file doesn't exist
     492
     493        }
     494
     495        if ( true !== $is_language ) {
    402496            //we don't have a valid language specified in the tag by user
    403497            //set the code block to be hilited using the 'code' lang file
    404             $language = 'code';
     498            $language         = 'code';
    405499            $language_display = $language;
    406500        }
    407501
    408         $options = array(
     502        $options = [
    409503            'show_line_numbers' => Helper::yesno_to_bool( $this->_option->get( 'show_line_numbers' ) ),
    410504            'show_plain_text'   => Helper::yesno_to_bool( $this->_option->get( 'plain_text' ) ),
    411505            'show_toolbar'      => Helper::yesno_to_bool( $this->_option->get( 'toolbar' ) ),
    412         );
     506        ];
    413507
    414508        /*
     
    440534
    441535        if ( ! empty( $geshi_error ) ) {
    442             return; //there's GeSHi error, bail from this function
    443         }
    444 
    445         $geshi->set_header_type( GESHI_HEADER_NONE );               //don't need any wrapper around hilited code, we've our own
    446         $geshi->enable_line_numbers( GESHI_NORMAL_LINE_NUMBERS );   //show line numbers
    447 
    448         if ( $options['show_line_numbers'] === false ) {
    449             $geshi->set_line_style( 'list-style: none;' );  //hide line numbers
    450         }
    451 
    452         $geshi->start_line_numbers_at( $firstline );        //where to start line numbering from
    453         $geshi->set_case_keywords( GESHI_CAPS_NO_CHANGE );  //don't mess with our code
    454         $geshi->set_tab_width( 4 );                         //if you don't know this then go stuff your head in sand, coding is not for you!
    455 
    456         $geshi->enable_keyword_links( Helper::yesno_to_bool( $this->_option->get( 'link_to_manual' ) ) );
    457 
    458         if ( is_array( $highlight ) ) {
    459             $geshi->highlight_lines_extra( $highlight );                            //show these lines as special
    460             $geshi->set_highlight_lines_extra_style( 'background-color:#FFFFBC;' ); //set bg color for special lines
    461         }
     536            return '';    //there's GeSHi error, bail out
     537        }
     538
     539        $geshi->set_header_type( GESHI_HEADER_NONE );    //don't need any wrapper around hilited code, we have our own
     540        $geshi->enable_line_numbers( GESHI_NORMAL_LINE_NUMBERS );    //show line numbers
     541
     542        if ( false === $options['show_line_numbers'] ) {
     543
     544            // hide line numbers
     545            // doing it this way so that line hiliting still works, otherwise it would not
     546            $geshi->set_line_style( 'list-style: none;' );
     547
     548        }
     549
     550        $geshi->start_line_numbers_at( $firstline );    //where to start line numbering from
     551        $geshi->set_case_keywords( GESHI_CAPS_NO_CHANGE );    //don't mess with our code
     552        $geshi->set_tab_width( 4 );    //if you don't know this then go stuff your head in sand, coding is not for you!
     553
     554        $geshi->enable_keyword_links(
     555            Helper::yesno_to_bool(
     556                $this->_option->get( 'link_to_manual' )
     557            )
     558        );
     559
     560        $geshi->highlight_lines_extra( $highlight );    //show these lines as special
     561        $geshi->set_highlight_lines_extra_style( 'background-color:#FFFFBC;' );    //set bg color for special lines
    462562
    463563        $geshi->enable_strict_mode( $geshi_mode );
    464564
    465         $hilited_code = $geshi->parse_code();   //get it all
     565        $hilited_code = $geshi->parse_code();    //get it all
    466566
    467567        if ( empty( $hilited_code ) ) {
    468             return;     //geshi banged up somewhere, we have nothing to show for all the hardwork above :(
     568            return '';    //geshi banged up somewhere, we have nothing to show for all the hardwork above :(
    469569        }
    470570
     
    475575         * to set it to FALSE again.
    476576         */
    477         if ( $options['show_plain_text'] === true ) {
     577        if ( true === $options['show_plain_text'] ) {
    478578            $this->__enqueue_js_assets = $options['show_plain_text'];
    479579        }
    480580
    481         return $this->_get_code_in_box( $hilited_code, array(
    482             'plain_text' => $options['show_plain_text'],
    483             'toolbar'    => $options['show_toolbar'],
    484             'file'       => $file,
    485             'language'   => $language_display,
    486         ) );
    487 
    488     }   //end _get_hilited_code()
    489 
    490     /*
    491      * This function is called for parsing a code hiliting tag setup in
    492      * $this->parse_shortcodes().
    493      * It hiltes the code, generates a unique token for the code, stores hilited
    494      * code in $this->__hilited_code with token as key and returns the token
     581        return $this->_get_code_in_box(
     582            $hilited_code,
     583            [
     584                'plain_text' => $options['show_plain_text'],
     585                'toolbar'    => $options['show_toolbar'],
     586                'file'       => $file,
     587                'language'   => $language_display,
     588            ]
     589        );
     590
     591    }    //end _get_hilited_code()
     592
     593    /**
     594     * Method to parse code hiliting tag set up in self::parse_shortcodes().
     595     * It hiltes the code, generates a unique token for the hilited code, stores
     596     * hilited code in a class var with token as key and returns the token
    495597     * to replace the tag in content which can later be replaced with
    496598     * the hilited code.
    497      */
    498     public function tokenize_code_block( $atts, $code = '', $tag = false ) {
     599     *
     600     * @param array  $atts
     601     * @param string $code
     602     * @param string $tag
     603     *
     604     * @return string
     605     *
     606     * @throws \ErrorException
     607     */
     608    public function replace_code_blocks_with_tokens( array $atts, string $code = '', string $tag = '' ) : string {
    499609
    500610        if ( empty( $tag ) || empty( $code ) ) {
    501             return $code;   //nothing to do, bail out
     611            return $code;    //nothing to do, bail out
    502612        }
    503613
    504614        //check if we've to strip code block
    505         if ( in_array( current_filter(), $this->__no_code_hilite_filters ) ) {
    506             return '';  //code hiliting not allowed for this filter, so remove code block
    507         }
    508 
    509         if ( array_key_exists( $tag, $this->__geshi_language ) ) {
    510             $atts['language'] = $tag;   //shorthand tag used, so tag name is language
    511         }
    512 
    513         ksort( $atts ); //sort attribute array on keys
    514 
    515         $shortcode_md5 = md5( serialize( array(
    516             'text' => $code,
    517             'atts' => $atts
    518         ) ) );  //create unique token key for this code block with these attributes
    519 
    520         if ( ! array_key_exists( $shortcode_md5, $this->__hilited_code ) ) {
    521 
    522             $this->__hilited_code[ $shortcode_md5 ] = $this->_get_hilited_code( $atts, $code ); //save hilited code in array
     615        if ( in_array( current_filter(), $this->__no_code_hilite_filters, true ) ) {
     616            return '';    //code hiliting not allowed for this filter, so remove code block
     617        }
     618
     619        if ( ! empty( $this->__languages[ $tag ] ) ) {
     620            $atts['language'] = $tag;    //shorthand tag used, so tag name is language
     621        }
     622
     623        ksort( $atts );    //sort attribute array on keys
     624
     625        $shortcode_md5 = md5(    //create unique token key for this code block with these attributes
     626            wp_json_encode(
     627                [
     628                    'text' => $code,
     629                    'atts' => $atts,
     630                ]
     631            )
     632        );
     633
     634        if ( empty( $this->__hilited_code[ $shortcode_md5 ] ) ) {
     635
     636            // save hilited code in array
     637            $this->__hilited_code[ $shortcode_md5 ] = $this->_get_hilited_code( $atts, $code );
    523638
    524639            if ( empty( $this->__hilited_code[ $shortcode_md5 ] ) ) {
    525                 //banged up somewhere, we didn't get anything, unset key in array & return empty
     640
     641                // messed up somewhere, we didn't get anything
     642                // unset key in array and return empty
    526643                unset( $this->__hilited_code[ $shortcode_md5 ] );
    527                 return;
     644
     645                return '';
     646
    528647            }
    529648
    530649        }
    531650
    532         $shortcode_token = sprintf( self::TOKEN, $shortcode_md5 );  //generate token
     651        $shortcode_token = sprintf( self::TOKEN, $shortcode_md5 );    //generate token HTML
    533652
    534653        unset( $shortcode_md5 );
    535654
    536         $this->__enqueue_assets = true; //yes we should enqueue CSS/JS assets, we have hilited code on page
    537 
    538         return $shortcode_token;    //return unique token, we'll replace it with hilited code later
    539     }   //end tokenize_code_block()
    540 
    541     /**
    542      * This function is called back by a filter early on and sets up shortcode
     655        $this->__enqueue_assets = true;    //yes we should enqueue CSS/JS assets, we have hilited code on page
     656
     657        // return unique token, we'll replace it with hilited code later
     658        return $shortcode_token;
     659
     660    }    //end replace_code_blocks_with_tokens()
     661
     662    /**
     663     * Method called back by a filter early on and sets up shortcode
    543664     * processing for code hiliting tags
    544      */
    545     public function parse_shortcodes( $content ) {
     665     *
     666     * @param string $content
     667     *
     668     * @return string
     669     */
     670    public function parse_shortcodes( string $content= '' ) : string {
    546671
    547672        if ( is_admin() ) {
     
    551676        global $shortcode_tags;
    552677
    553         //keep a copy of the registered shortcodes as we'd need to restore them later
     678        // keep a copy of the registered shortcodes as we need to restore them later
    554679        $original_shortcode_tags = $shortcode_tags;
    555680
    556         remove_all_shortcodes();    //clean the slate, we want only our shortcodes to be processed right now
    557 
    558         $tags = array_merge( array_keys( $this->__geshi_language ), array( 'sourcecode' ) );
     681        remove_all_shortcodes();    //clean the slate, we want only our shortcodes to be processed right now
     682
     683        $tags = array_merge( array_keys( $this->__languages ), [ 'sourcecode' ] );
    559684
    560685        foreach ( $tags as $tag ) {
    561             add_shortcode( $tag, array( $this, 'tokenize_code_block' ) );
    562         }
    563 
    564         $content = do_shortcode( $content );    //parse our shortcodes
    565 
    566         $shortcode_tags = $original_shortcode_tags; //restore original shortcodes
     686            add_shortcode( $tag, [ $this, 'replace_code_blocks_with_tokens' ] );
     687        }
     688
     689        $content = do_shortcode( $content );    //parse our shortcodes
     690
     691        $shortcode_tags = $original_shortcode_tags;    //restore original shortcodes
    567692
    568693        unset( $tags, $original_shortcode_tags );
     
    573698
    574699    /**
    575      * This function is called back by a filter in the last and replaces the unique
    576      * tokens with corresponding blocks of hilited code stored in $this->__hilited_code
    577      */
    578     public function add_hilited_code_blocks( $content ) {
     700     * Method, called back by a filter towards the end, to replace code hilite
     701     * tokens with corresponding blocks of hilited code
     702     *
     703     * @param string $content
     704     *
     705     * @return string
     706     */
     707    public function replace_tokens_with_code_blocks( string $content ) : string {
     708
    579709        if ( is_admin() || empty( $this->__hilited_code ) ) {
    580710            return $content;
     
    582712
    583713        /*
    584          * Run a loop on $this->__hilited_code and replace all tokens in $content
    585          * with appropriate blocks of hilited code.
     714         * Loop over our tokens array and replace all tokens
     715         * with appropriate blocks of hilited code
    586716         */
    587717        foreach ( $this->__hilited_code as $key => $code_block ) {
    588718
    589             $token = sprintf( self::TOKEN, $key );
     719            $token   = sprintf( self::TOKEN, $key );
    590720            $content = str_replace( $token, $code_block, $content );
    591721
     
    593723
    594724        return $content;
     725
    595726    }
    596727
    597728    /**
    598      * This function is called on a filter and it sets up [github] shortcode parsing
    599      */
    600     public function parse_github_gist_tags( $content ) {
     729     * Method, called on a filter, to set up [github] shortcode parsing
     730     *
     731     * @param string $content
     732     *
     733     * @return string
     734     */
     735    public function parse_github_shortcodes( string $content ) : string {
     736
    601737        if ( is_admin() ) {
    602738            return $content;
     
    605741        global $shortcode_tags;
    606742
    607         //keep a copy of the registered shortcodes as we'd need to restore them later
     743        // keep a copy of the registered shortcodes as we need to restore them later
    608744        $original_shortcode_tags = $shortcode_tags;
    609745
    610         remove_all_shortcodes();    //clean the slate, we want only our shortcodes to be processed right now
    611 
    612         //setup shortcode for github gist
    613         add_shortcode( 'github', array( $this, 'parse_github_gist_tag' ) );
    614 
    615         $content = do_shortcode( $content );    //parse our shortcodes
    616 
    617         $shortcode_tags = $original_shortcode_tags; //restore original shortcodes
     746        remove_all_shortcodes();    //clean the slate, we want only our shortcodes to be processed right now
     747
     748        // setup shortcode for github gist
     749        add_shortcode( 'github', [ $this, 'get_github_gist_embed' ] );
     750
     751        $content        = do_shortcode( $content );    //parse our shortcodes
     752        $shortcode_tags = $original_shortcode_tags;    //restore original shortcodes
    618753
    619754        unset( $original_shortcode_tags );
    620755
    621756        return $content;
     757
    622758    }
    623759
    624760    /**
    625      * This function handles the [github] tag
    626      */
    627     public function parse_github_gist_tag( $attrs, $content = '' ) {
    628 
    629         extract( shortcode_atts( array(
    630             'id'   => 0,
    631             'gist' => '',
    632         ), $attrs ) );
    633 
    634         $gist = parse_url( esc_url( untrailingslashit( $gist ) ), PHP_URL_PATH );
     761     * Method to return Github Gist embed
     762     *
     763     * @param array  $attrs
     764     * @param string $content
     765     *
     766     * @return string
     767     */
     768    public function get_github_gist_embed( array $attrs, string $content = '' ) : string {
     769
     770        extract(
     771            shortcode_atts(
     772                [
     773                    'id'   => 0,
     774                    'gist' => '',
     775                ],
     776                $attrs
     777            )
     778        );
     779
     780        $gist = wp_parse_url( untrailingslashit( $gist ), PHP_URL_PATH );
    635781
    636782        if ( ! empty( $gist ) ) {
     
    650796
    651797        if ( empty( $id ) ) {
    652             return;
    653         }
    654 
    655         $gist = sprintf( 'https://gist.github.com/%s', esc_url( sanitize_user( $id, true ) ) );
     798            return '';
     799        }
     800
     801        $gist = sprintf(
     802            'https://gist.github.com/%s',
     803            sanitize_user( $id, true )
     804        );
    656805
    657806        $returnable = sprintf( '<script src="%s.js"></script>', esc_url( $gist ) );
    658807
    659         if ( in_array( current_filter(), $this->__no_github_gist_filters ) ) {
    660             $returnable = sprintf( 'Github Gist: <a href="%s" rel="nofollow">%s</a>', esc_url( $gist ), esc_html( $gist ) );
     808        if ( in_array( current_filter(), $this->__no_github_gist_filters, true ) ) {
     809
     810            $returnable = sprintf(
     811                '<div class="igsh-gist"><span class="igsh-gist__label">Github Gist:</span> <a href="%s" rel="nofollow">%s</a></div>',
     812                esc_url( $gist ),
     813                esc_html( $gist )
     814            );
     815
    661816        }
    662817
    663818        return $returnable;
    664819
    665     }   //end parse_github_gist_tag()
    666 
    667 }   //end of class
    668 
     820    }    //end get_github_gist_embed()
     821
     822}    //end of class
    669823
    670824//EOF
  • igsyntax-hiliter/trunk/classes/geshi.php

    r1213527 r2719681  
    595595     * @since 1.0.0
    596596     */
    597     function GeSHi($source = '', $language = '', $path = '') {
     597    function __construct($source = '', $language = '', $path = '') {
    598598        if (!empty($source)) {
    599599            $this->set_source($source);
     
    47344734            static $callback_2;
    47354735            if (!isset($callback_2)) {
    4736                 $callback_2 = create_function('$matches', 'return "[" . str_replace("|", "", $matches[1]) . "]";');
     4736                $callback_2 = function( $matches ) {
     4737                    return '[' . str_replace('|', '', $matches[1]) . ']';
     4738                };
    47374739            }
    47384740            $list = preg_replace_callback('#\(\?\:((?:.\|)+.)\)#', $callback_2, $list);
     
    47734775}
    47744776
    4775 ?>
     4777//EOF
  • igsyntax-hiliter/trunk/classes/helper.php

    r1213527 r2719681  
    33 * Class containing collection of helper methods.
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 */
    77
     
    1616     *
    1717     * @param array $array_to_check Array which is to be checked
    18      * @return boolean Returns TRUE if the array is associative else FALSE. Even a single numeric key would make this function return FALSE.
    19      */
    20     public static function is_associative_array( array $array_to_check ) {
     18     *
     19     * @return bool Returns TRUE if the array is associative else FALSE. Even a single numeric key would make this function return FALSE.
     20     */
     21    public static function is_associative_array( array $array_to_check ) : bool {
    2122        return ! (bool) count( array_filter( array_keys( $array_to_check ), 'is_numeric' ) );
    2223    }
    2324
    2425    /**
     26     * Method to check for existence of a file
     27     *
     28     * @param string $path Physical path of the file which is to be checked
     29     *
     30     * @return bool Returns TRUE if file path is valid else FALSE
     31     */
     32    public static function is_file_path_valid( string $path ) : bool {
     33        return ( ! empty( $path ) && file_exists( $path ) && validate_file( $path ) === 0 );
     34    }
     35
     36    /**
    2537     * Method to render a template and return the markup
    2638     *
    2739     * @param string $template File path to the template file
    28      * @param array $vars Associative array of values which are to be injected into the template. The array keys become var names and key values respective var values.
    29      * @return string Template markup ready for output
    30      */
    31     public static function render_template( $template, array $vars = array() ) {
     40     * @param array  $vars     Associative array of values which are to be injected into the template. The array keys become var names and key values respective var values.
     41     * @param bool   $output   Optional - Set to TRUE to print out parsed template content, FALSE to return it as string
     42     *
     43     * @return string|void
     44     *
     45     * @throws \ErrorException
     46     */
     47    public static function render_template( string $template, array $vars = [], bool $output = false ) {
    3248
    3349        if ( empty( $template ) ) {
     
    3551        }
    3652
    37         if ( ! file_exists( $template ) ) {
    38             throw new ErrorException( 'Template ' . basename( $template ) . ' does not exist' );
     53        if ( ! static::is_file_path_valid( $template ) ) {
     54            throw new ErrorException(
     55                sprintf(
     56                    'Template %s does not exist',
     57                    basename( $template )
     58                )
     59            );
    3960        }
    4061
     
    4768        ob_start();
    4869        require $template;
    49         return ob_get_clean();
    50 
    51     }
    52 
    53     /**
    54      * This method returns the URL of an asset if relative path to asset is passed else
    55      * the URL to assets folder.
    56      *
    57      * @param string $asset_path Optional asset path relative from assets folder
     70        $html = ob_get_clean();
     71
     72        if ( true === $output ) {
     73            echo $html;    // phpcs:ignore This is ignored because any escaping to be done should be done in the template itself.
     74            return;
     75        }
     76
     77        return $html;
     78
     79    }
     80
     81    /**
     82     * Method to remove forward slash from the beginning of a string
     83     *
     84     * @param string $path String from which forward slash is to be removed from beginning
     85     *
     86     * @return string String with forward slash removed from beginning
     87     */
     88    public static function unleadingslashit( string $path ) : string {
     89        return ltrim( $path, '/' );
     90    }
     91
     92    /**
     93     * Method to add one forward slash at the beginning of a string
     94     *
     95     * @param string $path String to which forward slash is to be added at beginning
     96     *
     97     * @return string String with forward slash added at beginning
     98     */
     99    public static function leadingslashit( string $path ) : string {
     100        return sprintf( '/%s', static::unleadingslashit( $path ) );
     101    }
     102
     103    /**
     104     * Method to get the URL of an asset if relative path to asset is passed else the URL to assets folder.
     105     *
     106     * @param string $path Optional asset path relative from assets folder
     107     *
    58108     * @return string URL to asset or asset folder
    59109     */
    60     public static function get_asset_url( $asset_path = '' ) {
    61         return plugins_url( sprintf( '/assets/%s', ltrim( $asset_path, '/' ) ), dirname( __DIR__ ) );
    62     }
    63 
    64     public static function human_time_diff( $from = 0, $to = 0 ) {
    65 
    66         $from = intval( $from );
    67         $to = ( intval( $to ) < 1 ) ? time() : intval( $to );
    68 
    69         $divs = array(
     110    public static function get_asset_url( string $path = '' ) : string {
     111        return plugins_url(
     112            sprintf( '/assets/%s', static::unleadingslashit( $path ) ),
     113            __DIR__
     114        );
     115    }
     116
     117    /**
     118     * Method to get difference between two timestamps in a humanly readable format
     119     *
     120     * @param int $from
     121     * @param int $to
     122     *
     123     * @return string
     124     */
     125    public static function human_time_diff( int $from = 0, int $to = 0 ) : string {
     126
     127        $to = ( 1 > $to ) ? time() : $to;
     128
     129        $divs = [
    70130            'second' => 60,
    71131            'minute' => 60,
     
    74134            'week'   => ( 30 / 7 ),
    75135            'month'  => 12,
    76         );
     136        ];
    77137
    78138        $in_future = ( $to > $from );
    79 
    80         $diff = abs( intval( $from - $to ) );
    81 
     139        $diff      = abs( intval( $from - $to ) );
    82140        $diff_unit = 'year';
    83141
     
    110168     *
    111169     * @param array $default Array containing default values which are to be overridden
    112      * @param array $new Array containing new values
     170     * @param array $new     Array containing new values
     171     *
    113172     * @return array An array containing new values from $new which override existing values in $default
    114173     */
    115     public static function array_merge( array $default = array(), array $new = array() ) {
     174    public static function array_merge( array $default = [], array $new = [] ) : array {
    116175
    117176        if ( empty( $default ) ) {
    118             return false;
     177            return [];
    119178        }
    120179
     
    143202     *
    144203     * @param bool $value
     204     *
    145205     * @return string
    146206     */
    147207    public static function bool_to_yesno( $value ) {
     208
    148209        if ( ! is_bool( $value ) ) {
    149210            return $value;
    150211        }
    151212
    152         $value = ( $value === true ) ? 'yes' : 'no';
     213        $value = ( true === $value ) ? 'yes' : 'no';
    153214
    154215        return $value;
     216
    155217    }
    156218
     
    160222     *
    161223     * @param string $value
     224     *
    162225     * @return bool
    163226     */
    164227    public static function yesno_to_bool( $value ) {
     228
    165229        if ( ! is_string( $value ) ) {
    166230            return $value;
     
    170234
    171235        return $value;
    172     }
    173 
    174 }   //end of class
    175 
    176 
     236
     237    }
     238
     239    /**
     240     * Improved version of PHP's inbuilt filter_input() which works well on PHP CLI
     241     * as well which PHP default method does not.
     242     *
     243     * @param int    $type          One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV
     244     * @param string $variable_name Name of a variable to get
     245     * @param int    $filter        The ID of the filter to apply
     246     * @param null   $options       Filter to apply
     247     *
     248     * @return mixed|bool|null Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set.
     249     *
     250     * @since 2017-10-05 Amit Gupta
     251     */
     252    public static function filter_input( int $type, string $variable_name, int $filter = FILTER_DEFAULT, $options = null ) {
     253
     254        if ( 'cli' !== php_sapi_name() ) {
     255
     256            /*
     257             * Code is not running on PHP CLI and we are in clear.
     258             * Use the PHP method and bail out.
     259             */
     260            switch ( $filter ) {
     261
     262                case FILTER_SANITIZE_STRING:
     263                    $sanitized_variable = sanitize_text_field( filter_input( $type, $variable_name, $filter ) );
     264                    break;
     265
     266                default:
     267                    $sanitized_variable = filter_input( $type, $variable_name, $filter, $options );
     268                    break;
     269
     270            }
     271
     272            return $sanitized_variable;
     273
     274        }
     275
     276        /*
     277         * Code is running on PHP CLI and INPUT_SERVER returns NULL
     278         * even for set vars when run on CLI
     279         * @see https://bugs.php.net/bug.php?id=49184
     280         *
     281         * This is a workaround for that bug till its resolved in PHP binary
     282         * which doesn't look to be anytime soon. This is a friggin' 10 year old bug.
     283         */
     284
     285        $input             = '';
     286        $allowed_html_tags = wp_kses_allowed_html( 'post' );
     287
     288        /*
     289         * Marking the switch() block below to be ignored by PHPCS
     290         * because PHPCS squawks on using superglobals like $_POST or $_GET
     291         * directly but it can't be helped in this case as this code
     292         * is running on CLI.
     293         */
     294
     295        // phpcs:disable
     296
     297        switch( $type ) {
     298
     299            case INPUT_GET:
     300                if ( ! isset( $_GET[ $variable_name ] ) ) {
     301                    return null;
     302                }
     303
     304                $input = wp_kses( $_GET[ $variable_name ], $allowed_html_tags );
     305                break;
     306
     307            case INPUT_POST:
     308                if ( ! isset( $_POST[ $variable_name ] ) ) {
     309                    return null;
     310                }
     311
     312                $input = wp_kses( $_POST[ $variable_name ], $allowed_html_tags );
     313                break;
     314
     315            case INPUT_COOKIE:
     316                if ( ! isset( $_COOKIE[ $variable_name ] ) ) {
     317                    return null;
     318                }
     319
     320                $input = wp_kses( $_COOKIE[ $variable_name ], $allowed_html_tags );
     321                break;
     322
     323            case INPUT_SERVER:
     324                if ( ! isset( $_SERVER[ $variable_name ] ) ) {
     325                    return null;
     326                }
     327
     328                $input = wp_kses( $_SERVER[ $variable_name ], $allowed_html_tags );
     329                break;
     330
     331            case INPUT_ENV:
     332                if ( ! isset( $_ENV[ $variable_name ] ) ) {
     333                    return null;
     334                }
     335
     336                $input = wp_kses( $_ENV[ $variable_name ], $allowed_html_tags );
     337                break;
     338
     339            default:
     340                return null;
     341                break;
     342
     343        }    // end switch()
     344
     345        // phpcs:enable
     346
     347        return filter_var( $input, $filter );
     348
     349    }    //end filter_input()
     350
     351}    //end of class
    177352
    178353//EOF
  • igsyntax-hiliter/trunk/classes/ig-syntax-hiliter-gatekeeper.php

    r1213527 r2719681  
    33 * Gatekeeper class for the plugin which loads plugin only if minimum requirements are satisfied.
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 *
    77 * @since 2015-07-26
     
    1111final class iG_Syntax_Hiliter_Gatekeeper {
    1212
    13     const MIN_PHP_VERSION_REQUIRED = '5.3.0';
     13    const MIN_PHP_VERSION_REQUIRED = '7.4.0';
    1414
    1515    /**
     
    2929
    3030    /**
     31     * Factory method to initialize the class
     32     *
     33     * @return \iG_Syntax_Hiliter_Gatekeeper
     34     */
     35    public static function activate() {
     36
     37        $class = get_called_class();
     38
     39        return ( new $class() );
     40
     41    }
     42
     43    /**
    3144     * Check if plugin's minimum requirements are satisfied or not. If they are then
    3245     * Gatekeeper can grant a pass else deny passage.
     
    3548     */
    3649    private function _has_pass() {
     50
    3751        if ( version_compare( phpversion(), self::MIN_PHP_VERSION_REQUIRED ) == -1 ) {
    3852            //min requirements not met
     
    4155
    4256        return true;
     57
    4358    }
    4459
     
    4964     */
    5065    private function _load_plugin() {
     66
    5167        //load up autoloader
    5268        require_once( IG_SYNTAX_HILITER_ROOT . '/autoloader.php' );
     
    6682
    6783        }
     84
    6885    }
    6986
     
    7794     */
    7895    public function show_admin_notice() {
    79         printf( '<div class="error"><p>PHP version %s or greater is needed for <strong>iG:Syntax Hiliter</strong> plugin. You must upgrade your PHP to make it work.</p></div>', esc_html( self::MIN_PHP_VERSION_REQUIRED ) );
     96
     97        printf(
     98            '<div class="error"><p>PHP version %s or greater is needed for <strong>iG:Syntax Hiliter</strong> plugin. You must upgrade your PHP to make it work.</p></div>',
     99            esc_html( self::MIN_PHP_VERSION_REQUIRED )
     100        );
     101
    80102    }
    81103
    82 }   //end of class
    83 
     104}    //end of class
    84105
    85106//EOF
  • igsyntax-hiliter/trunk/classes/migrate.php

    r1213527 r2719681  
    33 * Class for migrating old plugin values to new
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 *
    77 * @since 2015-07-20
     
    1010namespace iG\Syntax_Hiliter;
    1111
    12 class Migrate extends Singleton {
     12use \iG\Syntax_Hiliter\Traits\Singleton;
     13
     14class Migrate {
     15
     16    use Singleton;
    1317
    1418    const V35_OPTION_NAME = 'igsh_options';
    1519
    1620    /**
    17      * @var iG\Syntax_Hiliter\Option
     21     * @var \iG\Syntax_Hiliter\Option
    1822     */
    1923    protected $_option;
     
    2428    protected $_db_version;
    2529
     30    /**
     31     * Class constructor
     32     */
    2633    protected function __construct() {
    2734        //init options
     
    2936    }
    3037
    31     public function settings( Base $obj ) {
     38    public function settings( Base $obj ) : void {
    3239
    3340        $this->_db_version = $this->_get_last_version();
    3441
    35         if ( $this->_db_version == round( floatval( IG_SYNTAX_HILITER_VERSION ), 1 ) ) {
    36             return; //current version, nothing to migrate, bail out
     42        if ( round( floatval( IG_SYNTAX_HILITER_VERSION ), 1 ) === $this->_db_version ) {
     43            return;    //current version, nothing to migrate, bail out
    3744        }
    3845
     
    6471     * @return float Last version of plugin installed. Returns 0 if its a fresh install.
    6572     */
    66     protected function _get_last_version() {
     73    protected function _get_last_version() : float {
     74
    6775        $db_version = floatval( get_option( Base::PLUGIN_ID . '-version', 0 ) );
    6876
     
    7280
    7381        return round( floatval( $db_version ), 1 );
     82
    7483    }
    7584
     
    8089     * @return void
    8190     */
    82     protected function _add_migrated_from_version() {
     91    protected function _add_migrated_from_version() : void {
    8392        update_option( Base::PLUGIN_ID . '-migrated-from', $this->_db_version );
    8493    }
     
    8897     * or not.
    8998     *
    90      * @return boolean Returns TRUE if plugin's last version in use was v3.5.x else FALSE
     99     * @return bool Returns TRUE if plugin's last version in use was v3.5.x else FALSE
    91100     */
    92     protected function _is_updating_from_35() {
     101    protected function _is_updating_from_35() : bool {
    93102        $old_options = get_option( self::V35_OPTION_NAME, false );
    94103
    95         if ( $old_options === false || ! is_array( $old_options ) ) {
     104        if ( false === $old_options || ! is_array( $old_options ) ) {
    96105            return false;
    97106        }
     
    105114     * @return void
    106115     */
    107     protected function _settings_from_35() {
    108         $old_options = get_option( self::V35_OPTION_NAME, array() );
     116    protected function _settings_from_35() : void {
     117
     118        $old_options = get_option( self::V35_OPTION_NAME, [] );
    109119
    110120        if ( isset( $old_options['PLAIN_TEXT'] ) ) {
     
    120130        }
    121131
    122         delete_option( self::V35_OPTION_NAME ); //delete old options from DB
     132        delete_option( self::V35_OPTION_NAME );    //delete old options from DB
    123133
    124134        $this->_add_migrated_from_version();
    125135
    126136        unset( $old_options );
     137
    127138    }
    128139
     
    132143     * @return void
    133144     */
    134     protected function _initialize_on_fresh_install( Base $obj ) {
    135         $obj->get_languages( 'yes' );       //rebuild language file list
     145    protected function _initialize_on_fresh_install( Base $obj ) : void {
     146
     147        $obj->get_languages( 'yes' );    //rebuild language file list
     148
    136149        $this->_option->commit();
     150
    137151    }
    138152
    139 }   //end of class
    140 
     153}    //end of class
    141154
    142155//EOF
  • igsyntax-hiliter/trunk/classes/option.php

    r1213527 r2719681  
    33 * Class for fetching and saving plugin options
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 */
    77
    88namespace iG\Syntax_Hiliter;
    99
    10 class Option extends Singleton {
     10use \iG\Syntax_Hiliter\Traits\Singleton;
     11
     12class Option {
     13
     14    use Singleton;
    1115
    1216    /**
    13      * @var Array An array which contains plugin options
     17     * @var array An array which contains plugin options
    1418     */
    1519    protected $_options;
    1620
    1721    /**
    18      * @var Array An array which contains default plugin options
     22     * @var array An array which contains default plugin options
    1923     */
    20     protected $_default_options = array(
    21         'fe-styles'         => 'yes',               //use plugin CSS to style hilited code box by default
    22         'strict_mode'       => 'maybe',             //don't use GeSHi strict mode always
    23         'non_strict_mode'   => array( 'php' ),      //langauges where strict mode is disabled
    24         'toolbar'           => 'yes',               //show toolbar above hilited code by default
    25         'plain_text'        => 'yes',               //show option to view code in plain text by default
    26         'show_line_numbers' => 'yes',               //show line numbers in code by default
    27         'hilite_comments'   => 'yes',               //hilite code posted in comments by default
    28         'link_to_manual'    => 'no',                //don't link keywords to manual by default
    29         'gist_in_comments'  => 'no',                //don't embed Github Gist in comments by default
    30     );
     24    protected $_default_options = [
     25        'fe-styles'         => 'yes',    //use plugin CSS to style hilited code box by default
     26        'strict_mode'       => 'maybe',    //don't use GeSHi strict mode always
     27        'non_strict_mode'   => [ 'php' ],    //langauges where strict mode is disabled
     28        'toolbar'           => 'yes',    //show toolbar above hilited code by default
     29        'plain_text'        => 'yes',    //show option to view code in plain text by default
     30        'show_line_numbers' => 'yes',    //show line numbers in code by default
     31        'hilite_comments'   => 'yes',    //hilite code posted in comments by default
     32        'link_to_manual'    => 'no',    //don't link keywords to manual by default
     33        'gist_in_comments'  => 'no',    //don't embed Github Gist in comments by default
     34    ];
    3135
     36    /**
     37     * Class constructor
     38     */
    3239    protected function __construct() {
    3340        $this->_load_all_options();
     
    3744     * @return void
    3845     */
    39     protected function _load_all_options() {
     46    protected function _load_all_options() : void {
     47
    4048        //fetch options array from wp_options & then do a safe merge with default options
    4149        $db_options = get_option( Base::PLUGIN_ID . '-options', false );
    4250
    4351        if ( empty( $db_options ) || ! is_array( $db_options ) ) {
    44             $db_options = array();
     52            $db_options = [];
    4553        }
    4654
    4755        $this->_options = Helper::array_merge( $this->_default_options, $db_options );
     56
    4857    }
    4958
    5059    /**
    51      * This function is just a wrapper to fetch an option from $_options class var,
    52      * since direct access to the $_options var is not allowed
     60     * Getter method to fetch a single option by name
     61     *
     62     * @param string $name
     63     *
     64     * @return mixed
    5365     */
    54     public function get( $option_name ) {
    55         if ( empty( $option_name ) || ! is_string( $option_name ) ) {
    56             return false;
    57         }
     66    public function get( string $name ) {
    5867
    59         if ( isset( $this->_options[ $option_name ] ) ) {
    60             return $this->_options[ $option_name ];
    61         }
    62 
    63         return false;
    64     }
    65 
    66     public function get_all() {
    67         return $this->_options;
    68     }
    69 
    70     /**
    71      * This function is for setting a value in the $_options class var as direct
    72      * access to it isn't allowed. It takes care of sanitizing the value before
    73      * putting it in $_options & saves only if the option name exists already.
    74      */
    75     public function save( $option_name, $option_value ) {
    76 
    77         if ( empty( $option_name ) || ! is_string( $option_name ) || ! isset( $this->_options[ $option_name ] ) ) {
    78             return false;
    79         }
    80 
    81         $can_be_empty = false;
    82 
    83         if ( is_array( $option_value ) ) {
    84             $option_value = array_map( 'strtolower', array_map( 'trim', array_map( 'sanitize_title', $option_value ) ) );
    85             $can_be_empty = true;
    86         } else {
    87             $option_value = strtolower( trim( sanitize_title( $option_value ) ) );
    88         }
    89 
    90         if ( ! empty( $option_value ) || $can_be_empty === true ) {
    91             $this->_options[ $option_name ] = $option_value;
    92             $this->commit();    //lets save in DB as well
    93 
    94             return true;
     68        if ( ! empty( $name ) && isset( $this->_options[ $name ] ) ) {
     69            return $this->_options[ $name ];
    9570        }
    9671
     
    10075
    10176    /**
    102      * This function is for saving the $_options class var in the DB, can be called anytime
    103      * or in the class destructor
     77     * Method to get all options
     78     *
     79     * @return array
     80     */
     81    public function get_all() : array {
     82        return $this->_options;
     83    }
     84
     85    /**
     86     * Method to save an option. It takes care of sanitizing the value before
     87     * saving it and saves an option only if the option name already exists.
     88     *
     89     * @param string $name
     90     * @param mixed  $value
     91     *
     92     * @return bool Returns TRUE if option is successfully saved else FALSE
     93     */
     94    public function save( string $name, $value ) : bool {
     95
     96        if ( empty( $name ) || ! isset( $this->_options[ $name ] ) ) {
     97            return false;
     98        }
     99
     100        $can_be_empty = false;
     101
     102        if ( is_array( $value ) ) {
     103
     104            $value = array_map( 'sanitize_title', $value );
     105            $value = array_map( 'trim', $value );
     106            $value = array_map( 'strtolower', $value );
     107
     108            $can_be_empty = true;
     109
     110        } else {
     111            $value = strtolower( trim( sanitize_title( $value ) ) );
     112        }
     113
     114        if ( ! empty( $value ) || true === $can_be_empty ) {
     115
     116            $this->_options[ $name ] = $value;
     117
     118            $this->commit();    //lets save in DB as well
     119
     120            return true;
     121
     122        }
     123
     124        return false;
     125
     126    }
     127
     128    /**
     129     * Method to save options in DB. This can be called anytime and even in the class destructor.
    104130     *
    105131     * @return bool
    106132     */
    107     public function commit() {
     133    public function commit() : bool {
     134
    108135        if ( empty( $this->_options ) ) {
    109136            return false;
     
    113140
    114141        return true;
     142
    115143    }
    116144
    117 }   //end of class
    118 
     145}    //end of class
    119146
    120147//EOF
  • igsyntax-hiliter/trunk/classes/validate.php

    r1213527 r2719681  
    33 * Class for validating plugin values
    44 *
    5  * @author Amit Gupta <http://amitgupta.in/>
     5 * @author Amit Gupta <https://amitgupta.in/>
    66 *
    77 * @since 2015-07-22
     
    1010namespace iG\Syntax_Hiliter;
    1111
    12 class Validate extends Singleton {
     12use \iG\Syntax_Hiliter\Traits\Singleton;
     13
     14class Validate {
     15
     16    use Singleton;
    1317
    1418    /**
    1519     * @var array Allowed values for strict mode option
    1620     */
    17     public static $strict_mode_values = array( 'always', 'maybe', 'never' );
     21    public static $strict_mode_values = [ 'always', 'maybe', 'never' ];
    1822
    1923    /**
    20      * Protected constructor, Singleton implemented
     24     * Class constructor
    2125     */
    2226    protected function __construct() {}
     
    2630     * it returns TRUE else FALSE. The parameter accepts only string.
    2731     *
    28      * @return boolean
     32     * @return bool
    2933     */
    30     public function is_yesno( $value ) {
     34    public function is_yesno( $value ) : bool {
     35
    3136        if ( ! is_string( $value ) ) {
    3237            return false;
     
    3540        $value = strtolower( trim( $value ) );
    3641
    37         if ( $value === "yes" || $value === "no" ) {
    38             return true;
    39         }
     42        return ( in_array( $value, [ 'yes', 'no' ], true ) );
    4043
    41         return false;
    4244    }
    4345
     
    4749     *
    4850     * @param string $value Value for strict mode option
     51     *
    4952     * @return string
    5053     */
    51     public function sanitize_strict_mode_values( $value ) {
     54    public function sanitize_strict_mode_values( string $value ) : string {
     55
    5256        $value = sanitize_title( strtolower( trim( $value ) ) );
    5357
    54         if ( empty( $value ) || ! is_string( $value ) || ! in_array( $value, static::$strict_mode_values ) ) {
     58        if ( empty( $value ) || ! in_array( $value, static::$strict_mode_values, true ) ) {
    5559            $value = static::$strict_mode_values[0];
    5660        }
    5761
    5862        return $value;
     63
    5964    }
    6065
     
    6671     * @return array A sanitized $values array, non-existing and duplicate language names removed
    6772     */
    68     public function languages( array $values = array(), array $languages = array() ) {
     73    public function languages( array $values = [], array $languages = [] ) : array {
    6974
    7075        if ( empty( $values ) || empty( $languages ) ) {
    71             return array();
     76            return [];
    7277        }
    7378
    74         $values = array_filter( array_unique( array_map( 'sanitize_file_name', array_map( 'trim', $values ) ) ) );
     79        $values = array_filter(
     80            array_unique(
     81                array_map(
     82                    'sanitize_file_name',
     83                    array_map( 'trim', $values )
     84                )
     85            )
     86        );
    7587
    7688        $values_count = count( $values );
    77         $clean_values = array();
     89        $clean_values = [];
    7890
    7991        for ( $i = 0; $i < $values_count; $i++ ) {
    8092
    81             if ( in_array( $values[ $i ], $languages ) ) {
     93            if ( in_array( $values[ $i ], $languages, true ) ) {
    8294                $clean_values[] = $values[ $i ];
    8395            }
     
    91103    }
    92104
    93 }   //end of class
    94 
     105}    //end of class
    95106
    96107//EOF
  • igsyntax-hiliter/trunk/ig-syntax-hiliter.php

    r1213527 r2719681  
    22/*
    33Plugin Name: iG:Syntax Hiliter
    4 Plugin URI: http://blog.igeek.info/wp-plugins/igsyntax-hiliter/
    5 Description: Syntax Highlighter plugin to colourize source code for various supported programming languages. See the MANUAL for more instructions.
    6 Version: 5.0
     4Plugin URI: https://igeek.info/category/wp-plugins/igsyntax-hiliter/
     5Description: Syntax Highlighter plugin to colourise source code for various supported programming languages. See the <a href="https://github.com/coolamit/ig-syntax-hiliter/blob/master/README.md">documentation</a> for more instructions.
     6Version: 5.1
    77Author: Amit Gupta
    8 Author URI: http://blog.igeek.info/
     8Author URI: https://igeek.info/
    99License: GPL v2
    1010*/
    1111
     12define( 'IG_SYNTAX_HILITER_VERSION', 5.1 );
    1213define( 'IG_SYNTAX_HILITER_ROOT', __DIR__ );
    13 
    14 if ( ! defined( 'IG_SYNTAX_HILITER_VERSION' ) ) {
    15     define( 'IG_SYNTAX_HILITER_VERSION', 5.0 );
    16 }
     14define( 'IG_SYNTAX_HILITER_URL', plugins_url( '/' ) );
     15define( 'IG_SYNTAX_HILITER_BASENAME', plugin_basename( __FILE__ ) );
    1716
    1817//set loader to execute on WP init
     
    2019
    2120function ig_syntax_hiliter_loader() {
     21
    2222    /*
    2323     * Load the Gatekeeper
     
    2828     * Activate the Gatekeeper
    2929     */
    30     new iG_Syntax_Hiliter_Gatekeeper();
     30    iG_Syntax_Hiliter_Gatekeeper::activate();
     31
    3132}
    3233
  • igsyntax-hiliter/trunk/readme.txt

    r1213537 r2719681  
    33Tags: syntax highlighter, code highlighter, code, source code, php, mysql, html, css, javascript
    44Requires at least: 4.1
    5 Tested up to: 4.3
    6 Stable tag: trunk
    7 License: GPLv2
     5Tested up to: 5.9
     6Requires PHP: 7.4.0
     7Stable tag: 5.1
     8License: GPLv2 or later
     9License URI: http://www.gnu.org/licenses/gpl-2.0.html
    810
    911A plugin to easily present source code on your site with syntax highlighting and formatting  (as seen in code editors, IDEs).
     
    1820
    1921* WordPress 4.1 or above
    20 * PHP 5.3 or above
     22* PHP 7.4.0 or above
    2123
    2224
    2325Pull requests are welcome on Github.
    2426
    25 Github: https://github.com/coolamit/ig-syntax-hiliter
     27Github: [https://github.com/coolamit/ig-syntax-hiliter/](https://github.com/coolamit/ig-syntax-hiliter/)
    2628
    2729== Installation ==
     
    5153== Other Notes ==
    5254
    53 ###Plugin Usage###
    54 
    55 Using this syntax highlighter is fairly easy. There is one tag and 8 optional attributes. Here's how code is posted for it to be highlighted.
    56 
    57 `[sourcecode language="language_name"]
    58 //some code here
    59 [/sourcecode]`
    60 
    61 So if you are posting some PHP code then it would be
    62 
    63 `[sourcecode language="php"]
    64 //some code here
    65 [/sourcecode]`
    66 
    67 or you can use shorthand tags like
    68 
    69 `[php]
    70 //some code here
    71 [/php]`
    72 
    73 
    74 Its advised to use the full format of the tag for semantics, however its a personal choice and the plugin supports both full format and shorthand.
    75 
    76 HTML entities need not be escaped, you can post your code as is and the plugin takes care of it all.
    77 
    78 **Important :** Do not forget to close the tags, as your code will not be hilited if you don't close your tags. Also, *don't nest tags*. Nesting of tags don't work, so don't try it, it'll ruin your output.
    79 
    80 Also a WYSIWYG editor (like the one bundled with WordPress) will probably mess up your code when you paste it in the editor. So if you are having that issue, then please don't report it as a bug. WYSIWYG editors are just not supported at present.
    81 
    82 ###(Optional) Plugin Attributes###
    83 
    84 **language :** Use this to specify the programming language whose code you are posting. This language has to be present in `geshi` directory inside plugin directory. If `language` attribute is not specified or if a non-existent language is specified in it then a generic code box is rendered. `lang` is the shorthand for `language` attribute.
    85 
    86 **firstline :** Use this to start line numbering from a number greater than 1.
    87 
    88 **highlight :** Use this to tell plugin which lines are to be marked as different for emphasis. Line numbers are actual line numbers of code and have no relation to the ones starting as per `firstline` attribute. It accepts a comma separated list of line numbers and line number ranges like 5-8 which is equal to 5,6,7,8
    89 
    90 `[sourcecode language="php" highlight="2,4-6,9"]
    91 //line 1 of PHP code
    92 //line 2 of PHP code
    93 //line 3 of PHP code
    94 //line 4 of PHP code
    95 //line 5 of PHP code
    96 //line 6 of PHP code
    97 //line 7 of PHP code
    98 //line 8 of PHP code
    99 //line 9 of PHP code
    100 [/sourcecode]`
    101 
    102 **file :** Use this to show a file name/path. This is displayed in the tool-bar shown above code box.
    103 
    104 **gutter :** Use this to tell plugin whether to show line numbers in the code box or not. It accepts either `yes` or `no`. This, if specified, will override the global option to show line numbers for that particular code box.
    105 
    106 **plaintext :** Use this to tell plugin whether to show plain text option for the code box or not. It accepts either `yes` or `no`. This, if specified, will override the global option to show plain text option for that particular code box.
    107 
    108 **toolbar :** Use this to tell plugin whether to show tool-bar for the code box or not. It accepts either `yes` or `no`. This, if specified, will override the global option to show toolbar for that particular code box.
    109 
    110 **strict_mode :** Use this to tell the plugin to use GeSHi Strict Mode for a particular code box or not. This attribute accepts `always` or `never` or `maybe` as value. If you don't know what this means then its better to ignore this attribute and let it remain default.
    111 
    112 ###Configuration###
    113 
    114 Configuring **iG:Syntax Hiliter** is a piece of cake. Login to your WordPress admin section & under the `Settings` menu you'll see `iG:Syntax Hiliter` in the sub-menu.
    115 
    116 When you click the `iG:Syntax Hiliter` configuration page, you are offered 10 configuration settings which you can set to your liking. Lets go through each of them.
    117 
    118 **Use plugin CSS for styling? :** This option allows you to tell the plugin whether it should use its own CSS for styling the code box (not the hilited code, just code box) or not. If you want to use your own styling for the code box, tool-bar etc then you can set it to `NO`. By default its set to `YES`.
    119 
    120 **GeSHi Strict Mode? :** This option allows you to tell the plugin the [strict mode](http://qbnz.com/highlighter/geshi-doc.html#using-strict-mode) setting to use with GeSHi. Strict mode can be set to be always on or off or you can set it to `MAYBE` to have GeSHi decide on its own using the language file of the language whose code you're hiliting. *If you don't have any clue about this then leave it at default setting.* By default its set to `MAYBE`. This option can be overridden for any code block using `strict_mode` attribute in the tag.
    121 
    122 **Languages where GeSHi strict mode is disabled :** This option lets you specify a comma separated list of languages where the GeSHi strict mode should always be disabled. Strict mode is disabled for PHP by default.
    123 
    124 **Show Toolbar? :** This option allows you to tell the plugin whether to show the tool-bar (which shows plain text option, file name, language name) above the code boxes or not. This option can be overridden for any code block using `toolbar` attribute in the tag.
    125 
    126 **Show Plain Text Option? :** This option allows you to tell the plugin whether to show the *Plain Text* view option on the code boxes or not. This option can be overridden for any code block using `plaintext` attribute in the tag.
    127 
    128 **Show line numbers in code? :** This option allows you to tell the plugin whether to show the line numbers along with code in the code boxes or not. Line numbers along with code look great, are a great help when referring to some code from a code box. This option can be overridden for any code block using `gutter` attribute in the tag.
    129 
    130 **Hilite code in comments? :** This option allows you to tell the plugin whether to hilite code posted in comments or not. If this is enabled, code posted in the comments will be hilited as it is in the posts.
    131 
    132 **Link keywords/function names to Manual? :** This option allows you to tell the plugin whether to link keywords, function names etc to that language's online manual or not. This works only if this feature is enabled for that particular language in GeSHi language file.
    133 
    134 **Enable GitHub Gist embed in comments? :** This option allows you to tell the plugin whether to embed Github Gist in comments or not. If disabled then a Gist posted in comments would just have a link to its page on Github.
    135 
    136 **Rebuild Shorthand Tags :** Language files in the plugin's directory and current theme (parent & child) directory are scanned and their names are cached to allow shorthand tag usage for all languages. This cache is rebuilt automatically every week. But if you wish to rebuild it manually you can do so by clicking this button.
    137 
     55[Documentation on plugin usage and configuration](https://github.com/coolamit/ig-syntax-hiliter/blob/master/README.md)
    13856
    13957== Frequently Asked Questions ==
     
    15876
    15977== ChangeLog ==
     78
     79= v5.1 =
     80
     81* Minimum required PHP version bumped to 7.4.0. The plugin simply won't load its code on lower versions.
     82* Refactored plugin code for PHP 7.4.x for better performing code.
     83* **This is the last release using the GeSHi library.** GeSHi library has not been updated in several years and it looks unlikely that it will continue. Next release of the plugin will use a different syntax highlighting library. All existing shortcodes will continue to work and so the update and transition would be seamless for the most part, except a feature or two that will phase out and a few changes in plugin configuration options.
    16084
    16185= v5.0 =
     
    260184== Upgrade Notice ==
    261185
    262 = 5.0 =
    263 Major re-write of plugin for cleaner, modular & better performing code. Fixes automatic tag cache rebuilds, new options allow more control over plugin and GeSHi.
     186= 5.1 =
     187Major refactor of plugin code for compatibility with PHP 7.4.0 and above.
    264188
    265189
  • igsyntax-hiliter/trunk/templates/frontend-code-box.php

    r1213527 r2719681  
    11<?php
    2 /*
    3  * Template for showing code box
     2/**
     3 * Template for showing hilited code in a box
     4 *
     5 * @package igsyntax-hiliter
    46 */
     7
     8if ( empty( $attrs ) || empty( $id_prefix ) || empty( $code ) ) {
     9    return '';
     10}
    511?>
    612<div id="<?php echo esc_attr( $id_prefix . $counter ); ?>" class="syntax_hilite">
    713
    8     <?php if ( $attrs['toolbar'] === true ) { ?>
     14    <?php if ( true === $attrs['toolbar'] ) { ?>
    915    <div class="toolbar">
    1016
    1117        <div class="view-different-container">
    12             <?php if ( $attrs['plain_text'] === true ) { ?>
     18            <?php if ( true === $attrs['plain_text'] ) { ?>
    1319            <a href="#" class="view-different">&lt; View <span><?php echo esc_html( $plain_text ); ?></span> &gt;</a>
    1420            <?php } ?>
     
    1723        <div class="language-name"><?php echo esc_html( $attrs['language'] ); ?></div>
    1824
    19         <?php if ( ! empty( $attrs['file'] ) ) { ?>
     25        <?php if ( ! empty( $attrs['file'] ) && ! empty( $file_path ) ) { ?>
    2026        <div class="filename" title="<?php echo esc_attr( $attrs['file'] ); ?>"><?php echo esc_html( $file_path ); ?></div>
    2127        <?php } ?>
  • igsyntax-hiliter/trunk/templates/plugin-options-page.php

    r1213527 r2719681  
    11<?php
    2 /*
     2/**
    33 * Template for the plugin options page
     4 *
     5 * @package igsyntax-hiliter
    46 */
    57?>
Note: See TracChangeset for help on using the changeset viewer.