<?php

    /**
     * This example demonstrates how to use xauth method to upload data to yfrog
     * Usage: upload-to-yfrog-example-with-xauth.php <FILENAME-TO-UPLOAD>
     */

    // TODO: PUT YOUR KEYS HERE

    // your app's OAuth consumer & secret
    define('OAUTH_CONSUMER_KEY', '');
    define('OAUTH_CONSUMER_SECRET', '');

    // your app user's token and secret, when twitter user granted access to your app
    define('OAUTH_TOKEN_KEY', '');
    define('OAUTH_TOKEN_SECRET', '');

    // END OF TODO

    // you can grab required file here:
    // http://github.com/abraham/twitteroauth
    require_once('OAuth.php');

    // instantiating OAuth customer 
    $consumer = new OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
    // instantiating signer
    $sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
    // user's token
    $token = new OAuthConsumer(OAUTH_TOKEN_KEY, OAUTH_TOKEN_SECRET);

    // sorry, guys, I'm too lazy to generate all parameters by myself so I'll parse URL that OAuth lib will construct for me :)
    // signing URL
    $url = 'https://api.twitter.com/1/account/verify_credentials.xml';
    $request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $url, array());
    $request->sign_request($sha1_method, $consumer, $token);
    $url = $request->to_url();
    $query = parse_url($url, PHP_URL_QUERY);
    parse_str($query, $args);

    // OK, we have all data needed in $args

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://yfrog.com/api/xauth_upload');

    // adding required headers, note: urlencode is important!
    $headers = array
    (
        "X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.xml",
        "X-Verify-Credentials-Authorization: " . 
        "oauth_consumer_key=\"" . urlencode($args['oauth_consumer_key']) . "\", " .
        "oauth_nonce=\"" . urlencode($args['oauth_nonce']) . "\"," . 
        "oauth_signature=\"" . urlencode($args['oauth_signature']) . "\"," . 
        "oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" . $args['oauth_timestamp'] . "\"," . 
        "oauth_token=\"" . urlencode($args['oauth_token']) . "\"," . 
        "oauth_version=\"1.0\""
    );

    $post = array
    (
        'media' => '@' . $argv[1], // filename
    );

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $response = curl_exec($ch);
    curl_close ($ch);

    echo $response;

?>