<?php
/*
 * $RCSfile: GalleryMembersHelper.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.
 */

/**
 * @package Members
 * @version $Revision: 1.20 $ $Date: 2005/08/23 03:49:45 $
 * @author Robert Balousek <rbalousek@hotmail.com>
 */

/**
 * A helper class for GalleryMembers
 *
 * Utility functions useful in managing GalleryMembers
 *
 * @package Members
 * @subpackage Classes
 */
class GalleryMembersHelper {

    /**
     * Return the total number of items a user owns
     *
     * @param int User id
     * @return array (object GalleryStatus a status code,
     *                int ItemCount a users total item count)
     * @static
     */
    function fetchUserItemCount($userId) {
        global $gallery;

	list ($ret, $aclIds) =
	    GalleryCoreApi::fetchAccessListIds('core.view', $gallery->getActiveUserId());
        if ($ret->isError()) {
            return array($ret->wrap(__FILE__, __LINE__), null);
        }
	if (empty($aclIds)) {
	    return array(GalleryStatus::success(), 0);
	}
	$aclMarkers = GalleryUtilities::makeMarkers(count($aclIds));

        $query = sprintf('
        SELECT
          COUNT([GalleryItem::id])
        FROM
	  [GalleryItem], [GalleryAccessSubscriberMap]
	WHERE
          [GalleryItem::ownerId] = ?
          AND
          [GalleryAccessSubscriberMap::itemId] = [GalleryItem::id]
          AND
          [GalleryAccessSubscriberMap::accessListId] IN (%s)
	', $aclMarkers);

	$data = array();
        $data[] = $userId;
	$data = array_merge($data, $aclIds);

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

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

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

    /**
     * Return the last N items a user created
     *
     * @param int User id, int Offset, int Count, string Order Direction
     * @return array (object GalleryStatus a status code,
     *                array (GalleryItem, GalleryItem, ...))
     * @static
     */
    function fetchLastUserItems($userId, $offset, $count, $orderDirection=ORDER_DESCENDING){
	global $gallery;

	switch($orderDirection) {
	case ORDER_ASCENDING:
	    $direction = 'ASC';
	    break;

	case ORDER_DESCENDING:
	    $direction = 'DESC';
	    break;

	default:
	    return array(GalleryStatus::error(ERROR_BAD_PARAMETER, __FILE__, __LINE__),
			 null);
	}

	list ($ret, $aclIds) =
	    GalleryCoreApi::fetchAccessListIds('core.view', $gallery->getActiveUserId());
        if ($ret->isError()) {
            return array($ret->wrap(__FILE__, __LINE__), null);
        }
	if (empty($aclIds)) {
	    return array(GalleryStatus::success(), array());
	}
	$aclMarkers = GalleryUtilities::makeMarkers(count($aclIds));

	$query = sprintf('
        SELECT
          [GalleryItem::id], [GalleryEntity::creationTimestamp]
        FROM
          [GalleryItem], [GalleryEntity], [GalleryAccessSubscriberMap]
        WHERE
          [GalleryItem::id] = [GalleryEntity::id]
          AND
          [GalleryItem::ownerId] = ?
          AND
	  [GalleryAccessSubscriberMap::itemId] = [GalleryItem::id]
          AND
          [GalleryAccessSubscriberMap::accessListId] IN (%s)
        ORDER BY
          [GalleryEntity::creationTimestamp] ' . $direction . '
        ', $aclMarkers);

	$data = array();
	$data[] = $userId;
	$data = array_merge($data, $aclIds);

	$options = array();
	$options['limit'] = array('count' => $count, 'offset' => $offset);

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

	/* Get all of our item ids */
	$itemIds = array();
	while ($result = $searchResults->nextResult()) {
	    $itemIds[] = $result[0];
	}

	/* Convert them to entities */
	if (sizeof($itemIds) > 0) {
	    list ($ret, $items) = GalleryCoreApi::loadEntitiesById($itemIds);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }
	} else {
	    $items = array();
	}

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

    /**
     * Return true if the user has permission to view the
     * Members Module
     *
     * @param int User id
     * @return array (object GalleryStatus a status code,
     *                bool canViewMembersModule permission)
     * @static
     */
    function canViewMembersModule($userId) {
	global $gallery;
	list ($ret, $viewSelectedGroupId) =
	    GalleryCoreApi::getPluginParameter('module', 'members', 'canViewMembersModule');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $result) = GalleryCoreApi::isUserInGroup($userId, $viewSelectedGroupId);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	return array(GalleryStatus::success(), $result);
    }

    /**
     * Return true if the user has permission to view the
     * members email address inside the members profile
     *
     * @param int User id
     * @return array (object GalleryStatus a status code,
     *                bool canViewProfileEmail permission)
     * @static
     */
    function canViewProfileEmail($userId) {
	global $gallery;
	$result = false;
	/* Can the user view email addresses in the member profile? */
	list ($ret, $resultOne) =
	    GalleryCoreApi::getPluginParameter('module', 'members', 'canViewEmailAddress');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $groupId) =
	    GalleryCoreApi::getPluginParameter('module', 'core', 'id.adminGroup');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/* Is the current user an admin? */
	list ($ret, $resultTwo) = GalleryCoreApi::isUserInGroup($userId, $groupId);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/*
	 * User can see member email in the profile if they are an admin,
	 * or if the module setting says they are allowed to.
	 */
	if ($resultOne || $resultTwo) {
	    $result = true;
	}

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

    /**
     * Return the calendar days since the user's creationTimestamp.
     *
     * @param int User id
     * @return array (object GalleryStatus a status code,
     *                int daysSinceCreation number in days)
     * @static
     */
    function daysSinceCreation($userId){
	list ($ret, $user) = GalleryCoreApi::loadEntitiesById($userId);

	/*
	 * The difference in the day of creationTimestamp and todays date,
         * divided by the number of seconds
	 * in a day, gives us a result in days
	 */
        $todayStamp = strtotime(date("F j, Y", time()));
	$creationStamp = strtotime(date("F j, Y", $user->getCreationTimestamp()));
	$age = (int)round(($todayStamp - $creationStamp) / (24 * 60 * 60));

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

    /**
     * Get the current member count
     *
     * @return array object GalleryStatus
     *               int how many members are registered
     */
    function getMembersCount() {
        global $gallery;
	list ($ret, $groupId) =
            GalleryCoreApi::getPluginParameter('module', 'core', 'id.allUserGroup');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	list ($ret, $totalUserCount) = GalleryCoreApi::fetchUserCount(null, $groupId);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
        return array(GalleryStatus::success(), (int)$totalUserCount);
    }
}
?>
