/
ExternalResource.php
183 lines (153 loc) · 5 KB
/
ExternalResource.php
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
<?php
namespace SmartCrowd;
use Etechnika\IdnaConvert\IdnaConvert;
class ExternalResource
{
private $link;
private $max_error = 1;
private $curl_options = [
CURLOPT_HEADER => 0,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3',
CURLOPT_FRESH_CONNECT => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
];
private static $base_href_exception_domains = ['https://vk.com'];
public function __construct($link) {
$this->link = $link;
}
public static function init($link) {
return new ExternalResource($link);
}
/**
* Объединяем массивы параметров с сохранением ключей
*
* @param array $options
* @return $this
*/
public function setCurlOptions(array $options) {
$this->curl_options = $options + $this->curl_options;
return $this;
}
public function getResource($rel2abs = true)
{
$link = static::instagramHook($this->link);
try {
$link = static::encodeUrl($link);
$response = static::getContent($link);
} catch (\Exception $e) {
return $e->getMessage();
}
static::setContentTypeHeaders($response);
$result = $rel2abs ? static::rel2abs($response['content'], $link) : $response['content'];
return $result;
}
/**
* Получение контента по ссылке
*
* @param $link
* @return string
* @throws \Exception
*/
public function getContent($link)
{
$i = 0;
do {
$result = $this->getResponse($link);
$i++;
} while ($result['errno'] == 7 && $this->max_error >= $i);
if ($result['errno'] !== 0) {
throw new \Exception("Не удалось загрузить страницу\n" . $link . ". Error: " . $result['errno']);
}
if ($result['http_code'] != 200) {
throw new \Exception("Ссылка недоступна " . $result['http_code']);
}
return $result;
}
/**
* @param $link
* @return mixed
*
*/
public function getResponse($link)
{
$ch = curl_init($link);
curl_setopt_array($ch, $this->curl_options);
$content = curl_exec($ch);
$result = curl_getinfo($ch);
$result['errno'] = curl_errno($ch);
$result['error'] = curl_error($ch);
$result['content'] = $content;
curl_close($ch);
return $result;
}
/**
* Энкодинг url
*
* @param $link
* @return string
*/
public static function encodeUrl($link)
{
$domain = parse_url($link, PHP_URL_HOST);
$encoded_domain = IdnaConvert::encodeString($domain);
return str_replace($domain, $encoded_domain, $link);
}
/**
* Задание базового URL для относительных URL
*
* @param $file
* @param $url
* @return mixed
*/
public static function rel2abs($file, $url)
{
$full_domain = static::getHostFromUrl($url);
$pattern = '#(<\s*((img)|(a)|(link))\s+[^>]*((src)|(href))\s*=\s*[\"\'])(?!\/\/)(?!http)([^\"\'>]+)([\"\'>]+)#';
$file = preg_replace($pattern, '$1' . $full_domain . '$9$10', $file);
if (!in_array($full_domain, static::$base_href_exception_domains)
&& !preg_match('/(<base[^>]* href="(.*)">)/', $file)) {
$file = preg_replace('/(<head[^>]*>)/', '$1<base href="' . $full_domain . '"/>', $file);
}
return $file;
}
/**
* @param string $url
* @param bool $with_scheme
*
* @return string
*/
public static function getHostFromUrl($url, $with_scheme = true)
{
$host = parse_url($url);
$host = $with_scheme ? $host['scheme'] . "://" . $host['host'] : $host['host'];
return $host;
}
/**
* Redirect all instagram links to captioned embed url
*
* @param $link
*
* @return mixed
*/
public static function instagramHook($link)
{
$instagram_hosts = ['instagram.com', 'www.instagram.com'];
$parsed_url = parse_url($link);
$host = isset($parsed_url['host']) ? strtolower($parsed_url['host']) : "";
if (in_array($host, $instagram_hosts)) {
$link = preg_replace('/\/embed(\/captioned)?(\/)?$/i', '', $link);
$link = rtrim($link, '\/');
$link = $link . "/embed/captioned";
}
return $link;
}
public static function setContentTypeHeaders($response)
{
if (strpos($response['content_type'], 'charset')) {
header('Content-type:' . $response['content_type']);
} elseif (preg_match('/<meta[^>]+charset=[\']?(.*?)[\']?[\/\s>]/i', $response['content'], $matches)) {
header('Content-type:' . $response['content_type'] . '; charset=' . $matches[1]);
}
}
}