<?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
 * Import Forum Module By Aan Gabriel
 * @link http://nircable.esy.es Nircable
 * @copyright Mobile Clubz
 */

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

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 (!$id || !$systemUser->isValid()) {
    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;
}

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;
  }



if (isset($_POST['submit'])) {
   $url = isset($_POST['url']) ? trim($_POST['url']) : '';
   //$url = trim($_POST['url']);
   $newn = isset($_POST['newn']) ? trim($_POST['newn']) : '';
   //$newn = $_POST['newn'];
   $tipf = format($url);
   $tentaptin = basename($url);
   $path_parts = pathinfo($url);
   $duoi = $path_parts['extension'];
   $ten = $path_parts['filename'];
   $sizef = Size($url);
   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) > 30) {
     $error[] = 'Error Length File Name Max 30';
  }
  if ($sizef > 1024 * $config['flsz']) {
      $error[] = _t('File size exceed') . ' ' . $config['flsz'] . 'kb.';
  }
  if (preg_match("/[^\da-z_\-.]+/", $fname)) {
     $error[] = _t('File name contains invalid characters');
  }
  if (file_exists("../files/forum/attach/$fname")) {
     $fname = time() . $fname;
  }
  $import = "../files/forum/attach/$fname";
  if (!$error) {
     if (copy($url, $import)) {
        echo '<div class="menu">' . _t('File attached') . '</div>';
     } else {
        $error[] = _t('Error uploading file');
     }
  }
  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 '<div class="gmenu"><a href="index.php?id=' . $res['refid'] . '&amp;page=' . $page . '">' . _t('Continue') . '</a></div>';
  } else {


echo '<div class="phdr"><b>' . _t('Add File') . '</b></div>'
        . '<div class="gmenu"><form action="index.php?act=import&amp;id=' . $id . '" method="post" enctype="multipart/form-data"><p>'
        . 'Insert URL:<br/><input type="text" name="url" value="http://"/></p>'
        . '<p>Save as <small>(without extension & lowercase)</small>:<br/><input type="text" name="newn"/>'
        . '</p><p><input type="submit" name="submit" value="' . _t('Upload') . '"/></p></form></div>'
        . '<div class="phdr">' . _t('Max. Size') . ': ' . $config['flsz'] . 'kb.</div>';
}

?>