Archive by Author

PHP: Detect if Script is Running from Console

I hacked together a script to import a large amount of data from a CSV file that was not very fun to work with, and I felt the need to restrict access to the command line in case there was any extra overhead in the script, or anything unforeseen quirks from running such an intensive script in the browser. (I didn’t really have to restrict access as I removed the import script after it was run, but now I needed to know.) Somehow, I needed to capture information about exactly HOW the script was being executed. It’s actually quite simple, PHP captures your console environment into a $_SERVER variable, specifically $_SERVER['CONSOLE'] and/or $_SERVER['TERM'].

if(!isset($_SERVER['SHELL'])) { echo "Please run this script from the console."; exit; }

[Edit: Shortly after posting the above snippet, I found a PHP function (see: php_sapi_name) that returns the type of interface between the web server and PHP. In this case, we are looking for it to return the value 'cli' for command line interface.]

if(php_sapi_name() != 'cli') {  echo "Please run this script from the console."; exit; }

The Hacker’s Code

“A hacker of the Old Code.”

  • Hackers come and go, but a great hack is forever.
  • Public goods belong to the public.*
  • Software hoarding is evil. Software does the greatest good given to the greatest number.
  • Don’t be evil.
  • Sourceless software sucks.
  • People have rights. Organizations live on sufferance.
  • Governments are organizations.
  • If it is wrong when citizens do it, it is wrong when governments do it.
  • Information wants to be free. Information deserves to be free.
  • Being legal doesn’t make it right.
  • Being illegal doesn’t make it wrong.
  • Subverting tyranny is the highest duty.
  • Trust your technolust!

* Definition: A good is public if the marginal production cost is lower than the marginal billing cost.

AdSense Earnings RSS Feed

/*
Hack Name: Adsense to RSS
Version: 1.1
Hack URI: http://planetozh.com/blog/my-projects/track-adsense-earnings-in-rss-feed/
Description: Follow your Adsense earnings with an RSS reader
Author: Ozh
Author URI: http://planetOzh.com
*/

/*
 * Release History
 *
 * 1.1 (04/23/2006 - CGibson)
 * Fixed to work with recent modifications to Google AdSense
 * - Changed "csv" post data field to "outputFormat"
 * - Changed spliting of date from "/" to "-"
 *
 * 1.0 (10/07/2005)
 * Initial Release
*/

/************ SCRIPT CONFIGURATION ***********/
/*********************************************/

$username="you@email.com";
    // your adsense username

$password="MySuPeRpAsSwOrD";
    // your adsense password

$daterange = 20 ;
    // range of days to aggregate in RSS reader

$cookie="./.cookiefile";
        // a temp file name - you mostly don't care about this
        // This will create a hidden file in the current directory. If it seems to fail,
        // replace with a full physical path (i.e. /home/you/temp/cookiefile)

/************ DO NOT MODIFY BELOW ************/
/*********************************************/

$daysbefore = mktime(0, 0, 0, date("m") , date("d") - $daterange, date("Y"));
list ($d_from,$m_from,$y_from) = split(':',date("j:n:Y", $daysbefore));
list ($d_to,$m_to,$y_to) = split(':',date("j:n:Y"));

/* Following lines are based on a script found on WMW forums */
/* http://www.webmasterworld.com/forum89/5349.htm */

$destination="/adsense/report/aggregate?"
    ."sortColumn=0"
    ."&reverseSort=false"
    ."&outputFormat=TSV_EXCEL"
    ."&product=afc"
    ."&dateRange.simpleDate=today"
    ."&dateRange.dateRangeType=custom"
    ."&dateRange.customDate.start.day=$d_from"
    ."&dateRange.customDate.start.month=$m_from"
    ."&dateRange.customDate.start.year=$y_from"
    ."&dateRange.customDate.end.day=$d_to"
    ."&dateRange.customDate.end.month=$m_to"
    ."&dateRange.customDate.end.year=$y_to"
    ."&unitPref=page"
    ."&reportType=property"
    ."&searchField="
    ."&groupByPref=date";

$postdata="destination=".urlencode($destination)."&username=".urlencode($username)."&password=".urlencode($password)."&null=Login";

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,"https://www.google.com/adsense/login.do");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt ($ch, CURLOPT_TIMEOUT, 20);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch); 

$result=preg_split("/\n/",$result);
array_pop($result);
array_pop($result);
array_shift($result);
$result = array_reverse($result);

header('Content-type: text/xml');
echo '';
echo "\n";
echo '\r\n";
echo "\r\n";
echo "\t\r\n";
echo "\t
https://www.google.com/adsense/\r\n";
echo "\tAn RSS feed of my Adsense earnings for the last " . $daterange . "days\r\n";
echo "\ten\r\n";

$firstday=1;
foreach ($result as $line) {
	$item = array();
	$line = str_replace("\x00",'',$line);
	$line = str_replace('"','',$line);
	list($day, $pages, $clicks, $ctr, $eCPM, $income) = preg_split("/\s/",$line);
	$item['title']= "";
	$item['guid'] = '' . md5($username.$day) . "";
	$day = split('-',$day);
	$day = mktime(0, 0, 0, $day[1] , $day[0], $day[2]);
	if ($firstday == 1) {
		$day = date("D, d M Y H:i:s +0000");
		$firstday = 0;
	} else {
		$day = date("D, d M Y H:i:s +0000", $day);
	}
	$item['pubDate'] = "
$day";
	$item['category'] = "";
	$item['description'] = "\$$income ($clicks clicks on $pages pages : CTR = $ctr - eCPM = $eCPM)";
	$item['content'] = "\r\n\t

Pages printed
Clicks
CTR
eCPM
Earnings


\r\n\t

$pages
$clicks
$ctr
$eCPM
$income


\r\n\t

\r\n]]>\r\n";

	print "\r\n";
	print $item['title'] ."\r\n";
	print $item['guid'] ."\r\n";
	print $item['pubDate'] ."\r\n";
	print $item['category'] ."\r\n";
	print $item['description'] ."\r\n";
	print $item['content'] ."\r\n";
	print "\r\n";
}

echo "\r\n";
echo "";

LiveJournal Image Search

/*
	lj.php - yet another LiveJournal image getter thingy
		by Ryland Sanders
		Friday, November 24, 2006
		This source code is released into the public domain, copy it and modify it as you see fit. A link and credit would be nice, though.
		This script gets the "latest images" XML stream from LiveJournal, parses it, filters it, and displays the resulting list as clickable links, limited to the number of images specified by the $limit parameter in the query string.
*/

echo "\r\n";
echo "\r\n";
echo "\t\r\n";
echo "\t


\r\n";
echo "\r\n";
echo "\r\n";
echo "\r\n";
echo "

LiveJournal images

\r\n"; echo '
LiveJournal images XML feed :: PHP source code for this page ' . "\r\n"; /* put script file name of this page in a variable (just in case you change the filename but forget to update the script with the new name) */ $thispage = getenv("SCRIPT_NAME"); /* get the 'limit' parameter from the query string. if the server is configured with register_globals turned on, it does this for you automatically, but I like to add zero to numerical values from the query string to make sure it's a number. if there's no 'limit' paramter in the query string, set it to the default, 100 images. */ $limit = $_GET['limit'] + 0; if (!$limit) { $limit = 100; } echo " Number of images: " . $limit . " - Limit to: 25 :: 50 :: 100 :: 250\r\n"; echo "   \r\n"; /* this is a callback function used by array_filter() below to filter our any elements that aren't tagged as 'RECENT-IMAGE' in LJ's xml stream */ function is_img($recent_image) { return $recent_image['tag'] == 'RECENT-IMAGE'; } /* open the stream and assign it to a file handle variable */ $handle = fopen("http://www.livejournal.com/stats/latest-img.bml", "r"); /* dump the stream contents into a string variable */ $ljxml = ""; while (!feof($handle)) { $ljxml .= fgets($handle); } /* close the stream */ fclose($handle); /* create an XML parser object */ $p = xml_parser_create(); /* parse the stream data into an array $vals */ xml_parse_into_struct($p, $ljxml, $vals); /* free the parser object, since we're done with it */ xml_parser_free($p); /* filter the $vals array using the callback function above */ $imgs = array_filter($vals, "is_img"); /* get a subset of the array limited to the number of images in the $limit variable */ if ($limit < 250) { $imgs = array_slice($imgs, 0, $limit); } /* loop through the array and print each array element as a clickable link */ $num_imgs = sizeof($imgs); $ct = 1; foreach ($imgs as $recent_image) { echo " LJ post URL ::\r\n"; echo "Image URL ::\r\n"; if ($ct > 1) { echo "Previous image ::\r\n"; } else { echo "Previous image ::\r\n"; } if ($ct < $num_imgs) { echo "Next image ::\r\n"; } else { echo "Next image ::\n"; } echo "Top of page\r\n"; echo "\r\n \r\n\r\n"; $ct++; } echo "\r\n"; echo "\r\n";

Must Have List of Android Applications

I recently purchased the Motorola Droid X (the day after release, I actually snagged the last one in my area, w00t) and squandered much time in the Google Market, the Android applications store. Here’s my results after downloading tons of apps, from project / time management apps to soundboard, and of course, the Star Wars lightsaber app. Click on the names to view the QR Code that is recognized by the Barcode Scanner application.

Fun / Useless Applications

  • Air Horn
    Use this application to get someone’s attention or annoy them, tons of effects to choose from: vuvuzella, loudspeaker, air horn, and more!
  • Ethereal Dialpad
    Random effects processor / synthesizer thingy, really fun to play with when you’re bored or drunk.
  • Wilhelm Scream
    You know that scream that has been used over and over in film? You can make your phone scream just like that, every time you throw it up in the air!

Localized / Nightlife Applications

  • FourSquare
    Check into your FourSquare account, and find out where your friends are at!
  • HappyHours
    Exactly like it sounds, an app that helps you find the closest bar that is serving drinks at happy hour prices.
  • Wertago
    Find out what’s going on tonight, who’s hanging out at what bar, club, or event, and check reviews of the place (even how hot it is or how much it sucks right now) before you go!

Music Applications

  • AudioBox.fm
    Upload your MP3s from home, play them anywhere on your phone!
  • Pandora
    Must have for any smart phone nowadays, stream radio from the cloud!

File Management

  • FTPServer
    Create an FTP server accessible via internet or intranet to share files to and from your device.
  • Twonky Server
    Create a network accessible share to transfer files to and from your device.

Game Applications

  • Oregon Trail
    Remake of the old classic, it feels a little limited, but it’s still fun!
  • SNESoid
    SNES emulator, and it’s the best one, to say the least.

Blogging Applications

  • WordPress
    Manage your WordPress blogs anywhere, as long as you brought your phone!
  • WP Stats
    Keep a close eye on your WordPress blog statistics any time, anywhere!

Geeky Applications

  • Spot Message
    Leave a message for another person based on GPS location. When they get to the intended destination, they will receive your message.
  • IRSSI ConnectBot
    Must have for geeks, store and run ssh commands, also includes a text based IRC client.
  • PixelPipe
    Post media or blog to over 110+ social networking services, or your own hosted WordPress platform.
  • Torrent-Fu
    Remotely manage your uTorrent or Transmission bittorrent clients.

Resizing DIVs On Browser Load And Resize

I will take Jelo over jQuery any day, but I had to tread in murky waters today making an update to a theme on one of my WordPress blogs.

I had a three column layout, the two sidebars were floated to the right properly, but the text in my main content div was going under my sidebars, to the full 100% width of the page. I couldn’t find a quick CSS solution without rewriting the structure of the page, so I decided to use jQuery, which was already loaded to handle some animations in the menu.

$(document).ready(function() {
  $('#content').css("width", ($(window).width() - $('#sidebar1').width() - $('#sidebar2').width()) + 'px');
});
$(window).bind('resize', function () {
  $('#content').css("width", ($(window).width() - $('#sidebar1').width() - $('#sidebar2').width()) + 'px');
});

Hope this was helpful to some one in some fashion!

Windows 7 Dream Scene Activator

Some of you might remember the “Dream Scene” feature that was available in versions of Windows Vista, where you would be able to set a video in WMV/MPG format as your desktop background. Well, sadly, this feature was eighty-six’ed in Windows 7. (Well, not really, because after a registry tweak, it becomes available again.)

However, Kishan Bagaria of The Windows Club has released a nifty little application that changes a registry value to re-enable this feature in Windows 7. Once you’ve applied this little patch, right click on any WMV/MPG and you will be able to “Set as desktop wallpaper …” from the context menu.

Don’t be confused by the title on the window of this application, it works for Windows 7 64 bit as well!

If you are looking for some neat looped videos to use as your wallpaper, or inspirational ones to make your own, look no further than DeviantART!

Download Windows 7 Dream Scene Activator

Snow Leopard Command Line Hacks

Here are my favorite command line hacks that enable special features or views in OS X 10.6 Snow Leopard.

  • Enable Quick Look Folder Previews
    defaults write com.apple.finder QLEnableXRayFolders 1
    Once you’ve entered this command, restart Finder (killall finder or ctrl+option+click Finder Dock Icon, and Relaunch), select a folder, and hit the space bar.
  • Enable AppleScript Studio Palette
    defaults write com.apple.InterfaceBuilder3 IBEnableAppleScriptStudioSupport -bool YES
    OS X 10.6 Snow Leopard allows you to work on AppleScript Studio Projects, but you can’t create new ones. Run the above command to add it back into Interface Builder.
  • Disable Focus Follows Mouse
    defaults write com.apple.Terminal FocusFollowsMouse -string NO
  • Confine Dictionary To One Window
    defaults write com.apple.Dictionary ProhibitNewWindowForRequest -bool TRUE
  • Change iTunes Green Maximize Button Functionality
    defaults write com.apple.iTunes zoom-to-window -bool YES
    During the initial launch of iTunes 9, the green + icon on the window bar maximized the iTunes window instead of alternating to the mini player. Use this command line hack to enable this functionality once again.
  • Automatically Play Movies in QuickTime X
    defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1
  • Keep QuickTime Full Screen While Switching Applications
    defaults write com.apple.QuickTimePlayerX MGFullScreenExitOnAppSwitch 0
  • Disable QuickTime Rounded Corners
    defaults write com.apple.QuickTimePlayerX MGCinematicWindowDebugForceNoRoundedCorners 1
  • Automatically Show Closed Captioning or Subtitles in QuickTime
    defaults write com.apple.QuickTimePlayerX MGEnableCCAndSubtitlesOnOpen 1
  • Make List View Stacks Function Like Grid View Stacks
    defaults write com.apple.dock use-new-list-stack -bool YES
  • Enable MouseOver Highlight in Stacks
    defaults write com.apple.dock mouse-over-hilite-stack -boolean yes
    Once typing in this command, restart Dock (killall dock) to view changes.

Create a Text File of Directory Contents

If you’ve ever needed to get a list of files in a specific directory for whatever purpose, maybe you need to verify files during a backup or transfer, you probably hunted for a good freeware application to do the trick. Sure, there are good options out there, but why find a download for something you can just as easily accomplish from the command line?

Running the following command will output a list of the contents of the current directory to your Desktop. Just replace YOU with your Windows username.

dir /b *. > C:\Users\YOU\Desktop\musicfiles.txt

It’s that easy!

Enable Stacks Mouseover Highlight (OSX 10.6)

Enabling automatic mouseover highlighting of icons in your grid stacks makes browsing for files that much easier, and it’s just a simple command away. It’s been changed from the original command in Leopard, so after opening Terminal, run these commands:

  1. defaults write com.apple.dock mouse-over-hilite-stack -boolean yes
  2. killall dock

When the dock restarts, you can check out your fancy new highlight by clicking on your grid stack’s icon!