<?php if (!defined('PmWiki')) exit();
/*  Copyright 2006-2007 Jon Haupt (jhaupt@gmail.com)
    This file is flickr-album.php; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  

    This script enables you to create interaction between PmWiki and Flickr. 

    You'll need a Flickr API (http://www.flickr.com/services/api/).  You'll 
    have to fill that in below.  Or you can set it in config.php (or a per-page/
    per-group customization file) by including this line before including
    flickr-album.php:
    $FlickrAPIKey = "put_your_API_key_here";

    To use this script, copy it into the cookbook/ directory
    and add the following line to config.php (or a per-page/per-group
    customization file).
    include_once("$FarmD/cookbook/flickr-album.php");

    As well, you'll need to install phpflickr (http://www.phpflickr.com), a 
    class written by Dan Coulter in PHP4 to act as a wrapper for Flickr's API.
    You can install phpFlickr anywhere that your webserver can get to it, but
    if you're only using it with PmWiki, the default location is
    /cookbook/phpFlickr.

    You'll want to enable caching of some sort unless you want it to be slow.  
    There are two options: filesystem caching and database caching.  You'll 
    need to configure one or the other.  To enable filesystem caching, simply 
    add a line to config.php like the below containing the location of a cache 
    folder you've created, and a line signifying you want to use the FS method,
    as shown below.  Make sure these appear before the include_once line.
    $FlickrFSLocation = "/var/www/foo/pmwiki/cookbook/phpFlickrCache";
    $FlickrFS = 1;
    
    To enable database caching, create a new MySQL database, add this line 
    with MySQL username and password, probably localhost, and the name of the 
    database you created (again before the include_once line):
    $FlickrDB = "mysql://user:password@localhost/dbname";

    The script will display an album of photos by a given username.
    The simplest album can be created by using the markup (:flickralbum:)
    which will create an album of 12 of the most recent photos added to flickr
    in 6 columns.  Similarly, you can do (:flickralbum user=foo:) for the most
    recent photos by the user with flickr userid foo.

    If you have lightbox working in your installation, you can also specify that
    images be displayed using lightbox by specifying lightbox=1.  Note that this
    requires additional work installing lightbox.  In order to do this, install
    Lightbox JS in an accessible folder and add the following to config.php:
    # lightbox
    $HTMLHeaderFmt['lightbox'] = "
      <script type='text/javascript' src='http://your_url/lightbox/js/prototype.js'></script>
      <script type='text/javascript' src='http://your_url/lightbox/js/scriptaculous.js?load=effects'></script>
      <script type='text/javascript' src='http://your_url/lightbox/js/lightbox.js'></script>";

    The following is a list of arguments possible for other combinations:

    Generic arguments, always apply:
    columns=? - number of columns in album
    number=? - total number of photos to show
    size=? (Square, Thumbnail, Medium, Original - note: not all photos come in every size)
    size2=? (same as above)
    lightbox=1 - Allow lightbox to control the images.

    Situation-specific arguments, specific to searches for photos by user, group, or set:
    user=? - flickr userid - for photos from a specific user
    tags=? - tags to limit by, comma-delimited
    order=recent - show most recent first
    order=interesting - show most interesting photo first
    group=? (group id) - for photos from a group photo pool
    set=? (set id) - for photos from a photoset

    Version Log:

    2007-03-05 Updated code for styling.  Now styled by class instead of by id.  Also
      changed the recipe to add three variables including the database location.
    January 2007 0.5 added lightbox controls; fixed username error
    May 2006 0.4 Began to add group options
    March 2006 0.3 Made non-username-specific albums possible
    February 2006 0.2 added global variable for API key
    January 2006 0.1 Initial Development

*/
$RecipeInfo['FlickrAlbum']['Version'] = '2007-03-05';

SDV($FlickrAPIKey, "put_your_API_key_here");
SDV($FlickrFS, 0);
SDV($FlickrDB, "mysql://user:password@localhost/dbname");
SDV($FlickrFSLocation, "/var/www/foo/pmwiki/cookbook/phpFlickrCache");

Markup("flickralbum", ">block", '/\\(:flickralbum\\s*(.*?):\\)/ei', "FlickrAlbum('$1')");

function FlickrAlbum($p) {
  global $FlickrAPIKey, $FlickrFS, $FlickrDB, $FlickrFSLocation;
  require_once("phpFlickr/phpFlickr.php");

  // Create new phpFlickr object
  $f = new phpFlickr($FlickrAPIKey,'',false);

  if ($FlickrFS == 1) {
  $f->enableCache(
   "fs",                                      /* for filesystem cache */
   "$FlickrFSLocation"          /* (for fs) */
  );
  } else {
  $f->enableCache(
   "db",                                         /* for database cache */
   "$FlickrDB"     /* (for db) */
  );
  }

  // Loop number for columns
  $i = 0;

  // Defaults
  $defaults = array (
    'columns' => 6,
    'number' => 12,
    'order' => 'recent',
    'tags' => '',
    'user' => '',
    'group' => '',
    'set' => '',
    'size' => 'square',
    'lightbox' => 0,
    'size2' => 'medium');
  $opt = array_merge($defaults, ParseArgs($p));

  // Begin output
  $output = "<div class='flickralbum'>";

  // sort out the user/set/group quandary
  $searchtype = 1;
  if ($opt['group'] != '') $searchtype = 2;
  if ($opt['set'] != '') $searchtype = 3;

  switch ($searchtype) {
    case 1:       // user
      // sort out the sorting thingy
      if ($opt['order'] == "interesting") $sort = "interestingness-desc";
      else $sort = "recent-desc";

      // If no username listed
      if ($opt['user'] == '') {
        // Run the search
        if ($opt['tags'] == '') {
          if ($opt['order'] == 'recent') $photos = $f->photos_getRecent(NULL, $opt['number']);
            else $photos = $f->interestingness_getList(NULL, NULL, $opt['number']);
          }
          else $photos = $f->photos_search(array("tags"=>$opt['tags'], "tag_mode"=>"all", "sort"=>$sort, "per_page"=>$opt['number']));
      }
        else {
          // Find the NSID of the username user=foo
          $flickrusername = $f->people_findByUsername($opt['user']);
          $nsid = $flickrusername['nsid'];

          // Get the friendly URL of the user's photos
          $photos_url = $f->urls_getUserPhotos($nsid);

          // Run the search
          $photos = $f->photos_search(array("user_id"=>$nsid, "tags"=>$opt['tags'], "tag_mode"=>"all", "sort"=>$sort, "per_page"=>$opt['number']));
        }

      if (is_array($photos['photo'])) {
      // Build the album
      foreach ($photos['photo'] as $photo) {
        // Have to fix url for each photo if no username
        if ($opt['user'] == '') $photos_url = "http://www.flickr.com/photos/".$photo['owner']."/";
        // Build image and link tags for each photo
        $output .= "<a href='";
        if ($opt['lightbox'] == 1) $output .= $f->buildPhotoURL($photo, $opt['size2'])."' rel='lightbox[flickr]' title='&lt;a href=&quot;$photos_url$photo[id]&quot;&gt;$photo[title]&lt;/a&gt;'";
        else $output .= "$photos_url$photo[id]'";
        $output .= "><img alt='$photo[title]' "."src='".$f->buildPhotoURL($photo, $opt['size'])."' />";
        $output .= "</a>";
        $i++;
          // If it reaches the end photo for $opt['columns'], insert a line break
          if ($i % $opt['columns'] == 0) $output .= "<br />";
        }   // End of user search
	 }
        break;
    case 2:    // Group
      // get the name of the group, and the nsid of the user, if applicable
      $groupinfo = $f->call("flickr.groups.getInfo", array("group_id"=>$opt['group']));
      $groupname = $groupinfo[name];
      if ($opt['user'] != '') $nsid = $f->people_findByUsername($opt['user']);

      // Run the search
      $photos = $f->call("flickr.groups.pools.getPhotos", array("user_id"=>$nsid, "group_id"=>$opt['group'], "tags"=>$opt['tags'], "per_page"=>$opt['number']));
      $photos_url = "http://www.flickr.com/photos/";

      if (is_array($photos['photo'])) {
      // Build the album
      foreach ($photos['photo'] as $photo) {
        // Build image and link tags for each photo
        $output .= "<a href='";
        if ($opt['lightbox'] == 1) $output .= $f->buildPhotoURL($photo, $opt['size2'])."' rel='lightbox[flickr]' title='&lt;a href=&quot;$photos_url$photo[owner]$photo[id]/in/pool-$groupname&quot;&gt;$photo[title]&lt;/a&gt;'";
        else $output .= "$photos_url$photo[owner]$photo[id]/in/pool-$groupname'";
        $output .= "><img alt='$photo[title]' src='".$f->buildPhotoURL($photo, $opt['size'])."' />";
        $output .= "</a>";
        $i++;
          // If it reaches the end photo for the column, insert a line break
          if ($i % $opt['columns'] == 0) $output .= "<br />";
      }
      }
      break;
    case 3:    // Set
      // blah
  }  // End of switch


  // Finish output and return it
  return $output."</div>";
}