What i find myself?
cakePHP
cakePHP : How to skip Associations on find
Aug 17th
Hi Friends,
I am back again. Now there are 10000 cases where we need to get the results from a table with specific set of fields. Like we need to get
$this->find("all", array("fields" => "User.firstname, User.lastname, User.avatar","order" => "User.last_login DESC", "limit" => $cnt));
Now if the parent table be User and it have so many associations then this find will join all the other sets of fields in other Associated tables.
To avoid this use the following
(I am writing code for model. If controller specify the model also. eg: $this->User->recursive = -1 etc)
function active_users($cnt = 9){ $this->recursive = -1; return $this->find("all", array("fields" => "User.firstname, User.lastname, User.avatar","order" => "User.last_login DESC", "limit" => $cnt)); }
Facebook Connect Plugin for cakePHP
Jul 30th
Hi,
Here is an excellent plugin for cakephp. Facebook operations can be easily handled through this. You can integrate to Auth component also.
check it out : Facebook Plugin for Cakephp
Thanks
Amjith
Google Map for CakePHP 1.3 +
Jul 23rd
Hi Friends,
Here is another link i found for google map. Google Map Helper . You can copy this code for good map for your views.
For Cake 1.3 +
copy and paste this file in /app/views/helper/google_map.php
< ?php /* * CakeMap -- a google maps integrated application built on CakePHP framework. * Based on initial versione from Garrett J. Woodworth : gwoo@rd11.com * Rewritten by : http://www.small-software-utilities.com * * @author info@small-software-utilities.com * @version 0.2 * @license OPPL * * Modified by Mahmoud Lababidi <lababidi@bearsontherun.com> * Date Dec 16, 2006 * Rewritten by small software utilities <info @small-software-utilities.com> * Date May, 2010 */ class GoogleMapHelper extends Helper { var $errors = array(); var $key = "your key here, not needed for v3"; var $url ="http://maps.google.com/maps/api/js?sensor=false"; function map($default, $style = 'width: 400px; height: 400px' ) { //if (empty($default)){return "error: You have not specified an address to map"; exit();} $out = "<div id=\"map\""; $out .= isset($style) ? "style=\"".$style."\"" : null; $out .= " ></div>"; $out .= " <script type=\"text/javascript\"> //< ![CDATA[ var directionDisplay; var directionsService = new google.maps.DirectionsService(); var map; var iconimage = \"http://labs.google.com/ridefinder/images/mm_20_red.png\"; var iconshadow = \"http://labs.google.com/ridefinder/images/mm_20_shadow.png\"; var myOptions = { zoom: ".$default['zoom'].", center: new google.maps.LatLng(".$default['lat'].", ".$default['long']."), mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: true }; var map = new google.maps.Map(document.getElementById(\"map\"), myOptions); function cleardirs() { if(directionsDisplay) directionsDisplay.setMap(null); div = document.getElementById('".(isset($default['directions_div'])?$default['directions_div']:'directions_div')."'); if(div) div.innerHTML = \"\"; } "; if(isset($default['directions_div'])) { $out .= " directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('".$default['directions_div']."')); function calcRoute(fromid,tolat,tolon) { directionsDisplay.setMap(map); from = document.getElementById(fromid).value; var start = from; var end = new google.maps.LatLng(tolat,tolon); var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); } "; } $out .=" //]]> </script>"; return $out; } function addMarkers(&$data, $icon=null) { $out = " <script type=\"text/javascript\"> //< ![CDATA[ "; if(is_array($data)) { $i = 0; foreach($data as $n=>$m){ $keys = array_keys($m); $point = $m[$keys[0]]; if(!preg_match('/[^0-9\\.\\-]+/',$point['longitude']) && preg_match('/^[-]?(?:180|(?:1[0-7]\\d)|(?:\\d?\\d))[.]{1,1}[0-9]{0,15}/',$point['longitude']) && !preg_match('/[^0-9\\.\\-]+/',$point['latitude']) && preg_match('/^[-]?(?:180|(?:1[0-7]\\d)|(?:\\d?\\d))[.]{1,1}[0-9]{0,15}/',$point['latitude'])) { $out .= " var point".$i." = new google.maps.LatLng(".$point['latitude'].",".$point['longitude']."); var marker".$i." = new google.maps.Marker({ position: point".$i.", map: map, title:\"".(isset($point['title'])?$point['title']:'')."\", shadow: iconshadow, icon: iconimage, });"; if(isset($point['title'])&&isset($point['html'])) { $out .= " var infowindow$i = new google.maps.InfoWindow({ content: \"$point[title]$point[html]\" }); google.maps.event.addListener(marker".$i.", 'click', function() { infowindow$i.open(map,marker".$i."); });"; } $data[$n][$keys[0]]['js']="marker$i.openInfoWindowHtml(marker$i.html);"; $i++; } } } $out .= " //]]> </script>"; return $out; } function addClick($var, $script=null) { $out = " <script type=\"text/javascript\"> //< ![CDATA[ $script google.maps.event.addListener(map, 'click', ".$var.", true); //]]> </script>"; return $out; } function addMarkerOnClick($innerHtml = null) { $mapClick = ' var mapClick = function (event) { var marker = new google.maps.Marker({ position:event.latLng, icon: iconimage, map:map }); var infowindow = new google.maps.InfoWindow({ content: \"'.$innerHtml.'\" }); google.maps.event.addListener(marker, \'click\', function() { infowindow.open(map,marker); }); } '; return $this->addClick('mapClick', $mapClick); } function moveMarkerOnClick($lngctl, $latctl, $innerHtml = null) { $mapClick = ' var mapClick = function (event) { marker0.setPosition(event.latLng); lngctl = document.getElementById(\''.$lngctl.'\'); latctl = document.getElementById(\''.$latctl.'\'); if(lngctl) lngctl.value = event.latLng.lng(); if(latctl) latctl.value = event.latLng.lat(); } '; return $this->addClick('mapClick', $mapClick); } } ?> </info>
And add in controller
var $helpers = array('GoogleMap');
Use in Views
< ?php $default = array('type'=>'0','zoom'=>13,'lat'=>'42.5846353751749','long'=>'11.5191650390625'); $points = array(); $points[0]['Point'] = array('longitude' =>$default['long'],'latitude' =>$default['lat']); $key = $this->GoogleMap->key; echo $javascript->link($this->GoogleMap->url); echo $this->GoogleMap->map($default,'width: 600px; height: 400px'); echo $this->GoogleMap->addMarkers($points); echo $this->GoogleMap->moveMarkerOnClick('StructureLongitudine','StructureLatitudine'); ?>
All credit of this helper goes to GoogleMap V3 cakePHP Helper
And i am trying to find a google database for IP to location(returns lat and lang). Will let you know soon.
Thanks
amjith
Integrating SWFUpload with CakePHP (all versions)
Jul 1st
Hi,
I am very impressed with SWFUpload and will make use of this in future developments. Its kool flash player can handle all things needed for a developer to handle things in client side. There are so many benefits of using this for fileuploads because everything needed for handling file uploads can be done with there flash player so as there is no need of checking through scripts. The only disadvantage is only flash supported clients can handle uploading.
As my fav is cakePHP and i uses 80% of my developments through cake, the first i i thought about integrating SWFUpload to CakePHP. For this as my first work is searched some components for easy use. I have found some. I have made some try to integrate this components and successfully wasted my 2 hours.
Later i though about why cant i directly integrate SWFUpload into the view. Since SWFUpload completely a client side script and just making an ajax call to the server, i planned to go as manual integration and got success.
As i have bad memory i think i need to update this in to blog so that it will be helpful for me in future. And may be you too…. enjoy
Integrating SWFUpload with CakePHP
- Download SWFUpload from http://code.google.com/p/swfupload/
- Be sure you have a cakePHP in your server
- Unzip and place the file in this manner (You can use anywhere and only thing is you should know how to set path in views)
- Copy all images to app\webroot\img . See i have these images in the folder cancelbutton.gif, XPButtonUploadText_61×22.png
- Copy all javascript and flash files app\webroot\js\swfupload. I have the following files in mentioned folder now fileprogress.js, handlers.js, swfupload.js, swfupload.queue.js, swfupload.swf, swfupload.swfobject.js, swfuploadbutton.swf
- In view (You can add this in layout in ‘head’ tag. I have added in view to reduce overload printing these files on all views and i know this is not a good method).
//This code is in view to print script files < ?php e($javascript->link(array( 'swfupload/swfupload', 'swfupload/swfupload.swfobject', 'swfupload/swfupload.queue', 'swfupload/fileprogress', 'swfupload/handlers', ))); ?>
Followed by
// Script code in view enclosed with script tag < script> var swfu; SWFUpload.onload = function () { var settings = { flash_url : site_url + "js/swfupload/swfupload.swf", upload_url: "< ?php echo $html->url('/images/sampleupload/'.$session->id()) ?>", post_params: { "PHPSESSID" : "NONE", ".what" : "OKAY" }, file_size_limit : "3 MB", file_types : "*.jpg", file_types_description : "JPG Files", file_upload_limit : 30, file_queue_limit : 0, custom_settings : { progressTarget : "fsUploadProgress", cancelButtonId : "btnCancel" }, debug: false, // Button Settings button_image_url : site_url + "/img/XPButtonUploadText_61x22.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 61, button_height: 22, // The event handler functions are defined in handlers.js swfupload_loaded_handler : swfUploadLoaded, file_queued_handler : fileQueued, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_start_handler : uploadStart, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, queue_complete_handler : queueComplete, // Queue plugin event // SWFObject settings minimum_flash_version : "9.0.28", swfupload_pre_load_handler : swfUploadPreLoad, swfupload_load_failed_handler : swfUploadLoadFailed }; swfu = new SWFUpload(settings); }
Please note. My settings may be different. So please read how the settings needed to be given for SWFUpload.onload. Just know how the paths are given. See “upload_url:” This is the path to controller method where it handles the uploads. I will add my method below/ And important is need to pass $session->id(). and in “flash_url:”, site_url is the location (eg: http://localhost/fileuploading)
- Now we can move to controller. There are few things to note in controller
// Controller images before filter to handle session->id() function beforeFilter() { if ($this->action == 'sampleupload') { $this->Session->id($this->params['pass'][0]); $this->Session->start(); } parent::beforeFilter(); }
Then the method simpleupload (I have added some components for uplaoding the file. You can use your own script for uploading)
// controller method code for uploading function sampleupload(){ // Code for Session Cookie workaround if (isset($_POST["PHPSESSID"])) { session_id($_POST["PHPSESSID"]); } else if (isset($_GET["PHPSESSID"])) { session_id($_GET["PHPSESSID"]); } // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762) $POST_MAX_SIZE = ini_get('post_max_size'); $unit = strtoupper(substr($POST_MAX_SIZE, -1)); $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1))); // Settings $save_path = realpath('../../app/webroot/uploads/listings') . "/";; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment) $upload_name = "Filedata"; $max_file_size_in_bytes = 2147483647; // 2GB in bytes $extension_whitelist = array("jpg", "gif", "png"); // Allowed file extensions $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; // Characters allowed in the file name (in a Regular Expression format) // Other variables $MAX_FILENAME_LENGTH = 260; $file_name = ""; $file_extension = ""; $uploadErrors = array( 0=>"There is no error, the file uploaded with success", 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 3=>"The uploaded file was only partially uploaded", 4=>"No file was uploaded", 6=>"Missing a temporary folder" ); // Validate the upload if (!isset($_FILES[$upload_name])) { $this->HandleError("No upload found in \$_FILES for " . $upload_name); exit(0); } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) { $this->HandleError($uploadErrors[$_FILES[$upload_name]["error"]]); exit(0); } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) { $this->HandleError("Upload failed is_uploaded_file test."); exit(0); } else if (!isset($_FILES[$upload_name]['name'])) { $this->HandleError("File has no name."); exit(0); } // Validate the file size (Warning: the largest files supported by this code is 2GB) $file_size = @filesize($_FILES[$upload_name]["tmp_name"]); if (!$file_size || $file_size > $max_file_size_in_bytes) { $this->HandleError("File exceeds the maximum allowed size"); exit(0); } if ($file_size < = 0) { $this->HandleError("File size outside allowed lower bound"); exit(0); } // Validate file name (for our purposes we'll just remove invalid characters) $file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name'])); if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) { $this->HandleError("Invalid file name"); exit(0); } // Validate that we won't over-write an existing file if (file_exists($save_path . $file_name)) { $this->HandleError("File with this name already exists"); exit(0); } // Validate file extension $path_info = pathinfo($_FILES[$upload_name]['name']); $file_extension = $path_info["extension"]; $is_valid_extension = false; foreach ($extension_whitelist as $extension) { if (strcasecmp($file_extension, $extension) == 0) { $is_valid_extension = true; break; } } if (!$is_valid_extension) { $this->HandleError("Invalid file extension"); exit(0); } /* Starts uploading functions */ $listing_id = $_POST['listing_id']; /* Ends uploading functions */ $listing = $this->Listing->read(null , $listing_id); $this->data['Image'] = $_FILES[$upload_name]; $file = $_FILES[$upload_name]; if (!empty($listing)) { $mls_number = $listing['Listing']['mls_number']; $listing_id = $listing['Listing']['id']; }else{ $this->HandleError(__('Invalid listing.', true)); } // Begin : uploading images.... $errors = array(); // grab the file $file_name = date('Ymdhis') . ".jpg"; // This is a component function use your upload code here $uploaded = $this->Upload->upload($file, $destination_path, $file_name); exit(0); } function HandleError($message) { echo $message; }
- Done.
Please note. Just take the concepts. There may be errors in controller. Use it with your idea
Amjith
Uploading larger files in cakePHP
Jun 21st
Hi,
Was just wondering about uploading larger files in cakePHP. hen i try to upload multiple larger images i was getting Maximum time limit error. I have checked various ways of tricks to prevent such as setting php_ini and all.. but cannot over ride server default settings. Last i got success
with this
create a .htaccess file (in cakePHP there will be a htaccess file in root.).
Add the following code to the .htaccess file
php_value upload_max_filesize 20M php_value post_max_size 20M php_value max_execution_time 200 php_value max_input_time 200
Change values as needed.
No i am lookign for someone to add some better way to solve this because some says this method will take more server resource
thanks
cakePHP – SEO text helper
May 21st
Hi Guys,
I got some code from somewhere for SEO titles. I have made it to cakePHP helper because i have to use it somewhere to create SEO titles for the URL. I have posted this because this may be helpful for you.
// app/views/helpers/link.php class LinkHelper extends AppHelper { function seoTitle($string) { $string = preg_replace("`\[.*\]`U","",$string); $string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string); $string = htmlentities($string, ENT_COMPAT, 'utf-8'); $string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string ); $string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string); return strtolower(trim($string, '-')); } }
Add helper to the controller
var $helpers = array('Link');
Call from view as
$Link->seoTitle("Ever Smoke weed before?");
will result as “ever-smoke-weed-before”
Thanks :-*
cakePHP – Truncate Strings and Restore tags helper
Apr 30th
I have used some functions from http://www.the-art-of-web.com/php/truncate/ for creating a helper in cakePHP for truncating strings. This will help to fix the closing tags from a HTML string so that we can make strings without breaking design.
I have several places where to use this functions to truncate strings.
Here is a small helper for cakePHP to truncate and restore tags which help you to display stings.
// app\views\helpers\truncate.php class TruncateHelper extends AppHelper { function myTruncate($string, $limit, $break=" ", $pad="...") { // return with no change if string is shorter than $limit if(strlen($string) < = $limit) return $string; $string = substr($string, 0, $limit); if(false !== ($breakpoint = strrpos($string, $break))) { $string = substr($string, 0, $breakpoint); } $string = $this->restoreTags($string); return $string . $pad; } function restoreTags($input) { $opened = array(); // loop through opened and closed tags in order if(preg_match_all("/< (\/?[a-z]+)>?/i", $input, $matches)) { foreach($matches[1] as $tag) { if(preg_match("/^[a-z]+$/i", $tag, $regs)) { // a tag has been opened if(strtolower($regs[0]) != 'br') $opened[] = $regs[0]; } elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) { // a tag has been closed unset($opened[array_pop(array_keys($opened, $regs[1]))]); } } } // close tags that are still open if($opened) { $tagstoclose = array_reverse($opened); foreach($tagstoclose as $tag) $input .= ""; } return $input; } } ?>
Initialize the helper in controller as
var $helpers = array('Trancate');
Use this in View
< ?php echo $trancate->myTruncate($html_content, 400, " ", "...");?>
Enjoy
Thanks
cakePHP – Admin url routing
Apr 26th
While we bake the controllers in cakePHP we will set admin functions to control the tables from admin side. This admin methods are very helpful to get all the functions copied as admin_<method> in each controller and we can bake the views for admin methods.
But while we use the admin functions, We usually have to go like
http://example.com/admin/users/login
while we have a user login section for admin
We have to overcome this as admin should be redirected from the URL
http://example.com/admin/
This is usually return a Missing Controller error.
To overcome this we can set routing in apps/config/routes.php adding a line
Router::connect('/admin', array('controller' => 'users', 'action' => 'login', 'admin' => 'true'));
This will make the URL for admin pretty as we just want to route the URL http://example.com/admin/ to http://example.com/admin/users/login so there wont be a Missing Controller Issues.
Thanks
cakePHP – Getting full URL path in View
Apr 25th
If you want to get full path URL of the page in view you can use this cakephp function in Views
<input name="post-share-link" type="text" value="<?php echo $html-/>url('/' . $this->params['url']['url'], true);?>" />
Where
< ?php echo $html->url('/' . $this->params['url']['url'], true);?>
Will print the current path to the page. This can be used to give the share links in page
Thanks
CakePHP Helper for SEO URL’s
Apr 25th
Hi,
SEO Plays a vital role in web development. So here is a small helper for creating SEO text links for your cakePHP application
// views/helpers/link.php class LinkHelper extends AppHelper { function seoTitle($string) { $string = preg_replace("`\[.*\]`U","",$string); $string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string); $string = htmlentities($string, ENT_COMPAT, 'utf-8'); $string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string ); $string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string); return strtolower(trim($string, '-')); } }
Call Helper from controller
var $helpers = array('Link');
Pass strings through the view as
$link->seoTitle($true_vote['Post']['title'])
This is mainly used with routing titles in URL
Example : This is very useful to use the functions while we need the post title to be in URL. So you can customize the title to SEO way and place it in view.
Thanks