<?php

require_once 'include/common.inc.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Request.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Utils.class.php';

Xoonips_Utils::denyGuestAccess();

$request = new Xoonips_Request();
$name = $request->getParameter('name');
$elementId = $request->getParameter('elementId');

$text = false;
$file = $request->getFile('file');
$errorMessage = false;
if (!is_null($file)) {
	// file was uploaded
	$originalFileName = $file['name'];
	$mimeType = $file['type'];
	$fileName = $file['tmp_name'];
	$error = (int) $file['error'];
	if ($error != 0) {
		if ($error == UPLOAD_ERR_INI_SIZE) {
			$errorMessage = _MD_XOONIPS_ITEM_UPLOAD_FILE_TOO_LARGE;
		} else {
			$errorMessage = _MD_XOONIPS_ITEM_UPLOAD_FILE_FAILED;
		}
		$textFromOpener = true;
	} else {
		// check mime type
		if (strstr($mimeType, 'text/plain') === false) {
			$errorMessage = 'unsupported file type : ' . $mimeType;
			$textFromOpener = true;
		} else {
			$text = file_get_contents($fileName);
			// convert encoding to _CHARSET
			$text = Xoonips_Utils::encodeUtf8($text);
			$textFromOpener = false;
		}
	}
} else {
	$textFromOpener = true;
}

xoops_header(false);

$xoopsTpl = new XoopsTpl();
$xoopsTpl->assign('displayName', $name);
$xoopsTpl->assign('name', $name);
$xoopsTpl->assign('elementId', $elementId);
$xoopsTpl->assign('text', $text);
$xoopsTpl->assign('textFromOpener', $textFromOpener);
$xoopsTpl->assign('errorMessage', $errorMessage);
$dirname = Xoonips_Utils::getDirname();
$xoopsTpl->display('db:'. $dirname . '_input_text_file_sub.html');

xoops_footer();

