OpenGraph.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. <?php
  2. /*
  3. Copyright 2010 Scott MacVicar
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. Original can be found at https://github.com/scottmac/opengraph/blob/master/OpenGraph.php
  14. */
  15. class OpenGraph implements Iterator
  16. {
  17. /**
  18. * There are base schema's based on type, this is just
  19. * a map so that the schema can be obtained
  20. *
  21. */
  22. public static $TYPES = array(
  23. 'activity' => array('activity', 'sport'),
  24. 'business' => array('bar', 'company', 'cafe', 'hotel', 'restaurant'),
  25. 'group' => array('cause', 'sports_league', 'sports_team'),
  26. 'organization' => array('band', 'government', 'non_profit', 'school', 'university'),
  27. 'person' => array('actor', 'athlete', 'author', 'director', 'musician', 'politician', 'public_figure'),
  28. 'place' => array('city', 'country', 'landmark', 'state_province'),
  29. 'product' => array('album', 'book', 'drink', 'food', 'game', 'movie', 'product', 'song', 'tv_show'),
  30. 'website' => array('blog', 'website'),
  31. );
  32. /**
  33. * Holds all the Open Graph values we've parsed from a page
  34. *
  35. */
  36. private $_values = array();
  37. /**
  38. * Fetches a URI and parses it for Open Graph data, returns
  39. * false on error.
  40. *
  41. * @param $URI URI to page to parse for Open Graph data
  42. * @return OpenGraph
  43. */
  44. static public function fetch($URI) {
  45. $curl = curl_init($URI);
  46. curl_setopt($curl, CURLOPT_FAILONERROR, true);
  47. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  48. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  49. curl_setopt($curl, CURLOPT_TIMEOUT, 15);
  50. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  51. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  52. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  53. $response = curl_exec($curl);
  54. curl_close($curl);
  55. if (!empty($response)) {
  56. return self::_parse($response);
  57. } else {
  58. return false;
  59. }
  60. }
  61. /**
  62. * Parses HTML and extracts Open Graph data, this assumes
  63. * the document is at least well formed.
  64. *
  65. * @param $HTML HTML to parse
  66. * @return OpenGraph
  67. */
  68. static private function _parse($HTML) {
  69. $old_libxml_error = libxml_use_internal_errors(true);
  70. $doc = new DOMDocument();
  71. $doc->loadHTML($HTML);
  72. libxml_use_internal_errors($old_libxml_error);
  73. $tags = $doc->getElementsByTagName('meta');
  74. if (!$tags || $tags->length === 0) {
  75. return false;
  76. }
  77. $page = new self();
  78. $nonOgDescription = null;
  79. foreach ($tags AS $tag) {
  80. if ($tag->hasAttribute('property') &&
  81. strpos($tag->getAttribute('property'), 'og:') === 0) {
  82. $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
  83. $page->_values[$key] = $tag->getAttribute('content');
  84. }
  85. //Added this if loop to retrieve description values from sites like the New York Times who have malformed it.
  86. if ($tag ->hasAttribute('value') && $tag->hasAttribute('property') &&
  87. strpos($tag->getAttribute('property'), 'og:') === 0) {
  88. $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
  89. $page->_values[$key] = $tag->getAttribute('value');
  90. }
  91. //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
  92. if ($tag->hasAttribute('name') && $tag->getAttribute('name') === 'description') {
  93. $nonOgDescription = $tag->getAttribute('content');
  94. }
  95. }
  96. //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
  97. if (!isset($page->_values['title'])) {
  98. $titles = $doc->getElementsByTagName('title');
  99. if ($titles->length > 0) {
  100. $page->_values['title'] = $titles->item(0)->textContent;
  101. }
  102. }
  103. if (!isset($page->_values['description']) && $nonOgDescription) {
  104. $page->_values['description'] = $nonOgDescription;
  105. }
  106. //Fallback to use image_src if ogp::image isn't set.
  107. if (!isset($page->values['image'])) {
  108. $domxpath = new DOMXPath($doc);
  109. $elements = $domxpath->query("//link[@rel='image_src']");
  110. if ($elements->length > 0) {
  111. $domattr = $elements->item(0)->attributes->getNamedItem('href');
  112. if ($domattr) {
  113. $page->_values['image'] = $domattr->value;
  114. $page->_values['image_src'] = $domattr->value;
  115. }
  116. }
  117. }
  118. if (empty($page->_values)) { return false; }
  119. return $page;
  120. }
  121. /**
  122. * Helper method to access attributes directly
  123. * Example:
  124. * $graph->title
  125. *
  126. * @param $key Key to fetch from the lookup
  127. */
  128. public function __get($key) {
  129. if (array_key_exists($key, $this->_values)) {
  130. return $this->_values[$key];
  131. }
  132. if ($key === 'schema') {
  133. foreach (self::$TYPES AS $schema => $types) {
  134. if (array_search($this->_values['type'], $types)) {
  135. return $schema;
  136. }
  137. }
  138. }
  139. }
  140. /**
  141. * Return all the keys found on the page
  142. *
  143. * @return array
  144. */
  145. public function keys() {
  146. return array_keys($this->_values);
  147. }
  148. /**
  149. * Helper method to check an attribute exists
  150. *
  151. * @param $key
  152. */
  153. public function __isset($key) {
  154. return array_key_exists($key, $this->_values);
  155. }
  156. /**
  157. * Will return true if the page has location data embedded
  158. *
  159. * @return boolean Check if the page has location data
  160. */
  161. public function hasLocation() {
  162. if (array_key_exists('latitude', $this->_values) && array_key_exists('longitude', $this->_values)) {
  163. return true;
  164. }
  165. $address_keys = array('street_address', 'locality', 'region', 'postal_code', 'country_name');
  166. $valid_address = true;
  167. foreach ($address_keys AS $key) {
  168. $valid_address = ($valid_address && array_key_exists($key, $this->_values));
  169. }
  170. return $valid_address;
  171. }
  172. /**
  173. * Iterator code
  174. */
  175. private $_position = 0;
  176. public function rewind() { reset($this->_values); $this->_position = 0; }
  177. public function current() { return current($this->_values); }
  178. public function key() { return key($this->_values); }
  179. public function next() { next($this->_values); ++$this->_position; }
  180. public function valid() { return $this->_position < sizeof($this->_values); }
  181. }