<?php

include '../php/classes/page.php';
include 'functions/func_file.php';
include 'functions/func_filesystem.php';
include 'functions/func_xml.php';
$page = new Page();
$page->init_user();

# make sure the user is logged in before he has access to the
# admin section
if(!$page->user()->check_role('admin'))
{
	$page->addMessage('You must login to use the administrator pages.');
	$page->display('menu',false);
	$page->content('admin/login.php');
}
else
{
	# get the page element parameter that we want to edit
	# if it doesn't exist, we just display the list of options
	# below
	$what_to_edit = isset($_REQUEST['what']) ? $_REQUEST['what'] : null;
	
	# gather the appropriate data to send to the template
	# and show the right template based on what page data we're editing
	switch($what_to_edit)
	{
		case 'photos':
			work_photos();
			break;
		case 'videos':
			work_videos();
			break;
		default:
			$page->content('admin/photosandvideos.php');
	}
}

$page->attr('title','Discipling the Nations: Administrator Area: Photos and Videos');
$page->menu('admin/menu.php');
$page->addCSSFile('admin.css');

$page->process();
###################################################### FUNCTION: work_toolsfor #
function work_photos()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT."/site/data/photosandvideos/albums.xml";
	$albums = xml_get_from_file($file_path);
	$photos = array();
	# get a list of all the photos in each album
	foreach($albums->album as $album)
	{
		$album_photos = filesys_get_wanted_children($DOCROOT.'/site/data/photosandvideos/albums/'.$album->imagefolder,'folder',"/^thumb_.*\.(jpg|JPG)$/");
		foreach($album_photos as $photo)
			$photos[(int)$album['id']][] = str_replace('thumb_','',$photo);
	}

	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;

	# take the appropriate action according to what we are "doing"
	if($do == 'addalbum' || $do == 'addphoto')
	{
		$page->data('albums',$albums);
		$page->content("admin/photosandvideos/photos/$do.php");
	}
	else if($do == 'deletealbum' || $do == 'editalbum')
	{
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}

		if($found)
		{
			$page->data('album',$albums->album[$c]);
			$page->content("admin/photosandvideos/photos/$do.php");
		}
		else
		{
			$page->addError('No such album exists.');
			$page->content('admin/photosandvideos/photos/list.php');
		}
	}
	else if($do == 'deletephoto')
	{
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['album'])
			{
				$found = true;
				break;
			}
			$c++;
		}

		if($found)
		{
			$page->data('album',$albums->album[$c]);
			$page->data('photo',$_GET['which']);
			$page->content("admin/photosandvideos/photos/deletephoto.php");
		}
		else
		{
			$page->addError('No such album exists.');
			$page->content('admin/photosandvideos/photos/list.php');
		}
	}
	# add the album and return to the list
	else if($do == 'doaddalbum')
	{
		$last_id = $albums->album[count($albums->album) - 1]['id'];
		$new_album = $albums->addChild('album');
		$new_album->addAttribute('id',$last_id + 1);
		$new_album->addChild('name',$_POST['name']);
		$new_album->addChild('subalbumof',$_POST['subalbumof']);
		$new_album->addChild('subalbums');
		
		$folder_name = preg_replace("/[^A-Za-z0-9]+/",'_',$new_album->name);
		$new_album->addChild('imagefolder',$folder_name);

		if(file_put_contents($file_path,$albums->asXML()))
		{
			mkdir($DOCROOT.'/site/data/photosandvideos/albums/'.$folder_name);
			$page->addMessage('Album added successfully.');
			$page->content("admin/photosandvideos/photos/list.php");
		}
		else
		{
			$page->addError('Could not add album.');
			$page->content("admin/photosandvideos/photos/addalbum.php");
		}
	}
	else if($do == 'doaddphoto')
	{	
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}
		if($found)
		{
			# make sure the files gets uploaded and moved correctly
			if($new_photos = file_process_upload('file',$DOCROOT.'/site/data/photosandvideos/albums/'.$albums->album[$c]->imagefolder))
			{
				if(!is_array($new_photos))
					$new_photos = array($new_photos);
					
				$photo_path = $DOCROOT.'/site/data/photosandvideos/albums/'.$albums->album[$c]->imagefolder;
				
				foreach($new_photos as $new_photo)
				{
					// Get new dimensions
					list($width, $height) = getimagesize($photo_path."/$new_photo");
					$ratio_orig = $width/$height;
					# max widths and heights for thumbnail images and small images
					$thumb_w = 100;
					$thumb_h = 100;
					$small_w = 400;
					$small_h = 400;

					# get right width/heigh for thumbnail
					if ($thumb_w/$thumb_h > $ratio_orig) {
					   $thumb_w = $thumb_h*$ratio_orig;
					} else {
					   $thumb_h = $thumb_w/$ratio_orig;
					}
					#get right width/height for small image
					if ($small_w/$small_h > $ratio_orig) {
					   $small_w = $small_h*$ratio_orig;
					} else {
					   $small_h = $small_w/$ratio_orig;
					}

					// Resample
					$thumb_img = imagecreatetruecolor($thumb_w, $thumb_h);
					$small_img = imagecreatetruecolor($small_w, $small_h);
					$original = imagecreatefromjpeg($photo_path."/$new_photo");
					imagecopyresampled($thumb_img, $original, 0, 0, 0, 0, $thumb_w, $thumb_h, $width, $height);
					imagecopyresampled($small_img, $original, 0, 0, 0, 0, $small_w, $small_h, $width, $height);

					// Output
					imagejpeg($thumb_img, $photo_path."/thumb_$new_photo", 100);
					imagejpeg($small_img, $photo_path."/small_$new_photo", 100);
			
					# get the update set of photos in this album
					if(!isset($photos[(int)$albums->album[$c]['id']]))
						$photos[(int)$albums->album[$c]['id']] = array();
					array_push($photos[(int)$albums->album[$c]['id']],$new_photo);
				}
				$page->addMessage('Photo successfully added.');
				$page->content("admin/photosandvideos/photos/list.php");
			}
			else
			{
				$page->addError('An error occurred while uploading the photo.  Please try again.');
				$page->content("admin/photosandvideos/photos/addphoto.php");
			}
		}
		else
		{
			$page->addError('Album does not exist.');
			$page->content("admin/photosandvideos/photos/list.php");
		}
	}	
	# edit the article and return to the list
	else if($do == 'doeditalbum')
	{
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}

		if(empty($_POST['name']))
		{
			$page->addError('You cannot leave the album name blank.');
			$page->data('album',$albums->album[$c]);
			$page->content("admin/photosandvideos/photos/deletealbum.php");
		}
		else if($found)
		{
			# do the following of the new name is different than the old
			if((string)$albums->album[$c]->name != $_POST['name'])
			{
				# update the folder with the new name
				$old_folder_name = (string)$albums->album[$c]->imagefolder;
				$new_folder_name = preg_replace("/[^A-Za-z0-9]+/",'_',$_POST['name']);
				$albums->album[$c]->imagefolder = $new_folder_name;
				# rename the folder
				rename($DOCROOT.'/site/data/photosandvideos/albums/'.$old_folder_name,
							$DOCROOT.'/site/data/photosandvideos/albums/'.$new_folder_name);
				# update the name
				$albums->album[$c]->name = $_POST['name'];
			}
			
			# if the album has been placed under a different parent album
			# has been updated
			if((int)$albums->album[$c]->subalbumof != $_POST['subalbumof'])
			{
				$previous_parent_id = $albums->album[$c]->subalbumof;
				
				# find the previous parent
				for($k = 0; $k < count($albums->album); $k++)
				{
					if((int)$albums->album[$k]['id'] == $previous_parent_id)
					{
						# now find the subalbum entry that is now invalid and delete it
						for($j = 0; $j < count($albums->album[$k]->subalbums->subalbum); $j++)
						{
							if((int)$albums->album[$k]->subalbums->subalbum[$j] == (int)$albums->album[$c]['id'])
							{
								unset($albums->album[$k]->subalbums->subalbum[$j]);
								break;
							}
						}
						break;
					}
				}
				
				# find the new parent and add a new subalbum entry
				for($k = 0; $k < count($albums->album); $k++)
				{
					if((int)$albums->album[$k]['id'] == $_POST['subalbumof'])
					{
						$albums->album[$k]->subalbums->addChild('subalbum',$albums->album[$c]['id']);
						break;
					}
				}
				
				$albums->album[$c]->subalbumof = $_POST['subalbumof'];
			}

			file_put_contents($file_path,$albums->asXML());

			$page->addMessage('Album successfully updated.');
			$page->content("admin/photosandvideos/photos/list.php");
		}
		else
		{
			$page->addError('Album does not exist.');
			$page->contents("admin/photosandvideos/photos/list.php");
		}
	}
	# perform the deletion of a file from a album
	else if($do == 'dodeletephoto')
	{
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['album'])
			{
				$found = true;
				break;
			}
			$c++;
		}

		# if we can unlink the file
		if($found)
		{
			$photo_path = $DOCROOT.'/site/data/photosandvideos/albums/'.$albums->album[$c]->imagefolder.'/';
			if(unlink($photo_path.$_POST['which']))
			{
				unlink($photo_path.'thumb_'.$_POST['which']);
				unlink($photo_path.'small_'.$_POST['which']);
				# remove the photo from the photos array
				$key = array_search($_POST['which'],$photos[(int)$albums->album[$c]['id']]);
				unset($photos[(int)$albums->album[$c]['id']][$key]);
				
				$page->addMessage('Photo successfully deleted.');	
			}
			else
				$page->addError('Could not delete photo.');
		}

		$page->content("admin/photosandvideos/photos/list.php");
	}
	# perform the deletion of the specified article
	else if($do == 'dodeletealbum')
	{
		# find the album with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($albums->album[$c]))
		{
			if((int)$albums->album[$c]['id'] == $_REQUEST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}
		if($found)
		{
			# delete each of the files in this album
			$photo_path = $DOCROOT.'/site/data/photosandvideos/albums/'.$albums->album[$c]->imagefolder.'/';
			foreach($photos[(int)$albums->album[$c]['id']] as $file)
			{
				unlink($photo_path.$file);
				unlink($photo_path.'thumb_'.$file);
				unlink($photo_path.'small_'.$file);
			}
			# delete the folder
			rmdir($DOCROOT.'/site/data/photosandvideos/albums/'.$albums->album[$c]->imagefolder);
			# if we can successfully unset the album, then print a success message
			unset($albums->album[$c]);
			if(!isset($albums->album[$c]))
			{
				$page->addMessage('Album successfully deleted.');
				file_put_contents($file_path,$albums->asXML());
			}
			else
			{
				$page->addError('Could not delete this album.');
			}	
		}
		$page->content("admin/photosandvideos/photos/list.php");
	}
	# display the list of book albums
	else
	{
		$page->content("admin/photosandvideos/photos/list.php");
	}
	$page->data('photos',$photos);
	$page->data('albums',$albums);
}
######################################################## FUNCTION: work_videos #
function work_videos()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT.'/site/data/photosandvideos/videos.xml';
	$videos = xml_get_from_file($file_path);
	
	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;
	
	# add, edit and delete just display a form or other template page
	# so we can just lump them all together here
	if($do == 'add' || $do == 'edit' || $do == 'delete')
	{
		# if we are editing or deleting, the template needs the video data
		if($do != 'add')
		{
			# find the video with the right id
			$found = null;
			$c = 0;
			while(is_null($found) && isset($videos->video[$c]))
			{
				if((int)$videos->video[$c]['id'] == $_POST['which'])
				{
					$found = true;
					break;
				}
				$c++;
			}
			$page->data('video',$videos->video[$c]);
		}
		$page->content('admin/photosandvideos/videos/'.$do.'.php');
	}
	# add the video and return to the list
	else if($do == 'doadd')
	{
		# make sure the file gets uploaded and moved correctly
		if($new_file = file_process_upload('videofile',$DOCROOT.'/site/data/photosandvideos/videos'))
		{
			# get the last id from the file
			$last_id = $videos->video[count($videos->video) - 1]['id'];
					
			$new_name = isset($_POST['name']) ? $_POST['name'] : $_FILES['videofile']['name'];
			$new_video = $videos->addChild('video');
			$new_video->addChild('name',$new_name);
			$new_video->addChild('file',$new_file);
			# try to save the image file, otherwise set the new image to the default
			if(!empty($_FILES['imagefile']['tmp_name']))
				if($new_imagefile = file_process_upload('imagefile',$DOCROOT.'/site/graphics/photosandvideos/video_thumbs'))
					$new_video->addChild('image',$new_imagefile);
			else
				$new_video->addChild('image','default.jpg');
			$new_video->addAttribute('id',$last_id + 1);
			
			file_put_contents($file_path,$videos->asXML());
			
			$page->addMessage('Video successfully added.');
			$page->data('videos',$videos);
			$page->content('admin/photosandvideos/videos/list.php');
		}
		else
		{
			$page->addError('An error occurred while uploading the video file.  Please try again.');
			$page->content('admin/photosandvideos/videos/add.php');
		}
	}	
	# edit the video and return to the list
	else if($do == 'doedit')
	{
		# find the video with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($videos->video[$c]))
		{
			if((int)$videos->video[$c]['id'] == $_POST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}
		
		# don't try anything if we couldn't find the video with the right id
		if(is_null($found))
		{
			$page->addError('Video was not found.');
			$page->data('videos',$videos);
			$page->content('admin/photosandvideos/videos/list.php');
			return;
		}
		# if a new file is specified then delete the old one and replace
		# the new one
		else if(!empty($_FILES['videofile']['name']))
		{
			# delete old file
			unlink($DOCROOT.'/site/data/photosandvideos/videos/'.$videos->video[$c]->file);
			# try to upload the new file
			if($new_file = file_process_upload('videofile',$DOCROOT.'/site/data/photosandvideos/videos'))
			{
				$videos->video[$c]->name = isset($_POST['name']) ? $_POST['name'] : $_FILES['videofile']['name'];
				$videos->video[$c]->file = $new_file;
				
				# if the image file is being updated too
				if($_FILES['imagefile']['name'] !== '')
				{
					if((string)$videos->video[$c]->image !== 'default.jpg')
						unlink($DOCROOT.'/site/graphics/photosandvideos/video_thumbs/'.$videos->video[$c]->image);
					if($new_imagefile = file_process_upload('file',$DOCROOT.'/site/graphics/photosandvideos/video_thumbs'))
						$videos->video[$c]->image = $new_imagefile;
					else
						$videos->video[$c]->image = 'default.jpg';
				}
				
				file_put_contents($file_path,$videos->asXML());
				$page->addMessage('Video successfully edited.');
				$page->data('videos',$videos);
				$page->content('admin/photosandvideos/videos/list.php');
			}
			else
			{
				$page->addError('An error occurred while uploading the video file.  Please try again.');
				$page->content('admin/photosandvideos/videos/edit.php');
			}			
		}
		# if no new file is uploaded
		else
		{
			if($_POST['name'] !== '')
				$videos->video[$c]->name = $_POST['name'];
			# if the image file is being updated too
			if(!empty($_FILES['imagefile']['name']))
			{
				if((string)$videos->video[$c]->image !== 'default.jpg')
					unlink($DOCROOT.'/site/graphics/photosandvideos/video_thumbs/'.$videos->video[$c]->image);
				if($new_imagefile = file_process_upload('imagefile',$DOCROOT.'/site/graphics/photosandvideos/video_thumbs'))
					$videos->video[$c]->image = $new_imagefile;
				else
					$videos->video[$c]->image = 'default.jpg';
			}
				
			file_put_contents($file_path,$videos->asXML());
			$page->addMessage('Video successfully edited.');
			$page->data('videos',$videos);
			$page->content('admin/photosandvideos/videos/list.php');
		}
	}
	# perform the deletion of the specified video
	else if($do == 'dodelete')
	{
		# find the video with the right id
		$found = null;
		$c = 0;
		while(is_null($found) && isset($videos->video[$c]))
		{
			if((int)$videos->video[$c]['id'] == $_POST['which'])
			{
				$found = true;
				break;
			}
			$c++;
		}
			
		$file_name = $DOCROOT.'/site/data/photosandvideos/videos/'.$videos->video[$c]->file;
		if(unlink($file_name))
		{
			# delete the thumbnail image
			unlink($DOCROOT.'/site/graphics/photosandvideos/video_thumbs/'.$videos->video[$c]->image);
			unset($videos->video[$c]);
			file_put_contents($file_path,$videos->asXML());
			$page->addMessage('Video successfully deleted.');
		}
		else
		{
			$page->addError('Could not delete video.');
		}
		$page->data('videos',$videos);	
		$page->content('admin/photosandvideos/videos/list.php');
	}
	# display the list of videos
	else
	{
		$page->data('videos',$videos);
		$page->content('admin/photosandvideos/videos/list.php');
	}
}

?>