jump to navigation

Another window helper March 30, 2006

Posted by rossoft in CakePHP.
6 comments

1. Download the zip from http://blogus.xilinus.com/pages/javawin
Place window.js in /js/window/  and the content of css theme folder in /css/window/

2. Put this on /app/views/helpers/window.php

<?php
/**
 * Window Helper
 * @author RosSoft
 * @license MIT
 * @version 0.10
 * 
 * @link http://blogus.xilinus.com/pages/javawin
 * 
 */
class WindowHelper extends Helper
{
    var $helpers=array('javascript','head');
    
    var $cssdir='window/';
    var $js='window/window';
    
    var $default_width=300;
    var $default_height=70;
    var $default_ok_label='Cerrar';
    var $default_cancel_label='Cancelar';
    var $default_cancel_function='void(0);';
    var $default_ok_function='void(0);';
    var $default_title='';
    var $default_hide_effect='Effect.BlindUp';
    var $default_show_effect='Effect.Appear';
    var $default_resizable=true;
    
    function _register_files()
    {
        $this->head->register_js($this->js);
        $this->head->register_jsblock('var window_helper_index=0;');
        $this->head->register_css($this->cssdir . 'alert');
        $this->head->register_css($this->cssdir. 'default');
        $this->head->register_css($this->cssdir. 'theme1');                
    }            

    /**
     * Shows a confirmation dialog box
     * @param string $content Content of the dialog box
     * @param array Association array of parameters
     * @see _get_params() 
     * @param boolean $jstag Enclose the javascript code in <javascript> tag
     * @return string
     */
    function show_confirm($content,$params=array(),$jstag=false)
    {
        $this->_register_files();
        $params=$this->_get_params($params);
        extract($params);
        
        ob_start();
        $jscode="Dialog.confirm('$content', 
                                        {windowParameters: {width:$width, height:$height}, okLabel: '$ok_label',
                                        cancelLabel: '$cancel_label',                                        
                                         cancel:function(win){ $cancel_function },
                                         ok:function(win){ $ok_function }});";
        if ($jstag)
        {
            echo $this->javascript->codeBlock($jscode);        
        }
        else
        {
            echo $jscode;
        }
        return ob_get_clean();
    }
    
    /**
     * Shows a window
     * @param string $value An url / or the html content of the window
     * @param boolean $is_url If true, then $value is an url, else the content in html
     * @param boolean $modal The window is modal 
     */
    
    function show_window($content,$is_url=false,$modal=false,$params=array(),$jstag=false)
    {                
        static $index=0;
        
        $params=$this->_get_params($params);
        extract($params);
        
        $this->_register_files();
        
        ob_start();
        $jscode="var win = new Window('window_' + window_helper_index, {className: 'dialog', title:'$title', zIndex:150, resizable: $resizable, width:$width, height:$height, hideEffect: $hide_effect, showEffect: $show_effect";
        if ($is_url)
        {
            $jscode.=", url: '$content'";
        }
        $jscode.="});";
        
        if (! $is_url)
        {
            $jscode.="win.getContent().innerHTML = '$content';";
        }
        if ($modal)
        {
            $jscode.="win.showCenter(true);";    
        }
        else
        {
            $jscode.="win.showCenter(false);";
        }
        $jscode.="window_helper_index++;";
        if ($jstag)
        {
            echo $this->javascript->codeBlock($jscode);
        }
        else
        {
            echo $jscode;
        }
        $index++;
        return ob_get_clean();
    }
    
    function _get_params($params)
    {        
        if (! isset($params['width']))
        {
            $params['width'] =$this->default_width;    
        }
        
        if  (!isset($params['height']))
        {            
            $params['height']=$this->default_height;
        }
        
        if (!isset($params['ok_label']))
        {
            $params['ok_label']=$this->default_ok_label;        
        }

        if (!isset($params['cancel_label']))
        {
            $params['cancel_label']=$this->default_cancel_label;        
        }        
        
        if (!isset($params['cancel_function']))
        {
            $params['cancel_function']=$this->default_cancel_function;        
        }

        if (!isset($params['ok_function']))
        {
            $params['ok_function']=$this->default_ok_function;        
        }

        if (!isset($params['title']))
        {
            $params['title']=$this->default_title;        
        }

        if (!isset($params['hide_effect']))
        {
            $params['hide_effect']=$this->default_hide_effect;    
        }
        
        if (!isset($params['show_effect']))
        {
            $params['show_effect']=$this->default_show_effect;    
        }
        
        if (!isset($params['resizable']))
        {
            $params['resizable']=$this->default_resizable;
        }
        
        
        return $params;
    }     
}
?>

Some examples:

<a href="javascript: void(0)" onclick="<?=$window->show_confirm('Are you sure?',array('width'=>200,'height'=>150))?>" >click here 1</a>
<br/>
<a href="javascript: void(0)" onclick="<?=$window->show_window('<b>Hello world</b>',false,true)?>" >click here 2</a>
<br/>
<a href="javascript: void(0)" onclick="<?=$window->show_window($html->url('/pruebas/test_submodal_result'),true,true,array('hide_effect'=>'Effect.Disappear','width'=>600,'height'=>300))?>" >click here 3</a>
<br/>

IP to Country component (Geo Location) March 29, 2006

Posted by rossoft in CakePHP.
4 comments

1. Download and uncompress this to vendors/geoip/geoip.dat

2. Download this and copy to vendors/geoip/geoip.php

3. Download the CacheObject component

4. Copy this to app/controllers/components/geoip.php

<?php
/*
 * GeoIP component 
 * Detects the country of your visitor
 *
 * @author      RosSoft
 * @version     0.1
 * @license        MIT
 * 
 * @link http://www.maxmind.com/
 * 
 * DAT file:
 * @link http://www.maxmind.com/download/geoip/database/GeoIP.dat.gz
 * 
 * PHP INC file:
 * @link http://www.maxmind.com/download/geoip/api/php/geoip.inc
 */

class GeoipComponent extends Object
{
    var $components=array('cacheObject','session');
    
    function detect()
    {    
        $addr=env('REMOTE_ADDR');
        $cacheName='geoip/' . md5($addr);
        $sessionName='geoip';
        $this->session->del($sessionName);
        if ($this->session->check($sessionName))
        {
            $country=$this->session->read($sessionName);            
        }
        else
        {
            $country=$this->cacheObject->read($cacheName);
            if (!$country)
            {
                vendor('geoip/geoip');
                $geoip_data= geoip_open(VENDORS . 'geoip' . DS . 'geoip.dat',GEOIP_STANDARD); /* apertura y lectura del archivo utilizando la constante GEOIP_STANDARD como forma de lectura que adquiere valor en geoip.inc */
                $country=geoip_country_name_by_addr($geoip_data, $addr);
                geoip_close($geoip_data);
                
                $this->cacheObject->write($cacheName,$country,'+5 day');
            }
            $this->session->write($sessionName,$country);
        }
        return $country;        
    }
}
?>

Usage:

Include the component $var components=array(‘xx’,’geoip’);

In your controller:
$country=$this->geoip->detect();

The country is cached in session and in cache file.

Register head tags from helpers (2) March 28, 2006

Posted by rossoft in CakePHP.
45 comments

Improved version of https://rossoft.wordpress.com/2006/03/23/register-javascript-css-files-from-helpers/&nbsp;

Some examples self-explanatory:

$head->register_js("test2");
$head->register_css("mycss2");
$head->register_css("mycss1",array('media'=>'print'));
$head->register_cssblock("    .modbox .el {display:none;}
                            .modbox .csl, .modbox .es {display:none;}
                            .modbox_e .el {display:none;}");
$head->register_jsblock('alert("hi!");');
$head->register_link(array(    'rel'=>'alternate',
                            'type'=>'text/xml',
                            'title'=>'General RSS 0.91',
                            'href'=>'http://www.elotrolado.net/temp/rss091.xml'));

$head->register_meta(array(    'http-equiv'=>'Content-Type',
                            'content'=>'text/html; charset=UTF-8'));

$head->register_raw('<script>alert("raw html");</script>');

Copy to /app/views/helpers/head.php

<?php
/**
 * Head Helper
 * Register <head> tags from helpers, then print them
 * in head through layout.
 * @author RosSoft
 * @license MIT
 * @version 0.2  
 */
class HeadHelper extends Helper 
{
    var $helpers=array('html','javascript');
    
    var $_library; //static array of items to be included            

    function __construct()
    {
           static $library=array();  //for php4 compat 
           $this->_library=& $library;
    }

    /**
     * Adds a css file to array 
     * @param string $file CSS file to be included
     * @param string $param Array of htmlAttributes
     */
    function register_css($file,$htmlAttributes=null)
    {
        $this->_register(array($file,'css',$htmlAttributes));
    }
    
    /**
     * Adds an inline css block to array 
     * @param string $css CSS tags to be included
     * @param string $param Array of htmlAttributes
     */
    function register_cssblock($css,$htmlAttributes=null)
    {
        $this->_register(array($css,'cssblock',$htmlAttributes));
    }
    
    
    /**
     * Adds a js file to array 
     * @param string $file CSS file to be included
     * @param string $param Array of htmlAttributes
     */
    function register_js($file)
    {
        $this->_register(array($file,'js'));
    }
    
    /**
     * Adds a javascript block to array 
     * @param string $javascript Javascript block to be included
     * @param string $param Array of htmlAttributes
     */
    function register_jsblock($javascript)
    {
        $this->_register(array($javascript,'jsblock'));
    }    
    
    /**
     * Adds a meta tag to array
     * @param array $htmlAttributes Array of html attributes of meta tag  
     */
    function register_meta($htmlAttributes)
    {
        $this->_register(array($htmlAttributes,'meta'));
    }
    
        
    /**
     * Adds a link tag to array
     * @param array $htmlAttributes Array of html attributes of meta tag  
     */
    function register_link($htmlAttributes)
    {
        $this->_register(array($htmlAttributes,'link'));
    }          
    
    /**
     * Adds a raw sequence of html tags to array
     * @param string $raw Sequence of html tags
     */
    function register_raw($raw)
    {
        $this->_register(array($raw,'raw'));
    }

    /**
     * Prints the html for all of the items registered
     * @return string 
     */           
    function print_registered()
    {
        foreach ($this->_library as $l)
        {
            switch ($l[1])
            {
                case 'css':
                    echo $this->html->css($l[0],'stylesheet',$l[2]);    
                    break;
                case 'js':
                    echo $this->javascript->link($l[0]);
                    break;
                case 'jsblock':
                    echo $this->javascript->codeBlock($l[0]);
                    break;
                case 'meta':
                    echo "<meta " . $this->_parseAttributes($l[0]) . " />";
                    break;
                case 'link':
                    echo "<link " . $this->_parseAttributes($l[0]) . " />";
                    break;
                case 'raw':
                    echo $l[0];
                    break;
                case 'cssblock':
                    echo '<style type="text/css" ' .  $this->_parseAttributes($l[2]) . " ><!--{$l[0]}--></style>";
                    break; 
                default:
                    die('Internal error on HeadHelper: Unknown type registered.');
            }
        }             
    }
    
    
    /**
     * Adds the item in the array if it doesn't already exist
     * @param array $item Item to be added
     * @access private
     */
    function _register($item)
    {
        if (! in_array($item,$this->_library))
        {
            $this->_library[]=$item;
        }                    
    }                                           
    
    
    
    /**
     * This is a copy of the same function in HtmlHelper
     * Returns a space-delimited string with items of the $options array. If a
     * key of $options array happens to be one of:
     *    + 'compact'
     *    + 'checked'
     *    + 'declare'
     *    + 'readonly'
     *    + 'disabled'
     *    + 'selected'
     *    + 'defer'
     *    + 'ismap'
     *    + 'nohref'
     *    + 'noshade'
     *    + 'nowrap'
     *    + 'multiple'
     *    + 'noresize'
     *
     * And its value is one of:
     *    + 1
     *    + true
     *    + 'true'
     *
     * Then the value will be reset to be identical with key's name.
     * If the value is not one of these 3, the parameter is not output.
     *
     * @param  array  $options      Array of options.
     * @param  array  $exclude      Array of options to be excluded.
     * @param  string $insertBefore String to be inserted before options.
     * @param  string $insertAfter  String to be inserted ater options.
     * @return string
     */
    function _parseAttributes($options, $exclude = null, $insertBefore = ' ',
    $insertAfter = null)
    {
        $minimizedAttributes = array(
        'compact',
        'checked',
        'declare',
        'readonly',
        'disabled',
        'selected',
        'defer',
        'ismap',
        'nohref',
        'noshade',
        'nowrap',
        'multiple',
        'noresize');

        if (!is_array($exclude))
        {
            $exclude = array();
        }

        if (is_array($options))
        {
            $out = array();

            foreach ($options as $key => $value)
            {
                if (!in_array($key, $exclude))
                {
                    if (in_array($key, $minimizedAttributes) && ($value === 1 ||
                    $value === true || $value === 'true' || in_array($value,
                    $minimizedAttributes)))
                    {
                        $value = $key;
                    }
                    elseif (in_array($key, $minimizedAttributes))
                    {
                        continue;
                    }
                    $out[] = "{$key}=\"{$value}\"";
                }
            }
            $out = join(' ', $out);
            return $out? $insertBefore.$out.$insertAfter: null;
        }
        else
        {
            return $options? $insertBefore.$options.$insertAfter: null;
        }
    }
    

}
           
?>

Maskedit Input helper (updated) March 27, 2006

Posted by rossoft in CakePHP.
13 comments

Creates a maskedit inputbox. Compatible with Firefox, IE

Usage from view:
$maskedit->maskedit(‘Customer/somefield’,’nnnn-aa-nn’,array(‘size’=>30));

1. Put this on app/views/helpers/maskedit.php

/**
 * Creates a masked input box
 * @author RosSoft
 * @license MIT
 * @version 0.1
 */
class MaskeditHelper extends Helper
{
    var $helpers=array(‘Html’,’Javascript’,’Head’);
   
    /*
     * Creates a masked input box
     * @param string $fieldname input box fieldname (model/field)
     * @param string $mask The input Mask
     * @param array $htmlAttributes Extra html attributes for input tag
     * @return string
     */
    function maskedit($fieldname,$mask,$htmlAttributes)
    {
        $this->Head->register_js(‘maskedit/maskedit’);
       
        if (!isset($htmlAttributes[‘id’]))
        {
            $htmlAttributes[‘id’]=”maskedit_” . str_replace(‘/’,’_’,$fieldname);
        }
        $htmlAttributes[‘onclick’]=”javascript:RS_InputMask_OnClick(event, this);”;
        $htmlAttributes[‘onkeypress’]=”javascript:RS_InputMask_KeyPress(event, this);”;
        $htmlAttributes[‘onkeydown’]=”javascript:RS_InputMask_KeyDown(event, this);”;
        $htmlAttributes[‘oninput’]=”javascript:RS_InputMask_OnInput(event, this);”;
        $htmlAttributes[‘onfocus’]=”javascript:RS_InputMask_GotFocus(this);”;
        $htmlAttributes[‘onpaste’]=”javascript:RS_InputMask_OnPaste(this);”;       
               
        ob_start();                       
        echo $this->Html->input($fieldname, $htmlAttributes,true);
        echo $this->Javascript->codeBlock(“maskeditInit(‘{$htmlAttributes[‘id’]}’,’$mask’)”);
        return ob_get_clean();
    }
}
/**
 * Mask examples:
 * nnnn-nn-nn   Date
 * aaaa-nn      4 letters, then two numbers
 * xxxx-nn      4 alphanumeric, then two numbers
 * Other simbols than n and a are literals (maybe exists more special chars)
 */
?>
2. Put this  on app/webroot/js/maskedit/maskedit.js (attention: unknown source code, unknown license, unknown source url)
3. Include the helper maskedit in your controller

var $helpers=array(‘xxxx’,’maskedit’);

4. Copy this helper and rename to HeadHelper to file: app/webroot/helpers/head.php

App-Wide components / helpers March 27, 2006

Posted by rossoft in CakePHP.
3 comments

You can set another array variable in app_controller, then merge it
at the constructor with the $components / $helpers variable.

class AppController
{

    /** Array of common components for all controllers */

    var $appComponents = array(‘rdAuth’,’session’);
    

    /** Array of common helpers for all controllers */

    var $appHelpers= array(‘Html’, ‘Javascript’);

    function __construct()

    {

        $this->components=am($this->appComponents,$this->components);

        $this->helpers=am($this->appHelpers,$this->helpers);

     
        parent::__construct();

    }
}
   

In your own controller, you can set the others helpers/components that
you use
class MyController extends AppController
{
    var $components=array(‘pdf’);
    var $helpers=array(‘myhtml’);
    function test() {}
}

Set the page title March 27, 2006

Posted by rossoft in CakePHP.
add a comment

You can set the page title from controller and views with this simple sentence:

$this->pageTitle=’A new title’;

Poor mans Cron Component March 27, 2006

Posted by rossoft in CakePHP.
2 comments

You must hack it a bit, because I use some constants and ‘configuracion’ component for storing the interval dates.

Usage: in beforeFilter() of AppController:
$this->cron->add(‘/mycontroller/cleanup’);

<?php
/*
 * Cron component
 * Executes tasks after rendering the output to the user at
 * certains time intervals.
 *
 * @author      RosSoft
 * @version     0.1
 * @license        MIT
 *
 */

class CronComponent extends Object
{
    var $controller;
    var $tareas=array();
    var $components=array(‘configuracion’,’requestHandler’);
    function startup(&$controller)
    {
        $this->controller=$controller;                       
    }
   
    /**
     * Adds a task to the list
     * @param string $tarea CakeURL of the action (/controller/action)
     */   
    function add($accion)
    {       
        $this->tareas[]=$accion;
    }
   
    function __destruct()
    {
        if (CONFIG_CRON_INTERVAL) //if 0 then disabled
        {
            $lastrun=$this->configuracion->value(‘CONFIG_CRON_LASTRUN’);
           
            $nextrun = $lastrun + 60 * CONFIG_CRON_INTERVAL;
            if (time()>$nextrun)
            {
                flush();
                if (! isset($this->requestHandler)
                    || ! $this->requestHandler->isAjax())
                {
                    $this->_execute_tasks();
                }
            }
        }
    }
   
   
    /**
     * Executed after flushed the page to the user, it the
     * call isn’t ajax.
     * It must call the programmed tasks if the timeout has
     * expired.
     */
    function _execute_tasks()
    {
        //a near future date for auto error recovering
        $this->configuracion->update(‘CONFIG_CRON_LASTRUN’,time() – CONFIG_CRON_RETRY_INTERVAL);           
        foreach ($this->tareas as $t)
        {
            @$this->controller->requestAction($t);           
        }
        $this->configuracion->update(‘CONFIG_CRON_LASTRUN’,time()+CONFIG_CRON_INTERVAL);
    }
}     

Register javascript & css files from helpers March 23, 2006

Posted by rossoft in CakePHP.
9 comments

If you have a helper that needs some javascript / css files that you want to include, you can include them in body or head.
It’s easy to include them in body, but if you want in head then you have to break a little your layout or include the file for all views.

I made a little helper for register the files you want from another helper, then print all the files registered in <head>.

In your own helper:
var $helpers=array(‘xxx’,’myhtml’);

function myfunc(xxx)
{
    $this->myhtml->register(‘tooltip’ , ‘js’);
    $this->myhtml->register(‘somecss’ , ‘css’);
}

In your layout, in head tag:
<? if (isset($myhtml)) echo $myhtml->print_registered(); ?>

Be sure to include myhtml helper in your appcontroller

<?
    class MyhtmlHelper extends Helper
    {
        var $helpers=array(‘html’,’javascript’);
       
           var $_library; //static array of files to be included            
          
           function __construct()
           {
               static $library;  //for php4 compat
               $this->_library=& $library;              
               $this->_library=array();             
           }
          
           /**
            * Adds a javascript file to array
            * @param string $file File to be included
            * @param type $type css | js
            */
           function register_file($file,$type)
           {
               if (! in_array($type,array(‘css’,’js’)))
               {
                die(“Myhtml_helper: Incorrect type: $type”);           
               }
               if (! in_array(array($file,$type),$this->_library))
               {
                   $this->_library[]=array($file,$type);
               }
                  
           }

        /**
         * Creates all the links to the files registered
         * @return string
         */          
           function print_registered()
           {
              foreach ($this->_library as $l)
              {
                  $file=$l[0];
                  $type=$l[1];
                  switch ($type)
                  {
                      case ‘css’:
                          echo $this->html->css($file);   
                          break;
                      case ‘js’:
                          echo $this->javascript->link($file);
                          break;
                  }
              }            
           }                                           
    }
?>

Submodal window helper March 20, 2006

Posted by rossoft in CakePHP.
2 comments

A helper for making submodal windows with this

1. Download this
2. Copy the *.js to /app/webroot/js/submodal/
3. Copy the *.css to /app/webroot/css/submodal/
4. Copy the close.gif to /app/webroot/img/submodal/
5. Put this on /app/views/helpers/submodal.php
<?php
/**
 * Submodal Helper
 * @author RosSoft
 * @license MIT
 * @version 0.10
 *
 * @link http://www.subimage.com/sublog/subModal
 *
 */
class SubmodalHelper extends Helper
{
    var $helpers=array(‘Html’,’Javascript’);
   
    var $css=’submodal/subModal’;
    var $jsdir=’submodal/’;
    var $img_close=’submodal/close.gif’;
    var $loading=’/pruebas/loading’;
     
    /**
     * Inits the submodal. Put on <body>
     * 
     */
    function init()
    {
        ob_start();
        if (!defined(‘MODAL_HELPER_REFS’))
        {
            define(‘MODAL_HELPER_REFS’,1);
            echo $this->Html->css($this->css);
            echo $this->Javascript->link($this->jsdir . ‘common’);
            echo $this->Javascript->link($this->jsdir . ‘subModal’);
            ?>
            <div id=”popupMask”>&nbsp;</div>
            <div id=”popupContainer”>
                 <div id=”popupInner”>
                      <div id=”popupTitleBar”>
                           <div id=”popupTitle”></div>
                           <div id=”popupControls”>
                               <?=$this->Html->image($this->img_close,array(‘onclick’=>’hidePopWin(true)’))?>
                       </div>
                      </div>
                      <iframe src=”<?=$this->Html->url($this->loading)?>” style=”width:100%;height:100%;background-color:transparent;” scrolling=”auto” frameborder=”0″ allowtransparency=”true” id=”popupFrame” name=”popupFrame” width=”100%” height=”100%”></iframe>
                 </div>
            </div>
            <?php
            $loading=$this->Html->url($this->loading);
            echo $this->Javascript->codeBlock(“gLoadingUrl=’$loading’; initPopUp(); hidePopWin(false);”);
            return ob_get_clean();
        }
        return ”;
    }

    /**
     * Change modal window url
     * @param string $url Url in form /controller/action/…
     * @param integer $width Width of the box
     * @param integer $height Height of the box
     * @param string $callback Will be called when window is closed
     * @return string Javascript code block enclosed in <script> tag
     */   
    function url($url,$width,$height,$callback=”)
    {
        return $this->Javascript->codeBlock($this->jsurl($url,$width,$height,$callback));
    }

    /**
     * Change modal window url
     * @param string $url Url in form /controller/action/…
     * @param integer $width Width of the box
     * @param integer $height Height of the box
     * @param string $callback Will be called when window is closed
     * @return string Javascript code block NOT enclosed in <script> tag
     */   
    function jsurl($url,$width,$height,$callback=null)
    {
        $url=$this->Html->url($url);
        if ($callback===null) $callback=’null’;
        return “showPopWin(‘$url’, $width, $height, $callback);window.setTimeout(‘setPopTitle();’, 2000);”;
    }   
}

/*
 
    Example of usage:
    <?=$submodal->init()?>
    <a href=”javascript: void(0)” onclick=”<?=$submodal->jsurl(‘/pruebas/test_submodal_result’,400,300,’windowclosed’)?>” >click here</a>
    <br/>
    <a href=”javascript: void(0)” onclick=”<?=$submodal->jsurl(‘/pruebas/test_submodal_result’,300,400)?>” >click here. Without callback</a>
    <script type=”text/javascript”>
    function windowclosed(code)
    {
        alert(“You have closed the window. Return code=” + code);
    }
    </script>
*/

?>

6. Include the helper in your controller var $helpers=array(‘xxx’,’Submodal’);

7. View code example:

<?=$submodal->init()?>

<a href=”javascript: void(0)” onclick=”<?=$submodal->jsurl(‘/pruebas/test_submodal_result’,400,300,’windowclosed’)?>” >click here</a>
<br/>
<a href=”javascript: void(0)” onclick=”<?=$submodal->jsurl(‘/pruebas/test_submodal_result’,300,400)?>” >click here. Without callback</a>
<script type=”text/javascript”>
function windowclosed(code)
{
    alert(“You have closed the window. Return code=” + code);
}
</script>

You have to put $submodal->init() anywhere in your  .
$submodal->jsurl() takes the parameters, url of the new window, width, height and a callback function that will be called after close. It returns a javascript call, you have to enclose it in a tag or anchor tag.

You have to edit the helper for set the loading page that will be shown.

Image Auth – CAPTCHA component March 16, 2006

Posted by rossoft in CakePHP.
30 comments

A human verification system through a text image

1. Include the component.
var  $components =array (‘xxx’,’yy’,’imageAuth’);

2. In the login action:
$this->imageAuth->generate();

3.
Create a new action for showing the image: /login/image_auth
function image_auth()
{
    $this->imageAuth->show();
}

4.
In the login form:
<img src=”<?=$html->url(’/login/image_auth’)?>” />

5. Put this in vendors/image_auth/

6. In your post-action:

if (! $this->imageAuth->check( $this->params[‘data’][‘text’] ))
{
    echo ‘Wrong text entered’;
}

7. Put this code in controllers/components/image_auth.php
<?php
/*
 * Image Auth component.
 * Real human verification system for forms
 *
 * @author      RosSoft
 * @version     0.1
 * @license        MIT
 *
 * @link http://phpbuilder.com/columns/patterson20060301.php3
 */
class ImageAuthComponent extends Object
{
    var $components = array(‘session’);
    var $controller;
   
    /** Font file */
    var $font=’ProggyCleanSZBP’;
   
    /** some background colors */
    var $bg_colors = array(
                                    ‘176.196.222’, // Blue
                                    ‘204.153.204’, // Purple
                                    ‘204.204.204’, // Gray
                                    ‘227.81.82’,     // Red
                                    ‘150.200.162’  // Green
                                    );
                                   
    /** Some font colors */
    var $font_colors = array(
                                    ‘0.0.139’, // Blue
                                    ‘104.34.139’, // Purple
                                    ‘79.79.79’, // Gray
                                    ‘128.0.0’, // Red
                                    ‘59.94.15’     // Green
                                    );
    /** Image width */                                
    var    $img_width = 170;
   
    /** Image height */
    var $img_height = 75;
   
    /** Font size */
    var $fnt_size = 24;
   
    /** Letter spacing */
    var $let_space = 10;

    /** Length of random string */       
    var $str_length = 6;
                                                           

    function startup(&$controller)
    {
        $this->controller=$controller;       
    }
   
    /**
     * Generates a new random string and stores on session
     * @param boolean $regenerate. If false and already exists a random string then it’s reused
     */   
    function generate($regenerate=true)
    {
        if (! $regenerate)
        {
            $regenerate= ! $this->session->check(‘image_auth_string’);
        }   
        if ($regenerate)
        {
            $rnd_str = $this->_gen_random_string($this->str_length);   
            $this->session->write(‘image_auth_string’,$rnd_str);       
        }
                   
    }
   
    /**
     * Outputs the random string as an image.
     * The string is readed from the session
     */
    function show()
    {
        $this->generate(false); //Generates a new string if there isn’t a generated one
        $rnd_str=$this->session->read(‘image_auth_string’);
       
        // Set GD font path
        putenv(‘GDFONTPATH=’.realpath(VENDORS . ‘image_auth’));
        /**
         * Image functions
         */
        // Create the image
        $img = imagecreate($this->img_width, $this->img_height) or die(‘Can not initialize GD Image Library’);

        // Define Background & Text colors
        list($br, $bg, $bb) = explode(‘.’, $this->bg_colors[rand(0, count($this->bg_colors)-1)]);
        list($tr, $tg, $tb) = explode(‘.’, $this->font_colors[rand(0, count($this->font_colors)-1)]);
        $bg_color = imagecolorallocate($img, $br, $bg, $bb);
        $txt_color = imagecolorallocate($img, $tr, $tg, $tb);
        $line_clr = imagecolorallocate($img, 0, 0, 0);
        // Create box around image
        imageline($img, 0, 0, $this->img_width, 0, $line_clr); // Top left to top right
        imageline($img, 0, 0, 0, $this->img_height, $line_clr); // Top left to bottom left
        imageline($img, 0, $this->img_height-1, $this->img_width, $this->img_height -1, $line_clr); // Bottom Left to Bottom right
        imageline($img, $this->img_width-1, 0, $this->img_width-1, $this->img_height, $line_clr); // Top right to bottom Right

        //     Write string into image
        for($i=0; $i
        {
            imagettftext($img, (rand() % $this->fnt_size / 1.5) + $this->fnt_size, rand(-30, 30), (($i*$this->fnt_size)+$this->let_space), rand($this->fnt_size+5, ($this->img_height – $this->fnt_size-5)), $txt_color, $this->font, $rnd_str{$i});
        }
        imagefilter($img,IMG_FILTER_GAUSSIAN_BLUR,200);
           header(“Pragma: public”);
           header(“Expires: 0”);
           header(“Cache-Control: no-store, no-cache”);
           header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
           header(“Cache-Control: public”);
        if (function_exists(‘imagepng’))
        {
            header(“Content-type: image/png”);
            imagepng($img);
        }
        else
        {
            header(“Content-type: image/jpeg”);
            imagejpeg($img);
        }
        $this->controller->autoRender=false;
    }
   
    /**
     * Checks the string passed against session for a valid auth
     * @param string $string String to be checked
     * @return boolean. True if valid  
     */   
    function check($string)
    {
        return ($string === $this->session->read(‘image_auth_string’));
    }

   
    /**
     * Random string generation function
     */
    function _gen_random_string($length=5, $str=”)
    {
        for($i=1; $i<=$length; $i++)
        {
            $ord = rand(48, 90);

            if( ( ($ord>=48) && ($ord<=57) ) || ( ($ord>=65) && ($ord<=90) ) )
            {
                $str .= chr($ord);
            }
            else
            {
                $str .= $this->_gen_random_string(1);
            }
        }
        return $str;
    }   
}