<?php
//zOOm Gallery//
/** 
-----------------------------------------------------------------------
|  zOOm Image Gallery! by Mike de Boer - a multi-gallery component    |
-----------------------------------------------------------------------

-----------------------------------------------------------------------
|                                                                     |
| Date: January, 2004                                                 |
| Author: Mike de Boer, <http://www.mikedeboer.nl>                    |
| Copyright: copyright (C) 2004 by Mike de Boer                       |
| Description: zOOm Image Gallery, a multi-gallery component for      |
|              Mambo based on RSGallery by Ronald Smit. It's the most |
|              feature-rich gallery component for Mambo!              |
| Filename: upl_scan.php                                              |
| Version: 2.0                                                        |
|                                                                     |
-----------------------------------------------------------------------
**/
// MOS Intruder Alerts
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
if(array_key_exists('uls', $_REQUEST))
	$urls = $_REQUEST['urls'];
if ($urls){
	$setFilename = $_REQUEST['setFilename'];
	$imgname = $_REQUEST['imgname'];
	$keywords = $_REQUEST['keywords'];
	$descr = $_REQUEST['descr'];
	$zoom->createCheckAllScript();
	if (!$catid){
		?>
		<script language="javascript" type="text/javascript">
			<!--
			alert("<?php echo html_entity_decode(_ZOOM_NOCAT);?>");
			location = 'index.php?option=com_zoom&Itemid=<?php echo $Itemid;?>&page=upload&formtype=scan';
			//-->
		</SCRIPT>
		<?php
		break;
	}
	/* Process all urls first */
	$temp_files = array();
	$userfile = array();
	$userfile_name = array();
	foreach ($urls as $url) {
		// Get rid of any extra white space
		$url = trim($url);
		/*
 		* Check to see if the URL is a local directory (inspired by
 		* code from Jared (hogalot)
        * First, append the Mambo-path if it isn't there already.
 		*/
        if(stristr($url, $mosConfig_absolute_path) !== true && !fs_is_dir($url)){
            if(substr($url,0,strlen($url)) == "/")
                $theUrl = $mosConfig_absolute_path.$url;
            else
                $theUrl = $mosConfig_absolute_path."/".$url;
        }else{
            $theUrl = $url;
        }
		if (fs_is_dir($theUrl)) {
			echo "<p>"._ZOOM_SCAN_STEP2_DESCR1." <i>$url</i> "._ZOOM_SCAN_STEP2_DESCR2."</p>";
			$handle = fs_opendir($theUrl);
			while (($file = readdir($handle)) != false) {
				if ($file != "." && $file != "..") {
					$tag = ereg_replace(".*\.([^\.]*)$", "\\1", $file);
					$tag = strtolower($tag);
					if ($zoom->acceptableFormat($tag)) {
						/* Tack it onto userfile */
						$userfile_name[] = $file;
						if (substr($url,-1) == "/") {
							$userfile[] = fs_export_filename($url . $file);
						} else {
							$userfile[] = fs_export_filename($url . "/" . $file);
						}
					}
				}
			}
			closedir($handle);
		}else{
			// Get rid of any preceding whitespace (fix for odd browsers like konqueror)
			$url = eregi_replace("^[[:space:]]+", "", $url);
			// If the URI doesn't start with a scheme, prepend 'http://'
			if (!fs_is_file($url)) {
				if (!ereg("^(http|ftp)", $url)) {
					$url = "http://$url";
				}
			}
			/* Parse URL for name and file type */
			$url_stuff = parse_url($url);
			$name = basename($url_stuff["path"]);
			$tag = ereg_replace(".*\.([^\.]*)$", "\\1", $url);
			$tag = strtolower($tag);
			//Dont output warning messages if we cant open url
			/*
 			* Try to open the url in lots of creative ways.
 			* Do NOT use fs_fopen here because that will pre-process
 			* the URL in win32 style (ie, convert / to \, etc).
	 		*/
			$id = @fopen($url, "rb");
			if (!ereg("http", $url)) {
				if (!$id) $id = @fopen("http://$url", "rb");
				if (!$id) $id = @fopen("http://$url/", "rb");
			}
			if (!$id) $id = @fopen("$url/", "rb");
			if ($id) {
				echo '<p>' . _ZOOM_A_MESS_PROCESSING_FILE . ' ' . urldecode($url) . '</p>';
			} else {
				echo '<p>' . _ZOOM_A_MESS_NOTOPEN_URL. ' "'. $url . '"</p>';
				continue;
			}
			// copy file locally
			$file = $mosConfig_absolute_path . "/media/photo.$name";
			$od = fs_fopen($file, "wb");
			if ($id && $od) {
				while (!feof($id)) {
					fwrite($od, fread($id, 65536));
				}
				fclose($id);
				fclose($od);
			}
			// Make sure we delete this file when we're through...
			$temp_files[$file]++;
			// If this is an image - add it to the processor array
			if ($zoom->acceptableFormat($tag)) {
				// Tack it onto userfile
				$userfile_name[] = $name;
				$userfile[] = $file;
			} else {
				// Slurp the file
				echo '<p>' . sprintf( _ZOOM_A_MESS_PARSE_URL, $url ) . '</p>';
				$fd = fs_fopen ($file, "r");
				$contents = fread ($fd, fs_filesize ($file));
				fclose ($fd);
				// We'll need to add some stuff to relative links
				$base_url = $url_stuff["scheme"] . '://' . $url_stuff["host"];
				$base_dir = '';
				if ($url_stuff["port"]) {
	  			$base_url .= ':' . $url_stuff["port"];
				}
				// Hack to account for broken dirname
				if (ereg("/$", $url_stuff["path"])) {
					$base_dir = $url_stuff["path"];
				} else {
					$base_dir = dirname($url_stuff["path"]);
				}
				// Make sure base_dir ends in a / ( accounts for empty base_dir )
				if (!ereg("/$", $base_dir)) {
					$base_dir .= '/';
				}
				$things = array();
				while ($cnt = eregi('(src|href)="?([^" >]+\.$zoom->acceptableFormatRegexp())[" >]',
						    $contents, 
						    $results)) {
					$things[$results[2]]++;
					$contents = str_replace($results[2], "", $contents);
					$userfile_name[] = $results[2];
				}
				// Add each unique link to an array we scan later
				foreach (array_keys($things) as $thing) {
					/* 
				 	* Some sites (slashdot) have images that start with // and this
		 			* confuses Gallery.  Prepend 'http:'
			 		*/
					if (!strcmp(substr($thing, 0, 2), "//")) {
						$thing = "http:$thing";
					}
					// Absolute Link ( http://www.foo.com/bar )
					if (substr($thing, 0, 4) == 'http') {
						$userfile[] = $thing;
					// Relative link to the host ( /foo.bar )
					} elseif (substr($thing, 0, 1) == '/') {
						$userfile[] = $base_url . $thing;
					// Relative link to the dir ( foo.bar )
					} else {
						$userfile[] = $base_url . $base_dir . $thing;
					}
				}
			}// END if is-image?
		}// END if is_dir?
		if(sizeof($userfile) > 0){
			?>
			<h2><?php echo _ZOOM_SCAN_STEP2;?></h2>
			<form name="select_img" method="post"action="index<?php echo ($zoom->_isBackend) ? "2" : "";?>.php?option=com_zoom&Itemid=<?php echo $Itemid;?>&page=upload&formtype=scan">
			<?php
			$zoom->createFileList($userfile);
			?>
			<br /><input class="button" type="submit" value="<?echo _ZOOM_UPLOAD;?>" name="submit_scan" />
			<br />
			<input type="hidden" name="catid" value="<?php echo $catid;?>" />
			<?php
			$zoom->_counter = 0;
			foreach($userfile as $file){
				$name = $userfile_name[$zoom->_counter];
				?>
				<input type="hidden" name="userfile[]" value="<?php echo $file;?>" />
				<input type="hidden" name="userfile_name[]" value="<?php echo $name;?>" />
				<?php
				$zoom->_counter++;
			}
			if(isset($setFilename))
				echo '<input type="hidden" name="setFilename" value="'.$imgname.'" />';
			else
				echo '<input type="hidden" name="imgname" value="'.$imgname.'" />';
			?>
			</form>
			<?php
		}else{
			echo '<p><center><span class="small">'. _ZOOM_NOIMG . '</span></center></p>';
		}// END if userfiles found?
        echo '<p><strong>' . count($userfile) . ' ' . _ZOOM_ALERT_IMGFOUND . '</strong></p>';
	}// END foreach urls...
}elseif($scannedimg){
	// Now, finally, it's time to start uploading...
	echo '<h2>'._ZOOM_SCAN_STEP3.'</h2>';
	$i = 0;
	foreach($scannedimg as $image){
		$filename = urldecode($userfile_name[$image]);
		// Get the actual image (with path and everything)...
		if(!fs_is_file($userfile[$image]))
			$theImage = $mosConfig_absolute_path."/".$userfile[$image];
		else
			$theImage = $userfile[$image];
        if (!empty($usercaption) && is_array($usercaption))
    		$caption = $zoom->removeTags(array_shift($usercaption));
        if(!$descr)
            $descr = $zoom->_CONFIG['tempDescr'];
        if (isset($setFilename))
            $name = $filename;
        else
            $name = $imgname;
        if($rotate[$image]){
            $key = "rotate$i";
            $degrees = $_REQUEST[$key];
            $rotatelt = $rotate[$image];
        }
        if($zoom->_toolbox->processImage($theImage, $filename, $keywords, $name, $descr, $rotatelt, $degrees, 2))
            $i++;
	} // end of foreach-loop
	if($zoom->_toolbox->_err_num > 0)
		$zoom->_toolbox->displayErrors($err_num, $err_names, $err_types);
	echo '<p><center><h4>' . $i . ' ' . _ZOOM_ALERT_UPLOADSOK . '</h4></center></p>';
}else{
	// Display form...
	$zoom->createFormControlScript("scan_form");
	?>
	<form name="scan_form" method="POST" action="index<?php echo ($zoom->_isBackend) ? "2" : "";?>.php?option=com_zoom&Itemid=<?php echo $Itemid;?>&page=upload&formtype=scan">
	<table border="0" cellpadding="0" cellspacing="0">
	<?php
	// if php safe_mode restriction is in use, warn the user! -> added by mic
	if( ini_get( 'safe_mode' ) == 1 ){ ?>
		<tr><td colspan="3">&nbsp;</td></tr>
		<tr>
			<td>&nbsp;</td>
			<td colspan="2"><strong><font color="red"><?php echo _ZOOM_A_MESS_SAFEMODE1; ?></font></strong></td>
		</tr>
		<?php
	} ?>
	<tr><td colspan="3">&nbsp;</td></tr>
	<tr>
		<td colspan="3"><h3><?php echo _ZOOM_SCAN_STEP1;?></h3></td>
	</tr>	
	<tr><td colspan="3">&nbsp;</td></tr>	
	<tr>
		<td><?php echo _ZOOM_FORM_INGALLERY; ?>:&nbsp;</td>
		<td colspan="2">
			<?php echo $zoom->createCatDropdown('catid', '<OPTION value="">---&nbsp;'._ZOOM_PICK.'&nbsp;---</OPTION>');?>
		</td>
	</tr>	
	<tr><td colspan="3">&nbsp;</td></tr>			
	<tr>
		<td><?php echo _ZOOM_FORM_LOCATION;?>:&nbsp;</td>
		<td>
			<input type="text" name="urls[]" size=40 class="inputbox" />
		</td>
		<td>&nbsp;<?php echo _ZOOM_SCAN_STEP1_DESCR;?></td>
	</tr>
	<tr><td colspan="3">&nbsp;</td></tr>
	<tr>
		<td><?php echo _ZOOM_NAME;?>:&nbsp;</td>
		<td>
			<input type="text" name="imgname" size="40" value="<?php echo $zoom->_CONFIG['tempName'];?>" class="inputbox" />
		</td>
		<td>
			<?php 
			if($zoom->_CONFIG['autonumber']){
				echo "<script>toggleDisabled('imgname');</script>&nbsp;"; ?>
				&nbsp;
				<input type="checkbox" name="setFilename" value="1" onclick="toggleDisabled('imgname')"<?php if($zoom->_CONFIG['autonumber']) echo " checked";?> /> <?php echo _ZOOM_FORM_SETFILENAME;?>
				<?php
			}else echo '&nbsp;'; ?>
		</td>
	</tr>
	<tr><td colspan="3">&nbsp;</td></tr>
	<tr>
		<td><?php echo _ZOOM_KEYWORDS;?>:&nbsp;</td>
		<td colspan="2">
			<input type="text" name="keywords" size="40" value="" class="inputbox" />
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr>
		<td valign="top"><?php echo _ZOOM_DESCRIPTION;?>:&nbsp;</td>
		<td colspan="2">
			<textarea class="inputbox" cols="50" rows="5" name="descr" /><?php echo $zoom->_CONFIG['tempDescr'];?></textarea>
		</td>
	</tr>
	<tr><td colspan="3">&nbsp;</td></tr>
	<tr>
		<td colspan="3" align="center">
			<input type="submit" value="<?php echo _ZOOM_BUTTON_UPLOAD;?>" name="submit_url" class="button" />
		</td>
	</tr>
	</table>
	<?php
} //END IF urls?
if ($temp_files) {
	// Clean up the temporary url file
	foreach ($temp_files as $tf => $junk) {
		fs_unlink($tf);
	}
} 
?>
