Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
ExecutiveReportChartDoctor
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 3
930
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
342
 probe
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
110
 report
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace App\Console\Commands;
4
5use App\Services\ExecutiveReportChartService;
6use Illuminate\Console\Command;
7
8/**
9 * Diagnose why the weekly executive report's charts are not appearing.
10 *
11 * The charts are PNGs rendered with GD and attached inline (cid:). When GD, its
12 * FreeType support or the font is missing on a host, the renderer returns an empty
13 * string and the section falls back to its HTML figure strip — the email arrives
14 * with titles and numbers but no charts, which is indistinguishable from a mail
15 * client blocking images. This command tells you which of those it is, on the box
16 * that actually sends the report.
17 *
18 *   php artisan report:chart-doctor
19 */
20class ExecutiveReportChartDoctor extends Command
21{
22    protected $signature = 'report:chart-doctor {--out= : Write a sample PNG here to eyeball the output}';
23
24    protected $description = 'Check whether this host can render the weekly report charts (GD + FreeType + font).';
25
26    public function handle(): int
27    {
28        $service = new ExecutiveReportChartService;
29
30        $this->line('PHP            : '.PHP_VERSION);
31        $this->line('gd loaded      : '.(extension_loaded('gd') ? 'yes' : 'NO'));
32        $this->line('imagettftext   : '.(function_exists('imagettftext') ? 'yes' : 'NO  (GD built without FreeType)'));
33        $this->line('imagescale     : '.(function_exists('imagescale') ? 'yes' : 'NO'));
34
35        if (extension_loaded('gd') && function_exists('gd_info')) {
36            $info = gd_info();
37            $this->line('FreeType       : '.(($info['FreeType Support'] ?? false) ? 'yes' : 'NO'));
38            $this->line('PNG support    : '.(($info['PNG Support'] ?? false) ? 'yes' : 'NO'));
39        }
40
41        $font = resource_path('fonts/DejaVuSans.ttf');
42        $this->line('font (resources): '.(is_readable($font) ? 'readable' : 'MISSING at '.$font));
43        $vendorFont = base_path('vendor/dompdf/dompdf/lib/fonts/DejaVuSans.ttf');
44        $this->line('font (fallback) : '.(is_readable($vendorFont) ? 'readable' : 'missing'));
45
46        $missing = $service->missingPrerequisite();
47        $this->newLine();
48
49        if ($missing !== null) {
50            $this->error('Charts CANNOT be rendered on this host: '.$missing);
51            $this->line('On Amazon Linux the usual fix is to install the GD extension with FreeType');
52            $this->line('and restart php-fpm. Until then the report sends with the figure strip only.');
53
54            return self::FAILURE;
55        }
56
57        // Actually render, so a subtly broken GD (present but erroring) is caught
58        // rather than merely reported as "prerequisites met".
59        $points = [];
60        foreach ([120, 180, 90, 210, 160] as $i => $v) {
61            $points[] = [
62                'week' => $i + 2,
63                'value' => (float) $v,
64                'pct' => $i === 0 ? null : ($v - 150) / 150 * 100,
65                'in_progress' => $i === 4,
66                'note' => $i === 2 ? 'Prueba' : null,
67            ];
68        }
69
70        $png = $service->renderSeries($points, 152.0, 'num');
71
72        if ($png === '' || substr($png, 0, 8) !== "\x89PNG\r\n\x1a\n") {
73            $this->error('Prerequisites look fine but rendering produced no valid PNG.');
74            $this->newLine();
75            $this->probe();
76
77            return self::FAILURE;
78        }
79
80        $this->info('Charts render correctly here ('.number_format(strlen($png)).' bytes).');
81
82        $filter = ExecutiveReportChartService::lastScaleFilter();
83        $this->line('downscale filter : '.($filter ?? 'none (unscaled)'));
84        if ($filter !== 'IMG_BICUBIC') {
85            $this->warn('This host rejected IMG_BICUBIC, so charts are softer than on a host that accepts it.');
86            $this->line('Harmless for correctness — the figures and layout are identical — but it explains');
87            $this->line('why the same chart is a different size here than elsewhere.');
88        }
89
90        if ($this->option('out')) {
91            file_put_contents($this->option('out'), $png);
92            $this->line('Sample written to '.$this->option('out'));
93        }
94
95        $this->newLine();
96        $this->line('If the charts still do not appear in the delivered email, the cause is');
97        $this->line('downstream of rendering — most likely the mail client suppressing inline');
98        $this->line('(cid:) images. Check the raw message source for the image/png parts.');
99
100        return self::SUCCESS;
101    }
102
103    /**
104     * Run each GD operation the renderer depends on, individually, capturing any
105     * warning each one emits.
106     *
107     * "Prerequisites present but no valid PNG" has two very different causes and
108     * they need different fixes: an operation returning false (a GD build that
109     * cannot do that particular thing), or stray output landing in the buffer
110     * ahead of the PNG bytes (a warning printed by php-cli with display_errors on,
111     * which corrupts the image). This tells them apart.
112     */
113    private function probe(): void
114    {
115        $this->line('Step-by-step probe:');
116
117        $warnings = [];
118        set_error_handler(function ($no, $str) use (&$warnings) {
119            $warnings[] = $str;
120
121            return true;
122        });
123
124        try {
125            $scale = 2;
126            $w = 400 * $scale;
127            $h = 200 * $scale;
128
129            $im = imagecreatetruecolor($w, $h);
130            $this->report('imagecreatetruecolor('.$w.'x'.$h.')', $im !== false);
131            if ($im === false) {
132                return;
133            }
134
135            $white = imagecolorallocate($im, 255, 255, 255);
136            $this->report('imagecolorallocate', $white !== false);
137            $this->report('imagefill', imagefill($im, 0, 0, $white));
138
139            imagesetthickness($im, 3 * $scale);
140            $this->report('imageline (thick)', imageline($im, 10, 10, $w - 10, $h - 10, $white));
141            imagesetthickness($im, 1);
142
143            $this->report('imagefilledellipse', imagefilledellipse($im, 50, 50, 10, 10, $white));
144
145            $font = resource_path('fonts/DejaVuSans.ttf');
146            $bbox = imagettfbbox(9 * $scale, 0, $font, 'Prueba 123');
147            $this->report('imagettfbbox', $bbox !== false);
148            $ttf = imagettftext($im, 9 * $scale, 0, 20, 40, $white, $font, 'Prueba 123');
149            $this->report('imagettftext', $ttf !== false);
150            $rot = imagettftext($im, 8 * $scale, 90, 40, 80, $white, $font, '+12%');
151            $this->report('imagettftext (rotated 90)', $rot !== false);
152
153            // The renderer's most fragile call: some libgd builds fail or return
154            // false for IMG_BICUBIC on larger canvases.
155            foreach (['IMG_BICUBIC' => IMG_BICUBIC, 'IMG_BILINEAR_FIXED' => IMG_BILINEAR_FIXED, 'IMG_NEAREST_NEIGHBOUR' => IMG_NEAREST_NEIGHBOUR] as $name => $mode) {
156                $scaled = imagescale($im, 400, 200, $mode);
157                $this->report('imagescale '.$name, $scaled !== false);
158                if ($scaled !== false) {
159                    imagedestroy($scaled);
160                }
161            }
162
163            // Does imagepng write clean bytes, or does something pollute the buffer?
164            ob_start();
165            $pngOk = imagepng($im, null, 9);
166            $bytes = (string) ob_get_clean();
167            $this->report('imagepng', $pngOk !== false);
168            $this->line('    bytes captured : '.number_format(strlen($bytes)));
169            $this->line('    first 8 bytes  : '.strtoupper(bin2hex(substr($bytes, 0, 8))).'  (expected 89504E470D0A1A0A)');
170            if (strlen($bytes) > 0 && substr($bytes, 0, 8) !== "\x89PNG\r\n\x1a\n") {
171                $lead = substr($bytes, 0, min(200, strpos($bytes, "\x89PNG") ?: 200));
172                $this->warn('    Buffer is polluted. Leading text: '.trim($lead));
173            }
174
175            imagedestroy($im);
176        } finally {
177            restore_error_handler();
178        }
179
180        $this->newLine();
181        $this->line('display_errors (cli) : '.var_export(ini_get('display_errors'), true));
182        $this->line('error_reporting      : '.error_reporting());
183        $this->line('memory_limit         : '.ini_get('memory_limit'));
184        $this->line('open_basedir         : '.(ini_get('open_basedir') ?: '(none)'));
185
186        if ($warnings !== []) {
187            $this->newLine();
188            $this->warn('Warnings emitted during the probe:');
189            foreach (array_unique($warnings) as $wmsg) {
190                $this->line('  - '.$wmsg);
191            }
192        }
193    }
194
195    private function report(string $label, bool $ok): void
196    {
197        $this->line('  '.str_pad($label, 30).($ok ? 'ok' : 'FAILED'));
198    }
199}