TYPO3 for Connecting External APIs: Flicker and Youtube

Dan Osipov

January 2010

Getting recent Flickr photos

The Flickr API is very powerful and gives access to just about everything a user can do manually. You can write scripts to automatically download latest pictures from a photostream, download photos or videos tagged with a certain keyword, or post comments on photos. In this recipe, we will make use of the phpFlickr library to perform some basic listing functions for photos in Flickr.

Getting ready

Before you start, you should sign up for a free Flickr account, or use an existing one. Once you have the account, you need to sign up for an API key. You can go to Your Account, and select the Extending Flickr tab. After filling in a short form, you should be given two keys—API key and secret key. We will use these in all Flickr operations. We will not go through the steps required for integration into extensions, and will leave this exercise to the reader. The code we present can be used in both frontend plugins and backend modules. As was previously mentioned, we will be using the phpFlickr library. Go to http://phpflickr.com/ to download the latest version of the library and read the complete documentation.

How to do it...

  1. Include phpFlickr, and instantiate the object (modify the path to the library, and replace api-key with your key):
    $flickrService = new phpFlickr('api-key');
  2. Get a list of photos for a specific user:
    $photos = $flickrService->people_getPublicPhotos('7542705@N08');
  3. If the operation succeeds, $photos will contain an array of 100 (by default) photos from the user. You could loop over the array, and print a thumbnail with a link to the full image by:

    foreach ($photos['photos']['photo'] as $photo) {
    $imgURL = $flickrService->buildPhotoURL($photo, 'thumbnail');
    print '<a href="http://www.flickr.com/photos/' .
    $photo['owner'] . '/' . $photo['id'] . '">' .
    '<img src="' . $imgURL . '" /></a><br />';

How it works...

The Flickr API is exposed as a set of REST services, which we can issue calls to. The tough work of signing the requests and parsing the results is encapsulated by phpFlickr, so we don't have to worry about it. Our job is to gather the parameters, issue the request, and process the response. In the example above, we got a list of public photos from a user 7542705@N08. You may not know the user ID of the person you want to get photos for, but Flickr API offers several methods for finding the ID:

$userID = $flickrService->people_findByEmail($email);
$userID = $flickrService->people_findByUsername($username);

If you have the user ID, but want to get more information about the user, you can do it with the following calls:

// Get more info about the user:
// Find which public groups the user belongs to:
// Get user's public photos:

We utilize the people_getPublicPhotos method to get the user's photostream. The returned array has the following structure:

[photos] => Array
[page] => 1
[pages] => 8
[perpage] => 100
[total] => 770
[photo] => Array
[0] => Array
[id] => 3960430648
[owner] => 7542705@N08
[secret] => 9c4087aae3
[server] => 3423
[farm] => 4
[title] => One Cold Morning
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0

We loop over the $photos['photos']['photo'] array, and for each image, we build a URL for the thumbnail using the buildPhotoURL method, and a link to the image page on Flickr.

There's more...

There are lots of other things we can do, but we will only cover a few basic operations.

Error reporting and debugging

Occasionally, you might encounter an output you do not expect. It's possible that the Flickr API returned an error, but by default, it's not shown to the user. You need to call the following functions to get more information about the error:

$errorCode = $flickrService->getErrorCode();
$errorMessage = $flickrService->getErrorMsg();

Downloading a list of recent photos

You can get a list of the most recent photos uploaded to Flickr using the following call:

$recentPhotos = $flickrService->photos_getRecent();

See also

  • Uploading files to Flickr
  • Uploading DAM files to Flickr

Uploading files to Flickr

In this recipe, we will take a look at how to upload files to Flickr, as well as how to access other authenticated operations. Although many operations don't require authentication, any interactive functions do. Once you have successfully authenticated with Flickr, you can upload files, leave comments, and make other changes to the data stored in Flickr that you wouldn't be allowed to do without authentication.

Getting ready

If you followed the previous example, you should have everything ready to go. We'll assume you have the $flickrService object instantiated ready.

How to do it...

  1. Before calling any operations that require elevated permissions, the service needs to be authenticated. Add the following code to perform the authentication:

    $frob = t3lib_div::_GET('frob');
    if (empty($frob)) {
    $flickrService->auth('write', false);
    } else {
  2. Call the function to upload the file:
  3. Once the file is uploaded, it will appear in the user's photostream.

How it works...

Flickr applications can access any user's data if the user authorizes them. For security reasons, users are redirected to Yahoo! to log into their account, and confirm access for your application. Once your application is authorized by a user, a token is stored in Flickr, and can be retrieved at any other time.

$flickrService->auth() requests permissions for the application. If the application is not yet authorized by the user, he/she will be redirected to Flickr. After giving the requested permissions, Flickr will redirect the user to the URL defined in the API key settings.

The redirected URL will contain a parameter frob. If present, $flickrService->auth_getToken($frob); is executed to get the token and store it in session. Future calls within the session lifetime will not require further calls to Flickr. If the session is expired, the token will be requested from Flickr service, transparent to the end user.

There's more...

Successful authentication allows you to access other operations that you would not be able to access using regular authentication.

Gaining permissions

There are different levels of permissions that the service can request. You should not request more permissions than your application will use.

API call

Permission level

$flickrService->auth('read', false);

Permissions to read users' files, sets, collections, groups, and more.

$flickrService->auth('write', false);

Permissions to write (upload, create new, and so on).

$flickrService->auth('delete', false);

Permissions to delete files, groups, associations, and so on.

Choosing between synchronous and asynchronous upload

There are two functions that perform a file upload:


The first function continues execution only after the file has been accepted and processed by Flickr. The second function returns after the file has been submitted, but not necessarily processed.

Why would you use the asynchronous method? Flickr service may have a large queue of uploaded files waiting to be processed, and your application might timeout while it's waiting. If you don't need to access the uploaded file right after it was uploaded, you should use the asynchronous method.

See also

  • Getting recent Flickr photos
  • Uploading DAM files to Flickr

Uploading DAM files to Flickr

In this recipe, we will make use of our knowledge of the Flickr API and the phpFlickr interface to build a Flickr upload service into DAM. We will create a new action class, which will add our functionality into a DAM file list and context menus.

Getting ready

For simplicity, we will skip the process of creating the extension. You can download the extension dam_flickr_upload and view the source code. We will examine it in more detail in the How it works... section.

How to do it...

  1. Sign up for Flickr, and request an API key if you haven't already done so.
  2. After you receive your key, click Edit key details.
    TYPO3 4.3 Multimedia Cookbook
  3. Fill in the application title and description as you see fit. Under the call back URL, enter the web path to the dam_flickr_upload/mod1/index.php file. For example, if your domain is http://domain.com/, TYPO3 is installed in the root of the domain, and you installed dam_flickr_upload in the default local location under typo3conf, then enter http://domain.com/typo3conf/ext/dam_flickr_upload/mod1/index.php
  4. You're likely to experience trouble with the callback URL if you're doing it on a local installation with no public URI.

  5. Install dam_flickr_upload. In the Extension Manager, under the extension settings, enter the Flickr API key and the secret key you have received.
  6. Go to the Media | File module, and click on the control button next to a file.
    TYPO3 4.3 Multimedia Cookbook
  7. Alternatively, select Send to Flickr in the context menu, which appears if you click on the file icon, as seen in the following screenshot:

    TYPO3 4.3 Multimedia Cookbook

  8. A new window will open, and redirect you to Flickr, asking you to authorize the application for accessing your account. Confirm the authorization by clicking the OK, I'LL AUTHORIZE IT button.

    TYPO3 4.3 Multimedia Cookbook

  9. The file will be uploaded, and placed into your photostream on Flickr.
  10. Subsequent uploads will no longer need explicit authorization. A window will come up, and disappear after the file has been successfully uploaded.

How it works...

Let's examine in detail how the extension works. First, examine the file tree. The root contains the now familiar ext_tables.php and ext_conf_template.txt files.The Res directory contains icons used in the DAM. The Lib directory contains the phpFlickr library. The Mod1 directory contains the module for uploading.


This file contains the global extension configuration variables. The two variables defined in this file are the Flickr API key and the Flickr secret key. Both of these are required to upload files.


As was mentioned previously, ext_tables.php is a configuration file that is loaded when the TYPO3 framework is initializing.

tx_dam::register_action ('tx_dam_action_flickrUpload', 'EXT:dam_

This line registers a new action in DAM. Actions are provided by classes extending the tx_dam_actionbase class, and define operations that can be performed on files and directories. Examples of actions include view, cut, copy, rename, delete, and more. The second parameter of the function defines where the action class is located.

['allowedExtensions'] = array('avi', 'wmv', 'mov', 'mpg', 'mpeg',
'3gp', 'jpg', 'jpeg', 'tiff', 'gif', 'png');

We define an array of file types that can be uploaded to Flickr. This is not hardcoded in the extension, but stored in ext_tables.php, so that it can be overwritten by extensions wanting to limit or expand the functionality to other file types.


This file defines the action class.

var $typesAvailable = array('control', 'context');

The $typesAvailable array defines the context in which the functionality can be used. In this case, we are allowing it to be used in Control setting (in the file list), and in the context menu. Other options include icon, button, globalcontrol, and multi. Refer to the DAM manual and source code to see how these can be used.

function isPossiblyValid($type, $itemInfo = NULL, $env = NULL)

This function returns TRUE if the rendering type is present in typesAvailable. Otherwise, it returns FALSE, and the action is made unavailable in the context.

function isValid($type, $itemInfo = NULL, $env = NULL)

This function is called for each individual file, and performs a check to see if the functionality should be enabled for the file. In our case, we check if the file extension is one of the allowed extensions:

$valid = in_array(strtolower($this->itemInfo['file_extension']),
['allowedExtensions']) ? TRUE : FALSE;

If the function returns TRUE, the action will be enabled for the specific file.

function getIcon($addAttribute = '')

The icon used by the action depends on if the action is enabled or disabled. If it is disabled, we show it visually by rendering a grayed out icon.

function getLabel()

This function returns a short label for the action.

function _getCommand()

This function returns a JavaScript action that is executed when the user clicks on the icon. In our case, it opens a new window, calling  mod1/index.php with parameters corresponding to the file we chose to upload.


This module establishes a connection with Flickr through the phpFlickr library, authenticates the request, and uploads the file.


Init() function initializes the class, and checks for the presence of the Flickr API key and the secret key. It also saves the parameters that have been passed in with the module call


This function performs Flickr authentication, as described in the recipe above. As the request could be redirected to Flickr for further authentication, this function saves the parameters passed into the module in the backend user session. It is done using the functions of the retrieve the information.


Assuming everything else went well, the main function simply calls the sync_upload function of the phpFlickr library to upload the file synchronously and report any errors. Another way the file can be uploaded is by using the async_upload function, which sends the request to Flickr, and proceeds without waiting for Flickr to index and store the file.

See also

  • Getting recent Flickr photos
  • Uploading files to Flickr

Reading list of movies from YouTube API

Working with the YouTube API is very similar to Flickr. We will use the Zend_Gdata library, which we can place in the lib directory. Let's now take a look at a simple task of pulling up the recent videos posted today.

Zend_Gdata is part of the Zend Framework, but can be downloaded separately from http://framework.zend.com/download/gdata.

Getting ready

We will only cover the essential code. It's up to the reader to place the code wherever appropriate, and make sure all the needed libraries are included.

Before you start, make sure that the path to the directory holding the Zend library is in your PHP include path.

How to do it...

  1. Load the required files:
    require_once 'Zend/Loader.php';
  2. Set search parameters and send the request to YouTube:
    // Initialize class
    $youTubeService = new Zend_Gdata_YouTube();
    $query = $youTubeService->newVideoQuery();
    // Set search keyword/phrase
    // Set start index
    // Set maximum number of results
    // Set search types
    $query->setFeedType('most viewed');
    // Set search time
    // Issue a query
    $feed = $youTubeService->getVideoFeed($query);
  3. Parse the resulting data:
    foreach ($feed as $videoEntry) {
    echo 'Video: ' . $videoEntry->getVideoTitle() . "n";
    echo 'Video ID: ' . $videoEntry->getVideoId() . "n";
    echo 'Updated: ' . $videoEntry->getUpdated() . "n";
    echo 'Description: ' . $videoEntry->getVideoDescription() .
    echo 'Category: ' . $videoEntry->getVideoCategory() . "n";
    echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) .
    echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() .
    echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() .
    echo 'Duration: ' . $videoEntry->getVideoDuration() . "n";
    echo 'View count: ' . $videoEntry->getVideoViewCount() . "n";
    echo 'Rating: ' . $videoEntry->getVideoRatingInfo() . "n";
    echo 'Geo Location: ' . $videoEntry->getVideoGeoLocation() .
    echo 'Recorded on: ' . $videoEntry->getVideoRecorded() . "n";
    foreach ($videoEntry->mediaGroup->content as $content) {
    if ($content->type === "video/3gpp") {
    echo 'Mobile RTSP link: ' . $content->url . "n";
    echo "Thumbnails:n";
    $videoThumbnails = $videoEntry->getVideoThumbnails();
    foreach($videoThumbnails as $videoThumbnail) {
    echo $videoThumbnail['time'] . ' - ' . $videoThumbnail['url'];
    echo ' height=' . $videoThumbnail['height'];
    echo ' width=' . $videoThumbnail['width'] . "n";

How it works...

The Zend_Gdata objects encapsulate much of the functionality, providing us convenient objects for working with the results. We provide our parameters, mainly the time span, sorting, limits on the results, and a keyword to search by, and the YouTube API returns a list of videos matching the criteria.

The $feed variable is an object of the Zend_Gdata_YouTube_VideoFeed class, which in turn is a collection of objects of the Zend_Gdata_YouTube_VideoEntry class. The latter has easy getter methods that we can use to get the information we need—such as video ID, title, description, category, thumbnail, and more.

There's more...

The API offers other options for narrowing down the selection of videos for a list. You can select the videos by placing restriction such as filters.


There are of course more filters than the ones we used. Here are some more functions you can use to set limits on results:

API call



Sets the list of the authors


Sets the array of categories


Sets the parameter to return videos of a specific format


Sets the location parameter for the query


Sets the location-radius parameter for the query


Sets the number of results to be returned


Sets the value of the orderby parameter


Sets the safeSearch parameter to either 'none',

'moderate' or 'strict'.


Sets the start index for the search results


Sets the time period over which this query should apply ('today', 'this_week', 'this_month', or 'all_time')


Sets the value of the uploader parameter


Sets the formatted video query (vq) URL param value

See also

  • Authenticating requests to YouTube API

Authenticating requests to YouTube API

Authentication with YouTube is very similar to authentication with Flickr covered in the Uploading DAM files to Flickr recipe, so we will skip on the details. It follows the same pattern of token pass back.

Getting ready

Make sure you have all the required classes already loaded (see Step 1 of How to do it... in the recipe Reading list of movies from YouTube API). In addition to the other two classes, load the Authentication library:


How to do it...

  1. First, you need to generate a URL to send the user to YouTube to provide authentication. The URL can be generated using the following method:
    $scope = 'http://gdata.youtube.com';
    $secure = false;
    $session = true;
    $returnURL = 'http://'. $_SERVER['HTTP_HOST']
    . $_SERVER['PHP_SELF'];
    $url = Zend_Gdata_AuthSub::getAuthSubTokenUri($returnURL,
    $scope, $secure, $session);
  2. Upon the user's return from YouTube, the request will contain a GET parameter with the token.
    $token = t3lib_div::_GET('token');
    if (isset($token)) {
    try {
    $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken
    } catch (Zend_Gdata_App_Exception $e) {
    $_SESSION['sessionToken'] = $sessionToken;

How it works...

After the URL is generated, the user needs to click it, and provide his or her credentials to YouTube. YouTube will confirm that the user wants to give our application access to his or her data.

TYPO3 4.3 Multimedia Cookbook

Assuming the user clicks yes, they will be redirected back to our application, where we will accept the token and store it in the user's session.

There's more...

Once you have successfully authenticated with YouTube, you can perform various actions that you couldn't do before. For example, you can post comments, manipulate playlists, tag videos, and most importantly, upload videos. The Zend_Gdata package provides enough information to get you started. As an exercise, try to recreate the dam_flickr_upload extension, but to upload a video to YouTube!

See also

  • Reading list of movies from YouTube API
  • Uploading DAM files to Flickr


In this article, we covered:

  • Getting recent Flickr photos
  • Uploading files to Flickr
  • Uploading DAM files to Flickr
  • Reading a list of movies from the YouTube API
  • Authenticating requests to the YouTube API


If you have read this article you may be interested to view :

You've been reading an excerpt of:

TYPO3 4.3 Multimedia Cookbook

Explore Title