<?php
/*
	Copyright 2010 Scott MacVicar

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

			 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
	 
	Original can be found at https://github.com/scottmac/opengraph/blob/master/OpenGraph.php
	 
*/

class PeepSoOpenGraph
{
	/**
	 * 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 $URI    URI to page to parse for Open Graph data
	 * @return OpenGraph
	 */
	static public function fetch($URI) {
		// #8110 Two user agents, tried in this order for a reason.
		//
		// 1. A social-crawler UA. Google (and a growing number of other sites)
		//    serve a metadata-less page shell to datacenter IPs that do not
		//    present a recognised crawler UA. A YouTube watch page then yields
		//    "<title> - YouTube</title>" with no og: tags at all and only the
		//    generic site-wide <meta name="description">, in whatever language
		//    the server's IP geolocates to. That shell arrives as HTTP 200, so
		//    it cannot be told apart from success and retried - which is why the
		//    crawler UA has to be the *first* attempt, not the fallback.
		//
		// 2. A browser UA, for sites with the opposite policy: Wikimedia and
		//    others answer 403 to crawler UAs. Those are genuine transport
		//    failures, so they do fall through to this second attempt.
		//
		// This previously forwarded $_SERVER['HTTP_USER_AGENT'], which also sent
		// no UA at all on cron/CLI requests, where that key is undefined.
		$user_agents = apply_filters('peepso_opengraph_user_agents', array(
			'facebookexternalhit/1.1',
			'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
		), $URI);

		// Without an explicit Accept-Language the remote end picks a language
		// from the *server's* IP rather than the site's locale, which is how a
		// box in Montreal ended up storing French descriptions.
		$locale = str_replace('_', '-', get_locale());
		$accept_language = array_unique(array($locale, substr($locale, 0, 2), 'en'));
		$weight = 1.0;
		foreach ($accept_language as $i => $tag) {
			$accept_language[$i] = (0 === $i) ? $tag : $tag . ';q=' . number_format($weight, 1);
			$weight -= 0.1;
		}

		$headers = apply_filters('peepso_opengraph_headers', array(
			'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'Accept-Language: ' . implode(',', $accept_language),
		), $URI);

		// Per attempt, so a URL that fails outright can cost twice this. In
		// practice a crawler-blocking site rejects immediately rather than
		// timing out, so the second attempt is cheap when it happens at all.
		$timeout = (int) apply_filters('peepso_opengraph_timeout', 15, $URI);

		foreach ((array) $user_agents as $user_agent) {
			$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, $timeout);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

			$response = curl_exec($curl);

			if (!empty($response)) {
				// A page with no usable metadata (an interstitial, a browser
				// upgrade notice) also warrants trying the next UA.
				$parsed = self::_parse($response);
				if ($parsed) {
					return $parsed;
				}
			}
		}

		return false;
	}

	/**
	 * Parses HTML and extracts Open Graph data, this assumes
	 * the document is at least well formed.
	 *
	 * @param $HTML    HTML to parse
	 * @return OpenGraph
	 */
	static private function _parse($HTML) {
		$old_libxml_error = libxml_use_internal_errors(true);

		// #8110 Entity-encode non-ASCII so DOMDocument (which assumes ISO-8859-1 when
		// the markup carries no charset) reads UTF-8 correctly. The old
		// mb_convert_encoding($HTML, 'HTML-ENTITIES', ...) spelling of this is
		// deprecated as of PHP 8.2 and warns on every fetch under 8.5.
		if (function_exists('mb_encode_numericentity'))
			$HTML = mb_encode_numericentity($HTML, array(0x80, 0x10FFFF, 0, 0x1FFFFF), 'UTF-8');

		$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') &&
					strpos($tag->getAttribute('property'), 'og:') === 0) {
				$key = strtr(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') &&
					strpos($tag->getAttribute('property'), 'og:') === 0) {
				$key = strtr(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 $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 $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;
	}

}
