<?php
/**
 * @version $Id: remotefile.func.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if (!defined('IN_PBDIGG'))
{
	exit('Access Denied!');
}

if($pb_watertype && !isset($WM))
{
	require_once(PBDIGG_ROOT.'include/Watermark.class.php');
	$WM = new Watermark();
}

function get_remote_files($text, $uploaddir = '')
{
	$remotefileurls = remote_file_url($text);
    $urls = save_remote_files($remotefileurls, $uploaddir);
	return str_replace($urls[0], $urls[1], $text);
}

function remote_file_url($text)
{
	global $_PBDEV;
	if(!preg_match_all('/(https?|ftp):\/\/([^\[\<\r\n]+?)\.(gif|jpg|jpeg|bmp|png)/im', $text, $matches))
	{
		return array();
	}
	$remotefileurls = array();
	foreach($matches[0] as $matche)
	{
		if($_PBDEV['PB_DOMAIN'] && strpos($matche, $_PBDEV['PB_DOMAIN']) !== FALSE) continue;
		$remotefileurls[] = $matche;
	}
	return array_unique($remotefileurls);
}

function save_remote_files($urls, $uploaddir)
{
	global $WM, $timestamp, $_PBENV, $pb_watertype;
	foreach($urls as $key => $url)
	{
		if(strpos($url, '://') === FALSE) continue;
		srand ((double) microtime() * 1000000);
		$filename = md5($url.rand(100, 999).$timestamp).'.'.Fext($url);
		$newfile = PBDIGG_ROOT.'attachments/'.$uploaddir.'/'.$filename;
		$newurl = $_PBENV['PB_URL'].'attachments/'.$uploaddir.'/'.$filename;
		if(@copy($url, $newfile))
		{
			if(file_exists($newfile) && $pb_watertype)
			{
				$WM->setImg($newfile);
				@chmod($newfile, 0777);
				$oldpath[] = $url;
				$newpath[] = $newurl;
			}
		}
	}
	return array($oldpath, $newpath);
}
?>