Showing posts with label cakephp. Show all posts
Showing posts with label cakephp. Show all posts

Friday, February 15, 2013

cakephp cpanel api component and controller

Update: added WHM accessKey support
The cPanel API component requires cURL to connect to the cPanel server.
The cURL part can be replaced with CakePHP's internal HttpSocket class, but at the time of this writing there is no SSL support in the HttpSocket class, so that cURL is used in this example.

Component Class:

<?php  /**
 * The cPanel API component provides easy controller integration with cPanel API calls.
 * Requires cURL support. 
 * 
 * @author Hendrik Daldrup <hendrik@jinarigo.ca>
 */
class CpanelApiComponent extends Object {

    var 
$disableStartup true;
    
    
/**
     * WHM domain name
     *
     * @var string
     * @access private
     */
    
var $__domain '';
    
    
/**
     * WHM port
     * default http port 2086
     * default https port 2087
     * 
     * @var integer
     * @access private
     */
    
var $__port 2086;
    
    
/**
     * WHM username
     *
     * @var string
     * @access private
     */
    
var $__user '';
    
    
/**
     * WHM password
     *
     * @var string
     * @access private
     */
    
var $__pass '';
    
    
/**
     * WHM accessKey
     *
     * @var string
     * @access private
     */
    
var $__accessKey '';
    
    
/**
     * Connect via https
     *
     * @var boolean
     * @access private
     */
    
var $__ssl false;
    
    
/**
     * cPanel URL string
     *
     * @var string
     * @access private
     */
    
var $__url '';
    
    
/**
     * Generate the cPanel URL, returns true on success.
     *
     * @param array $params Must include domain, user and pass. Port and SSL optional.
     * @return boolean
     */
    
function init($params = array()) {
        
        if (isset(
$params['domain']) && $params['domain'] != ''$this->__domain $params['domain'];
        else return 
false;
        
        if (isset(
$params['user']) && $params['user'] != ''$this->__user $params['user'];
        else return 
false;
        
        if (isset(
$params['pass']) && $params['pass'] != '') { 
            
$this->__pass $params['pass'];
        } else if (isset(
$params['accessKey']) && $params['accessKey'] != '') { 
            
$this->__accessKey $params['accessKey'];
        } else { 
            return 
false;
        }
        
        if (isset(
$params['port']) && $params['port'] != ''$this->__port $params['port'];
        if (isset(
$params['ssl']) && $params['ssl'] != ''$this->__ssl $params['ssl'];

        if (
$this->__ssl) {
            
$this->__url 'https';
        } else {
            
$this->__url 'http';
        }
        
$this->__url .= '://'.$this->__domain.':'.$this->__port;
        
        return 
true;
    }
    
    
/**
     * Sends a cPanel API query and returns the result 
     *
     * @param string $query cPanel API query to send, e.g.: '/xml-api/applist'
     * @return string
     */
    
function query($query null) {
        if (
$query) {
            
$ch curl_init();
            
curl_setopt($chCURLOPT_URL$this->__url.$query);
            
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
            
curl_setopt($chCURLOPT_RETURNTRANSFER1);
            if (isset(
$this->__accessKey) && $this->__accessKey != '') {
                
curl_setopt($chCURLOPT_HEADER0);
                
$customHeader[0] = "Authorization: WHM ".$this->__user.':'.$this->__accessKey;
                
curl_setopt($ch,CURLOPT_HTTPHEADER$customHeader);
            } else {
                  
curl_setopt($chCURLOPT_USERPWD$this->__user.':'.$this->__pass);
                
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
            }
            
$result curl_exec($ch);
            
curl_close($ch);

            return 
$result;
        }
        return 
false;
    }
    
}    
?>

Controller Class:

<?php  class CpanelController extends AppController  {
    var 
$name 'Cpanel';
    var 
$components = array('CpanelApi');
    
    function 
cpanelTest() {
        if (
$this->CpanelApi->init(array(
            
'domain' => 'WhmDomainName',
            
'user' => 'WhmUsername',
            
'pass' => 'WhmPassword',
            
//'accessKey' => 'WhmAccessKey',
            
'port' => 2086,
            
'ssl' => false))) 
        {
            
$cpanelData $this->CpanelApi->query('/xml-api/applist');
            
$this->set('cpanelData'$cpanelData);
        } else {
            
$this->Session->setFlash('Error in CpanelApiComponent init()');
        }
    }
}
?> 

Replace the WhmDomainName, WhmUsername and WhmPassword with the correct values of your WHM account.
The port and ssl values are optional, just make sure to change both, if you wish to use SSL support.
You can use the result to extract the data as needed. In this case it simply sends the result to the view.

It's also possible to use your WHM access key now. To do so, simply uncomment the 'accessKey' line in above controller example and remove the 'pass' line. Make sure to enter your access key as a single line, without any additional characters.

I hope this is usefull to someone and I will add a HttpSocket example, once SSL support is available.

http://bakery.cakephp.org/articles/Duncan/2008/07/15/cpanel-api-component 

Friday, February 1, 2013

Tuesday, January 22, 2013

A find condition about hasMany(has many) relationship in cakephp

Suppose you have two model User and UserRole.
And User has many UserRole.
Now you want to find User By specific UserRole.

User:
Fields: id, name, others........
var $hasMany = array(
    "UserRole"
);

UserRole:
Fields: id, user_id, role_id, others...var 
$belongsTo = array("User");

First you need to find all UserRole by your own conditions:

$userRoles = $this->UserRole->find("all", array(
    "conditions" => array(
        "UserRole.condition" => $value
    )
));

Now find User by UserRole as follows:

$users = $this->User->find("all", array(
    "conditions" => array(
        "User.id" => Set::extract("/UserRole/user_id", $userRoles)
    )
));


BINGO...

Friday, January 18, 2013

Cakephp delete and update records by conditions

Delete Records:
$this->ModelName->deleteAll(
    array(
        "ModelName.id" => 10
    )
);

Update Records:
$this->ModelName->updateAll(
    /* UPDATE FIELD */
    array(
        "ModelName.is_active" => 0,
    ),
    /* CONDITIONS */
    array(
        "ModelName.id" => 20,
        "ModelName.name LIKE" => '%SEARCH_TEXT%',
        "ModelName.name <>" => 'NOT_EQUAL_VALUE',
        'ModelName.integer_field > ' => 50, [Can use operand here]
        'TIMESTAMPDIFF(DAY, ModelName.date, NOW())' => 22 [number of day]
    )
);

Tuesday, November 27, 2012

phpWhois -base class to do whois queries with php

Code block:
        $pathMain = WWW_ROOT."..\\libs\\phpwhois\\whois.main.php";
        $pathUtils = WWW_ROOT."..\\libs\\phpwhois\\whois.utils.php";
        if(file_exists($pathMain) && file_exists($pathUtils)) {
            include_once($pathMain);
            include_once($pathUtils);
            $whois = new Whois();
            $whois->non_icann = true;
            $result = $whois->Lookup("yourcause22.com");
            print_r($result);
        }

Download WHOIS from:
http://www.phpwhois.org/
http://sourceforge.net/projects/phpwhois/?source=dlp

Thursday, July 26, 2012

Send Email Using CakePhp 2.0.6 and CakeEmail

Edit app/Config/email.php
public $default = array(
        'transport' => 'Smtp',
        'host' => '',
        'port' => 25,
        'timeout' => 300,
        'username' => '',
        'password' => '',
        'charset' => 'utf-8',
        'headerCharset' => 'utf-8',
    );

Create a component in app/Controller/Component as EmailHandlerServiceComponent.php
<?php
    class EmailHandlerServiceComponent extends Object {
        var $controller;

        public function sendEmail($to = "", $from = "", $fromName = "", $subject = "No Subject", $values = array())
        {
            App::uses('CakeEmail', 'Network/Email');
            $emailSender = new CakeEmail('default');
            $emailSender->to($to);
            $emailSender->subject(utf8Encode($subject));
            $emailSender->from(array($from=>$fromName));
            $emailSender->emailFormat('both');
            $emailSender->viewVars($values);
            $emailSender->template("first", "default");
            if ($emailSender->send()) {
                return true;
            } else {
                return false;
            }
        }
    }
?>

Create a file app/View/Layouts/Emails/html/default.php
Create a file app/View/Layouts/Emails/text/default.php 

Create a file app/View/Emails/html/first.php  
Create a file app/View/Emails/text/first.php 

Call sendEmail() from any controller.

You May Need To Edit app/lib/Cake/Network/Email/CakeEmail.php to set $this->charset and $this->_appCharset, set them to "utf-8" as default.