New Twitter API (v1.1) Quick Start

This tutorial will help you get started with the new Twitter API which will be much different than the deprecated 1.0 version. In this example we’ll look at how to get a user’s timeline via the API.

  1. Setup your developer account if you haven’t done so yet at https://dev.twitter.com
  2. Go to https://apps.twitter.com/ and create your app
  3. Once created click on the Keys and Access Tokens tab and Create Access Tokens (for this example we only need Read access but for other applications you may want read and write)
  4. Copy and paste contents of TwitterAPIExchange.php
  5. Create a new PHP file that includes the TwitterAPI Exchange and uses your access tokens to GET requests from Twitter API:
    <?php
    require_once('TwitterAPIExchange.php');
    
    /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
    $settings = array(
        'oauth_access_token' => "",
        'oauth_access_token_secret' => "",
        'consumer_key' => "",
        'consumer_secret' => "",
        'username' => 'jolamar',
        'count' => 2
    );
    
    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name='.$settings["username"].'&count='.$settings["count"];
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $feed = json_decode($twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest(), true);
                 
    foreach($feed as $tweet) {
        
        // twitter variables
        $created = date("j M Y", strtotime($tweet["created_at"]));
        $id = $tweet["id"];
        $text = $tweet["text"];
        $username = $tweet["user"]["screen_name"];
        $name = $tweet["user"]["name"];
        $retweet_count = $tweet["retweet_count"];
        $favorite_count = $tweet["favorite_count"];
        $hashtags = $tweet["entities"]["hashtags"]; //array
        $mediaItems = $tweet["entities"]["media"]; //array
        
        echo "<div class='liljoshTweet'>
        <div class='liljoshName'><a href='https://twitter.com/$username'>$name</a></div><!-- /.liljoshName -->
        <div class='liljoshUsername'><a href='https://twitter.com/$username'>@$username</a></div><!-- /.liljoshUsername -->
        <div class='liljoshDivide'><a href='https://twitter.com/$username/status/$id'> · </a></div><!-- /.liljoshDivide -->
        <div class='liljoshDate'><a href='https://twitter.com/$username/status/$id'>$created</a></div><!-- /.liljoshDate -->
        <div class='liljoshText'>".makeHashtagLinks(makeClickableLinks($text))."</div><!-- /.liljoshText -->";
        
        if(is_array($mediaItems)) {
            foreach($mediaItems as $media) {
                $media_url = $media["media_url_https"];
                $media_link = $media["expanded_url"];
                $width = $media["sizes"]["small"]["w"];
                $height = $media["sizes"]["small"]["h"];
                
                echo "<div class='liljoshImage'><a href='$media_link' target='_blank'><img src='$media_url' /></a></div><!-- /.liljoshImage -->";
            }
        }
        
        echo "</div><!-- /.liljoshTweet -->";
    
    }
                 
    function makeClickableLinks($s) {
      return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s);
    }
    
    function makeHashtagLinks($s) {
        return preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1<span class="liljoshHashtag">#</span><a href="https://twitter.com/hashtag/\2?src=hash" target="_blank">\2</a>', $s);
    }
    ?>
    
    <style>
    
    .liljoshTweet {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    border: 1px solid #e1e8ed;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    line-height: 1.375em;
    padding: 13px 15px 15px;
    position: relative;
    display:block;
    }
    
    .liljoshText {
    font-size: 26px;
    font-weight: 300;
    line-height: 32px;
    letter-spacing: .01em;
    clear:both;
    }
    
    .liljoshText a {
    color: #0084B4;
    text-decoration: none;
    }
    
    .liljoshName {
    font-size:14px;
    font-weight: bold;
    color: #292f33;
    }
    
    .liljoshUsername, .liljoshDate, .liljoshDivide {
    color: #8899a6;
    font-size: 13px;
    }
    
    .liljoshUsername, .liljoshName, .liljoshDate, .liljoshDivide {
    float:left;
    padding-right: 5px;
    }
    
    .liljoshUsername a, .liljoshName a, .liljoshDate a, .liljoshDivide a,
    .liljoshUsername a:hover, .liljoshName a:hover, .liljoshDate a:hover, .liljoshDivide a:hover,
    .liljoshUsername a:focus, .liljoshName a:focus, .liljoshDate a:focus, .liljoshDivide a:focus,
    .liljoshUsername a:active, .liljoshName a:active, .liljoshDate a:active, .liljoshDivide a:active {
    text-decoration: none;
    color: inherit;
    }
    
    .liljoshImage {
    max-height: 262px;
    clear: both;
    border-radius: 5px;
    overflow: hidden;
    display: inline-block;
    }
    
    .liljoshImage img {
    max-width: 570px;
    }
    
    .liljoshHashtag {
    color: #66B5D2;
    }
    
    </style>

Remove .php extensions with .htaccess

You can clean up your URL a little by automatically removing the .php extensions and index files using mod_rewrite. This requires your web server has Apache running the mod_rewrite module. Create an .htaccess file in your web root directory with this content:

# Author: Lil Josh (liljosh.com)
# Date: Sept 2014
# Description: Clean up the URL by removing the .php extension and index file

RewriteEngine On
RewriteBase /

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php

# Remove index file
RewriteRule ^(.*)index\.(html|htm|shtml|php)$ http://%{HTTP_HOST}/$1 [R=301,L]

Velocity Cheat Sheet

Setting a Variable

#set($varName = "example value")

Using a Variable

<h1>$varName</h1>

Comments

##Comments have two pound signs in front

XPath Tool (Single Node)

#set($firstName = $_XPathTool.selectSingleNode($contentRoot, "firstName").value)
##$contentRoot is a special variable to select the root of the structured data for the page/block
##.value gets the value of that node

XPath Tool (Multiple Nodes)

#set($people = $_XPathTool.selectNodes($contentRoot, "people"))
<p>There are $people.size() people</p>

For Each Loop

#foreach($person in $people)
 #set($firstName = $_XPathTool.selectSingleNode($person, "firstName").value)
 ##notice we used $person instead of $contentRoot this time
#end

**NEW – Query API**

#set($pages = $_.query().byContentType('News Article').maxResults(3).hasMetadata('category', 'sports').sortBy('created').sortDirection('desc').execute())

#set($query = $query.includePages(true))
#set($query = $query.includeFiles(false))
#set($query = $query.includeFolders(false))
#set($query = $query.includeBlocks(false))
#set($query = $query.includeSymlinks(false))
#set($query = $query.siteName("Global"))
#set($query = $query.publishableOnly(true))
#set($query = $query.indexableOnly(true))

Serialize Tool (Getting WYSIWYG HTML)

#set($wysiwyg = $_XPathTool.selectSingleNode($contentRoot, "wysiwygName"))
$_SerializerTool.serialize($wysiwyg, true)
##true means that it'll skip the root element of the wysiwyg which is not part of the HTML content

Locator Tool

#set($page = $_.locatePage("/WRAP_SDDU/IU-CONTAINER-NAME/site-name/path/to/page"))
<h1>$page.metadata.title</h1>

Date Tool

#set($currentPage = $_.locatePage($currentPagePath, $currentPageSiteName)) 
#set($date = $currentPage.createdOn)
$_DateTool.format('dd MMM Y', $date)

Property Tool

$_PropertyTool.outputProperties($currentPage) 

## Check if object exists
#if(!$_PropertyTool.isNull($currentPage.structuredData)))
 EXISTS
#end

## use this macro to make it easier to remember
#macro(properties $object)
 $_PropertyTool.outputProperties($object)
#end

#properties($object)

Importing Scripts

#import('/WRAP_SDDU/IU-CONTAINER-NAME/site-name/_internal/stylesheets/functions')

Sorting

#set($people = $_XPathTool.selectNodes($contentRoot, "people"))
##parameters are selection string, language, type of element, sort order, and case order
$_SortTool.addSortCriterion("lastName", "en", "text", "ascending", "upper-first") 
$_SortTool.sort($people) 

Defining Macros (Functions)

#macro(macroName $param)
 <h1>$param</h1>
#end

#macro(type $object)
 $object.identifier.type
#end

Using Macros/Functions

#macroName($param)

More examples at https://github.com/hannonhill/Velocity-Cookbook

More documentation at http://www.hannonhill.com/kb/Script-Formats/ and http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html

Query API:
https://hannonhill.jira.com/browse/CSI-812

Community Macros/Functions

## type - takes an object and shows what type of asset it is
#macro(type $object)
 $object.identifier.type
#end
## properties - takes an object and shows what properties are available
#macro(properties $object)
 $_PropertyTool.outputProperties($object)
#end
## getChildren - takes a folder object and creates a children variable
#macro(getChildren $object)
#if($object.identifier.type != "folder")
#set($children = $object.parentFolder.children)
 #else
#set($children = $object.children)
#end
#end
## getMetadata - takes an object and looks for the metadata
#macro(getMetadata $object $metadata)
 #if($metadata == "title")
 $!object.metadata.title
 #elseif($metadata == "teaser")
 $!object.metadata.teaser
 #elseif($metadata == "reviewDate")
 $!object.metadata.reviewDate
 #elseif($metadata == "startDate")
 $!object.metadata.startDate
 #elseif($metadata == "keywords")
 $!object.metadata.keywords
 #elseif($metadata == "displayName")
 $!object.metadata.displayName
 #elseif($metadata == "endDate")
 $!object.metadata.endDate
 #elseif($metadata == "author")
 $!object.metadata.author
 #elseif($metadata == "summary")
 $!object.metadata.summary
 #elseif($metadata == "description")
 $!object.metadata.description
 #elseif(!$_PropertyTool.isNull($object.metadata.getDynamicField($metadata).value))
 $!object.metadata.getDynamicField($metadata).value
 #else
 $!object.path
 #end
#end