<?php
/**
 * Download Manager parent controller
 *
 * @package blesta
 * @subpackage plugins.downloadmanager
 * @copyright Copyright (c) 2010, Phillips Data, Inc.
 * @license http://www.blesta.com/license/ The Blesta License Agreement
 * @link http://www.blesta.com/ Blesta
 */
class DownloadManagerController extends AppController
{
    public function preAction()
    {
        $this->structure->setDefaultView(APPDIR);

        parent::preAction();

        // Set the portal type
        $this->portal = 'client';
        if (substr($this->controller, 0, 5) == 'admin') {
            $this->portal = 'admin';
        }

        // Require login if is an admin controller
        if ($this->portal == 'admin') {
            $this->requireLogin();
        }

        // Auto load language for the controller
        Language::loadLang(
            [Loader::fromCamelCase(get_class($this))],
            null,
            dirname(__FILE__) . DS . 'language' . DS
        );
        Language::loadLang(
            'download_manager_manage_plugin',
            null,
            dirname(__FILE__) . DS . 'language' . DS
        );

        // Set the company ID
        $this->company_id = Configure::get('Blesta.company_id');

        // Set the page title
        $this->structure->set(
            'page_title',
            Language::_(
                'DownloadManagerManagePlugin.' . Loader::fromCamelCase($this->action ?? 'index')
                . '.page_title',
                true
            )
        );

        // Override default view directory
        $this->view->view = 'default';
        $this->orig_structure_view = $this->structure->view;
        $this->structure->view = 'default';

        // Restore structure view location of the admin portal
        $this->structure->setDefaultView(APPDIR);
        $this->structure->setView(null, $this->orig_structure_view);
    }

    /**
     * Determines whether the current request is a POST whose body was discarded
     * by PHP because it exceeded the post_max_size limit. When that happens both
     * $_POST and $_FILES arrive empty even though data was sent, so an upload that
     * is too large would otherwise fail silently and re-display the form with no
     * error. Detecting it lets callers surface a meaningful message instead.
     *
     * @return bool True if a POST body was sent but discarded for exceeding post_max_size
     */
    protected function postExceedsMaxSize()
    {
        return strtoupper($_SERVER['REQUEST_METHOD'] ?? '') === 'POST'
            && empty($this->post)
            && empty($this->files)
            && (int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 0;
    }

    /**
     * Returns the effective maximum upload size enforced by PHP (the smaller of
     * post_max_size and upload_max_filesize) as a human-readable string.
     *
     * @return string The maximum upload size, e.g. "40 MB"
     */
    protected function maxUploadSize()
    {
        $to_bytes = function ($value) {
            $value = trim((string) $value);
            if ($value === '') {
                return 0;
            }

            $bytes = (int) $value;
            switch (strtolower($value[strlen($value) - 1])) {
                case 'g':
                    $bytes *= 1024;
                    // no break
                case 'm':
                    $bytes *= 1024;
                    // no break
                case 'k':
                    $bytes *= 1024;
            }

            return $bytes;
        };

        $post_max = $to_bytes(ini_get('post_max_size'));
        $upload_max = $to_bytes(ini_get('upload_max_filesize'));

        // A post_max_size of 0 means unlimited; fall back to upload_max_filesize
        $limit = $post_max > 0 ? min($post_max, $upload_max) : $upload_max;

        $units = ['B', 'KB', 'MB', 'GB'];
        $i = 0;
        while ($limit >= 1024 && $i < count($units) - 1) {
            $limit /= 1024;
            $i++;
        }

        return round($limit, ($i > 1 ? 1 : 0)) . ' ' . $units[$i];
    }
}
