Half-Elf on Tech

Thoughts From a Professional Lesbian

Tag: coding

  • Date, Time, and PHP

    Date, Time, and PHP

    I had a case where I needed to convert time from the format of the US centric dd/MM/YYYY to something a little more sane.

    A Very Bad (and Stupid) Way

    Since I was starting from a set position of 18/07/2017 (for example), the first idea I had was to use explode to do this:

    $date = "18/07/2017";
    $datearray = explode("/", $date);
    $newdate = $date[1].'-'.$date[0].'-'.$date[2]
    

    I did say this was stupid, right? The reason I’d want to do that, though, is that gets it into a DD-MM-YYYY format, which can be parsed a little more easily. Unless you’re an American. Which means this idea is useless.

    A Less Bad, But Still Bad, Way

    What about making it unix timestamp?

    $date = "18/07/2017";
    $date_parse = date_parse_from_format( 'm/d/Y' , $date);
    $date_echo = mktime( $date_parse['hour'], $date_parse['minute'], $date_parse['second'], $date_parse['month'], $date_parse['day'], $date_parse['year'] );
    

    Now I have a unix timestamp, which I can output any which way I want! At this point, if I’m not sure what version of PHP people are using, as long as it’s above 5.2, my code will work. Awesome.

    But we can do better.

    A Clever Way

    Instead of all that, I could use date_parse_from_format:

    $date = "18/07/2017";
    $date_parse = date_create_from_format('m/j/Y', $date );
    $date_echo[] = date_format($date_parse, 'F d, Y');
    

    And this will convert “18/07/2017” into “18 July, 2017”

    Which is far, far more understandable.

    So Which Is Best?

    If it’s your own code on your own server, I’d use date_create_from_format to control the output as you want.

    If this is code you want to run on any server, like in a WordPress plugin, use the unix timestamp, and then use date_i18n to localize:

    date_i18n( get_option( 'date_format' ), $date_echo );
    
  • Fight For The Future: Battle for the Net

    Fight For The Future: Battle for the Net

    On July 12, 2017, we fight for the internet. Again.

    I know. Didn’t we just do this? Well we did, and we have to do it again.

    What Is Net Neutrality?

    Net neutrality is the principle that Internet providers don’t get to control what we see and do online. Think of it like if your phone company got to decide what numbers you could call and when. Back in 2015, we managed to get fairly strong net neutrality laws from the FCC (the US Federal Communication Commission) which stopped Internet providers from blocking, throttling, and paid prioritization—”fast lanes” for sites that pay, and slow lanes for everyone else.

    Isn’t that like TV?

    Yes it is! On your TV, you can only watch the stations you pay for. Now imagine the Internet that way. The problem though is that we don’t just use the Internet to watch movies. We use it to work, to develop code like WordPress, and to communicate world wide with like minded people to do all of that.

    What’s the battle for?

    Comcast and Verizon want to end net neutrality so they can control what we see and do online. It’s that simple. They want it to look like TV so they can say that we can’t work with our fellow developers in Serbia or Iran. They want to monitor all our communication with those people as well (which in the case of WordPress isn’t really a hinderance but still…).

    What can we do?

    Fight back!

    Change your websites so people see the damage being done. Inconvenience the hell out of them. Make everyone notice and get them aware. Even if they watch Fox News.

    The Fight for the Future has started the Battle for Net Neutrality just like they did in 2014 with The Great Internet Slowdown and like they do today with Blackout Congress.

    How do we fight back?

    Add the Battle For The Net Widget to your website.

    If you’re running WordPress, I made a Fight for the Future Alerts Plugin, which lets you decide which alerts you want to show. It currently only supports the upcoming Battle for the Net and the Blackout Congress, but I plan to add other on-going events as they occur.

    You can also use the Cat Signal which dynamically loads the right alert for you at the right time. The reason this is different is that not everyone wants to run an extra javascript all the time on their websites. Page speed is important after all. Plus they may not want to show every single alert.

  • Taxonomy Icons

    Taxonomy Icons

    Last year I talked about how I made icons for my taxonomy terms. When you have a limited number of terms, that makes sense. When you have a taxonomy with the potential for a high volume of terms, like nations (192), or worse an unlimited number of terms, this approach looses its value.

    Instead, I realized what I needed for a particular project was a custom icon for each taxonomy. Not the term.

    I split this up into two files because I used a slightly different setup for my settings API, but the tl;dr of all this is I made a settings page under themes called “Taxonomy Icons” which loads all the public, non-default taxonomies and associates them with an icon.

    For this to work for you, you will need to have your images in a folder and define that as your IMAGE_PATH in the code below. Also mine is using .svg files, so change that if you’re not.

    File 1: taxonomy-icons.php

    The one gotcha with this is I usually set my default values with $this->plugin_vars = array(); in the __construct function. You can’t do that with custom taxonomies, as they don’t exist yet.

    class TaxonomyIcons {
    
    	private $settings;
    	const SETTINGS_KEY = 'taxicons_settings';
    	const IMAGE_PATH   = '/path/to/your/images/';
    
    	/*
    	 * Construct
    	 *
    	 * Actions to happen immediately
    	 */
        public function __construct() {
    
    		add_action( 'admin_menu', array( $this, 'admin_menu' ) );
    		add_action( 'admin_init', array( $this, 'admin_init' ) );
    		add_action( 'init', array( $this, 'init' ) );
    
    		// Normally this array is all the default values
    		// Since we can't set it here, it's a placeholder
    		$this->plugin_vars = array();
    
    		// Create the list of imagess
    		$this->images_array = array();
    		foreach ( glob( static::IMAGE_PATH . '*.svg' ) as $file) {
    			$this->images_array[ basename($file, '.svg') ] = basename($file);
    		}
    
    		// Permissions needed to use this plugin
    		$this->plugin_permission = 'edit_posts';
    
    		// Menus and their titles
    		$this->plugin_menus = array(
    			'taxicons'    => array(
    				'slug'         => 'taxicons',
    				'submenu'      => 'themes.php',
    				'display_name' => __ ( 'Taxonomy Icons', 'taxonomy-icons' ),
    			),
    		);
        }
    
    	/**
    	 * admin_init function.
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function admin_init() {
    		// Since we couldn't set it in _construct, we do it here
    		// Create a default (false) for all current taxonomies
    		$taxonomies = get_taxonomies( array( 'public' => true, '_builtin' => false ), 'names', 'and' );
    		if ( $taxonomies && empty( $this->plugin_vars ) ) {
    			foreach ( $taxonomies as $taxonomy ) {
    				$this->plugin_vars[$taxonomy] = false;
    			}
    		}
    	}
    
    	/**
    	 * init function.
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function init() {
    		add_shortcode( 'taxonomy-icon', array( $this, 'shortcode' ) );
    	}
    
    	/**
    	 * Get Settings
    	 *
    	 * @access public
    	 * @param bool $force (default: false)
    	 * @return settings array
    	 * @since 0.1.0
    	 */
    	function get_settings( $force = false) {
    		if ( is_null( $this->settings ) || $force ) {
    			$this->settings = get_option( static::SETTINGS_KEY, $this->plugin_vars );
    		}
    		return $this->settings;
    	}
    
    	/**
    	 * Get individual setting
    	 *
    	 * @access public
    	 * @param mixed $key
    	 * @return key value (if available)
    	 * @since 0.1.0
    	 */
    	function get_setting( $key ) {
    		$this->get_settings();
    		if ( isset( $this->settings[$key] ) ) {
    			return $this->settings[$key];
    		} else {
    			return false;
    		}
    	}
    
    	/**
    	 * Set setting from array
    	 *
    	 * @access public
    	 * @param mixed $key
    	 * @param mixed $value
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function set_setting( $key, $value ) {
    		$this->settings[$key] = $value;
    	}
    
    	/**
    	 * Save individual setting
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function save_settings() {
    		update_option( static::SETTINGS_KEY, $this->settings );
    	}
    
    	/**
    	 * admin_menu function.
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function admin_menu() {
    
    		foreach ( $this->plugin_menus as $menu ) {
    			$hook_suffixes[ $menu['slug'] ] = add_submenu_page(
    				$menu['submenu'],
    				$menu['display_name'],
    				$menu['display_name'],
    				$this->plugin_permission,
    				$menu['slug'],
    				array( $this, 'render_page' )
    			);
    		}
    
    		foreach ( $hook_suffixes as $hook_suffix ) {
    			add_action( 'load-' . $hook_suffix , array( $this, 'plugin_load' ) );
    		}
    	}
    
    	/**
    	 * Plugin Load
    	 * Tells plugin to handle post requests
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function plugin_load() {
    		$this->handle_post_request();
    	}
    
    	/**
    	 * Handle Post Requests
    	 *
    	 * This saves our settings
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function handle_post_request() {
    		if ( empty( $_POST['action'] ) || 'save' != $_POST['action'] || !current_user_can( 'edit_posts' ) ) return;
    
    		if ( !wp_verify_nonce( $_POST['_wpnonce'], 'taxicons-save-settings' ) ) die( 'Cheating, eh?' );
    
    		$this->get_settings();
    
    		$post_vars = $this->plugin_vars;
    		foreach ( $post_vars as $var => $default ) {
    			if ( !isset( $_POST[$var] ) ) continue;
    			$this->set_setting( $var, sanitize_text_field( $_POST[$var] ) );
    		}
    
    		$this->save_settings();
    	}
    
    	/**
    	 * Render admin settings page
    	 * If setup is not complete, display setup instead.
    	 *
    	 * @access public
    	 * @return void
    	 * @since 0.1.0
    	 */
    	function render_page() {
    		// Not sure why we'd ever end up here, but just in case
    		if ( empty( $_GET['page'] ) ) wp_die( 'Error, page cannot render.' );
    
    		$screen = get_current_screen();
    		$view  = $screen->id;
    
    		$this->render_view( $view );
    	}
    
    	/**
    	 * Render page view
    	 *
    	 * @access public
    	 * @param mixed $view
    	 * @param array $args ( default: array() )
    	 * @return content based on the $view param
    	 * @since 0.1.0
    	 */
    	function render_view( $view, $args = array() ) {
    		extract( $args );
    		include 'view-' . $view . '.php';
    	}
    
    	/**
    	 * Render Taxicon
    	 *
    	 * This outputs the taxonomy icon associated with a specific taxonomy
    	 *
    	 * @access public
    	 * @param mixed $taxonomy
    	 * @return void
    	 */
    	public function render_taxicon ( $taxonomy ) {
    
    		// BAIL: If it's empty, or the taxonomy doesn't exist
    		if ( !$taxonomy || taxonomy_exists( $taxonomy ) == false ) return;
    
    		$filename = $this->get_setting( $taxonomy );
    
    		// BAIL: If the setting is false or otherwise empty
    		if ( $filename == false || !$filename || empty( $filename ) ) return;
    
    		$icon     = file_get_contents( static::IMAGE_PATH . $filename  . '.svg' );
    		$taxicon  = '<span role="img" class="taxonomy-icon ' . $filename . '">' . $icon . '</span>';
    
    		echo $taxicon;
    	}
    
    	/*
    	 * Shortcode
    	 *
    	 * Generate the Taxicon via shortcode
    	 *
    	 * @param array $atts Attributes for the shortcode
    	 *        - tax: The taxonomy
    	 * @return SVG icon of awesomeness
    	 */
    	function shortcode( $atts ) {
    		return $this->render_taxicon( $atts[ 'tax' ] );
    	}
    
    }
    
    new TaxonomyIcons();
    

    File 2: view-appearance_page_taxicons.php

    Why that name? If you look at my render_view function, I pass the ID from get_current_screen() to it, and that means the ID is appearance_page_taxicons and that’s the page name.

    <div class="wrap">
    
    	<h1><?php _e( 'Taxonomy Icons', 'taxonomy-icons' ); ?></h1>
    
    	<div>
    
    		<p><?php __( 'Taxonomy Icons allows you to assign an icon to a non-default taxonomy in order to make it look damn awesome.', 'taxonomy-icons' ); ?></p>
    
    		<p><?php __( 'By default, Taxonomy Icons don\'t display in your theme. In order to use them, you can use a shortcode or a function:' , 'taxonomy-icons' ); ?></p>
    
    		<ul>
    			<li>Shortcode: <code>[taxonomy-icon tax=TAXONOMY]</code></li>
    		</ul>
    
    		<form method="post">
    
    		<?php
    		if ( isset( $_GET['updated'] ) ) {
    			?>
    			<div class="notice notice-success is-dismissible"><p><?php _e( 'Settings saved.', 'taxonomy-icons' ); ?></p></div>
    			<?php
    		}
    		?>
    
    		<input type="hidden" name="action" value="save" />
    		<?php wp_nonce_field( 'taxicons-save-settings' ) ?>
    
    		<table class="form-table">
    
    			<tr>
    				<th scope="row"><?php _e( 'Category', 'taxonomy-icons' ); ?></th>
    				<th scope="row"><?php _e( 'Current Icon', 'taxonomy-icons' ); ?></th>
    				<th scope="row"><?php _e( 'Select Icon', 'taxonomy-icons' ); ?></th>
    			</tr>
    
    			<?php
    
    			foreach ( $this->plugin_vars as $taxonomy => $value ) {
    				?>
    				<tr>
    					<td>
    						<strong><?php echo get_taxonomy( $taxonomy )->label; ?></strong>
    						<br /><em><?php echo get_taxonomy( $taxonomy )->name; ?></em>
    					</td>
    
    					<td>
    						<?php
    						if ( $this->get_setting( $taxonomy ) && $this->get_setting( $taxonomy ) !== false ) {
    							echo $this->render_taxicon( $taxonomy );
    						}
    						?>
    
    					</td>
    
    					<td>
    						<select name="<?php echo $taxonomy; ?>" class="taxonomy-icon">
    							<option value="">-- <?php _e( 'Select an Icon', 'taxonomy-icons' ); ?> --</option>
    							<?php
    							foreach ( $this->images_array as $file => $name ) {
    								?><option value="<?php echo esc_attr( $file ); ?>" <?php echo $file == $this->get_setting( $taxonomy ) ? 'selected="selected"' : ''; ?>><?php echo esc_html( $name ); ?></option><?php
    								};
    							?>
    						</select>
    					</td>
    
    				</tr><?php
    			}
    
    			?>
    
    			<tr valign="top">
    				<td colspan="3">
    					<button type="submit" class="button button-primary"><?php _e( 'Save', 'taxonomy-icons' ); ?></button>
    				</td>
    			</tr>
    		</table>
    		</form>
    	</div>
    </div>
    

    End Result

    And in the end?

    An example of Taxonomy Icons

    By the way, the image has some wrong text, but that is what it looks like.

  • Why I Write About What I Code

    Why I Write About What I Code

    I was asked this the other day. Obviously sometimes I write about technology in general, or software I find and like, but a great deal of the posts here are about how I figure things out. And the reason I do that is, simply, it makes me a better writer and a better coder.

    Want to write better?

    There’s nothing that will make you a better write than writing. You will learn your voice, your tone, and your flavor of writing only if you write. It doesn’t matter if your writing is bad at first. By writing more and more and more you will only get better and better at the process, and more comfortable doing it.

    Getting into the habit of writing, where it’s an every day occurrence in your life, is imperative if you want to write better. It’s a talent, yes, but it’s also a skill. And if you don’t practice skills they get rusty. If they get too rusty, they break and you give up.

    Want to code better?

    The fastest way to get better at code is to read and review other people’s code and try to figure out how they did what they did. The reason I can continue to think as sharply as I do about plugin reviews is that I do it every day. Every. Single. Day. I look at 30 to 100 plugins, review the code as written by just as many developers, reverse engineer what they’ve done, and I start to understand better. I peer review people’s code, day in and day out.

    But nothing makes you a better code than coding. Obviously. And yet there’s one thing most people miss. You see, the critical review of your own code is absolutely necessary if you want to become a better coder. And in the absence of peer reviewed code, the best thing to do is rip it apart yourself.

    Can you explain your code?

    That’s it. That’s the magic. If you can explain your code, why you did what you did, why it does what it does, then you are at the step of critically reviewing your code. The number of times my code has improved because I’ve blogged about it is uncountable. As I write my post, I find myself typing “I used the function X because…” and I stop. Why did I use that function?

    It’s in the questioning of my own actions that I begin to understand my own internal logic. You know, the part of your brain your parents and teachers helped you form. Those early days of logic where you learned fire was hot and one plus one was two, you also developed your own style of thinking.

    Can you explain why?

    My father likes to tell me I used to do my math backwards, from left to right, before my school taught me otherwise. On occasion, I still do it that way because I want to look at my math from a different perspective. Talking about why I do that changes my understanding of the process. The solution was always the same, but the process of getting there is vastly different.

    When I talk about why I chose the path I did, I do more than just verbalize to myself what I’ve done, I teach someone else that there’s an answer and there’s a way to their answers as well. I’ve shown a path.

    I write to understand myself

    Above all else, I write to understand myself. Only by doing that can I improve at anything.

  • (Slightly) More Performant WP Queries

    (Slightly) More Performant WP Queries

    One of the things 10up lists as a best engineering practice is this:

    Do not use posts_per_page => -1.
    This is a performance hazard. What if we have 100,000 posts? This could crash the site. If you are writing a widget, for example, and just want to grab all of a custom post type, determine a reasonable upper limit for your situation.

    This is a very valid point, but I found myself stymied at how to work around it in a case where I knew I needed to check all posts in a custom type. And worse that post type was growing every week by 10 to 20. In my case, the reasonable upper limit was an unknown that was also unpredictable. But an endless loop would also be bad.

    One of the other recommendations from 10up is not to run more queries than needed. I was already using no_found_rows => true to prevent counting the total rows, as it’s really only necessary for pagination. I also force in the post type I’m scanning, which again limits how many possible items will be queried. And yes, I have update_post_meta_cache and update_post_term_cache set to false as in most cases those aren’t needed either.

    But what could I do to make the actual query of getting how many posts of type A had a post meta value that matched post type B? And to make it worse, I could have multiple values in the post metas. It’s really a case where, in retrospect, making them into a custom taxonomy might have been a bit wiser.

    What I decided to do was limit the number of posts queried based on how many posts were in the post type.

    posts_per_page => wp_count_posts( 'custom_post_type' )->publish;

    I’m not quite concerned with 100,000 posts, and I have some database caching installed to mitigate the load. But also I have set an upper limit and this feels less insane than the -1 value. Since I had to generate the count anyway for displaying statistics, I moved that check to a variable and called it twice.

  • Access: Denied or Granted?

    Access: Denied or Granted?

    One of the topics I discuss regularly with developers it that of access. When writing any code, we must always consider who should have access to it. Not in the ‘who can look at my code?’ aspect, but that of who can run the code.

    This happens a lot with plugins and themes when people create their own settings pages. While I’m the first to admit that the settings API in WordPress is a bag of wet hair that makes little logical sense, using it gives you access to a lot of built in security settings, such as nonces.

    But as I often tell people, a nonce is not bulletproof security. We cannot rely on nonces for authorization purposes.

    What is a Nonce?

    A nonce is a word or expression coined for or used on one occasion. But in security, a nonce is an arbitrary number or phrase that may only be used once. Due to it’s similarity to a nonce word, it reuses the name. In WordPress, it’s a pseudo-random number created on the click of (say) a save button, to ensure that someone had to press the button in order to run the function.

    For example. If your settings page has a nonce, then the nonce is generated on click and passed to the function(s) that validate and sanitize and save. If the nonce doesn’t check out, then WordPress knows someone didn’t press a button, and it won’t run the save. This prevents someone from just sending raw data at your code.

    Why isn’t that enough?

    With just a nonce, anyone who has access to the page can save data. This is okay when you think about something like a comment form or a contact form. Those are things that need to be accessible by non logged in users, right? What about the WordPress General settings page? The one that lets you change the URL of the website? Right. You only want that to be accessible to admins. Imagine if all logged in users could change that one. Yikes!

    In order to protect those pages, you have to consider who should have access to your code.

    1. Are the users logged in or out?
    2. What user permissions should be required?
    3. How much damage can be caused if the data is changed?

    That’s it. That’s all you have to ask. If it’s a contact form, then a nonce is all you need. If it’s a site definition change, then you may want to restrict it to admins or editors only.

    The Settings API

    When you use the settings API, some of this is made pretty straightforward for you:

    add_action( 'admin_menu', 'my_plugin_admin_menu' );
    function my_plugin_admin_menu() {
        add_options_page( 'My Plugin', 'My Plugin', 'manage_options', 'my-plugin', 'my_options_page' );
    }
    

    In that example, the third value for the options page is manage_options which means anyone who can manage site options (i.e. administrators) can access the settings page.

    The problem you run into is if you want a page to do double duty. What if you want everyone to see a page, but only admins can access the settings part? That’s when you need to use current_user_can() to wrap around your code. Just check if a user can do a thing, and then let them in. Or not.

    What Permissions are Best?

    In general, you should give admins access to everything, and after that, give people as little access as possible. While it may be annoying that an editor can’t, say, flush the cache, do they really need to? You have to measure the computational expense of what’s happening before you give access to anyone. It’s not just “Who should do a thing?” but “What are the consequences of the thing?”

    Look at the cache again. Flushing a cache, emptying it, is easy. But it takes time and server energy to rebuild. By deleting it, you force your server to rebuild everything, and that will slow your site down. An admin, who has access to delete plugins and themes, should be aware of that. An editor, who edits posts and menus, may not. And while some editors might, will all?

    This gets harder when you write your code for public use. You have to make hard decisions to protect the majority of users.

    Be as prudent as possible. Restrict as much as possible. It’s safer.