public function validateApiAccessControl() { if (kIpAddressUtils::isInternalIp()) { return true; } if ($this->getEnforceHttpsApi() && infraRequestUtils::getProtocol() != infraRequestUtils::PROTOCOL_HTTPS) { KalturaLog::err('Action was accessed over HTTP while the partner is configured for HTTPS access only'); return false; } $accessControl = $this->getApiAccessControl(); if (is_null($accessControl)) { return true; } $context = new kEntryContextDataResult(); $scope = new accessControlScope(); $scope->setKs(kCurrentContext::$ks); $scope->setContexts(array(ContextType::PLAY)); $disableCache = $accessControl->applyContext($context, $scope); if ($disableCache) { kApiCache::disableCache(); } if (count($context->getMessages())) { header("X-Kaltura-API-Access-Control: " . implode(', ', $context->getMessages())); } if (count($context->getActions())) { $actions = $context->getActions(); foreach ($actions as $action) { /* @var $action kAccessControlAction */ if ($action->getType() == RuleActionType::BLOCK) { KalturaLog::err('Action was blocked by API access control'); return false; } } } return true; }
public function output() { if ($this->maxAge && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $_SERVER['HTTP_IF_MODIFIED_SINCE'] == infraRequestUtils::formatHttpTime($this->lastModified)) { infraRequestUtils::sendCachingHeaders($this->maxAge, false, $this->lastModified); header("HTTP/1.1 304 Not Modified"); return; } $useXsendFile = false; $rangeLength = null; if (!$this->fileData && $this->xSendFileAllowed && in_array('mod_xsendfile', apache_get_modules())) { $useXsendFile = true; } else { list($rangeFrom, $rangeTo, $rangeLength) = infraRequestUtils::handleRangeRequest($this->fileSize); } if (class_exists('KalturaMonitorClient')) { KalturaMonitorClient::monitorDumpFile($this->fileSize, $this->filePath); } infraRequestUtils::sendCdnHeaders($this->fileExt, $rangeLength, $this->maxAge, $this->mimeType, false, $this->lastModified); // return "Accept-Ranges: bytes" header. Firefox looks for it when playing ogg video files // upon detecting this header it cancels its original request and starts sending byte range requests header("Accept-Ranges: bytes"); header("Access-Control-Allow-Origin:*"); if ($this->fileData) { echo substr($this->fileData, $rangeFrom, $rangeLength); } else { if ($useXsendFile) { header('X-Kaltura-Sendfile:'); header("X-Sendfile: {$this->filePath}"); } else { infraRequestUtils::dumpFilePart($this->filePath, $rangeFrom, $rangeLength); } } }
public static function dieError($errorCode, $message = null) { $description = self::$errorDescriptionMap[$errorCode]; $args = func_get_args(); if (count($args) > 1) { array_shift($args); $description = @call_user_func_array('sprintf', array_merge(array($description), $args)); } if ($message) { $description .= ", {$message}"; } KalturaLog::err("exiting on error {$errorCode} - {$description}"); $headers = array(); if (self::$responseCode) { $headers[] = self::$errorCodeMap[self::$responseCode]; } $headers[] = "X-Kaltura-App: exiting on error {$errorCode} - {$description}"; foreach ($headers as $header) { header($header); } header("X-Kaltura:error-{$errorCode}"); $headers[] = "X-Kaltura:cached-error-{$errorCode}"; self::terminateDispatch(); if ($errorCode != self::ACCESS_CONTROL_RESTRICTED && $errorCode != self::IP_COUNTRY_BLOCKED && $_SERVER["REQUEST_METHOD"] == "GET") { requestUtils::sendCachingHeaders(self::CACHE_EXPIRY, true, time()); if (function_exists('apc_store')) { $protocol = infraRequestUtils::getProtocol(); $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST']; $uri = $_SERVER["REQUEST_URI"]; apc_store("exterror-{$protocol}://{$host}{$uri}", $headers, self::CACHE_EXPIRY); } } die; }
protected static function getRemoteAddress() { $remoteAddr = infraRequestUtils::getIpFromHttpHeader('HTTP_X_FORWARDED_FOR', false); if (!$remoteAddr) { $remoteAddr = $_SERVER['REMOTE_ADDR']; } return $remoteAddr; }
public function getFieldValue(kScope $scope) { if ($this->getHttpHeader() || $this->getAcceptInternalIps()) { kApiCache::addExtraField(array("type" => kApiCache::ECF_IP, kApiCache::ECFD_IP_HTTP_HEADER => $this->getHttpHeader(), kApiCache::ECFD_IP_ACCEPT_INTERNAL_IPS => $this->getAcceptInternalIps()), kApiCache::COND_IP_RANGE, $this->getStringValues($scope)); return infraRequestUtils::getIpFromHttpHeader($this->getHttpHeader(), $this->getAcceptInternalIps(), true); } kApiCache::addExtraField(kApiCache::ECF_IP, kApiCache::COND_IP_RANGE, $this->getStringValues($scope)); return $scope->getIp(); }
public function output() { header('Content-Length: ' . strlen($this->content)); if ($this->contentType) { header('Content-Type: ' . $this->contentType); } header("Access-Control-Allow-Origin:*"); infraRequestUtils::sendCachingHeaders($this->maxAge); echo $this->content; }
/** * Register to a queue from which event messages will be provided according to given template. Queue will be created if not already exists * * @action register * @actionAlias eventNotification_eventNotificationTemplate.register * @param string $notificationTemplateSystemName Existing push notification template system name * @param KalturaEventNotificationParameterArray $userParamsArray User params * @return KalturaPushNotificationData */ function registerAction($notificationTemplateSystemName, $userParamsArray) { // find the template, according to its system name, on both current partner and partner 0 $partnerId = $this->getPartnerId(); $partnersIds = array(PartnerPeer::GLOBAL_PARTNER, $partnerId); $dbEventNotificationTemplate = EventNotificationTemplatePeer::retrieveBySystemName($notificationTemplateSystemName, null, $partnersIds); if (!$dbEventNotificationTemplate) { throw new KalturaAPIException(KalturaEventNotificationErrors::EVENT_NOTIFICATION_TEMPLATE_SYSTEM_NAME_NOT_FOUND, $notificationTemplateSystemName); } // verify template is push typed if (!$dbEventNotificationTemplate instanceof PushNotificationTemplate) { throw new KalturaAPIException(KalturaEventNotificationErrors::EVENT_NOTIFICATION_WRONG_TYPE, $notificationTemplateSystemName, get_class($dbEventNotificationTemplate)); } // Check all template needed params were actually given $missingParams = array(); $templateParams = $dbEventNotificationTemplate->getContentParameters(); // create array of all keys $userParamsArrayKeys = array(); foreach ($userParamsArray as $userParam) { array_push($userParamsArrayKeys, $userParam->toObject()->getKey()); } foreach ($templateParams as $templateParam) { if (!in_array($templateParam->getKey(), $userParamsArrayKeys)) { array_push($missingParams, $templateParam->getKey()); } } if ($missingParams != null) { throw new KalturaAPIException(KalturaErrors::MISSING_MANDATORY_PARAMETER, implode(",", $missingParams)); } //check that keys actually have values foreach ($userParamsArray as $userParam) { $userParamObj = $userParam->toObject(); if (!$userParamObj->getValue()) { KalturaLog::debug(print_r($userParamObj, true)); throw new KalturaAPIException(KalturaErrors::MISSING_MANDATORY_PARAMETER, "Value of " . $userParamObj->getKey()); } } $queueKey = $dbEventNotificationTemplate->getQueueKey($userParamsArray->toObjectsArray(), $partnerId, null); $hash = kCurrentContext::$ks_object->getHash(); // create queue if not exists if (!$dbEventNotificationTemplate->exists($queueKey)) { $dbEventNotificationTemplate->create($queueKey); } $result = new KalturaPushNotificationData(); $result->key = $this->encode($queueKey . ":" . $hash); // build the url to return $protocol = infraRequestUtils::getProtocol(); $host = kConf::get("push_server_host"); $secret = kConf::get("push_server_secret"); $ip = kCurrentContext::$user_ip; $token = base64_encode($partnerId . ":" . $this->encode($secret . ":" . $ip . ":" . $hash . ":" . uniqid())); $result->url = $protocol . "://" . $host . "/?p=" . $partnerId . "&x=" . urlencode($token); return $result; }
public static function get() { if (self::$_ip === null) { try { self::$_ip = (string) infraRequestUtils::getRemoteAddress(); } catch (Exception $ex) { self::$_ip = ''; } } return self::$_ip; }
private static function getObjectTypeCacheKey(IRelatedObject $object) { $userRoles = kPermissionManager::getCurrentRoleIds(); sort($userRoles); $objectType = get_class($object); $partnerId = self::$cachedObject->getPartnerId(); $profileKey = self::$responseProfileKey; $protocol = infraRequestUtils::getProtocol(); $ksType = kCurrentContext::getCurrentSessionType(); $userRoles = implode('-', $userRoles); $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; return "relate_rp{$profileKey}_p{$partnerId}_o{$objectType}_h{$protocol}_k{$ksType}_u{$userRoles}_w{$host}"; }
public function execute() { // Prevent the page fron being embeded in an iframe header('X-Frame-Options: DENY'); // Check if user already logged in and redirect to kmc2 if ($this->getRequest()->getCookie('kmcks')) { $this->redirect('kmc/kmc2'); } if (infraRequestUtils::getProtocol() != infraRequestUtils::PROTOCOL_HTTPS && kConf::get('kmc_secured_login')) { $url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; header('Location:' . $url); die; } $this->www_host = kConf::get('www_host'); $https_enabled = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? true : false; $this->securedLogin = kConf::get('kmc_secured_login') || $https_enabled ? true : false; $swfUrl = $this->securedLogin ? 'https://' : 'http://'; $swfUrl .= $this->www_host . myContentStorage::getFSFlashRootPath(); $swfUrl .= '/kmc/login/' . kConf::get('kmc_login_version') . '/login.swf'; $this->swfUrl = $swfUrl; $this->partner_id = $this->getRequestParameter("partner_id"); $this->logoUrl = null; if ($this->partner_id) { $partner = PartnerPeer::retrieveByPK($this->partner_id); if ($partner) { $this->logoUrl = kmcUtils::getWhitelabelData($partner, 'logo_url'); } } $this->beta = $this->getRequestParameter("beta"); //prevent script injections - allow only base64_encode chars , which is used when creating A new hash key $passHashparam = $this->getRequestParameter("setpasshashkey"); if ($passHashparam && !preg_match(self::BASE64_ENCODE_CHARS_REGEX, $passHashparam)) { KExternalErrors::dieError(KExternalErrors::INVALID_HASH); } $this->setPassHashKey = $passHashparam; $this->hashKeyErrorCode = null; $this->displayErrorFromServer = false; if ($this->setPassHashKey) { try { $loginData = UserLoginDataPeer::isHashKeyValid($this->setPassHashKey); $partnerId = $loginData->getConfigPartnerId(); $partner = PartnerPeer::retrieveByPK($partnerId); if ($partner && $partner->getPasswordStructureValidations()) { $this->displayErrorFromServer = true; } } catch (kCoreException $e) { $this->hashKeyErrorCode = $e->getCode(); } } sfView::SUCCESS; }
/** * Returns the delivery profile that matches the entryID and the streamer type. * @param string $entryId The entry id * @param PlayBackProtocol $streamerType the streamer type * @return DeliveryProfile */ public static function getDeliveryProfile($entryId, $streamerType = PlaybackProtocol::HTTP) { $deliveryAttributes = DeliveryProfileDynamicAttributes::init(null, $entryId, $streamerType); if ($streamerType == PlaybackProtocol::HTTP) { $deliveryAttributes->setMediaProtocol(infraRequestUtils::getProtocol()); $delivery = self::getLocalDeliveryByPartner($entryId, $streamerType, $deliveryAttributes, null, null, false); if ($delivery) { return $delivery; } // if a delivery profile wasn't found try again without forcing the request protocol $deliveryAttributes->setMediaProtocol(null); } return self::getLocalDeliveryByPartner($entryId, $streamerType, $deliveryAttributes, null, null, false); }
/** * @action pingDatabase * @return bool Always true if database available and writeable */ function pingDatabaseAction() { $hostname = infraRequestUtils::getHostname(); $server = ApiServerPeer::retrieveByHostname($hostname); if (!$server) { $server = new ApiServer(); $server->setHostname($hostname); } $server->setUpdatedAt(time()); if (!$server->save()) { return false; } return true; }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser, $create_cachekey = false) { myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3; // TODO - verify permissions for viewing lists $detailed = $this->getP("detailed", false); if (!$detailed) { $detailed = false; } $playlist_id = $this->getPM("playlist_id"); if ($create_cachekey) { if ($this->isAdmin()) { return null; } $ks_partner_id = null; $privileges = null; $ks = ks::fromSecureString(kCurrentContext::$ks); if ($ks) { $ks_partner_id = $ks->getPartnerId(); $privileges = $ks->getPrivileges(); } $cache_key_arr = array("playlist_id" => $playlist_id, "partner_id" => $partner_id, "ks_partner_id" => $ks_partner_id, "detailed" => $detailed, "user" => kCurrentContext::$ks_uid, "privileges" => $privileges, "is_admin" => $this->isAdmin(), "protocol" => infraRequestUtils::getProtocol()); $cahce_key = new executionCacheKey(); $cahce_key->expiry = 600; $cahce_key->key = md5(print_r($cache_key_arr, true)); return $cahce_key; } // this service is executed twice! (first time for the cache key, second time for the execution) if (is_null($this->playlist)) { $playlist = entryPeer::retrieveByPK($playlist_id); if (!$playlist) { throw new APIException(APIErrors::INVALID_ENTRY_ID, "Playlist", $playlist_id); } myPartnerUtils::addPartnerToCriteria('accessControl', $playlist->getPartnerId(), $this->getPrivatePartnerData(), $this->partnerGroup2(), null); $this->playlist = $playlist; } if ($this->isAdmin()) { myPlaylistUtils::setIsAdminKs(true); } $entry_list = myPlaylistUtils::executePlaylistById($partner_id, $playlist_id, null, $detailed); myEntryUtils::updatePuserIdsForEntries($entry_list); $level = $detailed ? objectWrapperBase::DETAIL_LEVEL_DETAILED : objectWrapperBase::DETAIL_LEVEL_REGULAR; $wrapper = objectWrapperBase::getWrapperClass($entry_list, $level); $this->addMsg("count", count($entry_list)); $this->addMsg($this->getObjectPrefix(), $wrapper); }
public function getExternalUrl($entryId, $format = PlaybackProtocol::HTTP) { $storage = StorageProfilePeer::retrieveByPK($this->getDc()); if (!$storage || $storage->getProtocol() == StorageProfile::STORAGE_KALTURA_DC) { return kDataCenterMgr::getInternalRemoteUrl($this); } $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($this->getDc(), $entryId, PlaybackProtocol::HTTP, infraRequestUtils::getProtocol())); if (is_null($urlManager) && infraRequestUtils::getProtocol() != 'http') { $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($this->getDc(), $entryId)); } if (is_null($urlManager)) { return null; } $url = $urlManager->getFileSyncUrl($this); $baseUrl = $urlManager->getUrl(); $url = ltrim($url, "/"); if (strpos($url, "://") === false) { $url = rtrim($baseUrl, "/") . "/" . $url; } return $url; }
protected function handleEntries($context, $feed, array $entries) { $protocol = infraRequestUtils::getProtocol(); $cachePrefix = "dist_" . $this->profile->getId() . "/{$protocol}/entry_"; $profileUpdatedAt = $this->profile->getUpdatedAt(null); $extendItems = $this->profile->getItemXpathsToExtend(); $enableCache = empty($extendItems); $cacheStore = null; if ($enableCache) { $cacheStore = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_FEED_ENTRY); if (is_null($cacheStore)) { $enableCache = false; } } $counter = 0; foreach ($entries as $entry) { $xml = null; $cacheKey = $cachePrefix . str_replace("_", "-", $entry->getId()); // replace _ with - so cache folders will be created with random entry id and not 0_/1_ if ($enableCache) { $cacheTime = $cacheStore->get($cacheKey . self::CACHE_CREATION_TIME_SUFFIX); $updatedAt = max($profileUpdatedAt, $entry->getUpdatedAt(null)); if ($updatedAt + self::CACHE_CREATION_MARGIN < $cacheTime) { $xml = $cacheStore->get($cacheKey); } } if (!$xml) { $entryDistribution = EntryDistributionPeer::retrieveByEntryAndProfileId($entry->getId(), $this->profile->getId()); if (!$entryDistribution) { KalturaLog::err('Entry distribution was not found for entry [' . $entry->getId() . '] and profile [' . $this->profile->getId() . ']'); continue; } $xml = $this->handleEntry($context, $feed, $entry, $entryDistribution); if (!is_null($xml) && $enableCache) { $cacheStore->set($cacheKey . self::CACHE_CREATION_TIME_SUFFIX, time()); $cacheStore->set($cacheKey, $xml); } } $feed->addItemXml($xml); $counter++; //to avoid the cache exceeding the memory size if ($counter % self::CACHE_SIZE == 0) { kMemoryManager::clearMemory(); } } }
public static function dumpUrl($url, $allowRange = true, $passHeaders = false, $additionalHeaders = null) { KalturaLog::debug("URL [{$url}], {$allowRange} [{$allowRange}], {$passHeaders} [{$passHeaders}]"); self::closeDbConnections(); $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.11.1"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // in case of private ips (internal to the datacenters) no need to check the certificate validity. // otherwise curling for https://127.0.0.1/ will fail as the certificate is for *.domain.com $urlHost = parse_url($url, PHP_URL_HOST); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, infraRequestUtils::isIpPrivate($urlHost) ? 0 : 2); // 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); } $sendHeaders = array("X-Kaltura-Proxy: dumpUrl"); if ($passHeaders) { $sentHeaders = self::getRequestHeaders(); foreach ($sentHeaders as $header => $value) { $sendHeaders[] = "{$header}: {$value}"; } } elseif ($allowRange && isset($_SERVER['HTTP_RANGE']) && $_SERVER['HTTP_RANGE']) { // get range parameters from HTTP range requst headers list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); curl_setopt($ch, CURLOPT_RANGE, $range); } if ($additionalHeaders) { foreach ($additionalHeaders as $header => $value) { $sendHeaders[] = "{$header}: {$value}"; } } // when proxying request to other datacenter we may be already in a proxied request (from one of the internal proxy servers) // we need to ensure the original HOST is sent in order to allow restirctions checks $host = isset($_SERVER["HTTP_X_FORWARDED_HOST"]) ? $_SERVER["HTTP_X_FORWARDED_HOST"] : $_SERVER["HTTP_HOST"]; for ($i = 0; $i < count($sendHeaders); $i++) { if (stripos($sendHeaders[$i], "host:") === 0) { array_splice($sendHeaders, $i, 1); break; } } $sendHeaders[] = "Host:{$host}"; curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); if ($_SERVER['REQUEST_METHOD'] == 'HEAD') { // request was HEAD, proxy only HEAD response curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); } else { // 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'); //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); header("Access-Control-Allow-Origin:*"); // avoid html5 xss issues header("X-Kaltura:dumpUrl"); // grab URL and pass it to the browser $content = curl_exec($ch); KalturaLog::debug("CURL executed [{$content}]"); // close curl resource, and free up system resources curl_close($ch); KExternalErrors::dieGracefully(); }
protected function getFieldValues($extraField) { switch ($extraField) { case self::ECF_REFERRER: $values = array(); // a request can theoritically have more than one referrer, in case of several baseEntry.getContextData calls in a single multirequest foreach ($this->_referrers as $referrer) { $values[] = infraRequestUtils::parseUrlHost($referrer); } return $values; case self::ECF_USER_AGENT: if (isset($_SERVER['HTTP_USER_AGENT'])) { return array($_SERVER['HTTP_USER_AGENT']); } break; case self::ECF_COUNTRY: return array(self::getCountry()); case self::ECF_IP: return array(self::getIp()); } return array(); }
public final function output() { $this->prepareFlavors(); if ($this->deliveryCode) { $this->replaceDeliveryCode(); } $this->tokenizeUrls(); $headers = $this->getHeaders(); $headers[] = "Access-Control-Allow-Origin:*"; $headers[] = "Access-Control-Expose-Headers: Server,range,Content-Length,Content-Range"; foreach ($headers as $header) { header($header); } if (kApiCache::hasExtraFields() && !$this->forceCachingHeaders) { $this->cachingHeadersAge = 0; } infraRequestUtils::sendCachingHeaders($this->cachingHeadersAge, true, $this->lastModified); $header = $this->getManifestHeader(); $footer = $this->getManifestFooter(); $flavors = $this->getManifestFlavors(); foreach ($this->contributors as $contributorInstance) { /* @var $contributorInstance BaseManifestEditor */ $header = $contributorInstance->editManifestHeader($header); $footer = $contributorInstance->editManifestFooter($footer); $flavors = $contributorInstance->editManifestFlavors($flavors); } $separator = $this->getSeparator(); $content = $header; if ($content) { $content .= $separator; } $content .= implode($separator, $flavors); $content .= $separator . $footer; header('Content-Length: ' . strlen($content)); // avoid chunked encoding echo $content; die; }
/** * Output file content * @param int $assetId Asset Id * @param string $fileExt File extension */ public function dumpFile($assetId, $fileExt) { $fileSize = $this->getFileSizeForAssetId($assetId, $fileExt); $range_length = $fileSize * 1024; $wamsURL = $this->getUrlForAssetId($assetId, $fileExt); $fh = fopen($wamsURL, 'rb'); if ($fh) { infraRequestUtils::sendCdnHeaders($fileExt, $fileSize); while ($range_length > 0) { $content = fread($fh, min(self::CHUNK_SIZE, $range_length)); echo $content; $range_length -= self::CHUNK_SIZE; } fclose($fh); } die; // no view }
private function _getKalturaHost() { $proto = 'http'; $kalturaHost = kConf::get('www_host'); if (infraRequestUtils::getProtocol() == infraRequestUtils::PROTOCOL_HTTPS) { $proto = 'https'; if (kConf::hasParam('www_host_https')) { $kalturaHost = kConf::get('www_host_https'); } } $url = $proto . '://' . $kalturaHost; return $url; }
private static function getExternalStorageUrl(Partner $partner, asset $asset, FileSyncKey $key, $servePlayManifest = false, $playManifestClientTag = null, $storageId = null) { if (!$partner->getStorageServePriority() || $partner->getStorageServePriority() == StorageProfile::STORAGE_SERVE_PRIORITY_KALTURA_ONLY) { return null; } if (is_null($storageId) && $partner->getStorageServePriority() == StorageProfile::STORAGE_SERVE_PRIORITY_KALTURA_FIRST) { if (kFileSyncUtils::getReadyInternalFileSyncForKey($key)) { // check if having file sync on kaltura dcs return null; } } $fileSync = kFileSyncUtils::getReadyExternalFileSyncForKey($key, $storageId); if (!$fileSync) { return null; } $storage = StorageProfilePeer::retrieveByPK($fileSync->getDc()); if (!$storage) { return null; } if ($servePlayManifest) { // in case of an https request, if a delivery profile which supports https doesn't exist use an http cdn api host if (infraRequestUtils::getProtocol() == infraRequestUtils::PROTOCOL_HTTPS && DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $asset->getEntryId(), PlaybackProtocol::HTTP, "https"))) { $url = requestUtils::getApiCdnHost(); } else { $url = infraRequestUtils::PROTOCOL_HTTP . "://" . kConf::get("cdn_api_host"); } $url .= $asset->getPlayManifestUrl($playManifestClientTag, $storageId); } else { $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $asset->getEntryId())); if ($urlManager) { $dynamicAttrs = new DeliveryProfileDynamicAttributes(); $dynamicAttrs->setFileExtension($asset->getFileExt()); $dynamicAttrs->setStorageId($fileSync->getDc()); $urlManager->setDynamicAttributes($dynamicAttrs); $url = ltrim($urlManager->getFileSyncUrl($fileSync), '/'); if (strpos($url, "://") === false) { $url = rtrim($urlManager->getUrl(), "/") . "/" . $url; } } else { KalturaLog::debug("Couldn't determine delivery profile for storage id"); $url = null; } } return $url; }
public function execute($limit = 0) { if ($this->executed) { return; } if ($limit) { $this->limit = $limit; } $microTimeStart = microtime(true); $renderer = KalturaSyndicationFeedFactory::getRendererByType($this->syndicationFeed->type); $renderer->init($this->syndicationFeed, $this->syndicationFeedDb, $this->mimeType); header($renderer->handleHttpHeader()); echo $renderer->handleHeader(); $cacheStore = null; if ($renderer->shouldEnableCache()) { $cacheStore = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_FEED_ENTRY); } $protocol = infraRequestUtils::getProtocol(); $cachePrefix = "feed_{$this->syndicationFeed->id}/{$protocol}/entry_"; $feedUpdatedAt = $this->syndicationFeedDb->getUpdatedAt(null); $e = null; $kalturaFeed = $this->syndicationFeed->type == KalturaSyndicationFeedType::KALTURA || $this->syndicationFeed->type == KalturaSyndicationFeedType::KALTURA_XSLT; $nextEntry = $this->getNextEntry(); while ($nextEntry) { $this->enableApcProcessingFlag(); $entry = $nextEntry; $nextEntry = $this->getNextEntry(); // in case no video player is requested by user and the entry is mix, skip it if ($entry->getType() === entryType::MIX && !$this->syndicationFeed->allowEmbed) { continue; } $xml = false; // check cache $updatedAt = max($feedUpdatedAt, $entry->getUpdatedAt(null)); if ($cacheStore) { $cacheKey = $cachePrefix . str_replace("_", "-", $entry->getId()) . self::CACHE_VERSION; // replace _ with - so cache folders will be created with random entry id and not 0_/1_ $cacheTime = $cacheStore->get($cacheKey . self::CACHE_CREATION_TIME_SUFFIX); if ($cacheTime !== false && $cacheTime > $updatedAt + self::CACHE_CREATION_MARGIN) { $xml = $cacheStore->get($cacheKey); } } if ($xml === false) { $e = null; if (!$kalturaFeed) { $e = new KalturaMediaEntry(); $e->fromObject($entry); } $flavorAssetUrl = is_null($e) ? null : $this->getFlavorAssetUrl($e); if (!$kalturaFeed && $entry->getType() !== entryType::MIX && is_null($flavorAssetUrl)) { $xml = ""; // cache empty result to avoid checking getFlavorAssetUrl next time } else { $xml = $renderer->handleBody($entry, $e, $flavorAssetUrl); } } if ($cacheStore) { $cacheStore->set($cacheKey . self::CACHE_CREATION_TIME_SUFFIX, time(), self::CACHE_EXPIRY); $cacheStore->set($cacheKey, $xml, self::CACHE_EXPIRY); } echo $renderer->finalize($xml, $nextEntry !== false); } echo $renderer->handleFooter(); if ($this->feedProcessingKey && function_exists('apc_delete')) { apc_delete($this->feedProcessingKey); } $microTimeEnd = microtime(true); KalturaLog::info("syndicationFeedRenderer- render time for ({$this->syndicationFeed->type}) is " . ($microTimeEnd - $microTimeStart)); }
public function getRequestParameter($name, $default = null) { $requestParams = infraRequestUtils::getRequestParams(); if (array_key_exists($name, $requestParams)) { return $requestParams[$name]; } if (isset(self::$shortNames[$name])) { $shortName = self::$shortNames[$name]; if (array_key_exists($shortName, $requestParams)) { return $requestParams[$shortName]; } } return $default; }
public static function getPlayServerHost($partner_id, $protocol = null) { if (is_null($protocol)) { $protocol = infraRequestUtils::getProtocol(); } $partner = PartnerPeer::retrieveByPK($partner_id); if (!$partner || !$partner->getPlayServerHost()) { return requestUtils::getPlayServerHost($protocol); } $playServerHost = $partner->getPlayServerHost(); $playServerHost = preg_replace('/^https?/', $protocol, $playServerHost); return $playServerHost; }
public static function getRequestParams() { if (!is_null(self::$requestParams)) { return self::$requestParams; } $scriptParts = explode('/', $_SERVER['SCRIPT_NAME']); $pathParts = array(); if (isset($_SERVER['PHP_SELF'])) { $pathParts = explode('/', $_SERVER['PHP_SELF']); } $pathParts = array_diff($pathParts, $scriptParts); $params = array(); reset($pathParts); while (current($pathParts)) { $key = each($pathParts); $value = each($pathParts); $params[$key['value']] = $value['value']; } self::$requestParams = array_merge($params, $_GET, $_POST, $_FILES); return self::$requestParams; }
public static function getRedirectExternalUrl(FileSync $file_sync, $additional_url = null) { $remote_url = self::getRemoteDcExternalUrl($file_sync); $remote_url = $remote_url . $_SERVER['REQUEST_URI']; $remote_url = preg_replace('/^https?:\\/\\//', '', $remote_url); $remote_url = infraRequestUtils::getProtocol() . '://' . $remote_url; KalturaLog::log("URL to redirect to [{$remote_url}]"); return $remote_url; }
protected static function getSessionKey($protocol = null, $ksType = null, array $userRoles = null, $host = null) { if (!$protocol) { $protocol = infraRequestUtils::getProtocol(); } if (!$ksType) { $ksType = kCurrentContext::getCurrentSessionType(); } if (!$userRoles) { $userRoles = kPermissionManager::getCurrentRoleIds(); } if (!$host) { $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; } sort($userRoles); $userRole = implode('-', $userRoles); return "{$protocol}_{$ksType}_{$host}_{$userRole}"; }
public function __toString() { if (self::$_ip === null) { self::$_ip = (string) infraRequestUtils::getRemoteAddress(); } return self::$_ip; }
public function getDataUrl($version = NULL) { if ($this->getType() == entryType::PLAYLIST) { return myPlaylistUtils::getExecutionUrl($this); } $current_version = $this->getVersion(); $entryId = $this->getId(); $media_type = $this->getMediaType(); if ($media_type == self::ENTRY_MEDIA_TYPE_VIDEO || $media_type == self::ENTRY_MEDIA_TYPE_AUDIO) { $protocolStr = infraRequestUtils::getProtocol(); $url = requestUtils::getApiCdnHost(); $url .= myPartnerUtils::getUrlForPartner($this->getPartnerId(), $this->getSubpId()); $url .= "/playManifest/entryId/{$entryId}/format/url/protocol/{$protocolStr}"; } else { if ($media_type == self::ENTRY_MEDIA_TYPE_IMAGE) { $width = self::DEFAULT_IMAGE_WIDTH; $height = self::DEFAULT_IMAGE_HEIGHT; $url = myPartnerUtils::getCdnHost($this->getPartnerId()); $url .= myPartnerUtils::getUrlForPartner($this->getPartnerId(), $this->getSubpId()); if (!$version) { $version = $current_version; } $url .= "/thumbnail/entry_id/{$entryId}/def_height/{$height}/def_width/{$width}/version/{$version}/type/1"; } else { return null; } } return $url; }
protected function warmCache($key) { if (self::$_cacheWarmupInitiated) { return; } self::$_cacheWarmupInitiated = true; $key = "cache-warmup-{$key}"; $cacheSections = kCacheManager::getCacheSectionNames(kCacheManager::CACHE_TYPE_API_WARMUP); if (!$cacheSections) { return; } foreach ($cacheSections as $cacheSection) { $cacheStore = kCacheManager::getCache($cacheSection); if (!$cacheStore) { return; } // abort warming if a previous warmup started less than 10 seconds ago if ($cacheStore->get($key) !== false) { return; } // flag we are running a warmup for the current request $cacheStore->set($key, true, self::WARM_CACHE_TTL); } $uri = $_SERVER["REQUEST_URI"]; $fp = fsockopen(kConf::get('api_cache_warmup_host'), 80, $errno, $errstr, 1); if ($fp === false) { error_log("warmCache - Couldn't open a socket [" . $uri . "]", 0); return; } $method = $_SERVER["REQUEST_METHOD"]; $out = "{$method} {$uri} HTTP/1.1\r\n"; $sentHeaders = self::getRequestHeaders(); $sentHeaders["Connection"] = "Close"; // mark request as a warm cache request in order to disable caching and pass the http/https protocol (the warmup always uses http) $sentHeaders[self::WARM_CACHE_HEADER] = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http"; // if the request wasn't proxied pass the ip on the X-FORWARDED-FOR header $ipHeader = infraRequestUtils::getSignedIpAddressHeader(); if ($ipHeader) { list($headerName, $headerValue) = $ipHeader; $sentHeaders[$headerName] = $headerValue; } foreach ($sentHeaders as $header => $value) { $out .= "{$header}:{$value}\r\n"; } $out .= "\r\n"; if ($method == "POST") { $postParams = array(); foreach ($_POST as $key => &$val) { if (is_array($val)) { $val = implode(',', $val); } $postParams[] = $key . '=' . urlencode($val); } $out .= implode('&', $postParams); } fwrite($fp, $out); fclose($fp); }