<?php
namespace FileRun;

global $settings, $config;
if (!$config) {exit();}

$this->data['contents'] = $this->readFile();
$isEditable = false;
if (Perms::check('upload')) {
	if (!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload'])) {
		$isEditable = true;
	}
}
if ($this->data['weblink'] && $isEditable) {
	$isEditable = WebLinks::verifyAllowEditing($this->data['weblink']['linkInfo']);
}
$list = [];
$enc = mb_list_encodings();
foreach($enc as $e) {
	$list[] = [$e];
}
$isClosable = $_REQUEST['_popup_id'] ? true : false;
$vars = [
	'isEditable' => $isEditable,
	'isClosable' => $isClosable,
	'URLRoot' => $config['url']['root'],
	'actionURL' => $this->actionURL,
	'path' => $this->data['relativePath'],
	'filename' => $this->data['fileName'],
	'windowId' => \S::fromHTML($_REQUEST['_popup_id']),
	'charsets' => $list,
	'csrf' => self::getCSRFToken()
];
if ($_REQUEST['charset'] && in_array($_REQUEST['charset'], $enc)) {
	$vars['charset'] = \S::fromHTML($_REQUEST['charset']);
	$this->data['contents'] = \S::convert2UTF8($this->data['contents'], $_REQUEST['charset']);
} else {
	$bom = pack("CCC", 0xef, 0xbb, 0xbf);
	if (strncmp($this->data['contents'], $bom, 3) === 0) {
		$this->data['contents'] = substr($this->data['contents'], 3);
	} else {
		$detectedCharset = \S::detectEncoding($this->data['contents']);
		$vars['charset'] = $detectedCharset;
		$this->data['contents'] = \S::convertEncoding($this->data['contents'], $detectedCharset, 'UTF-8');
	}
}

//Custom Actions: Text Editor

$page = [
	'styles' => ['basic', 'ext', 'fa'],
	'scripts' => [
		'ext',
		$this->url.'/app.js?v='.$settings->currentVersion,
		$this->url.'/ace/ace.js?v='.$settings->currentVersion,
		$this->url.'/ace/ext-modelist.js?v='.$settings->currentVersion
	],
	'loadMsg' => false,
	'jsGlobals' => [
		'FR.settings' => $vars
	],
	'contents' => '<textarea style="display:none;width:100%;height:100%" id="textContents" class="x-form-field">'.\S::safeHTML($this->data['contents']).'</textarea>'
];
require $config['path']['includes'].'/ui/page/plugin.php';