Monday, November 14, 2016

PHP- function to correct all the images orientation in a given path or directory

<?php
/*
This function correct all the images orientation in a given path or directory.

Run:    php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/test1');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test');"
*/
function correctImageOrientation($directory) {
   
    ini_set('memory_limit','2048M');
   
    $scanned_directory = array_diff(scandir($directory), array('..', '.'));
    echo "<pre>";
    print_r("scanned directory: \r\n");
    print_r($scanned_directory);
    echo "</pre>\r\n";
    foreach ($scanned_directory as &$file) {

        if (is_dir($directory."/".$file)) {
            correctImageOrientation($directory."/".$file);
        } else {                                   
            $filen = explode(".", $file);
            $ext = end($filen);
            try {

                $exif = @exif_read_data($directory."/".$file);

                $orientation = $exif['Orientation'];

                if (isset($orientation) && $orientation != 1){
                    switch ($orientation) {
                        case 3:
                        $deg = 180;
                        break;
                        case 6:
                        $deg = 270;
                        break;
                        case 8:
                        $deg = 90;
                        break;
                    }

                    if ($deg) {

                        // If png
                        if ($ext == "png") {
                            $img_new = imagecreatefrompng($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagepng($img_new,$directory.$file);
                        }else {
                            $img_new = imagecreatefromjpeg($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagejpeg($img_new,$directory."/".$file,80);
                        }
                    }
                    echo "<pre>";
                    print_r("image changed: \r\n");
                    print_r($directory."/".$file);
                    echo "</pre>\r\n";
                }

            } catch (Exception $e) {
                echo "error:";
                echo $e;
                echo "error";
            }
        }
    }
    unset($file);
}


correctImageOrientation('test/test1') ;
?>

Wednesday, August 17, 2016

Magento: Load record of my model by custom Field

Magento: Load record of my model by custom Field


$model = Mage::getModel('foo_bar/baz');
$model->load($id, 'field_name');

Wednesday, August 3, 2016

PHP- How to change the array key to start from 1 instead of 0 ?

how to change the array key to start from 1 instead of 0 ?

$newarr = array_combine(range(1, count($oldarr)), array_values($oldarr));

Wednesday, July 27, 2016

Magento: list all values of a single attribute

 $name='product_attribue_name';
    $attributeInfo =     Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem();
    $attributeId = $attributeInfo->getAttributeId();
    $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
    $attributeOptions = $attribute ->getSource()->getAllOptions(false);
    echo '<pre>'; print_r($attributeOptions);

Tuesday, July 26, 2016

Magento- get product collection by customer reviews

Magento- get product collection by customer reviews

<?php
$collection = Mage::getModel('review/review')
                ->getResourceCollection()
                ->addStoreFilter(Mage::app()->getStore()->getId())
                ->addFieldToSelect('*')
                ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
                ->addRateVotes();
$collection->getSelect()->group('entity_pk_value');
               
//echo $collection->getSelect();

print_r($collection->getData());

?>

Tuesday, March 22, 2016

Wordpress- Create Database Tables When on plugin actication hook

//create table               
function creat_table_on_actvation() {
         global $wpdb;
        $your_table_name = $wpdb->prefix . 'custom_contact_us';
     
        $sql = "CREATE TABLE IF NOT EXISTS " . $your_table_name . " (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `contact_name` varchar(255) NOT NULL,
          `contact_email` varchar(255) NOT NULL,
          `contact_subject` varchar(255) NOT NULL,
          `contact_message` text NOT NULL,
          `status` int(11) NOT NULL,
          `date_time` datetime NOT NULL,
          PRIMARY KEY (`id`)
        )";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'creat_table_on_actvation');

PayPal - Adaptive Chained Payments

<?php

class PaypalTest {

public $api_user = "XXXXXXXXXXXXXXXXXXXXXX";
public $api_pass = "XXXXXXXXXXXXXXXXX";
public $api_sig = "XXXXXXXXXXXXXXXXXXXXXXX";
public $app_id = "APP-80W284485P519543T";
public $apiUrl = 'https://svcs.sandbox.paypal.com/AdaptivePayments/';
//public $paypalUrl="https://www.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $paypalUrl="https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $headers;

public function __construct(){
    $this->headers = array(
        "X-PAYPAL-SECURITY-USERID: ".$this->api_user,
        "X-PAYPAL-SECURITY-PASSWORD: ".$this->api_pass,
        "X-PAYPAL-SECURITY-SIGNATURE: ".$this->api_sig,
        "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
        "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
        "X-PAYPAL-APPLICATION-ID: ".$this->app_id,
    );
  
    $this->envelope= array(
            "errorLanguage" => "en_US",
            "detailLevel" => "ReturnAll",
        );
  
  
}

public function getPaymentOptions($paykey){

//echo $paykey; die;
   $packet = array(
          "requestEnvelope" => $this->envelope ,
          "payKey" => $paykey
   );
 
   return $this->_paypalSend( $packet ,'GetPaymentOptions');
}

public function _paypalSend($data,$call){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->apiUrl.$call);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
    $response = json_decode(curl_exec($ch),true);
    return $response;

}

public function splitPay(){


    // create the pay request
    $createPacket = array(
        "actionType" =>"PAY_PRIMARY",
        "applicationId" =>"APP-80W284485P519543T",
        "currencyCode" => "USD",
        "receiverList" => array(
            "receiver" => array(
               array(
                    "amount"=> "7.00",
                    "primary" => true,
                    "email"=>"primary-reciever@gmail.com"
                ),
                array(
                    "amount"=> "3.00",
                    "primary" => false,
                    "email"=>"secondary-reciever@gmail.com"
                ),
            ),
        ),
        "returnUrl" => "http://your-site-url/confirm.php",
        "cancelUrl" => "http://your-site-url//cancel.php",
        "requestEnvelope" => $this->envelope
    );

    $response = $this->_paypalSend($createPacket,"Pay");
  
  
    
    $paykey =  $response['payKey'];
    //echo '9999<pre>'; print_r($response);
  
    //SET payment details
  
     $detailsPacket=array(
"requestEnvelope" =>$this->envelope,
"payKey" => $paykey,
"receiverOptions" => array(
    array(
    "receiver" => array("email" => "primary-reciever@gmail.com"),
            "invoiceData" => array(
                "item" => array(
                    array(
                        "name" => "product1",
                        "price" => "7.00",
                        "identifier" => "p1"
                    ),
                   )
            )
    ),
    array(
        "receiver" => array("email" => 'secondary-reciever@gmail.com'),
        "invoiceData" => array(
        "item" => array(
            array(
                "name" => "product1",
                "price" => "3.00",
                "identifier" => "p1"
            ),
        )
      )
    ),
)
);


    $response1 = $this->_paypalSend($detailsPacket,"SetPaymentOptions");
  
  
    //$dets= $this->getPaymentOptions($paykey);
    $dets= $this->getPaymentOptions($paykey);
  
  

    $msg = $paykey;
  
    mail("amu02.aftab@gmail.com","My subject",$msg);
    //echo $this->paypalUrl.$paykey; die;
    header("Location: ".$this->paypalUrl.$paykey);
}

    public function _paymentExecute($url, $data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        $response = json_decode(curl_exec($ch),true);
        return $response;
    }

}


if($_GET['exe_pay'] == 1){
  
    $url = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
  
    $payment = new PaypalTest();
    
    $packet = array(
          "requestEnvelope" => $payment->envelope,
          "payKey" => "AP-96831732KV5898725"
   );
    $response = $payment->_paymentExecute($url, $packet);
    echo '<pre>';print_r($response);
}elseif($_GET['get_info'] == 1){
    $url = "https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails";
  
    $payment = new PaypalTest();
  
    $packet = array(
          "requestEnvelope" => $payment->envelope,
          "payKey" => "AP-96831732KV5898725"
   );
    $response = $payment->_paymentExecute($url, $packet);
    echo '<pre>';print_r($response);
}else{
      
      
    $payment = new PaypalTest();
    $payment->splitPay();
  
}?>

PayPal - Adaptive parallel Payments

<?php
class PaypalTest {

public $api_user = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public $api_pass = "XXXXXXXXXXXXXXXXXXXX";
public $api_sig = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public $app_id = "APP-80W284485P519543T";
public $apiUrl = 'https://svcs.sandbox.paypal.com/AdaptivePayments/';
//public $paypalUrl="https://www.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $paypalUrl="https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $headers;

public function __construct(){
    $this->headers = array(
        "X-PAYPAL-SECURITY-USERID: ".$this->api_user,
        "X-PAYPAL-SECURITY-PASSWORD: ".$this->api_pass,
        "X-PAYPAL-SECURITY-SIGNATURE: ".$this->api_sig,
        "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
        "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
        "X-PAYPAL-APPLICATION-ID: ".$this->app_id,
    );
    $this->envelope= array(
            "errorLanguage" => "en_US",
            "detailLevel" => "ReturnAll",
        );
}

public function getPaymentOptions($paykey){

   $packet = array(
          "requestEnvelope" => $this->envelope ,
          "payKey" => $paykey
   );
  
   return $this->_paypalSend( $packet ,'GetPaymentOptions');
}

public function _paypalSend($data,$call){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->apiUrl.$call);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
    $response = json_decode(curl_exec($ch),true);
    return $response;

}
public function splitPay(){
    // create the pay request
    $createPacket = array(
        "actionType" =>"PAY",
        "currencyCode" => "USD",
        "receiverList" => array(
            "receiver" => array(
               array(
                    "amount"=> "2.00",
                    "email"=>"First Reciever Email"
                ),
                array(
                    "amount"=> "2.00",
                    "email"=>"Second Reciever Email"
                ),
            ),
        ),
        "returnUrl" => "http://your-site/confirm.php",
        "cancelUrl" => "http://your-site/cancel.php",
        "requestEnvelope" => $this->envelope
    );

    $response = $this->_paypalSend($createPacket,"Pay");
    $paykey =  $response['payKey'];
    //SET payment details
   
     $detailsPacket=array(
"requestEnvelope" =>$this->envelope,
"payKey" => $paykey,
"receiverOptions" => array(
    array(
    "receiver" => array("email" => "First Reciever Email"),
            "invoiceData" => array(
                "item" => array(
                    array(
                        "name" => "product1",
                        "price" => "2.00",
                        "identifier" => "p1"
                    ),
                   )
            )
    ),
    array(
        "receiver" => array("email" => 'Second Reciever Email'),
        "invoiceData" => array(
        "item" => array(
            array(
                "name" => "product1",
                "price" => "2.00",
                "identifier" => "p1"
            ),
        )
      )
    ),
)
);


    $response = $this->_paypalSend($detailsPacket,"SetPaymentOptions");
    $dets= $this->getPaymentOptions($paykey);
   
   
      header("Location: ".$this->paypalUrl.$paykey);
}
}


$payment = new PaypalTest();
$payment->splitPay();

?>

Thursday, February 18, 2016

Wordpress-How many tables default WordPress have? Can you name those default WordPress table?

The default version of WordPress is incorporated with 11 tables. They are-
  • wp_options
  • wp_users
  • wp_links
  • wp_commentmeta
  • wp_term_relationships
  • wp_postmeta
  • wp_posts
  • wp_term_taxonomy
  • wp_usermeta
  • wp_terms
  • wp_comments

Tuesday, February 9, 2016

PHP - simple download script

   #setting headers
    header('Content-Description: File Transfer');
    header('Cache-Control: public');
    header('Content-Type: '.$type);
    header("Content-Transfer-Encoding: binary");
    header('Content-Disposition: attachment; filename='. basename($file));
    header('Content-Length: '.filesize($file));
    ob_clean(); #THIS!
    flush();
    readfile($file);

Friday, February 5, 2016

PHP- Get Address Using Co-ordinates(lat Long)

PHP- Get Address Using Co-ordinates(lat Long)



$geolocation = $latitudeFrom.','.$longitudeFrom;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false';
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
    $response = array();
    foreach($json_decode->results[0]->address_components as $addressComponet) {
        if(in_array('political', $addressComponet->types)) {
                $response[] = $addressComponet->long_name;
        }
    }

    if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
    if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; }
    if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
    if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
    if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }

    if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$fourth;
        echo "<br/>Country:: ".$fifth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$third;
        echo "<br/>Country:: ".$fourth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
        echo "<br/>City:: ".$first;
        echo "<br/>State:: ".$second;
        echo "<br/>Country:: ".$third;
    }
    else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>State:: ".$first;
        echo "<br/>Country:: ".$second;
    }
    else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>Country:: ".$first;
    }
  }