PHP 5 – Sort by Folder

Recently, I needed to display a list of files with PHP. My only caveat was that I wanted to do so using newer methods of PHP 5 where possible.

I was delighted to find scandir. Problem was, scandir returns files mixed with folders and that would upset my flock of easily frightened Windows users.

So a quick… er medium… ok fine,  an exasperating search on Google and only outdated, complex and inefficient samples were to be found. PUFF!

So, here is the version I came up with.

Demo

Downloads

How it works

The most crucial part of all the code you will see inside the demo is the PHP getObjects() function. Without this everything else would be moot so lets go over it in a bit more detail.

function getObjects($path) {
    $path .= '/';
    $array = scandir($path); // returns an array of files and folders sorted alphabetically
    $array = array_diff($array, array('.', '..', '.DS_Store', 'Thumbs.db')); // filter out things we don't want

    $return_array = array();

    foreach($array as $item) {
        if(is_dir($path . $item)) {
            $return_array[$item] = getObjects($path . '/' . $item);
        }
    }

    $count = 0;
    foreach($array as $item) {
        if(!is_dir($path . $item)) {
            $return_array[$item] = $item;
            $count++;
        }
    }
    if($count == 0) {
        $return_array[''] = '';
    }

    return $return_array;
}

Line 3
Scandir returns an array of mixed folders and files for the path requested. This does not include sub directories.

Line 4
Filter out any undesirables. That means the current ‘.’ and parent directory ‘..’ although we don’t want any Mac ‘.DS_Store’ or WIndows ‘Thumbs.db’ files either.

Line 6
We create a new array called $return_array which will be built up with all the folders and files in the order we want them. Folders first, then files. Both alphabetically.

Line 8-12
Here we loop through each item in our filtered results from scandir. If the item is a directory we set the results of $return_array[$item] to a recursive call of the very same function we are already in. Traveling deeper each recursive call, that means we can handle seemingly infinite directory structures. Neat.

This first loop through only cares about directories which is exactly what puts them first in our $return_array. Files will come next.

Line 14
We set a variable $count to 0 to keep track of how many files we find in the next foreach loop.

Line 15-19
In this second loop we check to make sure the items are not directories and if so return those items while incrementing the $count variable.

Line 21-23
Now that we are finished looping for files we can check our $count variable. If 0 then set $return_array to ”. This can useful later in case we want to do something special for directories without files.

Line 25
Finally, we return whatever we have found. In most cases this means returning an $array to another instance of the function although ultimately the original one will return a completed array to the PHP call outside our function that started it all.

In the demo we can now loop through this nicely ordered array and write out some HTML and CSS, add a sprinkle of JavaScript and we have a real working web app.

Epilogue

Once you get your head around recursive loops things become much simpler. Plus you get to worry more about optimizing your code since each loop can be run so many times. It’s a good problem to have, really.

Anyway, I certainly hope this helps you in your next endeavor. I know I certainly would be lost without all the wonderful code and tutorials shared by others.

Cheers!


Add a password reset feature to Halogen eAppraisal

One really important feature missing from Halogen eAppraisal is the ability for users to reset their own passwords.

Seems like such a basic feature but even their friendly support folks confirmed that there was no addon or plan to release the feature in a future version. Weird!

No matter though, let’s make our own.

Investigation

I spent untold amounts of time clawing through unfamiliar Java code. A occasional scrap was enough to forge my determination but nothing really made sense yet. Too many files, too many directories but maybe if I just kept trying…

A-ha!

Hidden deep within the lair of <Tomcat>\webapps\Halogen\WEB-INF\classes\com\halogensoftware\common\security\ is a file called ‘Utility.class’. Inside, a string that resembles the worst regular expression ever created.

^a`Z{b1Y}c2X[d3W]e4V|f5U\g6T:h7S;i8R”j9Q’k0P<l-O>m=N?n~M,o!L.p@K/q#Jr$Is%Ht^Gu&Fv*Ew(Dx)Cy_Bz+A

I was sure this string was used to encrypt the passwords stored in the database but I needed a way to confirm that so…

Using a test account I set the password to the number 1 which was encrypted as the letter Y. Password 11 became Y}. Password 111 became Y}c.

Ah, so simple!

If your password was the ^ symbol it would find it in the string above and then move right one space and choose the letter “a” as your encrypted password. If your password was ^^ then the the first encrypted character would be “a” again but the second one would shift two places to the right and store the ` symbol

Here are a few more example conversions.

  • ^^^ becomes a`Z
  • wT7w becomes (hi)
  • A+z becomes ^^^

Notice that in the last example we’ve simply looped around once we hit the right side of the hash string.

Now that we know how it works let’s build our own utility in ASP that we can use to reset anyone’s password.

The Solution

Besides the obvious DSN string, you’ll want to carefully consider how you validate your users.

The setup I used at work talked to a Human Resources database and would validate no less than three pieces of information before even attempting a reset. I urge you dear reader to do the same.

sID = Request.Form("id")
sPassword = Request.Form("password")

Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open "DSN String for the Halogen eAppraisal Database"

Set oRS = Server.CreateObject("ADODB.Recordset")
oRS.Open "SELECT TOP 1 * FROM [view-user_info] WHERE username = '" & sID & "'", oConn, 0, 3 'adOpenForwardOnly, adLockOptimistic

If not oRS.EOF then
	sKeyCode = "a`Z{b1Y}c2X[d3W]e4V|f5U\g6T:h7S;i8R""j9Q'k0P<l-O>m=N?n~M,o!L.p@K/q#Jr$Is%Ht^Gu&Fv*Ew(Dx)Cy_Bz+A"
	sKeyCodeLength = Len(sKeyCode)
	x = 1
	sBadChar = 0
	Do until x > Len(sPassword)
		sChar = Mid(sPassword, x, 1)

		If InStr(sKeyCode, sChar) then
			sKeyCodePos = InStr(sKeyCode, sChar) + x
			If sKeyCodePos > sKeyCodeLength then
				'Need to loop around the beginning
				Do until sKeyCodePos <= sKeyCodeLength
					sKeyCodePos = sKeyCodePos - sKeyCodeLength
				loop
			End If
			sEncodeChar = Mid(sKeyCode, sKeyCodePos, 1)
			sEncodePassword = sEncodePassword + sEncodeChar
		Else
			'Could not find a character in sKeyCode
			sBadChar = sBadChar + 1
		End If
		x = x + 1
	loop

	If sBadChar > 0 then
		Response.Write "<p><strong>Unsupported characters were used to try to set the encrypted password. New password was not saved.</strong></p>"
	Else
		oRS("password") = sEncodePassword
		oRS("password_change_date") = NULL
		oRS.Update
		Response.Write "<p>The password for your account " & sID & " has been reset.</p>"
	End If
Else
	Response.Write "<p><strong>A corresponding account for the user " & sID & " does not exist. Please contact support.</strong></p>"
End If

oRS.Close
oConn.Close
Set oRS = nothing
Set oConn = nothing

Questions welcome so feel free to comment below.

See ya later, space cowboy.


Disable right clicking on images only

There are few instances where disabling someone’s context menu is appropriate. In most cases it’s unnecessary and can even lead to infuriating your visitors.

Here are some ways to target all the image elements on a page while leaving the rest of the hypertext in peace.

JavaScript

Lightweight, no framework required and works well in IE 6, 7, 8, Chrome, FireFox and Safari. Demo »

document.oncontextmenu = context_menu;

function context_menu(e) {
if (!e) var e = window.event;
	var eTarget = (window.event) ? e.srcElement : e.target;

	if (eTarget.nodeName == "IMG") {
		//context menu attempt on top of an image element
		return false;
	}
}

jQuery

Perhaps the prettiest code of the three. Demo »

$(document).ready(function(){
	$(document).bind("contextmenu",function(e){
		if(e.target.nodeName == 'IMG'){
			//context menu attempt on top of an image element
			return false;
		}
	});
});

MooTools

Moo… Demo »

window.addEvent('domready', function() {
	$(document.body).addEvent('contextmenu', function(e) {
		if(e.target.nodeName == 'IMG') {
			//context menu attempt on top of an image element
			return false;
		}
	});
});

Final Thoughts

With a bit more code you can target specific IDs, class names or any number of elemental combinations. Doing so will limit your context menu friendly fire and keep both you and your users in a happy balance.

Cheers!