Sunday, May 20, 2012

Upload file to server using ajax and php

Include jquery.form.js and jquery.min.js

<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>

jQuery("#contact-form").ajaxForm({
    beforeSubmit: function() {
        jQuery.showBackgroundWorkingState();
    },
    success: function(data) {
        /*console.log(data);*/
        try {
            if(data == CONSTANT_JS_SUCCESS_CODE) {

            } else {
                jQuery.showWarning("Error uploading file, please try again later.");       
            }
        } catch ( ex ) {
            jQuery.showWarning("Error uploading file, please try again later.");
        }
        jQuery.hideBackgroundWorkingState();
    },
    error: function() {
        jQuery.showWarning("Error uploading file, please try again later.");
        jQuery.hideBackgroundWorkingState();
    }
}).submit(); 
 
File save using php script:

<?php
$name = $_FILES['photoimg']['name'];
list($txt, $ext) = explode(".", $name);
$tmp = $_FILES['photoimg']['tmp_name'];
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/";
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $imageLocation.$actual_image_name)) {
    die("1");
}
die("0"); 
?>

Image crop using jquery and php

Download jquery plugin from: http://code.google.com/p/jcrop/

create a folder named: crop

create a folder named: css

create a folder named: img

create a folder named: js

move Jcrop.jpg and jquery.Jcrop.min.css to /css folder

move jquery.color.js, jquery.Jcrop.js and jquery.min.js to /js folder

place a image named pool.jpg to /img folder

create a file index.php:

<?php
<link rel="stylesheet" type="text/css" href="/css/jquery.Jcrop.min.css" /> 
<script type="text/javascript" src="/js/jquery.color.js"></script> 
<script type="text/javascript" src="/js/jquery.Jcrop.js"></script>

?>
<img src="/img/pool.jpg" id="cropbox" alt="Flowers" />
<script type="text/javascript">

    jQuery(function($){
        jQuery('#cropbox').Jcrop({
            onChange: showCoords,
            onSelect: showCoords
        });
        function showCoords(c)
        {
            jQuery('#x1').val(c.x);
            jQuery('#y1').val(c.y);
            jQuery('#x2').val(c.x2);
            jQuery('#y2').val(c.y2);
            jQuery('#w').val(c.w);
            jQuery('#h').val(c.h);
        };
        $("#imageResizeValirables").submit(function() {
            var formData = $(this).serialize();
            $.post('/action.php', formData, function(returnData) {
                if(returnData == 'success') {
                    $("#croppedImage").attr("src", "/crop/"+$("#beCroppedImage").attr("value") + "?" + new Date().getTime());
                } else {
                    alert("Try again please.");
                }
            });
        });
    });

</script>

<form onsubmit="return false;" id="imageResizeValirables" class="coords">
    <input type="hidden" id="beCroppedImage" name="img" value="pool.jpg">
    <input type="hidden" size="4" id="x1" name="x1" />
    <input type="hidden" size="4" id="y1" name="y1" />
    <input type="hidden" size="4" id="x2" name="x2" />
    <input type="hidden" size="4" id="y2" name="y2" />
    <input type="hidden" size="4" id="w" name="w" />
    <input type="hidden" size="4" id="h" name="h" />
    <input type="submit" value="Resize">
</form>
<img id="croppedImage" alt='' />

create another file action.php

$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/" . $_POST["img"];
$newImageLocation = $docRoot . "/app/webroot/crop/" . $_POST["img"];
 if (file_exists($imageLocation)) {
     list($current_width, $current_height) = getimagesize($imageLocation);
     $x1 = (int) $_POST['x1'];
     $y1 = (int) $_POST['y1'];
     $x2 = (int) $_POST['x2'];
     $y2 = (int) $_POST['y2'];
     $w = (int) $_POST['w'];
     $h = (int) $_POST['h'];

      $crop_width = $w;
      $crop_height = $h;
      $new = imagecreatetruecolor($crop_width, $crop_height);
      $current_image = imagecreatefromjpeg($imageLocation);
      imagecopyresampled($new, $current_image, 0, 0, $x1, $y1, $crop_width, $crop_height, $w, $h);
      imagejpeg($new, $newImageLocation, 100);
      echo "success";
      exit;
 }
 echo "fail";
 exit;

Wednesday, May 16, 2012

Upload Video To Youtube Using Php Script

DOWNLOAD ZEND DATA FROM:
http://framework.zend.com/download/gdata
OR
https://www.box.com/s/e28da8suyty2nc3jtm72
OR
https://docs.google.com/file/d/0B5nZNPW48dpFMTJPMks3WWZtd0E/edit?usp=sharing

set that root folder in project

index.php:

<?php
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();

Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

session_start();
/* your next url */
$next = 'http://localhost/phpYouTube/welcome.php';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
$returnData = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
header("Location: ".$returnData);
?>


welcome.php

<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
        $username = 'name@gmail.com',
        $password = 'password',
        $service = 'youtube',
        $client = null,
        $source = 'MySource', // a short string identifying your application
        $loginToken = null,
        $loginCaptcha = null,
        $authenticationURL);

$developerKey = 'DEVELOPER KEY'; /* https://code.google.com/apis/youtube/dashboard */
$applicationId = 'Video uploader v1';
$clientId = 'My video upload client - v1';

$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource('C:\Users\Public\Videos\Sample Videos\\Wildlife.wmv');
$filesource->setContentType('video/quicktime');
$filesource->setSlug('Wildlife.wmv');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
// The category must be a valid YouTube category!
$myVideoEntry->setVideoCategory('Autos');
// Set keywords. Please note that this must be a comma-separated string
// and that individual keywords cannot contain whitespace
$myVideoEntry->SetVideoTags('personal');
// set some developer tags -- this is optional
// (see Searching by Developer Tags for more details)
$myVideoEntry->setVideoDeveloperTags(array('mydevtag', 'anotherdevtag'));

// upload URI for the currently authenticated user
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
// try to upload the video, catching a Zend_Gdata_App_HttpException,
// if available, or just a regular Zend_Gdata_App_Exception otherwise
try {
    $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
    echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
    echo $e->getMessage();
}
}
?>

Direct post integration eway

Create a eWay account. go: http://www.eway.com.au/developers/partners/become-a-partner.html

Post data as:

<form action="https://www.eway.com.au/gateway/payment.asp" method="post" name="formEWay">
<input type="hidden" name="ewayCustomerID" value=""/>
<input type="hidden" name="ewayTotalAmount" value=""/>
<input type="hidden" name="ewayCustomerFirstName" value=""/>
<input type="hidden" name="ewayCustomerLastName" value=""/>
<input type="hidden" name="ewayCustomerEmail" value=""/>
<input type="hidden" name="ewayCustomerAddress" value=""/>
<input type="hidden" name="ewayCustomerPostcode" value=""/>
<input type="hidden" name="ewayCustomerInvoiceDescription" value="Purchase Order - 10"/>
<input type="hidden" name="ewayCustomerInvoiceRef" value=""/>
<input type="hidden" name="eWAYURL" value="http://dom.com/ewayreturn.php"/>
<input type="hidden" name="eWAYSiteTitle" value="<?php echo $_SERVER["SERVER_NAME"] ?>"/>
<input type="hidden" name="eWAYAutoRedirect" value="1"/>
<input type="hidden" name="eWAYTrxnNumber" value=""/>
<input type="submit" value="Process Secure Credit Card Transaction using eWay"/>
</form>

After return from eway, try the following.
if(isset($_POST['ewayTrxnReference']) && isset($_POST['ewayTrxnStatus']) && isset($_POST['ewayTrxnNumber'])) {
    $orderStatus = "Open";
    $pGateResult = "false";
    $txn_id = $_POST['ewayTrxnReference'];
    $result = $_POST['ewayTrxnStatus'];
    $order_number = $_POST['ewayTrxnNumber'];
    $returnAmount = 0;
    if(isset($_POST["eWAYReturnAmount"])) {
        $returnAmount = $this->getValueReturnedFromeWay($_POST["eWAYReturnAmount"]);
    }
    if (!empty($result) && strcmp('True', trim($result)) == 0) {
         $pGateResult = "true";
         $orderStatus = "Paid";
    }
}

Paypal direct post integration

  1. Create a paypal account(test sandbox)
  2. if test mode use: <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" name="formPayPal">
  3. live mode use: <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="formPayPal">
 <input type="hidden" name="cmd" value="_xclick"/>
    <input type="hidden" name="business" value="PAYPAL_ID"/>
    <input type="hidden" name="currency_code" value="$"/>
    <input type="hidden" name="item_name" value="Payment for Order100"/>
    <input type="hidden" name="item_number" value="100"/>
    <input type="hidden" name="amount" value="100.50"/>
    <input type="hidden" name="zip" value="2102"/>
    <input type="hidden" name="night_phone_a" value=""/>
    <input type="hidden" name="day_phone_a" value=""/>
    <input type="hidden" name="return" value="http://dom.com/paypalreturn.php"/>
    <input type="hidden" name="notify_url" value="http://dom.com/paypalreturn.php"/>

In paypalreturn.php file write the following to retreieve paypal info. 
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
       $value = urlencode(stripslashes($value));
       $req .= "&$key=$value";
}
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
if(GATEWAY_TESTING == 1) {
       $fp = fsockopen ('www.sandbox.paypal.com', 443, $errno, $errstr, 30);
} else {
       $fp = fsockopen ('www.paypal.com', 443, $errno, $errstr, 30);
}
 if (!$fp) {
      $pGateResponseText = "HTTP ERROR: fail connect to PayPal!!!";
       return;
 } else{
       fputs ($fp, $header . $req);
        while (!feof($fp)) {
                    $res = fgets ($fp, 1024);
                    if ((strcmp ($res, "VERIFIED") == 0) || GATEWAY_TESTING === 1) {
                        $item_name = $_POST['item_name'];
                        $item_number = $_POST['item_number'];
                        $payment_status = trim($_POST['payment_status']);
                        $payment_amount = $_POST['mc_gross'];
                        $payment_currency = $_POST['mc_currency'];
                        $txn_id = $_POST['txn_id'];
                        $receiver_email = $_POST['receiver_email'];
                        $payer_email = $_POST['payer_email'];
                        $order_number = $item_number; 
               }
        }
}




Tuesday, May 15, 2012

Execute Curl to GET POST PUT PATCH DELETE Method Using Php

$headers[] = "Authorization: Basic xxx";
$headers[] = "Accept: text/xml";

$post = array(
    "name" => "Some name",
    "roll" => "Some roll"

);

$result = CurlExecutor::execute("...com/api/test", "POST", $post, null, $headers);
CurlExecutor::prettyPrint($result);


<?php
class CurlExecutor
{
    static function execute($url, $method = "GET", $posts = null, $gets = null, $headers = null, Closure $closure = null)
    {
        $ch = curl_init();
        if ($gets != null) {
            $url .= "?" . (is_array($gets) ? self::makeRawQuery($gets) : $gets);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($posts != null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($posts) ? self::makeRawQuery($posts) : $posts);
        }
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, true);
        } else if ($method == "HEAD") {
            curl_setopt($ch, CURLOPT_NOBODY, true);
        } else if ($method == "PUT" || $method == "BATCH" || $method == "DELETE") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        if (!is_null($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if (!is_null($closure)) {
            $closure($ch);
        }
        $response = curl_exec($ch);
        if ((curl_errno($ch) == 60)) {
            /* Invalid or no certificate authority found - Retrying without ssl */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
        }
        /* If you want to retry on failed status code */
        $retryCodes = array('401', '403', '404');
        $retries = 0;
        $retryCount = 3;
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (in_array($httpStatus, $retryCodes)) {
            do {
                $response = curl_exec($ch);
                $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            } while (in_array($httpStatus, $retryCodes) && (++$retries < $retryCount));
        }
        if (curl_errno($ch)) {
            $response = curl_error($ch);
        }
        curl_close($ch);
        return array(
            "code" => $httpStatus,
            "response" => $response
        );
    }

    static function makeRawQuery($data, $keyPrefix = "")
    {
        $query = "";
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (strlen($keyPrefix) > 0) {
                    $keyPrefixDummy = $keyPrefix . "[" . $key . "]";
                } else {
                    $keyPrefixDummy = $key;
                }
                $query = $query . self::makeRawQuery($value, $keyPrefixDummy);
            } else {
                if (strlen($keyPrefix) > 0) {
                    $key = $keyPrefix . "[" . $key . "]";
                }
                $query .= $key . "=" . rawurlencode($value) . "&";
            }
        }
        return rtrim($query, "&");
    }

    static function prettyPrint($o)
    {
        echo "<pre>";
        print_r($o);
        echo "</pre>";
    }
}

Create a facebook apps and page tab

go to facebook developers area for apps: https://developers.facebook.com/apps
create a app.
set app display name
set app namespace
click tab app on facebook, give a url to view the page under apps home page, as iframe
select page tab and give your site url to visit from facebook apps as facebook iframe
get app id and secret from the app page
done,

Configuring a Page Tab

In order to enable this feature, you need to specify a Page Tab Name and a Page Tab URL (much like you provided a Canvas Page and Canvas URL previously) that is loaded when the user selects your Tab on a given Facebook Page. You must also specify aSecure Page Tab URL which is the HTTPS address of your content. Users browsing Facebook who have HTTPS enabled will be unable to use your tab if this URL is empty. Note that SSL support for your page tab app has been mandatory since October 1, 2011.
You can find these settings in the "Basic" section of your app's settings in the Developer App under 'Select how your app integrates with Facebook'. Click 'Page Tab' to expand the Page Tab settings, and the Page Tab fields will appear

Page Tab Width

The amount of space available to your tab app is bounded by the outer context of Facebook. It may be configured to display with a width of 520 pixels (default) or 810 pixels.

Adding an App to a Page

As a Page Tab App developer, you can prompt users to install your Page Tab App by including an "Install this Page Tab App" link that explicitly directs the user to the /dialog/pagetab endpoint, either within your Page Tab App or Website:
https://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL
where YOUR_APP_ID and YOUR_URL can be found in your app settings.
This URL brings up the Add to Page Dialog:


Integrating with Facebook APIs

When a user navigates to the Facebook Page, they will see your Page Tab added in the next available tab position. Broadly, a Page Tab is loaded in exactly the same way as a Canvas Page. Read more about this in the Canvas Tutorial. When a user selects your Page Tab, you will receive the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.
In addition, your app will also receive a string parameter called app_data as part of signed_request if an app_data parameter was set in the original query string in the URL your tab is loaded on. It could look like this: "https://www.facebook.com/YourPage?v=app_1234567890&app_data=any_string_here". You can use that to customize the content you render if you control the generation of the link.

Integrate facebook apps with facebook pages

At first download facebook sdk for php from here:
https://docs.google.com/file/d/0B5nZNPW48dpFbjZiSHNybEh0czg/edit?usp=sharing



App id and secret code goes here as 
$this->facebookObject = new Facebook(array(
            'appId' => $this->appId,
            'secret' => $this->secret,
        ));
this will return facebook object.

To get signed request by pages,
$this->signedRequest = $this->facebookObject->getSignedRequest();

If signed request dont come from a page you can die immediately
if (!isset($this->signedRequest["page"]["id"])) {
                die();
            }
 Get facebook user id if need
$this->facebookUser = $this->facebookObject->getUser();

If user is not logged in then retrieve login url
$loginMainUrl = $this->facebookObject->getLoginUrl();

** retrieve login return url 
$loginReturnUrl = $this->getLoginReturnUrl($this->signedRequest["page"]["id"]);
            $loginReturnUrl = urlencode($loginReturnUrl."?sk=app_".$this->appId);

            $loginMainUrls = explode("&", urldecode($loginMainUrl));
            $loginMainUrlNew = "";
            foreach($loginMainUrls as $temp) {
                if($loginMainUrlNew != "") {
                    $loginMainUrlNew .= "&";
                }
                if(substr($temp, 0, 12) == "redirect_uri") {
                    $loginMainUrlNew .= "redirect_uri=".$loginReturnUrl;
                } else {
                    $loginMainUrlNew .= ($temp);
                }
            }
<a target="_parent" href="<?php echo $loginMainUrlNew; ?>"><img src="<?php echo Router::url('/', true); ?>img/fb_login.jpg" alt="Login With Facebook"></a>

Get facebook pages link by implementing this function:
function getLoginReturnUrl($pageId) {
$url="https://graph.facebook.com/".$pageId;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
        $content = curl_exec($ch);
        $content = json_decode($content);
        if(isset($content->link) && strlen($content->link) > 0) {
            return $content->link;
        }
      return "";
}


When anyone add this apps to his/her page then do the following:
 foreach($_GET as $key=>$value) {
            if($key == "tabs_added") {
                if(count($value) > 0) {
                    foreach($value as $key2=>$value2) {
                        if($key2 != null && strlen($key2) > 0) {
                            $url = $this->getLoginReturnUrl($key2)."?sk=app_".$this->appId;
                            if($url != null && substr($url, 0, 4) == "http") {
                                header("Location: ".$url);
                            }
                        }
                    }
                }
            }
        }
this will redirect you to proper application page under the page which you add add this apps.

Add this html to your page to make user to add the apps to there pages

 <?php
$urlToAddThisApp = "http://www.facebook.com/dialog/pagetab?app_id=".Configure::read("facebookAppId")."&next=".urlencode(Router::url("/", true)."apps/facebook/thank_you");
$urlToAddThisApp .= "&skip_api_login=1&display=popup";
$urlToAddThisApp .= "&cancel_url=".urlencode(Router::url("/", true)."apps/facebook/cancel");
?>
<div>
    <a href="javascript:void(0);" onclick="open_win();">Add this app</a>
</div>
<script>
    function open_win() {
        var width = 500;
        var height = 350;
        var left = (screen.width/2)-(width/2);
        var top = 50;
        myWindow=window.open('<?php echo $urlToAddThisApp; ?>','','width='+width+', height='+height+', top='+top+', left='+left);
        myWindow.focus();
    }
</script>