processor.php 16.4 KB
Newer Older
John Punzalan's avatar
John Punzalan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Errors
 * @copyright  Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

 /**
 * Error processor
 *
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Error_Processor
{
    const MAGE_ERRORS_LOCAL_XML = 'local.xml';
    const MAGE_ERRORS_DESIGN_XML = 'design.xml';
    const DEFAULT_SKIN = 'default';
    const ERROR_DIR = 'errors';

    /**
     * Page title
     *
     * @var string
    */
    public $pageTitle;

    /**
     * Skin URL
     *
     * @var string
    */
    public $skinUrl;

    /**
     * Base URL
     *
     * @var string
    */
    public $baseUrl;

    /**
     * Post data
     *
     * @var array
    */
    public $postData;

    /**
     * Report data
     *
     * @var array
    */
    public $reportData;

    /**
     * Report action
     *
     * @var string
    */
    public $reportAction;

    /**
     * Report ID
     *
     * @var int
     */
    public $reportId;

    /**
     * Report file
     *
     * @var string
    */
    protected $_reportFile;

    /**
     * Show error message
     *
     * @var bool
    */
    public $showErrorMsg;

    /**
     * Show message after sending email
     *
     * @var bool
    */
    public $showSentMsg;

    /**
     * Show form for sending
     *
     * @var bool
    */
    public $showSendForm;

    /**
     * Server script name
     *
     * @var string
    */
    protected $_scriptName;

    /**
     * Is root
     *
     * @var bool
    */
    protected $_root;

    /**
     * Internal config object
     *
     * @var stdClass
    */
    protected $_config;

    public function __construct()
    {
        $this->_errorDir  = dirname(__FILE__) . '/';
        $this->_reportDir = dirname($this->_errorDir) . '/var/report/';

        if (!empty($_SERVER['SCRIPT_NAME'])) {
            if (in_array(basename($_SERVER['SCRIPT_NAME'],'.php'), array('404','503','report'))) {
                $this->_scriptName = dirname($_SERVER['SCRIPT_NAME']);
            }
            else {
                $this->_scriptName = $_SERVER['SCRIPT_NAME'];
            }
        }

        $reportId = (isset($_GET['id'])) ? (int)$_GET['id'] : null;
        if ($reportId) {
            $this->loadReport($reportId);
        }

        $this->_indexDir = $this->_getIndexDir();
        $this->_root  = is_dir($this->_indexDir.'app');

        $this->_prepareConfig();
        if (isset($_GET['skin'])) {
            $this->_setSkin($_GET['skin']);
        }
    }

    /**
     * Process 404 error
    */
    public function process404()
    {
        $this->pageTitle = 'Error 404: Not Found';
        $this->_sendHeaders(404);
        $this->_renderPage('404.phtml');
    }

    /**
     * Process 503 error
    */
    public function process503()
    {
        $this->pageTitle = 'Error 503: Service Unavailable';
        $this->_sendHeaders(503);
        $this->_renderPage('503.phtml');
    }

    /**
     * Process report
    */
    public function processReport()
    {
        $this->pageTitle = 'There has been an error processing your request';
        $this->_sendHeaders(503);

        $this->showErrorMsg = false;
        $this->showSentMsg  = false;
        $this->showSendForm = false;
        $this->reportAction = $this->_config->action;
        $this->_setReportUrl();

        if($this->reportAction == 'email') {
            $this->showSendForm = true;
            $this->sendReport();
        }
        $this->_renderPage('report.phtml');
    }

    /**
     * Retrieve skin URL
     *
     * @return string
     */
    public function getSkinUrl()
    {
        return $this->getBaseUrl() . self::ERROR_DIR. '/' . $this->_config->skin . '/';
    }

    /**
     * Retrieve base host URL without path
     *
     * @return string
     */
    public function getHostUrl()
    {
        /**
         * Define server http host
         */
        if (!empty($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
        } elseif (!empty($_SERVER['SERVER_NAME'])) {
            $host = $_SERVER['SERVER_NAME'];
        } else {
            $host = 'localhost';
        }

        $isSecure = (!empty($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off');
        $url = ($isSecure ? 'https://' : 'http://') . htmlspecialchars($host, ENT_COMPAT | ENT_HTML401, 'UTF-8');

        if (!empty($_SERVER['SERVER_PORT'])
            && preg_match('/\d+/', $_SERVER['SERVER_PORT'])
            && !in_array($_SERVER['SERVER_PORT'], array(80, 433))
        ) {
            $url .= ':' . $_SERVER['SERVER_PORT'];
        }
        return  $url;
    }

    /**
     * Retrieve base URL
     *
     * @return string
     */
    public function getBaseUrl($param = false)
    {
        $path = $this->_scriptName;

        if($param && !$this->_root) {
            $path = dirname($path);
        }

        $basePath = str_replace('\\', '/', dirname($path));
        return $this->getHostUrl() . ('/' == $basePath ? '' : $basePath) . '/';
    }

    /**
     * Retrieve client IP address
     *
     * @return string
     */
    protected function _getClientIp()
    {
        return (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : 'undefined';
    }

    /**
     * Get index dir
     *
     * @return string
     */
    protected function _getIndexDir()
    {
        $documentRoot = '';
        if (!empty($_SERVER['DOCUMENT_ROOT'])) {
            $documentRoot = rtrim($_SERVER['DOCUMENT_ROOT'],'/');
        }
        return dirname($documentRoot . $this->_scriptName) . '/';
    }

    /**
     * Prepare config data
     */
    protected function _prepareConfig()
    {
        $local  = $this->_loadXml(self::MAGE_ERRORS_LOCAL_XML);
        $design = $this->_loadXml(self::MAGE_ERRORS_DESIGN_XML);

        //initial settings
        $config = new stdClass();
        $config->action         = '';
        $config->subject        = 'Store Debug Information';
        $config->email_address  = '';
        $config->trash          = 'leave';
        $config->skin           = self::DEFAULT_SKIN;

        //combine xml data to one object
        if (!is_null($design) && (string)$design->skin) {
            $this->_setSkin((string)$design->skin, $config);
        }
        if (!is_null($local)) {
            if ((string)$local->report->action) {
                $config->action = $local->report->action;
            }
            if ((string)$local->report->subject) {
                $config->subject = $local->report->subject;
            }
            if ((string)$local->report->email_address) {
                $config->email_address = $local->report->email_address;
            }
            if ((string)$local->report->trash) {
                $config->trash = $local->report->trash;
            }
            if ((string)$local->skin) {
                $this->_setSkin((string)$local->skin, $config);
            }
        }
        if ((string)$config->email_address == '' && (string)$config->action == 'email') {
            $config->action = '';
        }

        $this->_config = $config;
    }

    /**
     * Load xml file
     *
     * @param string $config
     * return SimpleXMLElement
     */
    protected function _loadXml($xmlFile)
    {
        $configPath = $this->_getFilePath($xmlFile);
        return ($configPath) ? simplexml_load_file($configPath) : null;
    }

    /**
     * Send error headers
     *
     * @param int $statusCode
     */
    protected function _sendHeaders($statusCode)
    {
        $serverProtocol = !empty($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
        switch ($statusCode) {
            case 404:
                $description = 'Not Found';
                break;
            case 503:
                $description = 'Service Unavailable';
                break;
            default:
                $description = '';
                break;
        }

        header(sprintf('%s %s %s', $serverProtocol, $statusCode, $description), true, $statusCode);
        header(sprintf('Status: %s %s', $statusCode, $description), true, $statusCode);
    }

    /**
     * Render page
     */
    protected function _renderPage($template)
    {
        $baseTemplate = $this->_getTemplatePath('page.phtml');
        $contentTemplate = $this->_getTemplatePath($template);

        if ($baseTemplate && $contentTemplate) {
            require_once $baseTemplate;
        }
    }

    /**
     * Find file path
     *
     * @param string $file
     * @param array $directories
     * return $string
     */
    protected function _getFilePath($file, $directories = null)
    {
        if (is_null($directories)) {
            $directories = array();

            if (!$this->_root) {
                $directories[] = $this->_indexDir . self::ERROR_DIR . '/';
            }
            $directories[] = $this->_errorDir;
        }

        foreach ($directories as $directory) {
            if (file_exists($directory . $file)) {
                return $directory . $file;
            }
        }
    }

    /**
     * Find template path
     *
     * @param string $template
     * return $string
     */
    protected function _getTemplatePath($template)
    {
        $directories = array();

        if (!$this->_root) {
            $directories[] = $this->_indexDir . self::ERROR_DIR. '/'. $this->_config->skin . '/';

            if ($this->_config->skin != self::DEFAULT_SKIN) {
                $directories[] = $this->_indexDir . self::ERROR_DIR . '/'. self::DEFAULT_SKIN . '/';
            }
        }

        $directories[] = $this->_errorDir . $this->_config->skin . '/';

        if ($this->_config->skin != self::DEFAULT_SKIN) {
            $directories[] = $this->_errorDir . self::DEFAULT_SKIN . '/';
        }

        return $this->_getFilePath($template, $directories);
    }

    /**
     * Set report data
     *
     * @param array $reportData
     */
    protected function _setReportData($reportData)
    {
        $this->reportData = $reportData;

        if (!isset($reportData['url'])) {
            $this->reportData['url'] = '';
        }
        else {
            $this->reportData['url'] = $this->getHostUrl()
                                    . htmlspecialchars($reportData['url'], ENT_COMPAT | ENT_HTML401, 'UTF-8');
        }

        if (isset($this->reportData['script_name'])) {
            $this->_scriptName = $this->reportData['script_name'];
        }
    }

    /**
     * Create report
     *
     * @param array $reportData
     */
    public function saveReport($reportData)
    {
        $this->reportData = $reportData;
        $this->reportId   = abs(intval(microtime(true) * rand(100, 1000)));
        $this->_reportFile = $this->_reportDir . '/' . $this->reportId;
        $this->_setReportData($reportData);

        if (!file_exists($this->_reportDir)) {
            @mkdir($this->_reportDir, 0750, true);
        }

        $reportData = array_map('strip_tags', $reportData);
        @file_put_contents($this->_reportFile, serialize($reportData));
        @chmod($this->_reportFile, 0640);

        if (isset($reportData['skin']) && self::DEFAULT_SKIN != $reportData['skin']) {
            $this->_setSkin($reportData['skin']);
        }
        $this->_setReportUrl();

        if (headers_sent()) {
            print '<script type="text/javascript">';
            print "window.location.href = encodeURI('{$this->reportUrl}');";
            print '</script>';
            exit;
        }
    }

    /**
     * Get report
     *
     * @param int $reportId
     */
    public function loadReport($reportId)
    {
        $reportData = false;
        $this->reportId = $reportId;
        $this->_reportFile = $this->_reportDir . '/' . $reportId;

        if (!file_exists($this->_reportFile) || !is_readable($this->_reportFile)) {
            header("Location: " . $this->getBaseUrl());
            die();
        }

        $reportContent = file_get_contents($this->_reportFile);
        if (!preg_match('/[oc]:[+\-]?\d+:"/i', $reportContent )) {
            $reportData = unserialize($reportContent );
        }
        if (is_array($reportData)) {
            $this->_setReportData($reportData);
        }
    }

    /**
     * Send report
     *
     */
    public function sendReport()
    {
        $this->pageTitle = 'Error Submission Form';

        $this->postData['firstName'] = (isset($_POST['firstname'])) ? trim(htmlspecialchars($_POST['firstname'])) : '';
        $this->postData['lastName']  = (isset($_POST['lastname'])) ? trim(htmlspecialchars($_POST['lastname'])) : '';
        $this->postData['email']     = (isset($_POST['email'])) ? trim(htmlspecialchars($_POST['email'])) : '';
        $this->postData['telephone'] = (isset($_POST['telephone'])) ? trim(htmlspecialchars($_POST['telephone'])) : '';
        $this->postData['comment']   = (isset($_POST['comment'])) ? trim(htmlspecialchars($_POST['comment'])) : '';
        $url = htmlspecialchars($this->reportData['url'], ENT_COMPAT | ENT_HTML401);

        if (isset($_POST['submit'])) {
            if ($this->_validate()) {
                $msg  = "URL: {$url}\n"
                    . "IP Address: {$this->_getClientIp()}\n"
                    . "First Name: {$this->postData['firstName']}\n"
                    . "Last Name: {$this->postData['lastName']}\n"
                    . "E-mail Address: {$this->postData['email']}\n";
                if ($this->postData['telephone']) {
                    $msg .= "Telephone: {$this->postData['telephone']}\n";
                }
                if ($this->postData['comment']) {
                    $msg .= "Comment: {$this->postData['comment']}\n";
                }

                $subject = sprintf('%s [%s]', (string)$this->_config->subject, $this->reportId);
                @mail((string)$this->_config->email_address, $subject, $msg);

                $this->showSendForm = false;
                $this->showSentMsg  = true;
            } else {
                $this->showErrorMsg = true;
            }
        } else {
            $time = gmdate('Y-m-d H:i:s \G\M\T');

            $msg = "URL: {$url}\n"
                . "IP Address: {$this->_getClientIp()}\n"
                . "Time: {$time}\n"
                . "Error:\n{$this->reportData[0]}\n\n"
                . "Trace:\n{$this->reportData[1]}";

            $subject = sprintf('%s [%s]', (string)$this->_config->subject, $this->reportId);
            @mail((string)$this->_config->email_address, $subject, $msg);

            if ($this->_config->trash == 'delete') {
                @unlink($this->_reportFile);
            }
        }
    }

    /**
     * Validate submitted post data
     *
     * @return bool
     */
    protected function _validate()
    {
        $email = preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/',
            $this->postData['email']);
        return ($this->postData['firstName'] && $this->postData['lastName'] && $email);
    }

    /**
     * Skin setter
     *
     * @param string $value
     * @param stdClass $config
     */
    protected function _setSkin($value, stdClass $config = null)
    {
        if (preg_match('/^[a-z0-9_]+$/i', $value) && is_dir($this->_indexDir . self::ERROR_DIR . '/' . $value)) {
            if (!$config) {
                if ($this->_config) {
                    $config = $this->_config;
                }
            }
            if ($config) {
                $config->skin = $value;
            }
        }
    }

    /**
     * Set current report URL from current params
     */
    protected function _setReportUrl()
    {
        if ($this->reportId && $this->_config && isset($this->_config->skin)) {
            $this->reportUrl = "{$this->getBaseUrl(true)}errors/report.php?" . http_build_query(array(
                'id' => $this->reportId, 'skin' => $this->_config->skin
            ));
        }
    }
}