<?php
/*
 * $RCSfile: GalleryFileSystemEntityHelper_medium.class,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.11 $ $Date: 2005/08/23 03:49:04 $
 * @package GalleryCore
 * @author Bharat Mediratta <bharat@menalto.com>
 */

/**
 * Helper class for GalleryFileSystemEntities
 *
 * @package GalleryCore
 * @subpackage Helpers
 * @abstract
 */
class GalleryFileSystemEntityHelper_medium {

    /**
     * Typically, we create a FileSystemEntity with a specific path.  This
     * allows us to check for name collisions at this point.
     *
     * @param string the path component
     * @param int the id of the target parent
     * @param int (optional) ignore path collision with this id
     * @return array object GalleryStatus a status code
     *               boolean true if there's a collision
     * @static
     */
    function checkPathCollision($pathComponent, $parentId, $selfId=null) {
	global $gallery;

	$query = '
	  SELECT
	    COUNT([GalleryChildEntity::id])
	  FROM
	    [GalleryChildEntity], [GalleryFileSystemEntity]
	  WHERE
	    [GalleryChildEntity::parentId] = ?
	  AND
	    [GalleryFileSystemEntity::pathComponent] = ?
	  AND
	    [GalleryChildEntity::id] = [GalleryFileSystemEntity::id]
	';
	$data = array($parentId, $pathComponent);
	if (isset($selfId)) {
	    $query .= '
	      AND [GalleryChildEntity::id] <> ?
	    ';
	    $data[] = $selfId;
	}

	list ($ret, $searchResults) = $gallery->search($query, $data);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$result = $searchResults->nextResult();
	$isCollision = ($result[0] > 0);

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

    /**
     * Get a legal path component in the given parent id.  Legal by the platform standards, and
     * legal in that it doesn't cause a conflict with other path components.
     *
     * @param string the starting path component (eg, "IMG_10293.JPG")
     * @param int the target parent id
     * @param int (optional) ignore path collision with this id
     * @return array object GalleryStatus a status code
     *               string the legal path component
     * @static
     */
    function getLegalPathComponent($pathComponent, $parentId, $selfId=null) {
	global $gallery;
	$platform = $gallery->getPlatform();

	/* Make sure our path component uses legal characters */
	$pathComponent = $platform->legalizePathComponent(trim($pathComponent));

	/* Get the parent, just to verify id is valid */
	list ($ret, $parent) = GalleryCoreApi::loadEntitiesById($parentId);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/* Extract the file base and extension */
	list ($fileBase, $extension) = GalleryUtilities::getFileNameComponents($pathComponent);
	if (!empty($extension)) {
	    $extension = '.' . $extension;
	}

	/*
	 * If given string was extended characters that were all converted to "_" then
	 * autogenerate a new filename.. we'll use today's date.
	 */
	if (rtrim($fileBase, '_') == '') {
	    $fileBase = $platform->strftime('%Y%m%d');
	}

	/*
	 * Try <fileBase>.<extension>
	 *     <fileBase>_001.<extension>
	 *     <fileBase>_002.<extension>
	 *     etc.
	 * Don't be intimidated by the first 100 collisions
	 */
	$retry = 0;
	while (true) {
	    $newPathComponent = sprintf('%s%s%s',
				$fileBase,
				$retry > 0 ? sprintf('_%03d', $retry) : '',
				$extension);

	    /* Make sure that we don't have a collision in the db. */
	    list ($ret, $isCollision) = GalleryFileSystemEntityHelper_medium::checkPathCollision(
					$newPathComponent, $parentId, $selfId);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    if (!$isCollision) {
		break;
	    }

	    if (++$retry > 100) {
		return array(GalleryStatus::error(ERROR_COLLISION, __FILE__, __LINE__), null);
	    }
	}

	return array(GalleryStatus::success(), $newPathComponent);
    }
}
?>
