Final and auto load a class

To include a class within many languages you have to define it at the top and then off you go with programming with using that class. Well within PHP you can use the __autoload function that is called when you try to create a new instance of a class.

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}

this __autoload function above takes a parameter as the class name to load and then within the code it will try and load that class with how ever you want to, in this case I have placed the classes within the directory called classes and under there classname.php filename.

So if you try to load the class

$newclass = new basic();

it will look within the classes directory for the file basic.php for the autoload function above, you can alter it to load from where ever and how ever you want to.

The next part of this post is about the keyword ‘final’, the final keyword means that it is final so if you try and extend that class and extend the function that has been declared as final this will cause php interpretor to fail due to syntax error with something similar to

Fatal error: Cannot override final method class_name::function_name()

For an example here is two classes one is called basic and the other is called extendbasic, where the basic class has the final function within it

class basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this) . " : Hello";
	}
 
	final public function sayGoodbye()
	{
		echo "<br/>".get_class($this) . " : Goodbye";
	}
}

and here is the extendclass

class extendbasic extends basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this). " : the newer hello!!";	
		parent::sayHello();
	}
        // this will cause the php engine to fail!!!!!. because it is trying to over load the function sayGoogbye which has been declared as final
/*	public function sayGoodbye()
	{
		echo "I should not get here!!";
	}*/
}

Here is some code to call them both which they have been placed within a directory called ‘classes’

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}
 
$basicClass = new basic();
$basicClass->sayHello();
$basicClass->sayGoodbye();
$basicClass = new extendbasic();
$basicClass->sayHello();
$basicClass->sayGoodbye();

and the output would be

basic : Hello
basic : Goodbye
extendbasic : the newer hello!!
extendbasic : Hello
extendbasic : Goodbye

I am calling the parent function from within the extendbasic class sayHello function.

Curly brackets

It all depends on your type of coding, but I for style I do prefer to put array data within a separate part of the echo statement, for example.

$arr = array("first" => 1, "second" =>2);
 
echo "this is the first value " . $arr["first"];

but of course you can put the arr object within the echo statement as long as you { .. } it out, which is kinder similar to using the ” . as such,

echo "this is the second value {$arr["second"]}";

both work, but because of the array object uses the “..” for the hash key, then you will need to use the { .. }

CKEditor – custom dialog

The CKEditor is a great WYSIWYG and the best thing is that you are able to customize the interface to have buttons on the toolbars, here is a way that I created a custom button with custom image attached to it.

The editor is created with

var editor = CKEDITOR.replace( 'Content');

So from now on in the variable editor is linked to the CKEditor instance, to setup the plugins to load when the CKEditor is created you call the pluginsLoaded function

 editor.on( 'pluginsLoaded', function( ev )
         {
           if ( !CKEDITOR.dialog.exists( 'statisticsDialog' ) )
                 CKEDITOR.dialog.add( 'statisticsDialog','/statistics.js');
           // Register the command used to open the dialog.
           editor.addCommand( 'statisticsAddCmd', new CKEDITOR.dialogCommand('statisticsDialog' ) );
           editor.ui.addButton( 'Statistics',
                    {
                        label : 'Statistic',
                        command : 'statisticsAddCmd',
                        icon : '/statistics_small.png',
                    } );
});

The first part will check to make sure that there is not dialog already created with the same name, and if not then load the javascript file that is the custom built dialog. The second part is adding the command (the button clicked) to be linked to the custom dialog, and the third part is to add the actual button to the user interface (editor.ui). The addButton function links to the command to bring up the custom dialog.

Here is the custom dialog code that will be called when the user interface button is clicked.

CKEDITOR.dialog.add( 'statisticsDialog', function( editor )
{
      // Load data asynchronously.
       return {
               title : 'Pick a statistic',
               minWidth : 400,
               minHeight : 200,
               onOk : insertOntoEditor,
               contents : [
                       {
                               id : 'tab1',
                               label : 'First Tab',
                               title : 'First Tab',
                               elements :[
                                       {  id : 'graphselect',
                                               type : 'select',
                                               items : [ ["option1", "link to image"] ] ,
                               }]
                       }
               ]
       };
} );

The dialog, will load up a screen and have a one drop down box that will allow the user to choose from the options (will you need to insert more options, or dynamic created options if you wanted to) and once the OK button is clicked (onOK) it will call this function below

function insertOntoEditor()
{
       elem = this.getContentElement('tab1','graphselect');
       value = elem.getValue();
       if (value != -1)
       {
               var writer = new CKEDITOR.htmlWriter();
               var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<img src="http://'+document.domain+elem.getValue()+'"/>' );
               fragment.writeHtml( writer )
 
               // need to wrap up the graph image insertion into the ckeditor
               CKEDITOR.instances.Content.insertHtml(writer.getHtml());
       }
}

This will basically insert some code into the CKEditor from the drop down box, the “link to image” you will need to insert a link for the insertion.

CKEditor – Custom upload dialog

The great WYSIWYG editor called CKEditor allows you to do a custom file upload, so that you can handle where the file is stored and also you can do your database extra inserts for example.

To start with you have to tell the CKEditor where to post the file uploaded to custom built page

var editor = CKEDITOR.replace( 'Content',{ filebrowserUploadUrl :'/custom.imageuploader.php'});

Where the custom.imageuploader.php is the actual php page that will deal with the custom page, can be done in any other language if required. In the above code, the ‘Content’ is the textarea to change to a CKEditor WYSIWYG.

Here is a basic php page that you will need to alter to store the $_FILES[“upload”] into the place where you want to store and do any database code to link to the resource that you are uploading, but the bit underneath that you need to have, this will tell the CKEditor what to do after your PHP code has stored the file, the CKEditoFuncName, is required (but passed in) to tell the CKEditor what function to call after the upload has happened, the $wherestorage, is where the actual file is so that the WYSIWYG can show the image and any $message that may help the CKEditor user for any error reports.

<?php
// the files are stored within the upload part of the $_FILES 
$_FILES["upload"];
?>
<html>
<body>
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(
   <?php echo $_REQUEST["CKEditorFuncNum"].",\"".$wherestorage."\",\"".$message."\"";?>
);
</script>
</body>
</html>
?>

Custom wordpress page on a new URL

I liked to have the idea of having google search my site and have it displayed within my current site design, and since wordpress allows to have action hooks that allow you to interrupt the present flow of generating the wordpress outputted page.

So to have the google searched and display results within the style that I am using I first needed to create a plugin, if you create a file within your

wordpress base directory/wp-content/plugins/codingfriendsgooglesearch

within the file below within the that directory created above, (I saved this file as googlesearch.php, but it does not matter as long as it is a .php file with the plugin details at the top of the file between the /*… */ parts.

<?php
/*
Plugin Name: Google search page
Plugin URI: http://www.codingfriends.com
Donate link: http://www.codingfriends.com
Description: Google search page
Version: 0.1
Author: Ian Porter
Author URI: http://www.codingfriends.com
*/
 
function get_requested_uri() {
       $requesturi = $_SERVER['REQUEST_URI'];
       if (substr($requesturi, -1)!="/") {
               $requesturi = $requesturi."/";
       }
       preg_match_all('#[^/]+/#', $requesturi, $matches);
       $uri = $matches[0];
       return $uri;
}
 
function google_search_display() {
       $uri = get_requested_uri();
       if ($uri[0]=='googlesearch/') {
               include(TEMPLATEPATH . '/googlesearch.php');
               exit;
               }
}
 
add_action( 'template_redirect', 'google_search_display');
 
?>

What basically happens is when the template_redirect is called, this is when most of the processing of the page has already been done, and we are about to display the requested page from the blog, well in this case I would like to add function call to google_search_display, which is within this same file, and what it does is to search for ‘googlesearch/’ within the first part of the URL requested e.g.

http://www.codingfriends.com/googlesearch/

and if so display the googlesearch.php php file from within the templates directory, and here is my googlesearch.php file, and it displays the content within the div tag with cse-search-results, with the present style around the google search results.

<?php get_header(); ?>
<div id="content" class="narrowcolumn" role="main">
<div id="cse-search-results"></div>
<script type="text/javascript">
 var googleSearchIframeName = "cse-search-results";
 var googleSearchFormName = "cse-search-box";
 var googleSearchFrameWidth = 795;
 var googleSearchDomain = "www.google.co.uk";
 var googleSearchPath = "/cse";
</script>
<script type="text/javascript"
src="http://www.google.com/afsonline/show_afs_search.js"></script>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

wordpress is really nice where you are able to alter the present execution process.

CS71 – Ass1 – Finance – Part 5 – View users details – buy stock – change password

I am doing the Harvards building dynamic websites called CS-75 (also could be called E-75), because someone told me about it and I just thought might as well, it is all learning 🙂 even if allot of it you may already know.

As from the previous post, most of this page is in similar in nature it is just displaying data to the user that was built up from the classes files.

So to buy some stock, what this page will do is wait for the user to type in a stock symbol and then use the stock class to get the data back from that symbol and then have another input that will allow the user to buy some of that stock, also if the user clicks on the link it will display at the bottom of the page new items about the stock itself.

 
<?php
	require("functions_start.php");
 
	global $theStock;
 
	if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"]== false)
	{
		header("Location: /index.php");
		exit;
	}
 
	// of course the product price may change from searching to buying, depending on the time period so need to pull back 
	// the new value, just incase.
	if (isset($_REQUEST["buyme"]))
	{
		$stockID = strtoupper($_REQUEST["STOCK"]);
		$stockAmount = $_REQUEST["AMOUNT"];
		$stockPurchased = $theStock->BuyStock($_SESSION["username"], $stockID, $stockAmount);
	}
 
	if (isset($_REQUEST["searchSymbol"]))
	{
		if (strlen($_REQUEST["searchSymbol"]) >=3)
			$result = $theStock->GetStocksFromYahoo(strtoupper($_REQUEST["searchSymbol"]));
	}
 
	HTMLHeader("Buy some stock, search and buy");
 
	if (isset ($stockPurchased)) {
		echo "<p class=\"details\">";
		if ($stockPurchased >0 )
			echo "Stock was purchased ($stockID amount of $StockAmount total price of $stockPurchased each price was ". number_format($stockPurchased / $stockAmount,2).")"; 
		else
			echo "Problem with purchasing the stock, please email the error above to the support team";
		echo "</p>";
	}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" onsubmit="return CheckBuy()"/>
<?php
if (isset($result)) { 
  if ($result > 0) {
	echo "<h2>{$_REQUEST["searchSymbol"]}</h2>";
    echo "The price of {$_REQUEST["searchSymbol"]} is $result, do you want to buy ?<br/>Please enter how many and tick the box.<br/>";
	echo "<input type=\"text\" name=\"AMOUNT\" id=\"AMOUNT\" onkeyup=\"javascript:CheckKey(this)\"/>";
	echo "<input type=\"hidden\" name=\"STOCK\" value=\"{$_REQUEST["searchSymbol"]}\"/>";
	echo "<input type=\"checkbox\" name=\"buyme\" id=\"BUYME\"/>";
	echo "<input type=\"submit\" value=\"Submit\"/>";
	echo "<p><b>Or search for another stock</b></p>";
 }
else
    echo "<h2>Not stock of that symbol - {$_REQUEST["searchSymbol"]}</h2>";
}
?>
<br/>
Search Symbol :<input type="text" name="searchSymbol" id="searchSymbol"/>
<input type="submit" value="Submit"/>
</form>
<h2>Your present cash flow is</h2>
<?php
	echo number_format($theUser->GetCash($_SESSION["username"]),2);
 
	HTMLFooter();
?>

To view the stock details of the user, I just display the stock that the user has from data once again from the stock class, which also includes the current price of the stock. There is a checkbox that will allow the user to sell some of there stock (if they have any!!) and once again use the stock class to sell the stock and update the tables in the database.

<?php
	require("functions_start.php");
 
	global $theStock;
 
	if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"]== false)
	{
		header("Location: /index.php");
		exit;
	}
	foreach ($_REQUEST as $key => $value)
	{
		if (strpos($key, "remove_") === 0)
			$theStock->SellStock($_SESSION["username"], $value);
		if ($key=="stock")
			$getStock = $value;
	}
	HTMLHeader("The details of your account");
?>
<h2>The stocks that the user has</h2>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" onsubmit="return checkSell()">
<table>
<tr><td>Stock Name</td><td>Quantity</td><td>Price of Stock</td><td>Value</td><td>Sell</td></tr>
<?php
    $totalValue = 0;
	$usersStock = $theStock->ReturnAllStocks($_SESSION["username"]);
	foreach ($usersStock as $theStocks)
	{
		echo "<tr><td><a href=\"{$_SERVER["PHP_SELF"]}?stock={$theStocks[0]}\">{$theStocks[0]}</a></td><td>{$theStocks[1]}</td><td>{$theStocks[2]}</td><td>".
			number_format($theStocks[2] * $theStocks[1],2)."</td><td><input type=\"checkbox\" value=\"{$theStocks[0]}\" name=\"remove_{$theStocks[0]}\"/></td></tr>";
		$totalValue += $theStocks[2] * $theStocks[1];
	}
	echo "<tr><td colspan=\"2\"></td><td>Total value</td><td>".number_format($totalValue,2)."</td></tr>";
?>
</table>
<input id="center" type="submit" value="Submit"/>
</form>
<h2>Your present cash flow is</h2>
<?php
	echo number_format($theUser->GetCash($_SESSION["username"]),2);
	echo "<h2>Your cash + investments</h2>" . number_format($theUser->GetCash($_SESSION["username"]) + $totalValue,2);
 
	if (isset($getStock))
	{
		echo "<h2>$getStock more information</h2><table><tr><td>Date</td><td>Title/Link</td></tr>";
		$stockDetailsArray = $theStock->ArrayOfStockDetails($getStock);
		for ($i = 0; $i < sizeof($stockDetailsArray); $i++)
		{
			echo "<tr><td>{$stockDetailsArray[$i]["Date"]}</td><td><a href=\"{$stockDetailsArray[$i]["Link"]}\" target=\"_blank\">{$stockDetailsArray[$i]["Title"]}</a>";
		}
		echo "</table>";
	}
 
	HTMLFooter();
?>

The last part is the change of the password, which just will use the user class to update the users password to the requested input from the change password page.

<?php
	require("functions_start.php");
 
	if (isset($_REQUEST["password1"]) && isset($_REQUEST["password2"]))
	{
		if ($_REQUEST["password1"] == $_REQUEST["password2"])
			$error = $theUser->ChangePassword($_SESSION["username"], $_REQUEST["password1"]);
		else
			$notSamePassword = true;
	}
 
	if (!isset($_SESSION["authenticated"]))
	{
		header("Location: /index.php");
		exit;
	}
 
	HTMLHeader("Change password",true);
 
	if (isset($error))
	{
		if ($error)
			echo "<div>Password updated</div>";
		else 
			echo "<div id=\"error\">Cannot update the password, please contact the system admin</div>";
	}
	if (isset($notSamePassword))
		echo "<div>Passwords are not the same</div>";
?>
<!-- taken from http://www.html.it/articoli/nifty/index.html-->
<div id="login">
<b class="rtop">
  <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b>
</b>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" onsubmit="return CheckChangePasswords()">
Change your password <p>
New Password : <input type="password" name="password1" id="password1" value=""/></p>
Retype New Password : <input type="password" name="password2" id="password2" value=""/></p>
<input type="submit"/>
</p>
</form>
<b class="rbottom">
  <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b>
</b>
</div>
<?php
	HTMLFooter();
?>

The actual pages that are displayed to the user are all very basic as them selves, but the actual logic and formula are all within the classes that is the gold dust as such, since it is one point of checking and also one file to update if there is a update to the yahoo etc stocks details, because would have to update the different pages that display the stocks and that is not good for testing and also updating.

CS71 – Ass1 – Finance – Part 4 – Login Register Forgotten password

I am doing the Harvards building dynamic websites called CS-75 (also could be called E-75), because someone told me about it and I just thought might as well, it is all learning 🙂 even if allot of it you may already know.

Since most of the work is done in the class files, from the previous post then we just use the classes to only have basic php pages for the user. So the login page is just, which also has a check for if the user is already logged in and goto the viewdetails page, or if the user requests to logout then logout the user, the main page is just logging the user in.

<?php
	require("functions_start.php");
 
	if (isset($_REQUEST["username"]) && isset($_REQUEST["password"]))
	{
		$error = $theUser->LoginCheck($_REQUEST["username"], $_REQUEST["password"]);
	}
 
	if (isset($_REQUEST["logout"]))
		$theUser->Logout();
 
	if (isset($_SESSION["authenticated"]) && $_SESSION["authenticated"]== true)
	{
		header("Location: /viewdetails.php");
		exit;
	}
 
	HTMLHeader("Login to the stocks!",false);
 
	if (isset($error))
	{
		if ($error==false)
			echo "<div>Not able to login, please try again</div>";
	}
	if (isset($_REQUEST["logout"])) 
		echo "Thanks for using the site, you are logged out!";
?>
<!-- taken from http://www.html.it/articoli/nifty/index.html-->
<div id="login">
<b class="rtop">
  <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b>
</b>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" onsubmit="">
Login
<p>
Username : <input type="text" name="username" id="username" value="<?php echo $_REQUEST["username"]; ?>"/>
</p>
<p>
Password : <input type="password" name="password" id="password"/>
</p>
<p>
<input type="submit"/>
</p>
<p id="right">
<a href="register.php">Register</a> here.
</p>
</form>
<b class="rbottom">
  <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b>
</b>
</div>
<?php
	HTMLFooter();
?>

Here is the register page, where I send the request to the users class and utilize the return value to display either a message of check your emails (or in this case it will be a link on the top of the page) or display a error to the user depending on what could happen, e.g. not a valid valid/password(if the user turned off javascript checking) and also if there is already that email address present, the next check checks for the valid ID value that is sent to the user to validate there email.

<?php
	require("functions_start.php");
 
	if (isset($_REQUEST["username"]) && isset($_REQUEST["password"]))
	{
		$error = $theUser->RegisterUser($_REQUEST["username"], $_REQUEST["password"]);
		if ($error == -2)
			$notValidPassword = true;
		else if ($error == -1)
			$notValidEmail = true;
		else if ($error == 0)
			$emailAddressAlreadyPresent = true;
		else if ($error == 1)
			$checkEmails = true;
	}
 
	if (isset($_REQUEST["validid"]) && isset($_REQUEST["uid"]))
	{
		$error = $theUser->CheckUserGUID($_REQUEST["uid"], $_REQUEST["validid"]);
		if ($error == false)
			$userInvalid = true;
		else if ($error == true)
		{			
			$theUser->LoginCheck($_REQUEST["uid"],"",true);
			header("Location: /viewdetails.php");
			exit;
		}
	}
 
	if (isset($_SESSION["authenticated"]) && $_SESSION["authenticated"]== true)
	{
		header("Location: /viewdetails.php");
		exit;
	}
 
	HTMLHeader("Register",false);
 
	if (isset($error))
	{
		if (isset($checkEmails))
			echo "<div>Please check your emails to validate your email address</div>";
		else if (isset($notValidPassword))
			echo "<div id=\"error\">Not a valid password!, please enter one that is 6 characters and has at least 1 aphla/numeric</div>";
		else if (isset($emailAddressAlreadyPresent))
			echo "<div id=\"error\">Please use the forgotten password recovery,  already email address registered</div>";
		else if (isset($notValidEmail))
			echo "<div id=\"error\">Not a valid email address</div>";
		else if (isset($userInvalid))
			echo "<div id=\"error\">Does not validate correctly, please contact the system admin</div>";
	}
?>
<!-- taken from http://www.html.it/articoli/nifty/index.html-->
<div id="login">
<b class="rtop">
  <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b>
</b>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" onsubmit="return CheckRegister()">
Register <p>
Username : <input type="text" name="username" id="username" value="<?php echo $_REQUEST["username"]; ?>"/>
(valid email address)</p>
<p>
Password : <input type="password" name="password" id="password"/>
(Has to be at least 6 characters and with 1 numeric and aplha character</p>
<p>
<input type="submit"/>
</p>
</form>
<b class="rbottom">
  <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b>
</b>
</div>
<?php
	HTMLFooter();
?>

Here is the last part, that will allow the user to enter there email to be able to get a link to enable them to change there password.

<?php
	require("functions_start.php");
 
	if (isset($_REQUEST["username"]) )
	{
		$error = $theUser->ForgottenUser($_REQUEST["username"]);
		if ($error)
			$checkEmails = true;
		else 
			$notValidEmail = true;
	}
 
	if (isset($_REQUEST["validid"]) && isset($_REQUEST["uid"]))
	{
		$error = $theUser->CheckUserGUID($_REQUEST["uid"], $_REQUEST["validid"]);
		if ($error == false)
			$userInvalid = true;
		else if ($error == true)
		{			
			$theUser->LoginCheck($_REQUEST["uid"],"",true);
			header("Location: /changepassword.php");
			exit;
		}
	}
 
	if (isset($_SESSION["authenticated"]) && $_SESSION["authenticated"]== true)
	{
		header("Location: /viewdetails.php");
		exit;
	}
 
	HTMLHeader("Forgotten password",false);
 
	if (isset($error))
	{
		if (isset($checkEmails))
			echo "<div>Please check your emails to validate your email address</div>";
		else if (isset($notValidEmail))
			echo "<div id=\"error\">Cannot find that email address</div>";
	}
?>
<!-- taken from http://www.html.it/articoli/nifty/index.html-->
<div id="login">
<b class="rtop">
  <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b>
</b>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" onsubmit="return CheckRegister(true)">
Forgotten password, please enter your username <p>
Username : <input type="text" name="username" id="username" value="<?php echo $_REQUEST["username"]; ?>"/>
(valid email address)</p>
<input type="submit"/>
</p>
</form>
<b class="rbottom">
  <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b>
</b>
</div>
<?php
	HTMLFooter();
?>

As you can see the actual pages are really simple because most of the work is done in the class files