Wednesday, December 4, 2013

How to CREATING ACL WITH DATABASE IN ZEND FRAMEWORK[Easy tricky]

Hey Guys see the creation of a secure and powerful ACL (Access control list) it’s one of the most delicate and important pieces for building a sturdy website.  I’ll try to make this task easier sharing the code I used in one of my latest projects. This ACL system works with a MYSQL database which grant us total flexibility creating users and roles.


CREATING DATABASE TABLES

The first step is to create the necessary tables in database:
Table roles
For storing the roles or groups. Each role have is own privileges. This roles will be assigned to each user, and the users will inherit the role privileges.
1
2
3
4
5
CREATE TABLE `roles` (
  `id` tinyint(1) NOT NULL AUTO_INCREMENT,
  `role` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Now we add some roles to the table:Anonymous: For non-registered visitors.
Registered: For registered visitors.
Admin: For super users.
1
2
3
INSERT INTO roles (id, role) VALUES (1, 'Anonymous');
INSERT INTO roles (id, role) VALUES (2, 'Registered');
INSERT INTO roles (id, role) VALUES (3, 'Admin');
Table acl
To store all the controllers/actions. Each row means a different action that can be performed by the application.
1
2
3
4
5
6
7
8
CREATE TABLE `acl` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `controller` varchar(100) NOT NULL,
  `action` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `controller` (`controller`,`action`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
  CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
Table acl_to_roles
Establish the relation between the roles and actions. In other words: Which actions can perform each role/group.
1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE `acl_to_roles` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `acl_id` int(10) NOT NULL,
  `role_id` tinyint(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `acl_id` (`acl_id`),
  KEY `role_id` (`role_id`),
  CONSTRAINT `acl_to_roles_ibfk_1` FOREIGN KEY (`acl_id`)
     REFERENCES `acl` (`id`) ON DELETE CASCADE,
  CONSTRAINT `acl_to_roles_ibfk_2` FOREIGN KEY (`role_id`)
     REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Table users
It contains the field role_id, which establish the privileges that each user will inherit from the roles, and the general information about the users: login, password, ETC.
1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` tinyint(1) DEFAULT '1',
  `login` varchar(50) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  `salt` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `login_index` (`login`),
  KEY `password_index` (`password`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
  CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;

CREATE THE ACL PLUGIN

Now we need to create the ACL plugin. It will be located in the following path within our library folder: “/library/MyProject/Controller/Plugin/Acl.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
class MyProject_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $auth = Zend_Auth::getInstance();
        //var_dump($auth->getIdentity());
        $authModel=new Application_Model_Auth();
        if (!$auth->hasIdentity()){
            //If user doesn't exist it will get the Guest account from "users" table Id=1
            $authModel->authenticate(array('login'=>'Guest','password'=>'shocks'));
        }
        $request=$this->getRequest();
        $aclResource=new Application_Model_AclResource();
        //Check if the request is valid and controller an action exists. If not redirects to an error page.
        if( !$aclResource->resourceValid($request)){
            $request->setControllerName('error');
            $request->setActionName('error');
            return;
        }
        $controller = $request->getControllerName();
        $action = $request->getActionName();
        //Check if the requested resource exists in database. If not it will add it
        if( !$aclResource->resourceExists($controller, $action)){
            $aclResource->createResource($controller,$action);
        }
        //Get role_id
        $role_id=$auth->getIdentity()->role_id;
        $role=Application_Model_Role::getById($role_id);
        $role=$role[0]->role;
        // setup acl
        $acl = new Zend_Acl();
        // add the role
        $acl->addRole(new Zend_Acl_Role($role));
        if($role_id==3){//If role_id=3 "Admin" don't need to create the resources
            $acl->allow($role);
        }else{
            //Create all the existing resources
            $resources=$aclResource->getAllResources(); 
            // Add the existing resources to ACL
            foreach($resources as $resource){
                $acl->add(new Zend_Acl_Resource($resource->getController()));
                     
            }      
            //Create user AllowedResources
            $userAllowedResources=$aclResource->getCurrentRoleAllowedResources($role_id);               
             
            // Add the user permissions to ACL
            foreach($userAllowedResources as $controllerName =>$allowedActions){
                $arrayAllowedActions=array();
                foreach($allowedActions as $allowedAction){
                    $arrayAllowedActions[]=$allowedAction;
                }
                $acl->allow($role, $controllerName,$arrayAllowedActions);
            }
        }
        //Check if user is allowed to acces the url and redirect if needed
        if(!$acl->isAllowed($role,$controller,$action)){
            $request->setControllerName('error');
            $request->setActionName('access-denied');
            return;
        }
    }
}

Tuesday, December 3, 2013

how does integrate paypal ipn class example using php[Solved]

Hello Guy i have integrated in my application "paypal ipn" you can find out the way how to integrate to your application 
i think you can do, hope help you :)
<?php
class paypal_ipn_handler {

   var $last_error;                 // holds the last error encountered
   var $ipn_log;                    // bool: log IPN results to text file?
   var $ipn_log_file;               // filename of the IPN log
   var $ipn_response;               // holds the IPN response from paypal
   var $ipn_data = array();         // array contains the POST values for IPN
   var $fields = array();           // array holds the fields to submit to paypal
   var $sandbox_mode = false;

   function paypal_ipn_handler()
    {
        $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
       $this->last_error = '';
       $this->ipn_log_file = WP_ESTORE_PATH.'ipn_handle_debug.log';
       $this->ipn_response = '';
    }
 
 
  function formatMoney($number, $fractional=false)
     { 
  if ($fractional) { 
   $number = sprintf('%.2f', $number); 
  } 
  while (true) { 
   $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number); 
   if ($replaced != $number) { 
    $number = $replaced; 
   } else { 
    break; 
   } 
  } 
  return $number; 
 } 
   function validate_ipn()
    {
      // parse the paypal URL
      $url_parsed=parse_url($this->paypal_url);

      // generate the post string from the _POST vars aswell as load the _POST vars into an arry
      $post_string = '';
      foreach ($_POST as $field=>$value) {
         $this->ipn_data["$field"] = $value;
         $post_string .= $field.'='.urlencode(stripslashes($value)).'&';
      }

      $this->post_string = $post_string;
      $this->debug_log('Post string : '. $this->post_string,true);

      $post_string.="cmd=_notify-validate"; // append ipn command

      // open the connection to paypal
      if($this->sandbox_mode){//connect to PayPal sandbox
       $uri = 'ssl://'.$url_parsed['host'];
       $port = '443';          
       $fp = fsockopen($uri,$port,$err_num,$err_str,30);
      }
      else{//connect to live PayPal site using standard approach
       $fp = fsockopen($url_parsed['host'],"80",$err_num,$err_str,30);
      }
      
      if(!$fp)
      {
         // could not open the connection.  If loggin is on, the error message
         // will be in the log.
         $this->debug_log('Connection to '.$url_parsed['host']." failed. fsockopen error no. $errnum: $errstr",false);
         return false;

      }
      else
      {
         // Post the data back to paypal
         fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n");
         fputs($fp, "Host: $url_parsed[host]\r\n");
         fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
         fputs($fp, "Content-length: ".strlen($post_string)."\r\n");
         fputs($fp, "Connection: close\r\n\r\n");
         fputs($fp, $post_string . "\r\n\r\n");

         // loop through the response from the server and append to variable
         while(!feof($fp)) {
            $this->ipn_response .= fgets($fp, 1024);
         }

         fclose($fp); // close connection

         $this->debug_log('Connection to '.$url_parsed['host'].' successfuly completed.',true);
      }

      if (eregi("VERIFIED",$this->ipn_response))
      {
         // Valid IPN transaction.
         $this->debug_log('IPN successfully verified.',true);
         return true;

      }
      else
      {
         // Invalid IPN transaction.  Check the log for details.
         $this->debug_log('IPN validation failed.',false);
         return false;
      }
   }
   
     function validate_and_dispatch_product()
    {
 
   
 
   //do print your paypal ipn_data array
   $this->debug_log(print_r($this->ipn_data),true);
 

   
           
     return true;
    }

  function debug_log($message,$success,$end=false)
    {
      if (!$this->ipn_log) return;  // is logging turned off?

      // Timestamp
      $text = '['.date('m/d/Y g:i A').'] - '.(($success)?'SUCCESS :':'FAILURE :').$message. "\n";

      if ($end) {
       $text .= "\n------------------------------------------------------------------\n\n";
      }
      // Write to log
      $fp=fopen($this->ipn_log_file,'a');
      fwrite($fp, $text );
      fclose($fp);
   }
   
   
    
}

// Start of IPN handling (script execution)
$ipn_handler_instance = new paypal_ipn_handler();

if ($ipn_handler_instance->validate_ipn())
{
 $ipn_handler_instance->debug_log('Creating product Information to send.',true);

      if(!$ipn_handler_instance->validate_and_dispatch_product())
      {
          $ipn_handler_instance->debug_log('IPN product validation failed.',false);
      } 
}

How to select database in command line?

How to select database in command line?
USE DATABASE_NAME
mysq> use tesing

How to show table engine in mysql command line ?

SHOW TABLE STATUS WHERE Name = 'table_name'

why use magic method __toString() if php return varibale data type?

here is the error message ... must return a string value ... just means the return value of __toString() has to be a value of data type string. If $users_class in your example is not intended to be a string value, it has be to converted to a string before returning it.
But when reading the above example, it seems to me that the var $users_class may just not have been initialized yet. In this case change the method __toString() to :
public function __toString() {
    if(is_null($this->users_class)) {
        return 'NULL';
    }
    return $this->user_class;
}
To make the above code working, you'll need to make a change in the smarty code too. Remove the double quotes around the value of the value= attribute.

Saturday, November 30, 2013

Creating Wildcard Sub Domain Using Apache VirtualHost for php

You can't make dynamic subdomains with .htacces
You will need to configure the apache virtual host to accept requests for multiple domains
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com *.example.com
    DocumentRoot /www/domain
</VirtualHost>
Adding the wildcard subdomain *.example.com, your PHP application will receive
all requests for any
domain below example.com, ie garbage.example.combusted.example.com,
llama.example.com, etc.
At this point, your application will have to determine the validity of the subdomain and
display the appropriate error for unknown subs.
From there, parse the domain for mike.


2down voteaccepted
Wildcard sub-domains are definitely possible using Apache virtual hosts.
I had basically the same requirements and managed to get it working with Apache's mod_vhost_alias.somodule. Try this in your http-vhosts.conf file:
DocumentRoot "/home/admin1/public_html/userweb/" 
<Directory "/home/admin1/public_html/userweb/"> 
    Options None 
    AllowOverride None 
    Order allow,deny 
    Allow from all 
</Directory>

<VirtualHost *:80>
    DocumentRoot /home/admin1/public_html/
    ServerName www.example.com
</VirtualHost>

<VirtualHost *:80> 
    VirtualDocumentRoot /home/admin1/public_html/userweb/%1.example.com/ 
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /home/admin1/public_html/
    ServerName example.com
</VirtualHost>
Note that I haven't tested this, but it's pretty close to the solution that worked for me.

Friday, November 29, 2013

how to include view within view in zendframe work?[Solved]

Here is the example : hope help you guys :)
<?php echo $this->render('login/index.phtml'); ?>

how to send value to view page in zendframe work?[Solved]

Simple its using zend framework assign reference function to view page


within controller  function pass value to view page
you can two way to pass value to view page
one is : $this->request=150
Or
$value=150;
$this->view->assign('request',$value);
--------------------------------------------------------------
Get variable value within  view page
like
echo $this->request;

Thursday, November 28, 2013

how to configure NETBean IDE for PHP

Hello Guys tricky for debugging PHP.ini . easy to debug and help it sure.
  1. First download the NetBean IDE HERE  then install in your system
  2. then some change configure  in PHP.INI file
  3. Find and  remove  the line zend_extension = "XAMPP_HOME\php\ext\php_xdebug.dll".
  4. Find and  remove ; the line xdebug.remote_host=localhost. Change the value of the setting from localhost to 127.0.0.1.
  5. Find and  remove ; the line xdebug.remote_enable = 0. Change 0 to 1.
  6. Find and  remove ; the line xdebug.remote_handler = "dbgp".
  7. Find and remove ; the line xdebug.remote_port = 9000.
  8. Find and remove ; the line xdebug.show_local_vars = 1 
  9. Save php.ini.
  10. Run the XAMPP Control Panel Application and restart the Apache server.

Wednesday, November 27, 2013

how do i set checkbox value in zend framework form [Solved]

Hello guy you can set your form checkbox default value in zend framework
$checkbox=new Zend_Form_Element_Checkbox('remember');
 $checkbox->setChecked(true)->setuncheckedValue(0);