<?php

/*
   +----------------------------------------------------------------------+
   | Album Class                                                          |
   | Author: Adam Goldberg						  |
   +----------------------------------------------------------------------+
   | Copyright (c) 2008-2009 Adam J Goldberg	                          |
   | This file is part of Lifebox.					  |
   |									  |
   | Lifebox is free software: you can redistribute it and/or modify	  |
   | it under the terms of the GNU General Public License as published by |
   | the Free Software Foundation, either version 3 of the License, or    |
   | (at your option) any later version.				  |
   |									  |
   | Lifebox is distributed in the hope that it will be useful, 	  |
   | but WITHOUT ANY WARRANTY; without even the implied warranty of	  |
   | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the	  |
   | GNU General Public License for more details.			  |
   |									  |
   | You should have received a copy of the GNU General Public License	  |
   | along with Lifebox.  If not, see <http://www.gnu.org/licenses/>.	  |
   +----------------------------------------------------------------------+
   | Index of Albums							  |
   +----------------------------------------------------------------------+
	function Album ($string=false) {
        function setInfo ($data) {
        function commit(){
        function delete() {
	function getRoll($photo_id) {
	function doSearch ($query,$count=false) {
	function getAlbumList($type=false,$limit=false,$offset=0,$sort=1) {
	function getCustomAlbums($type=false,$highlight=true) {
        function updateViews() {
	function getAll() {
        function isHighlight($photo_id) {
        function setHighlight($highlight_photo_id) {
	function _setInfo() {
   +----------------------------------------------------------------------+
*/

require_once 'Photo.inc.php';
require_once 'Text.inc.php';
require_once 'Log.inc.php';
require_once 'Authenticate.inc.php';
require_once 'AlbumCategory.inc.php';

class Album {

	var $album_id;
	var $title_url;
	var $new_album;
	var $info;
	var $updated_info;

	/*****************************************************************
	 * Constructor
         *****************************************************************/
	function Album ($string=false) {
		if (strlen($string) == 32 AND !strpos($string,'-')) {
			$this->album_id = $string;
			$this->_setInfo();
		} elseif ($string) {
			$this->title_url = $string;
			$this->_setInfo();
		} else {
			$this->new_album = true;
		}
	}

	/*****************************************************************
	 * setInfo
         *****************************************************************/
        function setInfo ($data) {
	global $CONFIG;
	global $ERROR;

		if ($this->new_album) {
			#ERROR Checking
			if (empty($data['title'])) {
				$ERROR['title'] = 'Title is missing';
				return false;
			}

			if (empty($data['type'])) {
				$ERROR['type'] = 'Type is missing';
				return false;
			}

			$timestamp = time() ;

                        #Generate the album_id
                        $this->info['album_id'] = md5($timestamp);
			$this->updated_info['album_id'] = $this->info['album_id'];

                        #Make the clean title
                        $this->info['title_url'] = Text::generateCleanTitle(strip_tags($data['title']));
			$this->updated_info['title_url'] = $this->info['title_url'];

		}

		foreach ($data as $key => $value){

			$value = strip_tags($value);

			#Make sure the supplied info is a valid
			#Timestamp
			if ($key === 'timestamp_created' OR
			    $key === 'timestamp_modified') {
			    $value = strtotime($value);
			}

			#If an album type is supplied that is not
			#numeric, look up the numeric value
			if ($key === 'type' AND !is_numeric($value)) {
				$value = AlbumCategory::getCategoryList($value);
				$value = $value['type'];
			}

			#If an access level is specified, and if
			#it is not numeric, look up the numeric
			#value
			if ($key === 'level') {
                                $levels_list = Authenticate::getLevelsList($value);
                                $value = $levels_list['level'];
                        }
			
                        $this->info[$key] = strip_tags(trim($value));
			$this->updated_info[$key] = strip_tags(trim($value));
                        if ($this->info[$key] == 'on'){
                                $this->info[$key] = 1;
				$this->updated_info[$key] = 1;
                        }
        
                }

		return true;
	}

	/*****************************************************************
         * Adds a new album.
         *****************************************************************/
        function commit(){
        global $CONFIG;
        global $ERROR;
        global $db;
        
                if (!empty($ERROR)){
                        return false;
                }       
                
                if ($this->new_album){

			#Generate the current time
                        $timestamp = time();

                        #Build the query.
                        foreach ($this->updated_info as $key=>$value){

                                #Exceptions
                                if ($key !== 'agree'){
                                        $insert_into .= "$key,";
                                        $values .= "'$value',";
                                }
                        }

                        #strip the last comma
                        $insert_into = substr($insert_into,0,-1);
                        $values = substr($values,0,-1);


			#First, make a log
			$log = new Log($CONFIG['changelog_create_album']);
                	if (!$log->addEvent($this->info['album_id'],$timestamp,$this->info['title'])) {
				return false;
			}

                        $query = "INSERT INTO ".$CONFIG['tbl_albums']."
                                  (timestamp_created,
                                   $insert_into)
                                  VALUES ('$timestamp',
                                           $values)";
		} else {
			#Build the query.
                        foreach ($this->updated_info as $key=>$value){

                                $set .= "$key = '$value', ";

                        }

                        #strip the last comma
                        $set = substr($set,0,-2);


                        $query = "UPDATE ".$CONFIG['tbl_albums']."
                                  SET $set
                                  WHERE album_id = '".$this->album_id."'";
                }

		$result = $db->Execute($query);

		if ($result) {
			return true;
		} else {
			return false;
		}
	}

	/*****************************************************************
         * Delete an album from the database
         *****************************************************************/
        function delete() {
        global $CONFIG;
        global $db;

                $query = "DELETE FROM ".$CONFIG['tbl_albums']."
                          WHERE album_id = '".$this->album_id."'";
                $result = $db->Execute($query);

                if ($result) {
                        return true;
                } else {
                        return false;
                }
        }

	/*****************************************************************
	 *
         *****************************************************************/
	function getRoll($photo_id) {
	global $CONFIG;
	global $db;

		$query = "SELECT a.*
			  FROM ".$CONFIG['tbl_albums']." a,
			       ".$CONFIG['tbl_album_photo_map']." apm,
			       ".$CONFIG['tbl_photos']." p
			  WHERE p.photo_id = '$photo_id' AND
				p.photo_id = apm.photo_id AND
				apm.album_id = a.album_id AND
				a.type = '1'";
		$row = $db->getRow($query);

		if ($row) {
			if (is_numeric(str_replace('-','',substr($row['title'],0,10)))) {
                                $row['title_nodate'] = substr($row['title'],11);
                                $row['title_date'] = substr($row['title'],0,10);
                        } else {
                                $row['title_nodate'] = $row['title'];
                        }

			$row['url'] = '/'.$row['title_url'];

			return $row;
		} else {
			return false;
		}
	}

	/*****************************************************************
	 * Search Albums
         *****************************************************************/
	function doSearch ($query,$count=false) {
	global $CONFIG;
	global $db;
	global $_USER;
	
		# IF A COUNT WAS PERFORMED
		if ($count) {
			$query = "SELECT COUNT(DISTINCT a.album_id) as num
                          FROM ".$CONFIG['tbl_albums']." a
                          WHERE MATCH(title,text,location) AGAINST ('$query' IN BOOLEAN MODE) AND
			  num_photos > 0 AND
			  a.min_level <= ".$_USER['level']." AND
			  a.level <= ".$_USER['level'].""; 
			$row = $db->getRow($query);

			if ($row) {
				return $row['num'];
			} else {
				return false;
			}
		}

		# IF A SEARCH QUERY WAS PERFORMED
		$query = "SELECT *,
				 MATCH(title,text,location) AGAINST ('$query' IN BOOLEAN MODE) as score
			  FROM ".$CONFIG['tbl_albums']." a
			  WHERE MATCH(title,text,location) AGAINST ('$query' IN BOOLEAN MODE) AND
				num_photos > 0 AND
				a.min_level <= ".$_USER['level']." AND
				a.level <= ".$_USER['level']."
			  GROUP BY a.album_id";
		$results = $db->getAll($query);

		if ($results) {
			for ($i=0; $i<count($results); $i++){
                                        if (is_numeric(str_replace('-','',substr($results[$i]['title'],0,10)))) {
                                                $results[$i]['title_nodate'] = substr($results[$i]['title'],11);
                                                $results[$i]['title_date'] = substr($results[$i]['title'],0,10);
                                        } else {
                                                $results[$i]['title_nodate'] = $results[$i]['title'];
                                        }
			
                                        $results[$i]['album_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-album.jpg';
                                        $results[$i]['url'] = $CONFIG['full_site'].$results[$i]['title_url'];

                                        $timestamp = time();
                                        $timestamp_expired = ($timestamp - ($CONFIG['new_days'] * 24 * 60 * 60) );
                                        if ($results[$i]['timestamp_created'] > $timestamp_expired) {
                                                $results[$i]['is_new'] = TRUE;
                                        } else {
                                                $results[$i]['is_new'] = FALSE;
                                        }
		}
			return $results;
		} else {
			return false;
		}
	}

	/*****************************************************************
         * Get Album List
         *****************************************************************/
	function getAlbumList($type=false,$limit=false,$offset=0,$sort=1) {
	global $CONFIG;
	global $db;
	global $_USER;

		if (is_numeric($type)){
			$where = "AND a.type = $type";
		}

		if (!$limit) {
			$limit = 10000;
		}

		if ($type == 1) {
			$image = 'main_event';
		} elseif ($type == 2) {
			$image = 'main_album';
		} elseif ($type == 'other') {
			$where = 'AND a.type > 2';
		}

		#Determine Sort
		if ($sort == 1) {
			$order = "ORDER BY a.timestamp_created DESC, a.timestamp_modified DESC";
		} elseif ($sort == 2) {
			$order = "ORDER BY a.timestamp_created ASC, a.timestamp_modified DESC";
		} elseif ($sort == 3) {
			$order = "ORDER BY a.views DESC";
		} elseif ($sort == 4) {
			$order = "ORDER BY a.views ASC";
		} elseif ($sort == 5) {
			$order = "ORDER BY a.title ASC";
		} elseif ($sort == 6) {
			$order = "ORDER BY a.title DESC";
	    	} elseif ($sort == 7) {
			$order = "ORDER BY a.timestamp_modified DESC";
		} elseif ($sort == 8) {
			$order = "ORDER BY a.timestamp_modified ASC";
		} elseif ($sort == 9) {
			$order = "ORDER BY a.location ASC, a.title ASC";
		} else {
			$order = "ORDER BY a.timestamp_created DESC, a.timestamp_modified DESC";
		}

		if (!is_numeric($limit) AND $limit) {
			$query = "SELECT COUNT(*) as num
                                  FROM ".$CONFIG['tbl_albums']." a
                                  WHERE a.min_level <= ".$_USER['level']." AND
					a.level <= ".$_USER['level']." AND
					num_photos > 0
                                        $where";
			/*
			$query = "SELECT COUNT(DISTINCT apm.album_id) as num
	                          FROM ".$CONFIG['tbl_albums']." a,
	                               ".$CONFIG['tbl_photos']." p,
	                               ".$CONFIG['tbl_album_photo_map']." apm
	                          WHERE a.album_id = apm.album_id AND
	                                apm.photo_id = p.photo_id AND
	                                p.level <= ".$_USER['level']." AND
	                          $where
	                         ";
			*/
			$row = $db->CacheGetRow($CONFIG['cache_album_count'],$query);
			if ($row) {
				return $row['num'];
			} else {
				return false;
			}

		} else {

			$query = "SELECT a.*,
					 at.title as type_title,
                                 	 sa.title as level_title
				  FROM ".$CONFIG['tbl_albums']." a,
				       ".$CONFIG['tbl_s_access']." sa,
				       ".$CONFIG['tbl_album_types']." as at
				  WHERE a.min_level <= ".$_USER['level']." AND
					a.level <= ".$_USER['level']." AND
					a.level = sa.level AND
					at.type = a.type AND
					num_photos > 0
					$where
				  $order
				  LIMIT $offset,$limit";

			/*
			#Use a double limit for the subselects
			$limit_double = $limit * 2;
			$offset_difference = 
			$query = "SELECT a.* 
				  FROM ".$CONFIG['tbl_photos']." p, 
				       ".$CONFIG['tbl_album_photo_map']." apm 
				  INNER JOIN (SELECT a.* 
					      FROM ".$CONFIG['tbl_albums']." a 
					      WHERE $where
					      $order
					      LIMIT $offset,$limit_double) as a 
				  ON a.album_id = apm.album_id 
				  WHERE apm.photo_id = p.photo_id AND
					p.level <= ".$_USER['level']."
				  GROUP BY a.album_id
				  $order LIMIT $limit";
			*/

			$results = $db->CacheGetAll($CONFIG['cache_album_list'],$query);
			if ($results) {
	
				for ($i=0; $i<count($results); $i++){
					if (is_numeric(str_replace('-','',substr($results[$i]['title'],0,10)))) {
						$results[$i]['title_nodate'] = substr($results[$i]['title'],11);
						$results[$i]['title_date'] = substr($results[$i]['title'],0,10);
					} else {
						$results[$i]['title_nodate'] = $results[$i]['title'];
					}
	
					#If no Highlight is specified, generate one
					if (empty($results[$i]['highlight_photo_id'])) {
						$query = "SELECT p.photo_id
							  FROM ".$CONFIG['tbl_photos']." p,
							       ".$CONFIG['tbl_album_photo_map']." apm
							  WHERE p.photo_id = apm.photo_id AND
								apm.album_id = '".$results[$i]['album_id']."'
							  ORDER BY p.views DESC";
						$row = $db->getRow($query);
						
						$highlight_photo_id = $row['photo_id'];
	
						#Update the album record with the selected highlight ID
						$query = "UPDATE ".$CONFIG['tbl_albums']."
							  SET highlight_photo_id = '$highlight_photo_id'
							  WHERE album_id = '".$results[$i]['album_id']."'";
						$result=$db->Execute($query);
	
						if ($result) {
							$results[$i]['highlight_photo_id'] = $highlight_photo_id;
						}
					}

					$results[$i]['thumb_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-thumb.jpg';	
					$results[$i]['main_recent_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-main_recent.jpg';
					$results[$i]['album_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-album.jpg';
					$results[$i]['roll_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-roll.jpg';
					$results[$i]['preview_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-preview.jpg';
					$results[$i]['full_url'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-full.jpg';
       	                         	$results[$i]['url'] = $CONFIG['full_site'].$results[$i]['title_url'];
					
					$timestamp = time();
                                        $timestamp_expired = ($timestamp - ($CONFIG['new_days'] * 24 * 60 * 60) );
                                        if ($results[$i]['timestamp_created'] > $timestamp_expired OR $results[$i]['timestamp_modified'] > $timestamp_expired) {
                                                $results[$i]['is_new'] = TRUE;
                                        } else {
                                                $results[$i]['is_new'] = FALSE;
                                        }
	
				}
				return $results;
			} else {
				return false;
			}
		}
	}

	/*****************************************************************
	 * Gets a list of user created albums
         *****************************************************************/
	function getCustomAlbums($type=false,$highlight=true) {
	global $CONFIG;
	global $db;

		if ($type) {
			$where = "a.type = '$type'";
		} else {
			$where = "a.type > 1";
		}

		if ($highlight) {
			$query = "SELECT a.*,
					 at.title as type_title,
					 sa.title as level_title,
					 p.title as highlight_title
				  FROM ".$CONFIG['tbl_albums']." a,
				       ".$CONFIG['tbl_album_types']." at,
				       ".$CONFIG['tbl_s_access']." sa,
				       ".$CONFIG['tbl_photos']." p
				  WHERE at.type = a.type AND
					sa.level = a.level AND
					p.photo_id = a.highlight_photo_id AND
					$where
				  ORDER BY title ASC";
		} else {
			$query = "SELECT *
				  FROM ".$CONFIG['tbl_albums']." a
				  WHERE $where
				  ORDER BY a.title ASC";
		}

		$results = $db->getAll($query);
		if ($results) {

			if ($highlight) {
				for ($i=0; $i<count($results); $i++) {
					$results[$i]['highlight_thumb'] = $CONFIG['full_site'].'photo/'.$results[$i]['highlight_photo_id'].'-thumb'.'.jpg';
					$results[$i]['url'] = $CONFIG['full_site'].$results[$i]['title_url'];
				}
			}

			return $results;
		} else {
			return false;
		}
	}

	/*****************************************************************
         * Update views
         *****************************************************************/
        function updateViews() {
        global $CONFIG;
        global $db;
        global $_USER;
                $query = "INSERT INTO ".$CONFIG['tbl_views']."
                          (ip, host, album_id, referer, url,  timestamp_created, first, last, email)
                          VALUES ('".$_SERVER['REMOTE_ADDR']."',
                                  '".gethostbyaddr($_SERVER['REMOTE_ADDR'])."',
                                  '".$this->album_id."',
                                  '".addslashes($_SERVER['HTTP_REFERER'])."',
                                  'http://".addslashes($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'])."',
                                   now(),
                                  '".$_USER['first']."',
                                  '".$_USER['last']."',
                                  '".$_USER['email']."')";
                $result = $db->Execute($query);
        
                $query = "SELECT COUNT(*) as num
                          FROM views
                          WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND
                                album_id = '$this->album_id'";
                $result = $db->Execute($query);
                        
                $row = $db->getRow($query); 
                $timestamp = time();
                        
                if ($row['num'] <= 1){
                        $query = "UPDATE albums
                                  SET views = views + 1,
                                      timestamp_last_view = '$timestamp',
                                      last_viewer = '".$_USER['id']."'
                                  WHERE album_id = '".$this->album_id."'";
                        $result = $db->Execute($query);
                }       
                
        }
	
	/*****************************************************************
	 * Accessor method for info
         *****************************************************************/
	function getAll() {
	
		return $this->info;

	}

	/*****************************************************************
	 * Check if a specified image is a higlight image
         *****************************************************************/
        function isHighlight($photo_id) {
	global $CONFIG;
	global $db;

		$query = "SELECT COUNT(*) as num
			  FROM ".$CONFIG['tbl_albums']."
			  WHERE highlight_photo_id = '$photo_id'";
		$row = $db->getRow($query);

		if ($row['num'] > 0){
			return true;	
		} else {
			return false;
		}
                                
        } 
	/*****************************************************************
	 * Make Highlight Photo
         *****************************************************************/
        function setHighlight($highlight_photo_id) {
        global $CONFIG;
        global $db;
        global $_USER;

                if ($_USER['level'] < $CONFIG['permission_make_highlight']) {
                        return false;
                }

		$log = new Log($CONFIG['changelog_highlight']);
	
                if ($log->addEvent($this->album_id,$this->info['highlight_photo_id'],$highlight_photo_id)) {

			#Make sure the Permissions are set to public
			$p = new Photo($highlight_photo_id);
			$photo_info = $p->getAll();
			if ($photo_info['level'] != 1) {
				if ($p->changeLevel(1)) {
                        		$query = "UPDATE ".$CONFIG['tbl_albums']."
	                                  SET highlight_photo_id = '$highlight_photo_id'
	                                  WHERE album_id = '".$this->album_id."'";
	                	        $result = $db->Execute($query);
				}
			} else {
				$query = "UPDATE ".$CONFIG['tbl_albums']."
                                          SET highlight_photo_id = '$highlight_photo_id'
                                          WHERE album_id = '".$this->album_id."'";
                                        $result = $db->Execute($query);
			}

                        if ($result) {
                                return true;
                        } else {
                                return false;
                        }
                }
	}

	/*****************************************************************
         * Get Album Info
         *****************************************************************/
	function _setInfo() {
	global $CONFIG;
	global $db;

		if (isset($this->album_id)) {
			$where = "album_id = '$this->album_id'";
		} elseif (isset($this->title_url)) {
			$where = "title_url = '$this->title_url'";
		} else {
			return false;
		}

		$query = "SELECT *
			  FROM ".$CONFIG['tbl_albums']."
			  WHERE $where";
		$row = $db->getRow($query);

		if ($row) {
			if (is_numeric(str_replace('-','',substr($row['title'],0,10)))) {
	                        $row['title_nodate'] = substr($row['title'],11);
                                $row['title_date'] = substr($row['title'],0,10);
                        } else {
                                $row['title_nodate'] = $row['title'];
                        }

			$this->info = $row;
			$this->album_id = $row['album_id'];
			$this->title_url = $row['title_url'];
			return true;
		} else {
			return false;
		}
	}
}
