start.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace image_proxy;
  3. elgg_register_event_handler('init', 'system', __NAMESPACE__ . '\\init');
  4. function init() {
  5. //@TODO - can we do this without parsing all views?
  6. elgg_register_plugin_hook_handler('view', 'all', __NAMESPACE__ . '\\view_hook');
  7. }
  8. /**
  9. * replace any http images with https urls
  10. *
  11. * @param type $h
  12. * @param type $t
  13. * @param type $r
  14. * @param type $p
  15. * @return type
  16. */
  17. function view_hook($h, $t, $r, $p) {
  18. $http_url = str_replace('https://', 'http://', elgg_get_site_url());
  19. if (preg_match_all( '/<img[^>]+src\s*=\s*["\']?([^"\' ]+)[^>]*>/', $r, $extracted_image)) {
  20. foreach ($extracted_image[0] as $key => $i) {
  21. if (strpos($extracted_image[1][$key], elgg_get_site_url()) !== false) {
  22. continue; // already one of our links
  23. }
  24. // check if this is our url being requested over http, and rewrite to https
  25. if (strpos($extracted_image[1][$key], $http_url) === 0) {
  26. $https_image = str_replace('http://', 'https://', $extracted_image[1][$key]);
  27. $replacement_image = str_replace($extracted_image[1][$key], $https_image, $i);
  28. $r = str_replace($i, $replacement_image, $r);
  29. continue;
  30. }
  31. if (!is_https($extracted_image[1][$key])) {
  32. // replace this url
  33. $url = urlencode($extracted_image[1][$key]);
  34. if (strpos($url, 'http') === 0) {
  35. $token = get_token($extracted_image[1][$key]);
  36. $new_url = elgg_normalize_url('mod/image_proxy/image.php?url=' . $url . '&token=' . $token);
  37. $replacement_image = str_replace($extracted_image[1][$key], $new_url, $i);
  38. $r = str_replace($i, $replacement_image, $r);
  39. }
  40. }
  41. }
  42. }
  43. return $r;
  44. }
  45. /**
  46. * detect if the current page is using https
  47. *
  48. * @staticvar type $is_https
  49. * @return type
  50. */
  51. function is_https($url) {
  52. static $is_https;
  53. if (!is_array($is_https)) {
  54. $is_https = array();
  55. }
  56. if (isset($is_https[$url])) {
  57. return $is_https[$url];
  58. }
  59. $parts = parse_url($url);
  60. $is_https[$url] = strtolower($parts['scheme']) === 'https';
  61. return $is_https[$url];
  62. }
  63. function get_token($url) {
  64. if (elgg_get_config('image_proxy_secret')) {
  65. $site_secret = elgg_get_config('image_proxy_secret');
  66. }
  67. else {
  68. $site_secret = get_site_secret();
  69. }
  70. return sha1($site_secret . $url);
  71. }