<?php
/* $Id: picasa.module,v 1.1 2007/04/09 02:10:35 cyberswat Exp $ */

/**
 * @file
 * Allows for the display of albums, thumbnails and images stored at Google's
 * http://picasaweb.google.com/ utilizing the Picasa API
 * http://code.google.com/apis/picasaweb/overview.html
 * 
 * Modifications by james@kiwicart.co.nz - using picasaweb slideshow instead
 * of lists of photo thumbnails.
 *
 * @author Kevin Bridges
 * @link http://kevinbridges.org/
 */

/**
 * Picasa API URL
 */
define("PICASA_API_URL", "http://picasaweb.google.com/data/feed/api/");

/**
 * Picasa Web Album Title - displayed on the albums overview page.
 */
define("PICASA_WEB_ALBUM_TITLE", variable_get('picasa_album_title', 'Galleries'));
/**
 * Picasa Web Album Thumbnail Size - The size of the thumbnails while looking
 * at albums.
 */
define("PICASA_ALBUM_THUMBNAIL_SIZE", 160);

/**
 * Picasa Thumbnail Size - The size of the thumbnails when viewing a specific
 * album.
 */
define("PICASA_THUMBNAIL_SIZE", 144);

/**
 * Picasa Image Size - The size of the final image.  Google restricts this to
 * a maximum of 800 pixels.
 */
define("PICASA_IMAGE_SIZE", 800);

/**
 * Implementation of hook_menu().
 *
 * @return array
 */
function picasa_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
    'path' => 'admin/settings/picasa',
    'title' => t('Picasa Settings'),
    'description' => t('Picasa Settings page.'),
    'callback' => 'drupal_get_form',
    'callback arguments' => 'picasa_admin_settings',
    'access' => user_access('administer picasa'),
    );
  }
  $items[] = array('path' => 'albums',
  'title' => t('Web Albums'),
  'callback' => 'picasa_web_albums',
  'type' => MENU_LOCAL_TASK,
  'access' => user_access('view picasa'),
  'weight' => 0,
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 * @return array
 */
function picasa_perm() {
  return array('view picasa','administer picasa');
}

/**
 * Central function to display Picasa information.  Adds the stylesheet and
 * calls the appropriate display function based on the types of args available.
 *
 * @return string
 */
function picasa_web_albums() {
  // add picasa.css to the template.
  $cssPath = drupal_get_path('module', 'picasa') .'/picasa.css';
  drupal_add_css($cssPath, 'module', 'all', FALSE);

  if(arg(2)) {
    // arg(2) is the image id number
    $output = picasa_display_album_image();
  } elseif(arg(1) ) {
    // arg(1) is the album name
    $output = picasa_display_album_contents();
  } else {
    // No args so display all albums
    $output = picasa_display_albums();
  }
  return $output;
}

/**
 * Displays an overview of the albums from a Picasa web account.
 *
 * @return string
 */
function picasa_display_albums() {
  global $base_url;
  // generate the api url call and save the data as an array.
  $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '');
  $apiCall .= '?kind=album';
  $picasa = picasa_parse_rpc($apiCall);

  // Not interested in the feed information or icons.  Interested in the entries
  // that represent each album.
  $entries = $picasa['FEED'][0]['ENTRY'];

  // Loop through the entries and generate the display output.
  // output reflects the layout presented on Picasaweb.
  $output = '<ul id="picasa_albums">';
  $thumbSize = variable_get('PICASA_ALBUM_THUMBNAIL_SIZE',160);
  foreach($entries as $entry) {

    if ($entry['GPHOTO:NUMPHOTOS'][0]['VALUE'] == 0) {
			continue;
		}

    $attributes = $entry['MEDIA:GROUP'][0]['MEDIA:THUMBNAIL'][0]['ATTRIBUTES'];
    $title = $entry['TITLE'][0]['VALUE'].' (';
    $title .= $entry['GPHOTO:NUMPHOTOS'][0]['VALUE'].')';
    $published = $entry['PUBLISHED'][0]['VALUE'];
    $date = explode("-", substr($published,0,10));
    $time = explode(":", substr($published,11,8));
    $date = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
    $url = $attributes['URL'];

		$description = $entry['MEDIA:GROUP'][0]['MEDIA:DESCRIPTION'][0]['VALUE'];

    $image = str_replace("imgmax=160", "imgmax=".$thumbSize, $url);
    $link = 'albums/'.$entry['GPHOTO:NAME'][0]['VALUE'];

    $output .=
      '<li>'
      . l("<img src=\"$image\">", $link,NULL,NULL,NULL,TRUE,TRUE)
      . '<h3>'
      . l($title, $link,NULL,NULL,NULL,TRUE,TRUE)
      . '</h3>'
      . '<p>' . date('j M Y', $date) . '</p>'
			. ($description ? '<p>' . htmlentities($description) . '</p>' : '')
      . '</li>'
    ;

    # $image = str_replace("imgmax=160", "imgmax=".$thumbSize, $url);
    # $output .= '<div class="container'.$thumbSize.'">';
    # $output .= '<div class="title'.$thumbSize.'">'.$title.'</div>';
    # $output .= '<div class="thumbnail'.$thumbSize.'">';
    # $image = '<img src="'.$image.'" />';
    # $link = 'albums/'.$entry['GPHOTO:NAME'][0]['VALUE'];
    # $output .= l($image,$link,NULL,NULL,NULL,TRUE,TRUE);
    # $output .= '</div>';
    # $output .= '<div class="summary'.$thumbSize.'">'.date('M j, Y',$date);
    # $output .= '</div>';
    # $output .= '</div>';
  }
  $output .='</ul>';

  // set the pages title
  drupal_set_title(PICASA_WEB_ALBUM_TITLE);

  return $output;
}

/**
 * Displays the contents of a Picasa web album.
 *
 * @return string
 */
function picasa_display_album_contents() {
  global $base_url;

  $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '').'/album/'.arg(1).'?kind=tag';
  $picasa = picasa_parse_rpc($apiCall);
  // Loop through the entries and generate the display output.
  # $entries = $picasa['FEED'][0]['ENTRY'];

  $captions = false;

  $album_title = arg(1);
	$page_title = $picasa['FEED'][0]['TITLE'][0]['VALUE'];
	$description = $picasa['FEED'][0]['SUBTITLE'][0]['VALUE'];

  $output = '<div id="picasa_albums">';
  $output .= '<div id="picasa_slideshow">';
	if ($description) {
		$output .= '<p>' . htmlentities($description) . '</p>';
	}
  $output .=
    '<embed type="application/x-shockwave-flash"'
    . ' src="http://picasaweb.google.com/s/c/bin/slideshow.swf" width="'
		. variable_get('picasa_slideshow_width', '600')
		. '" height="'
		. variable_get('picasa_slideshow_height', '400')
		. '"'
    . ' flashvars="'
    . 'host=picasaweb.google.com'
    . (
      $captions
      ? '&captions=0'
      : ''
    )
    . '&RGB=0xFFFFFF'
    . '&feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2F'
		. variable_get('picasa_username', '')
		. '%2Falbum%2F'
    . urlencode($album_title)
    . '%3Fkind%3Dphoto%26alt%3Drss'
    . '" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>'
  ;
  $output .= '<p><a href=".">Back to ' . PICASA_WEB_ALBUM_TITLE . '</a></p>';
  $output .= '</div>';
  $output .= '</div>';

  // generate the api url call and save the data as an array.
  # $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '');
  # $apiCall.= '/album/'.arg(1).'?kind=photo';
  # $picasa = picasa_parse_rpc($apiCall);
  // Loop through the entries and generate the display output.
  # $entries = $picasa['FEED'][0]['ENTRY'];
  # $output = '<div id="picasa_albums">';
  # $thumbSize = variable_get('PICASA_THUMBNAIL_SIZE',144);
  # foreach($entries as $entry) {
    # $attributes = $entry['MEDIA:GROUP'][0]['MEDIA:THUMBNAIL'][0]['ATTRIBUTES'];
    # $image = str_replace("imgmax=72", "imgmax=".$thumbSize, $attributes['URL']);
    # $summary = $entry['SUMMARY'][0]['VALUE'];
    # $output .= '<div class="container'.$thumbSize.'">';
    # $output .= '<div class="title'.$thumbSize.'">'.$entry['TITLE'][0]['VALUE'];
    # $output .= '</div>';
    # $output .= '<div class="thumbnail'.$thumbSize.'">';
    # $image = '<img src="'.$image.'" />';
    # $link = 'albums/'.arg(1).'/'.$entry['GPHOTO:ID'][0]['VALUE'];
    # $title = array('title'=>str_replace('"','', $summary));
    # $output .= l($image,$link,$title,NULL,NULL,TRUE,TRUE);
    # $output .= '</div>';
    # $output .= '<div class="summary'.$thumbSize.'">'.$summary.'</div>';
    # $output .= '</div>';
  # }
  # $output .='</div>';

  // set the pages title
  $title = PICASA_WEB_ALBUM_TITLE.' - ' . $page_title;
  drupal_set_title($title);
  return $output;
}

/**
 * Displays a Picasa web album image.
 *
 * @return string
 */
function picasa_display_album_image() {
  global $base_url;
  // generate the api url call and save the data as an array.
  $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '');
  $apiCall.= '/album/'.arg(1).'/photoid/'.arg(2).'?kind=tag';
  $picasa = picasa_parse_rpc($apiCall);
  $image = $picasa['FEED'][0]['ICON'][0]['VALUE'];
  $title = $picasa['FEED'][0]['TITLE'][0]['VALUE'];
  $subtitle = $picasa['FEED'][0]['SUBTITLE'][0]['VALUE'];
  $thumbSize = variable_get('PICASA_IMAGE_SIZE',800);
  $image = str_replace("imgmax=288", "imgmax=".$thumbSize, $image);
  $output = '<div id="picasa_albums">';
    $output .= '<div class="container'.$thumbSize.'">';
    $output .= '<div class="title'.$thumbSize.'">'.$title.'</div>';
    $output .= '<div class="thumbnail'.$thumbSize.'"><img src="'.$image.'" />';
    $output .= '</div>';
    $output .= '<div class="subtitle'.$thumbSize.'">'.$subtitle.'</div>';
    $output .= '</div>';
  // set the pages title
  $title = PICASA_WEB_ALBUM_TITLE.' - '.$picasa['FEED'][0]['TITLE'][0]['VALUE'];
  drupal_set_title($title);

  return $output;
}

/**
 * Makes a remote call to the picasa api and parses the xml data into an array.
 *
 * @param $loc string
 * @return array
 */
function picasa_parse_rpc($loc){
  $contents = file_get_contents($loc);
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $contents, $vals, $index);
  xml_parser_free($parser);

  $tree = array();
  $i = 0;

  if (isset($vals[$i]['attributes'])) {
    $tree[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
    $index = count($tree[$vals[$i]['tag']])-1;
    $temp = array_merge($tree[$vals[$i]['tag']][$index],
      picasa_parse_rpc_children($vals, $i));
    $tree[$vals[$i]['tag']][$index] = $temp;
  } else {
    $tree[$vals[$i]['tag']][] = picasa_parse_rpc_children($vals, $i);
  }
  return $tree;
}
/**
 * Helper function for picasa_parse_rpc
 *
 */
function picasa_parse_rpc_children($vals, &$i) {
  $children = array(); // Contains node data
  if (isset($vals[$i]['value'])){
    $children['VALUE'] = $vals[$i]['value'];
  }

  while (++$i < count($vals)){
    switch ($vals[$i]['type']){

      case 'cdata':
        if (isset($children['VALUE'])){
          $children['VALUE'] .= $vals[$i]['value'];
        } else {
          $children['VALUE'] = $vals[$i]['value'];
        }
        break;

      case 'complete':
        if (isset($vals[$i]['attributes'])) {
          $children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
          $index = count($children[$vals[$i]['tag']])-1;

          if (isset($vals[$i]['value'])){
            $children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
          } else {
            $children[$vals[$i]['tag']][$index]['VALUE'] = '';
          }
        } else {
          if (isset($vals[$i]['value'])){
            $children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
          } else {
            $children[$vals[$i]['tag']][]['VALUE'] = '';
          }
        }
        break;

      case 'open':
        if (isset($vals[$i]['attributes'])) {
          $children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
          $index = count($children[$vals[$i]['tag']])-1;
          $temp = array_merge($children[$vals[$i]['tag']][$index],
            picasa_parse_rpc_children($vals, $i));
          $children[$vals[$i]['tag']][$index] = $temp;
        } else {
          $children[$vals[$i]['tag']][] = picasa_parse_rpc_children($vals, $i);
        }
        break;

      case 'close':
        return $children;
    }
  }
}


/**
 * Settings page.
 */
function picasa_admin_settings() {
  $form['picasa_settings'] = array(
  '#type' => 'fieldset',
  '#title' => t('Picasa Display Settings'),
  '#collapsible' => FALSE,
  '#collapsed' => FALSE,
  );
  $form['picasa_settings']['picasa_username'] = array(
  '#type' => 'textfield',
  '#title' => t('Your Picasa Web Username'),
  '#default_value' => variable_get('picasa_username', ''),
  '#size' => 70,
  '#maxlength' => 255,
  '#description' => t('The username you use at http://picasaweb.google.com/ to '.
    'view your Web Albums')
  );

  $form['picasa_settings']['picasa_album_title'] = array(
  '#type' => 'textfield',
  '#title' => t('Album title'),
  '#default_value' => variable_get('picasa_album_title', ''),
  '#size' => 70,
  '#maxlength' => 255,
  );

  $form['picasa_settings']['picasa_slideshow_width'] = array(
  '#type' => 'textfield',
  '#title' => t('Slideshow width'),
  '#default_value' => variable_get('picasa_slideshow_width', ''),
  '#size' => 10,
  '#maxlength' => 255,
  );

  $form['picasa_settings']['picasa_slideshow_height'] = array(
  '#type' => 'textfield',
  '#title' => t('Slideshow height'),
  '#default_value' => variable_get('picasa_slideshow_height', ''),
  '#size' => 10,
  '#maxlength' => 255,
  );

  $form['picasa_settings']['PICASA_ALBUM_THUMBNAIL_SIZE'] = array(
  '#type' => 'select',
  '#title' => t('Album Overview Thumbnail Size'),
  '#default_value' => variable_get('PICASA_ALBUM_THUMBNAIL_SIZE', '160'),
  '#description' => t('The maximum width of thumbnails on the albums overview '.
    'page.'),
  '#options' => array(
  '32' => '32',
  '48' => '48',
  '64' => '64',
  '160' => '160'
  )
  );
  $form['picasa_settings']['PICASA_THUMBNAIL_SIZE'] = array(
  '#type' => 'select',
  '#title' => t('Thumbnail Max Size'),
  '#default_value' => variable_get('PICASA_THUMBNAIL_SIZE', '144'),
  '#description' => t('The maximum width of thumbnails while browsing a '.
    'specific album.'),
  '#options' => array(
    '72' => '72',
    '144' => '144',
    '288' => '288',
    '320' => '320',
    '400' => '400',
    '800' => '800'
    )
  );
  $form['picasa_settings']['PICASA_IMAGE_SIZE'] = array(
  '#type' => 'select',
  '#title' => t('Image Max Size'),
  '#default_value' => variable_get('PICASA_IMAGE_SIZE', '800'),
  '#description' => t('The maximum width of the final images.  Google '.
  'restricts this to 800px.'),
  '#options' => array(
    '72' => '72',
    '144' => '144',
    '160' => '160',
    '200' => '200',
    '288' => '288',
    '320' => '320',
    '400' => '400',
    '800' => '800'
    )
  );

  return system_settings_form($form);
}

/**
 * Implementation of hook_block
 *
 */

function picasa_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Picasa Random Image');
      return $blocks;
    case 'configure':
      $form = array();
      return $form;
    case 'save':
      if ($delta == 0) {
        variable_set('picasa_block_string', $edit['picasa_block_string']);
      }
      return;
    case 'view': default:
      switch ($delta) {
        case 0:
          $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '');
          $apiCall .= '?kind=album';
          $picasa = picasa_parse_rpc($apiCall);
          $entries = $picasa['FEED'][0]['ENTRY'];
          $random = rand(1, count($entries))-1;
          $album = $entries[$random]['GPHOTO:NAME'][0]['VALUE'];
          $apiCall = PICASA_API_URL.'user/'.variable_get('picasa_username', '');
          $apiCall.= '/album/'.$album.'?kind=photo';
          $picasa = picasa_parse_rpc($apiCall);
          $entries = $picasa['FEED'][0]['ENTRY'];
          $random = rand(1, count($entries))-1;
          $imageID = $entries[$random]['GPHOTO:ID'][0]['VALUE'];
          $image = $entries[$random]['MEDIA:GROUP'][0]['MEDIA:THUMBNAIL'][0];
          $image = $image['ATTRIBUTES']['URL'];
          $image = str_replace("imgmax=72", "imgmax=144", $image);
          $block['subject'] = t('Random Image');
          $content = '<div style="text-align: center">';
          $content .= l('<img src="'.$image.'" />',
            'albums/'.$album.'/'.$imageID ,NULL,NULL,NULL,TRUE,TRUE);
          $content .= '</div>';
          $block['content'] = $content;
          break;
      }
      return $block;
  }
}
?>