Archive

Archive for the ‘Archive Post’ Category

Setting up Apache, PHP 5 and MySQL on Leopard

March 24th, 2009 No comments

Going to be a short blog post as Leopard has made this process very simple as PHP5 has been included as standard with the new OSX.

First thing you need to do is open terminal and edit your http.conf file by typing:

nano -sw /etc/apache2/httpd.conf

Firstly you need to enable the php module. Search for ‘php5_mod’ by typing it in when you press ctrl+w and press enter. This will bring you to a line with a hash before it….

#LoadModule php5_module libexec/apache2/libphp5.so

Remove this hash to enable php5.

Next you need to setup your document root, i.e. the location your webserver will default to when you go to http://localhost. Search for ‘DocumentRoot’ within nano again by pressing Ctrl+w and hitting return. Alter the location (I think its Library/WebServer or something by default) to be whatever you wish your webserver root to be. I set it to be the Sites folder of the User I setup for Leopard.

Next you need to enable Apache, this is exceedingly easy. Go to System Preferences and then Sharing. Click the checkbox next to Web Sharing and apache should be ready to do. Put a sample html or php file(including is always a good way to test if php is working) in the document root and go to http://localhost and you should see the sample page.

Next you need to get MySQL. I got it here: http://mirrors.sunsite.dk/mysql/downloads/mysql/5.0.html#macosx-dmg.
Follow the very easy steps in the package and you should be hunky-dorey!

Categories: Archive Post, MySQL, PHP Tags:

PHP named locks, redirecting & logging

March 24th, 2009 No comments

Hi all haven’t posted in a while have a couple of posts to catch up on :)

I’ve recently have the need to perform locking in php on the server level. Basically I want just a single php script to execute a piece of code at any time. This requirement was brought about by race conditions whereby two php scripts would go and execute the same piece of code which would consequently conflict with one another. I needed to stop this. The solution is nice and easy and works a treat.

Whenever a php script comes in and requests a lock on a piece of code it attempts to create a directory using phps mkdir with a specific name myLock1. If the directory already exists then the mkdir returns false and the locking fails. If the mkdir completes then the php script has locked the section of code. Now when another seperate php script comes in and tries to create the directory mkdir will return false and the locking will fail.

When the php script is finished with a piece of code then it unlocks by deleting the directory using rmdir. Now a new php script is free to come in lock the piece of code again.

This locking works across all php scripts (i.e. is server wide) and provides named locks as you can give the directories different names. So one section of code may be locking a myLock1 directory and another part be locking myLock2 directory but these won’t interfere with one another. I’ve attached the code for this simple locking below and highlighed how it would be used to lock a piece of code.

class FLock
	{	private $files = array();
		private $oUUID = "";

		function __construct()
		{	$this->oUUID = new UUID();
		}	

		function __destruct()
		{	foreach($this->files as $file)
			{
				fclose($this->files['$file']);
			}
		}

		private function saveFileHandle($filepath)
		{
			if(!array_key_exists("$filepath",$this->files))
			{
				$this->files["$filepath"] = array();
				$this->files["$filepath"]['directory'] = $filepath;
				$this->files["$filepath"]['locked'] = false;

			}

		}

		public function attemptFileLock($filepath=false, $lockFile=true)
		{
			global $fileLockingLocation; 

		    $this->saveFileHandle($filepath);

			$canLock = false;

		    if($lockFile == true)
			{	if(!$this->files["$filepath"]['locked'])
				{	try
					{
						$canLock = mkdir("$filepath");
						if($canLock)
						{
							$this->files["$filepath"]['locked'] = true;

						}

					}
					catch(Exception $ex)
					{
						LogError($ex);
					}
				}
			}
			else
			{	if($this->files["$filepath"]['locked'])
				{
					rmDir("$filepath");

					$this->files["$filepath"]['locked'] = false;

					//TODO - Fix
					return true;

				}
			}

		    return $canLock;
		} 

		public function removeAllFileLocks()
		{	foreach($this->files as $file)
			{	rmDir($file['directory']);
				$this->files[$file['directory']]['locked'] = false;
			}
		}
	}

To lock the some code you need to just do like what I’ve done below.

$this->oFL = new fLock();
$fileLockResult = $this->oFL->attemptFileLock("/fileLocks/".$lockName."_lock",true);
if($fileLockResult)
{
      //Perform mySQL inserts,deletes etc.
      $fileLockResult = $this->oFL->attemptFileLock("/fileLocks/".$lockName."_lock",false);
}
else
{
     //Sleep between 0.5 - 1 second
     usleep(500000+(mt_rand(1,10))*500000);
}

I’ve had to perform php redirects of late also, its nice and easy but as Michael found out, even when you put a redirect in a chunk of code, the rest of the script gets parsed and the redirection doesn’t occur straight away. So you may want to put in a die() or something after the redirect if you wish to abort the rest of the page’s processing.

   header( 'Location: http://www.yoursite.com/new_page.html' ) ;

Performing error logging with PHP is another task I’ve wanted to do of late. Basically I’ve created a php wrapper page that takes in a script location from the Asterisk dial plan and executes the passed in script within a try catch block. Wrapping the script execution within the try provides a simple error logging mechanism. Anywhere I want to log errors that are fatal to the application I can just perform a throw within a php script and the top-most wrapper will always catch and log the error.

#!/usr/bin/php -q
get_variable("scriptName");
		$agi->exec("AGI",$scriptName['data']);

	}
	catch(Exception $ex)
	{	if(!isset($agi))
		{	$agi = new AGI();
		}

		$errorFileName = 'error-'."date-".date("dmy_His");
		$errorInfo = "Error message: ".$ex->getMessage();
		$errorCode = "Error code: ".$ex->getCode();
		$errorFile = "File: ".$ex->getFile();
		$errorLineNo = "Line number: ".$ex->getLine();

		if(!isset($agi))
		{
			$errorCode = $errorCode." - AGI cannot be created.";
			$errorFile = $errorFile." - applicationWrapper.php catch block.";
		}

		//Log to error log directory
		writeVariableToFile($errorInfo,$errorFileName);
		writeVariableToFile($errorCode,$errorFileName,true);
		writeVariableToFile($errorFile,$errorFileName,true);
		writeVariableToFile($errorLineNo,$errorFileName,true);

		if(isset($agi))
		{	//Log to terminal if possible
			$agi->verbose($errorInfo);
			$agi->verbose($errorCode);
			$agi->verbose($errorFile);
			$agi->verbose($errorLineNo);
			$agi->text2wav($ex->getMessage());
		}

		//Log to php error log
		error_log($errorInfo);
		error_log($errorCode);
		error_log($errorFile);
		error_log($errorLineNo);

		exit(0);

	}

	exit(0);
?>

The error_log is a built in php error logging system. You can specify where PHP logs errors to within you php.ini config file, I set it up to log to the system log by uncommenting the error_log = syslog line but you can easily setup your own location for logging errors.

From the Asterisk dial plan i.e. the extensions.conf you basically have something like

exten => s,n,Set(scriptName=/my/Path/To/File/myfile.php)
exten => s,n,AGI(/path/to/wrapper/applicationWrapper.php)
exten => s,n,Hangup()
Categories: Archive Post, Asterisk, PHP Tags:

March 24th, 2009 No comments

Hi again,

Yesterday I had some fun trying to use Flex to call an upload.cfm page but as the CF page was behind a secured system(i.e. need to be logged in to call a page) the system was looking for the Flex app to login again. I only found this out by running Charles Web Debugging app which showed the request and response http data. I saw that response was source for a login page, strangely though the flex app told me the upload was called successfully and the file was uploaded successfully.
Also looking at the HTTP data I saw that the jsessionid wasn’t being passed in alongside the Flex request so I needed to pass the session variable into the Flex app from ColdFusion. The CF was determining that the session was over so it was looking for a login. After looking around a bit I saw that it wasn’t possible to just get the Session variable from the swf directly you have to request it from ColdFusion as it is stored server side(I think).
So I made a function in a CFC to get the session variable:

[code lang="xml"]






[/code]

I call this from the Flex app using a Flex WebService and then when I’m doing a URL request I pass the jsessionid alongside the request like so:

[code lang="actionscript"]
var uploadDestination:String = myModel.CFLocation + model.AssetModel.getInstance().UPLOAD_CFM_NAME + ';jsessionid=' + myModel.sessionID;
[/code]

The session id is stored alongside the model as a variable. This essentially calls ‘upload.cfm;jsessionid=xyz’

This fixed my problem and the app works fine now.

Categories: Archive Post, ColdFusion, Flex Tags:

March 24th, 2009 No comments

Hi,
Today I needed to format a number to contain 2 decimal places, it’s a bit weird way to do it but here is how I did it, if anyone else knows a better way please tell!

number format ‘,.99′: #numberformat(num,’,.99′)#

I ran into a few problems while trying to compile the app_conference addon for Asterisk both this week and last week.

conflicting types for ‘strtoq’ from stdlib.h and concat.h

error: ‘AST_MODULE’ undeclared here (not in a function)

The error was confusing and I found it difficult to find any solution to my problem. Everywhere just indicated that you didn’t need to do anything to get the source to compile. I got the Asterisk source apt-get install apt-get install asterisk-dev and modified the Makefile in the app_conference directory to point at the asterisk includes (/usr/src/asterisk/include for me). When I attempted to make the application but got the errors above.

The solution I sort of stumbled onto inadvertently actually. I tried to place the code in the asterisk-src/apps directory in the hope it would pickup the includes properly, not sure why I was doing it actually. Anyway when I tried to re-compile the asterisk source(which automatically compiles the app directory) I saw that I was getting an error in the build. After a quick google I found that this was because libncurses5-dev wasn’t installed. I also installed pkg-config and libtool but I’ve a feeling that it was libncurses that fixed my problem. Anyway after this I compile it ok with now errors, copied the app_conference.so into the /usr/lib/asterisk/modules.so directory restarted asterisk and bingo it worked. Only pity is that it is literally a conference application it does nothing else really, no voice prompts or admin sort of features like allowing a user to kick other users but I hope to either add those or come up with a work-around for this.

Xlite is available for Mac OS Leopard now http://www.counterpath.com/, it wasn’t previously. I was using Zoiper but it is nowhere near as good as XLite in my opinion so I’m happy with that.

Categories: Archive Post, ColdFusion, XML Tags:

Firefox and ColdFusion comparisons and some links

March 24th, 2009 No comments

Hi all,

Recently saw this article writen by a FF developer about whats been done by Mozilla to improve Firefox 3 and runs through some comparison tests with other browsers, accompanied by some pretty graphs.

http://blog.pavlov.net/2008/03/11/firefox-3-memory-usage/

Check out Mark’s blog(well Learnosity’s) for a comparison of SOAP and REST for ColdFusion MX, again accompanied b pretty charts!

http://www.learnosity.com/techblog/index.cfm/2008/3/13/CFMX–SOAP-vs-REST-benchmarks

Came across a nice plugin to visualise images in Firefox – check out http://piclens.com/site/firefox/win/ I really like it.

I’ve signed up for the beta of SearchMe, it sounds good in theory but will be interested to try it. Have a look at the video demo here
www.searchme.com

And finally what made my week. The work of Jeff Orkin’s on the topic of Goal Oriented Action Planning inspired my Masters and he has referenced my Master’s thesis from his MIT Media site, check out his publications(and games, they rock) http://web.media.mit.edu/~jorkin/goap.html

Categories: Archive Post, ColdFusion Tags:

PHP dump, Beejive and MySQL tidbits

March 24th, 2009 No comments

Hi,
Haven’t had time to post recently and this is a relatively short one.

I’ve been coding with PHP again recently and was looking for something similar to ColdFusions cfdump and didn’t know until last week that the var_dump function existed, its very handy although it doesn’t output the dumped variable in a very user-friendly fashion.

As I posted previously I jailbroke my iTouch and was looking for a good app for IM. I installed Apollo IM hearing that it was meant to be very good but it only has .Mac, MSN, AIM and one other I can’t remember, the main problem with the app is that there doesn’t seem to be Google Talk support. After looking around for a bit I found Beejive which is excellent, very nice to use but unfortunately only works from within Safari and isn’t a standalone app but will do for the moment. Check it out at Beejive.

I had this error during the week when doing some CF troubleshooting. I couldn’t figure it out for a while and the error message wasn’t especially helpful.

Element 25316 is undefined in a Java object of type class coldfusion.runtime.TemplateProxy.

The error occurred (I don’t know why I was doing this) when I was trying to index into a CF object as you would a struct! So if I had an object oObject and try to do something like oObject["someValue"] you will get an error like above.

Finally just a couple of quick really useful MYSQL snippets I picked up during the week. I needed to rename a MYSQL table, the SQL below does this nicely.

rename table myOriginalTable TO newTableName;

Another really great piece of SQL performs an insert if a record doesn’t exist and if it does exist it performs an update on the record.

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

Coalesce is a nice MYSQL function, it returns the first non-null in a list. If there is nothing besides NULL in the list, 1 is returned as in the case below.

SELECT COALESCE(NULL,1) FROM tbl_test
Categories: Archive Post, ColdFusion, MySQL Tags:

CF Exceptions, disable CF security & CF oddities

March 24th, 2009 No comments

Hi again,

Been a while since my last post so quite a bit to post, will probably split into two.

I was having a very strange problem in CF last week where CF was unable to find any Application.cfc of any of my sites. I did many updateapps, restarted ColdFusion a couple of times, ensured the relative paths were correct and there were no errors in the cfc. After reaching my wits end with it, I asked a co-worker(cheers Sharmo!) for his assistance. We checked the logs and a whole bunch of other things with no avail to figure out what was going wrong. Michael then explained how cfcs are converted into Java bytecode classes in the backend so we figured that there could be something funky going on with the caching in the backend or on of the classes had become corrupt. So we deleted all the classes from /Applications/JRun4/servers/cfusion/cfusion-ear/cfusion-war/WEB-INF/cfclasses and did a restart of ColdFusion and voila…all working again.

I’ve been performing a lot of exception checking for ColdFusion of late. There are several different types of ColdFusion error listed below. Some exceptions CAN contain exception specific data thrown along with the error. Every exception contains a message and a type(i.e. database, application etc. ). Each exception can also include two members of the cfcatch struct called rootCause and cause which include data that can explain the reason behind the exception.

Database – Mysql errors
Special variables

* cfcatch.rootcause.datasource : the SQL datasource
* cfcatch.rootcause.sql : the problematic sql code

Application – Errors in the application scope

Special variables

* cfcatch.extendedInfo : exactly what it says on the tin

Template – Occurs when a template which is included can’t be found

Special variables

* cfcatch.missingfileName : The name of the missing template

Security – Occurs with ColdFusion sandbox and other security exceptions

Special variables

* Couldn’t find any in specific but I’m sure there are, had some sandbox setup issues :)

MissingInclude – Thrown when a CF resource isn’t found when using cfinclude, cfmodule

Special variables

* cfcatch.misingFilename : The missing include filename

Lock – Exceptions which occur when failed locking operations occur.

Special variables

* cfcatch.lockName : the name of the lock that failed
* cfcatch.lockOperation : the type of lock operation that failed(timeout, mutex or unknown)

Object – Object exceptions, occur when an operation is performed on an object or something invalid is done with an object

Special variables

* Nothing special

Expression – Exceptions thrown by invalid CF expressions

Special variables

* cfcatch.errNumber : The expression error number

Any – Other errors including custom errors, search engine errors and other Java exceptions not caught by CF.

I’m sure there more but this is what I found from testing. You can find Adobe’s (rather poor) explanation of the CF8 exceptions here

I recently had the need to disable ColdFusion passwords for both the Administrator and the Sandbox security sections of the CF backend. The best way to do this is to directly modify the security xml file that ColdFusion reads in. On the Mac I’m working on this security file was located in /Applications/JRun4/servers/cfusion/cfusion-ear/cfusion-war/WEB-INF/cfusion/lib/neo-security.xml

Alter the end of this file and there are a few booleans there that be set to disable sandbox security, disable admin security, disable rds security and set the admin user name(I believe thats what the final entry is, I haven’t looked into it)



admin
Categories: Archive Post, ColdFusion Tags:

Get a CFC name, simultaneous instances of FF(again), XMLSearch case-sensitivity and Asterisk stats

March 24th, 2009 No comments

Hi all,

Today I finally sorted out getting multiple instances of Firefox running on my Mac simultaneously after having profile problems for the last few weeks with the new FF version. I followed the steps in the links below to get it working on Leopard, so I’m running Firefox 2.0.11 and Firefox 3 Beta 3. I like the beta a lot, much more stable than the older version, I would like to turn off the hinting in the URL as it occasionally promotes certain visited sites over others when I don’t want it to based on name(ie. I might want to go to webmail.edmundlong.com and when I type in ‘webmail’ into the URL it may suggest another site e.g. www.abertay.ac.uk/webmail over it when I don’t want it to because I’ve visited it more often)

http://support.mozilla.com/kb/Running+different+versions+of+Firefox+at+the+same+time

http://www.jeroencoumans.nl/journal/multiple-firefox-versions

Here’s a small ColdFusion snippet to get the name of a cfc using the metadata. cfcname contains the name of the cfc.



	

I’ve been working on coming up with a way of accessing the Asterisk CLI from a php page so that stats could be delivered to a webpage. After looking around a bit I see that there is an Asterisk Manager facility that can execute some Asterisk commands along with CLI actions. Below is the code I’m currently using where I have a text-box that I can enter some CLI command e.g. sip show peers and the result is displayed on screen. I’m planning on maybe doing something like this to display some backend stats from the Asterisk system, I could get conference information, number of connected IAX & SIP peers and a whole bunch of other stats. Asterisk doesn’t return the data in a very friendly format though but more on that when I get into it a bit more.

=5)
               {
                        $array[$count][$j]=$token;
                        $j++; $token = strtok(':(');
               }
       $count++;
       $wrets .= '';
       }

       for($i=5;$i<$count-4;$i++){ echo '

'.$array[$i][0].'

'.'

'.$array[$i][1].'

'; }

       fclose($socket);
}

function createActionList($server,$username,$secret,$port,$action="ListCommands")
{
       $socket = fsockopen($server,$port, $errno, $errstr, 1);
       fputs($socket, "Action: Login\r\n");
       fputs($socket, "UserName: $username\r\n");
       fputs($socket, "Secret: $secret\r\n\r\n");
       fputs($socket, "Action: ListCommands\r\n\r\n");
       fputs($socket, "Action: Logoff\r\n\r\n");
       $count=0;$array;
       while (!feof($socket)) {
               $wrets = fgets($socket, 8192);
               $token = strtok($wrets,':(');
               $j=0;
               while($token!=false & $count>=5)
               {
                        $array[$count][$j]=$token;
                        $j++; $token = strtok(':(');
               }
       $count++;
       $wrets .= '';
       }
		echo "
"; /*echo 'Command : ';*/ echo " Command : "; echo " Parameter : "; echo " "; echo "
"; fclose($socket); } if ($_POST['submit']) { executeAction('127.0.0.1','asterisk','asterisk',5038,$_POST['managersAction'],$_POST['variable']); } else { createActionList('127.0.0.1','asterisk','asterisk',5038); } ?>

This code is very very insecure and I’m using it only for testing, anyone could type ‘restart now’ to reboot your asterisk system!

I had a couple of problems when using XML search because XMLSearch in ColdFusion is case-sensitive. I had an XML document like the one below


<[CDATA[abc]]>

I used the xpath expression /config/edstest to search for the ‘edsTest’ node but of course this failed due the case-sensitivity involved. The solution was to take the XML and change it all to upper case using UCASE(xml). The good thing is that ColdFusion ignored the content between the CDATA tags and so didn’t resize ‘abc’ which is exactly what I wanted. I then just changed my xpath to /CONFIG/EDSTEST and the search performed as expected.

Categories: Archive Post, ColdFusion, PHP, XML Tags:

Creating a custom Farcry type

March 24th, 2009 No comments

Hi again,

I’ve been delving into the wonderful world of Farcry CMS. I needed to create a custom type and having never created one before didn’t really know where to start. Luckily for me I’m working with one of the ex-developers of Farcry Michael and he stepped me through how to create it. This process is for the latest beta version of Farcry 5 so may be different for other versions of the CMS.

First and foremost you need to need to create a new type cfc in you /webroot/farcry/projects/#projectName#/packages/types directory. I created a CFC called Products(although I think you may be better of leaving it all lower case, more on that later) which contains several properties. The properties contained in this CFC define what is to be contained in the request stObj whenever someone hits/calls the new types page. The products cfc extends the farcry core types cfc and so inherits all the generic stuff like status verison, object id etc properties that are common across all farcry objects. Next I began to include my own custom ’stuff’ that I want specific to that object. I created a title, display method and product type. The title is just a string and the display method goes off and creates a drop down list of all objects in the products directory in the webskin that begin with ‘displayPage’, again more on that later. The product type is a list of allowed types of products. I specified this as a string but it can easily be replaced by a query or you can pull in other Farcry objects. Finally we need an edit function that tells farcry where to look when editing the object in the back-end. I specified that farcry should look in the _Products directory and for edit.cfm. So whenever we are editing an object in the back end Farcry will load up edit.cfm and this page essentially becomes a regular form style page with a little difference as you need to save the changes back to the Farcry object & DB when completed.







	

	
	
	



The edit.cfm is quite long but I’ve edited it a bit and included it anyway.










	
	

	
	













	
	
	



	
	
	
	
 	
	
	
		 

	
	
		
		
		
		

		
		
			
			
			
			
			
			
			
			
			

		
			
		

	
		
		

#errormessage#

#application.rb.getResource("generalInfo")#: #stObj.title#

Now you’ve created your products.cfc log into the farcry backend and go to the Admin tab. Select COAPI management from the dropdown and then select types on the left hand nav. You should now see your newly created products object here ready to be deployed. You can select deploy and your products should be available in the backend. However you need to do one more thing before you can begin to create products in the backend and view them on the front end, you need to define how products are to be displayed on the front end. To do this create a products directory in the /webroot/farcry/products/#appName#/webskin/ and within this create a page called displayPageStandard. Whenever this page is called the stObj struct is passed into the page and you can now access all the properties of this specific product and display it as you wish. So within this page I just dumped the stObj and then created a simple table of the object title and type. Obviously you can do much more complex stuff than this but this is really just a tutorial on how to do it.

Now you should be able to create product objects select a display method and edit them according to your own custom edit.cfm. One problem I never encountered on my Mac but did in staging was that I had created the products cfc with a large “P” and had use the same casing everywhere around the project. No problem there but in staging an error occurred saying that the table ‘products’ couldn’t be found. Looks like Farcry LCASEs the products name when creating the table, Mac’s NFS filesystem was forgiving but on Linux the problem reared it’s head. Had to rename the table manually and it all worked fine again. Perhaps this is just a bug in the beta that will be fixed come the release date.

I wrote this based entirely off my memory do hope I haven’t left anything out!!!

Categories: Archive Post, ColdFusion Tags:

Webservices with CFC and Flex Cairngorm delegates

March 24th, 2009 No comments

Hi there,

Have continued working on Flex recently and have been looking into making an image upload/download application that adheres to the Cairngorm framework. Read up this article which gives an excellent overview of the framework : Cairngorm framework

One particular problem I overcome today was to do with invoking a WebService which calls a cfc method on my own local machine. I was getting a lot of errors when connecting the most annoying of which was error #2032 which gave me a HTTP stream error. Funny thing was I didn’t really believe this error and kinda knew my WebService was actually connecting with my CFC. I ended up going through my CFC function and completely stripping out the code where errors could have occurred and found that it was an error in my CFC that was giving me this error!!

My delegate is called by a command :

public function execute(event:CairngormEvent) : void
{    //Go to the image delegate and get the images. Add them to the model
     var delegate : ImageDelegate = new ImageDelegate(this);
     delegate.getImages(event.data);
}

The image delegate goes off and calls the web service:

public class ImageDelegate implements IResponder
{
private var responder : IResponder;
private var service : Object;

public function ImageDelegate(responder:IResponder)
{    this.service = ServiceLocator.getInstance().getWebService("getImages");
      this.responder = responder;
}

public function getImages(data:CairngormEvent):void
{
     this.service.getAssetFiles(data);

}

Here is my WebService that uses parameters into a CFC.





"jpg,png,gif"




Very simple but took about an hour to get right! I’m calling a getAssetFiles method in assetManager on my local machine using wsdl. The function takes in an assetTypeRequired parameter.

Categories: Archive Post, ColdFusion Tags: