<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

defined('_IN_JOHNCMS') or die('Error: restricted access');

//TODO: Добавить проверку, пустой ли каталог, если нет, выводить предупреждение
//TODO: Добавить рекурсивное удаление

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

$dir_clean = opendir('../files/temp/created_java/files');
while ($file = readdir($dir_clean)) {
    if ($file != 'index.php' && $file != '.htaccess' && $file != '.' && $file != '..') {
        $time_file = filemtime('../files/temp/created_java/files/' . $file);
        if ($time_file < ($realtime - 300))
            @unlink('../files/temp/created_java/files/' . $file);
    }
}
closedir($dir_clean);
$req_down = $db->query("SELECT * FROM `down__files` WHERE `id` = '$id' AND (`type` = 2 OR `type` = 3)  LIMIT 1");
$res_down = $req_down->fetch();
$format_file = $tools->format($res_down['name']);
if ($req_down->rowCount() == 0 || !is_file($res_down['dir'] . '/' . $res_down['name']) || $format_file != 'txt' || ($res_down['type'] == 3 && $systemUser->rights < 6 && $systemUser->rights != 4)) {
    require('../system/head.php');
    echo $tools->displayError('File not found<br /><a href="index.php">By category</a>');
    require('../system/end.php');
    exit;
}
if (isset($_GET['more'])) {
    $more = abs(intval($_GET['more']));
    $req_more = $db->query("SELECT * FROM `down_more` WHERE `id` = '$more' LIMIT 1");
    $res_more = $req_more->fetch();
    $format_file = $tools->format($res_more['name']);
    if (!$req_more->rowCount() || !is_file($res_down['dir'] . '/' . $res_more['name']) || $format_file != 'txt') {
        require('../system/head.php');
        echo $tools->displayError('File not found<br /><a href="index.php">By category</a>');
        require('../system/end.php');
        exit;
    }
    $down_file = $res_down['dir'] . '/' . $res_more['name'];
    $title_pages = $res_more['rus_name'];
    $txt_file = $res_more['name'];
} else {
    $down_file = $res_down['dir'] . '/' . $res_down['name'];
    $title_pages = $res_down['rus_name'];
    $txt_file = $res_down['name'];
}
if (!$_SESSION['down_' . $id]) {
    mysql_query("UPDATE `down__files` SET `field`=`field`+1 WHERE `id`='$id'");
    $_SESSION['down_' . $id] = 1;
}

$file = str_replace('.' . $format_file, '', $txt_file);
$name = str_replace('.' . $format_file, '', $txt_file);
$tmp = '../files/temp/created_java/files/' . $name . '.jar';
$tmp_jad = '../files/temp/created_java/files/' . $name . '.jar.jad';
if (!file_exists($tmp)) {
    $midlet_name = mb_substr($res_down['rus_name'], 0, 10);
    $midlet_name = iconv('UTF-8', 'windows-1251', $midlet_name);
    $book_text = file_get_contents($res_down['dir'] . '/' . $res_down['name']);
    $charset_text = strtolower(mb_detect_encoding($book_text, 'UTF-8, windows-1251'));
    if ($charset_text != 'windows-1251')
        $book_text = iconv('utf-8', 'windows-1251', $book_text);
    $files = fopen("../files/temp/created_java/java/textfile.txt", 'w+');
    flock($files, LOCK_EX);
    $book_name = iconv('UTF-8', 'windows-1251', $res['rus_name']);
    $result = "\r\n" . $book_name . "\r\n\r\n----------\r\n\r\n" . trim($book_text) . "\r\n\r\nDownloaded from " . $set['homeurl'];
    fputs($files, $result);
    flock($files, LOCK_UN);
    fclose($files);
    $manifest_text = 'Manifest-Version: 1.0
MIDlet-1: File #' . $id . ', , br.BookReader
MIDlet-Name: $tmp_jad
MIDlet-Vendor: JohnCMS
MIDlet-Version: 1.5.3
MIDletX-No-Command: true
MIDletX-LG-Contents: true
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
TCBR-Platform: Generic version (all phones)';
    $files = fopen("../files/temp/created_java/java/META-INF/MANIFEST.MF", 'w+');
    flock($files, LOCK_EX);
    fputs($files, $manifest_text);
    flock($files, LOCK_UN);
    fclose($files);
    require('../downloads/classes/pclzip.lib.php');
    $archive = new PclZip($tmp);
    $list = $archive->create('../files/temp/created_java/java', PCLZIP_OPT_REMove_PATH, '../files/download/temp/created_java/java');
    if (!file_exists($tmp)) {
        require('../system/head.php');
        echo $tools->displayError('Failed to create JAR Files');
        require('../system/end.php');
        exit;
    }
}
if (!file_exists($tmp_jad)) {
    $filesize = filesize($tmp);
    $jad_text = 'Manifest-Version: 1.0
MIDlet-1: File #' . $id . ', , br.BookReader
MIDlet-Name: File #' . $id . '
MIDlet-Vendor: JohnCMS
MIDlet-Version: 1.5.3
MIDletX-No-Command: true
MIDletX-LG-Contents: true
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
TCBR-Platform: Generic version (all phones)
MIDlet-Jar-Size: ' . $filesize . '
MIDlet-Jar-URL: ' . $config['homeurl'] . '/' . $dir_load . '/' . $tmp;
    $files = fopen($tmp_jad, 'w+');
    flock($files, LOCK_EX);
    fputs($files, $jad_text);
    flock($files, LOCK_UN);
    fclose($files);
}

require('../system/head.php');
echo '<div class="phdr"><b>' . $tools->checkout($title_pages) . '</b></div>';
echo '<div class="menu">Download: <a href="' . $tools->checkout($tmp) . '">JAR</a> | <a href="' . checkout($tmp_jad) . '">JAD</a></div>';
echo '<div class="phdr">Files will be available for download within 5 minutes</div>';
echo '<p><a href="index.php?act=view&amp;id=' . $id . '">To File</a></p>';
?>