<commit_before><?php

define( 'KALTURA_GENERIC_SERVER_ERROR', "Error getting sources from server. Please try again.");

// Include the kaltura client
require_once(  dirname( __FILE__ ) . '/kaltura_client_v3/KalturaClient.php' );
// Include the kaltura named multi request helper class: 
require_once(  dirname( __FILE__ ) . '/KalturaNamedMultiRequest.php');

/**
 * Generates a kaltura result object based on url Parameters 
 */
class KalturaResultObject {
	var $resultObj = null; // lazy init with getResultObject
	var $clientTag = null;
	var $uiConfFile = null;
	var $uiConfXml = null; // lazy init
	var $playlistObject = null; // lazy init playlist Object
	var $noCache = false;
	// flag to control if we are in playlist mode
	var $isPlaylist = null; // lazy init
	var $isJavascriptRewriteObject = null;
	var $error = false;
	// Set of sources
	var $sources = null;
	
	// Local flag to store whether output was came from cache or was a fresh request
	private $outputFromCache = false;
	// local flag to store if the uiconf file was from cache.
	private $outputUiConfFileFromCache = false;

	// Setup static error messages
	const NO_ENTRY_ID_FOUND = "No Entry ID was found";
	
	/**
	 * Variables set by the Frame request:
	 */
	public $urlParameters = array(
		'cache_st' => null,
		'p' => null,
		'wid' => null,
		'uiconf_id' => null,
		'entry_id' => null,
		'flashvars' => null,
		'playlist_id' => null,
		'urid' => null,
		// Custom service url properties ( only used when wgKalturaAllowIframeRemoteService is set to true ) 
		'ServiceUrl'=> null,
		'ServiceBase'=>null,
		'CdnUrl'=> null,
		'UseManifestUrls' => null,
		'debug' => null
	);
	
	var $playerConfig = array();

	function __construct( $clientTag = 'php'){
		//parse input:
		$this->parseRequest();
		// set client tag with cache_st
		$this->clientTag = $clientTag . ',cache_st: ' . $this->urlParameters['cache_st'];
		// load the request object:
		$this->getResultObject();
	}
	function getServiceConfig( $name ){
		global $wgKalturaAllowIframeRemoteService;
		
		// Check if we allow URL override: 
		if( $wgKalturaAllowIframeRemoteService == true ){
			// Check for urlParameters
			if( isset( $this->urlParameters[ $name ] ) ){
				return $this->urlParameters[ $name ];
			}
		}
		
		// Else use the global config: 
		switch( $name ){
			case 'ServiceUrl' : 
				global $wgKalturaServiceUrl;
				return $wgKalturaServiceUrl;
				break;
			case 'ServiceBase':
				global $wgKalturaServiceBase;
				return $wgKalturaServiceBase;
				break;
			case 'CdnUrl':
				global $wgKalturaCDNUrl;
				return $wgKalturaCDNUrl;
				break;
			case 'UseManifestUrls':
				global $wgKalturaUseManifestUrls;
				return $wgKalturaUseManifestUrls;
				break;
		}
		// else thorw an erro? 
	}
	function getError() {
		return $this->error;
	}
	public function getPlayerConfig( $confPrefix = false, $attr = false ) {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		$plugins = $this->playerConfig['plugins'];
		$vars = $this->playerConfig['vars'];

		if( $confPrefix ) {
			if( isset( $plugins[ $confPrefix ] ) ) {
				if( $attr ) {
					if( isset( $plugins[ $confPrefix ][ $attr ] ) ) {
						return $plugins[ $confPrefix ][ $attr ];
					} else {
						return null;
					}
				} else {
					return $plugins[ $confPrefix ];
				}
			} else {
				return null;
			}
		}

		if( $attr && isset( $vars[ $attr ] ) ) {
			return $vars[ $attr ];
		}

		return $this->playerConfig;
	}

	public function getWidgetPlugins() {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		return $this->playerConfig['plugins'];
	}

	public function getWidgetUiVars() {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		return $this->playerConfig['vars'];
	}

	// empty player test ( nothing in the uiConf says "player" diffrent from other widgets so we 
	// we just have to use the 
	function isEmptyPlayer(){
		if( !$this->urlParameters['entry_id'] && ! isset( $this->urlParameters['flashvars']['referenceId'] ) && !$this->isJavascriptRewriteObject()
			&& !$this->isPlaylist() ){
			return true;
		}
		return false;
	}
	// Check if the requested url is a playlist
	function isPlaylist(){
		// Check if the playlist is null: 
		if( !is_null ( $this->isPlaylist ) ){
			return $this->isPlaylist;
		}
		// Check if its a playlist url exists ( better check for playlist than playlist id )
		$this->isPlaylist = !! $this->getPlayerConfig('playlistAPI', 'kpl0Url');;
		return $this->isPlaylist;
	}
	function isJavascriptRewriteObject() {
		// If our playlist is Mrss, handle the playlist in the client side
		$playlistUrl = $this->getPlayerConfig('playlistAPI', 'kpl0Url');
		if( $playlistUrl && strpos($playlistUrl, "partnerservices") === false ) {
			return true;
		}

		// If this is a pptWidget, handle in client side
		if( $this->getPlayerConfig('pptWidgetAPI', 'plugin') ) {
			return true;
		}
		
		return false;
	}
	public function isCachedOutput(){
		global $wgEnableScriptDebug; 
		// Don't cache output if an iframe or there is an error.
		if( $wgEnableScriptDebug || $this->error ){
			return false;
		}
		return $this->outputFromCache;
	}
	public function isCachedUiConfFile(){
		global $wgEnableScriptDebug;
		if( $wgEnableScriptDebug ) 
			return false;
		return $this->outputUiConfFileFromCache;
	}
	public function getUserAgent() {
		return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
	}
	/**
	 * Checks if a user agent is restricted via the user restriction plugin present in the uiConf XML
	 * this check is run as part of resultObject handling so we must pass in the uiConf string
	 */ 
	public function isUserAgentRestrictedPlugin() {
		$userAgentPlugin = $this->getPlayerConfig('restrictUserAgent');
		if( $userAgentPlugin ) {
			$restrictedMessage = true;
			// Set error message
			if( $userAgentPlugin['restrictedUserAgentTitle'] && $userAgentPlugin['restrictedUserAgentMessage'] ) {
				$restrictedMessage = $userAgentPlugin['restrictedUserAgentTitle'] . "\n" . $userAgentPlugin['restrictedUserAgentMessage'];
			}

			$restrictedStrings = $userAgentPlugin['restrictedUserAgents'];
			if( $restrictedStrings ) {
				$userAgent = strtolower( $this->getUserAgent() );
				$restrictedStrings = strtolower( $restrictedStrings );
				$restrictedStrings = explode(",", $restrictedStrings);

				foreach( $restrictedStrings as $string ) {
					$string = str_replace(".*", "", $string); // Removes .*
					$string = trim($string);
					if( ! strpos( $userAgent, $string ) === false ) {
						return $restrictedMessage;
					}
				}
			}
		}
		return false;
	}
	/**
	*  Access Control Handling
	*/
	public function isAccessControlAllowed( &$resultObject = null ) {
		// Kaltura only has entry level access control not playlist level access control atm: 
		// don't check anything without an entry_id
		if( !isset( $this->urlParameters['entry_id'] ) ){
			return true;
		}

		// If we have an error, return
		if( $this->error ) {
			return $this->error;
		}

		if( !$resultObject ){
			$resultObject =  $this->getResultObject();
		}
		// check for access control resultObject property:
		if( !isset( $resultObject['accessControl']) ){
			return true;
		}
		$accessControl = $resultObject['accessControl'];
		
		// Check if we had no access control due to playlist
		if( is_array( $accessControl ) && isset( $accessControl['code'] )){
			// Error ? .. should do better error checking.
			// errors we have seen so far: 
				//$accessControl['code'] == 'MISSING_MANDATORY_PARAMETER'
				//$accessControl['code'] == 'INTERNAL_SERVERL_ERROR'  
			return true;
		}
		
		// Checks if admin
		if( $accessControl->isAdmin ) {
			return true;
		}

		/* Domain Name Restricted */
		if( $accessControl->isSiteRestricted ) {
			return "Un authorized domain\nWe're sorry, this content is only available on certain domains.";
		}

		/* Country Restricted */
		if( $accessControl->isCountryRestricted) {
			return "Un authorized country\nWe're sorry, this content is only available in certain countries.";
		}

		/* IP Address Restricted */
		if( $accessControl->isIpAddressRestricted) {
			return "Un authorized IP address\nWe're sorry, this content is only available for ceratin IP addresses.";
		}

		/* Session Restricted */
		if( $accessControl->isSessionRestricted && $accessControl->previewLength == -1 ) {
			return "No KS where KS is required\nWe're sorry, access to this content is restricted.";
		}

		if( $accessControl->isScheduledNow === 0) {
			return "Out of scheduling\nWe're sorry, this content is currently unavailable.";
		}
		
		//echo $this->getUserAgent() . '<br />';
		//echo '<pre>'; print_r($accessControl); exit();
		$userAgentMessage = "User Agent Restricted\nWe're sorry, this content is not available for your device.";
		if( isset( $accessControl->isUserAgentRestricted ) && $accessControl->isUserAgentRestricted ) {
			return $userAgentMessage;
		} else {
			$userAgentRestricted = $this->isUserAgentRestrictedPlugin();
			if( $userAgentRestricted === false ) {
				return true;
			} else {
				// We have user agent restriction, set up noCache flag
				$this->noCache = true;
				if( $userAgentRestricted === true ) {
					return $userAgentMessage;
				} else {
					return $userAgentRestricted;
				}
			}
		}
		return true;
	}

	function formatString( $str ) {
		// trim any whitespace
		$str = trim( $str );
		// decode the value: 
		$str = html_entity_decode( $str );
		if( $str === "true" ) {
			return true;
		} else if( $str === "false" ) {
			return false;
		} else {
			return $str;
		}
	}

	/* setupPlayerConfig()
	 * Creates an array of our player configuration.
	 * The array is build from: Flashvars, uiVars, uiConf
	 * The array include 2 arrays:
	 * plugins - contains all of our plugins configuration
	 * vars - contain flat player configuration
	 */
	function setupPlayerConfig() {

		$plugins = array();
		$vars = array();

		// Get all plugins elements
		if( $this->uiConfFile ) {
			$pluginsXml = $this->getUiConfXML()->xpath("*//*[@id]");
			for( $i=0; $i < count($pluginsXml); $i++ ) {
				$pluginId = (string) $pluginsXml[ $i ]->attributes()->id;
				// Enforce the lower case first letter of plugin convention: 
				$pluginId = strtolower( $pluginId[0] ) . substr($pluginId, 1 );
				$plugins[ $pluginId ] = array(
					'plugin' => true
				);
				foreach( $pluginsXml[ $i ]->attributes() as $key => $value) {
					if( $key == "id" ) {<commit_msg>Added a check for string existence<commit_after><?php

define( 'KALTURA_GENERIC_SERVER_ERROR', "Error getting sources from server. Please try again.");

// Include the kaltura client
require_once(  dirname( __FILE__ ) . '/kaltura_client_v3/KalturaClient.php' );
// Include the kaltura named multi request helper class: 
require_once(  dirname( __FILE__ ) . '/KalturaNamedMultiRequest.php');

/**
 * Generates a kaltura result object based on url Parameters 
 */
class KalturaResultObject {
	var $resultObj = null; // lazy init with getResultObject
	var $clientTag = null;
	var $uiConfFile = null;
	var $uiConfXml = null; // lazy init
	var $playlistObject = null; // lazy init playlist Object
	var $noCache = false;
	// flag to control if we are in playlist mode
	var $isPlaylist = null; // lazy init
	var $isJavascriptRewriteObject = null;
	var $error = false;
	// Set of sources
	var $sources = null;
	
	// Local flag to store whether output was came from cache or was a fresh request
	private $outputFromCache = false;
	// local flag to store if the uiconf file was from cache.
	private $outputUiConfFileFromCache = false;

	// Setup static error messages
	const NO_ENTRY_ID_FOUND = "No Entry ID was found";
	
	/**
	 * Variables set by the Frame request:
	 */
	public $urlParameters = array(
		'cache_st' => null,
		'p' => null,
		'wid' => null,
		'uiconf_id' => null,
		'entry_id' => null,
		'flashvars' => null,
		'playlist_id' => null,
		'urid' => null,
		// Custom service url properties ( only used when wgKalturaAllowIframeRemoteService is set to true ) 
		'ServiceUrl'=> null,
		'ServiceBase'=>null,
		'CdnUrl'=> null,
		'UseManifestUrls' => null,
		'debug' => null
	);
	
	var $playerConfig = array();

	function __construct( $clientTag = 'php'){
		//parse input:
		$this->parseRequest();
		// set client tag with cache_st
		$this->clientTag = $clientTag . ',cache_st: ' . $this->urlParameters['cache_st'];
		// load the request object:
		$this->getResultObject();
	}
	function getServiceConfig( $name ){
		global $wgKalturaAllowIframeRemoteService;
		
		// Check if we allow URL override: 
		if( $wgKalturaAllowIframeRemoteService == true ){
			// Check for urlParameters
			if( isset( $this->urlParameters[ $name ] ) ){
				return $this->urlParameters[ $name ];
			}
		}
		
		// Else use the global config: 
		switch( $name ){
			case 'ServiceUrl' : 
				global $wgKalturaServiceUrl;
				return $wgKalturaServiceUrl;
				break;
			case 'ServiceBase':
				global $wgKalturaServiceBase;
				return $wgKalturaServiceBase;
				break;
			case 'CdnUrl':
				global $wgKalturaCDNUrl;
				return $wgKalturaCDNUrl;
				break;
			case 'UseManifestUrls':
				global $wgKalturaUseManifestUrls;
				return $wgKalturaUseManifestUrls;
				break;
		}
		// else thorw an erro? 
	}
	function getError() {
		return $this->error;
	}
	public function getPlayerConfig( $confPrefix = false, $attr = false ) {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		$plugins = $this->playerConfig['plugins'];
		$vars = $this->playerConfig['vars'];

		if( $confPrefix ) {
			if( isset( $plugins[ $confPrefix ] ) ) {
				if( $attr ) {
					if( isset( $plugins[ $confPrefix ][ $attr ] ) ) {
						return $plugins[ $confPrefix ][ $attr ];
					} else {
						return null;
					}
				} else {
					return $plugins[ $confPrefix ];
				}
			} else {
				return null;
			}
		}

		if( $attr && isset( $vars[ $attr ] ) ) {
			return $vars[ $attr ];
		}

		return $this->playerConfig;
	}

	public function getWidgetPlugins() {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		return $this->playerConfig['plugins'];
	}

	public function getWidgetUiVars() {
		if( ! $this->playerConfig ) {
			$this->setupPlayerConfig();
		}
		return $this->playerConfig['vars'];
	}

	// empty player test ( nothing in the uiConf says "player" diffrent from other widgets so we 
	// we just have to use the 
	function isEmptyPlayer(){
		if( !$this->urlParameters['entry_id'] && ! isset( $this->urlParameters['flashvars']['referenceId'] ) && !$this->isJavascriptRewriteObject()
			&& !$this->isPlaylist() ){
			return true;
		}
		return false;
	}
	// Check if the requested url is a playlist
	function isPlaylist(){
		// Check if the playlist is null: 
		if( !is_null ( $this->isPlaylist ) ){
			return $this->isPlaylist;
		}
		// Check if its a playlist url exists ( better check for playlist than playlist id )
		$this->isPlaylist = !! $this->getPlayerConfig('playlistAPI', 'kpl0Url');;
		return $this->isPlaylist;
	}
	function isJavascriptRewriteObject() {
		// If our playlist is Mrss, handle the playlist in the client side
		$playlistUrl = $this->getPlayerConfig('playlistAPI', 'kpl0Url');
		if( $playlistUrl && strpos($playlistUrl, "partnerservices") === false ) {
			return true;
		}

		// If this is a pptWidget, handle in client side
		if( $this->getPlayerConfig('pptWidgetAPI', 'plugin') ) {
			return true;
		}
		
		return false;
	}
	public function isCachedOutput(){
		global $wgEnableScriptDebug; 
		// Don't cache output if an iframe or there is an error.
		if( $wgEnableScriptDebug || $this->error ){
			return false;
		}
		return $this->outputFromCache;
	}
	public function isCachedUiConfFile(){
		global $wgEnableScriptDebug;
		if( $wgEnableScriptDebug ) 
			return false;
		return $this->outputUiConfFileFromCache;
	}
	public function getUserAgent() {
		return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
	}
	/**
	 * Checks if a user agent is restricted via the user restriction plugin present in the uiConf XML
	 * this check is run as part of resultObject handling so we must pass in the uiConf string
	 */ 
	public function isUserAgentRestrictedPlugin() {
		$userAgentPlugin = $this->getPlayerConfig('restrictUserAgent');
		if( $userAgentPlugin ) {
			$restrictedMessage = true;
			// Set error message
			if( $userAgentPlugin['restrictedUserAgentTitle'] && $userAgentPlugin['restrictedUserAgentMessage'] ) {
				$restrictedMessage = $userAgentPlugin['restrictedUserAgentTitle'] . "\n" . $userAgentPlugin['restrictedUserAgentMessage'];
			}

			$restrictedStrings = $userAgentPlugin['restrictedUserAgents'];
			if( $restrictedStrings ) {
				$userAgent = strtolower( $this->getUserAgent() );
				$restrictedStrings = strtolower( $restrictedStrings );
				$restrictedStrings = explode(",", $restrictedStrings);

				foreach( $restrictedStrings as $string ) {
					$string = str_replace(".*", "", $string); // Removes .*
					$string = trim($string);
					if( ! strpos( $userAgent, $string ) === false ) {
						return $restrictedMessage;
					}
				}
			}
		}
		return false;
	}
	/**
	*  Access Control Handling
	*/
	public function isAccessControlAllowed( &$resultObject = null ) {
		// Kaltura only has entry level access control not playlist level access control atm: 
		// don't check anything without an entry_id
		if( !isset( $this->urlParameters['entry_id'] ) ){
			return true;
		}

		// If we have an error, return
		if( $this->error ) {
			return $this->error;
		}

		if( !$resultObject ){
			$resultObject =  $this->getResultObject();
		}
		// check for access control resultObject property:
		if( !isset( $resultObject['accessControl']) ){
			return true;
		}
		$accessControl = $resultObject['accessControl'];
		
		// Check if we had no access control due to playlist
		if( is_array( $accessControl ) && isset( $accessControl['code'] )){
			// Error ? .. should do better error checking.
			// errors we have seen so far: 
				//$accessControl['code'] == 'MISSING_MANDATORY_PARAMETER'
				//$accessControl['code'] == 'INTERNAL_SERVERL_ERROR'  
			return true;
		}
		
		// Checks if admin
		if( $accessControl->isAdmin ) {
			return true;
		}

		/* Domain Name Restricted */
		if( $accessControl->isSiteRestricted ) {
			return "Un authorized domain\nWe're sorry, this content is only available on certain domains.";
		}

		/* Country Restricted */
		if( $accessControl->isCountryRestricted) {
			return "Un authorized country\nWe're sorry, this content is only available in certain countries.";
		}

		/* IP Address Restricted */
		if( $accessControl->isIpAddressRestricted) {
			return "Un authorized IP address\nWe're sorry, this content is only available for ceratin IP addresses.";
		}

		/* Session Restricted */
		if( $accessControl->isSessionRestricted && $accessControl->previewLength == -1 ) {
			return "No KS where KS is required\nWe're sorry, access to this content is restricted.";
		}

		if( $accessControl->isScheduledNow === 0) {
			return "Out of scheduling\nWe're sorry, this content is currently unavailable.";
		}
		
		//echo $this->getUserAgent() . '<br />';
		//echo '<pre>'; print_r($accessControl); exit();
		$userAgentMessage = "User Agent Restricted\nWe're sorry, this content is not available for your device.";
		if( isset( $accessControl->isUserAgentRestricted ) && $accessControl->isUserAgentRestricted ) {
			return $userAgentMessage;
		} else {
			$userAgentRestricted = $this->isUserAgentRestrictedPlugin();
			if( $userAgentRestricted === false ) {
				return true;
			} else {
				// We have user agent restriction, set up noCache flag
				$this->noCache = true;
				if( $userAgentRestricted === true ) {
					return $userAgentMessage;
				} else {
					return $userAgentRestricted;
				}
			}
		}
		return true;
	}

	function formatString( $str ) {
		// trim any whitespace
		$str = trim( $str );
		// decode the value: 
		$str = html_entity_decode( $str );
		if( $str === "true" ) {
			return true;
		} else if( $str === "false" ) {
			return false;
		} else {
			return $str;
		}
	}

	/* setupPlayerConfig()
	 * Creates an array of our player configuration.
	 * The array is build from: Flashvars, uiVars, uiConf
	 * The array include 2 arrays:
	 * plugins - contains all of our plugins configuration
	 * vars - contain flat player configuration
	 */
	function setupPlayerConfig() {

		$plugins = array();
		$vars = array();

		// Get all plugins elements
		if( $this->uiConfFile ) {
			$pluginsXml = $this->getUiConfXML()->xpath("*//*[@id]");
			for( $i=0; $i < count($pluginsXml); $i++ ) {
				$pluginId = (string) $pluginsXml[ $i ]->attributes()->id;
				// Enforce the lower case first letter of plugin convention: 
                if ( isset( $pluginId[0] ) ) {
                    $pluginId = strtolower( $pluginId[0] ) . substr( $pluginId, 1 );
                }
				$plugins[ $pluginId ] = array(
					'plugin' => true
				);
				foreach( $pluginsXml[ $i ]->attributes() as $key => $value) {
					if( $key == "id" ) {
{'fraction_non_alphanumeric': 0.13425417005209578, 'fraction_numerical': 0.0009080915738660804, 'mean_word_length': 3.4910925091221294, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 149, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3425716', 'n_tokens_mistral': 7639, 'n_tokens_neox': 6546, 'n_words': 1887}