<?php
$locale->setSection("Web Links");

$linkInfo = $weblinks->getInfo($str->fromHTML($_GET['id']));

if (!is_array($linkInfo)) {
	echo "Invalid link.";
	exit();
}

if (!isEmptyMySQLDate($linkInfo['expiry'])) {
	if ($db->GetOne("SELECT '".$linkInfo['expiry']."' < NOW()") == "1") {
		$weblinks->deleteById($linkInfo['id']);
		echo "Invalid link.";
		exit();
	}
}

if (!$linkInfo['system']) {
	echo "Invalid link!";
	exit();
}

if ($linkInfo['password']) {
	if ($str->fromHTML($_REQUEST['pass']) != $linkInfo['password']) {
		echo "Invalid password!";
		exit();
   }
}

$fullPath = $linkInfo['path'];
$filename = $fm->basename($fullPath);

$fileman = new fileman;
$fileman->setUID($linkInfo['uid']);
$myfiles = new myfiles;
$myfiles->setUID($linkInfo['uid']);

$users->initPerms();
$userPerms = $users->userPerms->getPerms($linkInfo['uid']);

if ($userPerms["readonly"]) {
	exit("Access denied!");
}
if (!$userPerms["upload"]) {
	exit("Access denied!");
}

$shareInfo = false;
if ($linkInfo['share_id']) {
	$sharing = new fileman_myfiles_share();
	$sharing->uid = $linkInfo['uid'];
	$shareInfo = $sharing->getInfoById($linkInfo['share_id']);
	if (!$shareInfo) {
		echo $locale->t("The shared folder is no longer available.", "General");
		exit();
	}
	if (!$shareInfo['perms_alter']) {
		echo $locale->t("You are not allowed to modify files in this shared folder.", "General");
		exit();
	}
	$subPath = $fm->stripRoot($linkInfo['path'], $shareInfo['path']);
	$relativePath = gluePath('/ROOT/', $shareInfo['uid'], $shareInfo['id'], $subPath);
} else {
	$relativePath = gluePath('/ROOT/HOME', substr($linkInfo['path'], strlen($userPerms['homefolder'])));
}
$relativePath = $fm->dirname($relativePath);

$customActions = new custom_actions();
$contents = $customActions->getNewFileContents($str->fromHTML($_GET['action']));
if ($contents) {
	$rs = $myfiles->newFile($relativePath, $filename, false, $contents);
	if ($rs) {
		echo $locale->get("Changes saved.");
		exit();
	} else {
		header('HTTP/1.1 500 Internal Server Error');
		echo $locale->get("Failed to save changes.");
		echo "\r\n";
		echo " Error ".$myfiles->error['code'].": ".$myfiles->error['msg'];
		exit();
	}
} else {
	echo $locale->get("Empty contents.");
	exit();
}