Archive for Scripting

SSH publickey denied?

I was suddenly having trouble connecting to GitHub, after pulling in an OpenSSH update to version 7. Chances are that means the problem is security-related, meaning it’s worthwhile to take the time to investigate the cause.

$ git pull
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

A little debugging showed the following:

$ ssh -vT git@github.com
OpenSSH_7.1p2 Debian-2, OpenSSL 1.0.2f  28 Jan 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [192.30.252.130] port 22.
debug1: Connection established.
[…]
debug1: Skipping ssh-dss key /home/frans/.ssh/id_dsa for not in PubkeyAcceptedKeyTypes
[…]
debug1: No more authentication methods to try.
Permission denied (publickey).

Of course I could quickly fix the problem by adding PubkeyAcceptedKeyTypes ssh-dss to ~/.ssh/config, but checking OpenSSH.com tells me that “OpenSSH 7.0 and greater similarly disables the ssh-dss (DSA) public key algorithm. It too is weak and we recommend against its use.” So, although I could obviously re-enable it easily, I guess I’ll have to generate a new key. I hope GitHub’s guide is accurate for generating something sufficiently secure, because I’m kind of ticked off that something I generated in 2013 is already considered “legacy.” I hope I’m to blame and not an earlier version of GitHub’s guide.

Incidentally, to change the passphrase one would use the -p option, e.g.:

ssh-keygen -f id_rsa -p

Comments

Custom page number count in Prince

Prince makes it really easy to do all of the usual things with page numbers, like a different numbering scheme in the front matter and whatnot. Unfortunately you can’t counter-increment on @page, but thanks to Prince.addScriptFunc() you’ve got something better.

h2 {counter-reset: page 50}

@page {
	@bottom-left {
		content: prince-script(fixpagenum, counter(page));
		margin-left: 2cm;
	}
}

In this CSS, instead of passing regular generated content, we’re passing a prince-script. That script has to be defined somewhere, like this.

Prince.addScriptFunc("fixpagenum", function(pagenum) {
	pagenum = Number(pagenum);
	pagenum = pagenum + pagenum - 50;
	return pagenum;
});

The rationale in this case was to generate two separate documents, starting at page 50, one only left pages and the other only right pages. (Of course, the other one started at page 51.) I combined them with pdftk’s shuffle command.

pdftk left.pdf right.pdf shuffle output combined.pdf

I don’t think there’s a way to do something like this purely in Prince using CSS, but I’d love to be proved wrong.

Comments

Stop Hijacking Annoyances

Here’s another rescue from My Opera. The script was compiled by the user pehage on February 3, 2012, after a quick pointer by me. It is Opera UserJS, so it won’t work in any other browser. Don’t forget to enable User JavaScript on HTTPS if you so desire. In Opera 12 it no longer pops up a warning all the time.

// ==UserScript==
// @name Stop Hijacking Annoyances
// @include *
// ==/UserScript==

var annoyances = ["focus", "focusin", "focusout", /*"click",*/ "dblclick", "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "mouseenter", "mouseleave", "select", "submit", "keydown", "keypress", "keyup"];

for (var i=0; i<annoyances.length; i++) {
	//opera.postError(annoyances[i]);
	window.opera.addEventListener("BeforeEventListener." + annoyances[i], function (e) {
		e.preventDefault();
		//opera.postError(e);
	}, false);
}

And here is a simple testcase I created.

<!DOCTYPE html>
<html>
<head>
<title>keypress hijacker</title>
<script>
document.addEventListener('keypress', function(e){alert('document.addEventlistener on keypress ' + String.fromCharCode(e.which))}, false);
window.onkeydown = function(e){alert('window.onkeydown ' + String.fromCharCode(e.which))}
</script>
</head>
<body>
This page hijacks keypress events in order to display an alert message.
</body>
</html>

Comments

Data URI Bookmarklet

This is a repost of something I wrote on My Opera forums on 8 January 2013. The My Opera forums will be shutting down on 1 March 2014.


The easiest method [to base64 encode an image] might be to use the newly supported (since v12) FileReader object, which has a readAsDataURL method. I wrote a quick proof of concept using XHR because I’m not really sure how else to get data to it (aside from a file input which is no good here). Alternatively you could load the image in a canvas and call toDataURL, but then you’ll lose stuff like metadata and I’m not even sure if the compression and such will remain the same.

var xhr = new XMLHttpRequest(),
	reader = new FileReader();
xhr.open('GET', location.href, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', function () {
	if (xhr.status === 200) {
		reader.addEventListener('load', function (e) {
			location.href = e.target.result;
		});
		var responseWithMimeType = new Blob(new Array(xhr.response), {
			'type': xhr.getResponseHeader('Content-Type')
		});
		reader.readAsDataURL(responseWithMimeType);
	}
});
xhr.send();

It does seem a bit roundabout, so I’d love to hear it if anyone has more efficient suggestions.

I just realized you may not be aware of how to make a bookmarklet. To save myself the effort of removing comments and such I used http://chris.zarate.org/bookmarkleter to obtain the following result:

javascript:(function(){var%20xhr=new%20XMLHttpRequest(),reader=new%20FileReader();xhr.open('GET',location.href,true);xhr.responseType='blob';xhr.addEventListener('load',function(){if(xhr.status===200){reader.addEventListener('load',function(e){location.href=e.target.result;});var%20responseWithMimeType=new%20Blob(new%20Array(xhr.response),{'type':xhr.getResponseHeader('Content-Type')});reader.readAsDataURL(responseWithMimeType);}});xhr.send();})();

Create a new bookmark, paste that into the URL and give it a nickname of your choice.

Easier still, just drag this or right-click, bookmark link: To Data URI. There might be some security restrictions on MyOpera against javascript links, so I’m not sure if it’ll work.

But for local files a simple page would do just fine. All you need is input type=”file” and a tiny bit of scripting similar to the above. Something like this should do:

<!DOCTYPE html>
<html>
<head>
<title>File to Data URL</title>
</head>
<body>

<form>
<input type="file">
</form>

<script>
var file = document.querySelector('input[type=file]'), reader = new FileReader();

file.addEventListener('change', function(e) {
	reader.readAsDataURL(e.target.files[0]);
});

reader.addEventListener('load', function(e) {
	location.href = e.target.result;
});
</script>

</body>
</html>

Comments

Adding a User Font Size Preference to Simple Machines

Users should be able to choose their default font size easily through their browser, and their choice should be respected. But because all browsers default to 16px and most people never change the default, many sites—including Wikipedia—set their font-size to about 80% of that value to end up at a font size of 12px or 13px. Thus users might be prevented from lowering their font size on a site that actually respects their preferences if they so desire.

Because I don’t believe that either joining the 80% crowd or specifying a size in pixels is generally the right answer, I decided to add a user preference that overrides the font-size on the HTML element. For this to work as intended, your stylesheet needs to be entirely in percentages, em, rem, or use equivalent keywords like small and large.

First, in Admin > Configuration > Core Features, enable Advanced Profile Fields. Then, you can add custom profile fields in Admin > Configuration > Features and Options > Profile Fields. I added one named “Font size” with an input mask of /^[0-9]{1,3}(\.[0-9]{1,2})?(em|pt|px|%)$/.

Assuming your theme is based on the default, start editing index.template.php. Then, under the linked stylesheets you can put the override:

	// Custom user font-size
	if ($context['user']['is_logged']) {
		global $user_profile;
		loadMemberData($context['user']['id']);
		
		if (!empty($user_profile[$context['user']['id']]['options']['cust_fontsi'])) {
			echo '
	<style>', 'html {font-size: ', $user_profile[$context['user']['id']]['options']['cust_fontsi'], '}', '</style>';
		}
	}

To find out exactly what kind of useful values you can obtain from e.g. $context and $user_profile, you can use var_dump($user_profile).

Comments

Textarea Backup Localstorage v1.21

I figured I’d drop a note that I updated my Textarea Backup UserJS last month. What follows is the description from ExtendOpera.


Textarea Backup Localstorage

Retains what you type into textareas and contentEditable elements.

This script is only compatible with Opera 10.50 and up. If you need to use it with an older version use Textarea Backup but be advised that it comes with some disadvantages.

  1. Can automatically place previously typed text in textareas.
  2. Can add an unobtrusive menu in the top right corner of textareas

Actions menu screenshot (note the transparent object in the top right corner of the textarea):

Development can be followed on GitHub. Don’t be shy, open an issue or send me a pull request if you think you have something to contribute! 😉

Changelog

1.21 July 25, 2013. Sorry, I was a bit hasty about that last one. I passed my testcase, but only noticed that many contentEditables work differently in practice on this very site.

  • Fixed a bug that occurred when BODY was contentEditable, as is typical in iframes.
  • Properly compare initial value of contentEditable element to backed up value so you’ll only get prompted to overwrite when relevant.
  • Full changelog.

1.20 July 25, 2013. I wasn’t going to make yet another release in three days, but these new features could be implemented much faster than I initially predicted.

  • Trustworthy old persistent preferences support added. I also uploaded a sample settings file.
  • Fixed the keep_after_submission bug, so setting it to false is safe again.
  • Removed the form requirement.
  • Support contentEditable. This is a pretty big one, seeing how it was the most obvious missing feature.

1.11 July 24, 2013. Added configuration switches for the new feature.

  • For Opera 11.6x and Opera 12.x it now defaults to off because of potential performance concerns.

1.10 July 23, 2013. Added support for dynamically added textareas.

  • This new feature will only work in Opera 11.6x and up.

Comments

parseIntHelper()

The results of parseInt() are somewhat inconsistent, so I wrote this to clean it up (also see there). What to do with it? Who knows; it might come in handy someday.

function parseIntHelper(numberString, radix) {
	numberString = (typeof numberString === 'number') ? numberString.toString() : numberString; // I guess we should support number input just like parseInt.
	radix = (typeof radix === 'undefined') ? 10 : radix; // Set radix to 10 if undefined.
	
	numberString = numberString.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // Trim. Taken from http://blog.stevenlevithan.com/archives/faster-trim-javascript
	
	// Check if octal; non-standard but in line with other languages
	if ( numberString.indexOf('0o') === 0 || numberString.indexOf('0O') === 0 ) {
		numberString = numberString.slice(2); // Remove '0o'.
		radix = 8;
	}
	
	// Check if hex
	if ( numberString.indexOf('0x') === 0 || numberString.indexOf('0X') === 0 ) {
		numberString = numberString.slice(2); // Remove '0x'.
		radix = 16;
	}
	
	for (var i=0; i<numberString.length; i++) {
		var nStr = numberString[i];
		if (nStr === '.') {
			continue; // Ignore decimal mark, or rather the radix point. Maybe a check against more than 1 of these?
		}
		var parsed = parseInt(nStr, radix);
		if (isNaN(parsed)) {
			return parsed; // Return NaN if found
		}
	}
	return parseInt(numberString, radix); // Return regular parseInt if there was no shenanigans. Note that we do not support octal numbers prefixed with 0 because it's not in the ECMAScript 5 spec, although we do support the equally non-standard prefixed with 0o. That's because the behavior prefixed with 0 is just too unreliable, while we control what happens with 0o.
}

Comments

Using WordPress Excerpts in Meta Description

For a long time I’ve been aware of the fact that few, if any, WordPress themes seemed to do anything with the META element’s description feature. I never bothered to look into a solution, especially since I never used to add excerpts to my posts half a decade ago. However, I’ve bothered to do so ever since I started notifying people about updates on Twitter. It already makes the search results much more readable if you’re looking for something in the archives of this site, and I figured I should do the same for search engines.

Some uneventful searching later I found what I was looking for, but it definitely wasn’t right for me: I’ve got a huge volume of posts without any excerpts, so printing empty descriptions no matter what would be silly at best, and besides there are more descriptions out there than merely those of posts. After all, categories and even my site itself have a description as well. The comment by Matthew Slyman was much more to my liking, which I then customized as follows:

<?php
$desc;
if ( is_single() ) {
	$desc = get_the_excerpt();
}
elseif ( is_page() ) {
	$desc = get_the_excerpt();
}
elseif ( is_category() ) {
	$desc = category_description();
}
elseif ( is_home() ) {
	$desc = get_bloginfo('description');
}
$desc = htmlspecialchars(trim(strip_tags($desc)));
if (!empty($desc)) {
	echo '<meta name="description" content="';
	echo $desc;
	echo '"/>';
}
?>

Add the whole thing anywhere in your HEAD element in header.php. If excerpts seem to be missing from pages, there’s a simple solution. If you want to reuse the code above for some reason, wrap some sort of function around it and stick it in functions.php. Enjoy.

Comments

Word Count

Since I wanted to know the actual number of words in a paper in near-MLA format and couldn’t find my previous (simple) PHP script, I reimplemented an equally simplistic word counter in Javascript. It strips out citations between parentheses. Suggestions welcome and use at your own risk.

Comments

Javascript Associative Array of SVG Color Keywords

I thought I needed an associative array of SVG color keywords. I couldn’t find one, so I created this. Enjoy.

// see http://www.w3.org/TR/SVG/types.html#ColorKeywords
var SVGColors = new Object();
SVGColors['aliceblue'] = [240,248,255];
SVGColors['antiquewhite'] = [250,235,215];
SVGColors['aqua'] = [0,255,255];
SVGColors['aquamarine'] = [127,255,212];
SVGColors['azure'] = [240,255,255];
SVGColors['beige'] = [245,245,220];
SVGColors['bisque'] = [255,228,196];
SVGColors['black'] = [0,0,0];
SVGColors['blanchedalmond'] = [255,235,205];
SVGColors['blue'] = [0,0,255];
SVGColors['blueviolet'] = [138,43,226];
SVGColors['brown'] = [165,42,42];
SVGColors['burlywood'] = [222,184,135];
SVGColors['cadetblue'] = [95,158,160];
SVGColors['chartreuse'] = [127,255,0];
SVGColors['chocolate'] = [210,105,30];
SVGColors['coral'] = [255,127,80];
SVGColors['cornflowerblue'] = [100,149,237];
SVGColors['cornsilk'] = [255,248,220];
SVGColors['crimson'] = [220,20,60];
SVGColors['cyan'] = [0,255,255];
SVGColors['darkblue'] = [0,0,139];
SVGColors['darkcyan'] = [0,139,139];
SVGColors['darkgoldenrod'] = [184,134,11];
SVGColors['darkgray'] = [169,169,169];
SVGColors['darkgreen'] = [0,100,0];
SVGColors['darkgrey'] = [169,169,169];
SVGColors['darkkhaki'] = [189,183,107];
SVGColors['darkmagenta'] = [139,0,139];
SVGColors['darkolivegreen'] = [85,107,47];
SVGColors['darkorange'] = [255,140,0];
SVGColors['darkorchid'] = [153,50,204];
SVGColors['darkred'] = [139,0,0];
SVGColors['darksalmon'] = [233,150,122];
SVGColors['darkseagreen'] = [143,188,143];
SVGColors['darkslateblue'] = [72,61,139];
SVGColors['darkslategray'] = [47,79,79];
SVGColors['darkslategrey'] = [47,79,79];
SVGColors['darkturquoise'] = [0,206,209];
SVGColors['darkviolet'] = [148,0,211];
SVGColors['deeppink'] = [255,20,147];
SVGColors['deepskyblue'] = [0,191,255];
SVGColors['dimgray'] = [105,105,105];
SVGColors['dimgrey'] = [105,105,105];
SVGColors['dodgerblue'] = [30,144,255];
SVGColors['firebrick'] = [178,34,34];
SVGColors['floralwhite'] = [255,250,240];
SVGColors['forestgreen'] = [34,139,34];
SVGColors['fuchsia'] = [255,0,255];
SVGColors['gainsboro'] = [220,220,220];
SVGColors['ghostwhite'] = [248,248,255];
SVGColors['gold'] = [255,215,0];
SVGColors['goldenrod'] = [218,165,32];
SVGColors['gray'] = [128,128,128];
SVGColors['green'] = [0,128,0];
SVGColors['greenyellow'] = [173,255,47];
SVGColors['grey'] = [128,128,128];
SVGColors['honeydew'] = [240,255,240];
SVGColors['hotpink'] = [255,105,180];
SVGColors['indianred'] = [205,92,92];
SVGColors['indigo'] = [75,0,130];
SVGColors['ivory'] = [255,255,240];
SVGColors['khaki'] = [240,230,140];
SVGColors['lavender'] = [230,230,250];
SVGColors['lavenderblush'] = [255,240,245];
SVGColors['lawngreen'] = [124,252,0];
SVGColors['lemonchiffon'] = [255,250,205];
SVGColors['lightblue'] = [173,216,230];
SVGColors['lightcoral'] = [240,128,128];
SVGColors['lightcyan'] = [224,255,255];
SVGColors['lightgoldenrodyellow'] = [250,250,210];
SVGColors['lightgray'] = [211,211,211];
SVGColors['lightgreen'] = [144,238,144];
SVGColors['lightgrey'] = [211,211,211];
SVGColors['lightpink'] = [255,182,193];
SVGColors['lightsalmon'] = [255,160,122];
SVGColors['lightseagreen'] = [32,178,170];
SVGColors['lightskyblue'] = [135,206,250];
SVGColors['lightslategray'] = [119,136,153];
SVGColors['lightslategrey'] = [119,136,153];
SVGColors['lightsteelblue'] = [176,196,222];
SVGColors['lightyellow'] = [255,255,224];
SVGColors['lime'] = [0,255,0];
SVGColors['limegreen'] = [50,205,50];
SVGColors['linen'] = [250,240,230];
SVGColors['magenta'] = [255,0,255];
SVGColors['maroon'] = [128,0,0];
SVGColors['mediumaquamarine'] = [102,205,170];
SVGColors['mediumblue'] = [0,0,205];
SVGColors['mediumorchid'] = [186,85,211];
SVGColors['mediumpurple'] = [147,112,219];
SVGColors['mediumseagreen'] = [60,179,113];
SVGColors['mediumslateblue'] = [123,104,238];
SVGColors['mediumspringgreen'] = [0,250,154];
SVGColors['mediumturquoise'] = [72,209,204];
SVGColors['mediumvioletred'] = [199,21,133];
SVGColors['midnightblue'] = [25,25,112];
SVGColors['mintcream'] = [245,255,250];
SVGColors['mistyrose'] = [255,228,225];
SVGColors['moccasin'] = [255,228,181];
SVGColors['navajowhite'] = [255,222,173];
SVGColors['navy'] = [0,0,128];
SVGColors['oldlace'] = [253,245,230];
SVGColors['olive'] = [128,128,0];
SVGColors['olivedrab'] = [107,142,35];
SVGColors['orange'] = [255,165,0];
SVGColors['orangered'] = [255,69,0];
SVGColors['orchid'] = [218,112,214];
SVGColors['palegoldenrod'] = [238,232,170];
SVGColors['palegreen'] = [152,251,152];
SVGColors['paleturquoise'] = [175,238,238];
SVGColors['palevioletred'] = [219,112,147];
SVGColors['papayawhip'] = [255,239,213];
SVGColors['peachpuff'] = [255,218,185];
SVGColors['peru'] = [205,133,63];
SVGColors['pink'] = [255,192,203];
SVGColors['plum'] = [221,160,221];
SVGColors['powderblue'] = [176,224,230];
SVGColors['purple'] = [128,0,128];
SVGColors['red'] = [255,0,0];
SVGColors['rosybrown'] = [188,143,143];
SVGColors['royalblue'] = [65,105,225];
SVGColors['saddlebrown'] = [139,69,19];
SVGColors['salmon'] = [250,128,114];
SVGColors['sandybrown'] = [244,164,96];
SVGColors['seagreen'] = [46,139,87];
SVGColors['seashell'] = [255,245,238];
SVGColors['sienna'] = [160,82,45];
SVGColors['silver'] = [192,192,192];
SVGColors['skyblue'] = [135,206,235];
SVGColors['slateblue'] = [106,90,205];
SVGColors['slategray'] = [112,128,144];
SVGColors['slategrey'] = [112,128,144];
SVGColors['snow'] = [255,250,250];
SVGColors['springgreen'] = [0,255,127];
SVGColors['steelblue'] = [70,130,180];
SVGColors['tan'] = [210,180,140];
SVGColors['teal'] = [0,128,128];
SVGColors['thistle'] = [216,191,216];
SVGColors['tomato'] = [255,99,71];
SVGColors['turquoise'] = [64,224,208];
SVGColors['violet'] = [238,130,238];
SVGColors['wheat'] = [245,222,179];
SVGColors['white'] = [255,255,255];
SVGColors['whitesmoke'] = [245,245,245];
SVGColors['yellow'] = [255,255,0];
SVGColors['yellowgreen'] = [154,205,50];

CommentsTags:

Older Entries »