0 comments on “Debugging: Add locations w/ Power “Uncaught SyntaxError: redeclaration of const wp_data””

Debugging: Add locations w/ Power “Uncaught SyntaxError: redeclaration of const wp_data”

SLP 5.13.5 prerelease + Power 5.11 has a problem found during testing… the admin add locations breaks (probably a lot of other things as well).

The browser console:

This is related to moving to wp_add_inline_script() vs. the wp_localize_script() based on findings that indicate wp_localize_script() may a not work with block themes and it is really intended for i18n/l10n.

Further investigation finds…

store-locator-le/include/module/admin_tabs/SLP_BaseClass_Admin.php
enqueue_admin_javascript()

This is called for each add-on that needs it…


Power needs it.
handle: slppower_manage_locations
data stack:
{"ajax_nonce":"50164ddb77"}

SLP (base plugin) needs it.
handle: slp_manage_locations
data stack:
{"ajax_nonce":"50164ddb77"}

However, a code search shows that ONLY the base plugin admin JavaScript is using/referencing wp_data…

Why is Power setting up an enqueue of this file?

Code Analysis of enqueue_admin_javascript()…

This is always true:

if ( ! empty( $tab_js_settings ) ) {

Because this is always set further up in the code…

// All our JS will now have an AJAX_NONCE setting.
$tab_js_settings = array( 'ajax_nonce' => wp_create_nonce('slp_ajax'), );

They key player here “ajax_nonce” set above is ONLY ever used here… SLP base plugin admin.js… which is only called when doing a change_option. That is fired from both the base plugin and Power add on, HOWEVER… they both reference the SLP_ADMIN.change_option() method in JavaScript.

ajax_nonce usage in JavaScript is only in SLP base plugin admin.js (SLP_ADMIN) change_option() method attached to the options property (SLP_ADMIN.options.change_option).
All calls to the SLP_ADMIN.options.change_option() call

Resolution

Do not set the baseline tab_js_settings in SLP_BaseClass_Admin.php

This will stop the default (only) ajax_nonce PHP array entry from being set, effectively short-circuiting the enqueue of the script from the Power add-on.

While this fixes the issue short-term and stops overloading the tab_js_settings, if Power (or any other add on) finds it necessary to add some custom entries to the tab_js_settings array, it will break again. This is a fragile patch.

The change…

Add the handle to the JavaScript variable definition

The current setup is to hard-code the JS environment variable to “wp_data” for ALL add-ons. This will make them “fight” per the message above.

Instead of blindly referencing a generic hard-coded “wp_data” variable, let’s change that to be based on the add-on name.

For our use cases above that would do this.

For SLP base plugin wp_data => slp_data

For Power add on wp_data => slppower_data

The change…

0 comments on “WordPress Escaping and Sanitizing”

WordPress Escaping and Sanitizing

Escaping or Sanitizing General Rules

Arrays

Instead of manually detecting arrays then using array_map(), as noted below, instead use map_deep( $arrayOrScalarVar, ‘<method>’.

For example:

$cleanVar = map_deep( $_REQUEST['id'], 'santize_key');

For wp_kses_post use wp_kses_post_deep(). See below for more info.

When processing an array of values use array_map( ‘<method>’ , $arrayVar).

For example array_map( ‘sanitize_key’ , (array) $_REQUEST[‘id’] ).

Unslash Warnings

There is no need to call wp_unslash() before sanitizing inputs.

Related Resources


Securing Input (sanitizing)

sanitize_email()

Strips out all characters that are not allowable in an email.

sanitize_file_name()

sanitize_hex_color()

sanitize_hex_color_no_hash()

sanitize_html_class()

sanitize_key()

Lowercase alphanumeric characters, dashes, and underscores are allowed.

sanitize_meta()

This function applies filters that can be hooked to perform specific sanitization procedures for the particular metadata type and key. Does not sanitize anything on its own. Custom filters must be hooked in to do the work. The filter hook tag has the form “sanitize_{$meta_type}_meta_{$meta_key}“.

sanitize_mime_type()

sanitize_option()

Only sanitizes specific options known to WordPress (primarily for internal use).
After the value has been handled by the functions in the switch statement, it will be passed through a sanitize_option_$option filter.

sanitize_sql_orderby()

💙 sanitize_text_field()

From the WordPress docs…

  • Checks for invalid UTF-8,
  • Converts single < characters to entities
  • Strips all tags
  • Removes line breaks, tabs, and extra whitespace
  • Strips octets

Strips All Tags…

That means this CANNOT be used for anything that processes HTML elements.

The Code

/**
 * Sanitizes a string from user input or from the database.
 *
 * - Checks for invalid UTF-8,
 * - Converts single `<` characters to entities
 * - Strips all tags
 * - Removes line breaks, tabs, and extra whitespace
 * - Strips octets
 *
 * @param string $str String to sanitize.
 * @return string Sanitized string.
 */
function sanitize_text_field( $str ) {
	$filtered = _sanitize_text_fields( $str, false );

	/**
	 * Filters a sanitized text field string.
	 *
	 * @since 2.9.0
	 *
	 * @param string $filtered The sanitized string.
	 * @param string $str      The string prior to being sanitized.
	 */
	return apply_filters( 'sanitize_text_field', $filtered, $str );
}

💙 sanitize_textarea_field()

Like sanitize_text_field, but keeps newlines.

sanitize_title()

sanitize_title_for_query()

sanitize_title_with_dashes()

sanitize_user()

sanitize_url()

use esc_url_raw() – see below

wp_kses()

💙 wp_kses_post()

Calls wp_kses() with the ‘post’ context that automatically allows all HTML that is permitted in post content.

ℹ️ Processing an array or object? Use wp_kses_post_deep().

SLP Modifications

In SLP it allows HTML tags like Vue, etc. that are on the allowed HTML tags filter.

Converts & to &amp;

The wp_kses methods call wp_normalize_entities which bastardizes nearly all (but not ALL) occurrences of & in a string to &amp;.

That means wp_kses functions are basically useless for sanitizing query parameter strings.

The Code

 function wp_kses_post( $data ) {
    return wp_kses( $data, 'post' );
}

💙 wp_kses_post_deep()

Navigates through an array, object, or scalar, and sanitizes content for allowed HTML tags for post content.


function wp_kses_post_deep( $data ) {
    return map_deep( $data, 'wp_kses_post' );
}

Securing Output (escaping)

esc_attr()
Use on everything else that’s printed into an HTML element’s attribute.

esc_html()
Use anytime an HTML element encloses a section of data being displayed. This WILL NOT display HTML content, it is meant for being used inside HTML and will remove your HTML.

esc_js()
Use for inline Javascript.

esc_textarea() – Use this to encode text for use inside a textarea element.

esc_url()

Use on all URLs, including those in the src and href attributes of an HTML element.

Does encode things like & to wonky-ass WordPress HTML coded entities.

esc_url_raw()

Use when storing a URL in the database or in other cases where non-encoded URLs are needed.

Does NOT encode things like & to wonky-ass WordPress HTML coded entities.

esc_xml() – Use to escape XML block.

wp_kses() – See Santize above for more details.

💙 wp_kses_post() – See Sanitize above for more details.

💙 wp_kses_post_deep() – See Sanitize above for more details.


Nonces

wp_kses_data() – Alternative version of wp_kses() that allows only the HTML permitted in post comments.

wp_nonce_field( <action> , [ name = ‘_wpnonce’ ], [ referer = true ] , [ echo = true ])

– Add nonce input to a form.

check_admin_referer( <action> , [ name = ‘_wpnonce’ ])

– Check a received nonce is valid AND from an admin page.

0 comments on “WordPress & JavaScript “Admin Edition””

WordPress & JavaScript “Admin Edition”

WordPress does some odd things when it comes to managing the DOM elements, especially when it comes to JavaScript and CSS. WordPress has crafted their own creative PHP methodology for getting data from PHP into JavaScript when loading the scripts. This allows for JavaScript variables to be “pre-initialized” when the scripts are first rendered.

Useful for getting a known starting state in JavaScript based on PHP state and logic that has run up to the point that the scripts are loaded.

Not standard AT ALL given today’s single page app and other advanced methodologies just as REST queries, etc. that could do the same job.

0 comments on “SLP Settings : Quick Save”

SLP Settings : Quick Save

Originally all of the SLP settings forms had to be submitted by clicking a save button. This runs a typical form post + full page render… old-school web 1.X style.

Along the way work was done to utilize JavaScript triggers and save data with an onBlur on settings form fields. The tech uses jQuery using an AJAX-type model to send a single form field to the WordPress AJAX processor to manage saving a single field without re-rendering the entire page or sending the entire form.

How It Is Triggered

SLP base plugin’s admin.js initializes and hooks a change_option JS function to any INPUT type field with a quick_save CSS class attached.

    var qs_inputs = jQuery('.quick_save').find(':input');
    qs_inputs.on('change', function (e) {
      change_option(e.currentTarget);
    });
    qs_inputs.on('blur', function (e) {
      var start_val = e.currentTarget.defaultValue;
      if (e.currentTarget.value !== start_val) {
        change_option(e.currentTarget);
      }
    });
0 comments on “xDebug with phpStorm”

xDebug with phpStorm

VVV -enabled vagrant boxes are “ready to go” with real-time xDebug debugging. You’ll need to enable it after you’ve booted the guest OS by getting into the guest via command line.

Boot your vagrant box.

vagrant ssh

Once you are into the guest type…

xdebug_on

The xdebug broadcaster is now enabled for the guest OS. Any time you surf to a guest web page it will broadcast Xdebug data. Your IDE should be able to listen for xdebug publications and associate the local code to the xdebug publication. It may require that you “map” your folder structure from your IDE to the relevant server-named path, for example map ~/MyDrive/vagrant-local/www/wordpress-one/public_html to /srv/www/wordpress-one/public_html for it to associate the code in the IDE to the code in the server broadcast messages.

0 comments on “Keeping Forks Updated with Upstream”

Keeping Forks Updated with Upstream

When forking a repository you are making a new copy of the original source , creating what can become a completely different codebase over time. Often that is not the intention when working on a project ; you typically want your own copy to mess with but need it to be “in alignment” with the main production software, or “upstream”, on a regular basis.

Keeping your fork updated is done by using a secondary remote source on your local git clone of the forked repository. By default git clone creates a single remote with a default name of “origin”. Origin is typically the github or bitbucket copy of the codebase stored via git.

Any git repository can have multiple remotes assigned to them. One of the first things you should do when forking a repo and cloning it to a local box is to setup the “upstream” remote point of reference. I use the graphical git tool Sourcetree to help with this.

After cloning your fork, double-click the repository name in Sourcetree to open the commit browser window. With that window open you can open the Repository | Repository Setting menu. Open the sub-tab for “remotes”, add a new remote, name it “upstream” and put in the git URL that represents the original code repository from where your forked version came.

You can now fetch upstream branches alongside your own. When you want to bring your forked copy “in alignment” with the upstream, checkout the branch you want to have aligned… develop for example… fetch the same branch from upstream, them merge upstream/develop into your origin/develop branch. Push your local develop back to origin/develop and valla — your forked copy is now ‘in alignment” with upstream for that particular branch.

0 comments on “Fresh VVV Setup for Plugin Dev”

Fresh VVV Setup for Plugin Dev

Starting out you’ll need…

Virtualbox (6.1)
Vagrant (2.2.15)
Install the vagrant-goodhost plugins
A running copy of git

This is all per the VVV System Requirements

Getting the box up…

Clone of VVV to a local directory.

git clone -b stable git://github.com/Varying-Vagrant-Vagrants/VVV.git ./vagrant-local

# vagrant up

This will download, build, and boot a default WordPress box.

Getting the SLP software

Fork the main SLP bitbucket repo to your own local copy.

Clone that fork into the one.wordpress.test wp-content/plugins directory…

cd ./vagrant-local/www/wordpress-one/public_html/wp-content/plugins/

# git clone git@bitbucket.org:lance_cleveland/store-locator-plus.git


# git checkout develop