-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSimpleParseOpenGraph.php
243 lines (209 loc) · 7.24 KB
/
SimpleParseOpenGraph.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
/**
* Project codeigniter-basic-helper
* Created by PhpStorm
* User: 713uk13m <dev@nguyenanhung.com>
* Copyright: 713uk13m <dev@nguyenanhung.com>
* Date: 20/07/2023
* Time: 22:56
*/
namespace nguyenanhung\CodeIgniter\BasicHelper;
class SimpleParseOpenGraph extends BaseHelper implements \Iterator
{
/**
* There are base schema's based on type, this is just
* a map so that the schema can be obtained
*
*/
public static $TYPES = array(
'activity' => array('activity', 'sport'),
'business' => array('bar', 'company', 'cafe', 'hotel', 'restaurant'),
'group' => array('cause', 'sports_league', 'sports_team'),
'organization' => array('band', 'government', 'non_profit', 'school', 'university'),
'person' => array('actor', 'athlete', 'author', 'director', 'musician', 'politician', 'public_figure'),
'place' => array('city', 'country', 'landmark', 'state_province'),
'product' => array('album', 'book', 'drink', 'food', 'game', 'movie', 'product', 'song', 'tv_show'),
'website' => array('blog', 'website'),
);
/**
* Holds all the Open Graph values we've parsed from a page
*
*/
private $_values = array();
/**
* Fetches a URI and parses it for Open Graph data, returns
* false on error.
*
* @param mixed $URI URI to page to parse for Open Graph data
* @return SimpleParseOpenGraph|bool
*/
static public function fetch($URI)
{
$curl = curl_init($URI);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if (isset($_SERVER['HTTP_USER_AGENT'])) {
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
} else {
curl_setopt(
$curl,
CURLOPT_USERAGENT,
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
);
}
$response = curl_exec($curl);
curl_close($curl);
if (!empty($response)) {
return self::_parse($response);
}
return false;
}
/**
* Parses HTML and extracts Open Graph data, this assumes
* the document is at least well formed.
*
* @param mixed $HTML HTML to parse
* @return SimpleParseOpenGraph
*/
static private function _parse($HTML)
{
$old_libxml_error = libxml_use_internal_errors(true);
$doc = new \DOMDocument();
$doc->loadHTML($HTML);
libxml_use_internal_errors($old_libxml_error);
$tags = $doc->getElementsByTagName('meta');
if (!$tags || $tags->length === 0) {
return false;
}
$page = new self();
$nonOgDescription = null;
foreach ($tags as $tag) {
if ($tag->hasAttribute('property') &&
mb_strpos($tag->getAttribute('property'), 'og:') === 0) {
$key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_');
$page->_values[$key] = $tag->getAttribute('content');
}
//Added this if loop to retrieve description values from sites like the New York Times who have malformed it.
if ($tag->hasAttribute('value') && $tag->hasAttribute('property') &&
mb_strpos($tag->getAttribute('property'), 'og:') === 0) {
$key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_');
$page->_values[$key] = $tag->getAttribute('value');
}
//Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
if ($tag->hasAttribute('name') && $tag->getAttribute('name') === 'description') {
$nonOgDescription = $tag->getAttribute('content');
}
}
//Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
if (!isset($page->_values['title'])) {
$titles = $doc->getElementsByTagName('title');
if ($titles->length > 0) {
$page->_values['title'] = $titles->item(0)->textContent;
}
}
if (!isset($page->_values['description']) && $nonOgDescription) {
$page->_values['description'] = $nonOgDescription;
}
//Fallback to use image_src if ogp::image isn't set.
if (!isset($page->values['image'])) {
$domxpath = new \DOMXPath($doc);
$elements = $domxpath->query("//link[@rel='image_src']");
if ($elements->length > 0) {
$domattr = $elements->item(0)->attributes->getNamedItem('href');
if ($domattr) {
$page->_values['image'] = $domattr->value;
$page->_values['image_src'] = $domattr->value;
}
}
}
if (empty($page->_values)) {
return false;
}
return $page;
}
/**
* Helper method to access attributes directly
* Example:
* $graph->title
*
* @param mixed $key Key to fetch from the lookup
*/
public function __get($key)
{
if (array_key_exists($key, $this->_values)) {
return $this->_values[$key];
}
if ($key === 'schema') {
foreach (self::$TYPES as $schema => $types) {
if (array_search($this->_values['type'], $types)) {
return $schema;
}
}
}
}
/**
* Return all the keys found on the page
*
* @return array
*/
public function keys()
{
return array_keys($this->_values);
}
/**
* Helper method to check an attribute exists
*
* @param mixed $key
*/
public function __isset($key)
{
return array_key_exists($key, $this->_values);
}
/**
* Will return true if the page has location data embedded
*
* @return boolean Check if the page has location data
*/
public function hasLocation()
{
if (array_key_exists('latitude', $this->_values) && array_key_exists('longitude', $this->_values)) {
return true;
}
$address_keys = array('street_address', 'locality', 'region', 'postal_code', 'country_name');
$valid_address = true;
foreach ($address_keys as $key) {
$valid_address = ($valid_address && array_key_exists($key, $this->_values));
}
return $valid_address;
}
/**
* Iterator code
*/
private $_position = 0;
public function rewind()
{
reset($this->_values);
$this->_position = 0;
}
public function current()
{
return current($this->_values);
}
public function key()
{
return key($this->_values);
}
public function next()
{
next($this->_values);
++$this->_position;
}
public function valid()
{
return $this->_position < sizeof($this->_values);
}
}