Categories
Code

Google OAuth 2.0 Service account with PHP and Google APIs

This sample code uses Google Service Accounts with PHP to get a list of users in a Google Apps Domain using the Admin Directory API.

To get started, install the Google API PHP library, create a Google Service account with domain-wide delegation and save the private JSON file in the same directory as your PHP application.

useApplicationDefaultCredentials(); 
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES); 
  $client->setAccessType("offline");
  $client->setSubject($user);

  $service = new Google_Service_Directory($client); 

  $optParams = array( 
    'domain' => 'ctrlq.org', 
    'maxResults' => 10, 
    'orderBy' => 'email'
  ); 

  $results = $service->users->listUsers($optParams); 

  print_r($results);

?>
Categories
Code

Tutorial: Create Application with Google APIs and OAuth 2

Now that you understand the basics of Google OAuth 2, let’s build a simple application that uses OAuth 2.0 for connecting to Google API’s on user’s behalf.

1. Go to console.developers.google.com and create a new project.

2017-01-16_22-23-56.311.png

2. Give your project a name.2017-01-16_22-25-24.046.png

3. Go to Library, search for the Google APIs that you wish to use in your application and enable them one by one.

enable-gmail-api.png

4. Go to Credentials -> Create Credentials -> Oauth Client Id. We’ll discuss service accounts in a later chapter.

oauth-client-id.png

5. On the credentials screen, choose “Web Application” for the “Application Type” and http://localhost:8080 under Authorized redirect URIs and Authorized JavaScript origins.

If you have a live web server running PHP, you can put the site address for the redirect URI but for this application, we will only use a local server running on port 8080. You only need to specify the port if your web service is running on a port than 80 (standard).

google-oauth-credentials.png

Google will show you the Client ID and Client Secret on the next screen. Dismiss the window and instead download the JSON file containing your OAuth client credentials. Move this JSON file in the root directory of your PHP application.

client-secret-json.png

In the next section, we’ll look at the actual PHP example that will connect our application to the user’s Gmail account via OAuth.

Categories
Code

Connect to Google API with PHP and OAuth2 – Sample Code

This sample application describes how your PHP application can connect to the user’s Gmail account using the Google PHP client library and OAuth2. You’ll need to create the application inside Google Console.

The Client ID and secret are stored in a separate JSON while the access token and refresh token are also stored in the local file system.

setApplicationName("ctrlq.org Application");
  $client->setAuthConfig($KEY_LOCATION);
  
  // Incremental authorization
  $client->setIncludeGrantedScopes(true);
  
  // Allow access to Google API when the user is not present. 
  $client->setAccessType('offline');
  $client->setRedirectUri($REDIRECT_URI);
  $client->setScopes($SCOPES);
  
  if (isset($_GET['code']) && !empty($_GET['code'])) {
      try {
          // Exchange the one-time authorization code for an access token
          $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
          
          // Save the access token and refresh token in local filesystem
          file_put_contents($TOKEN_FILE, json_encode($accessToken));
          
          $_SESSION['accessToken'] = $accessToken;
          header('Location: ' . filter_var($REDIRECT_URI, FILTER_SANITIZE_URL));
          exit();
      }
      catch (\Google_Service_Exception $e) {
          print_r($e);
      }
  }
  
  if (!isset($_SESSION['accessToken'])) {
      
      $token = @file_get_contents($TOKEN_FILE);
      
      if ($token == null) {
          
          // Generate a URL to request access from Google's OAuth 2.0 server:
          $authUrl = $client->createAuthUrl();
          
          // Redirect the user to Google's OAuth server
          header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
          exit();
          
      } else {
          
          $_SESSION['accessToken'] = json_decode($token, true);
          
      }
  }
  
  $client->setAccessToken($_SESSION['accessToken']);
  
  /* Refresh token when expired */
  if ($client->isAccessTokenExpired()) {
      // the new access token comes with a refresh token as well
      $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
      file_put_contents($TOKEN_FILE, json_encode($client->getAccessToken()));
  }
  
  $gmail = new Google_Service_Gmail($client);
  
  $opt_param               = array();
  $opt_param['maxResults'] = 10;
  
  $threads = $gmail->users_threads->listUsersThreads("amit@labnol.org", $opt_param);
  
  foreach ($threads as $thread) {
      print $thread->getId() . " - " . $thread->getSnippet() . '
'; } ?>
Categories
Code

Validate an Email Address with PHP

Before sending email via SMTP, the client computer initiates a transaction with the SMTP email server that is listening for commands on TCP port 25. The SMTP command HELO initiates a transaction with the mail server and identifies itself, MAIL FROM and RCTP specify the sender and recipients respectively while QUIT will close the conversation. If the mail server returns the status as 250, that means the email address is validate and exists.

@hbattat has written a wrapper PHP library that can be used to determine if an email address is real or not. You specify the sender’s email, the recipient’s email and connect to the mail server to know whether that email exists on the domain or not. Email verification can be done using Windows Telnet as well.

\r\n");
            $from = fgets($connect, 1024);
            $details .= $from."\n";

                        // Send the SCPT command with the recepient's email address
            fputs($connect, "RCPT TO: <$toemail>\r\n");
            $to = fgets($connect, 1024);
            $details .= $to."\n";

            // Close the socket connection with QUIT command to the SMTP server
            fputs($connect, 'QUIT');
            fclose($connect);

            // The expected response is 250 if the email is valid
            if (!preg_match('/^250/i', $from) || !preg_match('/^250/i', $to)) {
                $result = 'invalid';
            } else {
                $result = 'valid';
            }
        }
    } else {
        $result = 'invalid';
        $details .= 'Could not connect to server';
    }
    if ($getdetails) {
        return array($result, $details);
    } else {
        return $result;
    }
}

SMTP also provides the VRFY command to query when the specified user exists on the host or not but it is often ignored by mail servers.

Also see: Find Person by Email Address

Categories
Code

How to use cURL with PHP – Basic Example

cURL is a PHP library and a command line tool (like wget) that helps you send files and also download data over HTTP and FTP. It supports proxies, you can transfer data over SSL connections, you can set cookies and even get files that are behind a login.

Here’s a basic example on how to use cURL in your PHP project:


Categories
Code

Blogger to WordPress Redirection

The Blogger to WordPress tutorial uses this PHP snippet to redirect visitors on the Blogger blog to the corresponding post on the WordPress site.

When a visitor is redirected from Blogger to WordPress, the blogger slug is contained in the query parameter string. On the WordPress side, this string is parsed and matched against the “blogger_permalink” custom fields on WordPress. If a match if found, the visitor is redirected to the corresponding WordPress post using a 301 redirect.

query_vars['blogger'];
  if ( isset ( $blogger ) ) {
    wp_redirect( labnol_get_wordpress_url ( $blogger ) , 301 );
    exit;
  }
}

add_action( 'template_redirect', 'labnol_blogger_template_redirect' );

function labnol_get_wordpress_url($blogger) {

  /* Extract the blogger slug from the full blogspot.com url */
  if ( preg_match('@^(?:https?://)?([^/]+)(.*)@i', $blogger, $url_parts) ) {

    /* Query the WordPress database to find matching posts */
    $query = new WP_Query ( array ( 
      "meta_key" => "blogger_permalink", "meta_value" => $url_parts[2] ) ); 

    /* if a match is found, get the permalink of the WordPress post */
    if ($query->have_posts()) {
      $query->the_post(); 
      $url = get_permalink(); 
    } 

    wp_reset_postdata(); 

  } 

  /* If permalink is not found, return the blog home page url */
  return $url ? $url : home_url();

}
Categories
Code

Create RSS Feeds from Amazon Listings

If an Amazon Category page does not offer RSS feeds, you can use PHP to easily create one. The PHP snippet below will download a page from the Amazon website and converts the products into an RSS feed so you can easily track when new items are added to that category.

The RSS feed will have the product name, the title, the permalink (URL) and the thumbnail image.

';
  $head .= '';
  $head .= '';
  $head .= 'Amazon ';
  $head .= 'http://www.amazon.com';
  $head .= 'Amazon RSS Feed';
   
  $url = "http://www.amazon.com/Best-Sellers-Kindle-Store/zgbs/digital-text/";
   
  $text = file_get_html($url); 

  foreach ($text->find("div.zg_item_compact") as $class) {
    foreach ($class->find('strong.price') as $price) {
      if ($price->plaintext == "Free") {
              $rssfeed .= '';
              foreach ($class->find("div.zg_title a") as $book) { 
                preg_match("/\/dp\/(.*)\/ref/", $book->href, $matches);                
                $ASIN  = trim($matches[1]);
                $url   = "http://www.amazon.com/dp/" . $ASIN . "/?tag=ctrlqorg-20";
                $img   = "http://images.amazon.com/images/P/" . $ASIN . ".01.LZZZZZZZ.jpg";
                $title = htmlentities(trim($book->plaintext));                
                $rssfeed .= '' . $title . '';
                $rssfeed .= '' . $url . '';
                $rssfeed .= '' . $url . '';
                $rssfeed .= '';
              }
              foreach ($class->find("div.zg_byline a") as $author) {
                  $bio  = "http://www.amazon.com" . $author->href . "/?tag=publisherapi-20";
                  $name = htmlentities(trim($author->plaintext));
                  $rssfeed .= 'By ' . $name . '';
              }
              $rssfeed .= '';
              $rssfeed .= '' . $now . '';
              $rssfeed .= '';
          }
      }
  }

  $footer  = '';
  $rssfeed = $head . $rssfeed . $footer;
  $fh      = fopen("amazon.rss", "w");

  fwrite($fh, $rssfeed);
  fclose($fh);

?>
Categories
Code

Web Scraping Amazon with PHP

There are two ways to get the price of any product listed on the Amazon website. You can either use the official Amazon API or you can perform web scraping.

Scraping essentially means that your script will download the web page from Amazon, parse the HTML and extract the price. This method is preferred when the Product Advertising API doesn’t have the prices for a particular product or when the price offered by the API is different from what is available on the Amazon website.

(Prezzo|Precio|Price|Prix Amazon|Preis):?\<\/b\>([^\<]+)/i';

    /* Return the price */

    if (preg_match($regex, $html, $price)) {
        $price = number_format((float)($price[2]/100), 2, '.', '');
        echo "The price for amazon.com/dp/$amazonISIN is $price";
    } else {
        echo "Sorry, the item is out-of-stock on Amazon";
    }

?>

All you have to do is specify the 10 digital Amazon ISIN code for a product and the PHP script will get the price for you.

Categories
Code

404 Page for WordPress with Suggestions

If a visitor mistypes a URL to your WordPress blog or clicks on a link that does not exists, you can show them a more helpful 404 error page that will have suggestions pointing to related articles that they can check out on your WordPress site. Internally, it runs a search using the 404 page URL as the query parameter.

Save this file as 404.php and place it in your WordPress theme folder.



404 Error - Page not found

query_vars['is_search'] = true; $s = str_replace("-", " ", $wp_query->query_vars['name']); $loop = new WP_Query('post_type=any&s=' . $s); ?> have_posts()): ?>

We tried finding the matching pages from our website. Here're some suggestions:

    have_posts()): $loop->the_post(); ?>
Categories
Code

Web Scraping Flipkart Prices with PHP

The India Price Tracker tool uses web scraping to extract the prices of products listed on the Flipkart website. It uses the CURL library of PHP to fetch the HTML DOM of a Flipkart page and then uses regular expressions to extract the price and product image from the Meta tags.

Make sure you specify a User Agent string with your CURL request else the Flipkart server will reject your request.

]*>([^<]*)<\/h1>/';
	preg_match($regex, $html, $title);

	$regex = '/data-src="([^"]*)"/i';
	preg_match($regex, $html, $image);

	if ($price && $title && $image) {
		$response = array("price" => "Rs. $price[1].00", "image" => $image[1], "title" => $title[1], "status" => "200");
	} else {
		$response = array("status" => "404", "error" => "We could not find the product details on Flipkart $url");
	}

	return $response;
}
Categories
Code

Use the Amazon API to Get Product Prices

You can use the Amazon Advertising API (AWS) to fetch the current prices, item description, customer reviews, product images, quantity available and other details of any product listed on various Amazon websites.

The getAmazonPrice() method takes the region (like “com” for US or “es” for Spain) and the 10-digit ASIN of any product. The response is returned as JSON that the Amazon Price Tracker can easily parse with Google Scripts. You cannot however use this technique for fetching prices of Kindle Books as the Amazon API doesn’t support them yet.

 "ItemLookup",
		"ItemId" => $asin,
		"IncludeReviewsSummary" => False,
		"ResponseGroup" => "Medium,OfferSummary",
	));

	$item = $xml->Items->Item;
	$title = htmlentities((string) $item->ItemAttributes->Title);
	$url = htmlentities((string) $item->DetailPageURL);
	$image = htmlentities((string) $item->MediumImage->URL);
	$price = htmlentities((string) $item->OfferSummary->LowestNewPrice->Amount);
	$code = htmlentities((string) $item->OfferSummary->LowestNewPrice->CurrencyCode);
	$qty = htmlentities((string) $item->OfferSummary->TotalNew);

	if ($qty !== "0") {
		$response = array(
			"code" => $code,
			"price" => number_format((float) ($price / 100), 2, '.', ''),
			"image" => $image,
			"url" => $url,
			"title" => $title
		);
	}

	return $response;
}

function getPage($url) {

	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_FAILONERROR, true);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$html = curl_exec($curl);
	curl_close($curl);
	return $html;
}

function aws_signed_request($region, $params) {

	$public_key = "PUBLIC_KEY";
	$private_key = "PRIVATE_KEY";

	$method = "GET";
	$host = "ecs.amazonaws." . $region;
	$host = "webservices.amazon." . $region;
	$uri = "/onca/xml";

	$params["Service"] = "AWSECommerceService";
	$params["AssociateTag"] = "affiliate-20"; // Put your Affiliate Code here
	$params["AWSAccessKeyId"] = $public_key;
	$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
	$params["Version"] = "2011-08-01";

	ksort($params);

	$canonicalized_query = array();
	foreach ($params as $param => $value) {
		$param = str_replace("%7E", "~", rawurlencode($param));
		$value = str_replace("%7E", "~", rawurlencode($value));
		$canonicalized_query[] = $param . "=" . $value;
	}

	$canonicalized_query = implode("&", $canonicalized_query);

	$string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
	$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
	$signature = str_replace("%7E", "~", rawurlencode($signature));

	$request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
	$response = getPage($request);

	var_dump($response);

	$pxml = @simplexml_load_string($response);
	if ($pxml === False) {
		return False;// no xml
	} else {
		return $pxml;
	}
}

?>

You’ll have to get your public and private access keys from the AWS Management Console and replace them in the PHP snippet. You also need to put your Amazon Affiliate ID for the country specific Amazon Affiliate program. For instance, the id for Amazon US would be different from Amazon UK though you can use the same Access Keys with the code.

Categories
Code

Using Gmail API to Send Rich Text Emails

The new HTML Mail app uses the Gmail API to send rich-text emails to anyone on your behalf. You can sign-in using your Google / Gmail account via OAuth and are presented with a HTML5 form to send emails. Unlike the Apps Script based solutions that require full access to your Gmail account, the new Gmail API only needs permissions to compose and send messages and does not have access to your Gmail messages and folders.

The app uses the Google PHP library to connect to the Gmail API though the can be easily ported to JavaScript, Python or Java. The text editor of the HTML Mail app is powered by TinyMCE.

setClientId($client_id);
  $client->setClientSecret($client_secret);
  $client->setRedirectUri($redirect_uri);

  // We only need permissions to compose and send emails
  $client->addScope("https://www.googleapis.com/auth/gmail.compose");
  $service = new Google_Service_Gmail($client);

  // Redirect the URL after OAuth
  if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
  }

  // If Access Toket is not set, show the OAuth URL
  if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
  } else {
    $authUrl = $client->createAuthUrl();
  }

  if ($client->getAccessToken() && isset($_POST['message'])) {

    $_SESSION['access_token'] = $client->getAccessToken();

    // Prepare the message in message/rfc822
    try {

        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($_POST["message"]), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $service->users_messages->send("me", $msg);

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['access_token']);
    }

  } ?>

 
  
 
  
Send Mail
Categories
Code

Send Base64 Encoded Email with PHP

Base 64 is a way to representing binary data – like images – into ASCII text. You can use use Base-64 encoding to easily send binary data through HTML Mail, e-mail attachments, JSON requests and HTML forms.

The encoded data uses A-Z, a-z, 0-9 and + and /, with = as a padding character while carriage return line feed (“\r\n”) characters are inserted into the output to keep the line lengths less than 76 characters. Here is the raw source of a MIME encoded HTML Mail:

To: amit@labnol.org
Subject: This is a MIME encoded email
From: from@labnol.org
Cc: cc@labnol.org
MIME-Version: 1.0
Content-Type: multipart/alternative;boundary = "Saturday16thofAugust2014081815AM"
Message-Id: <20140816081815.6ABFB2D793B0@iMac.local>
Date: Sat, 16 Aug 2014 13:48:15 +0530 (IST)

--Saturday16thofAugust2014081815AM
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: base64

PHA+VGhlIDxiPnF1aWNrPC9iPiA8ZW0+YnJvd248L2VtPiA8dT5mb3g8L3U+IGp1bXBlZCByaWdo
dCBvdmVyIHRoZSBsYXp5IGRvZy48L3A+PGhyIC8+

You can easily send MIME encoded email messages through PHP. The base64_encode() method encodes the HTML message with base64 while chunk_split() splits the encoded messages into smaller chunks and appends “\r\n” at the end.


The quick brown fox jumped right over the lazy dog.


"; $to = "amit@labnol.org"; $cc = "cc@labnol.org"; $bcc = "bcc@labnol.org"; $from = "from@labnol.org"; $subject = "This is a MIME encoded email"; $boundary = str_replace(" ", "", date('l jS \of F Y h i s A')); $newline = "\r\n"; $headers = "From: $from$newline". "Cc: $cc$newline". "Bcc: $bcc$newline". "MIME-Version: 1.0$newline". "Content-Type: multipart/alternative;". "boundary = \"$boundary\"$newline$newline". "--$boundary$newline". "Content-Type: text/html; charset=ISO-8859-1$newline". "Content-Transfer-Encoding: base64$newline$newline"; $headers .= rtrim(chunk_split(base64_encode($html))); mail($to,$subject,"",$headers); ?>
Categories
Code

Housie Tickets Generator in PHP

This PHP script generates housie tickets using Emojis instead of numbers. Each ticket has 3 rows with 9 columns of which 4 are blanks and the rest have unique but random emoji emoticons.

The emojis are rendered using 160×160 images extracted from the Apple Emoji font and would therefore render on any browser and device.

";
        for ($j=0; $j<9; $j++) {
            $img = $row[$i][$j] == "" ? "white.gif" : $row[$i][$j] . ".png";
            $table .= "";
        }
        $table .= "";
    }

    $table = "$table
"; return $table; } $html = ""; // Generate 2x5 tickets per sheet for ($i=0; $i<5; $i++) { $html .= "" . createTicket() . "" . createTicket() . ""; } echo "$html
"; ?>
Categories
Code

Retrieve Facebook Likes Count with PHP

You can get the total number of likes and share count of any web URL with a little bit of PHP and FQL (Facebook Query Language).

You don’t have to fiddle with the Facebook SDK or the API and this trick works for both Facebook pages as well as any external web page that has the like button or has been shared on Facebook.


function facebook_count($url){

    // Query in FQL
    $fql  = "SELECT share_count, like_count, comment_count ";
    $fql .= " FROM link_stat WHERE url = '$url'";

    $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);

    // Facebook Response is in JSON
    $response = file_get_contents($fqlURL);
    return json_decode($response);

}

$fb = facebook_count('https://www.facebook.com/digital.inspiration');

// facebook share count
echo $fb[0]->share_count;

// facebook like count
echo $fb[0]->like_count;

// facebook comment count
echo $fb[0]->comment_count;

Categories
Code

Store Passwords Securely with PHP

The Secure Passwords app generate unique passwords for every using the most secure bCrypt algorithm. The open source PHPass library also uses the Blowfish-based bcrypt library to create password hashes that you can use to store passwords in the database.

When the user enter a password during login, you can compute the hash and compare it with the hash in your database. This is more secure than other algorithms like md5, sha1, sha512, etc since they can be reversed though brutal force.


HashPassword('correct password');
 
// Check if a user has provided the correct password by comparing what they typed with our hash
$hasher->CheckPassword('wrong password', $hashedPassword); // false 
$hasher->CheckPassword('correct password', $hashedPassword); // true
?>
Categories
Code

Send Mail through GMail SMTP Server with PHP

The HTML Mail app lets you send rich text emails to anyone without requiring an account. Internally, it uses the mail() function of PHP to deliver these messages.

The PHP Mailer library on Github is a wrapper over the built-in mail function but adds support for attachments and also integrates with SMTP so you can send mail without having a local mail server. This script lets you send messages via your Google’s Gmail server.

isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';                       // Specify main and backup server
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'amit@gmail.com';                   // SMTP username
$mail->Password = 'digitalinspiration';               // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
$mail->Port = 587;                                    //Set the SMTP port number - 587 for authenticated TLS
$mail->setFrom('amit@gmail.com', 'Amit Agarwal');     //Set who the message is to be sent from
$mail->addReplyTo('labnol@gmail.com', 'First Last');  //Set an alternative reply-to address
$mail->addAddress('josh@example.net', 'Josh Adams');  // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/usr/labnol/file.doc');         // Add attachments
$mail->addAttachment('/images/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body in bold!';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

echo 'Message has been sent';
Categories
Code

RSS Feed for Google+

This PHP script will generate an RSS Feed for Google Plus users. You can need to replace the PlusID with your own Profile ID and the Google API key that can be obtained from code.google.com.

Google+ allows you to retrieve content from the network but the API doesn’t allow you post content on Google Plus. Code courtesy @SplitBrain/Github.

\n";
echo "\n";
echo "\n";
echo " ".htmlspecialchars($gplus->title)."\n";
echo " http://plus.google.com/$googlePlusID\n";
echo " \n";
echo " ".$gplus->updated."\n";
echo " ".$gplus->updated."\n";
foreach($gplus->items as $item) {
echo " \n";
echo " ".htmlspecialchars($item->title)."\n";
echo " ".htmlspecialchars($item->url)."\n";
echo " ".htmlspecialchars($item->id)."\n";
echo " ".$item->updated."\n";

// we might add a source quote from attachments
$desc = $item->object->content;

if(isset($item->object->attachments)) foreach($item->object->attachments as $attach){
if($attach->objectType == 'article'){
$desc .= '

';
$desc .= ''.$attach->displayName.'

';
$desc .= $attach->content;
$desc .= '

';
}elseif($attach->objectType == 'photo'){
echo " image->url)."\" type=\"".$attach->image->type."\" />\n";
}// FIXME what other attachement type need to be supported?
}

echo " ".htmlspecialchars($desc)."\n";

if($item->geocode){
list($lat,$lon) = explode(" ",$item->geocode);
echo " $lat\n";
echo " $lon\n";
}

echo " \n";
}
echo "\n";
echo "\n";

Categories
Code

Managing YouTube with Google Data API

The Copy YouTube Playlists tool uses Google Data API (PHP) and YouTube API (v3) to clone any public YouTube playlist into the YouTube account of the authorized user.

You need to create your own OAuth2 secret keys from the Google Developer’s Console and also the redirect URL should point to the page where the PHP script is hosted.

setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setRedirectUri($redirect);

    $youtube = new Google_YoutubeService($client);

    if (isset($_GET['code'])) {

        if (strval($_SESSION['state']) !== strval($_GET['state'])) {
            die('The session state did not match.');
        }

        $client->authenticate();
        $_SESSION['token'] = $client->getAccessToken();
        header('Location: ' . $redirect);

    }

    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    if ($client->getAccessToken()) {

            try {

                if ( preg_match('/(PL[A-Za-z0-9_-]+)/', $_POST["url"], $match) ) {

                    $plID = $match[0];
                    $pl_options = array ("id" => $plID, "maxResults" => 1);
                    $playlistDetails = $youtube->playlists->listPlaylists("snippet", $pl_options);

                    if ( $playlistDetails["pageInfo"]["totalResults"] == 1 ) {

                        $options = array ("playlistId" => $plID, "maxResults" => 50);
                        $videos = "";

                        do {

                            $playlist = $youtube->playlistItems->listPlaylistItems("snippet", $options);
                            $nextPageToken = $playlist["nextPageToken"];
                            $options["pageToken"] = $nextPageToken;

                            foreach ($playlist["items"] as $playlistItem) {
                                $videos .=  $playlistItem["snippet"]["resourceId"]["videoId"] . "#";
                            }

                        } while ($nextPageToken);

                        $playlistSnippet = new Google_PlaylistSnippet();
                        $playlistSnippet->setTitle($playlistDetails["items"][0]["snippet"]["title"]);

                        $playlistStatus = new Google_PlaylistStatus();
                        $playlistStatus->setPrivacyStatus('private');

                        $youTubePlaylist = new Google_Playlist();
                        $youTubePlaylist->setSnippet($playlistSnippet);
                        $youTubePlaylist->setStatus($playlistStatus);

                        $playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, array());

                        $ids = explode ( "#", $videos ) ;

                        for ($i=0; $isetVideoId($ids[$i]);
                            $resourceId->setKind('youtube#video');

                            $playlistItemSnippet = new Google_PlaylistItemSnippet();
                            $playlistItemSnippet->setPlaylistId($playlistResponse['id']);
                            $playlistItemSnippet->setResourceId($resourceId);

                            $playlistItem = new Google_PlaylistItem();
                            $playlistItem->setSnippet($playlistItemSnippet);

                            $playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());

                        }

                    }

                }

            } catch (Google_ServiceException $e) {
                $htmlBody .= sprintf('

A service error occurred: %s

', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('

An client error occurred: %s

', htmlspecialchars($e->getMessage())); } } else { $htmlBody = << END; } $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<Step 1: Sign-in with YouTube

END; } ?>
Categories
Code

Import iTunes JSON into WordPress

I am working on a little project that parses the JSON feeds of iTunes and imports the categories into WordPress. Here’s the relevant snippet.

I am using wp_remote_get here, a much simpler alternative to using CURL or file_get_content() of PHP. WordPress has built-in functions for inserting categories – wp_insert_category and wp_create_category – but they aren’t working in 3.5.1 and hence had to use wp_insert_term.


  // Written by Amit Agarwal

  $url = "http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=20";

  $data = wp_remote_retrieve_body (wp_remote_get($url));
  $json = json_decode($data, true);

  foreach ($json['26']['subgenres'] as $item) {
        $id = wp_insert_term ( $item['name'], 
                'category', array (
                'slug' => $item['url'], 
                'description' => $item['id']));

        if ( isset ($item['subgenres']) ) {
                foreach ($item['subgenres'] as $sub) {
                    wp_insert_term ( $sub['name'], 'category',
                        array ('slug' => $sub['url'],
                               'description' => $sub['id'],
                               'parent' => $id["term_id"]
                               )
                     );
                }
        }

}

Categories
Code

Simple PHP Templates

This is a simple PHP based template where the variable fields in the template are enclosed in double parenthesis and the actual values are passed in a single array. The entire substitution happens in one step using preg_replace.

If your template string is long, you can either put that in a separate PHP file (and use the include function) or simply use multi-line strings with the Heredoc syntax (delimited by <<<). Credit: Jeffrey

<?php

$template = "I am {{name}}, and I work for {{company}}. I am {{age}}.";

# Your template tags + replacements
$replacements = array(
	'name' => 'Jeffrey',
	'company' => 'Envato',
	'age' => 27
);

function bind_to_template($replacements, $template) {
	return preg_replace_callback('/{{(.+?)}}/',
             function($matches) use ($replacements) {
		return $replacements[$matches[1]];
	}, $template);
}

// I am Jeffrey, and I work for Envato. I am 27.
echo bind_to_template($replacements, $template);
Categories
Code

Using Google Text to Speech API – PHP

Google offers an undocumented text to speech API that help you transform text into voice. You can see a live demo at ctrlq.org/listen.

The following snippet of PHP code is responsible for the conversion while the MP3 files are cached to reduce requests to Google Translation servers.

<?php

// Convert Words (text) to Speech (MP3)
// ------------------------------------

// Google Translate API cannot handle strings > 100 characters
   $words = substr($_GET['words'], 0, 100);

// Replace the non-alphanumeric characters 
// The spaces in the sentence are replaced with the Plus symbol
   $words = urlencode($_GET['words']);

// Name of the MP3 file generated using the MD5 hash
   $file  = md5($words);
  
// Save the MP3 file in this folder with the .mp3 extension 
   $file = "audio/" . $file . ".mp3";

// If the MP3 file exists, do not create a new request
   if (!file_exists($file)) {
     $mp3 = file_get_contents(
        'http://translate.google.com/translate_tts?q=' . $words;
     file_put_contents($file, $mp3);
   }
?>

// Embed the MP3 file using the AUDIO tag of HTML5
<audio controls="controls" autoplay="autoplay">
  <source src="<? echo $file; ?>" type="audio/mp3" />
</audio>

Google Text to Speech – Command Line

You can also convert any piece of text to MP3 files from the command line using the wget or CURL command. Remember that the value of “q” parameter should have less than 100 characters else the Google Translate TTS API will throw an error.

wget -q -U Mozilla -O audio.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=hello+world

curl -A "Mozilla" "http://translate.google.com/translate_tts?tl=en&q=hello+world" > audio.mp3
Categories
Code

Google Sitemap Generator with PHP

This is the PHP code that runs the Blogger Sitemap Generator. The generated XML sitemaps are exposed to Google via the robots.txt file – see Add Google Sitemap to Blogger Blogs.

// Make sure that input contains http
 if(substr($blog,0,7) != "http://")
  $blog = "http://" . $blog;
  
// Make sure that blog URL ends with a slash
 if(substr($blog, -1) != "/")
  $blog = $blog . "/";

// Determine the count of blog posts
 $url = $blog . "atom.xml?redirect=false&start-index=1&max-results=1";

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

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

// Parse the XML ouput to determine the count
 $x = strpos($xml, "") + strlen("");
 $y = strpos($xml, "");
 $c = substr($xml, $x, $y-$x);

// Generate the XML sitemap for robots.txt
  if ($c >=1) {
    echo "# Blogger Sitemap generated on " . date("Y.m.d") . "
"; echo "User-agent: *
Disallow: /search
Allow: /
"; for($x=1; $x<=$c; $x=$x+500) { echo "
Sitemap: " . $blog . "atom.xml?redirect=false&start-index=" . $x . "&max-results=500"; } }
Categories
Code

Parsing the Twitter Trends API

Use the following PHP code to determine all the locations (cities and countries) for which Twitter can offer local trends data

The Twitter API offers the Trends availability data in JSON format that you can parse with the json_decode function of PHP.

";
 }

 function compare_country($a, $b) {
   return strnatcmp($a['country'], $b['country']);
  }
?>
Categories
Code

Google Analytics PHP Tracking Code

This PHP script creates a 1×1 invisible image (__utm.gif) for tracking print usage using Google Analytics.

The Google Analytics Profile ID and the Landing Page URL are passed to the script via GET Parameters while the Referrer and User Agent string are determined from the request headers.

 array(
          "method" => "GET",
          "user_agent" => $_SERVER["HTTP_USER_AGENT"],
          "header" => ("Accept-Language: " . 
                          $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    );
    if (!empty($_GET["utmdebug"])) {
      $data = file_get_contents(
          $utmUrl, false, stream_context_create($options));
    } else {
      $data = @file_get_contents(
          $utmUrl, false, stream_context_create($options));
    }
  }

  // Track a page view, updates all the cookies and campaign tracker,
  // makes a server side request to Google Analytics and writes the 
  // transparent gif byte data to the response.
  function trackPageView() {
    $timeStamp = time();
    $domainName = $_GET["d"];
    if (empty($domainName)) {
      $domainName = "";
    }

    // Get the referrer from the utmr parameter
    $documentReferer = $_GET["utmr"];
    if (empty($documentReferer) && $documentReferer !== "0") {
      $documentReferer = "-";
    } else {
      $documentReferer = urldecode($documentReferer);
    }

    $documentPath = '/print' . urldecode($_GET["u"]);

    $account = $_GET["id"];
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (empty($userAgent)) {
      $userAgent = "";
    }

    // Try and get visitor cookie from the request.
    $cookie = $_COOKIE[COOKIE_NAME];

    $guidHeader = $_SERVER["HTTP_X_DCMGUID"];
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_UP_SUBNO"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_JPHONE_UID"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_EM_UID"];
    }

    $visitorId = getVisitorId($guidHeader, $account, $userAgent, $cookie);

    // Always try and add the cookie to the response.
    setrawcookie(
        COOKIE_NAME,
        $visitorId,
        $timeStamp + COOKIE_USER_PERSISTENCE,
        COOKIE_PATH);

    $utmGifLocation = "http://www.google-analytics.com/__utm.gif";

    // Construct the gif hit url.
    $utmUrl = $utmGifLocation . "?" .
        "utmwv=" . VERSION .
        "&utmn=" . getRandomNumber() .
        "&utmhn=" . urlencode($domainName) .
        "&utmr=" . urlencode($documentReferer) .
        "&utmp=" . urlencode($documentPath) .
        "&utmac=" . $account .
        "&utmcc=__utma%3D999.999.999.999.999.1%3B" .
        "&utmvid=" . $visitorId .
        "&utmip=" . getIP($_SERVER["REMOTE_ADDR"]);

    sendRequestToGoogleAnalytics($utmUrl);

    writeGifData();
  }
?>