<?php // vim:ts=4:sw=4:noet

require_once(dirname(__FILE__) . '/KjwLib.php');

/**
 * Create directory. Tries to create it recursively.
 * Create mode is 2775.
 *
 * @param $path The directory to create.
 * @return Boolean specifying whether the directory exists afterwards.
 */
function kjwfs_mkdir($path) {
	if (is_dir($path))
		return true;
	if (@mkdir($path, 02775))
		return true;
	// Try to create parent(s)
	$n = strrpos($path, '/'); // DIRECTORY_SEPARATOR
	if ((int)$n === 0 || !kjwfs_mkdir(substr($path, 0, $n)))
		return false;
	// Try again
	if (@mkdir($path, 02775))
		return true;
	return false;
}

/**
 * Remove a directory and optionally all it's children.
 *
 * @param $path The directory to remove.
 * @param $filicide Boolean which tells us to remove children files as well
 *        and not just child directories.
 * @return Boolean specifying whether the directory is gone.
 */ 
function kjwfs_rmdir($path, $filicide = false) {
	$path = realpath($path);
	if (!is_dir($path))
		return false;
	$dp = opendir($path);
	$failed = false;
	while (($file = readdir($dp))) {
		if ($file != '.' && $file != '..') {
			$absfile = $path . '/' . $file;
			if (is_dir($absfile))
				$status = kjwfs_rmdir($absfile, $filicide);
			elseif ($filicide)
				$status = @unlink($absfile);
			else
				$status = false;
			if (!$status)
				$failed = true;
		}
	}
	closedir($dp);
	if ($failed)
		return false;
	return rmdir($path);
}

function kjwfs_file_put_contents($path, $data) {
	if (!kjwfs_mkdir(dirname($path)))
		return false;
	return file_put_contents($path, $data);
}

function kjwfs_wget($url, $http_headers = null) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	//curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPGET, 1);
	if ($http_headers !== null) {
		assert('is_array($http_headers)');
		curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers);
	}
	$data = curl_exec($ch);
	if (curl_errno($ch) != 0) {
		// see: curl_error($ch)
		curl_close($ch);
		return false;
	}
	curl_close($ch);
	return $data;
}
		
?>