<?php if (!defined('PmWiki')) exit();

/**************************************************************************

    Copyright 2014-2015 Kory Roberts (kaptainkory@gmail.com).
    
    This file is flickrgallery.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 recipe creates a thumbnail gallery of flickr images with the
    following features:
        * Very customizable.
        * Integrates with lightbox (or slimbox).

    This recipe requires the phpFlickr API kit by Dan Coulter:
        http://phpflickr.com

    Optionally, this recipe integrates easily with lightbox (or slimbox):
        http://www.huddletogether.com/projects/lightbox2
        http://www.digitalia.be/software/slimbox2
 
    For more information, please see the online documentation at
        http://www.pmwiki.org/wiki/Cookbook/FlickrGallery

**************************************************************************/

##### Version #####
$RecipeInfo['FlickrGallery']['Version'] = '2015-01-01';

##### Variables #####
SDVA($FlickrGallery, array(
	'FlickrAPI' => NULL,
	'FlickrSecret' => NULL,
	'DieOnError' => false,
	'EnableCache' => false,
	'CacheType' => 'fs',
	'CachePath' => $_SERVER['DOCUMENT_ROOT'] . '/cache',
	'HTMLWrapper'=> array('<div class="flickrgallery">', '</div>'),
	# $FlickrGallery['HTML'] options:
	# {{URL_*}} returns a flickr URL of a particular size: square, medium, etc.
	# {{*}} returns a flickr API response argument value for a <photo ... />.
	# {{S_*}} returns "sanitized" html code of above for safe use in lightbox.
	# {{D_*}} passes a directive argument directly into the HTML template.
	# {{F_*}} executes a user defined function, but is tricky to use.
	'HTML' => 	'<a href="{{URL_medium}}" title="{{S_title}}" rel="lightbox-set">
				<img border="0" alt="{{S_title}}" title="{{S_title}}" src="{{URL_square}}" />
				</a>',
	'HTMLErrorWrapper' => 	array('<p style="color: red; font-weight: bold;">- ', ' -</p>'),
));

SDVA($FlickrAPI, array(
	'Method' => 'flickr.photos.getRecent',
));

##### Initialize #####
FlickrGalleryInit();

##### Functions #####
function FlickrGalleryInit () {
	Markup_e('FlickrGallery', 'directives', '/\\(:flickrgallery\\s*(.*?):\\)/', "FlickrGallery(PSS(\$m[1]))");
}

function FlickrGallery($inpt=NULL) {
	global $FarmD, $FlickrGallery, $FlickrAPI;
	include_once("$FarmD/cookbook/phpFlickr/phpFlickr.php");
	$fg = $FlickrGallery;
	$fa = $FlickrAPI;
	$args = ParseArgs($inpt);
	if (!empty($args[''][0])) {
		$fa['Method'] = $args[''][0];
	}
	elseif (!empty($args['Method'])) {
		$fa['Method'] = $args['Method'];
	}
	elseif (!empty($args['method'])) {
		$fa['Method'] = $args['method'];
	}
	$fa_call = str_replace('flickr.', '', $fa['Method']);
	unset($fa['Method']);
	$args_keys = array_keys($args);
	foreach ($args_keys as $k) {
		$fa[$k] = $args[$k];
	}
	$f = new phpFlickr($fg['FlickrAPI'], $fg['FlickrSecret'], $fg['DieOnError']);
	if ($fg['EnableCache'] == true) {
		$f->enableCache($fg['CacheType'], $fg['CachePath']);
	}
	$photos = $f->call('flickr.' . $fa_call, $fa);
	if (@$photos['photos']['total'] != 0) {
		$g = 'photos';
	}
	elseif (@$photos['photoset']['total'] != 0) {
		$g = 'photoset';
	}
	else {
		return FlickrGalleryError($f, 'no Flickr images available for display');
	}
	foreach ($photos[$g]['photo'] as $photo) {
		$html_build = preg_replace_callback('/{{URL_(.*?)}}/i', function($match) use ($f, $photo) {
			return $f->buildPhotoURL(@$photo, @$match[1]);
		}, $fg['HTML']);
		$html_build = preg_replace_callback('/{{S_(.*?)}}/i', function($match) use ($photo) {
			if (is_array(@$photo[@$match[1]]) and array_key_exists('_content', @$photo[@$match[1]])) {
				return htmlspecialchars(@$photo[@$match[1]]['_content']);
			}
			else {
				return htmlspecialchars(@$photo[@$match[1]]);
			}
		}, $html_build);
		$html_build = preg_replace_callback('/{{D_(.*?)}}/i', function($match) use ($args) {
			return htmlspecialchars(@$args[@$match[1]]);
		}, $html_build);
		$html_build = preg_replace_callback('/{{F_(.*?)}}/mi', function($match) use ($photo) {
			return call_user_func(@$match[1], $photo);
		}, $html_build);
		$html_build = preg_replace_callback('/{{(.*?)}}/i', function($match) use ($photo) {
			return @$photo[@$match[1]];
		}, $html_build);
		@$html_out .= $html_build;
	}
	return Keep($fg['HTMLWrapper'][0] . $html_out . $fg['HTMLWrapper'][1]);
}

function FlickrGalleryError($f, $m) {
	global $FlickrGallery;
	if ($f->getErrorCode()) {
		$m = 'flickr API error ' . $f->getErrorCode() . ': ' . $f->getErrorMsg();
	}
	return Keep($FlickrGallery['HTMLErrorWrapper'][0] . $m . $FlickrGallery['HTMLErrorWrapper'][1]);
}