<?php
/*
 * $RCSfile: ItemEditCaptions.inc,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2005 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., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */

/**
 * @version $Revision: 1.7 $ $Date: 2005/08/30 00:40:06 $
 * @package GalleryCore
 * @subpackage UserInterface
 * @author Bharat Mediratta <bharat@menalto.com>
 * @author Changpeng Zhao
 */

/**
 * This controller will save many item captions at once.
 *
 * @package GalleryCore
 * @subpackage UserInterface
 */
class ItemEditCaptionsController extends GalleryController {

    /**
     * @see GalleryController::handleRequest
     */
    function handleRequest($form) {
	list ($itemId, $page) = GalleryUtilities::getRequestVariables('itemId', 'page');

	$status = $error = array();
	if (isset($form['action']['save'])) {
	    $ids = array_keys($form['items']);

	    list ($ret, $lockId) = GalleryCoreApi::acquireWriteLock($ids);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    /* We'll check permissions one at a time below, but precache them now */
	    $ret = GalleryCoreApi::studyPermissions($ids);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    list ($ret, $items) = GalleryCoreApi::loadEntitiesById($ids);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    $status['successCount'] = 0;
	    $status['errorCount'] = 0;
	    foreach ($items as $item) {
		/* Make sure we have permission to edit this item */
		list ($ret, $permissions) = GalleryCoreApi::getPermissions($item->getId());
		if ($ret->isError()) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}

		$id = $item->getId();
		if (isset($permissions['core.edit'])) {
		    if ($item->getSerialNumber() == $form['items'][$id]['serialNumber']) {
			$item->setTitle($form['items'][$id]['title']);
			$item->setSummary($form['items'][$id]['summary']);
			$item->setKeywords($form['items'][$id]['keywords']);
			$item->setDescription($form['items'][$id]['description']);

			$ret = $item->save();
			if ($ret->isError()) {
			    return array($ret->wrap(__FILE__, __LINE__), null);
			}
			$status[$id]['saved'] = 1;
			$status['successCount']++;
		    } else {
			$status[$id]['obsolete'] = 1;
			$status['errorCount']++;
		    }
		} else {
		    $status[$id]['permissionDenied'] = 1;
		    $status['errorCount']++;
		}
	    }

	    $ret = GalleryCoreApi::releaseLocks($lockId);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    /*
	     * Figure out where to redirect.  We always redirect even if we have
	     * an error since we may have saved some items, but not others.
	     */
	    $redirect['view'] = 'core.ItemAdmin';
	    $redirect['subView'] = 'core.ItemEditCaptions';
	    $redirect['itemId'] = (int)$itemId;
	    if (!$status['errorCount'] && isset($form['action']['save']['next'])) {
		$redirect['page'] = $page + 1;
	    } else if (!$status['errorCount'] && isset($form['action']['save']['previous'])) {
		$redirect['page'] = max($page-1, 0);
	    } else if (!$status['errorCount'] && isset($form['action']['save']['done'])) {
		$results['return'] = 1;
		$redirect['page'] = (int)$page;
	    } else {
		$redirect['page'] = (int)$page;
	    }
	} else if (isset($form['action']['cancel'])) {
	    $results['return'] = 1;
	}

	if (!empty($redirect)) {
	    $results['redirect'] = $redirect;
	} else {
	    $results['delegate']['view'] = 'core.ItemAdmin';
	    $results['delegate']['subView'] = 'core.ItemEditCaptions';
	}
	$results['status'] = $status;
	$results['error'] = $error;

	return array(GalleryStatus::success(), $results);
    }
}

/**
 * This view will allow the user to edit many item captions at once.
 *
 * @package GalleryCore
 * @subpackage UserInterface
 */
class ItemEditCaptionsView extends GalleryView {

    /**
     * @see GalleryView::loadTemplate
     */
    function loadTemplate(&$template, &$form) {
	global $gallery;

	list ($itemId, $page, $selectedId, $albumPage) =
	    GalleryUtilities::getRequestVariables('itemId', 'page', 'selectedId', 'albumPage');

	if ($form['formName'] != 'ItemEditCaption') {
	    $form['formName'] = 'ItemEditCaption';
	    $form['numPerPage'] = 9;

	    list ($ret, $item) = GalleryCoreApi::loadEntitiesById($itemId);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    list ($ret, $childIds) =
		GalleryCoreApi::fetchChildItemIdsWithPermission($itemId, 'core.edit');
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    $form['childItems'] = array();
	    $numPages = 1;
	    $numPages = ceil(sizeof($childIds) / $form['numPerPage']);
	    if (empty($page) && !empty($selectedId)) {
		/* No page given.  Determine which page we're on from the selectedId */
		for ($i = 0; $i < count($childIds); $i++) {
		    if ($childIds[$i] == $selectedId) {
			$page = ceil(($i + 1) / $form['numPerPage']);
		    }
		}
	    }
	    if (empty($page) && !empty($albumPage)) {
		/* Still no page.  Determine which page we're on from albumPage */
		list ($ret, $theme) = $this->loadThemeForItem($item);
		if ($ret->isError()) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}
		list ($ret, $params) = $theme->fetchParameters($itemId);
		if ($ret->isError()) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}
		$albumPageSize = $theme->getPageSize($params);
		if (!empty($albumPageSize)) {
		    $page = ceil((($albumPage - 1) * $albumPageSize + 1) / $form['numPerPage']);
		}
	    }
	    if (empty($page)) {
		$page = 1;
	    }

	    $start = $form['numPerPage'] * ($page - 1);
	    $childIds = array_slice($childIds, $start, $form['numPerPage']);

	    list ($ret, $childItems) = GalleryCoreApi::loadEntitiesById($childIds);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    /* Get child thumbnails */
	    list ($ret, $thumbnails) = GalleryCoreApi::fetchThumbnailsByItemIds($childIds);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    /* build peers table */
	    foreach ($childItems as $child) {
		$form['items'][$child->getId()] = $child->getMemberData();

		/* While we're at it, attach the thumbnails */
		if (isset($thumbnails[$child->getId()])) {
		    $thumbnail = $thumbnails[$child->getId()];
		    list ($ret, $thumbnail) =
			GalleryCoreApi::rebuildDerivativeCacheIfNotCurrent($thumbnail->getId());
		    if ($ret->isError()) {
			return array($ret->wrap(__FILE__, __LINE__), null);
		    }
		    $form['items'][$child->getId()]['thumbnail'] = $thumbnail->getMemberData();
		}
	    }
	}

	$urlGenerator =& $gallery->getUrlGenerator();

	$ItemEditCaptions = array();
	$ItemEditCaptions['canCancel'] = $urlGenerator->isNavigationBackPossible();
	$ItemEditCaptions['page'] = $page;
	$ItemEditCaptions['numPages'] = $numPages;

	$template->setVariable('controller', 'core.ItemEditCaptions');
	$template->setVariable('ItemEditCaptions', $ItemEditCaptions);

	return array(GalleryStatus::success(),
		     array('body' => 'modules/core/templates/ItemEditCaptions.tpl'));

    }

    /**
     * @see GalleryView::getViewDescription()
     */
    function getViewDescription() {
	list ($ret, $core) = GalleryCoreApi::loadPlugin('module', 'core');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	return array(GalleryStatus::success(), $core->translate('edit captions'));
    }
}
?>
