Example #1
0
 /**
  * will return a pair of file_root and file_path
  * This is the only function that should be extended for building a different path
  *
  * @param ISyncableFile $object
  * @param int $subType
  * @param $version
  */
 public function generateFilePathArr(ISyncableFile $object, $subType, $version = null)
 {
     //		$traces = debug_backtrace(false);
     //		foreach($traces as $i => $trace)
     //		{
     //			$file = $trace['file'];
     //			$line = $trace['line'];
     //			$class = $trace['class'];
     //			$function = $trace['function'];
     //			KalturaLog::debug("#$i Called from function [$class::$function] file[$file] line[$line]");
     //		}
     list($root, $path) = $object->generateFilePathArr($subType, $version);
     $root = str_replace('//', '/', $root);
     $path = str_replace('//', '/', $path);
     if (!kConf::hasParam('volumes')) {
         KalturaLog::debug("Path [{$root}{$path}]");
         return array($root, $path);
     }
     if (isset(self::$sessionCache[$path])) {
         return array($root, self::$sessionCache[$path]);
     }
     $volumes = kConf::get('volumes');
     $volume = $volumes[rand(0, count($volumes) - 1)];
     $newPath = str_replace('/content/', "/content/{$volume}/", $path);
     self::$sessionCache[$path] = $newPath;
     $path = $newPath;
     KalturaLog::debug("Path [{$root}{$path}]");
     return array($root, $path);
 }
Example #2
0
 protected static function init()
 {
     if (!kConf::hasParam('monitor_uri')) {
         return null;
     }
     $uri = kConf::get('monitor_uri');
     $pathInfo = parse_url($uri);
     if (isset($pathInfo['host']) && $pathInfo['port']) {
         $host = $pathInfo['host'];
         if (isset($pathInfo['scheme'])) {
             $host = $pathInfo['scheme'] . "://{$host}";
         }
         $errno = null;
         $errstr = null;
         self::$stream = fsockopen($host, $pathInfo['port'], $errno, $errstr, 1);
         if (self::$stream) {
             return true;
         }
         if (class_exists('KalturaLog')) {
             KalturaLog::err("Open socket failed: {$errstr}");
         }
     }
     self::$stream = fopen($uri, 'a');
     if (self::$stream) {
         return true;
     }
     self::$stream = false;
     // prevent init from being called again
     return false;
 }
Example #3
0
 protected function init()
 {
     if (!parent::init()) {
         return false;
     }
     // ignore params which may hurt caching such as callback, playSessionId
     if (kConf::hasParam('playmanifest_ignore_params')) {
         $ignoreParams = kConf::get('playmanifest_ignore_params');
         foreach ($ignoreParams as $paramName) {
             unset($this->_params[$paramName]);
         }
     }
     $this->_playbackContext = isset($this->_params['playbackContext']) ? $this->_params['playbackContext'] : null;
     unset($this->_params['playbackContext']);
     $this->_deliveryCode = isset($this->_params['deliveryCode']) ? $this->_params['deliveryCode'] : null;
     unset($this->_params['deliveryCode']);
     // take only the hostname part of the referrer parameter of baseEntry.getContextData
     if (isset($this->_params['referrer'])) {
         $referrer = base64_decode(str_replace(" ", "+", $this->_params['referrer']));
         if (!is_string($referrer)) {
             $referrer = "";
         }
         unset($this->_params['referrer']);
     } else {
         $referrer = self::getHttpReferrer();
     }
     $this->_referrers[] = $referrer;
     $this->finalizeCacheKey();
     $this->addExtraFields();
     return true;
 }
Example #4
0
 public function execute()
 {
     $this->result = 0;
     if (@$_REQUEST["exit"] == "true") {
         $this->systemLogout();
         $login = NULL;
         $password = NULL;
     } else {
         $login = @$_REQUEST["login"];
         $password = @$_REQUEST["pwd"];
     }
     //echo "login: $login, password: $password";
     $this->login = $login;
     $this->sign_in_referer = @$_REQUEST["sign_in_referer"];
     if (empty($this->sign_in_referer)) {
         $this->sign_in_referer = $this->getFlash("sign_in_referer");
     }
     if (empty($login) || empty($password)) {
         $this->result = 0;
     } else {
         if (kConf::hasParam("system_pages_login_password") && sha1($password) == kConf::get("system_pages_login_password")) {
             $this->systemAuthenticated();
             if (empty($this->sign_in_referer)) {
                 // should go back - the original hit was to this page - no reason to go back or refresh
                 $this->result = 2;
             } else {
                 $this->result = 1;
             }
         } else {
             $this->result = -1;
         }
     }
 }
 /**
  * @param int $type
  * @return kBaseCacheWrapper or null on error
  */
 public static function getCache($type)
 {
     if (array_key_exists($type, self::$caches)) {
         return self::$caches[$type];
     }
     if (!array_key_exists($type, self::$cacheConfigs)) {
         return null;
     }
     $config = self::$cacheConfigs[$type];
     $className = "k{$config[0]}CacheWrapper";
     require_once dirname(__FILE__) . '/' . $className . '.php';
     $cache = new $className();
     // get required kConf params
     $config = array_slice($config, 1);
     foreach ($config as $index => $value) {
         if (is_string($value) && substr($value, 0, strlen(self::KCONF_PARAM_PREFIX)) == self::KCONF_PARAM_PREFIX) {
             $value = substr($value, strlen(self::KCONF_PARAM_PREFIX));
             if (!kConf::hasParam($value)) {
                 self::$caches[$type] = null;
                 return null;
             }
             $config[$index] = kConf::get($value);
         }
     }
     // initialize the cache
     if (call_user_func_array(array($cache, 'init'), $config) === false) {
         $cache = null;
     }
     self::$caches[$type] = $cache;
     return $cache;
 }
Example #6
0
 public static function isRelativeTimeEnabled()
 {
     if (!kConf::hasParam('disable_relative_time_partners')) {
         return true;
     }
     return !in_array(kCurrentContext::getCurrentPartnerId(), kConf::get('disable_relative_time_partners'));
 }
 private static function getCacheKeyPrefix()
 {
     $result = self::GLOBAL_CACHE_KEY_PREFIX;
     if (kConf::hasParam('permission_cache_version')) {
         $result .= kConf::get('permission_cache_version');
     }
     return $result;
 }
 public function execute()
 {
     $widgetId = $this->getRequestParameter("wid");
     $widget = widgetPeer::retrieveByPK($widgetId);
     if (!$widget) {
         KalturaLog::err("Widget id [{$widgetId}] not found");
         die;
     }
     $entry = $widget->getentry();
     $entryId = $widget->getEntryId();
     if (!$entry) {
         KalturaLog::err("Entry id [{$entryId}] not found");
         die;
     }
     $uiConf = $widget->getuiConf();
     $uiConfId = $widget->getUiConfId();
     if (!$uiConf) {
         KalturaLog::err("UI Conf id [{$uiConfId}] not found");
         die;
     }
     $this->entry_name = $entry->getName();
     $this->entry_description = $entry->getDescription();
     $this->entry_thumbnail_url = $entry->getThumbnailUrl();
     $this->entry_thumbnail_secure_url = $entry->getThumbnailUrl(null, 'https');
     $this->entry_duration = $entry->getDuration();
     $flavor_tag = $this->getRequestParameter('flavor_tag', 'iphone');
     $flavor_assets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entryId, $flavor_tag);
     $flavor_asset = reset($flavor_assets);
     $flavorId = null;
     if ($flavor_asset) {
         $flavorId = $flavor_asset->getId();
     }
     $embed_host = kConf::hasParam('cdn_api_host') ? kConf::get('cdn_api_host') : kConf::get('www_host');
     $embed_host_https = kConf::hasParam('cdn_api_host_https') ? kConf::get('cdn_api_host_https') : kConf::get('www_host');
     $https_enabled = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? true : false;
     $protocol = $https_enabled ? 'https' : 'http';
     $port = $_SERVER["SERVER_PORT"] != "80" ? ":" . $_SERVER["SERVER_PORT"] : '';
     $partnerId = $widget->getPartnerId();
     $this->widget = $widget;
     $this->entry = $entry;
     $this->uiConf = $uiConf;
     // Build SWF Path
     $swfPath = "/index.php/kwidget/wid/" . $widgetId . "/uiconf_id/" . $uiConfId . "/entry_id/" . $entryId;
     // Set SWF URLs
     $this->swfUrl = 'http://' . $embed_host . $swfPath;
     $this->swfSecureUrl = 'https://' . $embed_host_https . $swfPath;
     // set player url
     $this->playerUrl = 'https://' . $embed_host_https . '/p/' . $this->partner_id . '/sp/' . $this->partner_id . '00/embedIframeJs/uiconf_id/' . $this->uiconf_id . '/partner_id/' . $this->partner_id . '?iframeembed=true&entry_id=' . $this->entry_id . '&flashvars[streamerType]=auto';
     $host = $https_enabled ? $embed_host_https : $embed_host;
     $this->html5Url = $protocol . "://" . $host . "/p/" . $partnerId . "/sp/" . $partnerId . "00/embedIframeJs/uiconf_id/" . $uiConfId . "/partner_id/" . $partnerId;
     $this->pageURL = $protocol . '://' . $_SERVER["SERVER_NAME"] . $port . $_SERVER["REQUEST_URI"];
     $this->flavorUrl = null;
     if (isset($flavorId)) {
         $this->flavorUrl = 'https://' . $embed_host_https . '/p/' . $partnerId . '/sp/' . $partnerId . '00/playManifest/entryId/' . $entryId . '/flavorId/' . $flavorId . '/format/url/protocol/' . $protocol . '/a.mp4';
     }
 }
Example #9
0
 public function __construct($filePath, $ffprobeBin = null)
 {
     if (is_null($ffprobeBin)) {
         if (kConf::hasParam('bin_path_ffprobeKAMFMediaInfoParser')) {
             $this->ffprobeBin = kConf::get('bin_path_ffprobeKAMFMediaInfoParser');
         }
     } else {
         $this->ffprobeBin = $ffprobeBin;
     }
     if (!file_exists($filePath)) {
         throw new kApplicativeException(KBaseMediaParser::ERROR_NFS_FILE_DOESNT_EXIST, "File not found at [{$filePath}]");
     }
     $this->filePath = $filePath;
 }
 /**
  * will return BatchJob objects.
  *
  * @param kExclusiveLockKey $lockKey
  * @param int $max_execution_time
  * @param int $number_of_objects
  * @param int $jobType
  * @param BatchJobFilter $filter
  */
 public static function getExclusiveJobs(kExclusiveLockKey $lockKey, $max_execution_time, $number_of_objects, $jobType, BatchJobFilter $filter)
 {
     $priority = kBatchManager::getNextJobPriority($jobType);
     $c = new Criteria();
     // added to support nfs delay
     if ($jobType == BatchJobType::EXTRACT_MEDIA || $jobType == BatchJobType::POSTCONVERT || $jobType == BatchJobType::STORAGE_EXPORT) {
         $interval = kConf::hasParam('nfs_safety_margin_sec') ? kConf::get('nfs_safety_margin_sec') : 5;
         $c->add(BatchJobPeer::CREATED_AT, time() - $interval, Criteria::LESS_THAN);
     }
     $c->add(BatchJobPeer::JOB_TYPE, $jobType);
     $c->add(BatchJobPeer::PRIORITY, $priority, Criteria::GREATER_EQUAL);
     $filter->attachToCriteria($c);
     $c->addAscendingOrderByColumn(BatchJobPeer::PRIORITY);
     $max_exe_attempts = BatchJobPeer::getMaxExecutionAttempts($jobType);
     return self::getExclusive($c, $lockKey, $max_execution_time, $number_of_objects, $max_exe_attempts);
 }
Example #11
0
 public static function getInstance($partnerId)
 {
     $partner = PartnerPeer::retrieveByPK($partnerId);
     if ($partner->getBroadcastUrlManager()) {
         $broadcastUrlManager = $partner->getBroadcastUrlManager();
         if (class_exists($broadcastUrlManager)) {
             return new $broadcastUrlManager($partnerId);
         }
     }
     if (kConf::hasParam('broadcast_url_manager')) {
         $broadcastUrlManager = kConf::get('broadcast_url_manager');
         if (class_exists($broadcastUrlManager)) {
             return new $broadcastUrlManager($partnerId);
         }
     }
     return new kBroadcastUrlManager($partnerId);
 }
 public function sendRegistrationInformationForPartner($partner, $skip_emails, $existingUser)
 {
     // email the client with this info
     $adminKuser = kuserPeer::retrieveByPK($partner->getAccountOwnerKuserId());
     $this->sendRegistrationInformation($partner, $adminKuser, $existingUser, null, $partner->getType());
     if (!$skip_emails && kConf::hasParam("report_partner_registration") && kConf::get("report_partner_registration")) {
         // email the wikisupport@kaltura.com  with this info
         $this->sendRegistrationInformation($partner, $adminKuser, $existingUser, self::KALTURA_SUPPORT);
         // if need to hook into SalesForce - this is the place
         if (include_once "mySalesForceUtils.class.php") {
             mySalesForceUtils::sendRegistrationInformationToSalesforce($partner);
         }
         // if need to hook into Marketo - this is the place
         if (include_once "myMarketoUtils.class.php") {
             myMarketoUtils::sendRegistrationInformation($partner);
         }
     }
 }
Example #13
0
 protected function internalFulfilled(kScope $scope)
 {
     $referrer = $scope->getReferrer();
     if ($this->getNot() === true && !$this->globalWhitelistDomainsAppended && strpos($referrer, "kwidget") === false && kConf::hasParam("global_whitelisted_domains")) {
         $ks = $scope->getKs();
         if (!$ks || !in_array($ks->partner_id, kConf::get('global_whitelisted_domains_exclude'))) {
             $this->globalWhitelistDomainsAppended = true;
             $globalWhitelistedDomains = kConf::get("global_whitelisted_domains");
             if (!is_array($globalWhitelistedDomains)) {
                 $globalWhitelistedDomains = explode(',', $globalWhitelistedDomains);
             }
             foreach ($globalWhitelistedDomains as $globalWhitelistedDomain) {
                 $this->values[] = new kStringValue($globalWhitelistedDomain);
             }
         }
     }
     kApiCache::addExtraField(kApiCache::ECF_REFERRER, kApiCache::COND_SITE_MATCH, $this->getStringValues($scope));
     return parent::internalFulfilled($scope);
 }
Example #14
0
function setCacheExpiry($entriesCount, $feedId)
{
    $expiryArr = kConf::hasMap("v3cache_getfeed_expiry") ? kConf::getMap("v3cache_getfeed_expiry") : array();
    foreach ($expiryArr as $item) {
        if ($item["key"] == "partnerId" && $item["value"] == kCurrentContext::$partner_id || $item["key"] == "feedId" && $item["value"] == $feedId) {
            KalturaResponseCacher::setExpiry($item["expiry"]);
            return;
        }
    }
    $expiry = kConf::get("v3cache_getfeed_default_cache_time_frame", 'local', 86400);
    if (kConf::hasParam("v3cache_getfeed_short_limits_array")) {
        $shortLimits = kConf::get("v3cache_getfeed_short_limits_array");
    } else {
        $shortLimits = array(50 => 900, 100 => 1800, 200 => 3600, 400 => 7200);
    }
    foreach ($shortLimits as $numOfEntries => $cacheTimeFrame) {
        if ($entriesCount <= $numOfEntries) {
            $expiry = min($expiry, $cacheTimeFrame);
        }
    }
    KalturaResponseCacher::setExpiry($expiry);
}
Example #15
0
 private function deleteOldFileSyncVersions(FileSync $newFileSync)
 {
     KalturaLog::debug('Deleting old file_sync versions for [' . $newFileSync->getId() . ']');
     if (kConf::hasParam('num_of_old_file_sync_versions_to_keep')) {
         $keepCount = kConf::get('num_of_old_file_sync_versions_to_keep');
         if (!is_numeric($newFileSync->getVersion())) {
             return;
         }
         $intVersion = intval($newFileSync->getVersion());
         $c = new Criteria();
         $c->add(FileSyncPeer::OBJECT_ID, $newFileSync->getObjectId());
         $c->add(FileSyncPeer::OBJECT_TYPE, $newFileSync->getObjectType());
         $c->add(FileSyncPeer::OBJECT_SUB_TYPE, $newFileSync->getObjectSubType());
         $c->add(FileSyncPeer::STATUS, array(FileSync::FILE_SYNC_STATUS_PURGED, FileSync::FILE_SYNC_STATUS_DELETED), Criteria::NOT_IN);
         $c->setLimit(40);
         //we limit the number of files to delete in one run so there will be no out of memory issues
         $fileSyncs = FileSyncPeer::doSelect($c);
         foreach ($fileSyncs as $fileSync) {
             if (is_numeric($fileSync->getVersion())) {
                 $currentIntVersion = intval($fileSync->getVersion());
                 if ($intVersion - $keepCount > $currentIntVersion) {
                     $key = kFileSyncUtils::getKeyForFileSync($fileSync);
                     self::deleteSyncFileForKey($key);
                 }
             }
         }
     }
 }
Example #16
0
 public static function adjustApiCacheForException($ex)
 {
     self::setExpiry(120);
     $cacheConditionally = false;
     if ($ex instanceof KalturaAPIException && kConf::hasParam("v3cache_conditional_cached_errors")) {
         $cacheConditionally = in_array($ex->getCode(), kConf::get("v3cache_conditional_cached_errors"));
     }
     if (!$cacheConditionally) {
         self::disableConditionalCache();
     }
 }
Example #17
0
 public static function getCdnHost($partner_id, $protocol = null, $hostType = null)
 {
     // in case the request came through https, force https url
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
         $protocol = 'https';
     }
     // temporary default is http since the system is not aligned to use https in all of its components (e.g. kmc)
     // right now, if a partner cdnHost is set to https:// the kmc wont work well if we reply with https prefix to its requests
     if ($protocol === null) {
         $protocol = 'http';
     }
     $partner = PartnerPeer::retrieveByPK($partner_id);
     if ($partner) {
         $whiteListHost = self::getWhiteListHost($partner);
         if (!is_null($whiteListHost)) {
             $cdnHost = $protocol . '://' . $whiteListHost;
             if (isset($_SERVER['SERVER_PORT'])) {
                 $cdnHost .= ":" . $_SERVER['SERVER_PORT'];
             }
             return $cdnHost;
         }
     }
     switch ($hostType) {
         case 'thumbnail':
             if ($partner && $partner->getThumbnailHost()) {
                 return preg_replace('/^https?/', $protocol, $partner->getThumbnailHost());
             }
             if ($partner && $partner->getCdnHost()) {
                 return preg_replace('/^https?/', $protocol, $partner->getCdnHost());
             }
             return requestUtils::getThumbnailCdnHost($protocol);
         case 'api':
             if ($protocol == 'https') {
                 $apiHost = kConf::hasParam('cdn_api_host_https') ? kConf::get('cdn_api_host_https') : kConf::get('www_host');
                 return 'https://' . $apiHost;
             } else {
                 $apiHost = kConf::hasParam('cdn_api_host') ? kConf::get('cdn_api_host') : kConf::get('www_host');
                 return 'http://' . $apiHost;
             }
             break;
         default:
             if ($partner && $partner->getCdnHost()) {
                 return preg_replace('/^https?/', $protocol, $partner->getCdnHost());
             }
             return requestUtils::getCdnHost($protocol);
     }
 }
Example #18
0
 public function doFromObject($dbCuePoint, KalturaDetachedResponseProfile $responseProfile = null)
 {
     parent::doFromObject($dbCuePoint, $responseProfile);
     if ($this->shouldGet('userId', $responseProfile)) {
         if ($dbCuePoint->getKuserId() !== null) {
             $dbKuser = kuserPeer::retrieveByPK($dbCuePoint->getKuserId());
             if ($dbKuser) {
                 if (!kConf::hasParam('protect_userid_in_api') || !in_array($dbCuePoint->getPartnerId(), kConf::get('protect_userid_in_api')) || !in_array(kCurrentContext::getCurrentSessionType(), array(kSessionBase::SESSION_TYPE_NONE, kSessionBase::SESSION_TYPE_WIDGET))) {
                     $this->userId = $dbKuser->getPuserId();
                 }
             }
         }
     }
 }
Example #19
0
 public static function dumpApiRequest($host, $onlyIfAvailable = false)
 {
     if ($onlyIfAvailable) {
         //validate that the other DC is available before dumping the request
         if (kConf::hasParam('disable_dump_api_request') && kConf::get('disable_dump_api_request')) {
             KalturaLog::debug('dumpApiRequest is disabled');
             return;
         }
     }
     if (kCurrentContext::$multiRequest_index > 1) {
         KExternalErrors::dieError(KExternalErrors::MULTIREQUEST_PROXY_FAILED);
     }
     self::closeDbConnections();
     // prevent loop back of the proxied request by detecting the "X-Kaltura-Proxy header
     if (isset($_SERVER["HTTP_X_KALTURA_PROXY"])) {
         KExternalErrors::dieError(KExternalErrors::PROXY_LOOPBACK);
     }
     $get_params = $post_params = array();
     // pass uploaded files by adding them as post data with curl @ prefix
     // signifying a file. the $_FILES[xxx][tmp_name] points to the location
     // of the uploaded file.
     // we preserve the original file name by passing the extra ;filename=$_FILES[xxx][name]
     foreach ($_FILES as $key => $value) {
         $post_params[$key] = "@" . $value['tmp_name'] . ";filename=" . $value['name'];
         if (!is_uploaded_file($value['tmp_name'])) {
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
     }
     foreach ($_POST as $key => $value) {
         $post_params[$key] = $value;
     }
     $url = $_SERVER['REQUEST_URI'];
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' && kConf::hasParam('https_param_salt')) {
         $post_params['apiProtocol'] = 'https_' . kConf::get('https_param_salt');
     }
     $httpHeader = array("X-Kaltura-Proxy: dumpApiRequest");
     $ipHeader = infraRequestUtils::getSignedIpAddressHeader();
     if ($ipHeader) {
         list($headerName, $headerValue) = $ipHeader;
         $httpHeader[] = $headerName . ": " . $headerValue;
     }
     $ch = curl_init();
     // set URL and other appropriate options
     curl_setopt($ch, CURLOPT_URL, $host . $url);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
     curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.11.1");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_POST, TRUE);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
     // Set callback function for body
     curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'kFileUtils::read_body');
     // Set callback function for headers
     curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'kFileUtils::read_header');
     header("X-Kaltura:dumpApiRequest " . kDataCenterMgr::getCurrentDcId());
     // grab URL and pass it to the browser
     $content = curl_exec($ch);
     // close curl resource, and free up system resources
     curl_close($ch);
     KExternalErrors::dieGracefully();
 }
Example #20
0
 /**
  * List metadata objects by filter and pager
  * 
  * @action list
  * @param KalturaMetadataFilter $filter
  * @param KalturaFilterPager $pager
  * @return KalturaMetadataListResponse
  */
 function listAction(KalturaMetadataFilter $filter = null, KalturaFilterPager $pager = null)
 {
     if (!$filter) {
         $filter = new KalturaMetadataFilter();
     }
     if (!$pager) {
         $pager = new KalturaFilterPager();
     }
     $applyPartnerFilter = true;
     if ($filter->metadataObjectTypeEqual == MetadataObjectType::ENTRY) {
         $entryIds = null;
         if ($filter->objectIdEqual) {
             $entryIds = array($filter->objectIdEqual);
         } else {
             if ($filter->objectIdIn) {
                 $entryIds = explode(',', $filter->objectIdIn);
             }
         }
         if (!$entryIds && kConf::hasParam('metadata_list_without_object_filtering_partners') && !in_array(kCurrentContext::getCurrentPartnerId(), kConf::get('metadata_list_without_object_filtering_partners')) && kCurrentContext::$ks_partner_id != Partner::BATCH_PARTNER_ID) {
             throw new KalturaAPIException(MetadataErrors::MUST_FILTER_ON_OBJECT_ID);
         }
         if ($entryIds) {
             $entryIds = entryPeer::filterEntriesByPartnerOrKalturaNetwork($entryIds, kCurrentContext::getCurrentPartnerId());
             if (!count($entryIds)) {
                 $response = new KalturaMetadataListResponse();
                 $response->objects = new KalturaMetadataArray();
                 $response->totalCount = 0;
                 return $response;
             }
             $filter->objectIdEqual = null;
             $filter->objectIdIn = implode(',', $entryIds);
             $applyPartnerFilter = false;
         }
     }
     if ($applyPartnerFilter) {
         $this->applyPartnerFilterForClass('Metadata');
     }
     return $filter->getListResponse($pager, $this->getResponseProfile());
 }
Example #21
0
 protected function handleErrorMapping(KalturaAPIException $apiException, $service, $action)
 {
     if (!kConf::hasParam('api_strict_error_map')) {
         KalturaLog::err('api_strict_error_map was not found in kConf and is mandatory!');
         return new KalturaAPIException(KalturaErrors::INTERNAL_SERVERL_ERROR);
     }
     $map = kConf::get('api_strict_error_map');
     if (!is_array($map)) {
         return $apiException;
     }
     $mapKey = strtolower($service) . '_' . strtolower($action);
     if (!isset($map[$mapKey])) {
         return $apiException;
     }
     $mapParams = $map[$mapKey];
     $defaultError = isset($mapParams['defaultError']) ? $mapParams['defaultError'] : null;
     $defaultNull = isset($mapParams['defaultNull']) ? $mapParams['defaultNull'] : null;
     $whiteListedErrors = isset($mapParams['whitelisted']) ? $mapParams['whitelisted'] : array();
     if (!is_array($whiteListedErrors)) {
         $whiteListedErrors = array();
     }
     if (array_search($apiException->getCode(), $whiteListedErrors, true) !== false) {
         KalturaLog::debug('Returning white-listed error: ' . $apiException->getCode());
         return $apiException;
     }
     // finally, replace the error or return null as default
     if ($defaultNull) {
         KalturaLog::debug('Replacing error code "' . $apiException->getCode() . '" with null result');
         return null;
     } else {
         $reflectionException = new ReflectionClass("KalturaAPIException");
         $errorStr = constant($defaultError);
         $args = array_merge(array($errorStr), $apiException->getArgs());
         /** @var KalturaAPIException $replacedException */
         $replacedException = $reflectionException->newInstanceArgs($args);
         KalturaLog::debug('Replacing error code "' . $apiException->getCode() . '" with error code "' . $replacedException->getCode() . '"');
         return $replacedException;
     }
 }
if ($wgHTTPProtocol == 'https') {
    $wgKalturaServiceUrl = wgGetUrl('cdn_api_host_https');
    $wgKalturaCDNUrl = wgGetUrl('cdn_host_https');
    $wgKalturaStatsServiceUrl = wgGetUrl('stats_host_https');
    $wgKalturaLiveStatsServiceUrl = wgGetUrl('live_stats_host_https');
}
// Default Asset CDN Path (used in ResouceLoader.php):
$wgCDNAssetPath = $wgKalturaCDNUrl;
// Default Kaltura Cache Path
$wgScriptCacheDirectory = $kConf->get('cache_root_path') . '/html5/' . $wgKalturaVersion;
if (strpos($_SERVER["HTTP_HOST"], "kaltura.com")) {
    $wgLoadScript = $wgKalturaServiceUrl . '/html5/html5lib/' . $wgKalturaVersion . '/load.php';
    $wgResourceLoaderUrl = $wgLoadScript;
}
// Salt for proxy the user IP address to Kaltura API
if ($kConf->hasParam('remote_addr_header_salt')) {
    $wgKalturaRemoteAddressSalt = $kConf->get('remote_addr_header_salt');
}
// Disable Apple HLS if defined in kConf
if ($kConf->hasParam('use_apple_adaptive')) {
    $wgKalturaUseAppleAdaptive = $kConf->get('use_apple_adaptive');
}
// Get Kaltura Supported API Features
if ($kConf->hasParam('features')) {
    $wgKalturaApiFeatures = $kConf->get('features');
}
// Allow Iframe to connect remote service
$wgKalturaAllowIframeRemoteService = true;
// Set debug for true (testing only)
$wgEnableScriptDebug = false;
// Get PlayReady License URL
 /**
  * validate a referrer either in 'restricted type' or 'allowed type'
  * 
  * @return bool
  */
 function isValid()
 {
     // get context info
     $accessControlScope = $this->getAccessControlScope();
     $referrerDomain = $accessControlScope->getReferrer();
     //$referrerDomain = preg_replace("/http[s]?\:\/\/([a-z0-9\-\.]*)\//", "\${1}", $accessControlScope->getReferrer());
     $referrerDomain = $this->extractDomainFromReferrer($referrerDomain);
     if (kConf::hasParam("global_whitelisted_domains")) {
         $globalWhitelistedDomains = kConf::get("global_whitelisted_domains");
         if ($globalWhitelistedDomains && $this->isReferrerOnSameDomain($referrerDomain, $globalWhitelistedDomains)) {
             return true;
         }
     }
     // extract site list from restriction object
     if ($this->siteList === "") {
         $sites = array();
     } else {
         $sites = explode(",", $this->siteList);
     }
     // if there is no referrer, request is not valid
     if (strlen($referrerDomain) == 0) {
         return false;
     }
     // no site lists, use defaults by the restriction type
     if (count($sites) == 0) {
         if ($this->type == self::SITE_RESTRICTION_TYPE_RESTRICT_LIST) {
             return true;
         } else {
             if ($this->type == self::SITE_RESTRICTION_TYPE_ALLOW_LIST) {
                 return false;
             }
         }
     }
     // match referrer to restricted domain list
     if ($this->type == self::SITE_RESTRICTION_TYPE_RESTRICT_LIST) {
         foreach ($sites as $site) {
             if ($this->isReferrerOnSameDomain($referrerDomain, $site)) {
                 return false;
             }
         }
         return true;
     } else {
         if ($this->type == self::SITE_RESTRICTION_TYPE_ALLOW_LIST) {
             foreach ($sites as $site) {
                 if ($this->isReferrerOnSameDomain($referrerDomain, $site)) {
                     return true;
                 }
             }
             return false;
         }
     }
 }
 /**
  * will return $max_count of objects using the peer.
  * The criteria will be used to filter the basic parameter, the function will encapsulate the inner logic of the BatchJob
  * and the exclusiveness.
  *
  * @param Criteria $c
  */
 private static function getExclusive(Criteria $c, kExclusiveLockKey $lockKey, $max_execution_time, $number_of_objects, $jobType, $maxOffset = null)
 {
     $schd = BatchJobLockPeer::SCHEDULER_ID;
     $work = BatchJobLockPeer::WORKER_ID;
     $btch = BatchJobLockPeer::BATCH_INDEX;
     $stat = BatchJobLockPeer::STATUS;
     $atmp = BatchJobLockPeer::EXECUTION_ATTEMPTS;
     $expr = BatchJobLockPeer::EXPIRATION;
     $recheck = BatchJobLockPeer::START_AT;
     $partnerLoadQuota = PartnerLoadPeer::QUOTA;
     $schd_id = $lockKey->getSchedulerId();
     $work_id = $lockKey->getWorkerId();
     $btch_id = $lockKey->getBatchIndex();
     $now = time();
     $now_str = date('Y-m-d H:i:s', $now);
     $delayedJobTypes = kConf::get('delayed_job_types');
     $apiJobType = kPluginableEnumsManager::coreToApi('BatchJobType', $jobType);
     // added to support nfs delay
     if (in_array($apiJobType, $delayedJobTypes)) {
         $interval = kConf::hasParam('nfs_safety_margin_sec') ? kConf::get('nfs_safety_margin_sec') : 5;
         $c->add(BatchJobLockPeer::CREATED_AT, time() - $interval, Criteria::LESS_THAN);
     }
     $c->add(BatchJobLockPeer::JOB_TYPE, $jobType);
     $c->add(BatchJobLockPeer::DC, kDataCenterMgr::getCurrentDcId());
     $c->add(BatchJobLockPeer::BATCH_VERSION, BatchJobLockPeer::getBatchVersion($jobType), Criteria::LESS_EQUAL);
     $prioritizers_ratio = BatchJobLockPeer::getPrioritizersRatio($jobType);
     $shouldUseJoin = BatchJobLockPeer::getMaxJobsForPartner($jobType) != self::UNLIMITED_QUOTA;
     self::addPrioritizersCondition($c, $prioritizers_ratio, $shouldUseJoin);
     // Query Parts
     $unClosedStatuses = implode(',', BatchJobPeer::getUnClosedStatusList());
     $statusCondition = "{$stat} IN ({$unClosedStatuses})";
     $lockExpiredCondition = "{$expr} <= '{$now_str}'";
     $pendingJobsCondition = "( {$stat} = " . BatchJob::BATCHJOB_STATUS_PENDING . " OR ( {$stat} = " . BatchJob::BATCHJOB_STATUS_RETRY . " AND {$recheck} <= '{$now_str}' ))";
     $unhandledJobCondition = "{$schd} IS NULL AND {$work} IS NULL AND {$btch} IS NULL ";
     $newJobsCond = "({$pendingJobsCondition} AND ({$unhandledJobCondition}))";
     if ($shouldUseJoin) {
         $partnerLoadCondition = "(({$partnerLoadQuota} > 0) OR ({$partnerLoadQuota} is null))";
         $newJobsCond .= " AND {$partnerLoadCondition}";
     }
     $jobAlreadyHandledByWorker = "{$schd} = {$schd_id} AND {$work} = {$work_id} AND {$btch} = {$btch_id}";
     $max_exe_attempts = BatchJobLockPeer::getMaxExecutionAttempts($jobType);
     $jobWasntExecutedTooMany = "{$atmp} <= {$max_exe_attempts} OR {$atmp} IS NULL";
     // Generate query
     $query = "\t{$statusCondition}\n\t\t\t\t\tAND\t(\n\t\t\t\t\t\t{$lockExpiredCondition}\n\t\t\t\t\t\tOR\t({$newJobsCond})\n\t\t\t\t\t\tOR ({$jobAlreadyHandledByWorker})\n\t\t\t\t\t)\n\t\t\t\t\tAND ({$jobWasntExecutedTooMany})";
     $c->add($stat, $query, Criteria::CUSTOM);
     // In case maxOffset isn't null, we want to take the chunk out of a random offset in between.
     // That's usefull for load handling
     if ($maxOffset) {
         $c->setOffset(rand(0, $maxOffset));
     }
     $c->setLimit($number_of_objects);
     $objects = BatchJobLockPeer::doSelect($c, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
     return self::lockObjects($lockKey, $objects, $max_execution_time);
 }
Example #25
0
 /**
  * batch reportStatus action saves the a status attribute from a remote scheduler and returns pending commands for the scheduler
  * 
  * @action reportStatus
  * @param KalturaScheduler $scheduler The scheduler
  * @param KalturaSchedulerStatusArray $schedulerStatuses A scheduler status array
  * @param KalturaWorkerQueueFilterArray $workerQueueFilters Filters list to get queues
  * @return KalturaSchedulerStatusResponse
  */
 function reportStatusAction(KalturaScheduler $scheduler, KalturaSchedulerStatusArray $schedulerStatuses, KalturaWorkerQueueFilterArray $workerQueueFilters)
 {
     $schedulerDb = $this->getOrCreateScheduler($scheduler);
     $schedulerChanged = false;
     // saves the statuses to the DB
     foreach ($schedulerStatuses as $schedulerStatus) {
         $schedulerStatus->schedulerId = $schedulerDb->getId();
         $schedulerStatus->schedulerConfiguredId = $scheduler->configuredId;
         if ($schedulerStatus->workerConfiguredId) {
             $worker = $this->getOrCreateWorker($schedulerDb, $schedulerStatus->workerConfiguredId, $schedulerStatus->workerType);
             $worker->setStatus($schedulerStatus->type, $schedulerStatus->value);
             $worker->save();
             $schedulerStatus->workerId = $worker->getId();
         } else {
             $schedulerChanged = true;
             $schedulerDb->setStatus($schedulerStatus->type, $schedulerStatus->value);
         }
         $schedulerStatusDb = new SchedulerStatus();
         $schedulerStatus->toObject($schedulerStatusDb);
         $schedulerStatusDb->save();
     }
     if ($schedulerChanged) {
         $schedulerDb->save();
     }
     // creates a response
     $schedulerStatusResponse = new KalturaSchedulerStatusResponse();
     if (kConf::hasParam('batch_enable_control_panel') && kConf::get('batch_enable_control_panel')) {
         // gets the control pannel commands
         $c = new Criteria();
         $c->add(ControlPanelCommandPeer::SCHEDULER_ID, $schedulerDb->getId());
         $c->add(ControlPanelCommandPeer::TYPE, KalturaControlPanelCommandType::CONFIG, Criteria::NOT_EQUAL);
         $c->add(ControlPanelCommandPeer::STATUS, KalturaControlPanelCommandStatus::PENDING);
         $commandsList = ControlPanelCommandPeer::doSelect($c);
         foreach ($commandsList as $command) {
             $command->setStatus(KalturaControlPanelCommandStatus::HANDLED);
             $command->save();
         }
         $schedulerStatusResponse->controlPanelCommands = KalturaControlPanelCommandArray::fromDbArray($commandsList, $this->getResponseProfile());
         // gets new configs
         $c = new Criteria();
         $c->add(SchedulerConfigPeer::SCHEDULER_ID, $schedulerDb->getId());
         $c->add(SchedulerConfigPeer::COMMAND_STATUS, KalturaControlPanelCommandStatus::PENDING);
         $configList = SchedulerConfigPeer::doSelect($c);
         foreach ($configList as $config) {
             $config->setCommandStatus(KalturaControlPanelCommandStatus::HANDLED);
             $config->save();
         }
         $schedulerStatusResponse->schedulerConfigs = KalturaSchedulerConfigArray::fromDbArray($configList, $this->getResponseProfile());
     } else {
         $schedulerStatusResponse->controlPanelCommands = new KalturaControlPanelCommandArray();
         $schedulerStatusResponse->schedulerConfigs = new KalturaSchedulerConfigArray();
     }
     // gets queues length
     $schedulerStatusResponse->queuesStatus = new KalturaBatchQueuesStatusArray();
     foreach ($workerQueueFilters as $workerQueueFilter) {
         $dbJobType = kPluginableEnumsManager::apiToCore('BatchJobType', $workerQueueFilter->jobType);
         $filter = $workerQueueFilter->filter->toFilter($dbJobType);
         $batchQueuesStatus = new KalturaBatchQueuesStatus();
         $batchQueuesStatus->jobType = $workerQueueFilter->jobType;
         $batchQueuesStatus->workerId = $workerQueueFilter->workerId;
         $batchQueuesStatus->size = kBatchManager::getQueueSize($workerQueueFilter->schedulerId, $workerQueueFilter->workerId, $dbJobType, $filter);
         $schedulerStatusResponse->queuesStatus[] = $batchQueuesStatus;
     }
     return $schedulerStatusResponse;
 }
Example #26
0
<?php

if (kConf::hasParam("testme_tracking_code")) {
    require kConf::get("testme_tracking_code");
}
?>
</body>
</html>
Example #27
0
 public function doFromObject($sourceObject, KalturaDetachedResponseProfile $responseProfile = null)
 {
     if (!$sourceObject) {
         return;
     }
     entryPeer::addValidatedEntry($sourceObject->getId());
     parent::doFromObject($sourceObject, $responseProfile);
     $partnerId = kCurrentContext::$ks_partner_id ? kCurrentContext::$ks_partner_id : kCurrentContext::$partner_id;
     if (implode(',', kEntitlementUtils::getKsPrivacyContext()) != kEntitlementUtils::DEFAULT_CONTEXT . $partnerId) {
         $this->categories = null;
         $this->categoriesIds = null;
     }
     if (!kConf::hasParam('protect_userid_in_api') || !in_array($sourceObject->getPartnerId(), kConf::get('protect_userid_in_api')) || !in_array(kCurrentContext::getCurrentSessionType(), array(kSessionBase::SESSION_TYPE_NONE, kSessionBase::SESSION_TYPE_WIDGET))) {
         if ($this->shouldGet('userId', $responseProfile)) {
             $this->userId = $sourceObject->getPuserId();
         }
         if ($this->shouldGet('creatorId', $responseProfile)) {
             $this->creatorId = $sourceObject->getCreatorPuserId();
         }
     }
 }
 public function execute()
 {
     sfView::SUCCESS;
     /** check parameters and verify user is logged-in **/
     $this->partner_id = $this->getP("pid");
     $this->subp_id = $this->getP("subpid", (int) $this->partner_id * 100);
     $this->uid = $this->getP("uid");
     $this->ks = $this->getP("kmcks");
     if (!$this->ks) {
         // if kmcks from cookie doesn't exist, try ks from REQUEST
         $this->ks = $this->getP('ks');
     }
     $this->screen_name = $this->getP("screen_name");
     $this->email = $this->getP("email");
     /** if no KS found, redirect to login page **/
     if (!$this->ks) {
         $this->redirect("kmc/kmc");
         die;
     }
     $ksObj = kSessionUtils::crackKs($this->ks);
     /** END - check parameters and verify user is logged-in **/
     /** Get array of allowed partners for the current user **/
     $this->allowedPartners = array();
     $currentUser = kuserPeer::getKuserByPartnerAndUid($this->partner_id, $ksObj->user, true);
     if ($currentUser) {
         $partners = myPartnerUtils::getPartnersArray($currentUser->getAllowedPartnerIds());
         foreach ($partners as $partner) {
             $this->allowedPartners[] = array('id' => $partner->getId(), 'name' => $partner->getName());
         }
         $this->full_name = $currentUser->getFullName();
     }
     /** load partner from DB, and set templatePartnerId **/
     $this->partner = $partner = null;
     $this->templatePartnerId = self::SYSTEM_DEFAULT_PARTNER;
     $this->ignoreSeoLinks = false;
     $this->ignoreEntrySeoLinks = false;
     $this->useEmbedCodeProtocolHttps = false;
     $this->v2Flavors = false;
     if ($this->partner_id !== NULL) {
         $this->partner = $partner = PartnerPeer::retrieveByPK($this->partner_id);
         kmcUtils::redirectPartnerToCorrectKmc($partner, $this->ks, $this->uid, $this->screen_name, $this->email, self::CURRENT_KMC_VERSION);
         $this->templatePartnerId = $this->partner ? $this->partner->getTemplatePartnerId() : self::SYSTEM_DEFAULT_PARTNER;
         $this->ignoreSeoLinks = $this->partner->getIgnoreSeoLinks();
         $this->ignoreEntrySeoLinks = PermissionPeer::isValidForPartner(PermissionName::FEATURE_IGNORE_ENTRY_SEO_LINKS, $this->partner_id);
         $this->useEmbedCodeProtocolHttps = PermissionPeer::isValidForPartner(PermissionName::FEATURE_EMBED_CODE_DEFAULT_PROTOCOL_HTTPS, $this->partner_id);
         $this->v2Flavors = PermissionPeer::isValidForPartner(PermissionName::FEATURE_V2_FLAVORS, $this->partner_id);
     }
     /** END - load partner from DB, and set templatePartnerId **/
     /** set default flags **/
     $this->payingPartner = 'false';
     $this->kdp508_players = array();
     $this->first_login = false;
     /** END - set default flags **/
     /** set values for template **/
     $this->service_url = myPartnerUtils::getHost($this->partner_id);
     $this->host = $this->stripProtocol($this->service_url);
     $this->embed_host = $this->host;
     if (kConf::hasParam('cdn_api_host') && kConf::hasParam('www_host') && $this->host == kConf::get('cdn_api_host')) {
         $this->host = kConf::get('www_host');
     }
     $this->cdn_url = myPartnerUtils::getCdnHost($this->partner_id);
     $this->cdn_host = $this->stripProtocol($this->cdn_url);
     $this->rtmp_host = myPartnerUtils::getRtmpUrl($this->partner_id);
     $this->flash_dir = $this->cdn_url . myContentStorage::getFSFlashRootPath();
     // Decide if to hide akamai delivery type
     $this->hideAkamaiHDNetwork = $partner->getDisableAkamaiHDNetwork();
     /** set payingPartner flag **/
     if ($partner && $partner->getPartnerPackage() != PartnerPackages::PARTNER_PACKAGE_FREE) {
         $this->payingPartner = 'true';
     }
     /** END - set payingPartner flag **/
     /** get partner languae **/
     $this->language = null;
     if ($partner->getKMCLanguage()) {
         $this->language = $partner->getKMCLanguage();
     }
     /** END - get partner languae **/
     /** set first_login flag **/
     $this->first_login = $partner->getIsFirstLogin();
     if ($this->first_login === true) {
         $partner->setIsFirstLogin(false);
         $partner->save();
     }
     /** END - set first_login flag **/
     /** get logout url **/
     $this->logoutUrl = null;
     if ($partner->getLogoutUrl()) {
         $this->logoutUrl = $partner->getLogoutUrl();
     }
     /** END - get logout url**/
     /** partner-specific: change KDP version for partners working with auto-moderaion **/
     // set content kdp version according to partner id
     $moderated_partners = array(31079, 28575, 32774);
     $this->content_kdp_version = 'v2.7.0';
     if (in_array($this->partner_id, $moderated_partners)) {
         $this->content_kdp_version = 'v2.1.2.29057';
     }
     /** END - partner-specific: change KDP version for partners working with auto-moderaion **/
     $this->kmc_swf_version = kConf::get('kmc_version');
     /** uiconf listing work **/
     /** fill $this->confs with all uiconf objects for all modules **/
     $kmcGeneralUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, self::SYSTEM_DEFAULT_PARTNER);
     $kmcGeneralTemplateUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, $this->templatePartnerId);
     /** for each module, create separated lists of its uiconf, for each need **/
     /** kmc general uiconfs **/
     $this->kmc_general = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcgeneral", false, $kmcGeneralUiConf);
     $this->kmc_permissions = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcpermissions", false, $kmcGeneralUiConf);
     /** P&E players: **/
     //$this->content_uiconfs_previewembed = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed", true, $kmcGeneralUiConf);
     //$this->content_uiconfs_previewembed_list = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed_list", true, $kmcGeneralUiConf);
     $this->content_uiconfs_flavorpreview = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_flavorpreview", false, $kmcGeneralUiConf);
     /* KCW uiconfs */
     $this->content_uiconfs_upload_webcam = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadWebCam", false, $kmcGeneralUiConf);
     $this->content_uiconfs_upload_import = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadImport", false, $kmcGeneralUiConf);
     $this->content_uiconds_clipapp_kdp = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kdpClipApp", false, $kmcGeneralUiConf);
     $this->content_uiconds_clipapp_kclip = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kClipClipApp", false, $kmcGeneralUiConf);
     /** content KCW,KSE,KAE **/
     //$this->content_uiconfs_upload = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_upload", false, $kmcGeneralUiConf);
     //$this->simple_editor = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_simpleedit", false, $kmcGeneralUiConf);
     //$this->advanced_editor = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_advanceedit", false, $kmcGeneralUiConf);
     /** END - uiconf listing work **/
     /** get templateXmlUrl for whitelabeled partners **/
     //$this->appstudio_templatesXmlUrl = $this->getAppStudioTemplatePath();
 }
$wgKalturaVersion = basename(getcwd());
// Gets the version by the folder name
// The default Kaltura service url:
$wgKalturaServiceUrl = $wgHTTPProtocol . '://' . $kConf->get('cdn_api_host');
// Default Kaltura CDN url:
$wgKalturaCDNUrl = $wgHTTPProtocol . '://' . $kConf->get('cdn_host');
// Default Stats URL
$wgKalturaStatsServiceUrl = $wgHTTPProtocol . '://' . $kConf->get('stats_host');
// SSL host names
if ($wgHTTPProtocol == 'https') {
    $wgKalturaServiceUrl = $wgHTTPProtocol . '://' . $kConf->get('cdn_api_host_https');
    $wgKalturaCDNUrl = $wgHTTPProtocol . '://' . $kConf->get('cdn_host_https');
    $wgKalturaStatsServiceUrl = $wgHTTPProtocol . '://' . $kConf->get('stats_host_https');
}
// Default Asset CDN Path (used in ResouceLoader.php):
$wgCDNAssetPath = $wgKalturaCDNUrl;
// Default Kaltura Cache Path
$wgScriptCacheDirectory = $kConf->get('cache_root_path') . '/html5/' . $wgKalturaVersion;
$wgResourceLoaderUrl = $wgKalturaServiceUrl . '/html5/html5lib/' . $wgKalturaVersion . '/load.php';
// Salt for proxy the user IP address to Kaltura API
if ($kConf->hasParam('remote_addr_header_salt')) {
    $wgKalturaRemoteAddressSalt = $kConf->get('remote_addr_header_salt');
}
// Disable Apple HLS if defined in kConf
if ($kConf->hasParam('use_apple_adaptive')) {
    $wgKalturaUseAppleAdaptive = $kConf->get('use_apple_adaptive');
}
// Allow Iframe to connect remote service
$wgKalturaAllowIframeRemoteService = true;
// Set debug for true (testing only)
$wgEnableScriptDebug = false;
 public function execute()
 {
     //entitlement should be disabled to serveFlavor action as we do not get ks on this action.
     KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
     requestUtils::handleConditionalGet();
     $flavorId = $this->getRequestParameter("flavorId");
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     $fileName = $this->getRequestParameter("fileName");
     $fileParam = $this->getRequestParameter("file");
     $fileParam = basename($fileParam);
     $pathOnly = $this->getRequestParameter("pathOnly", false);
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     $flavorAsset = assetPeer::retrieveById($flavorId);
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $entryId = $this->getRequestParameter("entryId");
     if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     if ($fileName) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
         header("Content-Type: application/force-download");
         header("Content-Description: File Transfer");
     }
     $clipTo = null;
     $entry = $flavorAsset->getentry();
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId());
     myPartnerUtils::enforceDelivery($entry, $flavorAsset);
     $version = $this->getRequestParameter("v");
     if (!$version) {
         $version = $flavorAsset->getVersion();
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version);
     if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) {
         $path = null;
         list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false);
         if ($file_sync) {
             $parent_file_sync = kFileSyncUtils::resolve($file_sync);
             $path = $parent_file_sync->getFullPath();
             if ($fileParam && is_dir($path)) {
                 $path .= "/{$fileParam}";
             }
         }
         $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json');
         if ($path) {
             $this->storeCache($renderer, $flavorAsset->getPartnerId());
         }
         $renderer->output();
         KExternalErrors::dieGracefully();
     }
     if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     if (!kFileSyncUtils::file_exists($syncKey, false)) {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         // always dump remote urls so they will be cached by the cdn transparently
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         kFileUtils::dumpUrl($remoteUrl);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $isFlv = false;
     if (!$shouldProxy) {
         $flvWrapper = new myFlvHandler($path);
         $isFlv = $flvWrapper->isFlv();
     }
     $clipFrom = $this->getRequestParameter("clipFrom", 0);
     // milliseconds
     if (is_null($clipTo)) {
         $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO);
     }
     // milliseconds
     if ($clipTo == 0) {
         $clipTo = self::NO_CLIP_TO;
     }
     if (!is_numeric($clipTo) || $clipTo < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number');
     }
     $seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($seekFrom <= 0) {
         $seekFrom = -1;
     }
     $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1);
     if ($seekFromBytes <= 0) {
         $seekFromBytes = -1;
     }
     if ($fileParam && is_dir($path)) {
         $path .= "/{$fileParam}";
         kFileUtils::dumpFile($path, null, null);
         KExternalErrors::dieGracefully();
     } else {
         if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) {
             $limit_file_size = 0;
             if ($clipTo != self::NO_CLIP_TO) {
                 if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) {
                     $contentPath = myContentStorage::getFSContentRootPath();
                     $tempClipName = $version . '_' . $clipTo . '.mp4';
                     $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName);
                     if (!file_exists($tempClipPath)) {
                         kFile::fullMkdir($tempClipPath);
                         $clipToSec = round($clipTo / 1000, 3);
                         $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1";
                         KalturaLog::log("Executing {$cmdLine}");
                         $output = array();
                         $return_value = "";
                         exec($cmdLine, $output, $return_value);
                         KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output));
                     }
                     if (file_exists($tempClipPath)) {
                         KalturaLog::log("Dumping {$tempClipPath}");
                         kFileUtils::dumpFile($tempClipPath);
                     } else {
                         KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping');
                     }
                 }
                 $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
                 if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                     $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                     $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2);
                 }
             }
             $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size);
             if (!$fileName) {
                 $this->storeCache($renderer, $flavorAsset->getPartnerId());
             }
             $renderer->output();
             KExternalErrors::dieGracefully();
         }
     }
     $audioOnly = $this->getRequestParameter("audioOnly");
     // milliseconds
     if ($audioOnly === '0') {
         // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) {
         $audioOnly = true;
     }
     $bytes = 0;
     if ($seekFrom !== -1 && $seekFrom !== 0) {
         list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly);
         list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly);
         $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte;
     } else {
         list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     }
     $metadataSize = $flvWrapper->getMetadataSize($audioOnly);
     $dataOffset = $metadataSize + myFlvHandler::getHeaderSize();
     $totalLength = $dataOffset + $bytes;
     list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength);
     if ($totalLength < 1000) {
         // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache
         requestUtils::sendCdnHeaders("flv", $rangeLength, 0);
     } else {
         requestUtils::sendCdnHeaders("flv", $rangeLength);
     }
     // dont inject cuepoint into the stream
     $cuepointTime = 0;
     $cuepointPos = 0;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("serveFlavor: error closing db {$e}");
     }
     header("Content-Type: video/x-flv");
     $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos);
     KExternalErrors::dieGracefully();
 }