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);
      } 
}