Thursday, January 28, 2010

Gmail like chat

http://anantgarg.com/2009/05/13/gmail-facebook-style-jquery-chat/

Friday, January 22, 2010

Changes in dreamweaver to open .ctp and .thtml file

There are ultimately 3 files that you need to edit. The first two are located in the folder that you installed Dreamweaver, in my case this is “C:\Program Files\Adobe\Adobe Dreamweaver CS3\configuration” although I’m using the latest version of Dreamweaver previous versions also have a “configuration” folder so go there.

Open up “Extensions.txt” and on the first line at the very end add THTML and CTP separated by commas, so the line should read:

1. ,MASTER,THTML,CTP:All Documents

,MASTER,THTML,CTP:All Documents

Similarly add these two extensions to the “:PHP Files” line.

1. PHP,PHP3,PHP4,PHP5,TPL,THTML,CTP:PHP Files

PHP,PHP3,PHP4,PHP5,TPL,THTML,CTP:PHP Files

Next open the “DocumentTypes” folder and edit the “MMDocumentTypes.xml” file, just open it up using notepad or wordpad. Search for the line which has an id “PHP_MySQL” and add the THTML/CTP file extensions to both the “winfileextension” and “macfileextension” so the line should read:

1. winfileextension="php,php3,php4,php5,thtml,ctp"
2. macfileextension="php,php3,php4,php5,thtml,ctp"

winfileextension="php,php3,php4,php5,thtml,ctp"
macfileextension="php,php3,php4,php5,thtml,ctp"

The final file is another version of the “Extensions.txt” which is located in your “Documents and Settings” Folder in my case this is “C:\Documents and Settings\James\Application Data\Adobe\Dreamweaver 9\Configuration” just add the very same things you inserted earlier.

Thursday, January 21, 2010

A solution for e-mail handling in CakePHP

The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, html or both. It supports sending via the built in mail functions of PHP, via smtp server or a debug mode where it writes the message out to a session flash message. It also supports file attachments.
Implements it in three easy Steps
1. Controller (STEP 1)

In your controller you need to add the component to your $components array or add a $components array to your controller like:
1. 2. var $components = array('Email');
3. ?>

In this example we will set up a private method to handle sending the email messages to a user identified by an $id. In our controller (let's use the User controller in this example)

1. 2. function _sendNewUserMail($id) {
3. $User = $this->User->read(null,$id);
4. $this->Email->to = $User['User']['email'];
5. $this->Email->bcc = array('anuragtrivediphp@gmail.com');
6. $this->Email->subject = 'Welcome to cakePHP email handling functionally';
7. $this->Email->replyTo = 'anuragtrivediphp @ gmail.com';
8. $this->Email->from = Anurag Blog ';
9. $this->Email->template = ‘contact'; // note no '.ctp'
10. //Send as 'html', 'text' or 'both' (default is 'text')
11. $this->Email->sendAs = 'both'; // because we like to send pretty mail
12. //Set view variables as normal
13. $this->set('User', $User);
14. //Do not pass any args to send()
15. $this->Email->send();
16. }
17. ?>

You have sent a message; you could call this from another method like
1. $this->_sendNewUserMail( $this->User->id );

2. Setting up the Layouts (Step 2)
To use both text and html mailing message you need to create layout files for them, just like in setting up your default layouts for the display of your views in a browser, you need to set up default layouts for your email messages. In the app/views/layouts/ directory you need to set up (at a minimum) the following structure
email/
html/
default.ctp
text/
default.ctp
These are the files that hold the layout templates for your default messages. Some example content is below
email/text/default.ctp
1.

email/html/default.ctp
1.
2. < html >
3. < body >
4.
5. < /body >
6. < /html >

3. Setup an email element for the message body
(Step 3)
In the app/views/elements/email/ directory you need to set up folders for text and html unless you plan to just send one or the other. In each of these folders you need to create templates for both types of messages referring to the content that you send to the view either by using $this->set() or using the $contents parameter of the send() method. Some simple examples are shown below. For this example we will call the templates
contact.ctp
1.Dear ,

In html

Dear ,< br />
Thank you for your interest.

Image Upload and Resize Component for CakePHP

image.php component file
/*
File: /app/controllers/components/image.php
*/
class ImageComponent extends Object
{
/*
* Uploads an image and its thumbnail into $folderName/big and $folderName/small respectivley.
* the generated thumnail could either have the same aspect ratio as the uploaded image, or could
* be a zoomed and cropped version.

* Directions:
* In view where you upload the image, make sure your form creation is similar to the following
* create('FurnitureSet',array('type' => 'file')); ?>
*
* In view where you upload the image, make sure that you have a file input similar to the following
* file('Image/name1'); ?>
*
* In the controller, add the component to your components array
* var $components = array("Image");
*
* In your controller action (the parameters are expained below)
* $image_path = $this->Image->upload_image_and_thumbnail($this->data,"name1",573,80,"sets",true);
* this returns the file name of the result image. You can store this file name in the database
*
* Note that your image will be stored in 2 locations:
* Image: /webroot/img/$folderName/big/$image_path
* Thumbnail: /webroot/img/$folderName/small/$image_path
*
* Finally in the view where you want to see the images
* image('sets/big/'.$furnitureSet['FurnitureSet']['image_path']);
* where "sets" is the folder name we saved our pictures in, and $furnitureSet['FurnitureSet']['image_path'] is the file name we stored in the database

* Parameters:
* $data: CakePHP data array from the form
* $datakey: key in the $data array. If you used file('Image/name1'); ?> in your view, then $datakey = name1
* $imgscale: the maximum width or height that you want your picture to be resized to
* $thumbscale: the maximum width or height that you want your thumbnail to be resized to
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
* $square: a boolean flag indicating whether you want square and zoom cropped thumbnails, or thumbnails with the same aspect ratio of the source image
*/
function upload_image_and_thumbnail($data, $datakey, $imgscale, $thumbscale, $folderName, $square,$controller) {
if (strlen($data[$controller][$datakey]['name'])>4){
$error = 0;
$tempuploaddir = "img/temp"; // the /temp/ directory, should delete the image after we upload
$biguploaddir = "upload/".$folderName."/big"; // the /big/ directory
$smalluploaddir = "upload/".$folderName."/small"; // the /small/ directory for thumbnails

// Make sure the required directories exist, and create them if necessary
if(!is_dir($tempuploaddir)) mkdir($tempuploaddir,true);
if(!is_dir($biguploaddir)) mkdir($biguploaddir,true);
if(!is_dir($smalluploaddir)) mkdir($smalluploaddir,true);

$filetype = $this->getFileExtension($data[$controller][$datakey]['name']);
$filetype = strtolower($filetype);

if (($filetype != "jpeg") && ($filetype != "jpg") && ($filetype != "gif") && ($filetype != "png"))
{
// verify the extension
return;
}
else
{
// Get the image size
$imgsize = GetImageSize($data[$controller][$datakey]['tmp_name']);
}

// Generate a unique name for the image (from the timestamp)
$id_unic = str_replace(".", "", strtotime ("now"));
$filename = $id_unic;

settype($filename,"string");
$filename.= ".";
$filename.=$filetype;
$tempfile = $tempuploaddir . "/$filename";
$resizedfile = $biguploaddir . "/$filename";
$croppedfile = $smalluploaddir . "/$filename";

if (is_uploaded_file($data[$controller][$datakey]['tmp_name']))
{
// Copy the image into the temporary directory
if (!copy($data[$controller][$datakey]['tmp_name'],"$tempfile"))
{
print "Error Uploading File!.";
exit();
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $imgscale, $resizedfile);

if($square) {
/*
* Generate the small square version of the image with scale of $thumbscale
*/
$this->crop_img($tempfile, $thumbscale, $croppedfile);
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $thumbscale, $croppedfile);
}

// Delete the temporary image
unlink($tempfile);
}
}

// Image uploaded, return the file name
return $filename;
}
}

/*
* Deletes the image and its associated thumbnail
* Example in controller action: $this->Image->delete_image("1210632285.jpg","sets");
*
* Parameters:
* $filename: The file name of the image
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
*/
function delete_image($filename,$folderName) {
unlink("upload/".$folderName."/big/".$filename);
unlink("upload/".$folderName."/small/".$filename);
}

function crop_img($imgname, $scale, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype){
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$width = imagesx($img_src);
$height = imagesy($img_src);
$ratiox = $width / $height * $scale;
$ratioy = $height / $width * $scale;

//-- Calculate resampling
$newheight = ($width <= $height) ? $ratioy : $scale;
$newwidth = ($width <= $height) ? $scale : $ratiox;

//-- Calculate cropping (division by zero)
$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;
$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;

//-- Setup Resample & Crop buffers
$resampled = imagecreatetruecolor($newwidth, $newheight);
$cropped = imagecreatetruecolor($scale, $scale);

//-- Resample
imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//-- Crop
imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

// Save the cropped image
switch($filetype)
{

case "jpeg":
case "jpg":
imagejpeg($cropped,$filename,80);
break;
case "gif":
imagegif($cropped,$filename,80);
break;
case "png":
imagepng($cropped,$filename,80);
break;
}
}

function resize_img($imgname, $size, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype) {
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$true_width = imagesx($img_src);
$true_height = imagesy($img_src);

if ($true_width>=$true_height)
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
else
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
$img_des = ImageCreateTrueColor($width,$height);
imagecopyresampled ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width, $true_height);

// Save the resized image
switch($filetype)
{
case "jpeg":
case "jpg":
imagejpeg($img_des,$filename,80);
break;
case "gif":
imagegif($img_des,$filename,80);
break;
case "png":
imagepng($img_des,$filename,80);
break;
}
}

function getFileExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
} ?>


How to use in controller?
Sample code is here:-
class UserAvatarsController extends AppController {
var $name = 'UserAvatars';
var $uses = array('UserAvatar','User'); //using modules
var $helpers = array('Html','Form','Javascript','Session');
var $paginate = array('limit' => 15); // Set records per page
var $components = array('Image'); // used Image components
function upload()
{
$this->user_session_check();
if (!empty($this->data))
{
$image_path = $this->Image->upload_image_and_thumbnail($this->data,"avatar",573,80,"avatar",true,'UserAvatar');
$this->data['UserAvatar']['avatar']=$image_path;
if ($this->UserAvatar->save($this->data))
{
$this->flash('Your avatar has been uploaded successfully',_ROOT.'avatar/upload',1);
}
}
}
}
?>

Custom 404 error page with CakePHP

1. Create your error layout in app/view/layouts/ (with name error.ctp)
2. Create your 404 error view in app/view/errors/ (with name error404.ctp)
In /cake/libs/view/errors you will find all the default error views.
You can copy and paste error404.ctp in your app/view/errors directory or create a new file and customize this view as you like.
3. Set the error layout in app_controller.php
Then add this to your app_controller.php :
function _setErrorLayout() {
if ($this->name == ‘CakeError’) {
$this->layout = ‘error’;
}
}

function beforeRender () {
$this->_setErrorLayout();
}