Favicon.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <?php
  2. namespace Favicon;
  3. class Favicon
  4. {
  5. protected static $TYPE_CACHE_URL = 'url';
  6. protected static $TYPE_CACHE_IMG = 'img';
  7. protected $url = '';
  8. protected $cacheDir;
  9. protected $cacheTimeout;
  10. protected $dataAccess;
  11. public function __construct($args = array())
  12. {
  13. if (isset($args['url'])) {
  14. $this->url = $args['url'];
  15. }
  16. $this->cacheDir = __DIR__ . '/../../resources/cache';
  17. $this->cacheTimeout = 604800;
  18. $this->dataAccess = new DataAccess();
  19. }
  20. /**
  21. * Set cache settings:
  22. * - dir: cache directory
  23. * - timeout: in seconds
  24. *
  25. * @param array $args
  26. */
  27. public function cache($args = array()) {
  28. if (isset($args['dir'])) {
  29. $this->cacheDir = $args['dir'];
  30. }
  31. if (!empty($args['timeout'])) {
  32. $this->cacheTimeout = $args['timeout'];
  33. }
  34. }
  35. public static function baseUrl($url, $path = false)
  36. {
  37. $return = '';
  38. if (!$url = parse_url($url)) {
  39. return FALSE;
  40. }
  41. // Scheme
  42. $scheme = isset($url['scheme']) ? strtolower($url['scheme']) : null;
  43. if ($scheme != 'http' && $scheme != 'https') {
  44. return FALSE;
  45. }
  46. $return .= "{$scheme}://";
  47. // Username and password
  48. if (isset($url['user'])) {
  49. $return .= $url['user'];
  50. if (isset($url['pass'])) {
  51. $return .= ":{$url['pass']}";
  52. }
  53. $return .= '@';
  54. }
  55. // Hostname
  56. if( !isset($url['host']) ) {
  57. return FALSE;
  58. }
  59. $return .= $url['host'];
  60. // Port
  61. if (isset($url['port'])) {
  62. $return .= ":{$url['port']}";
  63. }
  64. // Path
  65. if( $path && isset($url['path']) ) {
  66. $return .= $url['path'];
  67. }
  68. $return .= '/';
  69. return $return;
  70. }
  71. public function info($url)
  72. {
  73. if(empty($url) || $url === false) {
  74. return false;
  75. }
  76. $max_loop = 5;
  77. // Discover real status by following redirects.
  78. $loop = TRUE;
  79. while ($loop && $max_loop-- > 0) {
  80. $headers = $this->dataAccess->retrieveHeader($url);
  81. if (empty($headers)) {
  82. return false;
  83. }
  84. $exploded = explode(' ', $headers[0]);
  85. if( !isset($exploded[1]) ) {
  86. return false;
  87. }
  88. list(,$status) = $exploded;
  89. switch ($status) {
  90. case '301':
  91. case '302':
  92. $url = isset($headers['location']) ? $headers['location'] : '';
  93. if (is_array($url)) {
  94. $url = end($url);
  95. }
  96. break;
  97. default:
  98. $loop = FALSE;
  99. break;
  100. }
  101. }
  102. return array('status' => $status, 'url' => $url);
  103. }
  104. public function endRedirect($url) {
  105. $out = $this->info($url);
  106. return !empty($out['url']) ? $out['url'] : false;
  107. }
  108. /**
  109. * Find remote (or cached) favicon
  110. *
  111. * @param string $url to look for a favicon
  112. * @param int $type type of retrieval (FaviconDLType):
  113. * - HOTLINK_URL: returns remote URL
  114. * - DL_FILE_PATH: returns file path of the favicon downloaded locally
  115. * - RAW_IMAGE: returns the favicon image binary string
  116. *
  117. * @return string|bool favicon URL, false if nothing was found
  118. */
  119. public function get($url = '', $type = FaviconDLType::HOTLINK_URL)
  120. {
  121. // URLs passed to this method take precedence.
  122. if (!empty($url)) {
  123. $this->url = $url;
  124. }
  125. // Get the base URL without the path for clearer concatenations.
  126. $url = rtrim($this->baseUrl($this->url, true), '/');
  127. $original = $url;
  128. if (($favicon = $this->checkCache($original, self::$TYPE_CACHE_URL)) === false
  129. && ! $favicon = $this->getFavicon($original, false)
  130. ) {
  131. $url = rtrim($this->endRedirect($this->baseUrl($this->url, false)), '/');
  132. if (($favicon = $this->checkCache($url, self::$TYPE_CACHE_URL)) === false
  133. && ! $favicon = $this->getFavicon($url)
  134. ) {
  135. $url = $original;
  136. }
  137. }
  138. $this->saveCache($url, $favicon, self::$TYPE_CACHE_URL);
  139. switch ($type) {
  140. case FaviconDLType::DL_FILE_PATH:
  141. return $this->getImage($url, $favicon, false);
  142. case FaviconDLType::RAW_IMAGE:
  143. return $this->getImage($url, $favicon, true);
  144. case FaviconDLType::HOTLINK_URL:
  145. default:
  146. return empty($favicon) ? false : $favicon;
  147. }
  148. }
  149. private function getFavicon($url, $checkDefault = true) {
  150. $favicon = false;
  151. if(empty($url)) {
  152. return false;
  153. }
  154. // Try /favicon.ico first.
  155. if( $checkDefault ) {
  156. $info = $this->info("{$url}/favicon.ico");
  157. if ($info['status'] == '200') {
  158. $favicon = $info['url'];
  159. }
  160. }
  161. // See if it's specified in a link tag in domain url.
  162. if (!$favicon) {
  163. $favicon = trim($this->getInPage($url));
  164. }
  165. if (substr($favicon, 0, 2) === '//') {
  166. $favicon = 'https:' . $favicon;
  167. }
  168. // Make sure the favicon is an absolute URL.
  169. if( $favicon && filter_var($favicon, FILTER_VALIDATE_URL) === false ) {
  170. $favicon = $url . '/' . $favicon;
  171. }
  172. // Sometimes people lie, so check the status.
  173. // And sometimes, it's not even an image. Sneaky bastards!
  174. // If cacheDir isn't writable, that's not our problem
  175. if ($favicon && is_writable($this->cacheDir) && extension_loaded('fileinfo') && !$this->checkImageMType($favicon)) {
  176. $favicon = false;
  177. }
  178. return $favicon;
  179. }
  180. /**
  181. * Find remote favicon and return it as an image
  182. */
  183. private function getImage($url, $faviconUrl = '', $image = false)
  184. {
  185. if (empty($faviconUrl)) {
  186. return false;
  187. }
  188. $favicon = $this->checkCache($url, self::$TYPE_CACHE_IMG);
  189. // Favicon not found in the cache
  190. if( $favicon === false ) {
  191. $favicon = $this->dataAccess->retrieveUrl($faviconUrl);
  192. // Definitely not found
  193. if (!$this->checkImageMTypeContent($favicon)) {
  194. return false;
  195. } else {
  196. $this->saveCache($url, $favicon, self::$TYPE_CACHE_IMG);
  197. }
  198. }
  199. if( $image ) {
  200. return $favicon;
  201. }
  202. else
  203. return self::$TYPE_CACHE_IMG . md5($url);
  204. }
  205. /**
  206. * Display data as a PNG Favicon, then exit
  207. * @param $data
  208. */
  209. private function displayFavicon($data) {
  210. header('Content-Type: image/png');
  211. header('Cache-Control: private, max-age=10800, pre-check=10800');
  212. header('Pragma: private');
  213. header('Expires: ' . date(DATE_RFC822,strtotime('7 day')));
  214. echo $data;
  215. exit;
  216. }
  217. private function getInPage($url) {
  218. $html = $this->dataAccess->retrieveUrl("{$url}/");
  219. preg_match('!<head.*?>.*</head>!ims', $html, $match);
  220. if(empty($match) || count($match) == 0) {
  221. return false;
  222. }
  223. $head = $match[0];
  224. $dom = new \DOMDocument();
  225. // Use error suppression, because the HTML might be too malformed.
  226. if (@$dom->loadHTML($head)) {
  227. $links = $dom->getElementsByTagName('link');
  228. foreach ($links as $link) {
  229. if ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'shortcut icon') {
  230. return $link->getAttribute('href');
  231. }
  232. }
  233. foreach ($links as $link) {
  234. if ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'icon') {
  235. return $link->getAttribute('href');
  236. }
  237. }
  238. foreach ($links as $link) {
  239. if ($link->hasAttribute('href') && strpos($link->getAttribute('href'), 'favicon') !== FALSE) {
  240. return $link->getAttribute('href');
  241. }
  242. }
  243. }
  244. return false;
  245. }
  246. private function checkCache($url, $type) {
  247. if ($this->cacheTimeout) {
  248. $cache = $this->cacheDir . '/'. $type . md5($url);
  249. if (file_exists($cache) && is_readable($cache)
  250. && ($this->cacheTimeout === -1 || time() - filemtime($cache) < $this->cacheTimeout)
  251. ) {
  252. return $this->dataAccess->readCache($cache);
  253. }
  254. }
  255. return false;
  256. }
  257. /**
  258. * Will save data in cacheDir if the directory writable and any previous cache is expired (cacheTimeout)
  259. * @param $url
  260. * @param $data
  261. * @param $type
  262. * @return string cache file path
  263. */
  264. private function saveCache($url, $data, $type) {
  265. // Save cache if necessary
  266. $cache = $this->cacheDir . '/'. $type . md5($url);
  267. if ($this->cacheTimeout && !file_exists($cache)
  268. || (is_writable($cache) && $this->cacheTimeout !== -1 && time() - filemtime($cache) > $this->cacheTimeout)
  269. ) {
  270. $this->dataAccess->saveCache($cache, $data);
  271. }
  272. return $cache;
  273. }
  274. private function checkImageMType($url) {
  275. $fileContent = $this->dataAccess->retrieveUrl($url);
  276. return $this->checkImageMTypeContent($fileContent);
  277. }
  278. private function checkImageMTypeContent($content) {
  279. if(empty($content)) return false;
  280. $isImage = true;
  281. try {
  282. $fInfo = finfo_open(FILEINFO_MIME_TYPE);
  283. $isImage = strpos(finfo_buffer($fInfo, $content), 'image') !== false;
  284. finfo_close($fInfo);
  285. } catch (\Exception $e) {
  286. error_log('Favicon checkImageMTypeContent error: ' . $e->getMessage());
  287. }
  288. return $isImage;
  289. }
  290. /**
  291. * @return mixed
  292. */
  293. public function getCacheDir()
  294. {
  295. return $this->cacheDir;
  296. }
  297. /**
  298. * @param mixed $cacheDir
  299. */
  300. public function setCacheDir($cacheDir)
  301. {
  302. $this->cacheDir = $cacheDir;
  303. }
  304. /**
  305. * @return mixed
  306. */
  307. public function getCacheTimeout()
  308. {
  309. return $this->cacheTimeout;
  310. }
  311. /**
  312. * @param mixed $cacheTimeout
  313. */
  314. public function setCacheTimeout($cacheTimeout)
  315. {
  316. $this->cacheTimeout = $cacheTimeout;
  317. }
  318. /**
  319. * @return string
  320. */
  321. public function getUrl()
  322. {
  323. return $this->url;
  324. }
  325. /**
  326. * @param string $url
  327. */
  328. public function setUrl($url)
  329. {
  330. $this->url = $url;
  331. }
  332. /**
  333. * @param DataAccess|\PHPUnit_Framework_MockObject_MockObject $dataAccess
  334. */
  335. public function setDataAccess($dataAccess)
  336. {
  337. $this->dataAccess = $dataAccess;
  338. }
  339. }