<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 7/8/18
 * Time: 11:17 PM
 */

namespace IMATHUZH\Qfq\Core\Helper;


use IMATHUZH\Qfq\Core\Store\Session;


/**
 * Class DownloadPage
 * @package qfq
 */
class DownloadPage {

    /**
     * Retrieve the content of the given page and returns them.
     * $page
     *
     * @param string $page - Full URL like 'https://example.com' or T3 specific like 'export&s=badcaffee1234'
     * @param string $baseUrl - baserUrl from Configfile
     * @return bool|string
     * @throws \UserReportException
     */
    public static function getContent($page, $baseUrl) {

        if (empty($page)) {
            return false;
        }

        if (substr($page, 0, 4) != 'http') {
            if (empty($baseUrl)) {
                return false;
            }
            // We need to prefix
            $page = $baseUrl . $page;
        }

        // Check php.ini
        if (ini_get('allow_url_fopen') != '1') {
            throw new \UserReportException("php.ini: 'allow_url_fopen' is off and needs to be open to get '$page''", ERROR_DOWNLOAD_FOPEN_BLOCKED);
        }

        // Download page
        $ctx = array(
            "ssl" => array(
                "verify_peer" => false,
                "verify_peer_name" => false,
            ),
            'http' => array(
                'timeout' => 1200,
            ),
        );

        if (isset($_COOKIE[SESSION_NAME])) {
            $cookie_http = array(
                // Copy cookie: to forward current QFQ user session
                'method' => "GET",
                'header' => "Accept-language: en\r\n" .
                    "Cookie: " . SESSION_NAME . "=" . $_COOKIE[SESSION_NAME] . "\r\n",
            );
            $ctx['http'] = array_merge($ctx['http'], $cookie_http);
        }

        // The current session needs to be closed, cause the SESSION needs to be opened again by processing get_file_contents()
        // T3 is started again to render the requested page
        Session::close();

        return file_get_contents($page, false, stream_context_create($ctx));
    }
}