<?php
// Master Autoindex - Folder Copy Plugin
// ionutvmi@gmail.com 
// Sep 2012
// master-land.net
@set_time_limit(0);

include "../inc/init.php";

if(!is_admin()) {
	header("Location: $set->url");exit;
}

$links[] = mai_img("arr.gif")." <a href='index.php'>$lang->admincp </a>";
$links[] = mai_img("arr.gif")." Folder Copy ";


if($_POST){
	$_count = 0;
	$path = "../files".$_POST['path'];
	$files = getLinks($_POST['url']);
	$extensions = explode(",",$_POST['ext']);
	$dirid = $db->get_row("SELECT id FROM `". MAI_PREFIX ."files` WHERE `path`='".substr($path,2)."'")->id;

	foreach($files as $file){
		$info = (object)pathinfo($file);
		if(in_array($info->extension,$extensions)){
			$_name = trim(str_ireplace($_POST['r'],$_POST['w'],$file));

			$url = rtrim(trim($_POST['url']),"/")."/".trim($file);
			if(copy($url,$path."/".$_name)) {
				$_count++;
				$db->insert("INSERT INTO `". MAI_PREFIX ."files` SET `name`='".$db->escape($_name)."', `path`='".substr($path,2)."/".$db->escape($_name)."',`indir`='$dirid', `time`='".time()."',`size`='".filesize($path."/".$_name)."'");
			}
		}
	}
	if($_count > 0) {
		if($dirid != 0) {
			foreach(explode('/',substr($path,9)) as $dr){
				$_dr .="/".$dr;
				if($_dr != '/')
				$db->query("UPDATE `". MAI_PREFIX ."files` SET `time`='".time()."' WHERE `path` = '/files$_dr'");
			}
		}
	}
	$content .= "<div class='green'>$_count files added </div>";
}


$content .="<form action='#' method='post'>
Url: <br/><input type='text' name='url' value='http://'> <br/>
Copy to<br/>
<select name='path'><option value=''>./</option>";
$all_folders = $db->select("SELECT `path` FROM `". MAI_PREFIX ."files` WHERE `size` = '0'");

foreach($all_folders as $folder){
	$folder = substr($folder->path,6); // remove /files
	$content .= "<option value='$folder'>$folder</option>";
}
$content .="</select><br/>
Extensions(separated by comma ,):<br/>
<input type='text' name='ext' value='jpg,jar,gif'> <br/>
Replace:<br/>
<input type='text' name='r' value=''> => <input type='text' name='w' value=''>
<br/> <br/>
<input type='submit' value='Copy Files'>
</form>";


include "../header.php";

echo "<div class='title'>Folder Copy</div>
<div class='content'>
$content
</div>";

include "../footer.php";


// functions
function getLinks($link)
{
$ret = array();
$dom = new domDocument;
@$dom->loadHTML(file_get_contents($link));
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('a');
foreach ($links as $tag)
{
$ret[$tag->getAttribute('href')] = $tag->childNodes->item(0)->nodeValue;
}
return $ret;
}