Completed
Pull Request — master (#482)
by Markus
02:33
created

PrettyPageHandler::setPageTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Whoops - php errors for cool kids
4
 * @author Filipe Dobreira <http://github.com/filp>
5
 */
6
7
namespace Whoops\Handler;
8
9
use InvalidArgumentException;
10
use RuntimeException;
11
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
12
use Symfony\Component\VarDumper\Cloner\VarCloner;
13
use UnexpectedValueException;
14
use Whoops\Exception\Formatter;
15
use Whoops\Util\Misc;
16
use Whoops\Util\TemplateHelper;
17
18
class PrettyPageHandler extends Handler
19
{
20
    /**
21
     * Search paths to be scanned for resources, in the reverse
22
     * order they're declared.
23
     *
24
     * @var array
25
     */
26
    private $searchPaths = [];
27
28
    /**
29
     * Fast lookup cache for known resource locations.
30
     *
31
     * @var array
32
     */
33
    private $resourceCache = [];
34
35
    /**
36
     * The name of the custom css file.
37
     *
38
     * @var string
39
     */
40
    private $customCss = null;
41
42
    /**
43
     * @var array[]
44
     */
45
    private $extraTables = [];
46
47
    /**
48
     * @var bool
49
     */
50
    private $handleUnconditionally = false;
51
52
    /**
53
     * @var string
54
     */
55
    private $pageTitle = "Whoops! There was an error.";
56
57
    /**
58
     * @var array[]
59
     */
60
    private $applicationPaths;
61
    
62
    /**
63
     * @var array[]
64
     */
65
    private $blacklist = [
66
        '_GET' => [],
67
        '_POST' => [],
68
        '_FILES' => [],
69
        '_COOKIE' => [],
70
        '_SESSION' => [],
71
        '_SERVER' => [],
72
        '_ENV' => [],
73
    ];    
74
75
    /**
76
     * A string identifier for a known IDE/text editor, or a closure
77
     * that resolves a string that can be used to open a given file
78
     * in an editor. If the string contains the special substrings
79
     * %file or %line, they will be replaced with the correct data.
80
     *
81
     * @example
82
     *  "txmt://open?url=%file&line=%line"
83
     * @var mixed $editor
84
     */
85
    protected $editor;
86
87
    /**
88
     * A list of known editor strings
89
     * @var array
90
     */
91
    protected $editors = [
92
        "sublime"  => "subl://open?url=file://%file&line=%line",
93
        "textmate" => "txmt://open?url=file://%file&line=%line",
94
        "emacs"    => "emacs://open?url=file://%file&line=%line",
95
        "macvim"   => "mvim://open/?url=file://%file&line=%line",
96
        "phpstorm" => "phpstorm://open?file=%file&line=%line",
97
        "idea"     => "idea://open?file=%file&line=%line",
98
    ];
99
100
    /**
101
     * Constructor.
102
     */
103 1
    public function __construct()
104
    {
105 1
        if (ini_get('xdebug.file_link_format') || extension_loaded('xdebug')) {
106
            // Register editor using xdebug's file_link_format option.
107
            $this->editors['xdebug'] = function ($file, $line) {
108 1
                return str_replace(['%f', '%l'], [$file, $line], ini_get('xdebug.file_link_format'));
109
            };
110 1
        }
111
112
        // Add the default, local resource search path:
113 1
        $this->searchPaths[] = __DIR__ . "/../Resources";
114
        
115
        // blacklist php provided auth based values
116 1
        $this->blacklist('_SERVER', 'PHP_AUTH_USER');
117 1
        $this->blacklist('_SERVER', 'PHP_AUTH_PW');        
118 1
    }
119
120
    /**
121
     * @return int|null
122
     */
123 1
    public function handle()
124
    {
125 1
        if (!$this->handleUnconditionally()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->handleUnconditionally() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
126
            // Check conditions for outputting HTML:
127
            // @todo: Make this more robust
128 1
            if (php_sapi_name() === 'cli') {
129
                // Help users who have been relying on an internal test value
130
                // fix their code to the proper method
131 1
                if (isset($_ENV['whoops-test'])) {
132
                    throw new \Exception(
133
                        'Use handleUnconditionally instead of whoops-test'
134
                        .' environment variable'
135
                    );
136
                }
137
138 1
                return Handler::DONE;
139
            }
140
        }
141
142
        // @todo: Make this more dynamic
143
        $helper = new TemplateHelper();
144
145
        if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
146
            $cloner = new VarCloner();
147
            // Only dump object internals if a custom caster exists.
148
            $cloner->addCasters(['*' => function ($obj, $a, $stub, $isNested, $filter = 0) {
0 ignored issues
show
Unused Code introduced by
The parameter $isNested is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $filter is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
                $class = $stub->class;
150
                $classes = [$class => $class] + class_parents($class) + class_implements($class);
151
152
                foreach ($classes as $class) {
153
                    if (isset(AbstractCloner::$defaultCasters[$class])) {
154
                        return $a;
155
                    }
156
                }
157
158
                // Remove all internals
159
                return [];
160
            }]);
161
            $helper->setCloner($cloner);
162
        }
163
164
        $templateFile = $this->getResource("views/layout.html.php");
165
        $cssFile      = $this->getResource("css/whoops.base.css");
166
        $zeptoFile    = $this->getResource("js/zepto.min.js");
167
        $clipboard    = $this->getResource("js/clipboard.min.js");
168
        $jsFile       = $this->getResource("js/whoops.base.js");
169
170
        if ($this->customCss) {
171
            $customCssFile = $this->getResource($this->customCss);
172
        }
173
174
        $inspector = $this->getInspector();
175
        $frames    = $inspector->getFrames();
176
177
        $code = $inspector->getException()->getCode();
178
179
        if ($inspector->getException() instanceof \ErrorException) {
180
            // ErrorExceptions wrap the php-error types within the "severity" property
181
            $code = Misc::translateErrorCode($inspector->getException()->getSeverity());
182
        }
183
184
        // Detect frames that belong to the application.
185
        if ($this->applicationPaths) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->applicationPaths of type array[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
186
            /* @var \Whoops\Exception\Frame $frame */
187
            foreach ($frames as $frame) {
188
                foreach ($this->applicationPaths as $path) {
189
                    if (substr($frame->getFile(), 0, strlen($path)) === $path) {
190
                        $frame->setApplication(true);
191
                        break;
192
                    }
193
                }
194
            }
195
        }
196
197
        // List of variables that will be passed to the layout template.
198
        $vars = [
199
            "page_title" => $this->getPageTitle(),
200
201
            // @todo: Asset compiler
202
            "stylesheet" => file_get_contents($cssFile),
203
            "zepto"      => file_get_contents($zeptoFile),
204
            "clipboard"  => file_get_contents($clipboard),
205
            "javascript" => file_get_contents($jsFile),
206
207
            // Template paths:
208
            "header"                     => $this->getResource("views/header.html.php"),
209
            "header_outer"               => $this->getResource("views/header_outer.html.php"),
210
            "frame_list"                 => $this->getResource("views/frame_list.html.php"),
211
            "frames_description"         => $this->getResource("views/frames_description.html.php"),
212
            "frames_container"           => $this->getResource("views/frames_container.html.php"),
213
            "panel_details"              => $this->getResource("views/panel_details.html.php"),
214
            "panel_details_outer"        => $this->getResource("views/panel_details_outer.html.php"),
215
            "panel_left"                 => $this->getResource("views/panel_left.html.php"),
216
            "panel_left_outer"           => $this->getResource("views/panel_left_outer.html.php"),
217
            "frame_code"                 => $this->getResource("views/frame_code.html.php"),
218
            "env_details"                => $this->getResource("views/env_details.html.php"),
219
220
            "title"          => $this->getPageTitle(),
221
            "name"           => explode("\\", $inspector->getExceptionName()),
222
            "message"        => $inspector->getException()->getMessage(),
223
            "code"           => $code,
224
            "plain_exception" => Formatter::formatExceptionPlain($inspector),
225
            "frames"         => $frames,
226
            "has_frames"     => !!count($frames),
227
            "handler"        => $this,
228
            "handlers"       => $this->getRun()->getHandlers(),
229
230
            "active_frames_tab" => count($frames) && $frames->offsetGet(0)->isApplication() ?  'application' : 'all',
0 ignored issues
show
Bug introduced by
The method isApplication cannot be called on $frames->offsetGet(0) (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
231
            "has_frames_tabs"   => $this->getApplicationPaths(),
232
233
            "tables"      => [
234
                "GET Data"              => $this->maskBlacklisted($_GET, $this->blacklist['_GET']),
235
                "POST Data"             => $this->maskBlacklisted($_POST, $this->blacklist['_POST']),
236
                "Files"                 => $this->maskBlacklisted($_FILES, $this->blacklist['_FILES']),
237
                "Cookies"               => $this->maskBlacklisted($_COOKIE, $this->blacklist['_COOKIE']),
238
                "Session"               => isset($_SESSION) ? $this->maskBlacklisted($_SESSION, $this->blacklist['_SESSION']) :  [],
239
                "Server/Request Data"   => $this->maskBlacklisted($_SERVER, $this->blacklist['_SERVER']),
240
                "Environment Variables" => $this->maskBlacklisted($_ENV, $this->blacklist['_ENV']),
241
            ],
242
        ];
243
244
        if (isset($customCssFile)) {
245
            $vars["stylesheet"] .= file_get_contents($customCssFile);
246
        }
247
248
        // Add extra entries list of data tables:
249
        // @todo: Consolidate addDataTable and addDataTableCallback
250
        $extraTables = array_map(function ($table) use ($inspector) {
251
            return $table instanceof \Closure ? $table($inspector) : $table;
252
        }, $this->getDataTables());
253
        $vars["tables"] = array_merge($extraTables, $vars["tables"]);
254
255
        $plainTextHandler = new PlainTextHandler();
256
        $plainTextHandler->setException($this->getException());
257
        $plainTextHandler->setInspector($this->getInspector());
258
        $vars["preface"] = "<!--\n\n\n" . $plainTextHandler->generateResponse() . "\n\n\n\n\n\n\n\n\n\n\n-->";
259
260
        $helper->setVariables($vars);
261
        $helper->render($templateFile);
262
263
        return Handler::QUIT;
264
    }
265
266
    /**
267
     * @return string
268
     */
269
    public function contentType()
270
    {
271
        return 'text/html';
272
    }
273
274
    /**
275
     * Adds an entry to the list of tables displayed in the template.
276
     * The expected data is a simple associative array. Any nested arrays
277
     * will be flattened with print_r
278
     * @param string $label
279
     * @param array  $data
280
     */
281 1
    public function addDataTable($label, array $data)
282
    {
283 1
        $this->extraTables[$label] = $data;
284 1
    }
285
286
    /**
287
     * Lazily adds an entry to the list of tables displayed in the table.
288
     * The supplied callback argument will be called when the error is rendered,
289
     * it should produce a simple associative array. Any nested arrays will
290
     * be flattened with print_r.
291
     *
292
     * @throws InvalidArgumentException If $callback is not callable
293
     * @param  string                   $label
294
     * @param  callable                 $callback Callable returning an associative array
295
     */
296 1
    public function addDataTableCallback($label, /* callable */ $callback)
297
    {
298 1
        if (!is_callable($callback)) {
299
            throw new InvalidArgumentException('Expecting callback argument to be callable');
300
        }
301
302 1
        $this->extraTables[$label] = function (\Whoops\Exception\Inspector $inspector = null) use ($callback) {
303
            try {
304 1
                $result = call_user_func($callback, $inspector);
305
306
                // Only return the result if it can be iterated over by foreach().
307 1
                return is_array($result) || $result instanceof \Traversable ? $result : [];
308
            } catch (\Exception $e) {
309
                // Don't allow failure to break the rendering of the original exception.
310
                return [];
311
            }
312
        };
313 1
    }
314
315
    /**
316
     * Returns all the extra data tables registered with this handler.
317
     * Optionally accepts a 'label' parameter, to only return the data
318
     * table under that label.
319
     * @param  string|null      $label
320
     * @return array[]|callable
321
     */
322 2
    public function getDataTables($label = null)
323
    {
324 2
        if ($label !== null) {
325 2
            return isset($this->extraTables[$label]) ?
326 2
                   $this->extraTables[$label] : [];
327
        }
328
329 2
        return $this->extraTables;
330
    }
331
332
    /**
333
     * Allows to disable all attempts to dynamically decide whether to
334
     * handle or return prematurely.
335
     * Set this to ensure that the handler will perform no matter what.
336
     * @param  bool|null $value
337
     * @return bool|null
338
     */
339 1
    public function handleUnconditionally($value = null)
340
    {
341 1
        if (func_num_args() == 0) {
342 1
            return $this->handleUnconditionally;
343
        }
344
345
        $this->handleUnconditionally = (bool) $value;
346
    }
347
348
    /**
349
     * Adds an editor resolver, identified by a string
350
     * name, and that may be a string path, or a callable
351
     * resolver. If the callable returns a string, it will
352
     * be set as the file reference's href attribute.
353
     *
354
     * @example
355
     *  $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
356
     * @example
357
     *   $run->addEditor('remove-it', function($file, $line) {
358
     *       unlink($file);
359
     *       return "http://stackoverflow.com";
360
     *   });
361
     * @param string $identifier
362
     * @param string $resolver
363
     */
364 1
    public function addEditor($identifier, $resolver)
365
    {
366 1
        $this->editors[$identifier] = $resolver;
367 1
    }
368
369
    /**
370
     * Set the editor to use to open referenced files, by a string
371
     * identifier, or a callable that will be executed for every
372
     * file reference, with a $file and $line argument, and should
373
     * return a string.
374
     *
375
     * @example
376
     *   $run->setEditor(function($file, $line) { return "file:///{$file}"; });
377
     * @example
378
     *   $run->setEditor('sublime');
379
     *
380
     * @throws InvalidArgumentException If invalid argument identifier provided
381
     * @param  string|callable          $editor
382
     */
383 4
    public function setEditor($editor)
384
    {
385 4
        if (!is_callable($editor) && !isset($this->editors[$editor])) {
386
            throw new InvalidArgumentException(
387
                "Unknown editor identifier: $editor. Known editors:" .
388
                implode(",", array_keys($this->editors))
389
            );
390
        }
391
392 4
        $this->editor = $editor;
393 4
    }
394
395
    /**
396
     * Given a string file path, and an integer file line,
397
     * executes the editor resolver and returns, if available,
398
     * a string that may be used as the href property for that
399
     * file reference.
400
     *
401
     * @throws InvalidArgumentException If editor resolver does not return a string
402
     * @param  string                   $filePath
403
     * @param  int                      $line
404
     * @return string|bool
405
     */
406 4
    public function getEditorHref($filePath, $line)
407
    {
408 4
        $editor = $this->getEditor($filePath, $line);
409
410 4
        if (empty($editor)) {
411
            return false;
412
        }
413
414
        // Check that the editor is a string, and replace the
415
        // %line and %file placeholders:
416 4
        if (!isset($editor['url']) || !is_string($editor['url'])) {
417
            throw new UnexpectedValueException(
418
                __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
419
            );
420
        }
421
422 4
        $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
423 4
        $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);
424
425 4
        return $editor['url'];
426
    }
427
428
    /**
429
     * Given a boolean if the editor link should
430
     * act as an Ajax request. The editor must be a
431
     * valid callable function/closure
432
     *
433
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
434
     * @param  string                   $filePath
435
     * @param  int                      $line
436
     * @return bool
437
     */
438 1
    public function getEditorAjax($filePath, $line)
439
    {
440 1
        $editor = $this->getEditor($filePath, $line);
441
442
        // Check that the ajax is a bool
443 1
        if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
444
            throw new UnexpectedValueException(
445
                __METHOD__ . " should always resolve to a bool; got something else instead."
446
            );
447
        }
448 1
        return $editor['ajax'];
449
    }
450
451
    /**
452
     * Given a boolean if the editor link should
453
     * act as an Ajax request. The editor must be a
454
     * valid callable function/closure
455
     *
456
     * @param  string $filePath
457
     * @param  int    $line
458
     * @return array
459
     */
460 1
    protected function getEditor($filePath, $line)
461
    {
462 1
        if (!$this->editor || (!is_string($this->editor) && !is_callable($this->editor))) {
463
            return [];
464
        }
465
466 1
        if (is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor])) {
467
           return [
468
                'ajax' => false,
469
                'url' => $this->editors[$this->editor],
470
            ];
471
        }
472
473 1
        if (is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor]))) {
474 1
            if (is_callable($this->editor)) {
475
                $callback = call_user_func($this->editor, $filePath, $line);
476
            } else {
477 1
                $callback = call_user_func($this->editors[$this->editor], $filePath, $line);
478
            }
479
480 1
            if (is_string($callback)) {
481
                return [
482 1
                    'ajax' => false,
483 1
                    'url' => $callback,
484 1
                ];
485
            }
486
487
            return [
488
                'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
489
                'url' => isset($callback['url']) ? $callback['url'] : $callback,
490
            ];
491
        }
492
493
        return [];
494
    }
495
496
    /**
497
     * @param  string $title
498
     * @return void
499
     */
500 1
    public function setPageTitle($title)
501
    {
502 1
        $this->pageTitle = (string) $title;
503 1
    }
504
505
    /**
506
     * @return string
507
     */
508 1
    public function getPageTitle()
509
    {
510 1
        return $this->pageTitle;
511
    }
512
513
    /**
514
     * Adds a path to the list of paths to be searched for
515
     * resources.
516
     *
517
     * @throws InvalidArgumentException If $path is not a valid directory
518
     *
519
     * @param  string $path
520
     * @return void
521
     */
522 2
    public function addResourcePath($path)
523
    {
524 2
        if (!is_dir($path)) {
525 1
            throw new InvalidArgumentException(
526 1
                "'$path' is not a valid directory"
527 1
            );
528
        }
529
530 1
        array_unshift($this->searchPaths, $path);
531 1
    }
532
533
    /**
534
     * Adds a custom css file to be loaded.
535
     *
536
     * @param  string $name
537
     * @return void
538
     */
539
    public function addCustomCss($name)
540
    {
541
        $this->customCss = $name;
542
    }
543
544
    /**
545
     * @return array
546
     */
547 1
    public function getResourcePaths()
548
    {
549 1
        return $this->searchPaths;
550
    }
551
552
    /**
553
     * Finds a resource, by its relative path, in all available search paths.
554
     * The search is performed starting at the last search path, and all the
555
     * way back to the first, enabling a cascading-type system of overrides
556
     * for all resources.
557
     *
558
     * @throws RuntimeException If resource cannot be found in any of the available paths
559
     *
560
     * @param  string $resource
561
     * @return string
562
     */
563
    protected function getResource($resource)
564
    {
565
        // If the resource was found before, we can speed things up
566
        // by caching its absolute, resolved path:
567
        if (isset($this->resourceCache[$resource])) {
568
            return $this->resourceCache[$resource];
569
        }
570
571
        // Search through available search paths, until we find the
572
        // resource we're after:
573
        foreach ($this->searchPaths as $path) {
574
            $fullPath = $path . "/$resource";
575
576
            if (is_file($fullPath)) {
577
                // Cache the result:
578
                $this->resourceCache[$resource] = $fullPath;
579
                return $fullPath;
580
            }
581
        }
582
583
        // If we got this far, nothing was found.
584
        throw new RuntimeException(
585
            "Could not find resource '$resource' in any resource paths."
586
            . "(searched: " . join(", ", $this->searchPaths). ")"
587
        );
588
    }
589
590
    /**
591
     * @deprecated
592
     *
593
     * @return string
594
     */
595
    public function getResourcesPath()
596
    {
597
        $allPaths = $this->getResourcePaths();
598
599
        // Compat: return only the first path added
600
        return end($allPaths) ?: null;
601
    }
602
603
    /**
604
     * @deprecated
605
     *
606
     * @param  string $resourcesPath
607
     * @return void
608
     */
609
    public function setResourcesPath($resourcesPath)
610
    {
611
        $this->addResourcePath($resourcesPath);
612
    }
613
614
    /**
615
     * Return the application paths.
616
     *
617
     * @return array
618
     */
619
    public function getApplicationPaths()
620
    {
621
        return $this->applicationPaths;
622
    }
623
624
    /**
625
     * Set the application paths.
626
     *
627
     * @param array $applicationPaths
628
     */
629
    public function setApplicationPaths($applicationPaths)
630
    {
631
        $this->applicationPaths = $applicationPaths;
632
    }
633
    
634
    /**
635
     * blacklist a sensitive value within one of the superglobal arrays.
636
     *
637
     * @param $superGlobalName string the name of the superglobal array, e.g. '_GET'
638
     * @param $key string the key within the superglobal
639
     */
640 1
    public function blacklist($superGlobalName, $key) {
641 1
        $this->blacklist[$superGlobalName][] = $key;
642 1
    }
643
644
    /**
645
     * Checks all given values against the given list of blacklisted values.
646
     * Blacklisted values will be replaced by a equal length string cointaining only '*' characters.
647
     *
648
     * @param array $values a array of values
649
     * @param string[] $blacklisted
650
     * @return array $values without sensitive data
651
     */
652
    private function maskBlacklisted(array $values, array $blacklisted) {
653
        foreach($blacklisted as $key) {
654
            if (isset($values[$key])) {
655
                $values[$key] = str_repeat('*', strlen($values[$key]));
656
            }
657
        }
658
        return $values;
659
    }    
660
}
661