Location: PHPKode > scripts > EasyPhpAlbum > easyphpalbum/index.php
<?php 

/**

EasyPhpAlbum Version 1.4.4
A single script thumbnail gallery

Copyright (c) 2005-2010 JF Nutbroek <www.mywebmymail.com / hide@address.com>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

*******************************************************************************************

QUICK START - ONE ALBUM

Upload your photos and this index.php script to a directory on your webserver - thats all!!

*******************************************************************************************

MULTIPLE ALBUMS & EASY CONFIGURATION

Enable admin access, set a password and save this index.php file (edit line 74 and 75).
Create a write-enabled directory for your albums on your webserver and upload this script.
Enter the URL in your browser: http://www.yoursite.com/yourphotodir/index.php and press the
'Tab' key on your keyboard to get to the administrator login screen and create your album(s).
Manual access: add ?admin=1 to the url: www.abc.com/photo/index.php?admin=1

***************************************************************************************************

INTEGRATION OF EASYPHPALBUM ON YOUR WEBSITE
CMS : Add a menu item called 'wrapper'. Point the link to index.php in the photoalbum directory
HTML: Add an 'iframe' to your page that points to this index.php script. Example:
<iframe width="100%" height="600" marginwidth="0" marginheight="0" scrolling="no" 
 	frameborder="0" allowtransparency="true" src="/photoalbums/index.php"></iframe> 

ADDING AN ALBUM INDEX PHOTO/ICON
Add an 'index.jpg', 'index.gif' or 'index.png' to your album for the main album index page

MULTIMEDIA SUPPORT
Enable multimedia support, add a multimedia file to the album AND an image with the same name

SPECIFIC ORDER
Start directory/file names with a 3-digit number: '001 first directory' or '005 fifth photo'

LIGHTBOX SUPPPORT - Download from: http://www.lokeshdhakar.com/projects/lightbox2/
Create a directory on your webserver that contains the 3 lightbox directories (js, images and css)
In the configuration section enable lightbox support and provide the path to the directory

TILTVIEWER SUPPORT - Download from: http://www.airtightinteractive.com/projects/tiltviewer/
Copy the 3 files TiltViewer.swf, index.html, swfobject.js to your album(s) or use the admin panel
In the configuration section enable tiltviewer support and auto-create the gallery.xml file

PICLENS SUPPORT - No installation required, scripts will be downloaded from piclens.com
In the configuration section enable piclens support and auto-create the photos.rss file

***************************************************************************************************

CONFIGURATION SECTION A - Only editable in this script, make changes and save before uploading 

*/

// Login - Administrator access

$admin_access=false;							// Change to true for EASY configuration, press 'Tab' key in browser to access admin pages: true or false
$admins='admin,password';						// Admin(s) with access to this album: 'loginname,password' comma separated - change this to your own loginname and password!!
$admin_ip='';								// Allow admin login from specified IP addresses only, one or multiple IP's comma separated - optional
$enable_admin_keyboardshortcut=true;					// Press 'Tab' key on your keyboard to continue to the admin login screen: true or false

// Hosting the album

$max_albums=0;								// Maximum amount of albums 0=unlimited
$max_album_size=0;							// Maximum filesize of album in MB 0=unlimited
$allow_configuration=true;						// Allow modification of the configuration: true or false
$allow_create_album=true;						// Allow creation of new albums: true or false
$comment_size=250;							// Maxmimum amount of characters in single visitor comment

// Translations for the visitors

$language_page='Page';							// Text for page number
$language_homepage='Home';						// Text for homepage button in menu
$language_albums='Albums';						// Text for amount of albums
$language_photos='Photos';						// Text for amount of photos
$language_view='View';							// Text for tooltip image- change this in your own language
$language_view_next='->';						// Text for next image link- change this in your own language
$language_view_previous='<-';						// Text for previous image link- change this in your own language
$language_viewnext='Click to view next image (or use arrow keys)';	// Text for tooltip image in popup window
$language_viewmm='Play multimedia file';				// Text for tooltip multimedia file
$language_dir_empty='Directory empty';					// Text for empty directory
$language_login='Login';						// Text for login
$language_logout='Logout';						// Text for logout
$language_user='Username';						// Text for username
$language_passw='Password';						// Text for password
$language_slideshow='start slideshow';					// Text for starting slideshow
$language_stop_slideshow='stop slideshow';				// Text for stopping slideshow
$language_hitcounter_tooltip='Hit counter';				// Text for tooltip of hit counter
$language_email_alt='Email this page to a friend';			// Text for tooltip of email button
$language_email_subject='EasyPhpAlbum';					// Text for email subject line
$language_email_comment='Please copy this link in your browser:';	// Text for email comment line
$language_download='right-click to download: ';				// Text for download link
$language_rating='rating:';						// Text for rating photo
$language_hits='hits:';							// Text for hits photo
$language_countcomments='total comments: ';				// Text for thumbnail comments counter
$language_rating_votes='votes';						// Text for rating photo amount of votes
$language_rating_tooltip='Rating (5=excellent / 1=poor)';		// Text for rating tooltip
$language_rating_choose='Choose a rating';				// Text for rating selection
$language_rating_excellent='5 - Excellent';				// Text for rating selection
$language_rating_verygood='4 - Very good';				// Text for rating selection
$language_rating_good='3 - Good';					// Text for rating selection
$language_rating_fair='2 - Fair';					// Text for rating selection
$language_rating_poor='1 - Poor';					// Text for rating selection
$language_add_comment='add comment';					// Text for visitors to add a comment
$language_add_file='Upload file';					// Text for visitors to add a file
$language_save_comment='Save comment';					// Text for visitors to save the comment
$language_upload_comment='Upload file(s)';				// Text for visitors to upload files
$language_username_comment='Name';					// Text for visitors to add nickname to the comment or file upload
$language_comment_max='Maxmimum amount of characters';			// Text for visitors maximum comment characters
$language_up='Up';							// Text for menu directory up
$language_shop_info='No. of copies and type:';				// Text for shop number of copies per photo
$language_shop_order='Place order';					// Text for shop order button
$language_shop_cancel='Cancel';						// Text for shop cancel button
$language_shop_address='Your address:';					// Text for shop address
$language_shop_email_address='Your email-address:';			// Text for shop address
$language_shop_ordercomments='Your order and comments:';		// Text for shop address
$language_shop_confirmation='Order send - we will contact you asap.';	// Text for shop address
$language_sort_option1='standard album sort';				// Options for visitor album sort
$language_sort_option2='sort by hitcounter';				// Options for visitor album sort
$language_sort_option3='sort by comments';				// Options for visitor album sort
$language_sort_option4='sort by rating';				// Options for visitor album sort
$language_sort_option5='sort by date';					// Options for visitor album sort
$language_search='Search';						// Text for search option
$language_search_keyword='Keyword for search';				// Text for search option keyword
$language_search_noresults='Search returned no hits';			// Text for search option nothing found
$language_search_cancel='Back';						// Text for search option cancel
$language_visitor_upload_message='Upload OK';				// Text for successful upload
$language_visitor_upload_review='Uploaded content will be reviewed';	// Text for successful upload & admin review
$language_over18='I am 18 or older - ENTER';				// Text for adult content
$language_under18='I am under 18 - CANCEL';				// Text for teenagers
$language_18='Disclaimer: This photoalbum contains explicit content';	// Text for explicit content
$language_stats='Photos: ';						// Text for total amount of photos in album
$language_new='new!';							// Text for new photos
$language_selectalbum='please select an album';				// Text for album selectionbox
$language_lastupdated='Updated: days ago';				// Text for album 'last updated', the : must be included in the text

// ***************************************************************************************************
// CONFIGURATION SECTION B - Editable using the administrator web-interface (recommended)
// A configuration.php file inside the album will override any changes you make here

// Login - Restrict access for visitors

$restrict_access=false;							// Ask for valid login and password: true or false
$users='fred,1234,guest,guestpassword';					// User(s) with access to this album: 'name,password' comma separated

// Server & navigation

$gd2=true;								// Set to true if your server has GDLib2+ (for better quality thumbnails)
$title='EasyPhpAlbum 1.4.4';						// Page title - leave empty to display directory name
$home_page='http://www.mywebmymail.com';				// Menu link to another page or homepage of your website - leave empty to disable
$show_email_link=false;							// Shows 'email' button: true or false
$show_poweredby_easyphpalbum=true;					// Set to true or false. True is strongly recommended! ;)
$imagemagick=false;							// Use ImageMagick (when installed on server) for resize/rotate of images in admin section
$imagemagick_path='';							// The path to ImageMagick (leave empty if link is available on server) otherwise use for example '/usr/bin/'
$show_bottommenu=true;							// Display bottom album navigation menu: true or false
$show_topmenu=false;							// Display top album navigation menu: true or false
$show_dir_up=false;							// Display menu item 'directory up' - required for sub-sub-dir structure: true or false
$show_statistics=true;							// Count all albums and photos and show on main page: true or false
$show_album_statistics=false;						// Count photos in individual albums and show on main page: true or false
$use_main_config=false;							// Use configuration file from main album index page: true or false
$use_album_config='';							// Use configuration from other album - enter directory or album name or leave empty to disable
$enable_keyboard_arrows=true;						// Use the arrows keys on your keyboard to continue to the next or previous photo: true or false
$ban_ip='';								// IP adresses to ignore for the hitcounter, rating, comment and upload system - add one or multiple IP's comma separated, example: 127.0.0.1,10.0.0.150
$charset='ISO-8859-15';							// Charset for EasyPhpAlbum
$explicit_content=false;						// Shows explicit content warning: true or false
$show_topnavigation=false;						// Show navigation on top of page; true or false
$show_bottomnavigation=true;						// Show navigation on bottom of page; true or false
$show_album_selectbox=false;						// Shows a selectionbox instead of the navigation menu: true or false
$chmod_level='0755';							// The privileges on the server - use 0777 or 0755 - depends on hosting provider
$album_url='http://www.mysite.com/photoalbum';                          // The URL to your photoalbum directory (the directory location of index.php)

// Thumbnail layout and creation

$thumb_size=160;							// Size in px for thumbnails (min. 30 pixels)
$border_width=0;							// Add border around photo - width in px (0=no border)
$show_bordershadow=false;						// Display shadow around border: true or false
$show_binder=false;							// Display binder: true or false
$binder_spacing=8;							// Space between binder-rings in px
$clip_corner=15;							// Clip corner of photo - size in % of width (0=no clipping)
$clip_corner_round=true;						// Clip corner of photo - rounded or straight: true or false
$clip_topleft=false;							// Clip top left corner: true or false
$clip_topright=true;							// Clip top right corner: true or false
$clip_bottomleft=true;							// Clip bottom left corner: true or false
$clip_bottomright=true;							// Clip bottom right corner: true or false
$clip_randomly=false;							// Randomly clip 'enabled' corners: true or false
$show_number=false;							// Display photo number in thumbnail: true or false
$create_thumbnail_cache=true;						// Save thumbnails for faster display (recommended) - requires write access to (sub)directory: true or false
$thumbnail_txtfile=false;						// Display textfile from photo with thumbnail: true or false
$thumbnail_opacity=false;						// Use 'fade-out/fade-in' thumbnails: true or false
$opacity_level=50;							// Set opacity between 0 and 100; 0=invisible and 100=normal
$thumbnail_countcomments=false;						// Show amount of comments for photo: true or false
$indeximage_no_thumb=true;						// Do not 'thumbnailize' the albums index.jpg png or gif image: true or false
$thumbnail_borderpng='';						// Add a border to the thumbnail, filelocation of the (transparent) PNG image file, example 'gfx/border.png'
$thumbnail_spacing=0;							// Width in px of thumbnail-cell (0=autosize)
$thumbnail_rotation=false;						// Rotate the thumbnail: true or false
$thumbnail_rotation_degrees=0;						// 0=random, otherwise: 45 or -45
$valign_thumbnail='top';						// Alignment of thumbnail: 'middle', 'top' or 'bottom'
$show_thumb_name_top=false;						// Show name above thumbnail: true or false
$square_thumbnails=false;						// Create thumbnails with the same width & height: true or false
$animated_thumbnails=false;						// Do not 'thumbnailise' GIF images: true or false
$new=false;								// Mark new photos with 'new'
$new_days=14;								// Max. age of photo for 'new' indication
$last_updated=false;							// Show text album last updated x days ago

// Page layout and behaviour

$images_per_page=6;							// Number of photos to display per page
$columns_per_page=3;							// Number of photos next to each other
$popup=false;								// Display photo in popup or on page: true or false
$popup_force_focus=false;						// Set to true to force window on top (only for popup)
$popup_browse=true;							// Browse photos in popup window: true or false
$image_border=false;							// Display border around photo (only when $popup=false): true or false
$slideshow=true;							// Enable slideshow: true or false
$slideshow_delay=6000;						        // Time between slides in milliseconds (1 second = 1000 milliseconds). Minimum 1 second.
$page_header=true;							// Show page title and line (false=compact format): true or false
$center_title=false;						        // Centers title on page: true or false
$center_album=true;						        // Centers all content on page: true or false
$sort_thumbs=false;							// Sort thumbs according to (exif) date, new to old: true or false
$sort_rating=false;							// Sort thumbs according to rating score, high to low: true or false
$sort_hits=false;						        // Sort thumbs according to total hits, high to low: true or false
$sort_comments=false;						        // Sort thumbs according to total comments, high to low: true or false
$sort_hightolow=true;						        // Sort from high/new to low/old (score/rating and date): true or false
$visitor_sort=false;						        // Allow visitors to sort the photos in the album: true or false
$visitor_search=false;					                // Allow visitors to search the photos by keyword in the album: true or false
$visitor_search_columns=3;			                        // Search result - amount of photos next to each other
$background_image='';						        // The URL for your background image (example: 'http://www.mywebmymail.com/bg.gif'), leave empty for no background
$background_repeat='no-repeat';	                                        // Repeat your background image, valid settings: repeat / repeat-x / repeat-y / no-repeat
$background_position='50% 50%';	                                        // Position your background image based on % of width and % of height of page (50% 50% =centered)
$menu_background_image='';			                        // The URL for your menu background image (example: 'http://www.mywebmymail.com/bg.gif'), leave empty for no background
$backgroundtable_image='';			                        // The URL for your thumbnail background image (example: 'http://www.mywebmymail.com/bg.gif'), leave empty for no background
$content_width='90%';					                // The width of the page content: % or px, example: 85% or 800px
$content_leftmargin='10px';			                        // The left margin of the page content: % or px, example: 5% or 10px
$content_topmargin='0px';				                // The top margin of the page content: % or px, example: 5% or 10px
$header='';								// The URL to an image to use as a page header, leave empty to disable
$footer='';								// The URL to an image to use as a page footer, leave empty to disable
$transparent_page=false;				                // Make album background transparent for site integration: true or false
$transparent_menu=false;				                // Make album menu background transparent for site integration: true or false
$show_previous_next=false;			                        // When displaying the photo, show the thumbnails of the previous and next photo: true or false
$show_prev_next_below=false;		                                // Show previous and next thumbnail below the photo: true or false
$show_prev_next_size=80;				                // Size of previous and next thumbnail in px
$show_prev_next_position='middle';	                                // Alignment of previous and next thumbnail: 'middle', 'top' or 'bottom'
$link_bigimage=false;						        // Add a link to the photo to view it fullsize: true or false
$imagefader=true;							// Gradually fade a photo in (and out with slideshow enabled): true or false
$show_topline=true;							// Display the top line: true or false
$show_bottomline=true;					                // Display the bottom line: true or false
$fontfamily='Tahoma, Arial, Helvetica, sans-serif';	                // Font type to use
$aligntext_left=false;					                // Align photo textfile to the left (standard is centered): true or false

// Photo information

$show_name=true;							// Display file name: true or false (tip: use filename as short description for photo)
$show_name_top=true;							// Display file name above image: true or false
$show_details=false;							// Display photo dimensions & filesize: true or false
$show_date=false;							// Display date of photo (based on EXIF-date, if not available uses file-date): true or false
$show_date_format='d-M-Y H:i';		                                // Format for date - see PHP manual function date to change this
$show_exif_comment=false;					        // Display EXIF comment from photo (only when $popup=false): true or false
$show_iptc_caption=false;					        // Display the IPTC caption from photo  (only when $popup=false): true or false
$show_download=false;							// Show download link for photo in original size: true or false
$image_txtfile=true;							// Display text from a textfile (only when $popup=false). Filename for text file is same as photo (myphoto.jpg >> myphoto.txt): true or false
$visitor_comments=false;					        // Allow visitors to enter a comment with the photo: true or false
$visitor_comments_dateformat='d/M/Y H:i';	                        // Format for date with comment - see PHP manual function date to change this
$visitor_upload=false;			                                // Allow visitors to upload a file (be carefull!): true or false
$visitor_password=false;					        // Require valid password for uploading files: true or false
$visitor_upload_size=2048;				                // Maximum upload size for files from visitors in kB (2048 kB = 2 MB)
$visitor_upload_max_files=6;			                        // Maximum amount of files that can be uploaded by visitor simultaneously: 1 to 6 maximum
$visitor_files='png,gif,jpg,jpeg,swf,zip';	                        // Allow visitors to upload the specified file(s), comma separated 
$visitor_upload_adminreview=false;			                // Uploaded files will first be placed in the albums backup directory for review by the album administrator: true or false
$upload_email='';						        // Enter your email address to receive a notification of new uploads by mail, leave empty to disable
$comment_email='';							// Enter your email address to receive a copy of the comment by mail, leave empty to disable
$comment_logip=false;							// Save and display IP address with comment: true or false
$hit_counter=false;							// Enable hit counter - views per photo (not album), requires write access: true or false
$hit_counter_random=true;					        // Display segments irregular: true or false
$hit_counter_text=false;					        // Use text based hitcounter: true or false
$rating=false;								// Enable rating system - vistors rate the photo/multimediafile from scale 5 (excellent) to 1 (poor) - only when $popup=false, requires write access: true or false
$rating_text=false;							// Use text based rating - vistors rate the photo/multimediafile from scale 5 (excellent) to 1 (poor) - only when $popup=false, requires write access: true or false
$name_bold=true;							// Write photo name in bold: true or false
$name_italic=true;							// Write photo name in italic: true or false
$info_bold=false;							// Write photo information in bold: true or false
$info_italic=false;							// Write photo information in italic: true or false

// Photo manipulation for display

$image_resize=true;							// Set to true to resize photo for display, use this to show large photos in a smaller size: true or false
$image_resizeto=480;							// Size in px for resize (min. 30 pixels) or 0 for auto-resize
$image_inflate=false;							// Allow photo to be enlarged: true or false
$copyright='www.mywebmymail.com';	                                // Add copyright notice to photo (only when $image_resize=true)
$copyright_position='0% 100%';		                                // Position of copyright notice based on % of width and % of height of original image (50% 50% =centered)
$watermark='';							        // Add a watermark to the photo (only when $image_resize=true and GDLib2+), filelocation of the (transparent) PNG image file, example 'gfx/watermark.png'
$watermark_position='100% 100%';	                                // Position of watermark image based on % of width and % of height of original image (50% 50% =centered)
$watermark_transparancy=100;			                        // Transparency for watermark, 0 to 100: 0=not visible, 100=visible
$image_greyscale=false;						        // Convert color jpg photo to grayscale (only when $image_resize=true) - only for GDLib2+
$image_sepia_depth=80;						        // Add 'aged' effect to jpg photo only when $image_greyscale=true (0=disabled) - only for GDLib2+
$image_noise_depth=10;						        // Add random noise to jpg photo to make it look older only when $image_greyscale=true (0=disabled) - only for GDLib2+
$apply_thumbnail_borderpng=false;	                                // If you configured a border image for the thumbnail apply it to the photo as well: true or false

// Lightbox v2.0+ support

$lightbox=false;							// Set to true to enable lightbox: true or false
$lightbox_title=true;							// Set to true to enable caption support: true or false
$lightbox_group=true;							// Set to true to enable caption support: true or false
$lightbox_href='';							// Location of lightbox directory on your webserver, example 'http://www.abc.com/photoalbums/lightbox'

// TiltViewer v1.3 support

$tiltviewer=false;							// Enable tiltviewer support - Enable admin access and open configuration page in your browser to create xml file

// Piclens support

$piclens=false;								// Enable piclens support - Enable admin access and open configuration page in your browser to create rss file

// Photo shop system
// For a digital photo shop with PayPal payment processing 
// check the Digital Shop script on www.mywebmymail.com

$shop=false;								// Use shop system: true or false
$shop_email='';								// The email address the order will be emailed to
$shop_choice1='-,1x,2x,3x,4x,5x';		                        // Ordering information first selection box, comma separated 
$shop_choice2='-,09x13cm,10x15cm,11x17cm,13x18cm,25x30cm';	        // Ordering information second selection box, comma separated (leave empty to disable box)
$shop_columns=4;						        // All photos will be shown on a single page, this sets the amount of photos next to each other

// MultiMedia Files (MP3,Mpeg,AVI etc.)

$play_multimedia=false;							// Enable or Disable multimedia support (to link a photo to a MP3 file, include a MP3 with the same name as the photo): true or false
$embed_player=true;							// Embeds the player underneath the photo: true or false
$link_player=false;							// Creates a link from the image to the multimedia file: true or false
$download_multimedia=false;						// Add a download link to the multimedia file
$movie_formats='mpg,mpeg,avi,mov,swf,wmv';	                        // File extensions for supported movie files
$sound_formats='mp3,wav,au,wma,ogg';	                                // File extensions for supported sound files
$mm_watermark='';						        // Add a 'multimedia' watermark to the image (only when $image_resize=true and GDLib2+), filelocation of the (transparent) PNG image file, example 'gfx/multimedia_watermark.png'
$mm_watermark_position='100% 100%';		                        // Position of multimedia watermark image based on % of width and % of height of original image (50% 50% =centered)
$mm_watermark_transparancy=100;				                // Transparency for multimedia watermark, 0 to 100: 0=not visible, 100=visible
$mm_dir='';								// Directory for multimedia images (add a mp3.jpg to represent MP3 images, mpeg.png to represent MPEG files etc.), example 'gfx/'
$mm_thumbnail=false;							// Apply thumbnail settings to multimedia image: true or false
$mm_photo=false;							// Apply photo manipulation settings to multimedia image: true or false
$width_player=0;							// Set width of embedded multimediaplayer in px, 0=autosize
$height_player=0;							// Set height of embedded multimediaplayer in px, 0=autosize

// Automatic image resize

$resizeimages=false;					                // Set to true to auto-resize all uploaded photos permanently for smaller filesize - EXIF information is lost - write access required: true or false
$resizeto=640;								// Size in px for permanent resize (min. 30 pixels)
$donot_resize_gif=false;			                        // Do not resize GIF images (for animated content): true or false

// Colors for EasyPhpAlbum logo

$logo_line_color='#FE9900';		                                // Logo line color
$logo_text_color='#0A7FDC';		                                // Logo text color

// Page,Photo & Menu colors

$page_color='#D0DEEE';					                // Page background color
$text_color='#555555';							// Text color
$text_hover_color='#000000';						// Text hover color
$title_color='#0A7FDC';						        // Title color
$border_color='#D0DEEE';						// Photo border color
$table_color='#D0DEEE';							// Table background color
$item_border_color='#D0DEEE';						// Border color table
$line_color='#000000';							// Color for lines
$email_color='#FFFF99';							// Color for email button
$menu_line_width='1';							// Menu border line thickness in px (top+bottom)
$menu_bar_width='1';							// Menu bar line thickness in px (left + right)
$menu_bordertop_color='#000000';					// Menu border top color
$menu_borderbottom_color='#000000';				        // Menu border bottom color
$menu_borderleft_color='#000000';					// Menu border left color
$menu_borderright_color='#000000';				        // Menu border right color
$menu_bordertop_hover_color='#FE9900';		                        // Menu border hover top color
$menu_borderbottom_hover_color='#FE9900';	                        // Menu border hover bottom color
$menu_borderleft_hover_color='#D0DEEE';		                        // Menu border hover left color
$menu_borderright_hover_color='#D0DEEE';	                        // Menu border hover right color
$menu_text_color='#0A7FDC';						// Menu text color
$menu_texthover_color='#FE9900';					// Menu text hover color
$menu_background_color='#D0DEEE';					// Menu background color
$menu_background_hover_color='#D0DEEE';		                        // Menu background hover color
$hit_counter_linecolor='#999999';					// Hit counter line color
$hit_counter_segmentcolor='#000000';			                // Hit counter segment color
$hit_counter_textcolor='#FFFFFF';					// Hit counter text color
$rating_blockcolor='#CCCCCC';						// Rating color - no score
$rating_blockcolor_score='#FF0000';				        // Rating color - score

// META information for search-engines

$meta_description='EasyPhpAlbum, an easy to use single script photo, music and movie album with lots of features.';	// Short description for your album
$meta_keywords='easy,album,photo,movie,music,www.mywebmymail.com,easyphpalbum,gallery,thumbnails';                      // Search keywords comma separated
$meta_copyright_and_author='JF Nutbroek - www.mywebmymail.com';			                                        // Copyright and author of the website

// End of configuration
// ***************************************************************************************************

// Check if a configuration file exists - overrides the configuration in this index.php script
if (file_exists('configuration.php')) {include('configuration.php');}
$album_config=true;
if ($use_main_config) {
	if (file_exists('../configuration.php')) {
		include('../configuration.php');
		$album_config=false;
	}
}
if ($use_album_config!='') {
	if (file_exists("../$use_album_config/configuration.php")) {
		include("../$use_album_config/configuration.php");
		$album_config=false;
	}
}

// Check if a logout was requested
if (isset($_REQUEST['logout'])) {
	session_start();
	session_unset();
	session_destroy();
	if ($_REQUEST['logout']==1) {setcookie('epa','',time()-3600);} else {setcookie('epaadmin','',time()-3600);}
	if ($restrict_access) {require_login();}
}

// Check for administrator login
if ($admin_access && isset($_REQUEST['admin'])) {
	$users_configured=$users;
	$restrict_access_configured=$restrict_access;
	$users=$admins;
	$restrict_access=true;
	$admin_link='admin=1';
	if ($admin_ip!='') {
		$valid_ips=explode(',',$admin_ip);
		if (!in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {$users='';}
	}
} else {
	$admin_link='';
}

// Check for valid login - cookie and/or session
$logged_in=false;
if ($restrict_access || isset($_REQUEST['requirelogin'])) {
	session_start();
	$valid_users=explode(',',$users);
	foreach ($valid_users as $key => $user)
		$valid_users[$key]=md5($user . date('d'));
	if ($admin_link!='') {$cookiename='epaadmin';} else {$cookiename='epa';}
	// Check if cookie data is available and valid
	if (isset($_COOKIE[$cookiename])) {
		$cookie_data=explode('@',$_COOKIE[$cookiename]);
		if (count($cookie_data)==3) {
			if (in_array($cookie_data[0],$valid_users)) {
				$user_index=array_search($cookie_data[0],$valid_users);
				if ($valid_users[$user_index+1]!=$cookie_data[1])
					require_login();
				else if (md5($_SERVER['HTTP_USER_AGENT'])!=$cookie_data[2])
					require_login();
			} else {
				require_login();
			}
		} else {
			require_login();
		}
	// Check if form data is submitted  and valid
	} else if (isset($_REQUEST['new_user']) && isset($_REQUEST['new_password'])) {
		if (in_array(md5($_REQUEST['new_user'] . date('d')),$valid_users)) {
			$user_index=array_search(md5($_REQUEST['new_user'] . date('d')),$valid_users);
			if ($valid_users[$user_index+1]!=md5($_REQUEST['new_password'] . date('d'))) {
				require_login();
			} else {
				$_SESSION['epa_user']=md5($_REQUEST['new_user'] . date('d'));
				$_SESSION['epa_passw']=md5($_REQUEST['new_password'] . date('d'));
				$_SESSION['epa_agent']=md5($_SERVER['HTTP_USER_AGENT']);
				setcookie($cookiename,$_SESSION['epa_user'] . '@' . $_SESSION['epa_passw'] . '@' . $_SESSION['epa_agent'],time()+3600);
			}
		} else {
			require_login();
		}
	// Check if current session is valid
	} else if (isset($_SESSION['epa_passw']) && isset($_SESSION['epa_user']) && isset($_SESSION['epa_agent'])) {
		if ($_SESSION['epa_agent']!=md5($_SERVER['HTTP_USER_AGENT'])) {require_login();}
		if (in_array($_SESSION['epa_user'],$valid_users)) {
			$user_index=array_search($_SESSION['epa_user'],$valid_users);
			if ($valid_users[$user_index+1]!=$_SESSION['epa_passw']) {require_login();}
		} else {
			require_login();
		}
	// Session data and form data is invalid
	} else {
		require_login();
	}
	if ($visitor_password) {$logged_in=true;}
}

// Age check
$explicit_ok=false;
if ($explicit_content) {
  	if (isset($_REQUEST['over18'])) {
	   if ($_REQUEST['over18']==18) {
	    	setcookie('epa_18','true',time()+43200);
	    	$explicit_ok=true;
		}
	}
	if (isset($_COOKIE['epa_18']) || $admin_link!='') {$explicit_ok=true;}	
}

// Check for admin requests
if ($admin_link!='') {
	// Show configuration menu
	if (isset($_REQUEST['configuration'])) {configuration();}
	$supportedformats=explode(',',$movie_formats.','.$sound_formats.',png,gif,jpg,jpeg,txt,zip');
	// Rename image or directory
	if (isset($_REQUEST['renameimagenew']) && isset($_REQUEST['renameimageold'])) {
		$renameimageold=$_REQUEST['renameimageold'];
		if (is_file($renameimageold)) {
			$extension=strtolower(substr($renameimageold,strrpos($renameimageold,'.')+1,strlen($renameimageold)));
			if ($extension=='jpg' || $extension=='jpeg' || $extension=='png' || $extension=='gif'|| in_array($extension,$supportedformats)) {
				$newimagefilename=preg_replace("/([\\x00-\\x19\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$_REQUEST['renameimagenew']);
				@rename($renameimageold,$newimagefilename.'.'.$extension);
				$renameimageoldtxt=substr($renameimageold,0,strrpos($renameimageold,'.')).'.txt';
				if (file_exists($renameimageoldtxt))
					@rename($renameimageoldtxt,$newimagefilename.'.txt');
				else if (file_exists('textfiles/'.$renameimageoldtxt))
					@rename('textfiles/'.$renameimageoldtxt,'textfiles/'.$newimagefilename.'.txt');
			}
		} else if (is_dir($renameimageold)) {
			$albumname = preg_replace("/([\\x00-\\x19\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$_REQUEST['renameimagenew']);
			@rename($renameimageold,$albumname);
		}
	}
	// Delete a file or directory
	if (isset($_REQUEST['imagefilename'])) {
		$imagefilename=str_replace('/','',$_REQUEST['imagefilename']);
		$imagefilename=str_replace('..','',$imagefilename);
		if (isset($_REQUEST['backup'])) {
			if ($_REQUEST['backup']==1)
				$imagefilename='backup/'.$imagefilename;
		}
		if (is_file($imagefilename) || is_file('textfiles/'.$imagefilename)) {
			$extension=strtolower(substr($imagefilename,strrpos($imagefilename,'.')+1,strlen($imagefilename)));
			if ($extension=='jpg' || $extension=='jpeg' || $extension=='png' || $extension=='gif' || in_array($extension,$supportedformats)) {
				if (file_exists($imagefilename)) {@unlink($imagefilename);}
				if (is_dir('thumbnails')) {$subdir='thumbnails/';} else	{$subdir='';}
				if (file_exists($subdir.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumbindex.' . $extension))
					@unlink($subdir.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumbindex.' . $extension);
				if (file_exists($subdir.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension))
					@unlink($subdir.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension);
				// Delete rating and hitcounter files as well
				$imagefilename=substr($imagefilename,0,strrpos($imagefilename,'.')).'.stat';
				if (file_exists($imagefilename))
					@unlink($imagefilename);
				else if (file_exists('hitcounters/'.$imagefilename))
					@unlink('hitcounters/'.$imagefilename);
				$imagefilename=substr($imagefilename,0,strrpos($imagefilename,'.')).'.rate';
				if (file_exists($imagefilename))
					@unlink($imagefilename);
				else if (file_exists('ratings/'.$imagefilename))
					@unlink('ratings/'.$imagefilename);
			} else if ($extension=='txt') {
				if (file_exists($imagefilename))
					@unlink($imagefilename);
				else if (file_exists('textfiles/'.$imagefilename))
					@unlink('textfiles/'.$imagefilename);
			}
		} else if (is_dir($imagefilename)) {
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/hitcounters',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/ratings',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/textfiles',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/thumbnails',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/backup',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename.'/gfx',false,true,'*');
			removedir(str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename,false,true,'*');
		}
	}
	// Upload file(s)
	if (isset($_FILES['uploadimage1']) || isset($_FILES['uploadimage2']) || isset($_FILES['uploadimage3']) || isset($_FILES['uploadimage4']) || isset($_FILES['uploadimage5']) || isset($_FILES['uploadimage6'])) {
		for($i=1;$i<7;$i++) {
			if (isset($_FILES['uploadimage' . $i])) {
				$imagefilename=str_replace('/','',$_FILES['uploadimage' . $i]['name']);
				$imagefilename=str_replace('..','',$imagefilename);
				$imagefilename=preg_replace("/([\\x00-\\x19\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$imagefilename);
				$extension=strtolower(substr($imagefilename,strrpos($imagefilename,'.')+1,strlen($imagefilename)));
				if (in_array($extension,$supportedformats)) {
					if ($extension!='txt') {
						if (@move_uploaded_file($_FILES['uploadimage' . $i]['tmp_name'],str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename)) {
							if (filesize($imagefilename)==0) {@unlink($imagefilename);} else {@chmod($imagefilename,octdec($chmod_level));}
							if ($extension=='zip')
								unzipimages($imagefilename,$movie_formats.','.$sound_formats.',png,gif,jpg,jpeg,txt,zip','');
						}
					} else if (is_dir('textfiles')) {
						if (@move_uploaded_file($_FILES['uploadimage' . $i]['tmp_name'],str_replace(chr(92),chr(47),getcwd()).'/textfiles/'.$imagefilename)) {
							if (filesize('textfiles/'.$imagefilename)==0) {@unlink('textfiles/'.$imagefilename);} else {@chmod('textfiles/'.$imagefilename,octdec($chmod_level));}
						}
					} else {
						if (@move_uploaded_file($_FILES['uploadimage' . $i]['tmp_name'],str_replace(chr(92),chr(47),getcwd()).'/'.$imagefilename)) {
							if (filesize($imagefilename)==0) {@unlink($imagefilename);} else {@chmod($imagefilename,octdec($chmod_level));}
						}
					}
					if ($_FILES['uploadimage' . $i]['error']==UPLOAD_ERR_INI_SIZE)
						$title.=" - (upload failed: filesize too big)";
					if ($_FILES['uploadimage' . $i]['error']==UPLOAD_ERR_PARTIAL)
						$title.=" - (upload failed: upload interrupted)";
				}
			}
		}
	}
	// Add/edit text file for photo
	if (isset($_REQUEST['phototextfile']) && isset($_REQUEST['phototext'])) {
		if (is_dir('textfiles')) {
			if ($fp=@fopen('textfiles/'.$_REQUEST['phototextfile'],'w')) {
				fwrite($fp,stripslashes($_REQUEST['phototext']));
				fclose($fp);
			}
		} else {
			if ($fp=@fopen($_REQUEST['phototextfile'],'w')) {
				fwrite($fp,stripslashes($_REQUEST['phototext']));
				fclose($fp);
			}
		}
	}
	// Create text file for photo
	if (isset($_REQUEST['newtxtfile'])) {
		if (is_dir('textfiles')) {
			if (file_exists($_REQUEST['newtxtfile']))
				@touch('textfiles/'.substr($_REQUEST['newtxtfile'],0,strrpos($_REQUEST['newtxtfile'],'.')).'.txt');
				@chmod('textfiles/'.substr($_REQUEST['newtxtfile'],0,strrpos($_REQUEST['newtxtfile'],'.')).'.txt',octdec($chmod_level));
		} else {
			if (file_exists($_REQUEST['newtxtfile']))
				@touch(substr($_REQUEST['newtxtfile'],0,strrpos($_REQUEST['newtxtfile'],'.')).'.txt');
				@chmod(substr($_REQUEST['newtxtfile'],0,strrpos($_REQUEST['newtxtfile'],'.')).'.txt',octdec($chmod_level));
		}
	}
	// Backup image(s)
	for($i=1;$i<($images_per_page+1);$i++) {
		if (isset($_REQUEST['backup_'.$i])) {
			if (!is_dir('backup')) {@mkdir('backup');@chmod('backup',octdec($chmod_level));}
			$backupimage=$_REQUEST['backup_'.$i];
			@copy($backupimage,'backup/'.$backupimage);
		}
	}
	// Restore image
	if (isset($_REQUEST['restorefilename'])) {
		@copy('backup/'.$_REQUEST['restorefilename'],$_REQUEST['restorefilename']);
	}
	// Resize image(s)
	if (isset($_REQUEST['resizeimagesto'])) {
		$resizeimagesto=(int) $_REQUEST['resizeimagesto'];
		if ($resizeimagesto>0) {
			for($i=1;$i<($images_per_page+1);$i++) {
				if (isset($_REQUEST['image_'.$i])) {
					$resizeimage=$_REQUEST['image_'.$i];
					if (file_exists($resizeimage))
						resize($resizeimage,$resizeimagesto);	
				}
			}
		}
	}
	// Rotate image(s)
	if (isset($_REQUEST['rotateimages'])) {
		$direction=$_REQUEST['rotateimages'];
		if ($direction=='r' || $direction=='l') {
			for($i=1;$i<($images_per_page+1);$i++) {
				if (isset($_REQUEST['rotate_'.$i])) {
					$rotateimage=$_REQUEST['rotate_'.$i];
					if (file_exists($rotateimage))
						rotate($rotateimage,$direction);	
				}
			}
		}
	}
	// Create new album
	if (isset($_REQUEST['newalbumname'])) {
		$albumname = preg_replace("/([\\x00-\\x20\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$_REQUEST['newalbumname']);
		if(!file_exists($albumname) && $albumname!='') {
			if (@mkdir($albumname)) {
				if ($fp=@fopen($albumname.'/index.php','wb')) {
					fwrite($fp,"<?php\n");
					fwrite($fp,"include('../index.php');\n");
					fwrite($fp,'?>');
					fclose($fp);
				} else {
					@copy('index.php',$albumname.'/index.php');
				}
				@chmod($albumname,octdec($chmod_level));
				@chmod($albumname.'/index.php',octdec($chmod_level));
				if (file_exists('configuration.php')) {@copy('configuration.php',$albumname.'/configuration.php');@chmod($albumname.'/configuration.php',octdec($chmod_level));}
				if (!file_exists($albumname.'/hitcounters')) {@mkdir($albumname.'/hitcounters');@chmod($albumname.'/hitcounters',octdec($chmod_level));}
				if (!file_exists($albumname.'/ratings')) {@mkdir($albumname.'/ratings');@chmod($albumname.'/ratings',octdec($chmod_level));}
				if (!file_exists($albumname.'/textfiles')) {@mkdir($albumname.'/textfiles');@chmod($albumname.'/textfiles',octdec($chmod_level));}
				if (!file_exists($albumname.'/thumbnails')) {@mkdir($albumname.'/thumbnails');@chmod($albumname.'/thumbnails',octdec($chmod_level));}
				if (!file_exists($albumname.'/backup')) {@mkdir($albumname.'/backup');@chmod($albumname.'/backup',octdec($chmod_level));}
			} else {
				$title.=' - failed (please enable write access)';
			}
		} else {
			$title.=' - failed (album already exists)';		
		}
	}
}

// Redirect to tiltviewer
if (!isset($_REQUEST['admin']) && !isset($_REQUEST['configuration']) && $tiltviewer) {header("Location: index.html");}

// Display EasyPhpAlbum logo
if ($show_poweredby_easyphpalbum && isset($_REQUEST['poweredby'])) {
	if (imagetypes() & IMG_PNG) {
		header("Content-type: image/png");
		imagepng(poweredby_image());
	} else {
		header("Content-type: image/jpeg");
		imagejpeg(poweredby_image(),'',100);
	}
	exit;
}

// Display Email link 
if ($show_email_link && isset($_REQUEST['emaillink'])) {
	header("Content-type: image/png");
	imagepng(emaillink_image());
	exit;
}

// Update & output hit-counter
if ($hit_counter && isset($_REQUEST['statistics']) && isset($_REQUEST['image'])) {
	$image=$_REQUEST['image'];
	$stats_filename=substr($image,0,strrpos($image,'.')).'.stat';
	if (strpos($stats_filename,'/')!=false) {
		if (is_dir(substr($image,0,strrpos($image,'/')) . '/hitcounters'))
			$stats_filename=str_replace('/','/hitcounters/',$stats_filename);
	} else {
		if (is_dir('hitcounters'))
			$stats_filename='hitcounters/'.$stats_filename;
	}
	if (!file_exists($stats_filename) && file_exists($image)) {
		if (touch($stats_filename)) {
			if ($fp=@fopen($stats_filename,'w')) {
				fwrite($fp,'0');
				fclose($fp);
				@chmod($stats_filename,octdec($chmod_level));
			}
		} else {
			$hit_counter_random=false;
			header("HTTP/1.1 202 Accepted"); 
			header("Content-type: image/png");
			imagepng(hitcounter_image('ERROR'));
		}
	}
	if (is_writable($stats_filename)) {
		if ($fp=@fopen($stats_filename,'r+')) {
			$valid_ips=explode(',',$ban_ip);
			if ($_REQUEST['statistics']==1 && !in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {
				$stats=explode('@',fread($fp,filesize($stats_filename)));
				if (!in_array($_SERVER['REMOTE_ADDR'],$stats)) {
					array_push($stats,$_SERVER['REMOTE_ADDR']);
					$stats[0]=$stats[0]+1;
					rewind($fp);
					fwrite($fp,implode('@',$stats));
				}
			} else {
				$stats=explode('@',fread($fp,filesize($stats_filename)));
			}
			fclose($fp);
			header("HTTP/1.1 202 Accepted"); 
			header("Content-type: image/png");
			imagepng(hitcounter_image($stats[0]+0));
		}
	} else {
		$hit_counter_random=false;
		header("HTTP/1.1 202 Accepted"); 
		header("Content-type: image/png");
		imagepng(hitcounter_image('ERROR'));
	}
	exit;
}

// Update rating & output rating-scorebar
if ($rating && isset($_REQUEST['rating']) && isset($_REQUEST['rateimage'])) {
	$score=intval($_REQUEST['rating']);
	$image=$_REQUEST['rateimage'];
	$stats_filename=substr($image,0,strrpos($image,'.')).'.rate';
	if (is_dir('ratings'))
		$stats_filename='ratings/'.$stats_filename;
	if (!file_exists($stats_filename) && file_exists($image)) {
		if (touch($stats_filename)) {
			if ($fp=@fopen($stats_filename,'w')) {
				fwrite($fp,'0');
				fclose($fp);
				@chmod($stats_filename,octdec($chmod_level));
			}
		}
	}
	if (is_writable($stats_filename)) {
		if ($fp=@fopen($stats_filename,'r+')) {
			if ($score>0 && $score<6) {
				$stats=explode('@',fread($fp,filesize($stats_filename)));
				$valid_ips=explode(',',$ban_ip);
				if (!in_array($_SERVER['REMOTE_ADDR'],$stats) && !in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {
					rewind($fp);
					$stats[0]=$stats[0]+1;
					if (count($stats)>2) {$score=round(($stats[0]*$stats[1]+$score)/($stats[0]+1),2);}
					$number=explode('.',$score);
					$number[1]=(isset($number[1]))?$number[1]:'';
					$decimal=str_pad($number[1],2,'0');
					$score=$number[0].'.'.$decimal;
					$stats[1]=$score;
					array_push($stats,$_SERVER['REMOTE_ADDR']);
					fwrite($fp,implode('@',$stats));
					fclose($fp);
				}
			} else {
				$stats=explode('@',fread($fp,filesize($stats_filename)));
				if (count($stats)>2)
					$score=$stats[1];
				fclose($fp);
				header("HTTP/1.1 202 Accepted"); 
				header("Content-type: image/png");
				imagepng(rating_image(floor($score+0)));
				exit;
			}
		}
	}
}

// Save visitor comment with photo
if ($visitor_comments) {
	if (isset($_REQUEST['newcomment'])) {
		if ($_REQUEST['newcomment']!='') {
			// Make sure visitor stays on the same page
			if (isset($_REQUEST['comment_showimage']))
				$_REQUEST['showimage']=$_REQUEST['comment_showimage'];
			if (isset($_REQUEST['comment_screenwidth']))
				$_REQUEST['screenwidth']=$_REQUEST['comment_screenwidth'];
			// Add comment to textfile
			if (isset($_REQUEST['comment_username'])) {
				$username=substr(trim(stripslashes($_REQUEST['comment_username'])),0,10);
				if ($username=='') {$username='anonymous';}
			} else {
				$username='';
			}
			$valid_ips=explode(',',$ban_ip);
			if (is_dir('textfiles') && !in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {
				if ($fp=@fopen('textfiles/'.substr($_REQUEST['comment_showimage'],0,strrpos($_REQUEST['comment_showimage'],'.')).'.txt','ab')) {
					if ($comment_logip)
						fwrite($fp,'[ '.date($visitor_comments_dateformat).' - '.$_SERVER['REMOTE_ADDR'].' - by ' . $username . ' ]' . "\n");
					else
						fwrite($fp,'[ '.date($visitor_comments_dateformat).' - by '.$username . ' ]' . "\n");
					fwrite($fp,substr(trim(stripslashes($_REQUEST['newcomment'])),0,$comment_size) . "\n". "\n");
					fclose($fp);
					if ($comment_email!='')
						mail($comment_email,'New comment for photoalbum ' . $title,'photo: ' . $_REQUEST['comment_showimage'] . chr(10) . chr(10) . 'comment: ' . substr(trim(stripslashes($_REQUEST['newcomment'])),0,$comment_size) . chr(10) . chr(10) . 'Link: http://' . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS['SCRIPT_NAME'] . '?showimage=' . rawurlencode($_REQUEST['showimage']) . '&screenwidth=' . $_REQUEST['screenwidth'],'From: ' . $comment_email . "\r\n" . 'Reply-To: ' . $comment_email . "\r\n" . 'X-Mailer: PHP/' . phpversion());
				}
			} else if (!in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {
				if ($fp=@fopen(substr($_REQUEST['comment_showimage'],0,strrpos($_REQUEST['comment_showimage'],'.')).'.txt','ab')) {
					if ($comment_logip)
						fwrite($fp,'[ '.date($visitor_comments_dateformat).' - '.$_SERVER['REMOTE_ADDR'].' - by ' . $username . ' ]' . "\n");
					else
						fwrite($fp,'[ '.date($visitor_comments_dateformat).' - by '.$username . ' ]' . "\n");
					fwrite($fp,substr(trim(stripslashes($_REQUEST['newcomment'])),0,$comment_size) . "\n". "\n");
					fclose($fp);
					if ($comment_email!='')
						mail($comment_email,'New comment for photoalbum ' . $title,'photo: ' . $_REQUEST['comment_showimage'] . chr(10) . chr(10). 'comment: ' . substr(trim(stripslashes($_REQUEST['newcomment'])),0,$comment_size) . chr(10) . chr(10) . 'Link: http://' . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS['SCRIPT_NAME'] . '?showimage=' . rawurlencode($_REQUEST['showimage']) . '&screenwidth=' . $_REQUEST['screenwidth'],'From: ' . $comment_email . "\r\n" . 'Reply-To: ' . $comment_email . "\r\n" . 'X-Mailer: PHP/' . phpversion());
				}
			}
		}
	}
}

// Upload file(s) from visitor
if ($visitor_upload) {
	$valid_ips=explode(',',$ban_ip);
	if ((isset($_FILES['uploadfile1']) || isset($_FILES['uploadfile2']) || isset($_FILES['uploadfile3']) || isset($_FILES['uploadfile4']) || isset($_FILES['uploadfile5']) || isset($_FILES['uploadfile6'])) && !in_array($_SERVER['REMOTE_ADDR'],$valid_ips)) {
		$accepted_files=explode(',',$visitor_files);
		$uploaded_files='';
		if ($visitor_upload_adminreview) {
			if (!is_dir('backup')) {@mkdir('backup');@chmod('backup',octdec($chmod_level));}
		}
		for($i=1;$i<7;$i++) {
			if (isset($_FILES['uploadfile' . $i])) {
				$imagefilename=str_replace('/','',$_FILES['uploadfile' . $i]['name']);
				$imagefilename=str_replace('..','',$imagefilename);
				$imagefilename=preg_replace("/([\\x00-\\x20\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$imagefilename);
				$extension=strtolower(substr($imagefilename,strrpos($imagefilename,'.')+1,strlen($imagefilename)));
				if (in_array($extension,$accepted_files)) {
					if (isset($_REQUEST['comment_username'])) {
						$username=substr(preg_replace("/([\\x00-\\x20\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",trim(stripslashes($_REQUEST['comment_username']))),0,10);
						if ($username=='') {$username='anonymous';}
					} else {
						$username='anonymous';
					}
					$imagefilename=substr($imagefilename,0,strrpos($imagefilename,'.')).'_by_'.$username.'.'.$extension;			
					if ($visitor_upload_adminreview && $extension!='zip' && file_exists('backup')) {$reviewdir='backup/';} else {$reviewdir='';}
					if (file_exists($reviewdir.$imagefilename))
						$imagefilename=rand(0,999) . ' ' . $imagefilename;
					if (@move_uploaded_file($_FILES['uploadfile' . $i]['tmp_name'],str_replace(chr(92),chr(47),getcwd()).'/'.$reviewdir.$imagefilename)) {
					if (filesize($reviewdir.$imagefilename)==0) {@unlink($reviewdir.$imagefilename);} else {@chmod($reviewdir.$imagefilename,octdec($chmod_level));}
						if (in_array($extension,explode(',','png,gif,jpg,jpeg,swf'))) {
							if (!$check_file = @GetImageSize($reviewdir.$imagefilename)) {@unlink($reviewdir.$imagefilename);}
						}
						$uploaded_files.=$imagefilename.chr(10);
						if ($extension=='zip') {unzipimages($reviewdir.$imagefilename,$visitor_files,'_by_'.$username);}
						if (file_exists(substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension))
							@unlink(substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension);
						if (file_exists('thumbnails/'.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension))
							@unlink('thumbnails/'.substr($imagefilename,0,strrpos($imagefilename,'.')) . '_thumb.' . $extension);
					}
					if ($_FILES['uploadfile' . $i]['error']==UPLOAD_ERR_INI_SIZE)
						$title.=" | ERROR Upload failed: filesize too big";
					if ($_FILES['uploadfile' . $i]['error']==UPLOAD_ERR_PARTIAL)
						$title.=" | ERROR Upload failed: upload interrupted";
					if ($_FILES['uploadfile' . $i]['error']==UPLOAD_ERR_FORM_SIZE)
						$title.=" | ERROR Upload failed: filesize too big";
				}
			}
		}
		if ($upload_email!='' && $uploaded_files!='')
			mail($upload_email,'New upload for album ' . $title,'Uploaded file(s): ' .chr(10).chr(10). $uploaded_files .chr(10).chr(10) . 'Uploaded by: ' . $username . ' IP-address: ' . $_SERVER['REMOTE_ADDR'] . chr(10).chr(10) . 'Link: http://' . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS['SCRIPT_NAME'],'From: ' . $upload_email . "\r\n" . 'Reply-To: ' . $upload_email . "\r\n" . 'X-Mailer: PHP/' . phpversion());
		if ($uploaded_files!='' && !$visitor_upload_adminreview) {$title.=" | $language_visitor_upload_message";} 
		if ($uploaded_files!='' && $visitor_upload_adminreview) {$title.=" | $language_visitor_upload_review";}
	}
}

// Create and output image in specified size
if (isset($_REQUEST['image'])) {
	$image=$_REQUEST['image'];
	if (file_exists($image)) {
		$size=@GetImageSize($image);
		if ($size[2]==1) {
			if (imagetypes() & IMG_GIF) {
	    			$im=@imagecreatefromgif($image);
			} else {
				header("Content-type: image/png");
				imagepng(invalid_image('No GIF support'));
				exit;
			}
		}
		if ($size[2]==2) {
			if (imagetypes() & IMG_JPG) {
	    			$im=@imagecreatefromjpeg($image);
			} else {
				header("Content-type: image/png");
				imagepng(invalid_image('No JPG support'));
				exit;
			}
		}
		if ($size[2]==3) {
			if (imagetypes() & IMG_PNG) {
				$im=@imagecreatefrompng($image);
			} else {
				header("Content-type: image/jpeg");
				imagejpeg(invalid_image('No PNG support'),'',100);
				exit;
			}
		}
		if ($size[2]!=1 && $size[2]!=2 && $size[2]!=3) {
			$thumb=invalid_image('Invalid Image');
		} else {
			// Do not modify thumbnailindex file
			$is_index=substr($image,0,strrpos($image,'.'));
			if (strpos($is_index,'/')) {$is_index=substr($is_index,strrpos($is_index,'/')+1);}
			if ($is_index=='index' && $indeximage_no_thumb) {
				$thumb_size=$size[0];
				$border_width=0;
				$show_bordershadow=false;
				$show_binder=false;
				$clip_corner=0;
				$show_number=false;
				$thumbnail_borderpng='';
				$thumbnail_rotation=false;
				$square_thumbnails=false;
			}
			// Determine some sizes and settings
			if ($thumb_size<30)
				$thumb_size=30;
			if (isset($_REQUEST['resize'])) {
				if ($image_resizeto==0 && isset($_REQUEST['screenwidth']))
					$image_resizeto=floor($_REQUEST['screenwidth']/1.6);
				if (!$image_inflate) {
					if ($image_resizeto>$size[0] && $image_resizeto>$size[1])
						$image_resizeto=max($size[0],$size[1]);
				}
				$thumb_size=$image_resizeto;
				if (isset($_REQUEST['adminpanel'])) {
					$copyright='';
					$thumb_size=60;
					$mm_watermark='';
					$watermark='';
				}
				$show_number=false;
				$show_binder=false;
				$show_bordershadow=false;
				$clip_corner=0;
				if (!$apply_thumbnail_borderpng) {
					$thumbnail_borderpng='';
					$border_width=0;
				}
				$thumbnail_rotation=false;
			}
			if ($show_binder)
				$border_offset=3;
			else
				$border_offset=2;
			if ($show_bordershadow)
				$shadow_offset=3;
			else
				$shadow_offset=0;
			// Add watermark
			if ($watermark!='') {
				if ($gd2 && file_exists($watermark)) {
					$watermarkim=@imagecreatefrompng($watermark);
						$wpos=explode(' ',str_replace('%','',$watermark_position));
						if (count($wpos)>1)
							@imagecopymerge($im,$watermarkim,min(max(imagesx($im)*($wpos[0]/100)-0.5*imagesx($watermarkim),0),imagesx($im)-imagesx($watermarkim)),min(max(imagesy($im)*($wpos[1]/100)-0.5*imagesy($watermarkim),0),imagesy($im)-imagesy($watermarkim)),0,0,imagesx($watermarkim),imagesy($watermarkim),$watermark_transparancy+0);
						else
							@imagecopymerge($im,$watermarkim,imagesx($im)-imagesx($watermarkim),imagesy($im)-imagesy($watermarkim),0,0,imagesx($watermarkim),imagesy($watermarkim),$watermark_transparancy+0);
						@imagedestroy($watermarkim);
				}
			}
			// Add watermark for multimediafiles
			if ($mm_watermark!='') {
				if ($gd2 && file_exists($mm_watermark)) {
					$mm_file=get_multimedia($image,false);
					if ($mm_file!='') {
						$watermarkim=@imagecreatefrompng($mm_watermark);
						$wpos=explode(' ',str_replace('%','',$mm_watermark_position));
						if (count($wpos)>1)
							@imagecopymerge($im,$watermarkim,min(max(imagesx($im)*($wpos[0]/100)-0.5*imagesx($watermarkim),0),imagesx($im)-imagesx($watermarkim)),min(max(imagesy($im)*($wpos[1]/100)-0.5*imagesy($watermarkim),0),imagesy($im)-imagesy($watermarkim)),0,0,imagesx($watermarkim),imagesy($watermarkim),$mm_watermark_transparancy+0);
						else
							@imagecopymerge($im,$watermarkim,imagesx($im)-imagesx($watermarkim),imagesy($im)-imagesy($watermarkim),0,0,imagesx($watermarkim),imagesy($watermarkim),$mm_watermark_transparancy+0);
						@imagedestroy($watermarkim);
					}
				}
			}
			// Create empty thumbnail
			$x1=$border_width*$border_offset+$thumb_size+$shadow_offset;
			$x2=$border_width*$border_offset+ceil($size[0]/($size[1]/$thumb_size))+$shadow_offset;
			$y1=$border_width*2+ceil($size[1]/($size[0]/$thumb_size))+$shadow_offset;
			$y2=$border_width*2+$thumb_size+$shadow_offset;
			if ($gd2) {
				if ($size[0]>$size[1])
					$thumb=imagecreatetruecolor($x1,$y1);
				else
					$thumb=imagecreatetruecolor($x2,$y2);
			} else {
				if ($size[0]>$size[1])
					$thumb=imagecreate($x1,$y1);
				else
					$thumb=imagecreate($x2,$y2);
			}
			$black=imagecolorallocate($thumb,0,0,0);
			$white=imagecolorallocate($thumb,255,255,255);
			$gray=imagecolorallocate($thumb,192,192,192);
			$middlegray=imagecolorallocate($thumb,158,158,158);
			$darkgray=imagecolorallocate($thumb,128,128,128);
			imagefill($thumb,0,0,imagecolorallocate($thumb,hexdec(substr($table_color,1,2)),hexdec(substr($table_color,3,2)),hexdec(substr($table_color,5,2))));
			if ($show_binder)
				$bind_offset=4;
			else
				$bind_offset=0;
			imagefilledrectangle($thumb,$bind_offset,0,imagesx($thumb)-$shadow_offset,imagesy($thumb)-$shadow_offset,imagecolorallocate($thumb,hexdec(substr($border_color,1,2)),hexdec(substr($border_color,3,2)),hexdec(substr($border_color,5,2))));
			// Add shadow to thumbnail
			if ($show_bordershadow) {
				imagerectangle($thumb,$bind_offset,0,imagesx($thumb)-4,imagesy($thumb)-4,$gray);
				imageline($thumb,$bind_offset,imagesy($thumb)-3,imagesx($thumb),imagesy($thumb)-3,$darkgray);
				imageline($thumb,imagesx($thumb)-3,0,imagesx($thumb)-3,imagesy($thumb),$darkgray);
				imageline($thumb,$bind_offset+2,imagesy($thumb)-2,imagesx($thumb),imagesy($thumb)-2,$middlegray);
				imageline($thumb,imagesx($thumb)-2,2,imagesx($thumb)-2,imagesy($thumb),$middlegray);
				imageline($thumb,$bind_offset+2,imagesy($thumb)-1,imagesx($thumb),imagesy($thumb)-1,$gray);
				imageline($thumb,imagesx($thumb)-1,2,imagesx($thumb)-1,imagesy($thumb),$gray);
			}
			// Clip corner of original image
			if ($clip_corner>0) {
				$clip_corner=floor(imagesx($im)*($clip_corner/100));
				if ($clip_corner_round){
					$clip_degrees=90/$clip_corner;
					// Set centre point for polygon
					$points_tl=array(0,0);
					$points_br=array(imagesx($im),imagesy($im));
					$points_tr=array(imagesx($im),0);
					$points_bl=array(0,imagesy($im));
				}
				$bgcolor=imagecolorallocate($im,hexdec(substr($border_color,1,2)),hexdec(substr($border_color,3,2)),hexdec(substr($border_color,5,2)));
				for ($i=0;$i<$clip_corner;$i++) {
					if ($clip_corner_round){
						$x=$clip_corner*cos(deg2rad($i*$clip_degrees));
						$y=$clip_corner*sin(deg2rad($i*$clip_degrees));
						array_push($points_tl,$clip_corner-$x);
						array_push($points_tl,$clip_corner-$y);
						array_push($points_tr,imagesx($im)-$clip_corner+$x);
						array_push($points_tr,$clip_corner-$y);
						array_push($points_br,imagesx($im)-$clip_corner+$x);
						array_push($points_br,imagesy($im)-$clip_corner+$y);
						array_push($points_bl,$clip_corner-$x);
						array_push($points_bl,imagesy($im)-$clip_corner+$y);
					} else {
						if ($clip_randomly) {$random=1;} else {$random=0;}
						if ($clip_topleft && rand(0,$random)==0) {imageline($im,0,$i,$clip_corner-$i,$i,$bgcolor);}
						if ($clip_bottomright && rand(0,$random)==0) {imageline($im,imagesx($im)-$clip_corner+$i,imagesy($im)-$i-1,imagesx($im)+$clip_corner-$i,imagesy($im)-$i-1,$bgcolor);}
						if ($clip_topright && rand(0,$random)==0) {imageline($im,imagesx($im)-$clip_corner+$i,$i,imagesx($im)+$clip_corner-$i,$i,$bgcolor);}
						if ($clip_bottomleft && rand(0,$random)==0) {imageline($im,0,imagesy($im)-$i-1,$clip_corner-$i,imagesy($im)-$i-1,$bgcolor);}
					}
				}
				if ($clip_corner_round){
					// Add the final points to cope with rounding error
					array_push($points_tl,$clip_corner,0);
					array_push($points_br,imagesx($im)-$clip_corner,imagesy($im));
					array_push($points_tr,imagesx($im)-$clip_corner,0);
					array_push($points_bl,$clip_corner,imagesy($im));
					if ($clip_randomly) {$random=1;} else {$random=0;}
					if ($clip_topleft && rand(0,$random)==0) {imagefilledpolygon($im,$points_tl,count($points_tl)/2,$bgcolor);}
					if ($clip_bottomright && rand(0,$random)==0) {imagefilledpolygon($im,$points_br,count($points_br)/2,$bgcolor);}
					if ($clip_topright && rand(0,$random)==0) {imagefilledpolygon($im,$points_tr,count($points_tr)/2,$bgcolor);}
					if ($clip_bottomleft && rand(0,$random)==0) {imagefilledpolygon($im,$points_bl,count($points_bl)/2,$bgcolor);}
					// Cleanup - remove 1px from outline of image
					imagerectangle($im,0,0,imagesx($im)-1,imagesy($im)-1,$bgcolor);
				}
			}
			// Image created - modify colors (only for jpg & gd2)
			if ($image_greyscale && $size[2]==2 && $gd2) {
				imagetruecolortopalette($im,1,256);
					for ($c=0;$c<256;$c++) {    
						$col=imagecolorsforindex($im,$c);
						$new_col=floor($col['red']*0.2125+$col['green']*0.7154+$col['blue']*0.0721);
						$noise=rand(-$image_noise_depth,$image_noise_depth);
						if ($image_sepia_depth>0) {
							$r=$new_col+$image_sepia_depth+$noise;
							$g=floor($new_col+$image_sepia_depth/1.86+$noise);
							$b=floor($new_col+$image_sepia_depth/-3.48+$noise);
						} else {
							$r=$new_col+$noise;
							$g=$new_col+$noise;
							$b=$new_col+$noise;
						}
					imagecolorset($im,$c,max(0,min(255,$r)),max(0,min(255,$g)),max(0,min(255,$b)));
					}
			}
			// Copy photo to thumbnail
			if ($gd2)
				@imagecopyresampled($thumb,$im,$border_width*($border_offset-1),$border_width,0,0,imagesx($thumb)-($border_offset*$border_width)-$shadow_offset,imagesy($thumb)-2*$border_width-$shadow_offset,imagesx($im),imagesy($im));
			else
				@imagecopyresized($thumb,$im,$border_width*($border_offset-1),$border_width,0,0,imagesx($thumb)-($border_offset*$border_width)-$shadow_offset,imagesy($thumb)-2*$border_width-$shadow_offset,imagesx($im),imagesy($im));
			// Copy thumbnail border image
			if ($thumbnail_borderpng!='') {
				if ($gd2 && file_exists($thumbnail_borderpng)) {
					$borderim=@imagecreatefrompng($thumbnail_borderpng);
					@imagecopyresampled($thumb,$borderim,$bind_offset,0,0,0,imagesx($thumb)-$shadow_offset-$bind_offset,imagesy($thumb)-$shadow_offset,imagesx($borderim),imagesy($borderim));
					@imagedestroy($borderim);
				} else if (file_exists($thumbnail_borderpng)) {
					$borderim=@imagecreatefrompng($thumbnail_borderpng);
					@imagecopyresized($thumb,$borderim,$bind_offset,0,0,0,imagesx($thumb)-$shadow_offset-$bind_offset,imagesy($thumb)-$shadow_offset,imagesx($borderim),imagesy($borderim));
					@imagedestroy($borderim);
				}
			}
			// Add thumbnail number
			if ($show_number && isset($_REQUEST['number']) && isset($_REQUEST['total'])) {
				// Sample some pixels to determine text color
				$colors=array();
				for ($i=5;$i<25;$i++) {
					$indexis=ImageColorAt($thumb,$i,4+ceil($i/5));
					$rgbarray=ImageColorsForIndex($thumb,$indexis);
					array_push($colors,$rgbarray['red'],$rgbarray['green'],$rgbarray['blue']);
				}
				if (array_sum($colors)/count($colors)>180)
					$textcolor=$black;
				else
					$textcolor=$white;
				if ($show_binder)
					$number_offset=$border_width*2;
				else
					$number_offset=$border_width;
				if ($border_width==0)
					$number_offset=1;
				imagestring($thumb,1,$number_offset,2,($_REQUEST['number']+1) . '/' . $_REQUEST['total'],$textcolor);
			}
			// Add a binder
			if ($show_binder) {
				if ($binder_spacing<4)
					$binder_spacing=4;
				$spacing=floor(imagesy($thumb)/$binder_spacing)-2;
				$offset=floor((imagesy($thumb)-($spacing*$binder_spacing))/2);
				for ($i=$offset;$i<=$offset+$spacing*$binder_spacing;$i+=$binder_spacing) {
					imagefilledrectangle($thumb,8,$i-2,10,$i+2,$black);
					imageline($thumb,11,$i-1,11,$i+1,$darkgray);
					imageline($thumb,8,$i-2,10,$i-2,$darkgray);
					imageline($thumb,8,$i+2,10,$i+2,$darkgray);
					imagefilledrectangle($thumb,0,$i-1,8,$i+1,$gray);
					imageline($thumb,0,$i,8,$i,$white);
					imageline($thumb,0,$i-1,0,$i+1,$gray);
					imagesetpixel($thumb,0,$i,$darkgray);
				}
			}
			// Add copyright
			if (isset($_REQUEST['resize']) && $copyright!='') {
				$widthx=imagefontwidth(1)*strlen($copyright);
				if (($widthx+imagefontwidth(1))>imagesx($thumb)) {
					$copyright=substr($copyright,0,floor(imagesx($thumb)/imagefontwidth(1))-1);
					$widthx=imagefontwidth(1)*strlen($copyright);
				}
				$heighty=imagefontheight(1);
				$cpos=explode(' ',str_replace('%','',$copyright_position));
				if (count($cpos)>1) {
					$cposx=min(max(imagesx($thumb)*($cpos[0]/100)-0.5*$widthx,imagefontwidth(1)),imagesx($thumb)-$widthx-imagefontwidth(1));
					$cposy=min(max(imagesy($thumb)*($cpos[1]/100)-0.5*$heighty,$heighty),imagesy($thumb)-$heighty*1.5);
				} else {
					$cposx=imagefontwidth(1);
					$cposy=imagesy($thumb)-10;
				}			
				$colors=array();
				for ($i=$cposx;$i<($cposx+$widthx);$i++) {
					$indexis=ImageColorAt($thumb,$i,$cposy+0.5*$heighty);
					$rgbarray=ImageColorsForIndex($thumb,$indexis);
					array_push($colors,$rgbarray['red'],$rgbarray['green'],$rgbarray['blue']);
				}
				if (array_sum($colors)/count($colors)>180)
					imagestring($thumb,1,$cposx,$cposy,$copyright,$black);
				else
					imagestring($thumb,1,$cposx,$cposy,$copyright,$white);
			}
			// Randomly rotate the thumbnail - coded for compatibility with PHP 4.1.0
			if ($thumbnail_rotation) {
				if ($thumbnail_rotation_degrees==0)
					$thumbnail_rotation_degrees=rand(-1,1)*45;	// 45 degrees provides good result without the need for antialiasing
				if ($thumbnail_rotation_degrees<>0 && imagesx($thumb)<imagesy($thumb)) {$thumbnail_rotation_degrees=$thumbnail_rotation_degrees*-1;} // Tilt portrait thumbnails in other direction
				if ($thumbnail_rotation_degrees<>0) {
					$centerx=imagesx($thumb)/2;
					$centery=imagesy($thumb)/2;
					$maxsizex=ceil(abs(cos(deg2rad($thumbnail_rotation_degrees))*imagesx($thumb))+abs(sin(deg2rad($thumbnail_rotation_degrees))*imagesy($thumb)));
					$maxsizey=ceil(abs(sin(deg2rad($thumbnail_rotation_degrees))*imagesx($thumb))+abs(cos(deg2rad($thumbnail_rotation_degrees))*imagesy($thumb)));
					if ($maxsizex & 1) {$maxsizex+=3;} else	{$maxsizex+=2;}
					if ($maxsizey & 1) {$maxsizey+=3;} else {$maxsizey+=2;}
					if ($gd2) {$newthumb=imagecreatetruecolor($maxsizex,$maxsizey);} else {$newthumb=imagecreate($maxsizex,$maxsizey);}
					imagefill($newthumb,0,0,imagecolorallocate($newthumb,hexdec(substr($table_color,1,2)),hexdec(substr($table_color,3,2)),hexdec(substr($table_color,5,2))));			
					$newcenterx=imagesx($newthumb)/2;
					$newcentery=imagesy($newthumb)/2;
					$thumbnail_rotation_degrees+=180;
					for ($px=0;$px<imagesx($newthumb);$px++) {
						for ($py=0;$py<imagesy($newthumb);$py++) {
							$vectorx=($newcenterx-$px)*cos(deg2rad($thumbnail_rotation_degrees))+($newcentery-$py)*sin(deg2rad($thumbnail_rotation_degrees));
							$vectory=($newcentery-$py)*cos(deg2rad($thumbnail_rotation_degrees))-($newcenterx-$px)*sin(deg2rad($thumbnail_rotation_degrees));
							if (($centerx+$vectorx)>-1 && ($centerx+$vectorx)<($centerx*2) && ($centery+$vectory)>-1 && ($centery+$vectory)<($centery*2))
								@imagecopy($newthumb,$thumb,$px,$py,$centerx+$vectorx,$centery+$vectory,1,1);
						}
					}
					@imagedestroy($thumb);
					if ($gd2) {$thumb=imagecreatetruecolor(imagesx($newthumb),imagesy($newthumb));} else {$thumb=imagecreate(imagesx($newthumb),imagesy($newthumb));}
					@imagecopy($thumb,$newthumb,0,0,0,0,imagesx($newthumb),imagesy($newthumb));
					@imagedestroy($newthumb);
				}
			}
		}
		if ($square_thumbnails && isset($_REQUEST['number'])) {
			$squaresize=max(imagesx($thumb),imagesy($thumb));
			if ($gd2) {$newthumb=imagecreatetruecolor($squaresize,$squaresize);} else {$newthumb=imagecreate($squaresize,$squaresize);}
			imagefill($newthumb,0,0,imagecolorallocate($newthumb,hexdec(substr($border_color,1,2)),hexdec(substr($border_color,3,2)),hexdec(substr($border_color,5,2))));
			$centerx=floor(($squaresize-imagesx($thumb))/2);
			$centery=floor(($squaresize-imagesy($thumb))/2);
			@imagecopy($newthumb,$thumb,$centerx,$centery,0,0,imagesx($thumb),imagesy($thumb));
			@imagedestroy($thumb);
			if ($gd2) {$thumb=imagecreatetruecolor($squaresize,$squaresize);} else {$thumb=imagecreate($squaresize,$squaresize);}
			@imagecopy($thumb,$newthumb,0,0,0,0,$squaresize,$squaresize);
			@imagedestroy($newthumb);
		}
		if (strpos($image,'/')) {$subdir=substr($image,0,strpos($image,'/')+1);} else {$subdir='';}
		if (is_dir($subdir . 'thumbnails')) {$thumbdir='thumbnails/';} else {$thumbdir='';}
		if (isset($_REQUEST['indexalbum'])) {$indexalbum=(int) $_REQUEST['indexalbum'];} else {$indexalbum=0;}
		if ($indexalbum>0)
			$thumbfilename=$subdir . $thumbdir . substr($image,strlen($subdir),strrpos($image,'.')-strlen($subdir)) . '_thumbindex';
		else
			$thumbfilename=$subdir . $thumbdir . substr($image,0,strrpos($image,'.')) . '_thumb';
		if ($size[2]==1) {
			if ($create_thumbnail_cache && !isset($_REQUEST['resize'])) {
				@imagegif($thumb,$thumbfilename.'.gif');
				@chmod($thumbfilename.'.gif',octdec($chmod_level));
			}
			header("Content-type: image/gif");
			imagegif($thumb);
		} else if ($size[2]==2) {
			if ($create_thumbnail_cache && !isset($_REQUEST['resize'])) {
				@imagejpeg($thumb,$thumbfilename.'.jpg',90);
				@chmod($thumbfilename.'.jpg',octdec($chmod_level));
			}
			header("Content-type: image/jpeg");
			imagejpeg($thumb,'',90);
		} else if ($size[2]==3) {
			if ($create_thumbnail_cache && !isset($_REQUEST['resize'])) {
				@imagepng($thumb,$thumbfilename.'.png');
				@chmod($thumbfilename.'.png',octdec($chmod_level));
			}
			header("Content-type: image/png");
			imagepng($thumb);
		} else {
			header("Content-type: image/png");
			$supportedformats=explode(',',$movie_formats.','.$sound_formats);
			if (in_array(strtolower(substr($image,strrpos($image,'.')+1,strlen($image))),$supportedformats)) {imagepng(invalid_image('No thumbnail'));} else {imagepng(invalid_image('Invalid Image'));}
		}
	} else {
		header("Content-type: image/png");
		imagepng(invalid_image('File not found'));
	}
	@imagedestroy($im);
	@imagedestroy($thumb);
	exit;
}

// Batch resize all images in directory permanently - checks if image has been resized already
if ($resizeimages) {
	$images=array();
	$images=get_images(getcwd(),false,false,false);
	if (count($images)>0 && $resizeto>30) {
		foreach ($images as $image) {
			$size=@GetImageSize($image);
			if (max($size[0],$size[1])>$resizeto && (!$donot_resize_gif || ($donot_resize_gif && $size[2]!=1)))
				resize($image,$resizeto);
		}
	}
}

// Create new images for multimedia files without their own image
if ($play_multimedia && $mm_dir!='') {create_mm(false);}

// Detect sub directories - if present; current index.php file is home (main index) - otherwise detect directories one level higher
$dir_names=array();
$file_names=array();
$album_show=false;
$total_amount_images=0;
if ($dir=@opendir(getcwd())) {
	while ($file=@readdir($dir)) {
		if (($file!='.') && ($file!='..') && is_dir($file) && file_exists($file.'/index.php') && ($file!='_vti_cnf')) {
			$images=get_images($file,false,true,false);
			if (count($images)!=0) {
				array_push($dir_names,$file);
				$index_image_exists=count($file_names);
				$subtract_index=0;
				foreach ($images as $firstimage) {
					if (substr($firstimage,0,strrpos($firstimage,'.'))=='index') {
						array_push($file_names,$file . '/' . $firstimage);
						$subtract_index=-1;
						break;
					}
				}
				if ($index_image_exists==count($file_names))
					array_push($file_names,$file . '/' . $images[0]);
				$album_show=true;
				$total_amount_images=$total_amount_images+count($images)+$subtract_index;
			}
		}
	}
	@closedir($dir);
}
sort($dir_names);
sort($file_names);
$total_amount_albums=count($dir_names);
if (count($dir_names)==0) {
	$dir_names=array();
	if ($dir=@opendir('../')) {
		while ($file=@readdir($dir)) {
			if (($file!='.') && ($file!='..') && is_dir('../'.$file) && file_exists('../'.$file.'/index.php') && $file!=substr(getcwd(),-strlen($file)) && ($file!='_vti_cnf')) {
				$images=get_images('../' . $file,false,false,false);
				if (count($images)!=0)
					array_push($dir_names,'../' . $file);
			}
		}
		@closedir($dir);
	}
	sort($dir_names);
	if ($admin_link!='')
		$file_names=get_images('./',true,true,false);
	else
		$file_names=get_images('./',true,false,false);
}

// Add backup images for administrator access
$backup_not_published=0;
if ($admin_link!='' && is_dir('backup')) {
	$backup_files=array();
	if ($dir=@opendir('backup')) {
		while ($file=@readdir($dir)) {
			if (($file!='.') && ($file!='..') && !is_dir($file))
				array_push($backup_files,$file);	
		}
	}
	foreach($backup_files as $backup_image) {
		if (!in_array($backup_image,$file_names)) {
			array_push($file_names,$backup_image);
			$backup_not_published+=1;
		}
	}
}

// Add multimedia files for administrator access
if ($admin_link!='') {
	$add_mm_files=get_multimedia('',true);
	foreach($add_mm_files as $newfile) {array_push($file_names,$newfile);}
}

// Page title
if ($title=='') {
	$title=str_replace(chr(92),chr(47),getcwd());
	$title=str_replace('_',' ',$title);
	$title=substr($title,strrpos($title,chr(47))+1);
	if (preg_match("/([0-9]{3})/",substr($title,0,3))) {
		if (substr($title,3,1)==' ' || substr($title,3,1)=='_')
			$title=trim(substr($title,3));
	}
}

// Change display configuration for shop system, order stage 1,2 and 3
if ($shop && isset($_REQUEST['orderphotos'])) {
	$order=0;
	if ($_REQUEST['orderphotos']==1) {
		$images_per_page=9999;
		if (isset($_REQUEST['page'])) {unset($_REQUEST['page']);}
		$columns_per_page=$shop_columns;
		$thumbnail_txtfile=false;
		$thumbnail_countcomments=false;
		$popup=true;
		$order=1;
		if (isset($_REQUEST['old_searchkeyword'])) {
			// Filter results
			$searchresults=array();
			foreach($file_names as $file) {
				if (strpos(strtolower($file),strtolower($_REQUEST['old_searchkeyword']))===false) {} else {array_push($searchresults,$file);}
			}
			$file_names=$searchresults;
			}
	}
	if ($_REQUEST['orderphotos']==2) {$order=2;}
	if ($_REQUEST['orderphotos']==3) {$order=3;}
} else {
	$order=0;
}

// Change display configuration for search results
if ($visitor_search && isset($_REQUEST['searchkeyword'])) {
	if (strlen($_REQUEST['searchkeyword'])>0) {
		$images_per_page=9999;
		if (isset($_REQUEST['page'])) {unset($_REQUEST['page']);}
		$columns_per_page=$visitor_search_columns;
		$thumbnail_txtfile=false;
		$thumbnail_countcomments=false;
		$popup=true;
		// Filter results
		if (is_dir('textfiles')) {$txtdir='textfiles/';} else {$txtdir='';}
		$searchresults=array();
		foreach($file_names as $file) {
			if (strpos(strtolower($file),strtolower($_REQUEST['searchkeyword']))===false) {} else {array_push($searchresults,$file);}
			$txtfilename=substr($file,0,strrpos($file,'.')).'.txt';
			if (file_exists($txtdir.$txtfilename)) {
				if ($fp=@fopen($txtdir.$txtfilename,'r')) {
					$comment=fread($fp,filesize($txtdir.$txtfilename));
					if (strpos(strtolower($comment),strtolower($_REQUEST['searchkeyword']))===false) {} else {array_push($searchresults,$file);}
					fclose($fp);
				}
			}
		}
		$file_names=$searchresults;
	}
}

// Evaluate which thumbnails to show on current page
if ($explicit_content && !$explicit_ok) {
 	$file_names=null;
 	if (isset($_REQUEST['showimage'])) {unset($_REQUEST['showimage']);}
}
$max_files=count($file_names);
if (isset($_REQUEST['page'])) {$page=abs((int) $_REQUEST['page']);} else {$page=0;}
if ($images_per_page==0) {$images_per_page=1;}
$albumpage=ceil($page/$images_per_page)+1;
$show_files=$page+$images_per_page;
if ($show_files>$max_files) {$show_files=$max_files;}
if ($page==$show_files) {$page-=$images_per_page;}
if ($max_files==0) {$page=0;}

// Create HTML page
echo "<html><head><title>$title</title>\n";
echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=$charset\"><meta http-equiv=\"content-style-type\" content=\"text/css\"><meta http-equiv=\"content-script-type\" content=\"text/javascript\">\n";
echo "<meta name=\"description\" content=\"$meta_description\"><meta name=\"keywords\" content=\"$meta_keywords\"><meta name=\"copyright\" content=\"$meta_copyright_and_author\"><meta name=\"author\" content=\"$meta_copyright_and_author\">\n";
if ($piclens) {
	echo "<link rel=\"alternate\" href=\"photos.rss\" type=\"application/rss+xml\" title=\"\" id=\"gallery\">";
	echo "<script type=\"text/javascript\" src=\"http://lite.piclens.com/current/piclens.js\"></script>";
}
echo "</head><body marginwidth=\"0\" marginheight=\"0\" topmargin=\"0\" leftmargin=\"0\" bgcolor=\"" . trim($page_color,'#') . "\">\n";

// Insert CSS Styles
html_css();

// Insert Lightbox Style & Javascripts
if ($lightbox) {echo "<link rel=\"stylesheet\" href=\"$lightbox_href/css/lightbox.css\" type=\"text/css\" media=\"screen\" /><script src=\"$lightbox_href/js/prototype.js\" type=\"text/javascript\"></script><script src=\"$lightbox_href/js/scriptaculous.js?load=effects,builder\" type=\"text/javascript\"></script><script src=\"$lightbox_href/js/lightbox.js\" type=\"text/javascript\"></script>";}

// Javascript
echo "<div id=\"content\"><form name=\"browser\" method=\"POST\" action=\"index.php?$admin_link\" enctype=\"multipart/form-data\"><input type=\"hidden\" name=\"page\" value=\"$page\"><input type=\"hidden\" name=\"imagefilename\">\n";
echo "<script language=\"JavaScript\">\n";
echo "<!-- EasyPhpAlbum 1.4.4 @ www.mywebmymail.com //-->\n";
//if ($piclens) {echo "PicLensLite.start();\n";}
if ($slideshow_delay<1000) {$slideshow_delay=1000;}
$fadeinorout='';
$fader='';
if (($thumbnail_opacity || $imagefader) && !$popup) {
	if ($show_previous_next && $imagefader && $thumbnail_opacity) {
		$fadeinorout="onLoad=\"thumbfade();\" style=\"filter: alpha(opacity=0); KHTMLOpacity: 0; -moz-opacity: 0; opacity: 0\" onMouseover=\"fadeinout(this,1)\" onMouseout=\"fadeinout(this,0)\"";
		if (!$thumbnail_opacity) {$opacity_level=100;}
		echo "function thumbfade() {\n";
		echo "	setTimeout(\"setopacity(document.images['next_thumbnail'],$opacity_level);\",3500);\n";
		echo "	setTimeout(\"setopacity(document.images['previous_thumbnail'],$opacity_level);\",3500);\n";
		echo "}\n";
	} else if ($show_previous_next && $thumbnail_opacity) {
		$fadeinorout="onLoad=\"fadeinout(this,0);\" onMouseover=\"fadeinout(this,1)\" onMouseout=\"fadeinout(this,0)\"";
	}
	echo "function fadeinout(object,inorout) {\n";
	echo "	var opacity=(inorout > 0 ? 100 : $opacity_level);\n";
	echo "	if (opacity==100) opacity=99.999;\n";
	echo "	setopacity(object,opacity);\n";
	echo "}\n";
	echo "function setopacity(object,opacity) {\n";
	echo "	if (opacity==100) opacity=99.999;\n";
	echo "	object.style.filter=\"alpha(opacity:\"+opacity+\")\";\n";
	echo "	object.style.KHTMLOpacity=(opacity/100);\n";
	echo "	object.style.MozOpacity=(opacity/100);\n";
	echo "	object.style.opacity=(opacity/100);\n";
	echo "}\n";
	if ($imagefader) {
		echo "function fader() {\n";
		echo "	for(i=0;i<=100;i++)\n";
		echo "		setTimeout(\"setopacity(document.images['mainimage'],\" + i + \");\",i*20);\n";
		if ($slideshow && isset($_REQUEST['slideshow'])) {
			$show_previous_next=false;
			echo "	starttimer();\n";
			echo "	for(i=100;i>=0;i--)\n";
			echo "		setTimeout(\"setopacity(document.images['mainimage'],\" + i + \");\",$slideshow_delay+2000+((100-i)*20));\n";
		}
		echo "}\n";
	}
	if ($thumbnail_opacity && !isset($_REQUEST['showimage'])) {$fadeinorout="onLoad=\"fadeinout(this,0);\" onMouseover=\"fadeinout(this,1)\" onMouseout=\"fadeinout(this,0)\"";}
	if ($imagefader) {$fader="name=\"mainimage\" onLoad=\"fader();\" style=\"filter: alpha(opacity=0); KHTMLOpacity: 0; -moz-opacity: 0; opacity: 0\"";}
}
if ($popup) {echo "var popup=null;\n";}
echo "function showpage(page) {\n"; 
echo "	document.browser.page.value=page;\n";
if ($popup) {echo "if (popup && popup.open) popup.close();\n";}
echo "	document.browser.submit();\n";
echo "}\n";
echo "function viewer(image,name,width,height) {\n";
if ($popup) {
	// Change image width for auto-adjust
	if ($image_resize) {
		if ($image_resizeto==0) {echo "var newsize=Math.floor(screen.width/1.6);\n";} else {echo "var newsize=$image_resizeto;\n";}
		if (!$image_inflate) {
			echo "if (newsize>width && newsize>height)\n";
			echo "	newsize=Math.max(width,height);\n";
		}
		echo "if (width>height) {\n";
			echo "	var popup_width=newsize;\n";
			echo "	var popup_height=(height/(width/popup_width));\n";
		echo "} else {\n";
			echo "	var popup_width=(width/(height/newsize));\n";
			echo "	var popup_height=newsize;\n";
		echo "}\n";
		echo "width=Math.floor(popup_width);\n";
		echo "height=Math.floor(popup_height);\n";
	}
	// Center pop-up window on page
	echo "if (popup && popup.open) popup.close();\n";
	echo "var poswx=(screen.width > width ? (screen.width - width)/2 : 0);\n";
	echo "var poswy=(screen.height > height ? (screen.height - height)/3 : 0);\n";
	echo "if (poswx==0 && poswy==0) {\n";
	echo "	popup=window.open(\"\",\"popup\",\"width=\" + (screen.width-10) + \",height=\" + (screen.height-55) + \",status=no,hotkeys=no,menubar=no,toolbar=no,resizable=no,scrollbars=yes,top=\" + poswy + \",left=\" + poswx + \",dependent=yes,alwaysRaised=yes\");\n";
	echo "} else if (poswx==0) {\n";
	echo "	popup=window.open(\"\",\"popup\",\"width=\" + (screen.width-10) + \",height=\" + (height+1) + \",status=no,hotkeys=no,menubar=no,toolbar=no,resizable=no,scrollbars=yes,top=\" + poswy + \",left=\" + poswx + \",dependent=yes,alwaysRaised=yes\");\n";
	echo "} else if (poswy==0) {\n";
	echo "	popup=window.open(\"\",\"popup\",\"width=\" + (width+1) + \",height=\" + (screen.height-55) + \",status=no,hotkeys=no,menubar=no,toolbar=no,resizable=no,scrollbars=yes,top=\" + poswy + \",left=\" + poswx + \",dependent=yes,alwaysRaised=yes\");\n";
	echo "} else {\n";
	echo "	popup=window.open(\"\",\"popup\",\"width=\" + (width+1) + \",height=\" + (height+1) + \",status=no,hotkeys=no,menubar=no,toolbar=no,resizable=no,scrollbars=no,top=\" + poswy + \",left=\" + poswx + \",dependent=yes,alwaysRaised=yes\");\n";
	echo "}\n";
	// Write html to popup window
	if ($popup_browse) {
		if (!$slideshow) {$html_code='javascript:nextimage(3)';} else {$html_code='javascript:window.close()';}
		echo "name='" . preg_replace("/([\\x00-\\x20\\x7f-\\xff" . preg_quote('\/:*?"<>|', '/') . "])/e","",$title) . "';\n";
		if (!$slideshow) {$html_alt=$language_viewnext;} else {$html_alt=$language_stop_slideshow;}
	} else {
		$html_code='javascript:window.close()';
		$html_alt='X';
	}
	if ($imagefader) {$popup_style="style='filter: alpha(opacity=0); KHTMLOpacity: 0; -moz-opacity: 0; opacity: 0'";} else {$popup_style='';}
	if ($popup_force_focus)
		echo "popup.document.write(\"<html><head><title>\" + name + \"</title><meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'><body marginwidth='0' bgcolor='" . trim($page_color,'#') . "' marginheight='0' leftmargin='0' onBlur='window.focus()'>\");\n";
	else
		echo "popup.document.write(\"<html><head><title>\" + name + \"</title><meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'><body marginwidth='0' bgcolor='" . trim($page_color,'#') . "' marginheight='0' leftmargin='0'>\");\n";
//	if ($image_resize)
//		echo "popup.document.write(\"<center><table width='100%' height='100%' border='0' cellspacing='0' cellpadding='0'><tr valign='middle' align='center'><td><a href='$html_code'><img src='index.php?resize=1&image=\" + escape(image) + \"&screenwidth=\" + screen.width + \"' width='\" + width + \"' height='\" + height + \"' border='0' $popup_style name='mainimage' alt='$html_alt' onLoad='calibrate();'></a></td></tr></table></center>\");\n";
//	else
//		echo "popup.document.write(\"<center><table width='100%' height='100%' border='0' cellspacing='0' cellpadding='0'><tr valign='middle' align='center'><td><a href='$html_code'><img src='\" + escape(image) + \"' width='\" + width + \"' height='\" + height + \"' border='0' $popup_style name='mainimage' alt='$html_alt' onLoad='calibrate();'></a></td></tr></table></center>\");\n";

	if ($image_resize)
		echo "popup.document.write(\"<center><div style=\'display : table;position: absolute; top: 0px; left: 0px;\'><a href='$html_code'><img src='index.php?resize=1&image=\" + escape(image) + \"&screenwidth=\" + screen.width + \"' width='\" + width + \"' height='\" + height + \"' border='0' $popup_style name='mainimage' alt='$html_alt' onLoad='calibrate();'></a></div></center>\");\n";
	else
		echo "popup.document.write(\"<center><div style=\'display : table;position: absolute; top: 0px; left: 0px;\'><a href='$html_code'><img src='\" + escape(image) + \"' width='\" + width + \"' height='\" + height + \"' border='0' $popup_style name='mainimage' alt='$html_alt' onLoad='calibrate();'></a></div></center>\");\n";


	echo "popup.document.write(\"<script language='JavaScript'>\");\n";
	echo "popup.document.write(\"window.onerror = function() {return true;};\");\n";
	if ($imagefader) {
		echo "popup.document.write(\"function setopacity(object,opacity) {\");\n";
		echo "popup.document.write(\"	if (opacity==100) opacity=99.999;\");\n";
		echo "popup.document.write(\"	object.style.filter='alpha(opacity:' + opacity + ')';\");\n";
		echo "popup.document.write(\"	object.style.KHTMLOpacity=(opacity/100);\");\n";
		echo "popup.document.write(\"	object.style.MozOpacity=(opacity/100);\");\n";
		echo "popup.document.write(\"	object.style.opacity=(opacity/100);\");\n";
		echo "popup.document.write(\"}\");\n";
		echo "popup.document.write(\"function fader() {\");\n";
		echo "popup.document.write(\"	for(i=0;i<=100;i++)\");\n";
		echo "popup.document.write(\"		setTimeout('setopacity(document.images[0],' + i + ');',i*20);\");\n";
		$slideshow_delay+=2500;
		if ($slideshow && $popup_browse) {
			echo "popup.document.write(\"	for(i=100;i>=0;i--)\");\n";
			echo "popup.document.write(\"		setTimeout('setopacity(document.images[0],' + i + ');',$slideshow_delay+((100-i)*20));\");\n";
			$slideshow_delay+=2500;
			echo "popup.document.write(\"		setTimeout('nextimage(3);',$slideshow_delay);\");\n";
		}
		echo "popup.document.write(\"}\");\n";
	}
	if ($popup_browse) {
		echo "popup.document.write(\"images=new Array(\");\n";
		$allimages=array();
		$allimages=get_images(getcwd(),false,false,false);
		$alltotal=count($allimages);
		for ($count=0;$count<$alltotal;$count++) {
			$image_info=@GetImageSize('./' . $allimages[$count]);
			$dimensions=getdimensions($image_info);
			if ($count<$alltotal-1) {
				if ($image_resize && !($animated_thumbnails && $image_info[2]==1))
					echo "popup.document.write(\"'index.php?resize=1&image=\" + escape('$allimages[$count]') + \"&screenwidth=\" + screen.width + \"',$dimensions[0],$dimensions[1],\");\n";
				else
					echo "popup.document.write(\"'\" + escape('$allimages[$count]') + \"',$dimensions[0],$dimensions[1],\");\n";
			} else {
				if ($image_resize && !($animated_thumbnails && $image_info[2]==1))
					echo "popup.document.write(\"'index.php?resize=1&image=\" + escape('$allimages[$count]') + \"&screenwidth=\" + screen.width + \"',$dimensions[0],$dimensions[1]\");\n";
				else
					echo "popup.document.write(\"'\" + escape('$allimages[$count]') + \"',$dimensions[0],$dimensions[1]\");\n";
			}
		}			
		echo "popup.document.write(\");\");\n";
		echo "popup.document.write(\"var imageindex=0;\");\n";
		echo "popup.document.write(\"var selectedimage='\" + escape(image) + \"';\");\n";
		echo "popup.document.write(\"for (var found=0;found<images.length-1;found+=3) {\");\n";
		echo "popup.document.write(\"	if (images[found].indexOf(selectedimage)>-1)\");\n";
		echo "popup.document.write(\"		imageindex=found;\");\n";
		echo "popup.document.write(\"}\");\n";
		echo "popup.document.write(\"empty=new Image();\");\n";
		echo "popup.document.write(\"function nextimage(direction) {\");\n";
		echo "popup.document.write(\"	imageindex=imageindex+direction;\");\n";
		echo "popup.document.write(\"	if (imageindex>images.length-1)\");\n";
		echo "popup.document.write(\"		imageindex=0;\");\n";
		echo "popup.document.write(\"	if (imageindex<0)\");\n";
		echo "popup.document.write(\"		imageindex=images.length-3;\");\n";
		echo "popup.document.write(\"	document.images[0].src=empty;\");\n";
		echo "popup.document.write(\"	document.images[0].width=1;\");\n";
		echo "popup.document.write(\"	document.images[0].height=1;\");\n";
		if ($imagefader) {echo "popup.document.write(\"	setopacity(document.images[0],0);\");\n";}
		echo "popup.document.write(\"	document.images[0].src=images[imageindex];\");\n";
		if ($slideshow && !$imagefader) {echo "popup.document.write(\"	window.setTimeout('nextimage(3);',$slideshow_delay);\");\n";}
		echo "popup.document.write(\"}\");\n";
		if ($slideshow && !$imagefader) {echo "popup.document.write(\"	window.setTimeout('nextimage(3);',$slideshow_delay);\");\n";}
		if ($enable_keyboard_arrows && !$slideshow) {
			echo "popup.document.write(\"function reload(e) {\");\n";
			echo "popup.document.write(\"	if(e) {\");\n";
			echo "popup.document.write(\"		if(e.type=='keydown' && e.which==37) {nextimage(-3);}\");\n";
			echo "popup.document.write(\"		if(e.type=='keydown' && e.which==39) {nextimage(3);}\");\n";
			echo "popup.document.write(\"	}\");\n";
			echo "popup.document.write(\"	if(window.event) {\");\n";
			echo "popup.document.write(\"		if(event.type=='keydown'&& event.keyCode==37) {nextimage(-3);}\");\n";
			echo "popup.document.write(\"		if(event.type=='keydown'&& event.keyCode==39) {nextimage(3);}\");\n";
			echo "popup.document.write(\"	}\");\n";
			echo "popup.document.write(\"}\");\n";
			echo "popup.document.write(\"document.onkeydown=reload;\");\n";
		}
	}
	echo "popup.document.write(\"function calibrate() {\");\n";
	echo "popup.document.write(\"	var widthx=0;\");\n";
	echo "popup.document.write(\"	var heighty=0;\");\n";
	if ($popup_browse) {
		if ($image_resize) {
			if ($image_resizeto==0) {echo "popup.document.write(\"	var newsize=Math.floor(screen.width/1.6);\");\n";} else {echo "popup.document.write(\"	var newsize=$image_resizeto;\");\n";}
			if (!$image_inflate) {
				echo "popup.document.write(\"	if (newsize>images[imageindex+1] && newsize>images[imageindex+2])\");\n";
				echo "popup.document.write(\"		newsize=Math.max(images[imageindex+1],images[imageindex+2]);\");\n";
			}
			echo "popup.document.write(\"	if (images[imageindex+1]>images[imageindex+2]) {\");\n";
			echo "popup.document.write(\"		var popup_width=newsize;\");\n";
			echo "popup.document.write(\"		var popup_height=(images[imageindex+2]/(images[imageindex+1]/popup_width));\");\n";
			echo "popup.document.write(\"	} else {\");\n";
			echo "popup.document.write(\"		var popup_width=(images[imageindex+1]/(images[imageindex+2]/newsize));\");\n";
			echo "popup.document.write(\"		var popup_height=newsize;\");\n";
			echo "popup.document.write(\"	}\");\n";
			echo "popup.document.write(\"	images[imageindex+1]=popup_width;\");\n";
			echo "popup.document.write(\"	images[imageindex+2]=popup_height;\");\n";
		}
		echo "popup.document.write(\"	document.images[0].width=images[imageindex+1];\");\n";
		echo "popup.document.write(\"	document.images[0].height=images[imageindex+2];\");\n";
	}
	echo "popup.document.write(\"	window.resizeTo(document.images[0].width,document.images[0].height);\");\n";
	echo "popup.document.write(\"	scroll(3000,3000);\");\n";
	echo "popup.document.write(\"	if (window.pageYOffset){\");\n";
	echo "popup.document.write(\"		widthx=window.pageXOffset;\");\n";
	echo "popup.document.write(\"		heighty=window.pageYOffset;\");\n";
	echo "popup.document.write(\"	} else {\");\n";
	echo "popup.document.write(\"		widthx=document.body.scrollLeft;\");\n";
	echo "popup.document.write(\"		heighty=document.body.scrollTop;\");\n";
	echo "popup.document.write(\"	}\");\n";
        echo "popup.document.write(\"	scroll(0,0);\");\n";
	echo "popup.document.write(\"	if (widthx!=0 || heighty!=0){\");\n";
	echo "popup.document.write(\"		window.resizeBy(widthx,heighty);\");\n";
	echo "popup.document.write(\"		window.moveTo((screen.width-document.images[0].width)/2,(screen.height-document.images[0].height)/3);\");\n";
	echo "popup.document.write(\"	}\");\n";
	if ($imagefader) {echo "popup.document.write(\"	fader();\");\n";}
	echo "popup.document.write(\"}\");\n";
	if ($imagefader) {echo "popup.document.write(\"if (!(document.getElementById && !document.all)) {fader();}\");\n";}
	echo "popup.document.write(\"</\");\n";
	echo "popup.document.write(\"script>\");\n";
	echo "popup.document.write(\"</body></html>\");\n";
	echo "popup.document.close();\n";
	echo "popup.focus();\n";
	// Update statistics
	if ($hit_counter) {echo "updatestats(image,'');\n";}
} else {
	// Display photo on page
	if ($slideshow && isset($_REQUEST['slideshow']))
		echo "	document.location.href='index.php?slideshow=1&showimage=' + escape(image) + '&screenwidth=' + screen.width;\n";
	else
		echo "	document.location.href='index.php?showimage=' + escape(image) + '&screenwidth=' + screen.width;\n";
}
echo "}\n";
if (isset($_REQUEST['slideshow'])) {
	if (isset($_REQUEST['showimage'])) {
		if (in_array($_REQUEST['showimage'],$file_names)) {
			$forward=array_search($_REQUEST['showimage'],$file_names)+1;
			$count=count($file_names);
			$mm_file=get_multimedia($file_names[$forward],false);
			while ($mm_file!='' && $forward<$count) {
			 	$forward++;
				$mm_file=get_multimedia($file_names[$forward],false);
			}
			if ($forward==$count) {$next_slide=$file_names[0];} else {$next_slide=$file_names[$forward];}
			if ($imagefader) {$slideshow_delay+=4000;}
			echo "function starttimer() {\n";
			echo "	id=window.setTimeout(\"viewer('$next_slide','',0,0)\",$slideshow_delay);\n";
			echo "}\n";
			// Insert code for keyboard navigation
			if ($enable_keyboard_arrows) {
				echo "function reload(e) {\n";
				echo "	if(e) {\n";
				echo "		if(e.type=='keydown' && e.which==39) {viewer('$next_slide','',0,0);}\n";
				echo "	}\n";
				echo "	if(window.event) {\n";
				echo "		if(event.type=='keydown' && event.keyCode==39) {viewer('$next_slide','',0,0);}\n";
				echo "	}\n";
				echo "}\n";
				echo "document.onkeydown=reload;\n";
			}			
		}
	}
}
// Update statistics
if ($hit_counter) {
	echo "function updatestats(image,newpage) {\n"; 
	echo "	counter = new Image;\n";
	echo "	counter.src = \"index.php?statistics=1&image=\" + escape(image);\n";
	echo "	if(newpage!='') \n";
	echo "		id=window.setTimeout(\"document.location.href='\" + escape(newpage) + \"';\",500);\n";
	echo "}\n";
}
if ($admin_access && $admin_link=='' && $enable_admin_keyboardshortcut && !isset($_REQUEST['showimage']) && $order==0) {
	echo "function reload(e) {\n";
	echo "	if(e) \n";
	echo "		if(e.type=='keydown' && e.which==9) {document.location.href=\"index.php?admin=1\";}\n";
	echo "	if(window.event) \n";
	echo "		if(event.type=='keydown' && event.keyCode==9) {document.location.href=\"index.php?admin=1\";}\n";
	echo "}\n";
	echo "document.onkeydown=reload;\n";
}
if ($admin_link!='') {
	echo "function deletefile(name,page,backup) {\n";
	echo "	message='Are you sure you want to delete: ';\n";
	echo "	if (backup) message='Are you sure you want to delete from your backup: ';\n";
	echo "	if (confirm(message + name + \" ?\")) {\n";
	echo "	if (backup) document.browser.backup.value=1;\n";
	echo "	document.browser.imagefilename.value=name;\n";
	echo "	document.browser.page.value=page;\n";
	echo "	document.browser.submit(); }\n";
	echo "}\n";
	echo "function restorefile(name,page) {\n";
	echo "	if (confirm(\"Are you sure you want to restore \" + name + \" from your backup?\")) {\n";
	echo "	document.browser.restorefilename.value=name;\n";
	echo "	document.browser.page.value=page;\n";
	echo "	document.browser.submit(); }\n";
	echo "}\n";
	echo "function txtfile(name,page) {\n"; 
	echo "	document.browser.newtxtfile.value=name;\n";
	echo "	document.browser.page.value=page;\n";
	echo "	document.browser.submit();\n";
	echo "}\n";
	echo "function editfile(name,page) {\n"; 
	echo "	document.browser.edittxtfile.value=name;\n";
	echo "	document.browser.page.value=page;\n";
	echo "	document.browser.submit();\n";
	echo "}\n";
	echo "function renamefile(oldname,name,page) {\n"; 
	echo "	var answer=prompt('Please enter a new name:',name);\n";
	echo "	if (answer!=null && answer!='') {\n";
	echo "	document.browser.renameimageold.value=oldname;\n";
	echo "	document.browser.renameimagenew.value=answer;\n";
	echo "	document.browser.page.value=page;\n";
	echo "	document.browser.submit(); }\n";
	echo "}\n";
}
if ($explicit_content && !$explicit_ok) {
	echo "function agecheck() {\n"; 
	echo "	document.browser.over18.value=18;\n";
	echo "	document.browser.submit();\n";
	echo "}\n";	
}
echo "</script>\n";

if ($header!='' && $admin_link=='') {
	$extension=strtolower(substr($header,strrpos($header,'.')+1,strlen($header)));
	if ($extension=='jpg' || $extension=='jpeg' || $extension=='png' || $extension=='gif') {
		echo "<table width=\"100%\" border=\"0\">\n";
		echo "<tr><td><img src=\"$header\" border=\"0\"></td></tr>\n";
		echo "</table>\n";
	}
} else {
	// Add your php header here: include("http://www.yourweb