OpenGraph.php 6.7 KB

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