Favicon.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. $exploded = explode(' ', $headers[0]);
  82. if( !isset($exploded[1]) ) {
  83. return false;
  84. }
  85. list(,$status) = $exploded;
  86. switch ($status) {
  87. case '301':
  88. case '302':
  89. $url = $headers['Location'];
  90. break;
  91. default:
  92. $loop = FALSE;
  93. break;
  94. }
  95. }
  96. return array('status' => $status, 'url' => $url);
  97. }
  98. public function endRedirect($url) {
  99. $out = $this->info($url);
  100. return !empty($out['url']) ? $out['url'] : false;
  101. }
  102. /**
  103. * Find remote (or cached) favicon
  104. *
  105. * @param string $url to look for a favicon
  106. * @param int $type type of retrieval (FaviconDLType):
  107. * - HOTLINK_URL: returns remote URL
  108. * - DL_FILE_PATH: returns file path of the favicon downloaded locally
  109. * - RAW_IMAGE: returns the favicon image binary string
  110. *
  111. * @return string|bool favicon URL, false if nothing was found
  112. */
  113. public function get($url = '', $type = FaviconDLType::HOTLINK_URL)
  114. {
  115. // URLs passed to this method take precedence.
  116. if (!empty($url)) {
  117. $this->url = $url;
  118. }
  119. // Get the base URL without the path for clearer concatenations.
  120. $url = rtrim($this->baseUrl($this->url, true), '/');
  121. $original = $url;
  122. if (($favicon = $this->checkCache($original, self::$TYPE_CACHE_URL)) === false
  123. && ! $favicon = $this->getFavicon($original, false)
  124. ) {
  125. $url = rtrim($this->endRedirect($this->baseUrl($this->url, false)), '/');
  126. if (($favicon = $this->checkCache($url, self::$TYPE_CACHE_URL)) === false
  127. && ! $favicon = $this->getFavicon($url)
  128. ) {
  129. $url = $original;
  130. }
  131. }
  132. $this->saveCache($url, $favicon, self::$TYPE_CACHE_URL);
  133. switch ($type) {
  134. case FaviconDLType::DL_FILE_PATH:
  135. return $this->getImage($url, $favicon, false);
  136. case FaviconDLType::RAW_IMAGE:
  137. return $this->getImage($url, $favicon, true);
  138. case FaviconDLType::HOTLINK_URL:
  139. default:
  140. return empty($favicon) ? false : $favicon;
  141. }
  142. }
  143. private function getFavicon($url, $checkDefault = true) {
  144. $favicon = false;
  145. if(empty($url)) {
  146. return false;
  147. }
  148. // Try /favicon.ico first.
  149. if( $checkDefault ) {
  150. $info = $this->info("{$url}/favicon.ico");
  151. if ($info['status'] == '200') {
  152. $favicon = $info['url'];
  153. }
  154. }
  155. // See if it's specified in a link tag in domain url.
  156. if (!$favicon) {
  157. $favicon = $this->getInPage($url);
  158. }
  159. // Make sure the favicon is an absolute URL.
  160. if( $favicon && filter_var($favicon, FILTER_VALIDATE_URL) === false ) {
  161. $favicon = $url . '/' . $favicon;
  162. }
  163. // Sometimes people lie, so check the status.
  164. // And sometimes, it's not even an image. Sneaky bastards!
  165. // If cacheDir isn't writable, that's not our problem
  166. if ($favicon && is_writable($this->cacheDir) && !$this->checkImageMType($favicon)) {
  167. $favicon = false;
  168. }
  169. return $favicon;
  170. }
  171. /**
  172. * Find remote favicon and return it as an image
  173. */
  174. private function getImage($url, $faviconUrl = '', $image = false)
  175. {
  176. if (empty($faviconUrl)) {
  177. return false;
  178. }
  179. $favicon = $this->checkCache($url, self::$TYPE_CACHE_IMG);
  180. // Favicon not found in the cache
  181. if( $favicon === false ) {
  182. $favicon = $this->dataAccess->retrieveUrl($faviconUrl);
  183. // Definitely not found
  184. if (!$this->checkImageMTypeContent($favicon)) {
  185. return false;
  186. } else {
  187. $this->saveCache($url, $favicon, self::$TYPE_CACHE_IMG);
  188. }
  189. }
  190. if( $image ) {
  191. return $favicon;
  192. }
  193. else
  194. return self::$TYPE_CACHE_IMG . md5($url);
  195. }
  196. /**
  197. * Display data as a PNG Favicon, then exit
  198. * @param $data
  199. */
  200. private function displayFavicon($data) {
  201. header('Content-Type: image/png');
  202. header('Cache-Control: private, max-age=10800, pre-check=10800');
  203. header('Pragma: private');
  204. header('Expires: ' . date(DATE_RFC822,strtotime('7 day')));
  205. echo $data;
  206. exit;
  207. }
  208. private function getInPage($url) {
  209. $html = $this->dataAccess->retrieveUrl("{$url}/");
  210. preg_match('!<head.*?>.*</head>!ims', $html, $match);
  211. if(empty($match) || count($match) == 0) {
  212. return false;
  213. }
  214. $head = $match[0];
  215. $dom = new \DOMDocument();
  216. // Use error suppression, because the HTML might be too malformed.
  217. if (@$dom->loadHTML($head)) {
  218. $links = $dom->getElementsByTagName('link');
  219. foreach ($links as $link) {
  220. if ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'shortcut icon') {
  221. return $link->getAttribute('href');
  222. } elseif ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'icon') {
  223. return $link->getAttribute('href');
  224. } elseif ($link->hasAttribute('href') && strpos($link->getAttribute('href'), 'favicon') !== FALSE) {
  225. return $link->getAttribute('href');
  226. }
  227. }
  228. }
  229. return false;
  230. }
  231. private function checkCache($url, $type) {
  232. if ($this->cacheTimeout) {
  233. $cache = $this->cacheDir . '/'. $type . md5($url);
  234. if (file_exists($cache) && is_readable($cache)
  235. && ($this->cacheTimeout === -1 || time() - filemtime($cache) < $this->cacheTimeout)
  236. ) {
  237. return $this->dataAccess->readCache($cache);
  238. }
  239. }
  240. return false;
  241. }
  242. /**
  243. * Will save data in cacheDir if the directory writable and any previous cache is expired (cacheTimeout)
  244. * @param $url
  245. * @param $data
  246. * @param $type
  247. * @return string cache file path
  248. */
  249. private function saveCache($url, $data, $type) {
  250. // Save cache if necessary
  251. $cache = $this->cacheDir . '/'. $type . md5($url);
  252. if ($this->cacheTimeout && !file_exists($cache)
  253. || (is_writable($cache) && $this->cacheTimeout !== -1 && time() - filemtime($cache) > $this->cacheTimeout)
  254. ) {
  255. $this->dataAccess->saveCache($cache, $data);
  256. }
  257. return $cache;
  258. }
  259. private function checkImageMType($url) {
  260. $fileContent = $this->dataAccess->retrieveUrl($url);
  261. return $this->checkImageMTypeContent($fileContent);
  262. }
  263. private function checkImageMTypeContent($content) {
  264. if(empty($content)) return false;
  265. $fInfo = finfo_open(FILEINFO_MIME_TYPE);
  266. $isImage = strpos(finfo_buffer($fInfo, $content), 'image') !== false;
  267. finfo_close($fInfo);
  268. return $isImage;
  269. }
  270. /**
  271. * @return mixed
  272. */
  273. public function getCacheDir()
  274. {
  275. return $this->cacheDir;
  276. }
  277. /**
  278. * @param mixed $cacheDir
  279. */
  280. public function setCacheDir($cacheDir)
  281. {
  282. $this->cacheDir = $cacheDir;
  283. }
  284. /**
  285. * @return mixed
  286. */
  287. public function getCacheTimeout()
  288. {
  289. return $this->cacheTimeout;
  290. }
  291. /**
  292. * @param mixed $cacheTimeout
  293. */
  294. public function setCacheTimeout($cacheTimeout)
  295. {
  296. $this->cacheTimeout = $cacheTimeout;
  297. }
  298. /**
  299. * @return string
  300. */
  301. public function getUrl()
  302. {
  303. return $this->url;
  304. }
  305. /**
  306. * @param string $url
  307. */
  308. public function setUrl($url)
  309. {
  310. $this->url = $url;
  311. }
  312. /**
  313. * @param DataAccess|\PHPUnit_Framework_MockObject_MockObject $dataAccess
  314. */
  315. public function setDataAccess($dataAccess)
  316. {
  317. $this->dataAccess = $dataAccess;
  318. }
  319. }