Half-Elf on Tech

Thoughts From a Professional Lesbian

Tag: coding

  • Uniqueness Matters

    Uniqueness Matters

    This email gets sent a lot to plugin devs lately:

    All plugins should have unique function names, defines, and classnames. This will prevent your plugin from conflicting with other plugins or themes.

    For example, if your plugin is called “Easy Custom Post Types”, then you might prefix your functions with ecpt_{your function name here}. Similarly a define of LICENSE would be better done as ECPT_LICENSE.

    Please update your plugin to use more unique names.

    And once in a while someone asks why we care so much.

    There are 38,308 active plugins in the WordPress.org repository. If every one of them uses a global define of IS_PLUGIN_SETUP then they will all conflict with each other. If half use a script handle of plugincss then all those plugins will stomp over each other when it comes to enqueuing the CSS.

    It’s literally a numbers game.

    Every day we get at least 30 new plugin submissions to WordPress.org. That means every day at least 30 new potential conflicts show up. And it’s not just plugins. In WordPress 4.2, a new function was added: get_avatar_url()

    This was a great idea that saved people countless hours of work. Unless they logged in to see the error Fatal error: Cannot redeclare get_avatar_url() prance across their screen.

    Now in this case, theme authors had previously been told to include/make themselves, but was later added to core. All theme devs hosting on WordPress.org were notified and it was posted on the change blogs. But not everyone remembers to check those. And not everyone updates their themes right away. In a way, this probably could have been communicated better, but had the themes called their function mythemename_get_avatar_url() then this wouldn’t have been a problem.

    Prefix everything. Make it unique to your plugin or theme. WordPress is ‘home free’ and shouldn’t have to, but you should.

  • Heartbeat API

    Heartbeat API

    For the longest time I didn’t really get the heartbeat API. I get the very basics of it, but it took me a while to understand what it was really doing.

    We’re used to interacting with our websites in a very one-directional way. I click a link, I go to a page. Heartbeat API is a bi-directional communication, which can best be translated as ‘shit happens without you having to click.’ The browser and the server are happily chatting to each other all the time, without me having to do anything.

    If you’ve ever used Google Docs or MS Word or Apple Pages and noticed you don’t have to press ‘save’ all the time, that’s the idea of a Heartbeat API. It does the background things for you. That thing you should do (save often). In WordPress, the most obvious thing that Heartbeat does is it saves your posts as revisions.

    That doesn’t stop neurotics like me from pressing ‘save’ all the time.

    Of course, this can get a little expensive, checking all the time, so the Heartbeat API is smart. It only checks every 15 seconds by default (you can change this), and it only checks when you’re on a page doing something. If you just leave a page open, it slows down and, after an hour, turns off.

    But besides saving, the Heartbeat API can share information between the systems. For example, it can ping out to Jetpack and check if it’s up and everything’s working, or if you have to reconnect your LinkedIn settings. And since it’s javascript based, it doesn’t reload the page.

    You can use it to alert logged in users to new content. Imagine a post that suddenly had an overlay of ‘This post has been updated…’ Doing that requires two parts:

    1. Hook into the send call and add your data
    2. Hook into the receive call and show the data

    Pippin has a great heartbeat API example but he also warns people:

    I’ve managed to bring down server servers by using the Heartbeat API on the frontend.

    If you trigger things to be called too often, you can totally crash a server.

    The Heartbeat API is a step towards making our sites really responsive and modular. Instead of statically checking via PHP if someone’s logged in and changing display based on that, Heartbeat can dynamically change on the fly. This would allow caching systems like Varnish or static-file caches like WP Super Cache, to save the cache and speed up your site while still being dynamic. It lessens the weight on wp_ajax_ and makes things work with caches, rather than bypass them.

    And that will make our sites beat faster for everyone.

  • CloudFlare Code Muncher

    CloudFlare Code Muncher

    CloudFlare’s email protection butchered my code examples.

    Just putting that out there.

    What Happened?

    I went, perhaps ironically, to a post about changing your git repo URLs after activating CloudFlare, and was confused. See, I knew the code was something like me@mydomain.com:/path/to/repo but when I visited the page, it was all gibberish like this:

    /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */
    

    I quickly edited the post and saw the content there was just fine. The only content that was getting munged was code output. It was very confusing so I googled and found a surprising answer.

    What Was Wrong?

    Turns out it was “Email Address Obfuscation” — a feature in CloudFlare that munges your email address to protect it from being scraped. In and of itself, that is ultra cool.

    I could wrap everything like this:

    <!--email_off-->
    
    <!--/email_off-->
    

    Or I could filter all the shortcodes… Or I could turn off “Email Address Obfuscation”

    I went with turning off the setting because it was faster, and it’s not like people cant deduce my email address. But if I was going to set it up, the fastest would actually be to filter all shortcodes, and that proved problematic.

    Why All?

    One of the problems is that I use Syntax Highlighter Evolved to handle my code chunks, and one of the things that plugin does is let me use a shortcode based on the programing language. That means the most efficient way would be to say “If this is a shortcode, wrap it in the email-off tags to tell it to shut up.”

    Can You Code It?

    This is theoretical and not fully tested. Use at your own risk.

    With embeds, you can do things like this:

    add_filter('embed_oembed_html', 'halfelf_embed_oembed_html', 99, 4);
    function halfelf_embed_oembed_html($html, $url, $attr, $post_id) {
      return '<!--email_off-->' . $html . '<!--/email_off-->';
    }
    

    But sadly there isn’t a wrap around like that for shortcodes, which means we have to do some serious filtering. There’s a global array called $shortcode_tags that lists all shortcodes (as you register them, so shall they be added), so I’m going to take that and replace their callback functions with my own. Then in my callback, I’ll keep their callback but at the same time I’ll wrap around it:

    function cloudflare_email_off_for_shortcodes() {
        global $shortcode_tags;
    
        $shortcode_tags[ $tag ] = 'cloudflare_email_off_html';
    }
    add_action( 'init', 'cloudflare_email_off_for_shortcodes', 99 );
    
    function cloudflare_email_off_html( $attr, $content = null, $tag ) {
        global $shortcode_tags;
    
        return '<!--email_off-->' . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . '<!--/email_off-->';
    }
    

    But that struck me as a little expensive when I considered how rarely I put email addresses in things in the first place.

  • URL Validation

    URL Validation

    I was writing a script for a rather complex series of checks on a website. I wanted to do what I thought would be simple. I wanted to grab the website headers and parse them to check if a site was WordPress or not.

    That was a weird and wild trip.

    In theory, this is all the code you need:

    filter_var($url, FILTER_VALIDATE_URL)

    But as it turns out, that’s actually not the best thing! I started using it but found that I could break it pretty easily and, since I was writing a tool I knew would be used by end-users (who are exceptionally creative when it comes to breaking things), I googled around and found this blog post on Why URL validation with filter_var might not be a good idea.

    Yikes! All I was mad about was that FILTER_VALIDATE_URL thinks http://foo is okay, even when you tell it you want the damn host.

    In the end I used this Strict URL Validator code but even then I had to wrap it around this:

    	// Sanitize the URL
    	$gettheurl  = (string) rtrim( filter_var($_POST['url'], FILTER_SANITIZE_URL), '/' );
    	$gettheurl  = (string) $_POST['url'];
    
    	if (preg_match("~^https://~i", $gettheurl)) {
    		$gettheurl = "https://" . $gettheurl;
    	} elseif (!preg_match("~^(?:f|ht)tp?://~i", $gettheurl)) {
    	    $gettheurl = "http://" . $gettheurl;
    	}
    
    	// Is it a real URL? Call StrictURLValidator
    	require_once 'StrictUrlValidator.php';
    
    	if ( StrictUrlValidator::validate( $gettheurl, true, true ) === false ) { 
    
    		// Do the needful
    	}
    

    In many ways, this makes some sense. What is and isn’t a URL can be tetchy to check. http://foo is real. I can use it locally. That’s why http://localhost can exist. And we can’t just say “if not .com/org/net” anymore (if we ever really could). But boy is my code clunky.

  • Coding My Own Dogfood

    Coding My Own Dogfood

    I say no to a lot of pull requests on code.

    This is because I write plugins, not something massive and monolithic and used on a million websites. I’m a sole developer for my code, for the most part, and while pull requests are always welcome, the main reason I reject them is because I eat my own dogfood.

    Back in March of 2015, I decided to start using CloudFlare because we, at DreamHost, parter with them, so I should, you know, use them. It’s the same reason I use PageSpeed so much. And WordPress. I use what I use because I need to use it to be good at it.

    You cannot possibly be expected to write code for WordPress and support it if you don’t use it.

    I say this over and over again when I’m training people on WordPress. If you want to get good at supporting and fixing WordPress, then you need to use it and fix it. A lot. Every day. You need to use it so you know where everything is and can recognize what it should and should not do. You need to fix it so you know how to make it go back to looking like it should.

    If you’re writing code for WordPress, you need to do that too.

    Here’s my bottom line. If I’m writing a plugin, it’s going to be because I need what it does. If I’m writing a plugin, it’s because I’m going to use it. If there’s a feature I disagree with, I won’t add it in. If it’s something I will never use, it’s not going in. If it’s code I cannot test, I will never, ever, add it.

    That last one gets people mad at me a lot.

    The reality is that if I add in a feature for you and it doesn’t work, I can’t fix it because I don’t have the access needed. I cannot reproduce the error. If I can’t do that, how can I possibly fix it? I’ll have to work with you, via posts and emails, if you can’t fix it yourself.

    Pull requests are a wonderful thing, but if you’re making a pull for a new feature that’s something I can’t validate and test, then you’re also taking on the responsibility I did for the community. You’re promising to help me test it, develop it, future proof it. You’re promising to be there when I want to release a new version for everyone else. You’re promising to help support it and help others debug it.

    Are you ready for that?

  • If You Call Yourself a Developer You Should …

    If You Call Yourself a Developer You Should …

    Sometimes people scare me. Mostly it’s people who start a conversation with some variant of “I’ve been a developer for X years and I’ve never experienced a conversation like this…”

    It tends to come up when I kick someone’s code back and remark “Remove your own jQuery, delete the demo folders, and your domain name is a problem so change X to Y.”

    They get upset because I’ve not spelled out, specifically, to the letter, what’s wrong and where. I’ve had those conversations with everyone from a mom-and-pop shop coder to Microsoft and it really only bothers me when people are running dev companies and ask things like “How do I find that?” or “Where is that code?”

    So here are my rules of what a Developer should know:

    Know Logic

    You should understand logic. Not Spock Logic. Math Logic. And Computer Logic. Don’t worry. I don’t think you need to be a math rock star to write code. I think that if you understand basic algebra, which you may be surprised to know you do, then you’re okay. But you have to understand the most basic of logic gates:

    The basic computer logic gates (1/0, Yes/No, Or/Nor, etc)

    Can you look at that and understand the differences? Great. Write some code. Understanding the elementary building blocks of circuits, the A or B, the Yes or No, is the crux of programing. If you can’t logic that out, you should stop and read up on it. Most self-taught programmers have intuited that, but at some point they had a class in Boolean Algebra and learned this. Maybe it wasn’t called that, but most of us had that class in at least High School. You’ll need it.

    Know Grep

    You need to know how to search all the files in your code. If you’re on a linux flavor, grep or ack are your best friends. So when someone says “I see you’re calling domain.com in your code, why?” you know how to find that, even if they don’t give you a line.

    Know What You’ve Got

    You need to know all the packages added to your code. Did you add a library or a sub-module? This is your responsibility to know what they are. That way, when someone tells you to ‘remove the X module’ you’re not surprised. If it’s in your code, you should know what it is.

    Know What You Need

    You need to know what those packages are adding to your site. Did you download a whole jQuery library with all the demo files and a version of jQuery and the help docs? Do you really need all that? Dollars to donuts, you don’t. Don’t let your code be cluttered by what you don’t need. It’s more work to maintain it, and if there’s a security hole in it, you still have to be aware of it. Save yourself time, effort, and a hack. Leave out what you don’t need.

    Know What To Use

    You need to know how to edit the various filetypes. Personally I don’t care what you use. I like Coda. My friends like Sublime. I don’t care. Just make sure you use something that works for you and helps you work better. While you can do all your programing in Notepad, I wouldn’t suggest it. You will need tools to help you keep track of the complex world you’re building. Sometimes you’ll have to use a specialized tool.

    Know How Your Tools Work

    Did you know Github makes a downloadable zip of your code? Did you know that zip doesn’t include submodules? Did you know Github forks aren’t searchable? You should. I have a few awesome tools, like Coda, which lets me search my repositories and find code. I use BBEdit to search zips. I use a new tool to compare folders when I don’t have version control (for whatever reason). But I know how they all work.

    What Else?

    What do you think is imperative for someone who calls themself a professional developer to know?