<?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');

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';

$headmod = 'import';
require('../system/head.php');

/** @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);

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

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

if (!$systemUser->isValid()) {
    echo $tools->displayError(_t('You need to be logged in'));
    require('../system/end.php');
    exit;
}

if (!$id) {
    echo $tools->displayError(_t('Wrong data'));
    require('../system/end.php');
    exit;
}

// Проверяем, тот ли юзер заливает файл и в нужное ли место
$res = $db->query("SELECT * FROM `forum` WHERE `id` = '$id'")->fetch();

if ($res['type'] != 'm' || ($res['user_id'] != $systemUser->id)) {
    echo $tools->displayError(_t('Wrong data'));
    require('../system/end.php');
    exit;
}

// Проверяем лимит времени, отведенный для выгрузки файла
if ($res['time'] < (time() - 3600)) {
    echo $tools->displayError(_t('The time allotted for the file upload has expired'), '<a href="index.php?id=' . $res['refid'] . '&amp;page=' . $page . '">' . _t('Back') . '</a>');
    require('../system/end.php');
    exit;
}

$req1 = $db->query("SELECT COUNT(*) FROM `cms_forum_files` WHERE `post` = '$id'");
	if ($req1->fetchColumn()) {
echo $tools->displayError(_t('Error Uploading File'));
	require('../system/end.php');
	exit;
}

function format($name) {
    $f1 = strrpos($name, ".");
    $f2 = substr($name, $f1 + 1, 999);
    $fname = strtolower($f2);
    return $fname;
}

function Size($var)
  {
     $ch = curl_init($var);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_HEADER, TRUE);
     curl_setopt($ch, CURLOPT_NOBODY, TRUE);
     $data = curl_exec($ch);
     $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
     curl_close($ch);
     return $size;
  }

switch ($res['type']) {
	case "m":
	if (isset($_POST['submit'])) {
		$url = trim($_POST['url']);
		$newn = $_POST['newn'];
		$tipf = format($url);
		$tentaptin = basename($url);
		$path_parts = pathinfo($url);
		$duoi = $path_parts['extension'];
		$ten = $path_parts['filename'];
		if (empty ($newn)) {
			$fname = $tentaptin;
		} else {
			$fname = ''.$newn.'.'.$duoi.'';
		}
		$al_ext = array_merge($ext_win, $ext_java, $ext_sis, $ext_doc, $ext_pic, $ext_arch, $ext_video, $ext_audio, $ext_other);
		$ext = explode(".", $fname);
		$error = [];
		if (!in_array($duoi, $al_ext)) { 
			$error[] = _t('The forbidden file format.<br>You can upload files of the following extension') . ':<br />' . implode(', ', $al_ext);
	} 
  if (strlen($fname) > 100) {
     $error[] = 'Error Length File Name Max 100';
  }
  if ($sizef > 1024 * $config['flsz']) {
      $error[] = _t('Import File size exceeds') . ' ' . $config['flsz'] . 'kb.';
  }
	if (preg_match("/[^a-zA-Z0-9\-\@\*\(\)\?\!\{\}\~\_\.\+=\[\]]+/", $fname)) { 
		$error[] = _t('Filename contains invalid characters');
	} 
	if (file_exists("../files/forum/attach/$fname")) {
		$fname = time() . $fname;
	}
	$fname = ''.$fname.'';
	@chmod("$fname", 0777);
	chmod("../files/forum/attach/$fname", 0777);
	$import = "../files/forum/attach/$fname";
	if (copy($url, $import)) {
		echo '<div class="mainblok"><div class="phdr"><b>File Successfully Imported</b></div>';
		echo '<div class="gmenu">';echo 'File imported..<br/>';
	} else {
		$error[] = 'Error importing file..!!';
	}
               if (stristr($fname, '.zip')){
                  require_once('../downloads/classes/pclzip.lib.php');
                  copy(ROOT_PATH."files/forum/attach/$fname", ROOT_PATH."files/temp/$fname");
                  chmod(ROOT_PATH."files/temp/$fname", 0666);
                  $zip=new PclZip(ROOT_PATH."files/temp/$fname");
                  $content = $zip->add("copyright.txt", PCLZIP_OPT_REMOVE_PATH, $open);
                  if ($content==0){
                     echo 'Error: '.win_to_utf($zip->errorInfo(true));
                     unlink(ROOT_PATH."files/temp/$fname");
                  } else {
                     echo 'Zip '; 
								unlink(ROOT_PATH."files/forum/attach/$fname");
                     copy(ROOT_PATH."files/temp/$fname", ROOT_PATH."files/forum/attach/$fname");
                     unlink(ROOT_PATH."files/temp/$fname");
                  }
               }
            }
  if (!$error) {
     $ext = $duoi;
     if (in_array($ext, $ext_win)) {
        $type = 1;
     } elseif (in_array($ext, $ext_java)) {
        $type = 2;
     } elseif (in_array($ext, $ext_sis)) {
       $type = 3;
     } elseif (in_array($ext, $ext_doc)) {
       $type = 4;
     } elseif (in_array($ext, $ext_pic)) {
       $type = 5;
     } elseif (in_array($ext, $ext_arch)) {
       $type = 6;
     } elseif (in_array($ext, $ext_video)) {
       $type = 7;
     } elseif (in_array($ext, $ext_audio)) {
       $type = 8;
     } else {
       $type = 9;
     }
    $res2 = $db->query("SELECT * FROM `forum` WHERE `id` = '" . $res['refid'] . "'")->fetch();
    $res3 = $db->query("SELECT * FROM `forum` WHERE `id` = '" . $res2['refid'] . "'")->fetch();
    $db->exec("
              INSERT INTO `cms_forum_files` SET
              `cat` = '" . $res3['refid'] . "',
              `subcat` = '" . $res2['refid'] . "',
              `topic` = '" . $res['refid'] . "',
              `post` = '$id',
              `time` = '" . $res['time'] . "',
              `filename` = " . $db->quote($fname) . ",
              `filetype` = '$type'
            ");
   } else {
            echo $tools->displayError($error, '<a href="index.php?act=import&amp;id=' . $id . '">' . _t('Repeat') . '</a>');
   }
   $pa2 = $db->query("SELECT `id` FROM `forum` WHERE `type` = 'm' AND `refid` = '" . $res['refid'] . "'")->rowCount();
    $page = ceil($pa2 / $kmess);
		echo 'Attachment included<br/><a href="index.php?id=' . $res['refid'] . '&amp;page=' . $page . '">' . _t('Continue') . '</a></div></div>';
		} else {
			echo '<div class="mainblok"><div class="phdr"><a href="index.php?act=addfile&amp;id=' . $id . '"><b>Use upload option</b></a><br/><b>' . _t('Import File') . '</b></div>' .
'<div class="gmenu"><form action="index.php?act=import&amp;id=' . $id . '" method="post" enctype="multipart/form-data"><p>';
echo "Insert URL:<br/><input type='text' name='url' value='http://'/> <br/>Save as <small>[without extension]</small>:<br/><input type='text' name='newn'/>";
echo '</p><p><input type="submit" name="submit" value="Import file"/></p></form></div>' .
'<div class="phdr">' . $_t('Max Import File Size') . ': ' . $config['flsz'] . ' Kb</div>';
echo '</div>';
}
break;
default:
echo $tools->displayError(_t('Wrong Data'));
}
