/photogallery/includes/admin.class.php
0,0 → 1,1532
<?php
 
/**
* Class providing admin functions.
*
* @package singapore
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2006 Tamlyn Rhodes
* @version $Id: admin.class.php,v 1.65 2006/09/08 15:29:22 tamlyn Exp $
*/
 
define("SG_ADMIN", 1024);
define("SG_SUSPENDED", 2048);
 
//include the base IO class
require_once dirname(__FILE__)."/singapore.class.php";
 
/**
* Provides gallery, image and user administration functions.
*
* @uses Singapore
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
*/
class sgAdmin extends Singapore
{
/**
* Array of error messages raised by the script
* @var array
*/
var $errors = array();
/**
* Array of informational messages raised by the script
* @var array
*/
var $messages = array();
/**
* Base name of admin template file to include
* @var string
*/
var $includeFile = "login";
/**
* Admin constructor. Doesn't call {@link Singapore} constructor.
* @param string the path to the base singapore directory
*/
function sgAdmin($basePath = "")
{
//import class definitions
//io handler class included once config is loaded
require_once $basePath."includes/translator.class.php";
require_once $basePath."includes/thumbnail.class.php";
require_once $basePath."includes/gallery.class.php";
require_once $basePath."includes/config.class.php";
require_once $basePath."includes/image.class.php";
require_once $basePath."includes/user.class.php";
//start execution timer
$this->scriptStartTime = microtime();
 
//remove slashes
if(get_magic_quotes_gpc()) {
$_REQUEST = array_map(array("Singapore","arraystripslashes"), $_REQUEST);
//as if magic_quotes_gpc wasn't insane enough, php doesn't add slashes
//to the tmp_name variable so I have to add them manually. Grrrr.
foreach($_FILES as $key => $nothing)
$_FILES[$key]["tmp_name"] = addslashes($_FILES[$key]["tmp_name"]);
$_FILES = array_map(array("Singapore","arraystripslashes"), $_FILES);
}
$galleryId = isset($_REQUEST["gallery"]) ? $_REQUEST["gallery"] : ".";
//load config from singapore root directory
$this->config =& sgConfig::getInstance();
$this->config->loadConfig($basePath."singapore.ini");
$this->config->loadConfig($basePath."secret.ini.php");
//set runtime values
$this->config->pathto_logs = $this->config->pathto_data_dir."logs/";
$this->config->pathto_cache = $this->config->pathto_data_dir."cache/";
$this->config->pathto_current_template = $this->config->pathto_templates.$this->config->default_template."/";
$this->config->pathto_admin_template = $this->config->pathto_templates.$this->config->admin_template_name."/";
//load config from admin template ini file (admin.ini) if present
$this->config->loadConfig($basePath.$this->config->pathto_admin_template."admin.ini");
$this->template = $this->config->default_template;
//do not load gallery-specific ini files
 
//set current language from request vars or config
$this->language = isset($_REQUEST["lang"]) ? $_REQUEST["lang"] : $this->config->default_language;
//read the language file
$this->translator =& Translator::getInstance($this->language);
$this->translator->readLanguageFile($this->config->base_path.$this->config->pathto_locale."singapore.".$this->language.".pmo");
$this->translator->readLanguageFile($this->config->base_path.$this->config->pathto_locale."singapore.admin.".$this->language.".pmo");
//include IO handler class and create instance
require_once $basePath."includes/io_".$this->config->io_handler.".class.php";
$ioClassName = "sgIO_".$this->config->io_handler;
$this->io = new $ioClassName($this->config);
//set character set
if(!empty($this->translator->languageStrings[0]["charset"]))
$this->character_set = $this->translator->languageStrings[0]["charset"];
else
$this->character_set = $this->config->default_charset;
//set action to perform
if(empty($_REQUEST["action"])) $this->action = "menu";
else $this->action = $_REQUEST["action"];
//set page title
$this->pageTitle = $this->config->gallery_name;
//set root node of crumb line
$holder = new sgGallery("", new stdClass);
$holder->name = $this->config->gallery_name;
$this->ancestors = array($holder);
}
/**
* Push an error message onto the error stack
* @param string Error message
* @param string true if error is fatal; false otherwise (optional)
* @return false
*/
function pushError($error, $fatal = false)
{
if($fatal) die($error);
$this->errors[] = $error;
return false;
}
/**
* Push a message onto the message stack
* @return true
*/
function pushMessage($message)
{
$this->messages[] = $message;
return true;
}
function showMessages()
{
if(empty($this->errors) && empty($this->messages)) return '';
$errorText = $this->translator->_g("ERROR");
$ret = '<ul id="sgAdminMessages">';
foreach($this->errors as $error)
$ret .= '<li class="adminError">'.$errorText.': '.$error.'</li>'."\n";
foreach($this->messages as $message)
$ret .= '<li class="adminMessage">'.$message.'</li>'."\n";
$ret .= '</ul>';
return $ret;
}
/**
* Returns a link to the image or gallery with the correct formatting and path
* NOTE: This takes its arguments in a different order to {@link Singapore::formatURL()}
*
* @author Adam Sissman <adam at bluebinary dot com>
*/
function formatAdminURL($action, $gallery = null, $image = null, $startat = null, $extra = null)
{
$ret = $this->config->base_url."admin.php?";
$ret .= "action=".$action;
if($gallery != null) $ret .= "&amp;gallery=".$gallery;
if($image != null) $ret .= "&amp;image=".$image;
if($startat != null) $ret .= "&amp;startat=".$startat;
if($extra != null) $ret .= $extra;
if($this->language != $this->config->default_language) $ret .= '&amp;'.$this->config->url_lang.'='.$this->language;
if($this->template != $this->config->default_template) $ret .= '&amp;'.$this->config->url_template.'='.$this->template;
return $ret;
}
 
/**
* Tries to find temporary storage space
*/
function findTempDirectory()
{
if(isset($_ENV["TMP"]) && is_writable($_ENV["TMP"])) return $_ENV["TMP"];
elseif(isset($_ENV["TEMP"]) && is_writable($_ENV["TEMP"])) return $_ENV["TEMP"];
elseif(is_writable("/tmp")) return "/tmp";
elseif(is_writable("/windows/temp")) return "/windows/temp";
elseif(is_writable("/winnt/temp")) return "/winnt/temp";
else return null;
}
function getMaxHits($array)
{
$max = 0;
foreach($array as $obj)
if($obj->hits > $max)
$max = $obj->hits;
return $max;
}
/**
* Returns true if the current admin action has been confirmed (i.e. by clicking OK)
*/
function actionConfirmed()
{
return isset($_REQUEST["confirmed"]) && $_REQUEST["confirmed"] == $this->translator->_g("confirm|OK");
}
/**
* Returns true if the current admin action has been cancelled (i.e. by clicking Cancel)
*/
function actionCancelled()
{
return isset($_REQUEST["confirmed"]) && $_REQUEST["confirmed"] == $this->translator->_g("confirm|Cancel");
}
/**
* Checks request variables for action to perform, checks user permissions,
* performs action and sets file to include.
*/
function doAction()
{
//check if user is logged in
if(!$this->isLoggedIn() && $this->action != "login")
return;
//choose which file to include and/or perform admin actions
switch($this->action) {
case "addgallery" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"add")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->addGallery()) {
$this->selectGallery($this->gallery->id."/".$_REQUEST["newgallery"]);
$this->pushMessage($this->translator->_g("Gallery added"));
$this->includeFile = "editgallery";
} else {
$this->includeFile = "newgallery";
}
break;
case "addimage" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"add")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
break;
}
switch($_REQUEST["sgLocationChoice"]) {
case "remote" :
case "single" :
if($this->addImage())
$this->includeFile = "editimage";
else
$this->includeFile = "newimage";
break;
case "multi" :
if($this->addMultipleImages())
$this->includeFile = "view";
else
$this->includeFile = "newimage";
break;
default :
$this->includeFile = "newimage";
break;
}
break;
case "changethumbnail" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->actionConfirmed()) {
$this->saveGalleryThumbnail();
$this->includeFile = "editgallery";
} elseif($this->actionCancelled()) {
$this->includeFile = "editgallery";
} else {
$this->includeFile = "changethumbnail";
}
break;
case "deletegallery" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"delete")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->actionConfirmed() || ($this->gallery->galleryCount()==0 && $this->gallery->imageCount()==0)) {
if($this->deleteGallery())
$this->selectGallery($this->gallery->parent->id);
$this->includeFile = "view";
} elseif($this->actionCancelled()) {
$this->includeFile = "view";
} else {
$GLOBALS["confirmTitle"] = $this->translator->_g("Delete Gallery");
$GLOBALS["confirmMessage"] = $this->translator->_g("Gallery %s is not empty.\nAre you sure you want to irretrievably delete it and all subgalleries and images it contains?", "<em>".$this->gallery->name."</em>");
$this->includeFile = "confirm";
}
break;
case "deleteimage" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"delete")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->actionConfirmed()) {
$this->deleteImage();
$this->includeFile = "view";
} elseif($this->actionCancelled()) {
$this->includeFile = "view";
} else {
$GLOBALS["confirmTitle"] = $this->translator->_g("delete image");
$GLOBALS["confirmMessage"] = $this->translator->_g("Are you sure you want to irretrievably delete image %s from gallery %s?","<em>".$this->image->name().$this->image->byArtistText()."</em>","<em>".$this->gallery->name()."</em>");
$this->includeFile = "confirm";
}
break;
case "deleteuser" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->actionConfirmed()) {
if($this->deleteUser())
$this->pushMessage($this->translator->_g("User deleted"));
$this->includeFile = "manageusers";
} elseif($this->actionCancelled()) {
$this->includeFile = "manageusers";
} else {
$GLOBALS["confirmTitle"] = $this->translator->_g("delete user");
$GLOBALS["confirmMessage"] = $this->translator->_g("Are you sure you want to permanently delete user %s?","<em>".$_REQUEST["user"]."</em>");
$this->includeFile = "confirm";
}
break;
case "editgallery" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} else
$this->includeFile = "editgallery";
break;
case "editimage" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} else
$this->includeFile = "editimage";
break;
case "editpass" :
if($this->user->isGuest()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else
$this->includeFile = "editpass";
break;
case "editpermissions" :
$this->selectGallery();
if(!$this->user->isAdmin() && !$this->user->isOwner($this->gallery)) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} else
$this->includeFile = "editpermissions";
break;
case "editprofile" :
if($this->user->isGuest()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else
$this->includeFile = "editprofile";
break;
case "edituser" :
if(!$this->user->isAdmin() && $_REQUEST["user"] != $this->user->username || $this->user->isGuest()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else
$this->includeFile = "edituser";
break;
case "login" :
if($this->doLogin())
$this->includeFile = "menu";
else
$this->includeFile = "login";
break;
case "logout" :
$this->logout();
$this->includeFile = "login";
break;
case "manageusers" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else
$this->includeFile = "manageusers";
break;
case "multi" :
$this->selectGallery();
if(!isset($_REQUEST["sgGalleries"]) && !isset($_REQUEST["sgImages"])) {
$this->pushMessage($this->translator->_g("Please select one or more items."));
$this->includeFile = "view";
} elseif($_REQUEST["subaction"]==$this->translator->_g("Copy or move")) {
$this->includeFile = "multimove";
} elseif($_REQUEST["subaction"]==$this->translator->_g("Delete")) {
if(!$this->checkPermissions($this->gallery,"delete")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->actionConfirmed()) {
if(isset($_REQUEST["sgImages"])) {
$success = $this->deleteMultipleImages();
$this->pushMessage($this->translator->_g("%s images deleted.", $success));
} else {
$success = $this->deleteMultipleGalleries();
$this->pushMessage($this->translator->_g("%s galleries deleted.", $success));
}
$this->includeFile = "view";
} elseif($this->actionCancelled()) {
$this->includeFile = "view";
} else {
if(isset($_REQUEST["sgImages"])) {
$GLOBALS["confirmTitle"] = $this->translator->_g("Delete Images");
$GLOBALS["confirmMessage"] = $this->translator->_g("Are you sure you want to permanently delete %s images?",count($_REQUEST["sgImages"]));
} else{
$GLOBALS["confirmTitle"] = $this->translator->_g("Delete Galleries");
$GLOBALS["confirmMessage"] = $this->translator->_g("Are you sure you want to permanently delete %s galleries?",count($_REQUEST["sgGalleries"]));
}
$this->includeFile = "confirm";
}
} elseif($_REQUEST["subaction"]==$this->translator->_g("Re-index")) {
if(is_int($success = $this->reindexMultipleGalleries()))
$this->pushMessage($this->translator->_g("Galleries re-indexed. %s total images added.", $success));
$this->includeFile = "view";
}
break;
case "multimove" :
$this->selectGallery();
if($this->actionConfirmed()) {
if(isset($_REQUEST["sgImages"])) {
//$success = $this->moveMultipleImages();
//$this->adminMessage = $this->translator->_g("%s images moved.", $success);
$success=true;
$this->pushMessage("not yet implemented");
} else {
$success = $this->moveMultipleGalleries();
$this->pushMessage($this->translator->_g("%s galleries moved.", $success));
}
}
$this->includeFile = "view";
break;
case "newgallery" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"add")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} else
$this->includeFile = "newgallery";
break;
case "newimage" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"add")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} else
$this->includeFile = "newimage";
break;
case "newuser" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->addUser())
$this->includeFile = "edituser";
else
$this->includeFile = "manageusers";
break;
case "purgecache" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->actionConfirmed()) {
if($this->purgeCache())
$this->pushMessage($this->translator->_g("Thumbnail cache purged"));
$this->includeFile = "menu";
} elseif($this->actionCancelled()) {
$this->includeFile = "menu";
} else {
$dir = $this->getListing($this->config->pathto_cache,$this->config->recognised_extensions);
$GLOBALS["confirmTitle"] = $this->translator->_g("purge cached thumbnails");
$GLOBALS["confirmMessage"] = $this->translator->_g("Are you sure you want to delete all %s cached thumbnails?",count($dir->files));
$this->includeFile = "confirm";
}
break;
case "reindex" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit"))
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
else {
$imagesAdded = $this->reindexGallery();
if(is_int($imagesAdded))
$this->pushMessage($this->translator->_g("Gallery re-indexed. %s images added.",$imagesAdded));
}
$this->includeFile = "view";
break;
case "savegallery" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->saveGallery()) {
$this->includeFile = "view";
} else {
$this->includeFile = "editgallery";
}
break;
case "saveimage" :
$this->selectGallery();
if(!$this->checkPermissions($this->gallery,"edit")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->saveImage()) {
$this->pushMessage($this->translator->_g("Image info saved"));
$this->includeFile = "view";
} else {
$this->includeFile = "view";
}
break;
case "savepass" :
if($this->user->isGuest()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->savePass()) {
$this->pushMessage($this->translator->_g("Password saved"));
$this->includeFile = "menu";
} else {
$this->includeFile = "editpass";
}
break;
case "savepermissions" :
$this->selectGallery();
if(!$this->user->isAdmin() && !$this->user->isOwner($this->gallery)) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "view";
} elseif($this->savePermissions()) {
$this->pushMessage($this->translator->_g("Permissions saved"));
$this->includeFile = "view";
} else {
$this->includeFile = "editpermissions";
}
break;
case "saveprofile" :
if($_REQUEST["user"] != $this->user->username || $this->user->isGuest()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->saveUser()) {
$this->pushMessage($this->translator->_g("User info saved"));
$this->includeFile = "menu";
} else {
$this->includeFile = "editprofile";
}
break;
case "saveuser" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->saveUser())
$this->includeFile = "manageusers";
else
$this->includeFile = "edituser";
break;
case "showgalleryhits" :
$this->selectGallery();
//load hit data for child galleries
foreach(array_keys($this->gallery->galleries) as $index)
$this->io->getHits($this->gallery->galleries[$index]);
/*if(!$this->checkPermissions($this->gallery,"read")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else {*/
$this->includeFile = "galleryhits";
//}
break;
case "showimagehits" :
$this->selectGallery();
/*if(!$this->checkPermissions($this->gallery,"read")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else {*/
$this->includeFile = "imagehits";
//}
break;
case "suspenduser" :
if(!$this->user->isAdmin()) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} elseif($this->suspendUser())
$this->pushMessage($this->translator->_g("User info saved"));
$this->includeFile = "manageusers";
break;
case "view" :
$this->selectGallery();
/*if(!$this->checkPermissions($this->gallery,"read")) {
$this->pushMessage($this->translator->_g("You do not have permission to perform this operation."));
$this->includeFile = "menu";
} else*/
$this->includeFile = "view";
break;
case "menu" :
default :
$this->includeFile = "menu";
}
}
function &allGalleriesArray()
{
$root =& $this->io->getGallery(".", new stdClass, 100);
return $this->allGalleriesRecurse($root);
}
function &allGalleriesRecurse(&$gal)
{
if($gal->hasChildGalleries()) {
$galArray = array();
foreach($gal->galleries as $child)
$galArray = array_merge($galArray, $this->allGalleriesRecurse($child));
array_unshift($galArray, $gal);
return $galArray;
} else
return array($gal);
}
/**
* Returns a two-dimensional array of links for the admin bar.
*
* @returns string
*/
function adminLinksArray()
{
if(!$this->isLoggedIn()) return array(0 => array($this->translator->_g("admin bar|Back to galleries") => "."));
$ret[0][$this->translator->_g("admin bar|Admin")] = $this->formatAdminURL("menu");
$ret[0][$this->translator->_g("admin bar|Galleries")] = $this->formatAdminURL("view", isset($this->gallery) ? $this->gallery->idEncoded() : null);
$ret[0][$this->translator->_g("admin bar|Log out")] = $this->formatAdminURL("logout");
if($this->isGalleryPage() || $this->isAlbumPage() || $this->isImagePage()) {
$ret[1][$this->translator->_g("admin bar|Edit gallery")] = $this->formatAdminURL("editgallery",$this->gallery->idEncoded());
$ret[1][$this->translator->_g("admin bar|Access control")] = $this->formatAdminURL("editpermissions",$this->gallery->idEncoded());
$ret[1][$this->translator->_g("admin bar|Delete gallery")] = $this->formatAdminURL("deletegallery",$this->gallery->idEncoded());
$ret[1][$this->translator->_g("admin bar|New subgallery")] = $this->formatAdminURL("newgallery",$this->gallery->idEncoded());
$ret[1][$this->translator->_g("admin bar|Re-index gallery")] = $this->formatAdminURL("reindex",$this->gallery->idEncoded());
if($this->isImagePage()) {
$ret[2][$this->translator->_g("admin bar|Edit image")] = $this->formatAdminURL("editimage",$this->gallery->idEncoded(),$this->image->id);
$ret[2][$this->translator->_g("admin bar|Delete image")] = $this->formatAdminURL("deleteimage",$this->gallery->idEncoded(),$this->image->id);
}
$ret[2][$this->translator->_g("admin bar|New image")] = $this->formatAdminURL("newimage",$this->gallery->idEncoded());
}
return $ret;
}
/**
* Saves the new password if it is correctly specified.
*
* @return boolean true on success; false otherwise
*/
function savePass()
{
$users = $this->io->getUsers();
$found = false;
for($i=0;$i < count($users);$i++)
if($_POST["sgUsername"] == $users[$i]->username) {
$found = true;
if(md5($_POST["sgOldPass"]) == $users[$i]->userpass)
if($_POST["sgNewPass1"]==$_POST["sgNewPass2"])
if(strlen($_POST["sgNewPass1"]) >= 6 && strlen($_POST["sgNewPass1"]) <= 16) {
$users[$i]->userpass = md5($_POST["sgNewPass1"]);
if($this->io->putUsers($users)) return true;
else $this->pushError($this->translator->_g("Could not save user info"));
}
else
$this->pushError($this->translator->_g("New password must be between 6 and 16 characters long."));
else
$this->pushError($this->translator->_g("The new passwords you entered do not match."));
else
$this->pushError($this->translator->_g("The current password you entered does not match the one in the database."));
}
if(!$found) $this->pushError($this->translator->_g("The username specified was not found in the database."));
//some sort of error occurred so:
return false;
}
/**
* Attempts to log a registered user into admin.
*
* @return boolean true on success; false otherwise
*/
function doLogin()
{
if(!empty($_POST["sgUsername"]) && !empty($_POST["sgPassword"])) {
if($this->loadUser($_POST["sgUsername"]) && md5($_POST["sgPassword"]) == $this->user->userpass){
if($this->user->permissions & SG_SUSPENDED) {
$this->logout();
return $this->pushError($this->translator->_g("Your account has been suspended"));
} else {
$_SESSION["sgUser"]["username"] = $this->user->username;
$_SESSION["sgUser"]["ip"] = $_SERVER["REMOTE_ADDR"];
$_SESSION["sgUser"]["loginTime"] = time();
return $this->pushMessage($this->translator->_g("Welcome to singapore admin!"));
}
}
$this->logout();
return $this->pushError($this->translator->_g("Username and/or password incorrect"));
}
return $this->pushError($this->translator->_g("You must enter a username and password"));
}
/**
* Cancels a user's admin session.
*
* @return true
*/
function logout()
{
$_SESSION["sgUser"] = null;
return $this->pushMessage($this->translator->_g("Thank you and goodbye!"));
}
/**
* Checks if the specified operation is permitted on the specified object
*
* @param sgImage|sgGallery the object to be operated on
* @param string the action to perform (either 'read', 'edit', 'add' or 'delete')
* @return bool true if permissions are satisfied; false otherwise
*/
function checkPermissions($obj, $action, $gallery = null, $image = null)
{
//admins and object owners automatically have full permissions
if($this->user->isAdmin() || $this->user->isOwner($obj))// || (!$this->user->isGuest() && $obj->owner == "__nobody__"))
return true;
//get the appropriate permission bitmask depending on action
switch($action) {
case "read" :
$inheritPerm = SG_IHR_READ;
$worldPerm = SG_WLD_READ;
$groupPerm = SG_GRP_READ;
break;
case "edit" :
$inheritPerm = SG_IHR_EDIT;
$worldPerm = SG_WLD_EDIT;
$groupPerm = SG_GRP_EDIT;
break;
case "add" :
$inheritPerm = SG_IHR_ADD;
$worldPerm = SG_WLD_ADD;
$groupPerm = SG_GRP_ADD;
break;
case "delete" :
$inheritPerm = SG_IHR_DELETE;
$worldPerm = SG_WLD_DELETE;
$groupPerm = SG_GRP_DELETE;
break;
default :
//unrecognised action so disallow it
return false;
}
//check if the permission is inherited
if(($obj->permissions & $inheritPerm) == $inheritPerm)
if($obj->isRoot())
//shouldn't happen, but just in case
return false;
else
//check permissions of parent
return $this->checkPermissions($obj->parent, $action, $gallery, $image);
else
//not inherited so check world and group permissions of current object
return $obj->permissions & $worldPerm
|| ($this->isInGroup($this->user->groups, $obj->groups) && $obj->permissions & $groupPerm);
}
function savePermissions()
{
$obj =& $this->gallery;
$perms = 0;
switch($_POST["sgRead"]) {
case "inherit" : $perms |= SG_IHR_READ; break;
case "group" : $perms |= SG_GRP_READ; break;
case "world" : $perms |= SG_WLD_READ; break;
case "owner" : break;
}
switch($_POST["sgEdit"]) {
case "inherit" : $perms |= SG_IHR_EDIT; break;
case "group" : $perms |= SG_GRP_EDIT; break;
case "world" : $perms |= SG_WLD_EDIT; break;
case "owner" : break;
}
switch($_POST["sgAdd"]) {
case "inherit" : $perms |= SG_IHR_ADD; break;
case "group" : $perms |= SG_GRP_ADD; break;
case "world" : $perms |= SG_WLD_ADD; break;
case "owner" : break;
}
switch($_POST["sgDelete"]) {
case "inherit" : $perms |= SG_IHR_DELETE; break;
case "group" : $perms |= SG_GRP_DELETE; break;
case "world" : $perms |= SG_WLD_DELETE; break;
case "owner" : break;
}
$obj->permissions |= $perms; // isn't this equivalent
$obj->permissions &= $perms; // to == assignment?
//only the owner or admin can change groups
if($this->user->isAdmin() || $this->user->isOwner($obj));
$obj->groups = $_POST["sgGroups"];
//only the admin can change the owner
if($this->user->isAdmin())
$obj->owner = $_POST["sgOwner"];
if($this->io->putGallery($this->gallery))
return $this->pushMessage($this->translator->_g("Gallery info saved"));
return $this->pushError($this->translator->_g("Could not save gallery info"));
}
/**
* Creates a new user.
*
* @return bool true on success; false otherwise
*/
function addUser()
{
$users = $this->io->getUsers();
foreach($users as $usr)
if($usr->username == $_REQUEST["user"])
return $this->pushError($this->translator->_g("Username already exists"));
if(!preg_match("/^[a-zA-Z0-9_]{3,}$/",$_REQUEST["user"]))
return $this->pushError($this->translator->_g("Username must be at least 3 characters long and contain only alphanumeric characters"));
$users[count($users)] = new sgUser($_REQUEST["user"], md5("password"));
if($this->io->putUsers($users))
return $this->pushMessage($this->translator->_g("User info saved"));
return $this->pushError($this->translator->_g("Could not save user info"));
}
/**
* Deletes a user.
*
* @return bool true on success; false otherwise
*/
function deleteUser($username = null)
{
if($username == null)
$username = $_REQUEST["user"];
if($username == "admin" || $username == "guest")
return $this->pushError($this->translator->_g("Cannot delete built in accounts"));
$users = $this->io->getUsers();
foreach($users as $i => $usr)
if($usr->username == $username) {
//delete user at offset $i from $users
array_splice($users,$i,1);
if($this->io->putUsers($users))
return true;
return $this->pushError($this->translator->_g("Could not save user info"));
}
return $this->pushError($this->translator->_g("Username not recognised"));
}
/**
* Saves a user's info.
*
* @return bool true on success; false otherwise
*/
function saveUser() {
$users = $this->io->getUsers();
for($i=0; $i<count($users); $i++)
if($users[$i]->username == $_REQUEST["user"]) {
$users[$i]->email = $this->prepareText($_REQUEST["sgEmail"]);
$users[$i]->fullname = $this->prepareText($_REQUEST["sgFullname"]);
$users[$i]->description = $this->prepareText($_REQUEST["sgDescription"]);
if($this->user->isAdmin() && $_REQUEST["action"] == "saveuser") {
$users[$i]->groups = $this->prepareText($_REQUEST["sgGroups"]);
$users[$i]->permissions = ($_REQUEST["sgType"] == "admin") ? $users[$i]->permissions | SG_ADMIN : $users[$i]->permissions & ~SG_ADMIN;
if(isset($_REQUEST["sgPassword"]) && $_REQUEST["sgPassword"] != "**********")
$users[$i]->userpass = md5($_REQUEST["sgPassword"]);
}
if($this->io->putUsers($users))
return true;
return $this->pushError($this->translator->_g("Could not save user info"));
}
return $this->pushError($this->translator->_g("Username not recognised"));
}
/**
* Suspend or unsuspend a user's account.
*
* @return bool true on success; false otherwise
*/
function suspendUser() {
$users = $this->io->getUsers();
for($i=0; $i<count($users); $i++)
if($users[$i]->username == $_REQUEST["user"]) {
$users[$i]->permissions = ($users[$i]->permissions & SG_SUSPENDED) ? $users[$i]->permissions & ~SG_SUSPENDED : $users[$i]->permissions | SG_SUSPENDED;
if($this->io->putUsers($users))
return true;
return $this->pushError($this->translator->_g("Could not save user info"));
}
return $this->pushError($this->translator->_g("Username not recognised"));
}
/**
* Check for images in specified gallery directory which are
* not in the metadata and add them. If no gallery is specified,
* the current gallery is used.
* @param string id of gallery to reindex (optional)
* @return int|false the number of images added or false on error
*/
function reindexGallery($galleryId = null)
{
if($galleryId == null)
$gal =& $this->gallery;
else
$gal =& $this->io->getGallery($galleryId, new stdClass);
$imagesAdded = 0;
//get list of images
$dir = Singapore::getListing($this->config->pathto_galleries.$gal->id, $this->config->recognised_extensions);
//cycle through the image files
for($i=0; $i<count($dir->files); $i++) {
//search for the image file in the database images
for($j=0; $j<count($gal->images); $j++)
//if we find it
if($dir->files[$i] == $gal->images[$j]->id)
//skip the rest of this loop
continue 2;
//otherwise add the image to the database
$gal->images[$j] = new sgImage($dir->files[$i], $gal, $this->config);
$gal->images[$j]->name = $dir->files[$i];
list(
$gal->images[$j]->width,
$gal->images[$j]->height,
$gal->images[$j]->type
) = GetImageSize($this->config->pathto_galleries.$gal->id."/".$gal->images[$j]->id);
$imagesAdded++;
}
if($this->io->putGallery($gal))
return $imagesAdded;
return $this->pushError($this->translator->_g("Could not save gallery info"));
}
/**
* Reindexes several galleries from the current gallery.
*
* @return int|false number of images added on success; false otherwise
*/
function reindexMultipleGalleries()
{
$totalImagesAdded = 0;
foreach($_REQUEST["sgGalleries"] as $galleryId) {
$current = $this->reindexGallery($galleryId);
if($current === false) $this->pushError($this->translator->_g("Gallery '%s' could not be reindexed", $galleryId));
else $this->pushMessage($this->translator->_g("Gallery '%s' reindexed: %s images added", $galleryId, $current));
$totalImagesAdded += $current;
}
//reload gallery data if we changed any
if($totalImagesAdded)
$this->selectGallery();
return $totalImagesAdded;
}
/**
* Moves or copies galleries.
*
* @return int|false number of galleries moved; false otherwise
*/
function moveMultipleGalleries()
{
$totalGalleriesMoved = 0;
foreach($_REQUEST["sgGalleries"] as $galleryId) {
$source = $this->config->base_path.$this->config->pathto_galleries.$galleryId;
$target = $this->config->base_path.$this->config->pathto_galleries.$_REQUEST['sgMoveTarget'].'/'.basename($galleryId);
if(file_exists($target)) {
$this->pushError($this->translator->_g("Unable to copy/move gallery '%s' because the target gallery already exists.", $galleryId));
} elseif($this->isSubPath($source, $target, false)) {
$this->pushError($this->translator->_g("Unable to copy/move gallery '%s' because the target is a child of the source.", $galleryId));
//} elseif(!is_writable($target)) {
// $this->pushError($this->translator->_g("Unable to copy/move gallery '%s': the target is not writable", $galleryId));
} else {
if($_REQUEST["sgMoveType"] == 'move') { //Move
$current = rename($source, $target);
} else { //Copy
$current = $this->copyDir($source, $target);
}
if($current === false) $this->pushError($this->translator->_g("Unable to copy/move gallery '%s' because the operation failed.", $galleryId));
else $totalGalleriesMoved++;
}
}
//load target gallery
if($totalGalleriesMoved)
$this->selectGallery($_REQUEST['sgMoveTarget']);
return $totalGalleriesMoved;
}
/**
* Copies everything from directory $fromDir to directory $toDir
* and sets up files mode $chmod
* @author Anton Makarenko <makarenkoa at ukrpost dot net>
*/
function copyDir($fromDir, $toDir)
{
$success = true;
$handle = opendir($fromDir);
//ensure target directory exists
if(!file_exists($toDir))
if(mkdir($toDir))
chmod($toDir, octdec($this->config->directory_mode));
else
return false;
while(false !== ($item = readdir($handle)))
if($item != '.' && $item != '..') {
$from = $fromDir.'/'.$item;
$to = $toDir.'/'.$item;
if(is_dir($from)) {
if($success &= mkdir($to))
chmod($to, octdec($this->config->directory_mode));
//recurse
$this->copyDir($from, $to);
} else {
if($success &= copy($from, $to))
chmod($to, octdec($this->config->file_mode));
}
}
closedir($handle);
return $success;
}
/**
* Creates a gallery.
*
* @return boolean true on success; false otherwise
*/
function addGallery()
{
$newGalleryId = $this->gallery->id."/".$_REQUEST["newgallery"];
$path = $this->config->base_path.$this->config->pathto_galleries.$newGalleryId;
//fail if directory already exists
if(file_exists($path))
return $this->pushError($this->translator->_g("Gallery already exists."));
//create directory or fail
if(!Singapore::mkdir($path))
return $this->pushError($this->translator->_g("Unable to create directory '%s'", $path));
//explicitly set permissions on gallery directory
@chmod($path, octdec($this->config->directory_mode));
$gal =& new sgGallery($newGalleryId, $this->gallery);
$gal->name = $_REQUEST["newgallery"];
//set object owner
if(!$this->user->isGuest())
$gal->owner = $this->user->username;
//save gallery metadata
if($this->io->putGallery($gal))
return true;
else
return $this->pushError($this->translator->_g("Unable to save metadata."));
}
function prepareText($text, $multiline = false)
{
if($multiline) {
$text = strip_tags($text, $this->config->allowed_tags);
$text = str_replace(array("\n","\r"), array("<br />",""), $text);
} else {
$text = htmlspecialchars($text);
}
return $text;
}
/**
* Saves gallery info to the database.
*
* @return boolean true on success; false otherwise
*/
function saveGallery()
{
$this->gallery->categories = $_REQUEST["sgCategories"];
$this->gallery->name = $this->prepareText($_REQUEST["sgGalleryName"]);
$this->gallery->artist = $this->prepareText($_REQUEST["sgArtistName"]);
$this->gallery->email = $this->prepareText($_REQUEST["sgArtistEmail"]);
$this->gallery->date = $this->prepareText($_REQUEST["sgDate"]);
$this->gallery->copyright = $this->prepareText($_REQUEST["sgCopyright"]);
$this->gallery->summary = $this->prepareText($_REQUEST["sgSummary"],true);
$this->gallery->desc = $this->prepareText($_REQUEST["sgGalleryDesc"],true);
if($this->config->enable_clickable_urls) {
//recognise URLs and htmlise them
$this->gallery->desc = preg_replace('{(?<!href="|href=)\b('.SG_REGEXP_PROTOCOLURL.')\b(?!</a>)}', '<a href="$1">$1</a>', $this->gallery->desc); //general protocol match
$this->gallery->desc = preg_replace('{(?<!://)\b('.SG_REGEXP_WWWURL.')\b(?!</a>)}', '<a href="http://$1">$1</a>', $this->gallery->desc); //web addresses starting www. without path info
$this->gallery->desc = preg_replace('{(?<!mailto:|\.)\b('.SG_REGEXP_EMAILURL.')\b(?!</a>)}', '<a href="mailto:$1">$1</a>', $this->gallery->desc); //email addresses *@*.*
}
if($this->io->putGallery($this->gallery))
return true;
else
return $this->pushError($this->translator->_g("Could not save gallery info"));
}
/**
* Deletes a gallery and everything contained within it.
*
* @return boolean true on success; false otherwise
*/
function deleteGallery($galleryId = null)
{
if($galleryId === null)
$galleryId = $_REQUEST['gallery'];
//calculate the path where the folder actually resides.
$path = $this->config->base_path.$this->config->pathto_galleries.$galleryId;
//security check: make sure requested file is in galleries directory
if(!$this->isSubPath($this->config->base_path.$this->config->pathto_galleries,$path))
return $this->pushError($this->translator->_g("Requested item '%s' appears to be outside the galleries directory", $galleryId));
//check that the gallery to delete is not the top level directory
if(realpath($path) == realpath($this->config->base_path.$this->config->pathto_galleries))
return $this->pushError($this->translator->_g("Cannot delete the root gallery."));
//attempt to remove the offending directory and all contained therein
if($this->rmdir_all($path))
return $this->pushMessage($this->translator->_g("Gallery '%s' deleted.", $galleryId));
else
return $this->pushError($this->translator->_g("Unable to delete gallery '%s'.", $galleryId));
}
/**
* Deletes several galleries from the current gallery.
*
* @return int number of galleries deleted
*/
function deleteMultipleGalleries() {
$totalGalleriesDeleted = 0;
foreach($_REQUEST["sgGalleries"] as $galleryId) {
$this->deleteGallery($galleryId);
$totalGalleriesDeleted++;
}
//reload gallery data if we deleted any
if($totalGalleriesDeleted)
$this->selectGallery();
return $totalGalleriesDeleted;
}
/**
* Saves changes to the gallery thumbnail to the database.
*
* @return boolean true on success; false otherwise
*/
function saveGalleryThumbnail()
{
$this->gallery->filename = $_REQUEST['sgThumbName'];
if($this->io->putGallery($this->gallery))
$this->pushMessage($this->translator->_g("Thumbnail changed."));
else
$this->pushError($this->translator->_g("Unable to save metadata."));
}
/**
* Adds an image to the database.
*
* @return boolean true on success; false otherwise
*/
function addImage()
{
if($_REQUEST["sgLocationChoice"] == "remote") {
$image = $_REQUEST["sgImageURL"];
$path = $image;
} elseif($_REQUEST["sgLocationChoice"] == "single") {
//set filename as requested and strip off any clandestine path info
if($_REQUEST["sgNameChoice"] == "same") $image = basename($_FILES["sgImageFile"]["name"]);
else $image = basename($_REQUEST["sgFileName"]);
//make sure image is valid
if(!preg_match("/\.(".$this->config->recognised_extensions.")$/i", $image)) {
$imgInfo = GetImageSize($_FILES["sgImageFile"]["tmp_name"]);
switch($imgInfo[2]) {
case 1 : $image .= '.gif'; break;
case 2 : $image .= '.jpg'; break;
case 3 : $image .= '.png'; break;
case 6 : $image .= '.bmp'; break;
case 7 :
case 8 : $image .= '.tif'; break;
default :
return $this->pushError($this->translator->_g("Uploaded image '%s' has unrecognised extension and image type could not be determined from file contents.", $image));
}
}
$path = $this->config->base_path.$this->config->pathto_galleries.$this->gallery->id."/".$image;
$srcImage = $image;
if(file_exists($path))
switch($this->config->upload_overwrite) {
case 1 : //overwrite
$this->deleteImage($image);
break;
case 2 : //generate unique
for($i=0;file_exists($path);$i++) {
$pivot = strrpos($srcImage,".");
$image = substr($srcImage, 0, $pivot).'-'.$i.substr($srcImage, $pivot,strlen($srcImage)-$pivot);
$path = $this->config->base_path.$this->config->pathto_galleries.$this->gallery->id."/".$image;
}
break;
case 0 : //raise error
default :
return $this->pushError($this->translator->_g("File already exists."));
}
if(!move_uploaded_file($_FILES["sgImageFile"]["tmp_name"],$path))
return $this->pushError($this->translator->_g("Could not upload file."));
// try to change file-permissions
@chmod($path, octdec($this->config->file_mode));
}
$img =& new sgImage($image, $this->gallery);
$img->name = strtr(substr($image, strrpos($image,"/"), strrpos($image,".")-strlen($image)), "_", " ");
list($img->width, $img->height, $img->type) = GetImageSize($path);
//leave owner of guest-uploaded files as default '__nobody__'
if(!$this->user->isGuest())
$img->owner = $this->user->username;
$this->gallery->images[] =& $img;
//set as gallery thumbnail?
if($this->gallery->imageCount()==1)
$this->gallery->filename = $img->id;
if($this->io->putGallery($this->gallery)) {
$this->selectImage($image);
return $this->pushMessage($this->translator->_g("Image added", $image));
} else {
@unlink($path);
return $this->pushError($this->translator->_g("Unable to save metadata."));
}
}
/**
* Adds the contents of an uploaded archive to the database.
*
* @return boolean true on success; false otherwise
*/
function addMultipleImages()
{
//find system temp directory
if(!($systmpdir = $this->findTempDirectory()))
return $this->pushError($this->translator->_g("Unable to find temporary storage space."));
//create new temp directory in system temp dir but stop after 100 attempts
while(!Singapore::mkdir($tmpdir = $systmpdir."/".uniqid("sg")) && $tries++<100);
$archive = $_FILES["sgArchiveFile"]["tmp_name"];
if(!is_uploaded_file($archive))
return $this->pushError($this->translator->_g("Could not upload file."));
//decompress archive to temp
$cmd = escapeshellcmd($this->config->pathto_unzip);
$cmd .= ' -d "'.escapeshellcmd(realpath($tmpdir));
$cmd .= '" "'.escapeshellcmd(realpath($archive)).'"';
if(!exec($cmd))
return $this->pushError($this->translator->_g("Could not decompress archive."));
//start processing archive contents
$wd = $tmpdir;
$contents = $this->getListing($wd,$this->config->recognised_extensions);
//cope with archives contained within a directory
if(empty($contents->files) && count($contents->dirs) == 1)
$contents = $this->getListing($wd .= '/'.$contents->dirs[0],$this->config->recognised_extensions);
$success = true;
 
//add any images to current gallery
foreach($contents->files as $image) {
//check image is valid and ignore it if it isn't
if(!preg_match("/\.(".$this->config->recognised_extensions.")$/i", $image)) {
$imgInfo = GetImageSize($wd.'/'.$image);
switch($imgInfo[2]) {
case 1 : $image .= '.gif'; break;
case 2 : $image .= '.jpg'; break;
case 3 : $image .= '.png'; break;
case 6 : $image .= '.bmp'; break;
case 7 :
case 8 : $image .= '.tif'; break;
default :
$this->pushMessage($this->translator->_g("Uploaded image '%s' has unrecognised extension and image type could not be determined from file contents.", $image));
continue;
}
}
$path = $this->config->pathto_galleries.$this->gallery->id."/".$image;
$srcImage = $image;
if(file_exists($path))
switch($this->config->upload_overwrite) {
case 1 : //overwrite
$this->deleteImage($image);
break;
case 2 : //generate unique
for($i=0;file_exists($path);$i++) {
$pivot = strrpos($srcImage,".");
$image = substr($srcImage, 0, $pivot).'-'.$i.substr($srcImage, $pivot,strlen($srcImage)-$pivot);
$path = $this->config->base_path.$this->config->pathto_galleries.$this->gallery->id."/".$image;
}
break;
case 0 : //raise error
default :
$this->pushError($this->translator->_g("File '%s' already exists."));
$success = false;
continue;
}
copy($wd.'/'.$srcImage,$path);
// try to change file-permissions
@chmod($path, octdec($this->config->file_mode));
$img =& new sgImage($image, $this->gallery);
$img->name = strtr(substr($image, strrpos($image,"/"), strrpos($image,".")-strlen($image)), "_", " ");
list($img->width, $img->height, $img->type) = GetImageSize($path);
 
//leave owner of guest-uploaded files as default '__nobody__'
if(!$this->user->isGuest())
$img->owner = $this->user->username;
$this->gallery->images[] = $img;
}
//add any directories as subgalleries, if allowed
if($this->config->allow_dir_upload == 1 && !$this->user->isGuest()
|| $this->config->allow_dir_upload == 2 && $this->user->isAdmin())
foreach($contents->dirs as $gallery) {
$path = $this->config->pathto_galleries.$this->gallery->id."/".$gallery;
if(file_exists($path))
switch($this->config->upload_overwrite) {
case 1 : //overwrite
$this->deleteGallery($this->gallery->id.'/'.$gallery);
break;
case 2 : //generate unique
for($i=0;file_exists($path);$i++)
$path = $this->config->pathto_galleries.$this->gallery->id."/".$gallery.'-'.$i;
break;
case 0 : //raise error
default :
$this->pushError($this->translator->_g("File '%s' already exists."));
$success = false;
continue;
}
//move from temp dir to gallery
rename($wd.'/'.$gallery, $path);
//change directory permissions (but not contents)
@chmod($path, octdec($this->config->directory_mode));
}
//if images were added save metadata
if(!empty($contents->files))
$this->io->putGallery($this->gallery)
or $this->pushError($this->translator->_g("Unable to save metadata."));
//if subgalleries were added reload gallery data
if(!empty($contents->dirs))
$this->selectGallery();
//remove temporary directory
$this->rmdir_all($tmpdir);
if($success)
return $this->pushMessage($this->translator->_g("Archive contents added."));
else
return $this->pushError($this->translator->_g("Some archive contents could not be added."));
}
/**
* Saves image info to the database.
*
* @return boolean true on success; false otherwise
*/
function saveImage()
{
$this->image->id = $this->prepareText($_REQUEST['image']);
$this->image->thumbnail = $this->prepareText($_REQUEST["sgThumbnail"]);
$this->image->categories = $this->prepareText($_REQUEST["sgCategories"]);
$this->image->name = $this->prepareText($_REQUEST["sgImageName"]);
$this->image->artist = $this->prepareText($_REQUEST["sgArtistName"]);
$this->image->email = $this->prepareText($_REQUEST["sgArtistEmail"]);
$this->image->location = $this->prepareText($_REQUEST["sgLocation"]);
$this->image->date = $this->prepareText($_REQUEST["sgDate"]);
$this->image->copyright = $this->prepareText($_REQUEST["sgCopyright"]);
$this->image->desc = $this->prepareText($_REQUEST["sgImageDesc"],true);
$this->image->camera = $this->prepareText($_REQUEST["sgField01"]);
$this->image->lens = $this->prepareText($_REQUEST["sgField02"]);
$this->image->film = $this->prepareText($_REQUEST["sgField03"]);
$this->image->darkroom = $this->prepareText($_REQUEST["sgField04"]);
$this->image->digital = $this->prepareText($_REQUEST["sgField05"]);
if($this->io->putGallery($this->gallery))
return true;
else
return $this->pushError($this->translator->_g("Unable to save metadata."));
}
/**
* Deletes an image from the current gallery.
*
* @param string the filename of the image to delete (optional)
* @return boolean true on success; false otherwise
*/
function deleteImage($image = null)
{
if($image === null)
$image = $this->image->id;
//if file is remote or doesn't exist then there's no point trying to delete it
if(!sgImage::isRemote($image) && file_exists($this->config->pathto_galleries.$this->gallery->id."/".$image))
//check that we're not being fooled into deleting something we shouldn't
if(!$this->isSubPath($this->config->pathto_galleries, $this->config->pathto_galleries.$this->gallery->id."/".$image))
return $this->pushError($this->translator->_g("Requested item '%s' appears to be outside the galleries directory.", htmlspecialchars($image)));
else
unlink($this->config->pathto_galleries.$this->gallery->id."/".$image);
//remove the image from the images array
foreach($this->gallery->images as $i => $img)
if($img->id == $image) {
array_splice($this->gallery->images,$i,1);
//image removed from array so save metadata
if($this->io->putGallery($this->gallery)) {
//nulling image reference will select parent gallery
$this->image = null;
return $this->pushMessage($this->translator->_g("Image '%s' deleted", htmlspecialchars($image)));
} else {
return $this->pushError($this->translator->_g("Unable to save metadata."));
}
}
//image not found in array
return $this->pushError($this->translator->_g("Image not found '%s'", htmlspecialchars($image)));
}
/**
* Deletes several images from the current gallery.
*
* @return int|false number of images deleted on success; false otherwise
*/
function deleteMultipleImages() {
$deleted = 0;
foreach($_REQUEST["sgImages"] as $image)
if($this->deleteImage($image))
$deleted++;
 
return $deleted;
}
/**
* Deletes the contents of the cache directory.
*
* @return boolean true on success; false otherwise
*/
function purgeCache()
{
$dir = $this->getListing($this->config->pathto_cache, $this->config->recognised_extensions);
$success = true;
for($i=0;$i<count($dir->files);$i++) {
$success &= unlink($dir->path.$dir->files[$i]);
}
return $success;
}
 
}
 
 
?>
/photogallery/includes/config.class.php
0,0 → 1,57
<?php
 
/**
* Config class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: config.class.php,v 1.8 2005/11/30 23:02:18 tamlyn Exp $
*/
 
/**
* Reads configuration data from data/singapore.ini and stores the values
* as properties of itself.
*
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003, 2004 Tamlyn Rhodes
*/
class sgConfig
{
 
/**
* Implements the Singleton design pattern by always returning a reference
* to the same sgConfig object. Use instead of 'new'.
*/
function &getInstance()
{
static $instance;
if(!is_object($instance))
//note that the new config object is NOT assigned by reference as
//references are not stored in static variables (don't ask me...)
$instance = new sgConfig();
return $instance;
}
/**
* Parses an ini file for configuration directives and imports the values
* into the current object overwriting any previous values.
* @param string relative or absolute path to the ini file to load
* @return boolean true on success; false otherwise
*/
function loadConfig($configFilePath)
{
if(!file_exists($configFilePath)) return false;
//get values from ini file
$ini_values = parse_ini_file($configFilePath);
 
//import values into object scope
foreach($ini_values as $key => $value) $this->$key = $value;
return true;
}
}
 
?>
/photogallery/includes/gallery.class.php
0,0 → 1,320
<?php
 
/**
* Gallery class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: gallery.class.php,v 1.19 2006/09/12 11:53:18 thepavian Exp $
*/
 
//include the base class
require_once dirname(__FILE__)."/item.class.php";
/**
* Data-only class used to store gallery data.
*
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003-2005 Tamlyn Rhodes
*/
class sgGallery extends sgItem
{
/**
* Filename of the image used to represent this gallery.
* Special values:
* - __none__ no thumbnail is displayed
* - __random__ a random image is chosen every time
* @var string
*/
var $filename = "__none__";
/**
* Short multiline summary of gallery contents
* @var string
*/
var $summary = "";
/**
* Array of {@link sgImage} objects
* @var array
*/
var $images = array();
/**
* Array of {@link sgGallery} objects
* @var array
*/
var $galleries = array();
/**
* Constructor
* @param string gallery id
* @param sgGallery reference to the parent gallery
*/
function sgGallery($id, &$parent)
{
$this->id = $id;
$this->parent =& $parent;
$this->config =& sgConfig::getInstance();
$this->translator =& Translator::getInstance();
}
/** @return bool true if this is a non-album gallery; false otherwise */
function isGallery() { return $this->hasChildGalleries(); }
/** @return bool true if this is an album; false otherwise */
function isAlbum() { return !$this->isGallery(); }
/** @return bool true if this is the root gallery; false otherwise */
function isRoot() { return $this->id == "."; }
/** @return bool true if this gallery has child galleries; false otherwise */
function hasChildGalleries() { return $this->galleryCount() != 0; }
/** @return bool true if this gallery contains one or more images; false otherwise */
function hasImages() { return $this->imageCount() != 0; }
function imageCount() { return count($this->images); }
function galleryCount() { return count($this->galleries); }
function imageCountText() { return $this->translator->_ng("%s image", "%s images", $this->imageCount()); }
function galleryCountText() { return $this->translator->_ng("%s gallery", "%s galleries", $this->galleryCount()); }
/**
* Caches returned value for use with repeat requests
* @return string the rawurlencoded version of the gallery id
*/
function idEncoded()
{
return isset($this->idEncoded) ? $this->idEncoded : $this->idEncoded = $this->encodeId($this->id);
}
/**
* rawurlencode() supplied string but preserve / character for cosmetic reasons.
* @param string id to encode
* @return string encoded id
* @static
*/
function encodeId($id)
{
$in = explode("/",$id);
$out = array();
for($i=1;$i<count($in);$i++)
$out[$i-1] = rawurlencode($in[$i]);
return $out ? implode("/",$out) : ".";
}
function nameForce()
{
if($this->name)
return $this->name;
elseif($this->isRoot())
return $this->config->gallery_name;
else
return substr($this->id, strrpos($this->id,'/')+1);
}
/**
* If the gallery is an album then it returns the number of
* images contained otherwise the number of sub-galleries is returned
* @return string the contents of the specified gallery
*/
function itemCountText()
{
if($this->isAlbum())
return $this->imageCountText();
else
return $this->galleryCountText();
}
/**
* If the gallery is an album then it returns the number of
* images contained otherwise the number of sub-galleries is returned
* @return int the contents of the specified gallery
*/
function itemCount()
{
if($this->isAlbum())
return $this->imageCount();
else
return $this->galleryCount();
}
/**
* @return int number of galleries in current view
*/
function galleryCountSelected()
{
return min($this->galleryCount() - $this->startat, $this->config->thumb_number_gallery);
}
/**
* @return int number of image in current view
*/
function imageCountSelected()
{
return min($this->imageCount() - $this->startat, $this->config->thumb_number_album);
}
/**
* @return string the absolute, canonical system path to the image
*/
function realPath()
{
return realpath($this->config->base_path.$this->config->pathto_galleries.$this->id);
}
function thumbnailURL($type = "gallery")
{
$thumb = $this->thumbnail($type);
return $thumb->URL();
}
function thumbnailHTML($class = "sgThumbGallery", $type = "gallery")
{
$thumb = $this->thumbnail($type);
if($thumb == null) {
$ret = nl2br($this->translator->_g("No\nthumbnail"));
} else {
$ret = '<img src="'.$thumb->URL().'" ';
$ret .= 'class="'.$class.'" ';
$ret .= 'width="'.$thumb->width().'" height="'.$thumb->height().'" ';
$ret .= 'alt="'.$this->translator->_g("Sample image from gallery").'" />';
}
return $ret;
}
function thumbnailLink($class = "sgThumbGallery", $type = "gallery")
{
return '<a href="'.$this->URL().'">'.$this->thumbnailHTML($class, $type).'</a>';
}
/**
* Removes script-generated HTML (BRs and URLs) but leaves any other HTML
* @return string the summary of the gallery
*/
function summaryStripped()
{
return str_replace("<br />","\n",$this->summary());
}
function hasPrev()
{
return (bool) $this->index();
}
function hasNext()
{
$index = $this->index();
return $index !== false && $index < $this->parent->galleryCount()-1;
}
function &prevGallery()
{
$tmp =& new sgGallery($this->parent->id.'/'.$this->parent->galleries[$this->index()-1], $this->parent);
return $tmp;
}
function &nextGallery()
{
$tmp =& new sgGallery($this->parent->id.'/'.$this->parent->galleries[$this->index()+1], $this->parent);
return $tmp;
}
function prevURL($action = null)
{
$tmp =& $this->prevGallery();
return $tmp->URL(null, $action);
}
function nextURL($action = null)
{
$tmp =& $this->nextGallery();
return $tmp->URL(null, $action);
}
function prevLink($action = null)
{
return '<a href="'.$this->prevURL($action).'">'.$this->prevText().'</a>';
}
function nextLink($action = null)
{
return '<a href="'.$this->nextURL($action).'">'.$this->nextText().'</a>';
}
function prevText()
{
return $this->translator->_g("gallery|Previous");
}
function nextText()
{
return $this->translator->_g("gallery|Next");
}
/**
* finds position of current gallery in parent array
*/
function index()
{
if(!$this->isRoot())
foreach($this->parent->galleries as $key => $galleryId)
if(basename($this->id) == $galleryId)
return $key;
return false;
}
/** Accessor methods */
function summary() { return $this->summary; }
/** Private methods */
function thumbnail($type)
{
//only create thumbnail if it doesn't already exist
if(!isset($this->thumbnails[$type])) {
if($this->filename == "__none__" || $this->imageCount() == 0)
return;
elseif($this->filename == "__random__") {
srand(time()); //seed random number generator and select random image
$img =& $this->images[rand(0,count($this->images)-1)];
} else
$img =& $this->findImage($this->filename);
//create thumbnail
$this->thumbnails[$type] =& new sgThumbnail($img, $type);
}
return $this->thumbnails[$type];
}
/**
* Finds an image from the current gallery
* @param mixed either the filename of the image to select or the integer
* index of its position in the images array
* @return sgImage the image found
*/
function &findImage($image)
{
if(is_string($image))
foreach($this->images as $index => $img)
if($img->id == $image)
return $this->images[$index];
elseif(is_int($image) && $image >= 0 && $image < $this->imageCount())
return $this->images[$image];
return null;
}
}
 
 
?>
/photogallery/includes/image.class.php
0,0 → 1,339
<?php
 
/**
* Image class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: image.class.php,v 1.22 2006/08/06 13:50:20 thepavian Exp $
*/
 
//include the base class
require_once dirname(__FILE__)."/item.class.php";
/**
* Data-only class used to store image data.
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003-2005 Tamlyn Rhodes
*/
class sgImage extends sgItem
{
/**
* Width in pixels of the image
* @var int
*/
var $width = 0;
/**
* Height in pixels of the image
* @var int
*/
var $height = 0;
/**
* Image file format flag as returned by GetImageSize()
* @var int
*/
var $type;
/**
* Configurable field
*/
var $camera = "";
var $lens = "";
var $film = "";
var $darkroom = "";
var $digital = "";
/**
* Constructor
* @param string image id
* @param sgGallery reference to the parent gallery
*/
function sgImage($id, &$parent)
{
$this->id = $id;
$this->parent =& $parent;
$this->config =& sgConfig::getInstance();
$this->translator =& Translator::getInstance();
}
/**
* Over-rides the method in the item class
* @return true returns true
*/
function isImage() { return true; }
/**
* @return bool true if image height is greater than width
*/
function isPortrait()
{
return $this->width()/$this->height() > 1;
}
/**
* @return bool true if image height is greater than width
*/
function isLandscape()
{
return $this->width()/$this->height() < 1;
}
function hasPrev()
{
return (bool) $this->index();
}
function hasNext()
{
$index = $this->index();
return $index !== false && $index < $this->parent->imageCount()-1;
}
function &firstImage()
{
return $this->parent->images[0];
}
function &prevImage()
{
return $this->parent->images[$this->index()-1];
}
function &nextImage()
{
return $this->parent->images[$this->index()+1];
}
function &lastImage()
{
return $this->parent->images[count($this->parent->images)-1];
}
function firstLink($action = null)
{
if(!$this->hasPrev())
return "";
$tmp =& $this->firstImage();
return '<a href="'.$tmp->URL(null, $action).'">'.$this->firstText().'</a>';
}
function prevLink($action = null)
{
if(!$this->hasPrev())
return "";
return '<a href="'.$this->prevURL($action).'">'.$this->prevText().'</a>';
}
function nextLink($action = null)
{
if(!$this->hasNext())
return "";
return '<a href="'.$this->nextURL($action).'">'.$this->nextText().'</a>';
}
function lastLink($action = null)
{
if(!$this->hasNext())
return "";
$tmp =& $this->lastImage();
return '<a href="'.$tmp->URL(null, $action).'">'.$this->lastText().'</a>';
}
function prevURL($action = null)
{
$tmp =& $this->prevImage();
return $tmp->URL(null, $action);
}
function nextURL($action = null)
{
$tmp =& $this->nextImage();
return $tmp->URL(null, $action);
}
function firstText() { return $this->translator->_g("image|First"); }
function prevText() { return $this->translator->_g("image|Previous"); }
function nextText() { return $this->translator->_g("image|Next"); }
function lastText() { return $this->translator->_g("image|Last"); }
function parentText() { return $this->translator->_g("image|Thumbnails"); }
function imageURL()
{
if($this->config->full_image_resize) {
$img = $this->thumbnail("image");
return $img->URL();
} else
return $this->realURL();
}
function realURL()
{
if($this->isRemote())
return $this->id;
else
return $this->config->base_url.$this->config->pathto_galleries.$this->parent->idEncoded()."/".$this->idEncoded();
}
function imageHTML($class = "sgImage")
{
$ret = "<img src=\"".$this->imageURL().'" ';
$ret .= 'class="'.$class.'" ';
$ret .= 'width="'.$this->width().'" height="'.$this->height().'" ';
if($this->config->imagemap_navigation) $ret .= 'usemap="#sgNavMap" border="0" ';
$ret .= 'alt="'.$this->name().$this->byArtistText().'" />';
return $ret;
}
function thumbnailURL($type = "album")
{
$thumb = $this->thumbnail($type);
return $thumb->URL();
}
function thumbnailHTML($class = "sgThumbnailAlbum", $type = "album")
{
$thumb = $this->thumbnail($type);
$ret = "<img src=\"".$thumb->URL().'" ';
$ret .= 'class="'.$class.'" ';
$ret .= 'width="'.$thumb->width().'" height="'.$thumb->height().'" ';
$ret .= 'alt="'.$this->name().$this->byArtistText().'" />';
return $ret;
}
function thumbnailLink($class = "sgThumbnailAlbum", $type = "album")
{
return '<a href="'.$this->URL().'">'.$this->thumbnailHTML($class, $type).'</a>';
}
function thumbnailPopupLink($class = "sgThumbnailAlbum", $type = "album")
{
$ret = '<a href="'.$this->URL().'" onclick="';
$ret .= "window.open('".$this->imageURL()."','','toolbar=0,resizable=1,";
$ret .= "width=".($this->width()+20).",";
$ret .= "height=".($this->height()+20)."');";
$ret .= "return false;\">".$this->thumbnailHTML($class, $type)."</a>";
return $ret;
}
function nameForce()
{
if($this->name)
return $this->name;
elseif($this->isRemote())
return substr($this->id, strrpos($this->id,'/') + 1, strrpos($this->id,'.') - strrpos($this->id,'/') - 1);
else
return substr($this->id, 0, strrpos($this->id,'.'));
}
/**
* checks if image is remote (filename starts with 'http://')
*/
function isRemote($image = null)
{
if($image == null) $image = $this->id;
return substr($image, 0, 7) == "http://";
}
/**
* @return string the absolute, canonical system path to the image
*/
function realPath()
{
if($this->isRemote())
return $this->id;
else
return realpath($this->config->base_path.$this->config->pathto_galleries.$this->parent->id."/".$this->id);
}
/**
* @return string the rawurlencoded version of the image id
*/
function idEncoded()
{
return rawurlencode($this->id);
}
function width()
{
if($this->config->full_image_resize) {
$img = $this->thumbnail("image");
return $img->width();
} else
return $this->realWidth();
}
function height()
{
if($this->config->full_image_resize) {
$img = $this->thumbnail("image");
return $img->height();
} else
return $this->realHeight();
}
/**
* finds position of current image in parent array
*/
function index()
{
foreach($this->parent->images as $key => $img)
if($this->id == $img->id)
return $key;
return false;
}
function realWidth()
{
//try to load image dimensions if not already loaded
if($this->width == 0) {
$size = @GetImageSize($this->realPath());
if($size)
list($this->width, $this->height, $this->type) = $size;
else
return $this->config->thumb_width_image;
}
return $this->width;
}
function realHeight()
{
//try to load image dimensions if not already loaded
if($this->height == 0) {
$size = @GetImageSize($this->realPath());
if($size)
list($this->width, $this->height, $this->type) = $size;
else
return $this->config->thumb_height_image;
}
return $this->height;
}
/** Accessor methods */
function type() { return $this->type; }
/* Private methods */
function &thumbnail($type)
{
//only create thumbnail if it doesn't already exist
if(!isset($this->thumbnails[$type]))
$this->thumbnails[$type] =& new sgThumbnail($this, $type);
return $this->thumbnails[$type];
}
}
 
?>
/photogallery/includes/index.php
0,0 → 1,0
<?php header("Location: ../") ?>
/photogallery/includes/io.class.php
0,0 → 1,174
<?php
 
/**
* IO class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: io.class.php,v 1.11 2005/12/04 04:39:46 tamlyn Exp $
*/
 
/**
* Abstract superclass of all IO classes. Also implements iifn code.
* @package singapore
* @abstract
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003, 2004 Tamlyn Rhodes
*/
class sgIO
{
/**
* Reference to a {@link sgConfig} object representing the current
* script configuration
* @var sgConfig
*/
var $config;
/**
* Constructor. Can be over-ridden by subclass but does not need to be.
* @param sgConfig pointer to current script configuration object
*/
function sgIO()
{
$this->config =& sgConfig::getInstance();
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getName()
{
return "undefined";
}
 
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getVersion()
{
return "undefined";
}
 
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getAuthor()
{
return "undefined";
}
 
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getDescription()
{
return "undefined";
}
 
/**
* Fetches gallery info for the specified gallery (and immediate children).
* @param string gallery id
* @param sgItem reference to parent gallery
* @param int number of levels of child galleries to fetch (optional)
* @param string language code spec for this request (optional, ignored)
*/
function &getGallery($galleryId, &$parent, $getChildGalleries = 1, $language = null)
{
$gal =& new sgGallery($galleryId, $parent);
if(file_exists($this->config->base_path.$this->config->pathto_galleries.$galleryId)) {
$bits = explode("/",$gal->id);
$temp = strtr($bits[count($bits)-1], "_", " ");
if($temp == ".")
$gal->name = $this->config->gallery_name;
elseif($this->config->enable_iifn && strpos($temp, " - "))
list($gal->artist,$gal->name) = explode(" - ", $temp);
else
$gal->name = $temp;
$dir = Singapore::getListing($this->config->base_path.$this->config->pathto_galleries.$gal->id."/", $this->config->recognised_extensions);
//set gallery thumbnail to first image in gallery (if any)
if(isset($dir->files[0])) $gal->filename = $dir->files[0];
for($i=0; $i<count($dir->files); $i++)
//always get the first image for the gallery thumbnail
//but only get the rest if child galleries are requested
if($getChildGalleries || $i==0) {
$gal->images[$i] =& new sgImage($dir->files[$i], $gal);
//trim off file extension and replace underscores with spaces
$temp = strtr(substr($gal->images[$i]->id, 0, strrpos($gal->images[$i]->id,".")-strlen($gal->images[$i]->id)), "_", " ");
//split string in two on " - " delimiter
if($this->config->enable_iifn && strpos($temp, " - "))
list($gal->images[$i]->artist,$gal->images[$i]->name) = explode(" - ", $temp);
else
$gal->images[$i]->name = $temp;
//get image size and type
list(
$gal->images[$i]->width,
$gal->images[$i]->height,
$gal->images[$i]->type
) = @GetImageSize($this->config->base_path.$this->config->pathto_galleries.$gal->id."/".$gal->images[$i]->id);
//set parent link
$gal->images[$i]->parent =& $gal;
} else
//otherwise just create an empty array of the appropriate length
$gal->images[$i] = $dir->files[$i];
} else {
//selected gallery does not exist
return null;
}
//discover child galleries
if($getChildGalleries)
//but only fetch their info if required too
foreach($dir->dirs as $gallery)
$gal->galleries[] =& $this->getGallery($galleryId."/".$gallery, $gal, $getChildGalleries-1, $language);
else
//otherwise just copy their names in so they can be counted
$gal->galleries = $dir->dirs;
return $gal;
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function putGallery($gal) {
return false;
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getHits($gal) {
return false;
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function putHits($gal) {
return false;
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function getUsers() {
return array();
}
/**
* Pseudo-abstract method to be over-ridden in subclasses.
*/
function putUsers($users) {
return false;
}
}
 
?>
/photogallery/includes/io_csv.class.php
0,0 → 1,325
<?php
 
/**
* IO class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: io_csv.class.php,v 1.34 2006/06/25 00:13:56 tamlyn Exp $
*/
 
//include the base IO class
require_once dirname(__FILE__)."/io.class.php";
/**
* Class used to read and write data to and from CSV files.
* @see sgIO_iifn
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003, 2004 Tamlyn Rhodes
*/
class sgIO_csv extends sgIO
{
//constructor provided by parent class
/**
* Name of IO backend.
*/
function getName()
{
return "CSV";
}
 
/**
* Version of IO backend.
*/
function getVersion()
{
return "$Revision: 1.34 $";
}
 
/**
* Author of IO backend.
*/
function getAuthor()
{
return "Tamlyn Rhodes";
}
 
/**
* Brief description of IO backend and it's requirements.
*/
function getDescription()
{
return "Uses comma separated value files. Does not require a database.";
}
 
/**
* Fetches gallery info for the specified gallery and immediate children.
* @param string gallery id
* @param string language code spec for this request (optional)
* @param int number of levels of child galleries to fetch (optional)
* @return sgGallery the gallery object created
*/
function &getGallery($galleryId, &$parent, $getChildGalleries = 1, $language = null)
{
$gal =& new sgGallery($galleryId, $parent);
 
if($language == null) {
$translator =& Translator::getInstance();
$language = $translator->language;
}
//try to open language specific metadata
$fp = @fopen($this->config->base_path.$this->config->pathto_galleries.$galleryId."/metadata.$language.csv","r");
//if fail then try to open generic metadata
if(!$fp)
$fp = @fopen($this->config->base_path.$this->config->pathto_galleries.$galleryId."/metadata.csv","r");
if($fp) {
 
while($temp[] = fgetcsv($fp,2048));
fclose($fp);
list(
$gal->filename,
$gal->thumbnail,
$gal->owner,
$gal->groups,
$gal->permissions,
$gal->categories,
$gal->name,
$gal->artist,
$gal->email,
$gal->copyright,
$gal->desc,
$gal->summary,
$gal->date
) = $temp[1];
//only fetch individual images if child galleries are required
if($getChildGalleries) {
for($i=0;$i<count($temp)-3;$i++) {
$gal->images[$i] =& new sgImage($temp[$i+2][0], $gal, $this->config);
list(,
$gal->images[$i]->thumbnail,
$gal->images[$i]->owner,
$gal->images[$i]->groups,
$gal->images[$i]->permissions,
$gal->images[$i]->categories,
$gal->images[$i]->name,
$gal->images[$i]->artist,
$gal->images[$i]->email,
$gal->images[$i]->copyright,
$gal->images[$i]->desc,
$gal->images[$i]->location,
$gal->images[$i]->date,
$gal->images[$i]->camera,
$gal->images[$i]->lens,
$gal->images[$i]->film,
$gal->images[$i]->darkroom,
$gal->images[$i]->digital
) = $temp[$i+2];
//get image size and type
list(
$gal->images[$i]->width,
$gal->images[$i]->height,
$gal->images[$i]->type
) = @GetImageSize($gal->images[$i]->realPath());
}
//otherwise just fill in empty images
} else if(count($temp) > 3) {
for($i=0;$i<count($temp)-3;$i++)
$gal->images[$i] =& new sgImage($temp[$i+2][0], $gal);
}
} else
//no metadata found so use iifn method implemented in superclass
return parent::getGallery($galleryId, $parent, $getChildGalleries, $language);
//discover child galleries
$dir = Singapore::getListing($this->config->base_path.$this->config->pathto_galleries.$galleryId."/");
if($getChildGalleries)
//but only fetch their info if required too
foreach($dir->dirs as $gallery)
$gal->galleries[] = $this->getGallery($galleryId."/".$gallery, $gal, $getChildGalleries-1, $language);
else
//otherwise just copy their names in so they can be counted
$gal->galleries = $dir->dirs;
return $gal;
}
/**
* Stores gallery information.
* @param sgGallery instance of gallery object to be stored
*/
function putGallery($gal) {
$dataFile = $this->config->base_path.$this->config->pathto_galleries.$gal->id."/metadata.csv";
@chmod($dataFile, octdec($this->config->file_mode));
$fp = @fopen($dataFile,"w");
if(!$fp)
return false;
$success = (bool) fwrite($fp,"filename,thumbnail,owner,group(s),permissions,catergories,image name,artist name,artist email,copyright,image description,image location,date taken,camera info,lens info,film info,darkroom manipulation,digital manipulation");
$success &= (bool) fwrite($fp,"\n\"".
$gal->filename.'",,'.
$gal->owner.','.
$gal->groups.','.
$gal->permissions.','.
$gal->categories.',"'.
str_replace('"','""',$gal->name).'","'.
str_replace('"','""',$gal->artist).'","'.
str_replace('"','""',$gal->email).'","'.
str_replace('"','""',$gal->copyright).'","'.
str_replace('"','""',$gal->desc).'","'.
str_replace('"','""',$gal->summary).'","'.
str_replace('"','""',$gal->date).'"'
);
for($i=0;$i<count($gal->images);$i++)
$success &= (bool) fwrite($fp,"\n\"".
$gal->images[$i]->id.'",,'.
//$gal->images[$i]->thumbnail.','.
$gal->images[$i]->owner.','.
$gal->images[$i]->groups.','.
$gal->images[$i]->permissions.','.
$gal->images[$i]->categories.',"'.
str_replace('"','""',$gal->images[$i]->name).'","'.
str_replace('"','""',$gal->images[$i]->artist).'","'.
str_replace('"','""',$gal->images[$i]->email).'","'.
str_replace('"','""',$gal->images[$i]->copyright).'","'.
str_replace('"','""',$gal->images[$i]->desc).'","'.
str_replace('"','""',$gal->images[$i]->location).'","'.
str_replace('"','""',$gal->images[$i]->date).'","'.
str_replace('"','""',$gal->images[$i]->camera).'","'.
str_replace('"','""',$gal->images[$i]->lens).'","'.
str_replace('"','""',$gal->images[$i]->film).'","'.
str_replace('"','""',$gal->images[$i]->darkroom).'","'.
str_replace('"','""',$gal->images[$i]->digital).'"'
);
$success &= (bool) fclose($fp);
return $success;
}
/**
* Fetches hit data from file.
* @param sgGallery gallery object to load hits into
*/
function getHits(&$gal) {
$fp = @fopen($this->config->base_path.$this->config->pathto_galleries.$gal->id."/hits.csv","r");
if($fp) {
flock($fp, LOCK_SH);
while($temp[] = fgetcsv($fp,255));
flock($fp, LOCK_UN);
fclose($fp);
} else $temp = array();
if(isset($temp[0]))
list(
,
$gal->hits,
$gal->lasthit
) = $temp[0];
for($i=0;$i<count($temp)-2;$i++) {
if(isset($gal->images[$i]) && $temp[$i+1][0] == $gal->images[$i]->id)
list(
,
$gal->images[$i]->hits,
$gal->images[$i]->lasthit
) = $temp[$i+1];
else
foreach($gal->images as $key => $img)
if($temp[$i+1][0] == $img->id)
list(
,
$gal->images[$key]->hits,
$gal->images[$key]->lasthit
) = $temp[$i+1];
}
return true;
}
/**
* Stores gallery hits.
* @param sgGallery gallery object to store
*/
function putHits($gal) {
$logfile = $this->config->base_path.$this->config->pathto_galleries.$gal->id."/hits.csv";
if(!file_exists($logfile) && !@touch($logfile)) return false;
@chmod($logfile, octdec($this->config->file_mode));
$fp = @fopen($logfile,"r+");
if(!$fp) return false;
flock($fp, LOCK_EX);
ftruncate($fp, 0);
fwrite($fp, '"'.
$gal->id.'",'.
$gal->hits.','.
$gal->lasthit
);
foreach($gal->images as $img)
fwrite($fp, "\n\"".
$img->id.'",'.
$img->hits.','.
$img->lasthit
);
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
/**
* Fetches all registered users.
*/
function getUsers() {
$fp = fopen($this->config->base_path.$this->config->pathto_data_dir."users.csv.php","r");
//strip off description line
fgetcsv($fp,1024);
for($i=0;$entry = fgetcsv($fp,1000,",");$i++) {
$users[$i] = new sgUser(null,null);
list(
$users[$i]->username,
$users[$i]->userpass,
$users[$i]->permissions,
$users[$i]->groups,
$users[$i]->email,
$users[$i]->fullname,
$users[$i]->description,
$users[$i]->stats
) = $entry;
}
fclose($fp);
return $users;
}
/**
* Stores all registered users.
* @param array an array of sgUser objects representing the users to store
*/
function putUsers($users) {
$fp = fopen($this->config->base_path.$this->config->pathto_data_dir."users.csv.php","w");
if(!$fp) return false;
$success = (bool) fwrite($fp,"<?php die(\"The contents of this file are hidden\"); ?>username,md5(pass),permissions,group(s),email,name,description,stats\n");
for($i=0;$i<count($users);$i++)
$success &= (bool) fwrite($fp,$users[$i]->username.",".$users[$i]->userpass.",".$users[$i]->permissions.",\"".$users[$i]->groups."\",\"".$users[$i]->email."\",\"".$users[$i]->fullname."\",\"".$users[$i]->description."\",\"".$users[$i]->stats."\"\n");
fclose($fp);
return $success;
}
}
 
?>
/photogallery/includes/io_mysql.class.php
0,0 → 1,91
<?php
 
/**
* IO class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003, 2004 Tamlyn Rhodes
* @version $Id: io_mysql.class.php,v 1.7 2005/11/30 23:02:18 tamlyn Exp $
*/
 
//include the base IO class and generic SQL class
require_once dirname(__FILE__)."/iosql.class.php";
/**
* Class used to read and write data to and from a MySQL database.
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2004 Tamlyn Rhodes
*/
class sgIO_mysql extends sgIOsql
{
/**
* @param sgConfig pointer to a {@link sgConfig} object representing
* the current script configuration
*/
function sgIO_mysql()
{
$this->config =& sgConfig::getInstance();
mysql_connect($this->config->sql_host, $this->config->sql_user, $this->config->sql_pass);
mysql_select_db($this->config->sql_database);
}
 
/**
* Name of IO backend.
*/
function getName()
{
return "MySQL";
}
 
/**
* Version of IO backend.
*/
function getVersion()
{
return "$Revision: 1.7 $";
}
 
/**
* Author of IO backend.
*/
function getAuthor()
{
return "Tamlyn Rhodes";
}
 
/**
* Brief description of IO backend and it's requirements.
*/
function getDescription()
{
return "Uses a MySQL database. Requires a MySQL database server and the MySQL PHP extension.";
}
 
function query($query)
{
return mysql_query($query);
}
function escape_string($query)
{
return mysql_escape_string($query);
}
function fetch_array($res)
{
return mysql_fetch_array($res);
}
function num_rows($res)
{
return mysql_num_rows($res);
}
 
function error()
{
return mysql_error();
}
 
}
 
?>
/photogallery/includes/io_sqlite.class.php
0,0 → 1,95
<?php
 
/**
* IO class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003, 2004 Tamlyn Rhodes
* @version $Id: io_sqlite.class.php,v 1.4 2005/11/30 23:02:18 tamlyn Exp $
*/
 
//include the generic SQL class
require_once dirname(__FILE__)."/iosql.class.php";
/**
* Class used to read and write data to and from a SQLite database.
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2004 Tamlyn Rhodes
*/
class sgIO_sqlite extends sgIOsql
{
/**
* Database resource pointer
*/
var $db;
/**
* @param sgConfig pointer to a {@link sgConfig} object representing
* the current script configuration
*/
function sgIO_sqlite()
{
$this->config =& sgConfig::getInstance();
$this->db = sqlite_open($this->config->base_path.$this->config->pathto_data_dir."sqlite.dat");
}
 
/**
* Name of IO backend.
*/
function getName()
{
return "SQLite";
}
 
/**
* Version of IO backend.
*/
function getVersion()
{
return "$Revision: 1.4 $";
}
 
/**
* Author of IO backend.
*/
function getAuthor()
{
return "Tamlyn Rhodes";
}
 
/**
* Brief description of IO backend and it's requirements.
*/
function getDescription()
{
return "Uses a SQLite database. Requires only the SQLite PHP extension which incorporates the database server.";
}
 
function query($query)
{
return sqlite_query($this->db, $query);
}
function escape_string($query)
{
return sqlite_escape_string($query);
}
function fetch_array($res)
{
return sqlite_fetch_array($res);
}
function num_rows($res)
{
return sqlite_num_rows($res);
}
 
function error()
{
return sqlite_error_string(sqlite_last_error($this->db));
}
 
}
 
?>
/photogallery/includes/iosql.class.php
0,0 → 1,252
<?php
 
/**
* IO class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003, 2004 Tamlyn Rhodes
* @version $Id: iosql.class.php,v 1.5 2006/01/22 03:25:36 tamlyn Exp $
*/
 
//include the base IO class
require_once dirname(__FILE__)."/io.class.php";
/**
* Class used to read and write data to and from a MySQL database.
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2004 Tamlyn Rhodes
*/
class sgIOsql extends sgIO
{
/**
* Overridden in subclasses
*/
function query($query) { }
function escape_string($query) { }
function fetch_array($res) { }
function num_rows($res) { }
function error()
{
return "unknown error";
}
/**
* Fetches gallery info for the specified gallery and immediate children.
* @param string gallery id
* @param string language code spec for this request (optional)
* @param int number of levels of child galleries to fetch (optional)
*/
function &getGallery($galleryId, &$parent, $getChildGalleries = 1, $language = null)
{
$gal =& new sgGallery($galleryId, $parent);
if($language == null) $language = $this->config->default_language;
//try to open language specific gallery info
$res = $this->query("SELECT * FROM ".$this->config->sql_prefix."galleries ".
"WHERE id='".$this->escape_string($galleryId)."' ".
"AND lang='".$this->escape_string($language)."'");
//if fail then try to open generic gallery info
if(!$res || !$this->num_rows($res))
$res = $this->query("SELECT * FROM ".$this->config->sql_prefix."galleries ".
"WHERE id='".$this->escape_string($galleryId)."' and lang=''");
//if that succeeds then get galleries from db
if($res && $this->num_rows($res)) {
$galinfo = $this->fetch_array($res);
$gal->filename = $galinfo['filename'];
$gal->owner = $galinfo['owner'];
$gal->groups = $galinfo['groups'];
$gal->permissions = $galinfo['permissions'];
$gal->categories = $galinfo['categories'];
$gal->name = $galinfo['name'];
$gal->artist = $galinfo['artist'];
$gal->email = $galinfo['email'];
$gal->copyright = $galinfo['copyright'];
$gal->desc = $galinfo['description'];
$gal->summary = $galinfo['summary'];
$gal->date = $galinfo['date'];
$gal->hits = $galinfo['hits'];
$gal->lasthit = $galinfo['lasthit'];
//try to open language specific image info
$res = $this->query("SELECT * FROM ".$this->config->sql_prefix."images ".
"WHERE galleryid='".$this->escape_string($galleryId)."' ".
"AND lang='".$this->escape_string($language)."'");
//if fail then try to open generic image info
if(!$res || !$this->num_rows($res))
$res = $this->query("SELECT * FROM ".$this->config->sql_prefix."images ".
"WHERE galleryid='".$this->escape_string($galleryId)."' and lang=''");
for($i=0;$i<$this->num_rows($res);$i++) {
$imginfo = $this->fetch_array($res);
$gal->images[$i] =& new sgImage($imginfo['filename'], $gal);
$gal->images[$i]->thumbnail = $imginfo['thumbnail'];
$gal->images[$i]->owner = $imginfo['owner'];
$gal->images[$i]->groups = $imginfo['groups'];
$gal->images[$i]->permissions = $imginfo['permissions'];
$gal->images[$i]->categories = $imginfo['categories'];
$gal->images[$i]->name = $imginfo['name'];
$gal->images[$i]->artist = $imginfo['artist'];
$gal->images[$i]->email = $imginfo['email'];
$gal->images[$i]->copyright = $imginfo['copyright'];
$gal->images[$i]->desc = $imginfo['description'];
$gal->images[$i]->location = $imginfo['location'];
$gal->images[$i]->date = $imginfo['date'];
$gal->images[$i]->camera = $imginfo['camera'];
$gal->images[$i]->lens = $imginfo['lens'];
$gal->images[$i]->film = $imginfo['film'];
$gal->images[$i]->darkroom = $imginfo['darkroom'];
$gal->images[$i]->digital = $imginfo['digital'];
$gal->images[$i]->width = $imginfo['width'];
$gal->images[$i]->height = $imginfo['height'];
$gal->images[$i]->type = $imginfo['type'];
$gal->images[$i]->hits = $imginfo['hits'];
$gal->images[$i]->lasthit = $imginfo['lasthit'];
}
} else
//no record found so use iifn method implemented in parent class
return parent::getGallery($galleryId, $parent, $getChildGalleries, $language);
//discover child galleries
$dir = Singapore::getListing($this->config->base_path.$this->config->pathto_galleries.$galleryId."/");
if($getChildGalleries)
//but only fetch their info if required too
foreach($dir->dirs as $gallery)
$gal->galleries[] =& $this->getGallery($galleryId."/".$gallery, $gal, $getChildGalleries-1, $language);
else
//otherwise just copy their names in so they can be counted
$gal->galleries = $dir->dirs;
return $gal;
}
/**
* Stores gallery information.
* @param sgGallery instance of gallery object to be stored
*/
function putGallery($gal, $language = "") {
//insert gallery info
$success = (bool) $this->query("REPLACE INTO ".$this->config->sql_prefix."galleries ".
"(id,lang,filename,owner,groups,permissions,categories,name,artist,".
"email,copyright,description,summary,date,hits,lasthit) VALUES ('".
$this->escape_string($gal->id)."','".$language."','".
$this->escape_string($gal->filename)."','".
$gal->owner."','".$gal->groups."',".$gal->permissions.",'".
$this->escape_string($gal->categories)."','".
$this->escape_string($gal->name)."','".
$this->escape_string($gal->artist)."','".
$this->escape_string($gal->email)."','".
$this->escape_string($gal->copyright)."','".
$this->escape_string($gal->desc)."','".
$this->escape_string($gal->summary)."','".
$this->escape_string($gal->date)."',".
$gal->hits.",".$gal->lasthit.")");
//delete all image info
$success &= (bool) $this->query("DELETE FROM ".$this->config->sql_prefix."images ".
"WHERE galleryid='".$this->escape_string($gal->id)."' AND lang='".$language."'");
for($i=0;$i<count($gal->images);$i++) {
$success &= (bool) $this->query("INSERT INTO ".$this->config->sql_prefix."images ".
"(galleryid,lang,filename,owner,groups,permissions,categories,name,artist,".
"email,copyright,description,location,date,camera,lens,film,darkroom,digital,".
"width,height,type,hits,lasthit) VALUES ('".
$this->escape_string($gal->id)."','".$language."','".
$this->escape_string($gal->images[$i]->id)."','".
$gal->images[$i]->owner."','".$gal->images[$i]->groups."',".
$gal->images[$i]->permissions.",'".
$this->escape_string($gal->images[$i]->categories)."','".
$this->escape_string($gal->images[$i]->name)."','".
$this->escape_string($gal->images[$i]->artist)."','".
$this->escape_string($gal->images[$i]->email)."','".
$this->escape_string($gal->images[$i]->copyright)."','".
$this->escape_string($gal->images[$i]->desc)."','".
$this->escape_string($gal->images[$i]->location)."','".
$this->escape_string($gal->images[$i]->date)."','".
$this->escape_string($gal->images[$i]->camera)."','".
$this->escape_string($gal->images[$i]->lens)."','".
$this->escape_string($gal->images[$i]->film)."','".
$this->escape_string($gal->images[$i]->darkroom)."','".
$this->escape_string($gal->images[$i]->digital)."',".
$gal->images[$i]->width.",".$gal->images[$i]->height.",".
$gal->images[$i]->type.",".$gal->images[$i]->hits.",".
$gal->images[$i]->lasthit.")");
}
return $success;
}
/**
* Hits are loaded by getGallery so this method does nothing
* @param sgGallery gallery object to load hits into
*/
function getHits(&$gal) {
return true;
}
/**
* Stores gallery hits.
* @param sgGallery gallery object to store
*/
function putHits($gal) {
//if gallery data doesn't exist in database, add it
$res = $this->query("SELECT id FROM ".$this->config->sql_prefix."galleries ".
"WHERE id='".$this->escape_string($gal->id)."'");
if(!$res || !$this->num_rows($res))
$this->putGallery($gal);
$success = (bool) $this->query("UPDATE ".$this->config->sql_prefix."galleries ".
"SET hits=".$gal->hits.", lasthit=".$gal->lasthit." ".
"WHERE id='".$this->escape_string($gal->id)."'");
foreach($gal->images as $img)
$success &= (bool) $this->query("UPDATE ".$this->config->sql_prefix."images ".
"SET hits=".$img->hits.", lasthit=".$img->lasthit." ".
"WHERE galleryid='".$this->escape_string($gal->id)."' ".
"AND filename='".$this->escape_string($img->id)."'");
return $success;
}
/**
* Fetches all registered users.
*/
function getUsers() {
$res = $this->query("SELECT * FROM ".$this->config->sql_prefix."users");
for($i=0;$i<$this->num_rows($res);$i++) {
$usrinfo = $this->fetch_array($res);
$users[$i] = new sgUser($usrinfo['username'],$usrinfo['userpass']);
$users[$i]->permissions = $usrinfo['permissions'];
$users[$i]->groups = $usrinfo['groups'];
$users[$i]->email = $usrinfo['email'];
$users[$i]->fullname = $usrinfo['fullname'];
$users[$i]->description = $usrinfo['description'];
$users[$i]->stats = $usrinfo['stats'];
}
return $users;
}
/**
* Stores all registered users.
* @param array an array of sgUser objects representing the users to store
*/
function putUsers($users) {
//empty table
$success = (bool) $this->query("DELETE FROM ".$this->config->sql_prefix."users");
for($i=0;$i<count($users);$i++)
$success &= (bool) $this->query("INSERT INTO ".$this->config->sql_prefix."users ".
"(username,userpass,permissions,groups,email,fullname,description,stats) VALUES ('".
$this->escape_string($users[$i]->username)."','".
$users[$i]->userpass."',".$users[$i]->permissions.",'".
$this->escape_string($users[$i]->groups)."','".
$this->escape_string($users[$i]->email)."','".
$this->escape_string($users[$i]->fullname)."','".
$this->escape_string($users[$i]->description)."','".
$this->escape_string($users[$i]->stats)."')");
return $success;
}
}
 
?>
/photogallery/includes/item.class.php
0,0 → 1,297
<?php
 
/**
* Singapore gallery item class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2005-6 Tamlyn Rhodes
* @version $Id: item.class.php,v 1.10 2006/09/08 15:29:22 tamlyn Exp $
*/
 
//permissions bit flags
define("SG_GRP_READ", 1);
define("SG_GRP_EDIT", 2);
define("SG_GRP_ADD", 4);
define("SG_GRP_DELETE", 8);
define("SG_WLD_READ", 16);
define("SG_WLD_EDIT", 32);
define("SG_WLD_ADD", 64);
define("SG_WLD_DELETE", 128);
define("SG_IHR_READ", 17);
define("SG_IHR_EDIT", 34);
define("SG_IHR_ADD", 68);
define("SG_IHR_DELETE", 136);
 
/**
* Abstract class from which sgImage and sgGallery are derived.
*
* @abstract
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2005-6 Tamlyn Rhodes
*/
class sgItem
{
/**
* The id of the item. In the case of galleries this is the path to the
* gallery from root and must be unique. For images it is the image file
* name (or URL for remote images).
* @var string
*/
var $id;
/**
* Username of the user to which the item belongs
* @var string
*/
var $owner = "__nobody__";
/**
* Space-separated list of groups to which the item belongs
* @var string
*/
var $groups = "";
/**
* Bit-field of permissions
* Default is to inherit everything.
* @var int
*/
var $permissions = 255;
/**
* Space-separated list of categories to which the item belongs (not used)
* @var string
*/
var $categories = "";
/**
* The name or title of the item
* @var string
*/
var $name = "";
/**
* The name of the original item creator (or anyone else)
* @var string
*/
var $artist = "";
/**
* Email of the original item creator (or anyone else)
* @var string
*/
var $email = "";
/**
* Optional copyright information
* @var string
*/
var $copyright = "";
/**
* Multiline description of the item
* @var string
*/
var $desc = "";
/**
* Date associated with item
* @var string
*/
var $date = "";
var $location = "";
/**
* Number of times item has been viewed
* @var int
*/
var $hits = 0;
/**
* Unix timestamp of last time item was viewed
* @var int
*/
var $lasthit = 0;
/**
* Pointer to the parent sgItem
* @var sgItem
*/
var $parent;
/**
* Reference to the current config object
* @var sgConfig
*/
var $config;
/**
* Reference to the current translator object
* @var Translator
*/
var $translator;
/**
* Array in which the various sized thumbnails representing this item are stored
* @var array
*/
var $thumbnails = array();
/** Accessor methods */
function name() { return $this->name; }
function artist() { return $this->artist; }
function date() { return $this->date; }
function location() { return $this->location; }
function description() { return $this->desc; }
function canEdit() { return false; }
function idEntities() { return htmlspecialchars($this->id); }
/**
* Removes script-generated HTML (BRs and URLs) but leaves any other HTML
* @return string the description of the item
*/
function descriptionStripped()
{
$ret = str_replace("<br />","\n",$this->description());
if($this->config->enable_clickable_urls) {
//strip off html from autodetected URLs
$ret = preg_replace('{<a href="('.SG_REGEXP_PROTOCOLURL.')\">\1</a>}', '\1', $ret);
$ret = preg_replace('{<a href="http://('.SG_REGEXP_WWWURL.')">\1</a>}', '\1', $ret);
$ret = preg_replace('{<a href="mailto:('.SG_REGEXP_EMAILURL.')">\1</a>}', '\1', $ret);
}
return $ret;
}
/**
* If the current item has an artist specified, returns " by " followed
* by the artist's name. Otherwise returns an empty string.
* @return string
*/
function byArtistText()
{
if(empty($this->artist))
return "";
else
return " ".$this->translator->_g("artist name|by %s",$this->artist);
}
/**
* Obfuscates the given email address by replacing "." with "dot" and "@" with "at"
* @param boolean override the obfuscate_email config setting (optional)
* @return string obfuscated email address or HTML mailto link
*/
function emailLink($forceObfuscate = false)
{
if($this->config->obfuscate_email || $forceObfuscate)
return strtr($this->email,array("@" => ' <b>'.$this->translator->_g("email|at").'</b> ', "." => ' <b>'.$this->translator->_g("email|dot").'</b> '));
else
return "<a href=\"mailto:".$this->email."\">".$this->email."</a>";
}
 
function nameLink($action = null)
{
return '<a href="'.$this->URL(0, $action).'">'.$this->nameForce().'</a>';
}
function parentURL($action = null)
{
$perpage = $this->parent->isAlbum() ? $this->config->thumb_number_album : $this->config->thumb_number_gallery;
return $this->parent->URL(floor($this->index() / $perpage) * $perpage, $action);
}
function parentLink($action = null)
{
return '<a href="'.$this->parentURL($action).'">'.$this->parentText().'</a>';
}
function parentText()
{
return $this->translator->_g("gallery|Up");
}
/**
* @return array associative array of item properties in the form "name" => "value"
*/
function detailsArray()
{
$ret = array();
//generic properties
if(!empty($this->date)) $ret[$this->translator->_g("Date")] = $this->date;
if(!empty($this->location)) $ret[$this->translator->_g("Location")] = $this->location;
if(!empty($this->desc)) $ret[$this->translator->_g("Description")] = $this->desc;
if(!empty($this->email)) $ret[$this->translator->_g("Email")] = $this->emailLink();
//image properties
if(!empty($this->camera)) $ret[$this->translator->_g("Camera")] = $this->camera;
if(!empty($this->lens)) $ret[$this->translator->_g("Lens")] = $this->lens;
if(!empty($this->film)) $ret[$this->translator->_g("Film")] = $this->film;
if(!empty($this->darkroom)) $ret[$this->translator->_g("Darkroom manipulation")] = $this->darkroom;
if(!empty($this->digital)) $ret[$this->translator->_g("Digital manipulation")] = $this->digital;
//special properties
if(!empty($this->copyright)) $ret[$this->translator->_g("Copyright")] = $this->copyright;
elseif(!empty($this->artist))$ret[$this->translator->_g("Copyright")] = $this->artist;
if($this->config->show_views)
$ret[$this->translator->_g("Viewed")] = $this->translator->_ng("viewed|%s time", "viewed|%s times",$this->hits);
return $ret;
}
function isAlbum() { return false; }
function isGallery() { return false; }
function isImage() { return false; }
 
/**
* Returns a link to the image or gallery with the correct formatting and path
*
* @param int page offset (optional)
* @param string action to perform (optional)
* @return string formatted URL
*/
function URL($startat = null, $action = null)
{
$query = array();
if($this->config->use_mod_rewrite) { //format url for use with mod_rewrite
$ret = $this->config->base_url;
$ret .= $this->isImage() ? $this->parent->idEncoded() : $this->idEncoded();
if($startat) $ret .= ','.$startat;
$ret .= '/';
if($this->isImage()) $ret .= $this->idEncoded();
if($action) $query[] = $this->config->url_action."=".$action;
if($this->translator->language != $this->config->default_language) $query[] = $this->config->url_lang.'='.$this->translator->language;
if($GLOBALS["sg"]->template != $this->config->default_template) $query[] = $this->config->url_template.'='.$GLOBALS["sg"]->template;
if(!empty($query))
$ret .= '?'.implode(ini_get('arg_separator.output'), $query);
} else { //format plain url
$query[] = $this->config->url_gallery."=".($this->isImage() ? $this->parent->idEncoded() : $this->idEncoded());
if($this->isImage()) $query[] = $this->config->url_image."=".$this->idEncoded();
if($startat) $query[] = $this->config->url_startat."=".$startat;
if($action) $query[] = $this->config->url_action."=".$action;
if($this->translator->language != $this->config->default_language)
$query[] = $this->config->url_lang.'='.$this->translator->language;
if(isset($GLOBALS["sg"]->template) && $GLOBALS["sg"]->template != $this->config->default_template)
$query[] = $this->config->url_template.'='.$GLOBALS["sg"]->template;
$ret = $this->config->index_file_url.implode(ini_get('arg_separator.output'), $query);
}
return $ret;
}
}
 
 
?>
/photogallery/includes/singapore.class.php
0,0 → 1,976
<?php
 
/**
* Main class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2006 Tamlyn Rhodes
* @version $Id: singapore.class.php,v 1.75 2006/09/12 11:56:11 thepavian Exp $
*/
 
//define constants for regular expressions
define('SG_REGEXP_PROTOCOLURL', '(?:http://|https://|ftp://|mailto:)(?:[a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,4}(?::[0-9]+)?(?:/[^ \n\r\"\'<]+)?');
define('SG_REGEXP_WWWURL', 'www\.(?:[a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,4}(?:/[^ \n\r\"\'<]+)?');
define('SG_REGEXP_EMAILURL', '(?:[\w][\w\.\-]+)+@(?:[\w\-]+\.)+[a-zA-Z]{2,4}');
 
/**
* Provides functions for handling galleries and images
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
*/
class Singapore
{
/**
* current script version
* @var string
*/
var $version = "0.10.1";
/**
* instance of a {@link sgConfig} object representing the current
* script configuration
* @var sgConfig
*/
var $config;
/**
* instance of the currently selected IO handler object
* @var sgIO_csv
*/
var $io;
/**
* instance of a {@link Translator}
* @var Translator
*/
var $translator;
/**
* instance of a {@link sgGallery} representing the current gallery
* @var sgGallery
*/
var $gallery;
/**
* reference to the currently selected {@link sgImage} object in the
* $images array of {@link $gallery}
* @var sgImage
*/
var $image;
/**
* two character code of language currently in use
* @var string
*/
var $language = null;
/**
* name of template currently in use
* @var string
*/
var $template = null;
/**
* details of current user
* @var sgUser
*/
var $user = null;
/**
* name of action requested
* @var string
*/
var $action = null;
/**
* Constructor, does all init type stuff. This code is a total mess.
* @param string the path to the base singapore directory
*/
function Singapore($basePath = "")
{
//import class definitions
//io handler class included once config is loaded
require_once $basePath."includes/translator.class.php";
require_once $basePath."includes/thumbnail.class.php";
require_once $basePath."includes/gallery.class.php";
require_once $basePath."includes/config.class.php";
require_once $basePath."includes/image.class.php";
require_once $basePath."includes/user.class.php";
//start execution timer
$this->scriptStartTime = microtime();
//remove slashes
if(get_magic_quotes_gpc())
$_REQUEST = array_map(array("Singapore","arraystripslashes"), $_REQUEST);
//desanitize request
$_REQUEST = array_map("htmlentities", $_REQUEST);
//load config from singapore root directory
$this->config =& sgConfig::getInstance();
$this->config->loadConfig($basePath."singapore.ini");
$this->config->loadConfig($basePath."secret.ini.php");
//if instantiated remotely...
if(!empty($basePath)) {
//...try to guess base path and relative url
if(empty($this->config->base_path))
$this->config->base_path = $basePath;
if(empty($this->config->base_url))
$this->config->base_url = $basePath;
//...load local config if present
//may over-ride guessed values above
$this->config->loadConfig("singapore.local.ini");
}
//set current gallery to root if not specified in url
$galleryId = isset($_REQUEST[$this->config->url_gallery]) ? $_REQUEST[$this->config->url_gallery] : ".";
//load config from gallery ini file (gallery.ini) if present
$this->config->loadConfig($basePath.$this->config->pathto_galleries.$galleryId."/gallery.ini");
//set current template from request vars or config
//first, preset template to default one
$this->template = $this->config->default_template;
//then check if requested template exists
if(!empty($_REQUEST[$this->config->url_template])) {
$templates = Singapore::getListing($this->config->base_path.$this->config->pathto_templates);
foreach($templates->dirs as $single) {
if($single == $_REQUEST[$this->config->url_template]) {
$this->template = $single;
break;
}
}
}
 
$this->config->pathto_current_template = $this->config->pathto_templates.$this->template.'/';
//load config from template ini file (template.ini) if present
$this->config->loadConfig($basePath.$this->config->pathto_current_template."template.ini");
//set runtime values
$this->config->pathto_logs = $this->config->pathto_data_dir."logs/";
$this->config->pathto_cache = $this->config->pathto_data_dir."cache/";
$this->config->pathto_admin_template = $this->config->pathto_templates.$this->config->admin_template_name."/";
//set current language from request vars or config
if(!empty($_REQUEST[$this->config->url_lang]))
$this->language = $_REQUEST[$this->config->url_lang];
else {
$this->language = $this->config->default_language;
if($this->config->detect_language)
foreach($this->getBrowserLanguages() as $lang)
if($lang=="en" || file_exists($basePath.$this->config->pathto_locale."singapore.".$lang.".pmo")) {
$this->language = $lang;
break;
}
}
//read the language file
$this->translator =& Translator::getInstance($this->language);
$this->translator->readLanguageFile($this->config->base_path.$this->config->pathto_locale."singapore.".$this->language.".pmo");
//clear the UMASK
umask(0);
//include IO handler class and create instance
require_once $basePath."includes/io_".$this->config->io_handler.".class.php";
$ioClassName = "sgIO_".$this->config->io_handler;
$this->io = new $ioClassName($this->config);
//load gallery and image info
$this->selectGallery($galleryId);
//set character set
if(!empty($this->translator->languageStrings[0]["charset"]))
$this->character_set = $this->translator->languageStrings[0]["charset"];
else
$this->character_set = $this->config->default_charset;
//set action to perform
if(empty($_REQUEST["action"])) $this->action = "view";
else $this->action = $_REQUEST["action"];
}
/**
* Load gallery and image info
* @param string the id of the gallery to load (optional)
*/
function selectGallery($galleryId = "")
{
if(empty($galleryId)) $galleryId = isset($_REQUEST[$this->config->url_gallery]) ? $_REQUEST[$this->config->url_gallery] : ".";
//try to validate gallery id
if(strlen($galleryId)>1 && $galleryId{1} != '/') $galleryId = './'.$galleryId;
//detect back-references to avoid file-system walking
if(strpos($galleryId,"../")!==false) $galleryId = ".";
//find all ancestors to current gallery
$this->ancestors = array();
$ancestorNames = explode("/", $galleryId);
$numberOfAncestors = count($ancestorNames);
//construct fully qualified gallery ids
$ancestorIds[0] = ".";
for($i=1; $i<$numberOfAncestors; $i++)
$ancestorIds[$i] = $ancestorIds[$i-1]."/".$ancestorNames[$i];
//fetch galleries passing previous gallery as parent pointer
for($i=0; $i<$numberOfAncestors; $i++)
if(!$this->ancestors[$i] =& $this->io->getGallery(
$ancestorIds[$i], $this->ancestors[$i-1],
//only fetch children of bottom level gallery
($i==$numberOfAncestors-1) ? 1 : 0
)
)
break;
//need to remove bogus parent of root gallery created by previous step
unset($this->ancestors[-1]);
//set reference to current gallery
$this->gallery = &$this->ancestors[count($this->ancestors)-1];
//check if gallery was successfully fetched
if($this->gallery == null) {
$this->gallery = new sgGallery($galleryId, $this->ancestors[0]);
$this->gallery->name = $this->translator->_g("Gallery not found '%s'",htmlspecialchars($galleryId));
}
//sort galleries and images
$GLOBALS["sgSortOrder"] = $this->config->gallery_sort_order;
if($this->config->gallery_sort_order!="x") usort($this->gallery->galleries, array("Singapore","multiSort"));
$GLOBALS["sgSortOrder"] = $this->config->image_sort_order;
if($this->config->image_sort_order!="x") usort($this->gallery->images, array("Singapore","multiSort"));
unset($GLOBALS["sgSortOrder"]);
//if startat is set then cast to int otherwise startat 0
$this->gallery->startat = isset($_REQUEST[$this->config->url_startat]) ? (int)$_REQUEST[$this->config->url_startat] : 0;
$this->startat = $this->gallery->startat; //depreciated
//select the image (if any)
if(!empty($_REQUEST[$this->config->url_image]))
$this->selectImage($_REQUEST[$this->config->url_image]);
//load hit data
if($this->config->track_views || $this->config->show_views)
$this->io->getHits($this->gallery);
//update and save hit data
if($this->config->track_views) {
if($this->isImagePage()) {
$this->image->hits++;
$this->image->lasthit = time();
} elseif($this->gallery->startat == 0) {
$this->gallery->hits++;
$this->gallery->lasthit = time();
}
$this->io->putHits($this->gallery);
}
}
/**
* Selects an image from the current gallery
* @param mixed either the filename of the image to select or the integer
* index of its position in the images array
* @return boolean true on success; false otherwise
*/
function selectImage($image)
{
if(is_string($image)) {
foreach($this->gallery->images as $index => $img)
if($img->id == $image) {
$this->image =& $this->gallery->images[$index];
return true;
}
} elseif(is_int($image) && $image >= 0 && $image < count($this->gallery->images)) {
$this->image =& $this->gallery->images[$image];
return true;
}
$this->image =& new sgImage("", $this->gallery);
$this->image->name = $this->translator->_g("Image not found '%s'",htmlspecialchars($image));
return false;
}
/**
* Obfuscates the given email address by replacing "." with "dot" and "@" with "at"
* @param string email address to obfuscate
* @param boolean override the obfuscate_email config setting (optional)
* @return string obfuscated email address or HTML mailto link
*/
function formatEmail($email, $forceObfuscate = false)
{
if($this->config->obfuscate_email || $forceObfuscate)
return strtr($email,array("@" => ' <b>'.$this->translator->_g("email|at").'</b> ', "." => ' <b>'.$this->translator->_g("email|dot").'</b> '));
else
return "<a href=\"mailto:".$email."\">".$email."</a>";
}
 
/**
* Returns image name for image pages and gallery name for gallery pages.
* If either of these is empty, returns gallery_name config option.
*
* @return string Title of current page
*/
function pageTitle()
{
$crumbArray = $this->crumbLineArray();
$ret = "";
for($i=count($crumbArray)-1;$i>0;$i--)
$ret .= $crumbArray[$i]->nameForce()." &lt; ";
$ret .= $crumbArray[$i]->nameForce();
return $ret;
}
/**
* @return bool true if this is an image page; false otherwise
*/
function isImagePage()
{
return !empty($this->image);
}
/**
* @return bool true if this is a non-album gallery page; false otherwise
*/
function isGalleryPage()
{
return !empty($this->gallery) && $this->gallery->galleryCount()>0;;
}
/**
* @return bool true if this is an album page; false otherwise
*/
function isAlbumPage()
{
return !$this->isGalleryPage() && !$this->isImagePage() && !empty($this->gallery);
}
/**
* @return int the script execution time in seconds rounded to two decimal places
*/
function scriptExecTime()
{
$scriptStartTime = $this->scriptStartTime;
$scriptEndTime = microtime();
list($usec, $sec) = explode(" ",$scriptStartTime);
$scriptStartTime = (float)$usec + (float)$sec;
list($usec, $sec) = explode(" ",$scriptEndTime);
$scriptEndTime = (float)$usec + (float)$sec;
$scriptExecTime = floor(($scriptEndTime - $scriptStartTime)*100)/100;
return $scriptExecTime;
}
/**
* Displays the script execution time if configured to do so
* @returns string the script execution time
*/
function scriptExecTimeText()
{
if($this->config->show_execution_time)
return $this->translator->_g("Page created in %s seconds",$this->scriptExecTime());
else
return "";
}
function poweredByText()
{
return $this->translator->_g("Powered by").' <a href="http://www.sgal.org/">singapore</a>';
}
function allRightsReserved()
{
return $this->translator->_g("All rights reserved.");
}
function licenseText()
{
return $this->translator->_g("Images may not be reproduced in any form without the express written permission of the copyright holder.");
}
function adminURL()
{
return '<a href="'.$this->config->base_url.'admin.php">';
}
function adminLink()
{
return $this->adminURL().$this->translator->_g("Log in")."</a>";
}
/**
* Checks to see if the user is currently logged in to admin mode. Also resets
* the login timeout to the current time.
* @returns boolean true if the user is logged in; false otherwise
* @static
*/
function isLoggedIn()
{
if(
isset($this->user) &&
$_SESSION["sgUser"]["ip"] == $_SERVER["REMOTE_ADDR"] &&
(time() - $_SESSION["sgUser"]["loginTime"] < 600)
) {
//reset loginTime to current time
$_SESSION["sgUser"]["loginTime"] = time();
return true;
}
return false;
}
function loadUser($username = null)
{
if($username == null)
if(isset($_SESSION["sgUser"]))
$username = $_SESSION["sgUser"]["username"];
else
return false;
$users = $this->io->getUsers();
foreach($users as $user)
if($user->username == $username) {
$this->user = $user;
return $user;
}
return false;
}
/**
* Creates an array of objects each representing an item in the crumb line.
* @return array the items of the crumb line
*/
function crumbLineArray()
{
$crumb = $this->ancestors;
if($this->isImagePage()) $crumb[] = $this->image;
return $crumb;
}
/**
* @return string the complete crumb line with links
*/
function crumbLineText()
{
$crumbArray = $this->crumbLineArray();
 
$ret = "";
for($i=0;$i<count($crumbArray)-1;$i++)
$ret .= $crumbArray[$i]->nameLink()." &gt;\n";
$ret .= $crumbArray[$i]->nameForce();
 
return $ret;
}
function crumbLine()
{
return $this->translator->_g("crumb line|You are here:")." ".$this->crumbLineText();
}
/**
* Generates the HTML code for imagemap_navigation
* @return string imagemap HTML code
*/
function imageMap()
{
if(!$this->config->imagemap_navigation) return "";
$imageWidth = $this->image->width();
$imageHeight = $this->image->height();
$middleX = round($imageWidth/2);
$middleY = round($imageHeight/2);
$ret = "<map name=\"sgNavMap\" id=\"sgNavMap\">\n";
if($this->image->hasNext()) $ret .= '<area href="'.$this->image->nextURL().'" alt="'.$this->image->nextText().'" title="'.$this->image->nextText().'" shape="poly" ';
else $ret .= '<area href="'.$this->image->parentURL().'" alt="'.$this->image->parentText().'" title="'.$this->image->parentText().'" shape="poly" ';
$ret .= "coords=\"$middleX,$middleY,$imageWidth,$imageHeight,$imageWidth,0,$middleX,$middleY\" />\n";
if($this->image->hasPrev()) $ret .= '<area href="'.$this->image->prevURL().'" alt="'.$this->image->prevText().'" title="'.$this->image->prevText().'" shape="poly" ';
else $ret .= '<area href="'.$this->image->parentURL().'" alt="'.$this->image->parentText().'" title="'.$this->image->parentText().'" shape="poly" ';
$ret .= "coords=\"$middleX,$middleY,0,0,0,$imageHeight,$middleX,$middleY\" />\n";
$ret .= '<area href="'.$this->image->parentURL().'" alt="'.$this->image->parentText().'" title="'.$this->image->parentText().'" shape="poly" ';
$ret .= "coords=\"$middleX,$middleY,0,0,$imageWidth,0,$middleX,$middleY\" />\n";
$ret .= '</map>';
return $ret;
}
/**
* Generates the HTML code for the language select box
* @return string select box HTML code
*/
function languageFlipper()
{
if(!$this->config->language_flipper) return "";
$languageCache = $this->config->base_path.$this->config->pathto_data_dir."languages.cache";
// Look for the language file
if(!file_exists($languageCache))
return "";
// Open the file
$fp = @fopen($languageCache, "r");
if (!$fp) return "";
// Read contents
$str = '';
while (!feof($fp)) $str .= fread($fp, 1024);
// Unserialize
$availableLanguages = @unserialize($str);
$ret = '<div class="sgLanguageFlipper">';
$ret .= '<form method="get" action="'.$_SERVER["PHP_SELF"]."\">\n";
//carry over current get vars
foreach($_GET as $var => $val)
$ret .= '<input type="hidden" name="'.$var.'" value="'.htmlspecialchars($val)."\" />\n";
$ret .= '<select name="'.$this->config->url_lang."\">\n";
$ret .= ' <option value="'.$this->config->default_language.'">'.$this->translator->_g("Select language...")."</option>\n";
foreach($availableLanguages as $code => $name) {
$ret .= ' <option value="'.$code.'"';
if($code == $this->language && $this->language != $this->config->default_language)
$ret .= 'selected="true" ';
$ret .= '>'.htmlentities($name)."</option>\n";
}
$ret .= "</select>\n";
$ret .= '<input type="submit" class="button" value="'.$this->translator->_g("Go")."\" />\n";
$ret .= "</form></div>\n";
return $ret;
}
/**
* Generates the HTML code for the template select box
* @return string select box HTML code
*/
function templateFlipper()
{
if(!$this->config->template_flipper) return "";
//get list of installed templates
$templates = Singapore::getListing($this->config->base_path.$this->config->pathto_templates, "dirs");
$ret = '<div class="sgTemplateFlipper">';
$ret .= '<form method="get" action="'.$_SERVER["PHP_SELF"]."\">\n";
//carry over current get vars
foreach($_GET as $var => $val)
$ret .= '<input type="hidden" name="'.$var.'" value="'.htmlspecialchars($val)."\" />\n";
$ret .= '<select name="'.$this->config->url_template."\">\n";
$ret .= ' <option value="'.$this->config->default_template.'">'.$this->translator->_g("Select template...")."</option>\n";
foreach($templates->dirs as $name)
//do not list admin template(s)
if(strpos($name, "admin_")===false) {
$ret .= ' <option value="'.$name.'"';
if($name == $this->template && $this->template != $this->config->default_template)
$ret .= 'selected="true" ';
$ret .= '>'.$name."</option>\n";
}
$ret .= "</select>\n";
$ret .= '<input type="submit" class="button" value="'.$this->translator->_g("Go")."\" />\n";
$ret .= "</form></div>\n";
return $ret;
}
/**
* @param string $seperator optional string to seperate the Gallery Tab Links
* @return string
*/
function galleryTab($seperator = " | ")
{
$showing = $this->galleryTabShowing();
return Singapore::conditional($this->galleryTabLinks(), $showing.$seperator."%s", $showing);
}
/**
* @return string
*/
function galleryTabShowing()
{
if($this->isAlbumPage()) {
$total = $this->gallery->imageCount();
$perPage = $this->config->thumb_number_album;
} else {
$total = $this->gallery->galleryCount();
$perPage = $this->config->thumb_number_gallery;
}
if($this->gallery->startat+$perPage > $total)
$last = $total;
else
$last = $this->gallery->startat+$perPage;
return $this->translator->_g("Showing %s-%s of %s",($this->gallery->startat+1),$last,$total);
}
/**
* @return string
*/
function galleryTabLinks()
{
$ret = "";
if($this->hasPrevPage())
$ret .= $this->prevPageLink()." ";
//This is for compatibility with old templates
//it detects if compatibility mode is on using method_exists()
if(!$this->gallery->isRoot() && method_exists($this, 'galleryName'))
$ret .= $this->gallery->parentLink();
if($this->hasNextPage())
$ret .= " ".$this->nextPageLink();
return $ret;
}
function navigationLinks() {
$ret = "<link rel=\"Top\" title=\"".$this->config->gallery_name."\" href=\"".$this->ancestors[0]->URL()."\" />\n";
if($this->isImagePage()) {
$ret .= "<link rel=\"Up\" title=\"".$this->image->parent->name()."\" href=\"".$this->image->parent->URL()."\" />\n";
if ($this->image->hasPrev()) {
$first= $this->image->firstImage();
$prev = $this->image->prevImage();
$ret .= "<link rel=\"First\" title=\"".$first->name()."\" href=\"".$first->URL()."\" />\n";
$ret .= "<link rel=\"Prev\" title=\"".$prev->name()."\" href=\"".$prev->URL()."\" />\n";
}
if ($this->image->hasNext()) {
$next = $this->image->nextImage();
$last = $this->image->lastImage();
$ret .= "<link rel=\"Next\" title=\"".$next->name()."\" href=\"".$next->URL()."\" />\n";
$ret .= "<link rel=\"Last\" title=\"".$last->name()."\" href=\"".$last->URL()."\" />\n";
//prefetch next image
$ret .= "<link rel=\"Prefetch\" href=\"".$next->imageURL()."\" />\n";
}
} else {
if(!$this->gallery->isRoot())
$ret .= "<link rel=\"Up\" title=\"".$this->gallery->parent->name()."\" href=\"".$this->gallery->parent->URL()."\" />\n";
if($this->hasPrevPage()) {
$ret .= "<link rel=\"Prev\" title=\"".$this->translator->_g("gallery|Previous")."\" href=\"".$this->prevPageURL()."\" />\n";
$ret .= "<link rel=\"First\" title=\"".$this->translator->_g("gallery|First")."\" href=\"".$this->firstPageURL()."\" />\n";
}
if($this->hasNextPage()) {
$ret .= "<link rel=\"Next\" title=\"".$this->translator->_g("gallery|Next")."\" href=\"".$this->nextPageURL()."\" />\n";
$ret .= "<link rel=\"Last\" title=\"".$this->translator->_g("gallery|Last")."\" href=\"".$this->lastPageURL()."\" />\n";
}
}
return $ret;
}
/**
* @return int the number of 'pages' or 'screen-fulls'
*/
function galleryPageCount() {
if($this->isAlbumPage())
return intval($this->gallery->imageCount()/$this->config->thumb_number_album)+1;
else
return intval($this->gallery->galleryCount()/$this->config->thumb_number_gallery)+1;
}
/**
* @return int
*/
function lastPageIndex() {
if($this->isAlbumPage())
return ($this->galleryPageCount()-1)*
($this->isAlbumPage()?$this->config->thumb_number_album:$this->config->thumb_number_gallery);
}
/**
* @return bool true if there is at least one more page
*/
function hasNextPage() {
if($this->isAlbumPage())
return count($this->gallery->images)>$this->startat+$this->config->thumb_number_album;
elseif($this->isGalleryPage())
return count($this->gallery->galleries)>$this->startat+$this->config->thumb_number_gallery;
elseif($this->isImagePage())
return isset($this->gallery->images[$this->image->index+1]);
}
/**
* @return bool true if there is at least one previous page
*/
function hasPrevPage() {
if($this->isAlbumPage() || $this->isGalleryPage())
return $this->startat > 0;
elseif($this->isImagePage())
return isset($this->gallery->images[$this->image->index-1]);
}
function firstPageURL() {
return $this->gallery->URL(0);
}
function firstPageLink() {
return "<a href=\"".$this->firstPageURL()."\">".$this->translator->_g("First %s", $this->itemsPerPage())."</a>";
}
/**
* @return string the URL of the previous page
*/
function prevPageURL() {
return $this->gallery->URL($this->startat - $this->itemsPerPage());
}
function prevPageLink() {
return "<a href=\"".$this->prevPageURL()."\">".$this->translator->_g("Previous %s", $this->itemsPerPage())."</a>";
}
/**
* @return string the URL of the next page
*/
function nextPageURL() {
return $this->gallery->URL($this->startat + $this->itemsPerPage());
}
function nextPageLink() {
return "<a href=\"".$this->nextPageURL()."\">".$this->translator->_g("Next %s", $this->itemsPerPage())."</a>";
}
function lastPageURL() {
$perpage = $this->isAlbumPage() ? $this->config->thumb_number_album : $this->config->thumb_number_gallery;
return $this->gallery->URL(floor($this->gallery->itemCount() / $perpage) * $perpage);
}
function lastPageLink() {
return "<a href=\"".$this->lastPageURL()."\">".$this->translator->_g("Last %s", $this->itemsPerPage())."</a>";
}
function itemsPerPage()
{
return $this->isAlbumPage() ? $this->config->thumb_number_album : $this->config->thumb_number_gallery;
}
/**
* @return string link for adding a comment to image
*/
function imageCommentLink()
{
return "<a href=\"".
$this->formatURL($this->gallery->idEncoded(), $this->image->id, null, "addcomment").
"\">".$this->translator->_g("Add a comment")."</a>";
}
/**
* @return array array of sgImage objects
*/
function &previewThumbnailsArray()
{
$ret = array();
$index = $this->image->index();
$start = ceil($index - $this->config->thumb_number_preview/2);
for($i = $start; $i < $start + $this->config->thumb_number_preview; $i++)
if(isset($this->image->parent->images[$i]))
$ret[$i] =& $this->image->parent->images[$i];
return $ret;
}
function previewThumbnails()
{
$thumbs =& $this->previewThumbnailsArray();
$index = $this->image->index();
$ret = "";
foreach($thumbs as $key => $thumb) {
$thumbClass = "sgThumbnailPreview";
if($key==$index-1) $thumbClass .= " sgThumbnailPreviewPrev";
elseif($key==$index) $thumbClass .= " sgThumbnailPreviewCurrent";
elseif($key==$index+1) $thumbClass .= " sgThumbnailPreviewNext";
$ret .= $thumb->thumbnailLink($thumbClass, "preview")."\n";
}
return $ret;
}
//////////////////////////////
//////ex-sgUtils methods//////
//////////////////////////////
/**
* Callback function for sorting things
* @static
*/
function multiSort($a, $b) {
switch($GLOBALS["sgSortOrder"]) {
case "f" :
case "p" : return strcmp($a->id, $b->id); //path
case "F" :
case "P" : return strcmp($b->id, $a->id); //path (reverse)
case "n" : return strcmp($a->name, $b->name); //name
case "N" : return strcmp($b->name, $a->name); //name (reverse)
case "i" : return strcasecmp($a->name, $b->name); //case-insensitive name
case "I" : return strcasecmp($b->name, $a->name); //case-insensitive name (reverse)
case "a" : return strcmp($a->artist, $b->artist); //artist
case "A" : return strcmp($b->artist, $a->artist); //artist (reverse)
case "d" : return strcmp($a->date, $b->date); //date
case "D" : return strcmp($b->date, $a->date); //date (reverse)
case "l" : return strcmp($a->location, $b->location); //location
case "L" : return strcmp($b->location, $a->location); //location (reverse)
}
}
/**
* Slightly pointless method
*/
function conditional($conditional, $iftrue, $iffalse = null)
{
if($conditional) return sprintf($iftrue, $conditional);
elseif($iffalse != null) return sprintf($iffalse, $conditional);
else return "";
}
/**
* Callback function for recursively stripping slashes
* @static
*/
function arraystripslashes($toStrip)
{
if(is_array($toStrip))
return array_map(array("Singapore","arraystripslashes"), $toStrip);
else
return stripslashes($toStrip);
}
function thumbnailPath($gallery, $image, $width, $height, $forceSize, $mode = 1)
{
$config =& sgConfig::getInstance();
switch($mode) {
case 0 :
return $config->pathto_data_dir."cache/".$width."x".$height.($forceSize?"f":"").strtr("-$gallery-$image",":/?\\","----");
case 1 :
return $config->pathto_galleries.$gallery."/_thumbs/".$width."x".$height.($forceSize?"f":"").strtr("-$image",":/?\\","----");
}
}
/**
* @param string relative or absolute path to directory
* @param string regular expression of files to return (optional)
* @param bool true to get hidden directories too
* @returns stdClass|false a data object representing the directory and its contents
* @static
*/
function getListing($wd, $mask = null, $getHidden = false)
{
$dir = new stdClass;
$dir->path = realpath($wd)."/";
$dir->files = array();
$dir->dirs = array();
$dp = opendir($dir->path);
if(!$dp) return false;
 
while(false !== ($entry = readdir($dp)))
if(is_dir($dir->path.$entry)) {
if(($entry{0} != '.' && $entry{0} != '_') || $getHidden)
$dir->dirs[] = $entry;
} else {
if($mask == null || preg_match("/\.($mask)$/i",$entry))
$dir->files[] = $entry;
}
sort($dir->files);
sort($dir->dirs);
closedir($dp);
return $dir;
}
/**
* Recursively deletes all directories and files in the specified directory.
* USE WITH EXTREME CAUTION!!
* @returns boolean true on success; false otherwise
* @static
*/
function rmdir_all($wd)
{
if(!$dp = opendir($wd)) return false;
$success = true;
while(false !== ($entry = readdir($dp))) {
if($entry == "." || $entry == "..") continue;
if(is_dir("$wd/$entry")) $success &= Singapore::rmdir_all("$wd/$entry");
else $success &= unlink("$wd/$entry");
}
closedir($dp);
$success &= rmdir($wd);
return $success;
}
/**
* Returns an array of language codes specified in the Accept-Language HHTP
* header field of the user's browser. q= components are ignored and removed.
* hyphens (-) are converted to underscores (_).
* @return array accepted language codes
* @static
*/
function getBrowserLanguages()
{
$langs = array();
foreach(explode(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]) as $bit)
if($pos = strpos($bit,";"))
$langs[] = strtr(substr($bit,0,$pos),"-","_");
else
$langs[] = strtr($bit,"-","_");
return $langs;
}
/**
* Wrapper for mkdir() implementing the safe-mode hack
*/
function mkdir($path)
{
$config =& sgConfig::getInstance();
if($config->safe_mode_hack) {
$connection = ftp_connect($config->ftp_server);
// login to ftp server
$result = ftp_login($connection, $config->ftp_user, $config->ftp_pass);
// check if connection was made
if ((!$connection) || (!$result))
return false;
ftp_chdir($connection, $config->ftp_base_path); // go to destination dir
if(!ftp_mkdir($connection, $path)) // create directory
return false;
ftp_site($connection, "CHMOD ".$config->directory_mode." ".$path);
ftp_close($connection); // close connection
return true;
} else
return mkdir($path, octdec($config->directory_mode));
}
/**
* Tests if $child is within or is the same path as $parent.
*
* @param string path to parent directory
* @param string path to child directory or file
* @param bool set false to prevent canonicalisation of paths (optional)
* @return bool true if $child is contained within or is $parent
*/
function isSubPath($parent, $child, $canonicalise = true)
{
$parentPath = $canonicalise ? realpath($parent) : $parent;
$childPath = $canonicalise ? realpath($child) : $child;
return $parentPath && $childPath && substr($childPath,0,strlen($parentPath)) == $parentPath;
}
 
 
function isInGroup($groups1,$groups2)
{
return (bool) array_intersect(explode(" ",$groups1),explode(" ",$groups2));
}
}
 
 
?>
/photogallery/includes/thumbnail.class.php
0,0 → 1,228
<?php
 
/**
* Thumbnail class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: thumbnail.class.php,v 1.13 2006/06/24 20:33:00 tamlyn Exp $
*/
 
 
/**
* Creates and manages image thumbnails
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003-2005 Tamlyn Rhodes
*/
class sgThumbnail
{
var $config;
var $maxWidth = 0;
var $maxHeight = 0;
var $thumbWidth = 0;
var $thumbHeight = 0;
var $cropWidth = 0;
var $cropHeight = 0;
var $forceSize = false;
var $imagePath = "";
var $thumbPath = "";
function sgThumbnail(&$img, $type)
{
$this->config =& sgConfig::getInstance();
$this->image =& $img;
$widthVar = "thumb_width_".$type;
$heightVar = "thumb_height_".$type;
$cropVar = "thumb_crop_".$type;
$this->maxWidth = $this->config->$widthVar;
$this->maxHeight = $this->config->$heightVar;
if(isset($this->config->$cropVar))
$this->forceSize = $this->config->$cropVar;
if($this->image == null) return;
$this->imagePath = $this->image->realPath();
$this->thumbPath = $this->config->base_path.Singapore::thumbnailPath($this->image->parent->id, $this->image->id, $this->maxWidth, $this->maxHeight, $this->forceSize);
$this->thumbURL = $this->config->base_url .Singapore::thumbnailPath($this->image->parent->id, $this->image->id, $this->maxWidth, $this->maxHeight, $this->forceSize);
 
//security check: make sure requested file is in galleries directory
if(!Singapore::isSubPath($this->config->base_path.$this->config->pathto_galleries, $this->imagePath) && !$this->image->isRemote())
return;
//security check: make sure $image has a valid extension
if(!$this->image->isRemote() && !preg_match("/.+\.(".$this->config->recognised_extensions.")$/i",$this->image->id))
return;
$this->calculateDimensions();
//link straight to image if it smaller than required size
if($this->image->width <= $this->thumbWidth && $this->image->height <= $this->thumbHeight) {
$this->thumbURL = $this->image->realURL();
return;
}
$imageModified = @filemtime($this->imagePath);
$thumbModified = @filemtime($this->thumbPath);
if($imageModified > $thumbModified || !$thumbModified)
$this->buildThumbnail();
}
/** Accessor methods */
function width() { return $this->thumbWidth; }
function height() { return $this->thumbHeight; }
function URL() { return $this->thumbURL; }
/** Private methods */
/**
* Calculates thumbnail dimensions.
*/
function calculateDimensions()
{
//if aspect ratio is to be constrained set crop size
if($this->forceSize) {
$newAspect = $this->maxWidth/$this->maxHeight;
$oldAspect = $this->image->realWidth()/$this->image->realHeight();
if($newAspect > $oldAspect) {
$this->cropWidth = $this->image->realWidth();
$this->cropHeight = round($this->image->realHeight()*($oldAspect/$newAspect));
} else {
$this->cropWidth = round($this->image->realWidth()*($newAspect/$oldAspect));
$this->cropHeight = $this->image->realHeight();
}
//else crop size is image size
} else {
$this->cropWidth = $this->image->realWidth();
$this->cropHeight = $this->image->realHeight();
}
if($this->cropHeight > $this->maxHeight && ($this->cropWidth <= $this->maxWidth
|| ($this->cropWidth > $this->maxWidth && round($this->cropHeight/$this->cropWidth * $this->maxWidth) > $this->maxHeight))) {
$this->thumbWidth = round($this->cropWidth/$this->cropHeight * $this->maxHeight);
$this->thumbHeight = $this->maxHeight;
} elseif($this->cropWidth > $this->maxWidth) {
$this->thumbWidth = $this->maxWidth;
$this->thumbHeight = round($this->cropHeight/$this->cropWidth * $this->maxWidth);
} else {
$this->thumbWidth = $this->image->realWidth();
$this->thumbHeight = $this->image->realHeight();
}
}
function buildThumbnail() {
//set cropping offset
$cropX = floor(($this->image->width-$this->cropWidth)/2);
$cropY = floor(($this->image->height-$this->cropHeight)/2);
//check thumbs directory exists and create it if not
if(!file_exists(dirname($this->thumbPath)))
Singapore::mkdir(dirname($this->thumbPath));
//if file is remote then copy locally first
if($this->image->isRemote()) {
$ip = @fopen($this->imagePath, "rb");
$tp = @fopen($this->thumbPath, "wb");
if($ip && $tp) {
while(fwrite($tp,fread($ip, 4095)));
fclose($tp);
fclose($ip);
$this->imagePath = $this->thumbPath;
}
}
switch($this->config->thumbnail_software) {
case "im" : //use ImageMagick v5.x
$cmd = '"'.$this->config->pathto_convert.'"';
if($this->forceSize) $cmd .= " -crop {$this->cropWidth}x{$this->cropHeight}+{$this->cropX}+{$this->cropY}";
$cmd .= " -geometry {$this->thumbWidth}x{$this->thumbHeight}";
if($this->image->type == 2) $cmd .= " -quality ".$this->config->thumbnail_quality;
if($this->config->progressive_thumbs) $cmd .= " -interlace Plane";
if($this->config->remove_jpeg_profile) $cmd .= ' +profile "*"';
$cmd .= ' '.escapeshellarg($this->imagePath).' '.escapeshellarg($this->thumbPath);
exec($cmd);
break;
case "im6" : //use ImageMagick v6.x
$cmd = '"'.$this->config->pathto_convert.'"';
$cmd .= ' '.escapeshellarg($this->imagePath);
if($this->config->progressive_thumbs) $cmd .= " -interlace Plane";
if($this->image->type == 2) $cmd .= " -quality ".$this->config->thumbnail_quality;
if($this->forceSize) $cmd .= " -crop {$this->cropWidth}x{$this->cropHeight}+{$this->cropX}+{$this->cropY}";
$cmd .= " -resize {$this->thumbWidth}x{$this->thumbHeight}";
if($this->config->remove_jpeg_profile) $cmd .= ' +profile "*"';
$cmd .= ' '.escapeshellarg($this->thumbPath);
exec($cmd);
break;
case "gd2" :
case "gd1" :
default : //use GD by default
//read in image as appropriate type
switch($this->image->type) {
case 1 : $image = ImageCreateFromGIF($this->imagePath); break;
case 3 : $image = ImageCreateFromPNG($this->imagePath); break;
case 2 :
default: $image = ImageCreateFromJPEG($this->imagePath); break;
}
if($image) {
switch($this->config->thumbnail_software) {
case "gd2" :
//create blank truecolor image
$thumb = ImageCreateTrueColor($this->thumbWidth,$this->thumbHeight);
//resize image with resampling
ImageCopyResampled(
$thumb, $image,
0, 0, $cropX, $cropY,
$this->thumbWidth, $this->thumbHeight, $this->cropWidth, $this->cropHeight);
break;
case "gd1" :
default :
//create blank 256 color image
$thumb = ImageCreate($this->thumbWidth,$this->thumbHeight);
//resize image
ImageCopyResized(
$thumb, $image,
0, 0, $cropX, $cropY,
$this->thumbWidth, $this->thumbHeight, $this->cropWidth, $this->cropHeight);
break;
}
} /*else {
$thumb = ImageCreate($this->thumbWidth, $this->thumbHeight);
$bg = ImageColorAllocate($thumb, 255, 255, 255);
$text = ImageColorAllocate($thumb, 255, 0, 0);
ImageString($thumb, 1, 0, 0, "Cannot load source image", $text);
}*/
//set image interlacing
@ImageInterlace($thumb, $this->config->progressive_thumbs);
//output image of appropriate type
switch($this->image->type) {
case 1 :
//GIF images are saved as PNG
case 3 :
ImagePNG($thumb, $this->thumbPath);
break;
case 2 :
default:
ImageJPEG($thumb, $this->thumbPath, $this->config->thumbnail_quality);
break;
}
@ImageDestroy($image);
@ImageDestroy($thumb);
}
//set file permissions on newly created thumbnail
@chmod($this->thumbPath, octdec($this->config->file_mode));
}
 
}
 
?>
/photogallery/includes/translator.class.php
0,0 → 1,160
<?php
 
/**
* Translation class.
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003-2005 Tamlyn Rhodes
* @version $Id: translator.class.php,v 1.5 2006/02/06 18:47:57 tamlyn Exp $
*/
/**
* Provides functions for translating strings using GNU Gettext PO files
* @package singapore
* @author Joel Sjögren <joel dot sjogren at nonea dot se>
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003, 2004 Tamlyn Rhodes
*/
class Translator
{
/**
* Array of language strings in the form
* "english string" => "foreign string"
* @private
* @var array
*/
var $languageStrings = array();
var $language = "en";
/**
* Constructor
* @param string language code
* @private
*/
function Translator($language)
{
$this->language = $language;
}
/**
* Implements a version of the Singleton design pattern by always returning
* a reference to the same Translator object for each language. If no
* language is specified then the first loaded Translator is returned.
* @param string language code (optional)
* @static
*/
function &getInstance($language = 0)
{
static $instances = array();
$key = empty($instances) ? 0 : $language;
if(!isset($instances[$key]))
//note that the new object is NOT assigned by reference as
//references are not stored in static variables (don't ask me...)
$instances[$key] = new Translator($language);
return $instances[$key];
}
/**
* Reads a language file and saves the strings in an array.
* Note that the language code is used in the filename for the
* datafile, and is case sensitive.
*
* @author Joel Sjögren <joel dot sjogren at nonea dot se>
* @param string file to load
* @return bool success
*/
function readLanguageFile($languageFile)
{
// Look for the language file
if(!file_exists($languageFile))
return false;
// Open the file
$fp = @fopen($languageFile, "r");
if (!$fp) return false;
// Read contents
$str = '';
while (!feof($fp)) $str .= fread($fp, 1024);
// Unserialize
$newStrings = @unserialize($str);
//Append new strings to current languageStrings array
$this->languageStrings = array_merge($this->languageStrings, $newStrings);
// Return successful
return (bool) $newStrings;
}
/**
* Returns a translated string, or the same if no language is chosen.
* You can pass more arguments to use for replacement within the
* string - just like sprintf(). It also removes anything before
* the first | in the text to translate. This is used to distinguish
* strings with different meanings, but with the same spelling.
* Examples:
* _g("Text");
* _g("Use a %s to drink %s", _g("glass"), "water");
*
* @author Joel Sjögren <joel dot sjogren at nonea dot se>
* @param string text to translate
* @return string translated string
*/
function _g ($text)
{
// String exists and is not empty?
if(!empty($this->languageStrings[$text])) {
$text = $this->languageStrings[$text];
} else {
$text = preg_replace("/^[^\|]*\|/", "", $text);
}
// More arguments were passed? sprintf() them...
if (func_num_args() > 1) {
$args = func_get_args();
array_shift($args);
//preg_match_all("/%((\d+\\\$)|.)/", str_replace("%%", "", $text), $m);
//while (count($args) < count($m[0])) $args[] = '';
$text = vsprintf($text, $args);
}
return $text;
}
/**
* Plural form of _g().
*
* @param string singular form of text to translate
* @param string plural form of text to translate
* @param string number
* @return string translated string
*/
function _ng ($msgid1, $msgid2, $n)
{
//calculate which plural to use
if(!empty($this->languageStrings[0]["plural"]))
eval($this->languageStrings[0]["plural"]);
else
$plural = $n==1?0:1;
// String exists and is not empty?
if (!empty($this->languageStrings[$msgid1][$plural])) {
$text = $this->languageStrings[$msgid1][$plural];
} else {
$text = preg_replace("/^[^\|]*\|/", "", ($n == 1 ? $msgid1 : $msgid2));
}
if (func_num_args() > 3) {
$args = func_get_args();
array_shift($args);
array_shift($args);
return vsprintf($text, $args);
}
return sprintf($text, $n);
}
}
 
?>
/photogallery/includes/user.class.php
0,0 → 1,121
<?php
 
/**
* User class.
*
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License
* @copyright (c)2003, 2004 Tamlyn Rhodes
* @version $Id: user.class.php,v 1.5 2006/03/14 19:38:54 tamlyn Exp $
*/
 
/**
* Class used to represent a user.
* @package singapore
* @author Tamlyn Rhodes <tam at zenology dot co dot uk>
* @copyright (c)2003, 2004 Tamlyn Rhodes
*/
class sgUser
{
/**
* Username of user. Special cases are 'guest' and 'admin'.
* @var string
*/
var $username = "";
 
/**
* MD5 hash of password
* @var string
*/
var $userpass = "5f4dcc3b5aa765d61d8327deb882cf99";
/**
* Bit-field of permissions
* @var int
*/
var $permissions = 0;
/**
* Space-separated list of groups of which the user is a member
* @var string
*/
var $groups = "";
/**
* Email address of user
* @var string
*/
var $email = "";
/**
* The name or title of the user
* @var string
*/
var $fullname = "";
/**
*Description of user account
* @var string
*/
var $description = "";
/**
* Statistics (what's this? I don't know!)
* @var string
*/
var $stats = "";
/**
* Constructor ensures username and userpass have values
*/
function sgUser($username, $userpass)
{
$this->username = $username;
$this->userpass = $userpass;
}
/**
* Checks if currently logged in user is an administrator.
*
* @return bool true on success; false otherwise
*/
function isAdmin()
{
return $this->permissions & SG_ADMIN;
}
/**
* Checks if currently logged in user is a guest.
*
* @return bool true on success; false otherwise
*/
function isGuest()
{
return $this->username == "guest";
}
/**
* Checks if this user is the owner of the specified item.
*
* @param sgItem the item to check
* @return bool true if this user is the owner; false otherwise
*/
function isOwner($item)
{
return $item->owner == $this->username;
}
/**
* Checks if this user is a member of the group(s) supplied
*
* @return bool true on success; false otherwise
*/
function isInGroup($groups)
{
return (bool) array_intersect(explode(" ",$groups),explode(" ",$this->groups));
}
}
 
?>
/photogallery/singapore_gallery_files/includes/io_sqlite.class.php
File deleted
/photogallery/singapore_gallery_files/includes/admin.class.php
File deleted
/photogallery/singapore_gallery_files/includes/translator.class.php
File deleted
/photogallery/singapore_gallery_files/includes/io_mysql.class.php
File deleted
/photogallery/singapore_gallery_files/includes/item.class.php
File deleted
/photogallery/singapore_gallery_files/includes/user.class.php
File deleted
/photogallery/singapore_gallery_files/includes/gallery.class.php
File deleted
/photogallery/singapore_gallery_files/includes/image.class.php
File deleted
/photogallery/singapore_gallery_files/includes/io_csv.class.php
File deleted
/photogallery/singapore_gallery_files/includes/index.php
File deleted
\ No newline at end of file
/photogallery/singapore_gallery_files/includes/thumbnail.class.php
File deleted
/photogallery/singapore_gallery_files/includes/config.class.php
File deleted
/photogallery/singapore_gallery_files/includes/iosql.class.php
File deleted
/photogallery/singapore_gallery_files/includes/io.class.php
File deleted
/photogallery/singapore_gallery_files/includes/singapore.class.php
File deleted