init.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. class Af_Tumblr_1280 extends Plugin {
  3. private $host;
  4. function about() {
  5. return array(1.0,
  6. "Replace Tumblr pictures and videos with largest size if available (requires CURL)",
  7. "fox");
  8. }
  9. function flags() {
  10. return array("needs_curl" => true);
  11. }
  12. function init($host) {
  13. $this->host = $host;
  14. if (function_exists("curl_init")) {
  15. $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
  16. }
  17. }
  18. function hook_article_filter($article) {
  19. if (!function_exists("curl_init") || ini_get("open_basedir"))
  20. return $article;
  21. $charset_hack = '<head>
  22. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  23. </head>';
  24. $doc = new DOMDocument();
  25. $doc->loadHTML($charset_hack . $article["content"]);
  26. $found = false;
  27. if ($doc) {
  28. $xpath = new DOMXpath($doc);
  29. $images = $xpath->query('(//img[contains(@src, \'media.tumblr.com\')])');
  30. foreach ($images as $img) {
  31. $src = $img->getAttribute("src");
  32. $test_src = preg_replace("/_\d{3}.(jpg|gif|png)/", "_1280.$1", $src);
  33. if ($src != $test_src) {
  34. $ch = curl_init($test_src);
  35. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  36. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  37. curl_setopt($ch, CURLOPT_HEADER, true);
  38. curl_setopt($ch, CURLOPT_NOBODY, true);
  39. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  40. curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
  41. @$result = curl_exec($ch);
  42. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  43. if ($result && $http_code == 200) {
  44. $img->setAttribute("src", $test_src);
  45. $found = true;
  46. }
  47. }
  48. }
  49. $video_sources = $xpath->query('//video/source[contains(@src, \'.tumblr.com/video_file\')]');
  50. foreach ($video_sources as $source) {
  51. $src = $source->getAttribute("src");
  52. $new_src = preg_replace("/\/\d{3}$/", "", $src);
  53. if ($src != $new_src) {
  54. $source->setAttribute("src", $new_src);
  55. $found = true;
  56. }
  57. }
  58. if ($found) {
  59. $doc->removeChild($doc->firstChild); //remove doctype
  60. $article["content"] = $doc->saveHTML();
  61. }
  62. }
  63. return $article;
  64. }
  65. function api_version() {
  66. return 2;
  67. }
  68. }