Batch Uninstall Windows Updates

This post shows how to programmatically automatize the batch uninstall of multiple Windows Update hotfixes. The code samples are in AutoHotKey syntax, and you can get the full source code, as well as compiled executables ready to run, on the Windows Updates Uninstaller Utility online repository.

Listing the Updates

The simplest way to get a list of the installed Windows Updates is through WMIC, which is an internal Windows command-line interface for accessing management functions. Using the QFE module, we can generate a list by running the following command, for example from the Command Console:
wmic qfe get "HotFixID" /format:table

This will list the installed updates directly in the console, like this:
updates list on console

It’s easier to parse them from a text file, and luckily our friend QFE can do that for us too with the following command:

wmic qfe list brief /format:texttablewsys >"%Path_of_the_text_file%"

where %Path_of_the_text_file% is what it says, the path of the text file to be created, such as C:\hotfix.txt for example, or wherever. When listing in a file, it won’t list individual columns but the whole table, so you’ll need to use character offsets when parsing columns.

Uninstalling the Updates

To uninstall each update, the easiest way is to use WUSA, which is a built in Windows utility for managing Windows Updates. Since you already have a list of the installed updates, you just need to extract the hotfix ID number from each row, and run the following command for each update:

wusa.exe /kb:%HotfixId% /uninstall /quiet /norestart

where %HotfixId% is the hotfix ID number. For example, to uninstall update KB279503 you need to run the following:

wusa.exe /kb:279503 /uninstall /quiet /norestart

and so on. Since uninstalling each update takes time, you should wait for one uninstall to end before beginning the next one. If you’re using AutoHotKey, you can simply use the RunWait command and it will wait for each execution to finish before starting the next one.

Putting it all together

The essence is simple: get the list of updates, parse it to retrieve the hotfix IDs, and uninstall them one by one. If you’re into AutoHotKey, it’s pretty easy to do, as you can see at the Windows Updates Uninstaller Utility online repository. There you’ll find an AutoHotKey implementation with a basic GUI, in both source-code and compiled executable form, so you can toy with the code or use as-is.

Install PHPUnit with VisualPHPUnit on a Shared Hosting Server

Update: The 4.x branch of PHPUnit has some changes, such as no longer using Autoload.php, that make this tutorial outdated. I’ll try to see if the new versions can be run on shared hosting as well, but in the meantime, the following instructions only apply for PHPUnit 3.x.

Here’s how to install and run PHPUnit with the VisualPHPUnit graphical interface, on any shared hosting server, without need for PEAR, composer, phar, or SSH command line; in fact all you need is your web browser, FTP access, and a code editor such as Notepad++.

PHPUnit: Dependency Madness

PHPUnit is the best case against the DRY philosophy I’ve ever came across, since it’s chock-full of random dependencies you won’t even be using for anything else. As such, be prepared to download and extract a helluva lot of packages.

First of all create a folder on your computer for housing all necessary files and directories, I’ve named mine Utilities for reference. Now go to https://github.com/sebastianbergmann/phpunit/branches and check the requirements of every numbered version until you find the newest one that will run on the php version you’ve got on your server. If you don’t know which version of php you’re using, run phpinfo() to find out. Download the zip for your version, and extract just the PHPUnit folder inside into Utilities.

Go to https://github.com/sebastianbergmann/php-file-iterator, download the zip and extract just the File folder into Utilities.

Go to https://github.com/sebastianbergmann/php-text-template, download the zip and extract just the Text folder into Utilities.

For the next 3 packages, download the zip files and extract just the PHP folder in each zip into Utilities (merge the folders):
https://github.com/sebastianbergmann/php-code-coverage
https://github.com/sebastianbergmann/php-timer
https://github.com/sebastianbergmann/php-token-stream

Now create a folder inside Utilities called SebastianBergmann . Now create 3 folders inside SebastianBergmann, called: Diff , Exporter , and Version . For the next 3 packages, download the zip files and extract just the contents of the src folder (not the folder itself, only its contents) in each one into the corresponding folder inside SebastianBergmann:
https://github.com/sebastianbergmann/diff
https://github.com/sebastianbergmann/exporter
https://github.com/sebastianbergmann/version

Finally, go to https://github.com/sebastianbergmann/phpunit-mock-objects, download the zip and extract just the PHPUnit folder into Utilities (merge it with the existing folder).

Great, now that you’ve got PHPUnit and all its dependencies, upload the “Utilities” folder to your server, preferably into a non web-accesible location. For reference, your folder tree should look like this:

folder tree

VisualPHPUnit: Let there be GUI

Now that PHPUnit is on your server, let’s make it usable with a web browser based GUI. Download the zip from https://github.com/NSinopoli/VisualPHPUnit, extract it, and rename the main folder if you want (I creatively renamed mine to VisualPHPUnit for reference).

Go into app/config/bootstrap.php and make the following changes:

  • Comment or delete the following line:
    'pear_path' => '/usr/share/pear',
  • The default directory for tests is VisualPHPUnit/app/test , if you wish to change it or add other directories, modify the ‘test_directories’ array. By the way, $root points to the VisualPHPUnit folder.
  • Comment or delete the following lines:
    set_include_path(
    get_include_path()
    . PATH_SEPARATOR . $root
    . PATH_SEPARATOR . $config['pear_path']
    );
  • Below the lines you just commented, add the following two, changing the relative paths so that they point to your Utilities folder from the web-accessible folder where you’ll upload the VisualPHPUnit package:
    set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Utilities');
    set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Utilities' . '/PHPUnit');

Now upload your VisualPHPUnit folder to a web-accessible location on your server. Fire up your browser, open your VisualPHPUnit location, and see if you feel lucky.

Well do you, punk?

If your stars have aligned now you should have a working install of PHPUnit with VisualPHPUnit. If not, it’s troubleshooting time!

“Fatal error: require_once() [function.require]: Failed opening required ‘PHPUnit/Autoload.php'”

Your include paths in VisualPHPUnit/app/config/bootstrap.php are wrong, sort them out

“Fatal error: require_once() [function.require]: Failed opening required {any other file related to phpunit}

You missed a PHPUnit dependency, you can find all the packages you need (and then some more) at https://github.com/sebastianbergmann?tab=repositories

“404: Not Found” error / You just get the Index of your /VisualPHPUnit folder

You’ve got the curse of the .htaccess, brought on by lazy open-source web development practices. There are 2 .htaccess files in VisualPHPUnit that are used to redirect requests, and we need to fix them.

First open the .htaccess file in the “VisualPHPUnit” folder.

  • Find the following line:
    RewriteRule ^$ app/public/ [L]
    add an [R] flag so that you can see the redirected address in your browser, so the line becomes:
    RewriteRule ^$ app/public/ [L,R]
  • Go to your web browser, reload your VisualPHPUnit tab, and check the address to which you’re being redirected. It should be {your VisualPHPUnit location}/app/public/ . Since it’s not, find the following line in your .htaccess file:
    RewriteEngine on
    and insert the following line after it:
    RewriteBase /
  • Reload again your browser tab, and check where you’re being redirected now. Part of the path will probably be missing in the middle, so you’ll need to edit the line you just added so that your browser ends up redirecting you correctly to {your VisualPHPUnit location}/app/public/ . In my case I had to change it to this:
    RewriteBase /VisualPHPUnit/
  • Once you get redirected to the correct address, you need to remove the [R] flag you set at the beginning, so that the line you modified to
    RewriteRule ^$ app/public/ [L,R]
    becomes once again
    RewriteRule ^$ app/public/ [L]

Your browser should load VisualPHPUnit now, but tests will not work since we need to fix the remaining redirection. Go into VisualPHPUnit/app/public and open the .htaccess file there.

  • Find the following line:
    RewriteRule ^(.*)$ index.php [QSA,L]
    and insert the [R] redirection flag as before, so the line becomes:
    RewriteRule ^(.*)$ index.php [QSA,L,R]
  • Go to your browser and open the link on the top of your VisualPHPUnit tab that says “Archives”. Check the address bar to see where you are being redirected. You should be redirected to {your VisualPHPUnit location}/app/public/index.php . Since you’re not, you know the drill, find the following line in your .htaccess file:
    RewriteEngine on
    and insert the following line after it:
    RewriteBase /
  • Reload your browser tab, check where you’re being redirected and what’s missing in the path, and modify the line you just added until the redirection takes you to the correct address. In my case, I had to change it to this:
    RewriteBase /VisualPHPUnit/app/public/
  • Once you get redirected to the correct address, you need to remove the [R] flag you set, so that the line you modified to
    RewriteRule ^(.*)$ index.php [QSA,L,R]
    becomes once again
    RewriteRule ^(.*)$ index.php [QSA,L]

Now you should be able to see the files in your test directory and run tests.

Tests don’t run and return empty results

You’re using a PHPUnit version that requires a newer PHP version to run. Get an older version of PHPUnit.

“Fatal error: Uncaught exception ‘PHPUnit_Framework_Error_Notice’ with message ‘Non-static method PHP_Timer::start() should not be called statically, assuming $this from incompatible context'” when you try running tests

You’ve got the curse of the shitty non-backwards-compatible dependency refactoring, go into your Utilities folder and open PHPUnit/Framework/TestResult.php and make the following changes:

  • Find the following line:
    PHP_Timer::start();
    comment it out or delete it, and insert the following 2 lines after it:
    $timer = new PHP_Timer;
    $timer->start();
  • Find the following line:
    $time = PHP_Timer::stop();
    comment it out or delete it, and insert the following line after it:
    $time = $timer->stop();

Your tests should run fine now.

Sorting objects hierarchically in recursive multidimensional arrays in PHP

When retrieving a group of objects from a database, sometimes we need to recreate some hierarchy inside a multidimensional array or object for further processing. However, since the language wasn’t developed with such usage scenarios in mind, the way to achieve this is anything but intuitive. Many developers just adjust their DB structure in order to make such sorting easier, but it’s always good to have a choice. I recently came across this problem myself, and think the solution I came up with is not only interesting, but could be useful to other developers out there. If you find this useful, or would like to propose a different solution, I’d love to read your comments below.

The Problem

Let’s say, as an example, that you have a DB table with columns id and parent, where id is an auto-generated primary key, and parent refers to id by a foreign key. The idea is every entry has either a parent in the same table, or a NULL parent and hence is at the top level of the hierarchy. We do not know how deep the hierarchy goes, and must be able to recursively populate a multidimensional array or object in order to recreate it.

The (Generic) Solution

First of all, we assume we are retrieving all entries into a plain array. We ORDER BY parent ASC, with NULLS first so we process the top level entries first. We will need to create 2 arrays, one for storing the entries hierarchically, and the other to keep track of the path of each entry inside the hierarchy. We will be dealing with arrays exclusively in this example, but using objects instead is pretty straightforward.


$entries = yourGetEntriesFromDbFunction();  //The array with our retrieved DB entries
$entryRecords = array();                    //Our hierarchy will be created in this array
//We will track the path of each entry here, with an array
//for each entry containing the ids of all its ancestors:
$entryPaths = array();
foreach ($entries as $entry) {
    //Create a new key inside each entry to store its children:
    $entry['children'] = array();
    $entryPaths[$entry['id']] = array();    //Make a space for the path of the entry
    if ($entry['parent'] === NULL) {        //If top level, just insert into the hierarchy array
        $entryRecords[$entry['id']] = $entry;
    } else {
    	$pathRef =& $entryRecords;          //Save a reference to the top level of our hierarchy
        //Traverse our current hierarchy based on the path of the entry's parent by reassigning a
        //single variable by reference to the children container of each level in the hierarchy:
        foreach ($entryPaths[$entry['parent']] as $path) {
    		$pathRef =& $pathRef[$path]['children'];
    	}
        //Once we reach the entry's parent's children container, just add the entry to it:
        $pathRef[] = $entry;
        //Register the entry's path by first copying parent's path
        $entryPaths[$entry['id']] = $entryPaths[$entry['parent']];
    }
    $entryPaths[$entry['id']][] = $entry['id']; //Finally add the id of the entry to its path
}

As you can see, the main idea is to save the path of each entry we insert in order to know how to get to it, and then traverse the path of the parent by reassigning references to the children container of each post in the path. This way we can always reach the parent of a post inside our hierarchy, no matter how complicated, provided that all parents are inserted before their children into it.

Speak Yii to me

Actually, I came up with this algorithm while working with Active Records on Yii Framework, so might as well share the code that inspired this post. I have a Section Model, with id, parent, and order columns. id and parent are as in the above example, but the order column provides the order in which the children in a post should be sorted. I added a public property named “children” to the Model in order to be able to store a record’s children in it, but that’s all. Since it’s the same principle as above, it’s mostly uncommented:


$sections = Section::model()->findAll(
    array('order'=>'parent ASC NULLS FIRST,"order"'));  //PostgreSQL FTW
$entryRecords = array();
$entryPaths = array();
foreach ($sections as $section) {
	$section->children = array();
    $entryPaths[$section->id] = array();
    if ($section->parent === NULL) {
        $entryRecords[$section->order] = $section;
    } else {
    	$pathRef =& $entryRecords;
        foreach ($entryPaths[$section->parent] as $path) {
    		$pathRef =& $pathRef[$path]->children;
    	}
        $pathRef[] = $section;
        $entryPaths[$section->id] = $entryPaths[$section->parent]; 
    }
    $entryPaths[$section->id][] = $section->order;
}

Hope you find some of this as useful as I did, and if you find this solution pretty obvious or even intuitive, congratulations: you’re a better web developer than I am.

What is Google Authenticator, and how it can protect your personal and business accounts

In this day and age when concepts like hacking, phishing, and identity theft have become commonplace because of their prevalence, it’s no wonder companies in the tech sector are heavily investing in security technologies in order to keep themselves, and their clients, one step ahead of the game. Google, being one of the biggest web companies, with hundreds of millions of user accounts, is one of them, and has developed a really ingenious authentication system that can be used not just to protect their own user accounts, but also many existing third-party platforms.

Authentication

The use of passwords, or passphrases, to make sure a user is really who he says he is, has been the cornerstone of user authentication since the advent of computing. The premise is simple: since the password is secret, only the real user should know it, right? However, the weakness of such a system is that an unchanging password can be guessed, either “by hand”, or programatically through what is called a brute force attack. It can also be stolen by intercepting a user’s communications, such as his requests to log into his account. The solution? An “ever-changing” password.

OTP – One Time Password

Being realistic, changing your password each time you use it to login wouldn’t be practical. Not only would you waste a lot of time each time we go into our account, but tracking what the password is at any given time would be a logistical nightmare. But, what if your user account did all of this for us automatically? That is the premise of OTP algorithms: each time you login, you use a different password, automatically generated by an application on your computer or smartphone. It is precisely this technology that Google has implemented to secure even further their user accounts; they call it two-factor authentication. To show the system you really are who you say you are, you supply two proofs of identity: something only you know (your “static” password, as you have always done until now), and something only you own (your computer or smartphone which generates the one-time code, i.e. your “ever-changing” password). In this case the One Time Password doesn’t substitute your static password, but actually adds another layer of security on top of it. That way, even if either your static password or your authenticating device (your PC or smartphone) gets stolen, the perpetrator cannot log into your account without the other one.

Securing your Accounts

Google Authenticator is based on open standards, and there are not only existing implementations for popular web systems and frameworks, but also open source libraries for integrating this technology into any user system imaginable. There are Google Authenticator solutions available for WordPress, Joomla, Prestashop, Magento, as well as the native implementation for Google and GApps accounts. As for authenticating devices, there are free apps for Android, iPhone, and Blackberry devices, Windows, Mac OS, and Linux PCs, and there are even specialized standalone gadgets you can purchase. If you are reading this, chances are you already own a device you can use for authentication; if that’s the case, don’t you have an account worth protecting?

Disclosure: I’m the developer of the Prestashop and module mentioned above, so you might say I have some vested interest in the success of the Google Authenticator technology; however the reason I developed this solution in the first place is because I think the technology really provides value by dramatically increasing the security of user accounts in a relatively simple yet elegant way. Isn’t that what development is all about?

Retrofitting jQuery prop() for when using both older and newer jQuery versions

When upgrading your existing website to jQuery 1.6 or higher, you may have noticed that the attr() method stopped working like it has since time immemorial, breaking all previous code that used it. Supposedly jQuery 1.61 added some backwards compatibility fixes, but they don’t really work, at least for me. They say “just replace all attr() calls for prop() and be done”, however it’s not that simple if your code is supposed to work on different versions of jQuery, for example when developing extensions or modules for constantly updated frameworks, since prop() didn’t exist before jQuery 1.6.

Actually, there is a simple way to make your code work on both older and newer jQuery versions. All you need to do is replace all attr() calls for prop() (it takes the same arguments so don’t worry), and add the following before your code:


       if (typeof jQuery.fn.prop != 'function') {
            jQuery.fn.prop = jQuery.fn.attr;
        }
    

All this does is check if the prop() method exists, and if not, it creates it by cloning attr(). Hope this saves you some time.

Write most latin script based languages with special characters quickly and easily on a US layout keyboard in Windows

Do you have a US Standard layout keyboard, but need to write in another language which uses special letters or diacritics? Possibly even various languages with their own different latin script based characters? If you want the quickest, most versatile and intuitive way right away, you can skip the rest of this post and download Intuitive Keyboard Expander. If you want to know how it works, as well as other more limited ways to write such characters, then keep on reading.

Keyboard Language Settings

On Windows systems, perhaps the most used way to type another language’s special letters and characters is to change the keyboard language (layout) configuration. In the Regional and Language Options in the Control Panel, you can add other languages’ layouts, and change between them by either pressing the Alt+Shift key combination, or manually on the Languages toolbar, which normally appears on the Taskbar when you have more than one language installed. The shortcomings are that you need to activate the corresponding layout each time you want to change the language you’re using, and that you must know by heart which keys do what on each layout (for example, the ; key on a US Standard keyboard will write ñ instead on a Latin American layout, and most of the symbols are in different keys).

Character Map

Another, more cumbersome way, is to copy the needed characters from the Character Map (in Accesories->System Tools from the Start Menu). This way you can get practically any character you want, at the cost of having to look for it, copy it, and paste it on your document each time you need to use it. For typing lots of text, or just in a language with a lot of diacritics and special letters, this is obviously not practical because of the sheer amount of time you need to get each one of these characters.

RichEdit-Enabled Programs

In some programs which use the RichEdit control, such as Wordpad, you can enter many special characters by writing their Unicode Hexadecimal Code, followed by the Alt+X key combination. The disadvantages are that it doesn’t work in most programs, you have to actually know the Hexadecimal Code of every character you’re going to use, and that you can’t write numbers or the letters af immediately preceding the special character, because they’re going to be treated as part of the Code.

Alt Codes

A more technical, yet savvy way, is to use what is commonly known as the “Alt Codes”. There are actually two types of “Alt Codes”, the Decimal and the Hexadecimal. The Decimal codes work by default on most Windows installations, but the problem is they’re not Universal because they depend on your computer’s Code Page (basically the list of allowed characters on each specific language version of the Operating System, which has actually become obsolete thanks to the advent of Unicode, but for legacy reasons it’s still embedded in Windows up to this day). This means that two computers configured in different languages will write different characters for each Code. To use them you need to hold the Alt key while typing the Decimal Code of the character on the Numeric Keypad. Of course you need to know the Decimal Code for each character.

The Hexadecimal “Alt Codes” work in a very similar way to the Decimal ones, but with a few changes. First of all, they’re Universal, which means a given Code will type the same Unicode character on any computer, regardless of language settings. Also you have a way larger set of possible characters you can input, because it supports any Unicode character. The disadvantages would be that it’s not enabled by default in many versions of Windows, so you would need to add a key to the Registry for it to work (EnableHexNumpad as a REG_SZ type with a value of 1, in HKCU\Control Panel\Input Method\), and that as with the Decimal variant, you would need to know the Hexadecimal Code for each character. To use them, you need to hold the Alt key while typing first the + Key on the Numeric Keypad, and then the Hexadecimal Code anywhere on the keyboard.

Intuitive Keyboard Expander

So… is there a better way to type special characters from other languages? Yes, and it’s called Intuitive Keyboard Expander. What this free program does is transform some of your normal keys into special modifiers, much like Ctrl or Alt, but without losing the key’s functionality. For example, if you hold the (apostrophe) key while typing a letter, you will get that letter with an acute accent, as in áóúśź, but if you just release it without pressing other letters, you will get its intended function, in this case (apostrophe). All the modifiers are very intuitive and easy to remember (for example` for Grave Accents, , (comma) for Cedillas and Ogoneks, / for diagonal strikes as in øł¢, : for diaeresis and umlauts, etc.), and all in all they allow you to write more than 70 different latin script based languages.

This program works by using the Windows API to send Unicode characters as virtual keys. There are only two minor disadvantages, which are that you’ll need to hold the right arrow key to use the autorepeat functionality of the keys assigned as special modifiers, and that some key combinations may not work on cheaper keyboards because of key ghosting. The best of all is that it’s Open Source, which means you can check and even compile the code yourself, if you aren’t too trusting. Anyway if this sounds like a program that could be useful to you, check the full documentation and download it from the official website.