aboutsummaryrefslogtreecommitdiff
path: root/lib/Favicon/Favicon.php
blob: 7e6c42d6e9e7adf68ce4296d42c1a0f3c5f9a0df (plain)
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
<?php

namespace Favicon;

class Favicon
{
    protected static $TYPE_CACHE_URL = 'url';
    protected static $TYPE_CACHE_IMG = 'img';
    protected $url = '';
    protected $cacheDir;
    protected $cacheTimeout;
    protected $dataAccess;

    public function __construct($args = array())
    {
        if (isset($args['url'])) {
            $this->url = $args['url'];
        }
        
        $this->cacheDir = __DIR__ . '/../../resources/cache';
        $this->cacheTimeout = 604800;
        $this->dataAccess = new DataAccess();
    }

    /**
     * Set cache settings:
     *   - dir: cache directory
     *   - timeout: in seconds
     *
     * @param array $args
     */
    public function cache($args = array()) {
        if (isset($args['dir'])) {
            $this->cacheDir = $args['dir'];
        }

        if (!empty($args['timeout'])) {
            $this->cacheTimeout = $args['timeout'];
        }
    }

    public static function baseUrl($url, $path = false)
    {
        $return = '';

        if (!$url = parse_url($url)) {
            return FALSE;
        }

        // Scheme
        $scheme = isset($url['scheme']) ? strtolower($url['scheme']) : null;
        if ($scheme != 'http' && $scheme != 'https') {

            return FALSE;
        }
        $return .= "{$scheme}://";

        // Username and password
        if (isset($url['user'])) {
            $return .= $url['user'];
            if (isset($url['pass'])) {
                $return .= ":{$url['pass']}";
            }
            $return .= '@';
        }

        // Hostname
        if( !isset($url['host']) ) {
            return FALSE;
        }
        
        $return .= $url['host'];

        // Port
        if (isset($url['port'])) {
            $return .= ":{$url['port']}";
        }

        // Path
        if( $path && isset($url['path']) ) {
            $return .= $url['path'];
        }
        $return .= '/';

        return $return;    
    }

    public function info($url)
    {
        if(empty($url) || $url === false) {
            return false;
        }
        
        $max_loop = 5;
        
        // Discover real status by following redirects. 
        $loop = TRUE;
        while ($loop && $max_loop-- > 0) {
            $headers = $this->dataAccess->retrieveHeader($url);
            if (empty($headers)) {
                return false;
            }
            $exploded = explode(' ', $headers[0]);
            
            if( !isset($exploded[1]) ) { 
                return false;
            }
            list(,$status) = $exploded;
            
            switch ($status) {
                case '301':
                case '302':
                    $url = isset($headers['location']) ? $headers['location'] : '';
                    break;
                default:
                    $loop = FALSE;
                    break;
            }
        }

        return array('status' => $status, 'url' => $url);
    }
    
    public function endRedirect($url) {
        $out = $this->info($url);
        return !empty($out['url']) ? $out['url'] : false;
    }

    /**
     * Find remote (or cached) favicon
     *
     * @param string $url  to look for a favicon
     * @param int    $type type of retrieval (FaviconDLType):
     *                       - HOTLINK_URL: returns remote URL
     *                       - DL_FILE_PATH: returns file path of the favicon downloaded locally
     *                       - RAW_IMAGE: returns the favicon image binary string
     *
     * @return string|bool favicon URL, false if nothing was found
     */
    public function get($url = '', $type = FaviconDLType::HOTLINK_URL)
    {
        // URLs passed to this method take precedence.
        if (!empty($url)) {
            $this->url = $url;
        }

        // Get the base URL without the path for clearer concatenations.
        $url = rtrim($this->baseUrl($this->url, true), '/');
        $original = $url;
        if (($favicon = $this->checkCache($original, self::$TYPE_CACHE_URL)) === false
            && ! $favicon = $this->getFavicon($original, false)
        ) {
            $url = rtrim($this->endRedirect($this->baseUrl($this->url, false)), '/');
            if (($favicon = $this->checkCache($url, self::$TYPE_CACHE_URL)) === false
                && ! $favicon = $this->getFavicon($url)
            ) {
                $url = $original;
            }
        }

        $this->saveCache($url, $favicon, self::$TYPE_CACHE_URL);

        switch ($type) {
            case FaviconDLType::DL_FILE_PATH:
                return $this->getImage($url, $favicon, false);
            case FaviconDLType::RAW_IMAGE:
                return $this->getImage($url, $favicon, true);
            case FaviconDLType::HOTLINK_URL:
            default:
                return empty($favicon) ? false : $favicon;
        }
    }
    
    private function getFavicon($url, $checkDefault = true) {
        $favicon = false;
        
        if(empty($url)) {
            return false;
        }
        
        // Try /favicon.ico first.
        if( $checkDefault ) {
            $info = $this->info("{$url}/favicon.ico");
            if ($info['status'] == '200') {
                $favicon = $info['url'];
            }
        }

        // See if it's specified in a link tag in domain url.
        if (!$favicon) {
            $favicon = $this->getInPage($url);
        }
        
        // Make sure the favicon is an absolute URL.
        if( $favicon && filter_var($favicon, FILTER_VALIDATE_URL) === false ) {
            $favicon = $url . '/' . $favicon;
        }

        // Sometimes people lie, so check the status.
        // And sometimes, it's not even an image. Sneaky bastards!
        // If cacheDir isn't writable, that's not our problem
        if ($favicon && is_writable($this->cacheDir) && extension_loaded('fileinfo') && !$this->checkImageMType($favicon)) {
            $favicon = false;
        }

        return $favicon;
    }

    /**
     * Find remote favicon and return it as an image
     */
    private function getImage($url, $faviconUrl = '', $image = false)
    {
        if (empty($faviconUrl)) {
            return false;
        }

        $favicon = $this->checkCache($url, self::$TYPE_CACHE_IMG);
        // Favicon not found in the cache
        if( $favicon === false ) {
            $favicon = $this->dataAccess->retrieveUrl($faviconUrl);
            // Definitely not found
            if (!$this->checkImageMTypeContent($favicon)) {
                return false;
            } else {
                $this->saveCache($url, $favicon, self::$TYPE_CACHE_IMG);
            }
        }

        if( $image ) {
            return $favicon;
        }
        else
            return self::$TYPE_CACHE_IMG . md5($url);
    }

    /**
     * Display data as a PNG Favicon, then exit
     * @param $data
     */
    private function displayFavicon($data) {
        header('Content-Type: image/png');
        header('Cache-Control: private, max-age=10800, pre-check=10800');
        header('Pragma: private');
        header('Expires: ' . date(DATE_RFC822,strtotime('7 day')));
        echo $data;
        exit;
    }

    private function getInPage($url) {
        $html = $this->dataAccess->retrieveUrl("{$url}/");
        preg_match('!<head.*?>.*</head>!ims', $html, $match);
        
        if(empty($match) || count($match) == 0) {
            return false;
        }
        
        $head = $match[0];
        
        $dom = new \DOMDocument();
        // Use error suppression, because the HTML might be too malformed.
        if (@$dom->loadHTML($head)) {
            $links = $dom->getElementsByTagName('link');
            foreach ($links as $link) {
                if ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'shortcut icon') {
                    return $link->getAttribute('href');
                } elseif ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'icon') {
                    return $link->getAttribute('href');
                } elseif ($link->hasAttribute('href') && strpos($link->getAttribute('href'), 'favicon') !== FALSE) {
                    return $link->getAttribute('href');
                }
            }
        }
        return false;
    }

    private function checkCache($url, $type) {
        if ($this->cacheTimeout) {
            $cache = $this->cacheDir . '/'. $type . md5($url);
            if (file_exists($cache) && is_readable($cache)
                && ($this->cacheTimeout === -1 || time() - filemtime($cache) < $this->cacheTimeout)
            ) {
                return $this->dataAccess->readCache($cache);
            }
        }
        return false;
    }

    /**
     * Will save data in cacheDir if the directory writable and any previous cache is expired (cacheTimeout)
     * @param $url
     * @param $data
     * @param $type
     * @return string cache file path
     */
    private function saveCache($url, $data, $type) {
        // Save cache if necessary
        $cache = $this->cacheDir . '/'. $type . md5($url);
        if ($this->cacheTimeout && !file_exists($cache)
            || (is_writable($cache) && $this->cacheTimeout !== -1 && time() - filemtime($cache) > $this->cacheTimeout)
        ) {
            $this->dataAccess->saveCache($cache, $data);
        }
        return $cache;
    }

    private function checkImageMType($url) {
        
        $fileContent = $this->dataAccess->retrieveUrl($url);
        
        return $this->checkImageMTypeContent($fileContent);
    }

    private function checkImageMTypeContent($content) {
        if(empty($content)) return false;

        $isImage = true;
        try {
            $fInfo = finfo_open(FILEINFO_MIME_TYPE);
            $isImage = strpos(finfo_buffer($fInfo, $content), 'image') !== false;
            finfo_close($fInfo);
        } catch (Exception $e) {
        }

        return $isImage;
    }
    
    /**
     * @return mixed
     */
    public function getCacheDir()
    {
        return $this->cacheDir;
    }

    /**
     * @param mixed $cacheDir
     */
    public function setCacheDir($cacheDir)
    {
        $this->cacheDir = $cacheDir;
    }

    /**
     * @return mixed
     */
    public function getCacheTimeout()
    {
        return $this->cacheTimeout;
    }

    /**
     * @param mixed $cacheTimeout
     */
    public function setCacheTimeout($cacheTimeout)
    {
        $this->cacheTimeout = $cacheTimeout;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @param string $url
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * @param DataAccess|\PHPUnit_Framework_MockObject_MockObject $dataAccess
     */
    public function setDataAccess($dataAccess)
    {
        $this->dataAccess = $dataAccess;
    }
}