Showing posts with label curl. Show all posts
Showing posts with label curl. Show all posts

2 Legged OAuth in PHP


Google Apps Premier/Education administrators can take advantage of 2 legged OAuth to communicate with the Google Data APIs. This sample makes use of the PHP OAuth library from oauth.net.
<?php
require_once('OAuth.php');

// Establish an OAuth consumer based on our admin 'credentials'
$CONSUMER_KEY = 'yourdomain.com'; 
$CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'; 
$consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET, NULL);

// Setup OAuth request based our previous credentials and query
$user= 'any.user@yourdomain.com';
$base_feed = 'http://www.google.com/m8/feeds/contacts/default/full/';
$params = array('max-results' => 10, 'xoauth_requestor_id' => $user);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $base_feed, $params);

// Sign the constructed OAuth request using HMAC-SHA1
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);

// Make signed OAuth request to the Contacts API server
$url = $base_feed . '?' . implode_assoc('=', '&', $params);
echo send_request($request->get_normalized_http_method(), $url, $request->to_header());
 
/**
 * Makes an HTTP request to the specified URL
 * @param string $http_method The HTTP method (GET, POST, PUT, DELETE)
 * @param string $url Full URL of the resource to access
 * @param string $auth_header (optional) Authorization header
 * @param string $postData (optional) POST/PUT request body
 * @return string Response body from the server
 */
function send_request($http_method, $url, $auth_header=null, $postData=null) {
  $curl = curl_init($url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_FAILONERROR, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

  switch($http_method) {
    case 'GET':
      if ($auth_header) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); 
      }
      break;
    case 'POST':
      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/atom+xml', 
                                                   $auth_header)); 
      curl_setopt($curl, CURLOPT_POST, 1);                                       
      curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
      break;
    case 'PUT':
      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/atom+xml', 
                                                   $auth_header)); 
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
      break;
    case 'DELETE':
      curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); 
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method); 
      break;
  }
  $response = curl_exec($curl);
  if (!$response) {
    $response = curl_error($curl);
  }
  curl_close($curl);
  return $response;
}

/**
 * Joins key:value pairs by inner_glue and each pair together by outer_glue
 * @param string $inner_glue The HTTP method (GET, POST, PUT, DELETE)
 * @param string $outer_glue Full URL of the resource to access
 * @param array $array Associative array of query parameters
 * @return string Urlencoded string of query parameters
 */
function implode_assoc($inner_glue, $outer_glue, $array) {
  $output = array();
  foreach($array as $key => $item) {
    $output[] = $key . $inner_glue . urlencode($item);
  }
  return implode($outer_glue, $output);
}
?>

Editing contact photos using curl


You can use curl to modify Contacts API contact photos from the command line.

To start, you'll need to get the photo edit link from the contacts feed. This is expressed in the feed as the following XML element:

<link rel="http://schemas.google.com/contacts/2008/rel#photo-edit type="image/*" href="http://www.google.com/m8/feeds/photos/media/user/id/version" />

The photo edit link is contained inside the href attribute. For this example, it would be http://www.google.com/m8/feeds/photos/media/user/id/version.

Once you have this, you can add or update a photo by running:

curl -H "Authorization: GoogleLogin ..." \
-H "Content-Type: image/jpeg" \
-X PUT \
--binary-data "@/path/to/image.jpg" \
http://www.google.com/m8/feeds/photos/media/user/id/version

Be sure to replace the Content-Type and file path with appropriate values for your new photo.

To delete a photo, run:

curl -H "Authorization: GoogleLogin ..." \
-X DELETE \
http://www.google.com/m8/feeds/photos/media/user/id/version

You'll need to make sure that the Authorization header contains a valid ClientLogin token, as explained in the tip "Perform ClientLogin using curl.

Performing a GET with a POST using a Data API


Sometimes you can only do a GET when you need to do a DELETE, since some systems don't support all of the HTTP verbs. Also since Flash doesn't let you set a custom Authorization header on a GET, sometimes you need to do a GET with a POST. How can you do this? With the X-HTTP-Method-Override header:
X-HTTP-Method-Override: GET
For example, say you want to perform a video search in YouTube using a POST request:
POST /feeds/api/videos HTTP/1.1
Host: gdata.youtube.com
X-HTTP-Method-Override: GET
Content-Length: 23
Content-Type: application/x-www-form-urlencoded

vq=kitten&max-results=1
This is the same as performing a GET on http://gdata.youtube.com/feeds/api/videos?vq=kitten&max-results=1 The POST body is used as the set of query parameters. You can also do this using the curl command:
curl -H "X-HTTP-Method-Override: GET" -X POST http://gdata.youtube.com/feeds/api/videos -d "vq=kitten&max-results=1"

Post on Blogger using curl


This command line curl script reads an XML file containing the blog post's XML and uses curl to authenticate and post to Blogger. Here is the XML for an example post:
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Knock knock</title>
  <content type="xhtml">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Who's there?</p>
      <p>Orange.</p>
      <p>Orange who?</p>
      <p>Orange you glad you know how to post using curl?!? (lol!)</p>
    </div>
  </content>
  <category scheme="http://www.blogger.com/atom/ns#" term="joke"/>
  <category scheme="http://www.blogger.com/atom/ns#" term="curl"/>
</entry>
With the above stored in blog_post.xml, we can now post it using the following shell script:
#!/bin/sh

# Authenticate
# Requires $GDATA_PASSWORD to be set as an environment variable.
G_AUTH_TOKEN=`curl 2>/dev/null https://www.google.com/accounts/ClientLogin \
    -d Email=YOUR_EMAIL_ADDRESS@example.com \
    -d Passwd=$GDATA_PASSWORD  \
    -d accountType=GOOGLE \
    -d source=curlExample \
    -d service=blogger \
  | grep '^Auth=' | cut -c 6-`

# Post on my blog.
curl -v --request POST -H "Content-Type: application/atom+xml" \
    -H "Authorization: GoogleLogin auth=$G_AUTH_TOKEN" \
    "http://www.blogger.com/feeds/YOUR_BLOGS_ID/posts/default" --data "@blog_post.xml"

Perform ClientLogin using curl


Requests an authorization token for one of the Google Data API services and stores it in the shell environment variable GDATA_AUTH. This shell script takes three command line parameters, the email address for the desired account, password, and the service name of the service which the token will be used to access.
#!/bin/sh
export GDATA_AUTH=`curl 2>/dev/null https://www.google.com/accounts/ClientLogin \
  -d Email=$1 -d Passwd=$2 -d accountType=HOSTED_OR_GOOGLE -d source=curlExample \
  -d service=$3 | grep '^Auth=' | cut -c 6-`
echo $GDATA_AUTH

Fetch a Google Data feed using PHP & Curl


As a continuation from my last post, here's how you get a feed.
<?
// Note: this function assumes secure=0 AuthSub tokens
function getFeed($feedUri, $sessionToken) {
  $curl = curl_init($feedUri);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/atom+xml',
    'Authorization: AuthSub token="' . trim($sessionToken) . '"'
  ));
  $response = curl_exec($curl);

  if (!$response) {
    die('Error: ' . curl_error($curl) . "\n");
  }
  curl_close($curl);
  
  return $response;
}
?>

AuthSub using PHP's libcurl



<?
$secure = 0;
$session = 1;
$scope = 'http://www.google.com/calendar/feeds';
$next = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";

$token = @$_GET['token'];  // only a single use token

if(!$token) {
 echo "<a href=\"https://www.google.com/accounts/AuthSubRequest?scope=$scope&session=$session&secure=$secure&next=$next\">Sign in to Google</a>";
 exit;
}

$sessionToken = upgradeToken($token);
echo "Single use token: $token\n";
echo "Session token: $sessionToken";

// TODO: get a feed

function upgradeToken($token) {
  $ch = curl_init("https://www.google.com/accounts/AuthSubSessionToken");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: AuthSub token="' . trim($token) . '"'
  ));

  $result = curl_exec($ch);
  curl_close($ch);

  $splitStr = split("=", $result);

  return trim($splitStr[1]);
}
?>