<?php

include_once 'UpageLogFormatter.php';

error_reporting(E_ALL & ~E_STRICT);
ini_set('display_errors', 1);

function errorHandlerUpagePlugin($errno, $errstr, $errfile, $errline, $errcontext)
{
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }
    ob_start();
    switch ($errno) {
        case E_USER_ERROR:
            echo "USER ERROR: $errstr\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
            echo "Aborting...\n";
            break;
        case E_USER_WARNING:
            echo "USER WARNING: $errstr<br />\n";
            break;
        case E_USER_NOTICE:
            echo "USER NOTICE: $errstr<br />\n";
            break;
        default:
            echo $errstr;
            break;
    }
    $error = ob_get_clean();

    $bt = debug_backtrace();
    $formatter = new UpageLogFormatter();
    $callstack = '';
    foreach($bt as $key => $caller) {
        if (0 === $key) continue;
        $callstack .= "   -> ";
        if (isset($caller['class']))
            $callstack .= $caller['class'] . '::';
        $callstack .= $caller['function'] . '(' . $formatter->args($caller['args']) . ')';
        $callstack .= "\n";
    }
    $error = "\n\n" . 'error handler: ' . $error . "\n" . print_r($errcontext, true) . "  Callstack: \n" . $callstack . "\n\n";

    http_response_code(500);
    exit($error);

    /* Don't execute PHP internal error handler */
    return true;
}

set_error_handler('errorHandlerUpagePlugin', E_ALL);

function shutdownHandler()
{
    $errorText = '';
    $error = error_get_last();
    switch ($error['type'])
    {
        case E_ERROR:
        case E_CORE_ERROR:
        case E_COMPILE_ERROR:
        case E_PARSE:
            $errorText = "\n\n" . 'shutdown handler: ' . $error['message'];
    }
    if ('' !== $errorText) {
        http_response_code(500);
        exit($error);
    }
}

register_shutdown_function("shutdownHandler");

function isSSL() {
    $isSSL = false;

    if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'){
        $_SERVER['HTTPS']='on';
    }

    if (isset($_SERVER['HTTPS'])) {
        if ('on' == strtolower($_SERVER['HTTPS']))
            $isSSL = true;
        if ('1' == $_SERVER['HTTPS'])
            $isSSL = true;
    } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        $isSSL = true;
    }
    return $isSSL;
}

function getUpageDomain() {
    $domain = isset($_GET['domain'])
        ? urldecode($_GET['domain'])
        : 'http://upage.io';

    $domain = preg_replace('#(.*)\/$#', '$1', $domain);
    if (isSSL()) {
        $domain = str_replace('http://', 'https://', $domain);
    } else {
        $domain = str_replace('https://', 'http://', $domain);
    }
    return $domain;
}

function getStartFiles() {
    $hash = md5(round(microtime(true)));
    $root = dirname(dirname((JURI::current())));
    $lib = $root . '/plugins/editors-xtd/upagebutton/lib';
    return array(
        'upage.css' => $lib . '/css/upage.css?version=' . $hash,
        'bootstrap' => $lib . '/css/bootstrap.css?version=' . $hash,
        'template' => $lib . '/css/template.css?version=' . $hash,
        'template.ie' => $lib . '/css/template.ie.css?version=' . $hash,
        'editor' => $lib . '/js/editor.js?version=' . $hash,
        'editor-utility' => $lib . '/js/editor-utility.js?version=' . $hash,
        'editor-uploader' => $lib . '/js/editor-uploader.js?version=' . $hash,
        'loader' => getUpageDomain() . '/Editor/loader.js'
    );
}

function getConfigObject() {
    $root = dirname(dirname((JURI::current())));
    $index = $root  . '/plugins/editors-xtd/upagebutton/lib/index.php';
    $postId = JRequest::getCmd('id', '');
    return json_encode(array(
        'actions' => array(
            'uploadImage'           => $index . '?action=uploadImage',
            'uploadSections'        => $index . '?action=uploadSections',
            'updatePost'            => $index . '?action=updatePost',
            'getSite'               => $index . '?action=getSite',
            'getPage'               => $index . '?action=getPage',
            'duplicatePage'         => $index . '?action=duplicatePage',
            'updatePages'           => $index . '?action=updatePages',
            'updatePageSections'    => $index . '?action=updatePageSections',
        ),
        'uploadImageOptions' => array(
            'formFileName' => 'async-upload'
        ),
        'postId' => $postId,
        'returnUrl' => $root . '/administrator/index.php?option=com_content&view=article&layout=edit&id=' . $postId
    ));
}

function themlerShortCodesPluginIsInstalled() {
    $db = JFactory::getDbo();
    $query = $db->getQuery(true)
        ->select('*')
        ->from($db->quoteName('#__extensions'))
        ->where('type = ' . $db->quote('plugin'))
        ->where('element = ' . $db->quote('themlercontent'));
    $db->setQuery($query);
    $result = $db->loadObject();
    if (!$result)
        return false;
    return true;
}