<?php
/*
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2002 Bharat Mediratta
 * 
 * This program is free software; 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 program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// Hack prevention.
if (!empty($HTTP_GET_VARS["GALLERY_BASEDIR"]) ||
		!empty($HTTP_POST_VARS["GALLERY_BASEDIR"]) ||
		!empty($HTTP_COOKIE_VARS["GALLERY_BASEDIR"])) {
	print "Security violation\n";
	exit;
}

require_once("./init.php"); 

// Hack check
if (!$gallery->user->canReadAlbum($gallery->album)) {
	header("Location: " . makeAlbumUrl());
	return;
}

if (!$gallery->album->isLoaded()) {
	header("Location: " . makeAlbumUrl());
	return;
}

if (!$page) {
	$page = $gallery->session->albumPage[$gallery->album->fields["name"]];
	if (!$page) {
		$page = 1;
	}
} else {
	$gallery->session->albumPage[$gallery->album->fields["name"]] = $page;
}

$albumName = $gallery->session->albumName;

if (!$gallery->session->viewedAlbum[$albumName]) {
	$gallery->session->viewedAlbum[$albumName] = 1;
	$gallery->album->incrementClicks();
} 

$rows = $gallery->album->fields["rows"];
$cols = $gallery->album->fields["cols"];
$numPhotos = $gallery->album->numPhotos($gallery->user->canWriteToAlbum($gallery->album));
$perPage = $rows * $cols;
$maxPages = max(ceil($numPhotos / $perPage), 1);

if ($page > $maxPages) {
	$page = $maxPages;
}

$start = ($page - 1) * $perPage + 1;
$end = $start + $perPage;

$nextPage = $page + 1;
if ($nextPage > $maxPages) {
	$nextPage = 1;
        $last = 1;
}

$previousPage = $page - 1;
if ($previousPage == 0) {
	$previousPage = $maxPages;
	$first = 1;
}

$bordercolor = $gallery->album->fields["bordercolor"];

$imageCellWidth = floor(100 / $cols) . "%";
$fullWidth="100%";

$navigator["page"] = $page;
$navigator["pageVar"] = "page";
$navigator["maxPages"] = $maxPages;
$navigator["fullWidth"] = $fullWidth;
$navigator["url"] = makeAlbumUrl($gallery->session->albumName);
$navigator["spread"] = 5;
$navigator["bordercolor"] = $bordercolor;

$breadCount = 0;
$breadtext = array();
$pAlbum = $gallery->album;
do {
  if (!strcmp($pAlbum->fields["returnto"], "no")) {
    break;
  }
  $pAlbumName = $pAlbum->fields['parentAlbumName'];
  if ($pAlbumName) {
    $pAlbum = new Album();
    $pAlbum->load($pAlbumName);
    $breadtext[$breadCount] = "アルバム：<a href=\"" . makeAlbumUrl($pAlbumName) .
      "\">" . $pAlbum->fields['title'] . "</a>";
  } else {
    //-- we're at the top! ---
    $breadtext[$breadCount] = "ギャラリー：<a href=\"" . makeGalleryUrl("albums.php") .
      "\">" . $gallery->app->galleryTitle . "</a>"; 
  }
  $breadCount++;
} while ($pAlbumName);

//-- we built the array backwards, so reverse it now ---
for ($i = count($breadtext) - 1; $i >= 0; $i--) {
	$breadcrumb["text"][] = $breadtext[$i];
}
$breadcrumb["text"][] = "<b>".$gallery->album->fields['title']."</b>";

$javascript = '
  <script type="text/javascript">
  <!--
  var statusWin;
  function showProgress() {
	statusWin = '.popup_status("progress_uploading.php").'
  }

  function hideProgress() {
	if (typeof(statusWin) != "undefined") {
		statusWin.close();
		statusWin = void(0);
	}
  }

  function hideProgressAndReload() {
	hideProgress();
	history.go(0);
  }

  function imageEditChoice(selected_select) {
	  var sel_index = selected_select.selectedIndex;
	  var sel_value = selected_select.options[sel_index].value;
	  selected_select.options[0].selected = true;
	  selected_select.blur();
	  '.popup(sel_value, 1).'
  } 
  // --> 
  </script>';

$xoopsOption['template_main'] = 'xoopsgallery_viewalbum.html';
include_once XOOPS_ROOT_PATH.'/header.php';
$xoopsTpl->assign('gallery_version', $gallery->version);

$xoopsTpl->assign('javascript', $javascript);
$xoopsTpl->assign('album_title', $gallery->album->fields['title']);
$xoopsTpl->assign('album_desc', $gallery->album->fields['description']);

function showChoice($label, $target, $args) {
    global $gallery;
    
    if (empty($args['set_albumName'])) {
	$args['set_albumName'] = $gallery->session->albumName;
    }
	return "<option value='" . makeGalleryUrl($target, $args) . "'>$label</option>";
}

$adminText = "<b>";
if ($numPhotos == 1) {  
	$adminText .= "このアルバムには1個のアイテムがあります";
} else {
	$adminText .= "このアルバムには $numPhotos 個のアイテムがあります";
	if ($maxPages > 1) {
		$adminText .= " (全 " . $maxPages . " ページ)";
	}
}

if ($gallery->user->canWriteToAlbum($gallery->album)) {
	$hidden = $gallery->album->numHidden();
	$verb = "are";
	if ($hidden == 1) {
		$verb = "is";
	}
	if ($hidden) {
		$adminText .= " ($hidden $verb hidden)";
	}
} 
$adminText .="</b>";
$adminHasCommands = false;
//$adminCommands = "<span class =\"itemPoster\">";

if ($gallery->user->canAddToAlbum($gallery->album)) {
	$adminCommands .= '<a href="#" onClick="'.popup("add_photos.php?set_albumName=" .
				$gallery->session->albumName).'">[フォトの追加]</a>&nbsp;';
	$adminHasCommands = true;
}
if ($gallery->user->canCreateSubAlbum($gallery->album)) {
	$adminCommands .= '<a href="' . doCommand("new-album", 
						array("parentName" => $gallery->session->albumName),
						 "view_album.php") .
						 '">[サブアルバムの新規作成]</a>&nbsp;';
	$adminHasCommands = true;
}

if ($gallery->user->canChangeTextOfAlbum($gallery->album)) {
	$adminCommands .= '<a href=' . makeGalleryUrl("captionator.php", 
						array("set_albumName" => $tmpAlbumName, 
						      "page" => $page, 
						      "perPage" => $perPage)) .
			'>[見出しの編集]</a>&nbsp;';
	$adminHasCommands = true;
}

if ($gallery->user->canWriteToAlbum($gallery->album)) {
	if ($gallery->album->numPhotos(1)) {
	        $adminCommands .= '<a href="#" onClick="'.popup("sort_album.php?set_albumName=" .
				$gallery->session->albumName).
				'">[並べ替え]</a>&nbsp;';
	        $adminCommands .= '<a href="#" onClick="'.popup("resize_photo.php?set_albumName=" .
				$gallery->session->albumName . "&index=all").
				'">[全てをリサイズ]</a>&nbsp;';
	        $adminCommands .= '<a href="#" onClick="'.popup("do_command.php?cmd=remake-thumbnail&set_albumName=" .
				$gallery->session->albumName . "&index=all").
				'">[サムネイルの再構築]</a>&nbsp;&nbsp;'; 
	}
        $adminCommands .= '<a href="#" onClick="'.popup("edit_appearance.php?set_albumName=" .
			$gallery->session->albumName).
			'">[アルバムの設定]</a>&nbsp;';
	$adminHasCommands = true;
}

if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($gallery->album)) {
        $adminCommands .= '<a href="#" onClick="'.popup("album_permissions.php?set_albumName=" .
			$gallery->session->albumName).
			'">[アクセス権]</a>&nbsp;';
		$adminHasCommands = true;
}

$adminCommands .= '<a href=' . 
	 makeGalleryUrl("slideshow.php",
		array("set_albumName" => $albumName)) .
	'>[スライドショー]</a>&nbsp;';

if (!$GALLERY_EMBEDDED_INSIDE) {
	if ($gallery->user->isLoggedIn()) {
	        $adminCommands .= "<a href=" .
					doCommand("logout", array(), "view_album.php", array("page" => $page)) .
				  ">[ログアウト]</a>";
	} else {
		$adminCommands .= '<a href="#" onClick="'.popup("login.php").'">[login]</a>';
	} 
}
//$adminCommands .= "</span>";
$xoopsTpl->assign('adminbox', $adminText.'<br />'.$adminCommands);
$xoopsTpl->assign('adminHasCommands', $adminHasCommands);
$breadcrumb["top"] = true;
if (strcmp($gallery->album->fields["returnto"], "no") 
   || ($gallery->album->fields["parentAlbumName"])) {
	ob_start();
	include($GALLERY_BASEDIR . "layout/breadcrumb.inc");
	$xoopsTpl->assign('breadcrumb', ob_get_contents());
	ob_end_clean();
}
ob_start();
include($GALLERY_BASEDIR . "layout/navigator.inc");
$xoopsTpl->assign('navbar', ob_get_contents());
ob_end_clean();

$image_handler =& xoops_getmodulehandler('image');
$album_images =& $image_handler->getObjects(new Criteria('image_albumdir', $gallery->session->albumName), true);
$numPhotos = $gallery->album->numPhotos(1);
if ($numPhotos) {

	$rowCount = 0;

	// Find the correct starting point, accounting for hidden photos
	$rowStart = 0;
	$cnt = 0;
	while ($cnt < $start) {
		$rowStart = getNextPhoto($rowStart);
		$cnt++;
	}

	while ($rowCount < $rows) {

		/* Do the picture row */
		$i = $rowStart;
		$j = 1;
		$pictures = array();
		while ($j <= $cols && $i <= $numPhotos) {
			$picture = array();
			//-- put some parameters for the wrap files in the global object ---
			//$gallery->html_wrap['borderColor'] = $bordercolor;
			//$gallery->html_wrap['borderWidth'] = $borderwidth;
			//$gallery->html_wrap['pixelImage'] = $imageDir . "/pixel_trans.gif";
			//$scaleTo = $gallery->album->fields["thumb_size"];
			//list($iWidth, $iHeight) = $gallery->album->getThumbDimensions($i, $scaleTo);
			//if ($iWidth == 0) {
			//    $iWidth = $gallery->album->fields["thumb_size"];
			//}
			//if ($iHeight == 0) {
			//    $iHeight = 100;
			//}
			//$gallery->html_wrap['thumbWidth'] = $iWidth;
			//$gallery->html_wrap['thumbHeight'] = $iHeight;

			$id = $gallery->album->getPhotoId($i);
			$picture['index'] = $i;
			if ($gallery->album->isMovie($id)) {
				$picture['image'] = $gallery->album->getThumbnailTag($i);
				$picture['link'] = $gallery->album->getPhotoPath($i);
			} elseif ($gallery->album->isAlbumName($i)) {
				$myAlbumName = $gallery->album->isAlbumName($i);
				$myAlbum = new Album();
				$myAlbum->load($myAlbumName);

				$picture['image'] = $myAlbum->getHighlightAsThumbnailTag($scaleTo);
				$picture['link'] = makeAlbumUrl($myAlbumName);

			} else {
				$photo = $gallery->album->getPhoto($i);
				$picture['image'] = $gallery->album->getThumbnailTag($i);
				$xoops_imageid = $photo->image->getXoopsImageId();
				$xoops_imageid = !empty($xoops_imageid) ? intval($xoops_imageid) : 0;
				$picture['link'] = makeAlbumUrl($gallery->session->albumName, $id, array('xoops_imageid' => $xoops_imageid));
			}
			$pictures[] =& $picture;
			unset($picture);
			$j++; 
			$i = getNextPhoto($i);
		}
	
		/* Now do the caption row */
		$captions = array();
		$adminforms = array();
		$i = $rowStart;
		$j = 1;
		while ($j <= $cols && $i <= $numPhotos) {
			
			if ($gallery->album->isAlbumName($i)) {
			    $iWidth = $gallery->album->fields['thumb_size'];
			} else {
			    list($iWidth, $iHeight) = $gallery->album->getThumbDimensions($i);
			}

			// put form outside caption to compress lines

			$adminform = '';
            if (($gallery->user->canDeleteFromAlbum($gallery->album)) ||
                                    ($gallery->user->canWriteToAlbum($gallery->album)) ||
                                    ($gallery->user->canChangeTextOfAlbum($gallery->album))) {
				$showAdminForm = 1;
			} else { 
				$showAdminForm = 0;
			}
			if ($showAdminForm) {
				$adminform = makeFormIntro("view_album.php", array("name" => "image_form_$i")); 
			}
			$caption = array();
			$id = $gallery->album->getPhotoId($i);
			if ($gallery->album->isHidden($i)) {
				$caption['status'] = '('._MD_GALLERY_HIDDEN.')';
			}
			if ($gallery->album->isAlbumName($i)) {
				$myAlbum = new Album();
				$myAlbum->load($gallery->album->isAlbumName($i));
				$myDescription = $myAlbum->fields['description'];
				$caption['title'] = _MD_GALLERY_ALBUM.': '.$myAlbum->fields['title'];
				if ($myDescription != "No description") {
					$caption['description'] = $myDescription;
				}
				$caption['last_update'] = formatTimestamp($myAlbum->getLastModificationTime(), 'm');
				$caption['num_items'] = $myAlbum->numPhotos($gallery->user->canWriteToAlbum($myAlbum));
				if (!(strcmp($gallery->album->fields["display_clicks"] , "yes")) && ($myAlbum->getClicks() > 0)) {
				   	$caption['num_views'] = $myAlbum->getClicks();
				}
			} else {
				$caption['title'] = $gallery->album->getCaption($i);
				$caption['index'] = $i;
				$photo = $gallery->album->getPhoto($i);
				$xoops_imageid = $photo->image->getXoopsImageId();
				// indicate with * if we have a comment for a given photo
				if (!empty($xoops_imageid) && is_object($album_images[$xoops_imageid])) {
					if (($xoopsModuleConfig['com_rule'] > 0) && ($gallery->album->fields["public_comments"] = 'yes')) {
						$caption['num_comments'] = $album_images[$xoops_imageid]->getVar('image_comments');
					}
					$caption['last_update'] = formatTimestamp($album_images[$xoops_imageid]->getVar('image_created'), 'Y-m-d H:i');

$itemCaptureDate = $gallery->album->getItemCaptureDate($i);
$hours = $itemCaptureDate["hours"];
$minutes = $itemCaptureDate["minutes"];
$seconds = $itemCaptureDate["seconds"];
$mon = $itemCaptureDate["mon"];
$mday = $itemCaptureDate["mday"];
$year = $itemCaptureDate["year"];
					$caption['captureupdate'] = $year . "-" . $mon . "-" . $mday . " " . $hours . ":" . $minutes;
$checknochange = $album_images[$xoops_imageid]->getVar('image_created') - strtotime($caption['captureupdate'].":".$seconds);
if ($checknochange < 180 && $checknochange > -180){$caption['captureupdate'] = "------";}
				}
				if (!(strcmp($gallery->album->fields["display_clicks"] , "yes")) && ($gallery->album->getItemClicks($i) > 0)) {
					$caption['num_views'] = $gallery->album->getItemClicks($i);
				}
			}

			if ($showAdminForm) {
				if ($gallery->album->isMovie($id)) {
					$label = "ムービー";
				} elseif ($gallery->album->isAlbumName($i)) {
					$label = "アルバム";
				} else {
					$label = "フォト";
				}
				$adminform .= "<select style='FONT-SIZE: 10px;' name='s' ".
					"onChange='imageEditChoice(document.image_form_$i.s)'>";
				$adminform .= "<option value=''><< $label の編集>></option>";
			}
			if ($gallery->user->canChangeTextOfAlbum($gallery->album)) {
				if ($gallery->album->isAlbumName($i)) {
					if ($gallery->user->canChangeTextOfAlbum($myAlbum)) {	
						$adminform .= showChoice("タイトルの編集", 
							"edit_field.php", 
							array("set_albumName" => $myAlbum->fields["name"],
								"field" => "title"));
						$adminform .= showChoice("詳細の編集",
							"edit_field.php",
							array("set_albumName" => $myAlbum->fields["name"],
								"field" => "description"));
					}
					if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($myAlbum)) {
						$adminform .= showChoice("アルバムフォルダ名変更",
							"rename_album.php",
							array("set_albumName" => $myAlbum->fields["name"],
							      "index" => $i));
					}
				} else {
					$adminform .= showChoice("見出しの編集", "edit_caption.php", array("index" => $i));
				}
			}
			if ($gallery->user->canWriteToAlbum($gallery->album)) {
				if (!$gallery->album->isMovie($id) && !$gallery->album->isAlbumName($i)) {
					$adminform .= showChoice("サムネイルの編集", "edit_thumb.php", array("index" => $i));
					$adminform .= showChoice("$label の回転", "rotate_photo.php", array("index" => $i));
				}
				if (!$gallery->album->isMovie($id)) {
					$adminform .= showChoice("$label をギャラリーに表示する", "highlight_photo.php", array("index" => $i));
				}
				if ($gallery->album->isAlbumName($i)) {
				        $myAlbumName = $gallery->album->isAlbumName($i);

					$adminform .= showChoice("カウンタのリセット", "do_command.php",
						array("cmd" => "reset-album-clicks",
						      "set_albumName" => $myAlbumName,
							"return" => urlencode(makeGalleryUrl("view_album.php"))));
				}
				$adminform .= showChoice("$label の移動", "move_photo.php", array("index" => $i));
				if ($gallery->album->isHidden($i)) {
					$adminform .= showChoice("$label の閲覧", "do_command.php", array("cmd" => "show", "index" => $i));
				} else {
					$adminform .= showChoice("$label を隠す", "do_command.php", array("cmd" => "hide", "index" => $i));
				}
			}
			if ($gallery->user->canDeleteFromAlbum($gallery->album)) {
				if($gallery->album->isAlbumName($i)) { 
					if($gallery->user->canDeleteAlbum($myAlbum)) {
						$adminform .= showChoice("$label の削除", "delete_photo.php",
							array("id" => $myAlbum->fields["name"],
							      "albumDelete" => 1));
					}
				} else {
					$adminform .= showChoice("$label の削除", "delete_photo.php",
						   array("id" => $id));
				}
			}
			if($gallery->album->isAlbumName($i)) { 
			    if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($myAlbum)) {
				$adminform .= showChoice("アクセス権",
					   "album_permissions.php",
					   array("set_albumName" => $myAlbum->fields["name"]));
			    }
			}
			if ($showAdminForm) {
				$adminform .= '</select></form>';
			}
			$captions[] =& $caption;
			$adminforms[] =& $adminform;
			unset($caption, $adminform);
			$j++;
			$i = getNextPhoto($i);
		}
		$xoopsTpl->append('picturerows', array('pictures' => $pictures, 'adminforms' => $adminforms, 'captions' => $captions));
		$rowCount++;
		$rowStart = $i;
	}
}
$xoopsTpl->assign('lang_lastupdate', _MD_GALLERY_LUPDATE);
$xoopsTpl->assign('lang_views', _MD_GALLERY_VIEWS);
$xoopsTpl->assign('lang_comments', _MD_GALLERY_COMMENTS);
$xoopsTpl->assign('lang_items', _MD_GALLERY_ITEMS);
$xoopsTpl->assign('lang_description', _DESCRIPTION);
$xoopsTpl->assign('lang_capturedate', '撮影日付');

include XOOPS_ROOT_PATH.'/footer.php';

?>