PHP RFC Preview: Dynamic Callback Expressions

I’m posting this to get some initial feedback on this idea before I officially submit an RFC.

Background

Even with PHP’s growing object-oriented and functional programming features, the callback remains widely-used and useful. However, forcing authors to create callbacks via strings and arrays presents difficulties:

  1. Most IDEs do not recognize callbacks as such, and so cannot offer autocompletion, rename refactoring, and other benefits of code comprehension.
  2. Authors can misspell identifiers inside strings.
  3. Within namespaced code, authors can forget to prepend the namespace, since function calls within the namespace do not require it.
  4. Where use statements change the identifier for a class, authors can specify the local classname instead of the fully resolved name.

Proposal Continue reading  

Convert Google Maps embed HTML to Street View URL

You can use the form below to convert the HTML embed code Google Maps gives you to a usable Street View URL

Why do I need this?

The new Google Maps layout has a chain-link icon on the left that gives you a URL to what you’re looking at. If you’re in Street View, sometimes the given URL doesn’t include the proper parameters and you end up back on the top-down map view. This converter pulls a valid Street View URL out of the embed HTML.

source code

Obama’s ONDCP still can’t be trusted

The Office of National Drug Control Policy under Bush, led by John Walters, was notorious for flat-out lies and evidence bending, especially regarding cannabis (it was a holy culture war for Ashcroft as well), but under Obama the office has mostly put focus on prescription drug abuse and “drugged driving”.

With 2012 bringing a host of cannabis-related ballot initiatives to voters, Walters’ style of deception is making a comeback. Look at this editorial.

Data also reveal that marijuana potency has almost tripled in the past 20 years. This is especially troubling for use among teens because the earlier a person begins to use drugs, the more likely they are to develop a more serious abuse and addiction problem later in life.

No studies I’m aware of link an increase in THC potency to anything mentioned in the second sentence. Also note that cannabis regulation could actually dictate potency, and kids are getting pot earlier under the current policy. The irony here is that higher THC potency reduces the amount of smoking (a good thing) the user needs to do to achieve the desired level of intoxication.

Would marijuana legalization make Tennessee healthier or safer? One needs to look no further than Tennessee’s current painful experience with prescription drug abuse.

Prescription drugs (generally highly pure synthetic opiates) are not cannabis.

…prescription drugs are legal, regulated, and taxed — and yet rates of the abuse…

Proposed cannabis regulation is generally not by prescription, so this sentence seems purely a distraction. Prescription drugs are scary!

Nationally, someone dies from an unintentional drug overdose — driven in large part by prescription drug abuse — on average every 19 minutes.

Prescription drug abuse is deadly, and is not cannabis use. Surely he forgot to mention cannabis is practically non-toxic.

What would America look like if we had just as many people using marijuana as we currently have smoking cigarettes, abusing alcohol, and abusing prescription drugs?

Why would we have that? It’s true that legalized cannabis would broaden the base of users, but there’s just not a lot of reason to cue scary music.

The bottom line is that laws that control substances have had a real and lasting effect on keeping drug use rates relatively low.

A gem of truth! Prohibition does reduce use, which is only one of many metrics by which you should judge public policy. We could certainly reduce alcohol use, premarital sex, masturbation, swearing, blasphemy and other ills by making them all illegal and giving police endlessly increasing funding and power to stamp them out.

Moreover, other addictive substances like alcohol and tobacco, which are already legal and taxed, cost much more in social costs than the revenue they generate.

It’s true, drugs that are not cannabis are not cannabis, and alcohol excise taxes should be raised considerably. Why has the ONDCP never taken up this cause? As Mark Kleiman put it, a drug policy that ignores alcohol is like a naval policy that ignores the Pacific. Further, you’ll not find a study that shows cannabis causes more damage than alcohol/tobacco.

This isn’t to say that we believe we can arrest our way out of our nation’s drug problem.

AFAIK in no way has the ONDCP or DEA promoted any policy that would lead to fewer arrests, and the federal grant programs that built up local drug task force militarization are still in place (with a nice boost in the stimulus act).

[blah blah diversion treatment programs]

Yes, a small percentage of daily cannabis users will find it difficult to quit, experiencing problems with sleeping, mood, and discomfort (think quitting tobacco). IMO introducing the criminal justice system as executed in the U.S. does not, on net, improve any user’s situation.

(BTW, evidence suggests that involuntary treatment is a waste of money for most people, who can and do quit even highly addictive substances by themselves with a credible threat of an immediate and short jail sentence. Sending cannabis users who happen to get caught to treatment is an incredible waste of money and hard-to-find treatment space.)

Marijuana legalization would be disastrous public health policy, because it would increase availability and increase the use of a substance that we know to be harmful.

While increase in availability and use is a certainty of commercial legalization (it’s not my preferred policy), there’s only a sliver of the accounting on display here. This may come as a shock, but people can enjoy and benefit from cannabis use, and of course the removal of the damaging aspects of prohibition reduce future damage.

On whole I see commercial “legalization” as being a small net win, and a large win if its mandated that users may only use vaporizers (or e-cigarettes); that higher CBD/THC ratios are required; and that it remains illegal to “spike” foods for unsuspecting eaters, which I suspect to be the leading cause of people “freaking out” and seeking ultimately unnecessary ER visits. There’s also some encouraging evidence that suggests that, in medical marijuana states, young adults and teens are substituting cannabis for alcohol use resulting in notable drops in traffic fatalities.

Decades of experience have shown that there are no “silver bullet” approaches to addressing our national drug problem.

So true, but discovering silver bullets requires firing a few; unless I’m mistaken we haven’t actually tried any other approaches over those decades regarding cannabis on the federal level. I think we should.

Mad Men Theme Chords

I know there’s a full R2J2 song I haven’t heard yet, but since we’re marathoning MM I had to figure out at least this part. With capo on the 4th fret it’s easier to work the melody in.

x-0-2-2-1-1  C#m
x-0-2-2-1-0  (x 2)
x-2-3-2-x-0  D#m7-5
x-2-3-2-3-x  (x 2)
0-x-3-2-3-x  C#m/G#
0-x-2-2-1-x  (x 2)
x-x-1-2-1-x  D#7-9/G
x-x-1-2-0-x  (x 2)
0-x-0-1-1-x  G#7+
0-x-0-1-0-x  (x 2)
x-0-4-2-1-0  C#m6 (C#m the 2nd time)

The final synth harmony is a low C# and slightly flat B with rich harmonics implying a C#7 (major).

String Subtypes for Safer Web Programming

Valid HTML markup involves several different contexts and escaping rules, yet many APIs give no precise indication of which context their string return values are escaped for, or how strings should be escaped before being passed in (let’s not even get into character encoding). Most programming languages only have a single String type, so there’s a strong urge to document function with @param string and/or @return string and move on to other work, but this is rarely sufficient information.

Look at the documentation for WordPress’s get_the_title:

Returns

(string) 
Post title. …

If the title is Stan "The Man" & Capt. <Awesome>, will & and < be escaped? Will the quotes be escaped? “string” leaves these important questions unanswered. This isn’t meant to slight WordPress’s documentation team (they at least frequently give you example code from which you can guess the escaping model); the problem is endemic to web software.

So for better web security—and developer sanity—I think we need a shared vocabulary of string subtypes which can supply this missing metadata at least via mention or annotation in the documentation (if not via actual types).

Proposed Subtypes and Content Models

A basic set of four might help quite a bit. Each should have its own URL to explain its content model in detail, and how it should be handled:

Unescaped
Arbitrary characters not escaped for HTML in any way, possibly including nulls/control characters. If a string’s subtype is not explicit, for safety it should be assumed to contain this content.
Markup
Well-formed HTML markup matching the serialization of a DocumentFragment
TaglessMarkup
Markup containing no literal less-than sign (U+003C) characters (e.g. for output inside title/textarea elements)
AttrValue
TaglessMarkup containing no literal apostrophe (U+0027) or quotation mark (U+0022) characters, for output as a single/double-quoted attribute value

What would these really give us?

These subtypes cannot make promises about what they contain, but are rather for making explicit what they should contain. It’s still up to developers to correctly handle input, character encoding, filtering, and string operations to fulfill those contracts.

The work left to do is to define how these subtypes should be handled and in what contexts they can be output as-is, and what escaping needs to be applied in other contexts.

Obvious Limitations

For the sake of simplicity, these subtypes shouldn’t attempt to address notions of input filtering or whether a string should be considered “clean”, “tainted”, “unsafe”, etc. A type/annotation convention like this should be used to assist—not replace—experienced developers practicing secure coding methods.

RotURL: Rot13 for URLs

RotURL is a simple substitution cipher for encoding/obscuring URLs embedded in other URLs (e.g. in a querystring). Also, common chars that need to be escaped (:/?=&%#) are mapped to infrequently used capital letters, so this generally yields shorter querystrings, too.

/**
 * Rot35 with URL/urlencode-friendly mappings. To avoid increasing size during
 * urlencode(), commonly encoded chars are mapped to more rarely used chars.
 */
function rotUrl($url) {
    return strtr($url,
        './-:?=&%# ZQXJKVWPY abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHILMNORSTU',
        'ZQXJKVWPY ./-:?=&%# 123456789ABCDEFGHILMNORSTUabcdefghijklmnopqrstuvwxyz');
}

rotUrl('https://en.wikipedia.org/w/index.php?title=Special%3ASearch&search=Base64#foo')
    == '8MMGLJQQ5EZR9B9G5491ZFI7QRQ9E45SZG8GKM9MC5VxG5391CPcjx51I38WL51I38Vk1L5fdY6FF';
rotUrl(rotUrl($anyUrl)) = $anyUrl;

You could save a few more bytes by encoding the schema (e.g. “h” for http://, “H” for https://). Since your end encoding has to be URL-safe, there’s not much you can do beyond this to compress a URL embedded in a URL.

Validate Private Page Bookmarklet

ValidatePrivatePage <– validates in current window

ValidatePrivatePage <– validates in new window (your pop-up blocker may complain)

If you need to validate the markup of a page that’s not public (e.g. on localhost), you can now use this bookmarklet to auto-submit the current page source to the validator (instead of viewing source, copying, opening the validator, pasting in, and pressing “check”).

Note: this gets the page source making an XMLHTTPRequest to the current URL, so it does not get interpreted by the browser; i.e. this is NOT based on innerHTML(). If the request made returns a different page (e.g. you were logged out in the meantime), that page’s source will be sent to the validator. Not much can be done about that. I once wrote a crusty PHP4 class/bookmarklet combo that helped do this, but thanks to the standardization of XMLHTTPRequest, this is easy in JS now. You should also thank W3C for allowing cross-domain POSTs to the validator :)

NetBeans Love & Hate

For those cases where you have to work on remote code, NetBeans‘ remote project functionality seems to put it ahead of other PHP IDEs. It pulls down a tree of files and uploads files that you save. Having a local copy allows it to offer its full code comprehension, auto-complete, and great rename refactoring for “remote” code. In contrast Eclipse allows you to open remote files using Remote System Explorer, but you only get PHP syntax highlighting, not the excellent PDT.

But NetBeans is not all smiles and sunshine. Continue reading