Esempio n. 1
0
 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);
         }
     }
 }
 /**
  * Serves multiple files for synchronization between datacenters 
  */
 public function execute()
 {
     $fileSyncIds = $this->getRequestParameter("ids");
     $hash = $this->getRequestParameter("hash");
     // validate hash
     $currentDc = kDataCenterMgr::getCurrentDc();
     $currentDcId = $currentDc["id"];
     $expectedHash = md5($currentDc["secret"] . $fileSyncIds);
     if ($hash !== $expectedHash) {
         $error = "Invalid hash - ids [{$fileSyncIds}] got [{$hash}] expected [{$expectedHash}]";
         KalturaLog::err($error);
         KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
     }
     // load file syncs
     $fileSyncs = FileSyncPeer::retrieveByPks(explode(',', $fileSyncIds));
     if ($fileSyncs) {
         KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveMultiFile', $fileSyncs[0]->getPartnerId());
     }
     // resolve file syncs
     $filePaths = array();
     foreach ($fileSyncs as $fileSync) {
         if ($fileSync->getDc() != $currentDcId) {
             $error = "FileSync id [" . $fileSync->getId() . "] does not belong to this DC";
             KalturaLog::err($error);
             KExternalErrors::dieError(KExternalErrors::BAD_QUERY);
         }
         // resolve if file_sync is link
         $fileSyncResolved = kFileSyncUtils::resolve($fileSync);
         // check if file sync path leads to a file or a directory
         $resolvedPath = $fileSyncResolved->getFullPath();
         if (is_dir($resolvedPath)) {
             $error = "FileSync id [" . $fileSync->getId() . "] is a directory";
             KalturaLog::err($error);
             KExternalErrors::dieError(KExternalErrors::BAD_QUERY);
         }
         if (!file_exists($resolvedPath)) {
             $error = "Path [{$resolvedPath}] for fileSync id [" . $fileSync->getId() . "] does not exist";
             KalturaLog::err($error);
             continue;
         }
         $filePaths[$fileSync->getId()] = $resolvedPath;
     }
     $boundary = md5(uniqid('', true));
     header('Content-Type: multipart/form-data; boundary=' . $boundary);
     foreach ($filePaths as $id => $filePath) {
         echo "--{$boundary}\n";
         echo "Content-Type: application/octet-stream\n";
         echo "Content-Disposition: form-data; name=\"{$id}\"\n\n";
         readfile($filePath);
         echo "\n";
     }
     echo "--{$boundary}--\n";
     KExternalErrors::dieGracefully();
 }
Esempio n. 3
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $file_sync_id = $this->getRequestParameter("id");
     $hash = $this->getRequestParameter("hash");
     $file_name = $this->getRequestParameter("fileName");
     if ($file_name) {
         $file_name = base64_decode($file_name);
     }
     $file_sync = FileSyncPeer::retrieveByPk($file_sync_id);
     if (!$file_sync) {
         $current_dc_id = kDataCenterMgr::getCurrentDcId();
         $error = "DC[{$current_dc_id}]: Cannot find FileSync with id [{$file_sync_id}]";
         KalturaLog::err($error);
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFile', $file_sync->getPartnerId());
     kDataCenterMgr::serveFileToRemoteDataCenter($file_sync, $hash, $file_name);
     die;
 }
Esempio n. 4
0
 public function execute($input_parameters = null)
 {
     if (!kQueryCache::isCurrentQueryHandled()) {
         kApiCache::disableConditionalCache();
     }
     $search = array();
     $replace = array();
     if (is_null($input_parameters)) {
         $search = array_reverse(array_keys($this->values));
         $replace = array_reverse($this->values);
     } else {
         $i = 1;
         foreach ($input_parameters as $value) {
             $search[] = ':p' . $i++;
             if (is_null($value)) {
                 $replace[] = "NULL";
             } else {
                 $replace[] = "'{$value}'";
             }
         }
         $search = array_reverse($search);
         $replace = array_reverse($replace);
     }
     $sql = str_replace($search, $replace, $this->queryString);
     KalturaLog::debug($sql);
     $sqlStart = microtime(true);
     if (self::$dryRun && !preg_match('/^(\\/\\*.+\\*\\/ )?SELECT/i', $sql)) {
         KalturaLog::debug("Sql dry run - " . (microtime(true) - $sqlStart) . " seconds");
     } else {
         try {
             parent::execute($input_parameters);
         } catch (PropelException $pex) {
             KalturaLog::alert($pex->getMessage());
             throw new PropelException("Database error");
         }
         $sqlTook = microtime(true) - $sqlStart;
         KalturaLog::debug("Sql took - " . $sqlTook . " seconds");
         KalturaMonitorClient::monitorDatabaseAccess($sql, $sqlTook);
     }
 }
Esempio n. 5
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     // where file is {entryId/flavorId}.{ism,ismc,ismv}
     $objectId = $type = null;
     $objectIdStr = $this->getRequestParameter("objectId");
     if ($objectIdStr) {
         list($objectId, $type) = @explode(".", $objectIdStr);
     }
     if (!$type || !$objectId) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER);
     }
     $ks = $this->getRequestParameter("ks");
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     $syncKey = $this->getFileSyncKey($objectId, $type);
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveIsm', $this->entry->getPartnerId());
     myPartnerUtils::enforceDelivery($this->entry, $this->flavorAsset);
     if (!kFileSyncUtils::file_exists($syncKey, false)) {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for type [{$type}] objectId [{$objectId}]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         kFileUtils::dumpUrl($remoteUrl);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     if ($type == 'ism') {
         $fileData = $this->fixIsmManifestForReplacedEntry($path);
         $renderer = new kRendererString($fileData, 'image/ism');
         $renderer->output();
         KExternalErrors::dieGracefully();
     } else {
         kFileUtils::dumpFile($path);
     }
 }
Esempio n. 6
0
 /**
  * @return bool false on error
  */
 protected function reconnect()
 {
     $this->memcache = null;
     if ($this->connectAttempts >= self::MAX_CONNECT_ATTEMPTS) {
         return false;
     }
     $connectResult = false;
     $connStart = microtime(true);
     while ($this->connectAttempts < self::MAX_CONNECT_ATTEMPTS) {
         $this->connectAttempts++;
         $memcache = new Memcache();
         //$memcache->setOption(Memcached::OPT_BINARY_PROTOCOL, true);			// TODO: enable when moving to memcached v1.3
         $curConnStart = microtime(true);
         if ($this->persistent) {
             $connectResult = @$memcache->pconnect($this->hostName, $this->port);
         } else {
             $connectResult = @$memcache->connect($this->hostName, $this->port);
         }
         if ($connectResult || microtime(true) - $curConnStart < 0.5) {
             // retry only if there's an error and it's a timeout error
             break;
         }
         self::safeLog("got timeout error while connecting to memcache...");
     }
     $connTook = microtime(true) - $connStart;
     self::safeLog("connect took - {$connTook} seconds to {$this->hostName}:{$this->port} attempts {$this->connectAttempts}");
     if (class_exists("KalturaMonitorClient")) {
         KalturaMonitorClient::monitorConnTook($this->hostName, $connTook);
     }
     if (!$connectResult) {
         self::safeLog("failed to connect to memcache");
         return false;
     }
     $this->memcache = $memcache;
     return true;
 }
 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();
 }
Esempio n. 8
0
 /**
  * This functions checks if a certain response resides in cache.
  * In case it does, the response is returned from cache and a response header is added.
  * There are two possibilities on which this function is called:
  * 1)	The request is a single 'stand alone' request (maybe this request is a multi request containing several sub-requests)
  * 2)	The request is a single request that is part of a multi request (sub-request in a multi request)
  *
  * in case this function is called when handling a sub-request (single request as part of a multirequest) it
  * is preferable to change the default $cacheHeaderName
  *
  * @param $cacheHeaderName - the header name to add
  * @param $cacheHeader - the header value to add
  */
 public function checkCache($cacheHeaderName = 'X-Kaltura', $cacheHeader = 'cached-dispatcher')
 {
     $result = $this->checkCacheInternal($cacheHeaderName, $cacheHeader);
     if (isset($this->_params['service'])) {
         $isInMultiRequest = isset($this->_params['multirequest']);
         $action = $this->_params['service'];
         if ($action != 'multirequest' && isset($this->_params['action'])) {
             $action = $this->_params['service'] . '.' . $this->_params['action'];
         }
         KalturaMonitorClient::monitorApiStart($result !== false, $action, $this->_partnerId, $this->getCurrentSessionType(), $this->clientTag, $isInMultiRequest);
     }
     return $result;
 }
Esempio n. 9
0
 /**
  * Will forward to the regular swf player according to the widget_id
  */
 public function execute()
 {
     KExternalErrors::setResponseErrorCode(KExternalErrors::HTTP_STATUS_NOT_FOUND);
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL2;
     requestUtils::handleConditionalGet();
     ignore_user_abort();
     $entry_id = $this->getRequestParameter("entry_id");
     $widget_id = $this->getRequestParameter("widget_id", 0);
     $upload_token_id = $this->getRequestParameter("upload_token_id");
     $version = $this->getIntRequestParameter("version", null, 0, 10000000);
     $type = $this->getIntRequestParameter("type", 1, 1, 5);
     //Hack: if KMS sends thumbnail request containing "!" char, the type should be treated as 5.
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     if (strpos($width, "!") || strpos($height, "!")) {
         $type = 5;
     }
     $width = $this->getFloatRequestParameter("width", -1, -1, 10000);
     $height = $this->getFloatRequestParameter("height", -1, -1, 10000);
     $nearest_aspect_ratio = $this->getIntRequestParameter("nearest_aspect_ratio", 0, 0, 1);
     $imageFilePath = null;
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $quality = $this->getIntRequestParameter("quality", 0, 0, 100);
     $src_x = $this->getFloatRequestParameter("src_x", 0, 0, 10000);
     $src_y = $this->getFloatRequestParameter("src_y", 0, 0, 10000);
     $src_w = $this->getFloatRequestParameter("src_w", 0, 0, 10000);
     $src_h = $this->getFloatRequestParameter("src_h", 0, 0, 10000);
     $vid_sec = $this->getFloatRequestParameter("vid_sec", -1, -1);
     $vid_slice = $this->getRequestParameter("vid_slice", -1);
     $vid_slices = $this->getRequestParameter("vid_slices", -1);
     $density = $this->getFloatRequestParameter("density", 0, 0);
     $stripProfiles = $this->getRequestParameter("strip", null);
     $flavor_id = $this->getRequestParameter("flavor_id", null);
     $file_name = $this->getRequestParameter("file_name", null);
     $file_name = basename($file_name);
     // actual width and height of image from which the src_* values were taken.
     // these will be used to multiply the src_* parameters to make them relate to the original image size.
     $rel_width = $this->getFloatRequestParameter("rel_width", -1, -1, 10000);
     $rel_height = $this->getFloatRequestParameter("rel_height", -1, -1, 10000);
     $def_width = $this->getFloatRequestParameter("def_width", -1, -1, 10000);
     $def_height = $this->getFloatRequestParameter("def_height", -1, -1, 10000);
     if ($width == -1 && $height == -1) {
         if ($def_width == -1) {
             $width = 120;
         } else {
             $width = $def_width;
         }
         if ($def_height == -1) {
             $height = 90;
         } else {
             $height = $def_height;
         }
     } else {
         if ($width == -1) {
             $width = 0;
         } else {
             if ($height == -1) {
                 $height = 0;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     $partner = null;
     $format = $this->getRequestParameter("format", null);
     // validating the inputs
     if (!is_numeric($quality) || $quality < 0 || $quality > 100) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'quality must be between 20 and 100');
     }
     if (!is_numeric($src_x) || $src_x < 0 || $src_x > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_x must be between 0 and 10000');
     }
     if (!is_numeric($src_y) || $src_y < 0 || $src_y > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_y must be between 0 and 10000');
     }
     if (!is_numeric($src_w) || $src_w < 0 || $src_w > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_w must be between 0 and 10000');
     }
     if (!is_numeric($src_h) || $src_h < 0 || $src_h > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_h must be between 0 and 10000');
     }
     if (!is_numeric($width) || $width < 0 || $width > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'width must be between 0 and 10000');
     }
     if (!is_numeric($height) || $height < 0 || $height > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'height must be between 0 and 10000');
     }
     if (!is_numeric($density) || $density < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'density must be positive');
     }
     if (!is_numeric($vid_sec) || $vid_sec < -1) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_sec must be positive');
     }
     if (!preg_match('/^[0-9a-fA-F]{1,6}$/', $bgcolor)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'bgcolor must be six hexadecimal characters');
     }
     if ($vid_slices != -1 && $vid_slices <= 0 || !is_numeric($vid_slices)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_slices must be positive');
     }
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $partnerId = $upload_token->getPartnerId();
             $partner = PartnerPeer::retrieveByPK($partnerId);
             if ($partner) {
                 KalturaMonitorClient::initApiMonitor(false, 'extwidget.thumbnail', $partner->getId());
                 if ($quality == 0) {
                     $quality = $partner->getDefThumbQuality();
                 }
                 if ($density == 0) {
                     $density = $partner->getDefThumbDensity();
                 }
                 if (is_null($stripProfiles)) {
                     $stripProfiles = $partner->getStripThumbProfile();
                 }
             }
             $thumb_full_path = myContentStorage::getFSCacheRootPath() . myContentStorage::getGeneralEntityPath("uploadtokenthumb", $upload_token->getIntId(), $upload_token->getId(), $upload_token->getId() . ".jpg");
             kFile::fullMkdir($thumb_full_path);
             if (file_exists($upload_token->getUploadTempPath())) {
                 $src_full_path = $upload_token->getUploadTempPath();
                 $valid_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP);
                 $image_type = exif_imagetype($src_full_path);
                 if (!in_array($image_type, $valid_image_types)) {
                     // capture full frame
                     myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 3);
                     if (!file_exists($thumb_full_path)) {
                         myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 0);
                     }
                     $src_full_path = $thumb_full_path;
                 }
                 // and resize it
                 myFileConverter::convertImage($src_full_path, $thumb_full_path, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles, null, $format);
                 kFileUtils::dumpFile($thumb_full_path);
             } else {
                 KalturaLog::debug("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFileUtils::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // get the widget
         $widget = widgetPeer::retrieveByPK($widget_id);
         if (!$widget) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_AND_WIDGET_NOT_FOUND);
         }
         // get the kshow
         $kshow_id = $widget->getKshowId();
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if ($kshow) {
             $entry_id = $kshow->getShowEntryId();
         } else {
             $entry_id = $widget->getEntryId();
         }
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.thumbnail', $entry->getPartnerId());
     if ($nearest_aspect_ratio) {
         // Get the entry's default thumbnail path (if any)
         $defaultThumbnailPath = myEntryUtils::getLocalImageFilePathByEntry($entry, $version);
         // Get the file path of the thumbnail with the nearest
         $selectedThumbnailDescriptor = kThumbnailUtils::getNearestAspectRatioThumbnailDescriptorByEntryId($entry_id, $width, $height, $defaultThumbnailPath);
         if ($selectedThumbnailDescriptor) {
             $imageFilePath = $selectedThumbnailDescriptor->getImageFilePath();
             $thumbWidth = $selectedThumbnailDescriptor->getWidth();
             $thumbHeight = $selectedThumbnailDescriptor->getHeight();
             // The required width and height will serve as the final crop values
             $src_w = $width;
             $src_h = $height;
             // Base on the thumbnail's dimensions
             kThumbnailUtils::scaleDimensions($thumbWidth, $thumbHeight, $width, $height, kThumbnailUtils::SCALE_UNIFORM_SMALLER_DIM, $width, $height);
             // Set crop type
             $type = KImageMagickCropper::CROP_AFTER_RESIZE;
         }
     }
     $partner = $entry->getPartner();
     // not allow capturing frames if the partner has FEATURE_DISALLOW_FRAME_CAPTURE permission
     if ($vid_sec != -1 || $vid_slice != -1 || $vid_slices != -1) {
         if ($partner->getEnabledService(PermissionName::FEATURE_BLOCK_THUMBNAIL_CAPTURE)) {
             KExternalErrors::dieError(KExternalErrors::NOT_ALLOWED_PARAMETER);
         }
     }
     if ($partner) {
         if ($quality == 0) {
             $quality = $partner->getDefThumbQuality();
         }
         if ($density == 0) {
             $density = $partner->getDefThumbDensity();
         }
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1 && $rel_width) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1 && $rel_height) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     KalturaLog::debug("get thumbnail filesyncs");
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFileUtils::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         $tempThumbPath = $entry->getLocalThumbFilePath($version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             KExternalErrors::dieGracefully();
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFileUtils::dumpUrl($remoteUrl);
     }
     // if we didnt return a template for the player die and dont return the original deleted thumb
     if ($entry_status == entryStatus::DELETED) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
     }
     if (!$tempThumbPath) {
         try {
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $imageFilePath, $density, $stripProfiles, $thumbParams, $format);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::log("Error - resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::log("Error - no original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
             $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
             if (!$remoteFileSync) {
                 // file does not exist on any DC - die
                 KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                 KalturaLog::log("ERROR - Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFileUtils::dumpUrl($remoteUrl);
         }
     }
     $nocache = false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules(ContextType::THUMBNAIL)) {
         $nocache = true;
     }
     $cache = null;
     if (!is_null($entry->getPartner())) {
         $partnerCacheAge = $entry->getPartner()->getThumbnailCacheAge();
     }
     if ($nocache) {
         $cacheAge = 0;
     } else {
         if ($partnerCacheAge) {
             $cacheAge = $partnerCacheAge;
         } else {
             if (strpos($tempThumbPath, "_NOCACHE_") !== false) {
                 $cacheAge = 60;
             } else {
                 $cacheAge = 3600;
                 $cache = new myCache("thumb", 2592000);
                 // 30 days, the max memcache allows
             }
         }
     }
     $lastModified = $entry->getAssetCacheTime();
     $renderer = kFileUtils::getDumpFileRenderer($tempThumbPath, null, $cacheAge, 0, $lastModified);
     $renderer->partnerId = $entry->getPartnerId();
     if ($cache) {
         $invalidationKey = $entry->getCacheInvalidationKeys();
         $invalidationKey = kQueryCache::CACHE_PREFIX_INVALIDATION_KEY . $invalidationKey[0];
         $cacheTime = time() - kQueryCache::CLOCK_SYNC_TIME_MARGIN_SEC;
         $cachedResponse = array($renderer, $invalidationKey, $cacheTime);
         $cache->put($_SERVER["REQUEST_URI"], $cachedResponse);
     }
     $renderer->output();
     KExternalErrors::dieGracefully();
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }
Esempio n. 10
0
function checkCache()
{
    $baseDir = "/tmp/cache_v2";
    $start_time = microtime(true);
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http";
    $host = "";
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    } else {
        if (isset($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
        }
    }
    $uri = $_SERVER["REQUEST_URI"];
    if (function_exists('apc_fetch')) {
        $url = apc_fetch("redirect-" . $protocol . $uri);
        if ($url) {
            sendCachingHeaders(60, true, time());
            header("X-Kaltura:cached-dispatcher-redirect");
            header("Location:{$url}");
            die;
        }
        $errorHeaders = apc_fetch("exterror-{$protocol}://{$host}{$uri}");
        if ($errorHeaders !== false) {
            sendCachingHeaders(60, true, time());
            foreach ($errorHeaders as $header) {
                header($header);
            }
            die;
        }
    }
    if (strpos($uri, "/playManifest") !== false) {
        require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kPlayManifestCacher.php";
        $cache = kPlayManifestCacher::getInstance();
        $cache->checkOrStart();
    } else {
        if (strpos($uri, "/partnerservices2") !== false) {
            $params = $_GET + $_POST;
            unset($params['ks']);
            unset($params['kalsig']);
            $params['uri'] = $_SERVER['PATH_INFO'];
            $params['__protocol'] = $protocol;
            ksort($params);
            $keys = array_keys($params);
            $key = md5(implode("|", $params) . implode("|", $keys));
            $cache_filename = "{$baseDir}/cache-{$key}";
            if (file_exists($cache_filename)) {
                if (filemtime($cache_filename) + 600 < time()) {
                    @unlink($cache_filename);
                    @unlink($cache_filename . ".headers");
                    @unlink($cache_filename . ".log");
                } else {
                    $content_type = @file_get_contents("{$baseDir}/cache-{$key}.headers");
                    if ($content_type) {
                        header("Content-Type: {$content_type}");
                    }
                    $response = @file_get_contents("{$baseDir}/cache-{$key}");
                    if ($response) {
                        header("Access-Control-Allow-Origin:*");
                        // avoid html5 xss issues
                        if (strpos($uri, "/partnerservices2/executeplaylist") !== false) {
                            $max_age = 60;
                            sendCachingHeaders($max_age, true, time());
                        } else {
                            sendCachingHeaders(0);
                        }
                        $processing_time = microtime(true) - $start_time;
                        header("X-Kaltura:cached-dispatcher,{$key},{$processing_time}");
                        echo $response;
                        die;
                    }
                }
            }
        } else {
            if (strpos($uri, "/kwidget") !== false) {
                require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php";
                $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2);
                if ($cache) {
                    // check if we cached the patched swf with flashvars
                    $uri = $protocol . $uri;
                    $cachedResponse = $cache->get("kwidgetswf{$uri}");
                    if ($cachedResponse) {
                        $max_age = 60 * 10;
                        header("X-Kaltura:cached-dispatcher");
                        header("Content-Type: application/x-shockwave-flash");
                        sendCachingHeaders($max_age, true, time());
                        header("Content-Length: " . strlen($cachedResponse));
                        echo $cachedResponse;
                        die;
                    }
                    $cachedResponse = $cache->get("kwidget{$uri}");
                    if ($cachedResponse) {
                        header("X-Kaltura:cached-dispatcher");
                        header("Expires: Sun, 19 Nov 2000 08:52:00 GMT");
                        header("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
                        header("Pragma", "no-cache");
                        if (strpos($uri, "nowrapper") !== false) {
                            header("Location:{$cachedResponse}");
                            die;
                        }
                        $referer = @$_SERVER['HTTP_REFERER'];
                        $externalInterfaceDisabled = strstr($referer, "bebo.com") === false && strstr($referer, "myspace.com") === false && strstr($referer, "current.com") === false && strstr($referer, "myyearbook.com") === false && strstr($referer, "facebook.com") === false && strstr($referer, "friendster.com") === false ? "" : "&externalInterfaceDisabled=1";
                        $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer);
                        if (strpos($cachedResponse, "/swfparams/") > 0) {
                            $cachedResponse = substr($cachedResponse, 0, -4) . urlencode($noncached_params) . ".swf";
                        } else {
                            $cachedResponse .= $noncached_params;
                        }
                        header("Location:{$cachedResponse}");
                        die;
                    }
                }
            } else {
                if (strpos($uri, "/thumbnail") !== false) {
                    require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php";
                    $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2);
                    if ($cache) {
                        require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php';
                        $cachedResponse = $cache->get("thumb{$uri}");
                        if ($cachedResponse && is_array($cachedResponse)) {
                            list($renderer, $invalidationKey, $cacheTime) = $cachedResponse;
                            $keysStore = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_QUERY_CACHE_KEYS);
                            if ($keysStore) {
                                $modifiedTime = $keysStore->get($invalidationKey);
                                if ($modifiedTime && $modifiedTime > $cacheTime) {
                                    return;
                                    // entry has changed (not necessarily the thumbnail)
                                }
                            }
                            require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php';
                            KalturaMonitorClient::initApiMonitor(true, 'extwidget.thumbnail', $renderer->partnerId);
                            header("X-Kaltura:cached-dispatcher-thumb");
                            $renderer->output();
                            die;
                        }
                    }
                } else {
                    if (strpos($uri, "/embedIframe/") !== false) {
                        require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php";
                        $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2);
                        if ($cache) {
                            // check if we cached the patched swf with flashvars
                            $cachedResponse = $cache->get("embedIframe{$uri}");
                            if ($cachedResponse) {
                                header("X-Kaltura:cached-dispatcher");
                                sendCachingHeaders(0);
                                header("Location:{$cachedResponse}");
                                die;
                            }
                        }
                    } else {
                        if (strpos($uri, "/serveFlavor/") !== false && function_exists('apc_fetch') && $_SERVER["REQUEST_METHOD"] == "GET") {
                            require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php';
                            require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererString.php';
                            require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php';
                            require_once dirname(__FILE__) . '/../apps/kaltura/lib/request/kIpAddressUtils.php';
                            $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
                            $cacheKey = 'dumpFile-' . kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR']) . '-' . $host . $uri;
                            $renderer = apc_fetch($cacheKey);
                            if ($renderer) {
                                KalturaMonitorClient::initApiMonitor(true, 'extwidget.serveFlavor', $renderer->partnerId);
                                header("X-Kaltura:cached-dispatcher");
                                $renderer->output();
                                die;
                            }
                        }
                    }
                }
            }
        }
    }
}
Esempio n. 11
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $entryId = $this->getRequestParameter("entry_id");
     $flavorId = $this->getRequestParameter("flavor");
     $fileName = $this->getRequestParameter("file_name");
     $fileName = basename($fileName);
     $ksStr = $this->getRequestParameter("ks");
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $entry = null;
     if ($ksStr) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.download', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $shouldPreview = false;
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, ContextType::DOWNLOAD);
     if ($securyEntryHelper->shouldPreview()) {
         $shouldPreview = true;
     } else {
         $securyEntryHelper->validateForDownload();
     }
     $flavorAsset = null;
     if ($flavorId) {
         // get flavor asset
         $flavorAsset = assetPeer::retrieveById($flavorId);
         if (is_null($flavorAsset) || !$flavorAsset->isLocalReadyStatus()) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         // the request flavor should belong to the requested entry
         if ($flavorAsset->getEntryId() != $entryId) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
     } else {
         $flavorAssets = assetPeer::retrieveReadyWebByEntryId($entry->getId());
         foreach ($flavorAssets as $curFlavorAsset) {
             if ($securyEntryHelper->isAssetAllowed($curFlavorAsset)) {
                 $flavorAsset = $curFlavorAsset;
                 break;
             }
         }
     }
     // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source
     if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) {
         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
         if (!$securyEntryHelper->isAssetAllowed($flavorAsset)) {
             $flavorAsset = null;
         }
     }
     if ($flavorAsset) {
         $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset);
     } else {
         $syncKey = $this->getBestSyncKeyForEntry($entry);
     }
     if (is_null($syncKey)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     $this->handleFileSyncRedirection($syncKey);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     list($fileBaseName, $fileExt) = kAssetUtils::getFileName($entry, $flavorAsset);
     if (!$fileName) {
         $fileName = $fileBaseName;
     }
     if ($fileExt && !is_dir($filePath)) {
         $fileName = $fileName . '.' . $fileExt;
     }
     $preview = 0;
     if ($shouldPreview && $flavorAsset) {
         $preview = $flavorAsset->estimateFileSize($entry, $securyEntryHelper->getPreviewLength());
     } else {
         if (kCurrentContext::$ks_object) {
             $preview = kCurrentContext::$ks_object->getPrivilegeValue(kSessionBase::PRIVILEGE_PREVIEW, 0);
         }
     }
     //enable downloading file_name which inside the flavor asset directory
     if (is_dir($filePath)) {
         $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
     }
     $this->dumpFile($filePath, $fileName, $preview);
     KExternalErrors::dieGracefully();
     // no view
 }
Esempio n. 12
0
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $entry_id = $this->getRequestParameter("entry_id");
     $ks_str = $this->getRequestParameter("ks");
     $base64_referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64_referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $clip_from = $this->getRequestParameter("clip_from", 0);
     // milliseconds
     $clip_to = $this->getRequestParameter("clip_to", 2147483647);
     // milliseconds
     if ($clip_to == 0) {
         $clip_to = 2147483647;
     }
     $request = $_SERVER["REQUEST_URI"];
     // remove dynamic fields from the url so we'll request a single url from the cdn
     $request = str_replace("/referrer/{$base64_referrer}", "", $request);
     $request = str_replace("/ks/{$ks_str}", "", $request);
     $entry = null;
     if ($ks_str) {
         try {
             kCurrentContext::initKsPartnerUser($ks_str);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     // workaround the filter which hides all the deleted entries -
     // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here
     if (!$entry) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'keditorservices.flvclipper', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_BLOCK_FLVCLIPPER_ACTION, $entry->getPartnerId())) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     // set the memory size to be able to serve big files in a single chunk
     ini_set("memory_limit", "64M");
     // set the execution time to be able to serve big files in a single chunk
     ini_set("max_execution_time", 240);
     if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         KExternalErrors::dieGracefully();
     } else {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $version = $this->getRequestParameter("version", null);
             $width = $this->getRequestParameter("width", -1);
             $height = $this->getRequestParameter("height", -1);
             $crop_provider = $this->getRequestParameter("crop_provider", null);
             $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
             $type = $this->getRequestParameter("type", 1);
             $quality = $this->getRequestParameter("quality", 0);
             $src_x = $this->getRequestParameter("src_x", 0);
             $src_y = $this->getRequestParameter("src_y", 0);
             $src_w = $this->getRequestParameter("src_w", 0);
             $src_h = $this->getRequestParameter("src_h", 0);
             $vid_sec = $this->getRequestParameter("vid_sec", -1);
             $vid_slice = $this->getRequestParameter("vid_slice", -1);
             $vid_slices = $this->getRequestParameter("vid_slices", -1);
             if ($width == -1 && $height == -1) {
                 $width = 640;
                 $height = 480;
             } else {
                 if ($width == -1) {
                     // if only either width or height is missing reset them to zero, and convertImage will handle them
                     $width = 0;
                 } else {
                     if ($height == -1) {
                         $height = 0;
                     }
                 }
             }
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
             kFileUtils::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0);
         }
     }
     $audio_only = $this->getRequestParameter("audio_only");
     // milliseconds
     $flavor = $this->getRequestParameter("flavor", 1);
     //
     $flavor_param_id = $this->getRequestParameter("flavor_param_id", null);
     //
     $streamer = $this->getRequestParameter("streamer");
     //
     if (substr($streamer, 0, 4) == "rtmp") {
         // the fms may add .mp4 to the end of the url
         $streamer = "rtmp";
     }
     // grab seek_from_bytes parameter and normalize url
     $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1);
     $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request);
     if ($seek_from_bytes <= 0) {
         $seek_from_bytes = -1;
     }
     // grab seek_from parameter and normalize url
     $seek_from = $this->getRequestParameter("seek_from", -1);
     $request = str_replace("/seek_from/{$seek_from}", "", $request);
     if ($seek_from <= 0) {
         $seek_from = -1;
     }
     $this->dump_from_byte = 0;
     // reset accurate seek from timestamp
     $seek_from_timestamp = -1;
     // backward compatibility
     if ($flavor === "0") {
         // for edit version
         $flavor = "edit";
     }
     if ($flavor === "1" || $flavor === 1) {
         // for play version
         $flavor = null;
     }
     // when flavor is null, we will get a default flavor
     if ($flavor == "edit") {
         $flavorAsset = assetPeer::retrieveBestEditByEntryId($entry->getId());
     } elseif (!is_null($flavor)) {
         $flavorAsset = assetPeer::retrieveById($flavor);
         // when specific asset was request, we don't validate its tags
         if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } elseif (is_null($flavor) && !is_null($flavor_param_id)) {
         $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor_param_id);
         if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } else {
         if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
             $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
         } else {
             $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
         }
         if (!$flavorAsset) {
             $flavorAssets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB);
             if (count($flavorAssets) > 0) {
                 $flavorAsset = $flavorAssets[0];
             }
         }
     }
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (kFileSyncUtils::file_exists($syncKey, false)) {
         $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     } else {
         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);
         }
         if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
             $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $flavorAsset->getEntryId()), null, $flavorAsset);
             if (!$urlManager) {
                 KalturaLog::log("Error - failed to find an HTTP delivery for storage profile [" . $fileSync->getDc() . "]");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             $url = rtrim($urlManager->getUrl(), '/') . '/' . ltrim($urlManager->getFileSyncUrl($fileSync), '/');
             header('location: ' . $url);
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         $this->redirect($remoteUrl);
     }
     $flv_wrapper = new myFlvHandler($path);
     $isFlv = $flv_wrapper->isFlv();
     // scrubbing is not allowed within mp4 files
     if (!$isFlv) {
         $seek_from = $seek_from_bytes = -1;
     }
     if ($seek_from !== -1 && $seek_from !== 0) {
         if ($audio_only === '0') {
             // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
         } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
             $audio_only = true;
         }
         list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only);
         list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only);
         $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte;
     }
     // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath();
     $extStorageUrl = $entry->getExtStorageUrl();
     if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $request_host = parse_url($extStorageUrl, PHP_URL_HOST);
         $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl);
         $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$akamai_url}");
         KExternalErrors::dieGracefully();
     } elseif ($extStorageUrl) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$extStorageUrl}");
         KExternalErrors::dieGracefully();
     }
     // use headers to detect cdn
     $cdn_name = "";
     $via_header = @$_SERVER["HTTP_VIA"];
     if (strpos($via_header, "llnw.net") !== false) {
         $cdn_name = "limelight";
     } else {
         if (strpos($via_header, "akamai") !== false) {
             $cdn_name = "akamai";
         } else {
             if (strpos($via_header, "Level3") !== false) {
                 $cdn_name = "level3";
             }
         }
     }
     // setting file extension - first trying frrom flavor asset
     $ext = $flavorAsset->getFileExt();
     // if failed, set extension according to file type (isFlv)
     if (!$ext) {
         $ext = $isFlv ? "flv" : "mp4";
     }
     $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0";
     // dont check for rtmp / and for an already redirect url
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // check security using ks
         $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer, ContextType::PLAY);
         if ($securyEntryHelper->shouldPreview()) {
             $this->checkForPreview($securyEntryHelper, $clip_to);
         } else {
             $securyEntryHelper->validateForPlay($entry, $ks_str);
         }
     } else {
         // if needs security check using cdn authentication mechanism
         // for now assume this is a cdn request and don't check for security
     }
     // use limelight mediavault if either security policy requires it or if we're trying to seek within the video
     if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) {
         // we have three options:
         // arrived through limelight mediavault url - the url is secured
         // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url
         // didnt use limelight - enforce ks
         // the cdns are configured to authenticate request for /s/....
         // check if we're already in a redirected secure link using the "/s/" prefix
         $secure_request = substr($request, 0, 3) == "/s/";
         if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) {
             // request was validated by cdn let it through
         } else {
             // extract ks
             $ks_str = $this->getRequestParameter("ks", "");
             if ($entry->getSecurityPolicy()) {
                 if (!$ks_str) {
                     $this->logMessage("flvclipper - no KS");
                     KExternalErrors::dieGracefully();
                 }
                 $ks = kSessionUtils::crackKs($ks_str);
                 if (!$ks) {
                     $this->logMessage("flvclipper - invalid ks [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
                 $matched_privs = $ks->verifyPrivileges("sview", $entry_id);
                 $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]");
                 if (!$matched_privs) {
                     $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
             }
             if ($cdn_name == "limelight") {
                 $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension;
                 $secret = kConf::get("limelight_madiavault_password");
                 $expire = "&e=" . (time() + 120);
                 $ll_url .= $expire;
                 $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}";
                 $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs;
                 //header("Location: $ll_url");
                 $this->redirect($ll_url);
             } else {
                 if ($cdn_name == "level3") {
                     $level3_url = $request . $flv_extension;
                     if ($entry->getSecurityPolicy()) {
                         $level3_url = "/s{$level3_url}";
                         // set expire time in GMT hence the date("Z") offset
                         $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30);
                         $level3_url .= $expire;
                         $secret = kConf::get("level3_authentication_key");
                         $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20);
                         $level3_url .= "&h={$hash}";
                     }
                     $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}";
                     header("Location: {$level3_url}");
                     KExternalErrors::dieGracefully();
                 } else {
                     if ($cdn_name == "akamai") {
                         $akamai_url = $request . $flv_extension;
                         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
                         if ($seek_from_timestamp == -1) {
                             $seek_from_timestamp = $seek_from;
                         }
                         $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000);
                         header("Location: {$akamai_url}");
                         KExternalErrors::dieGracefully();
                     }
                 }
             }
             // a seek request without a supporting cdn - we need to send the answer from our server
             if ($seek_from_bytes !== -1 && $via_header === null) {
                 $this->dump_from_byte = $seek_from_bytes;
             }
         }
     }
     // always add the file suffix to the request (needed for scrubbing by some cdns,
     // and also breaks without extension on some corporate antivirus).
     // we add the the novar paramter since a leaving a trailing "?" will be trimmed
     // and then the /seek_from request will result in another url which level3
     // will try to refetch from the origin
     // note that for streamer we dont add the file extension
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // a seek request without a supporting cdn - we need to send the answer from our server
         if ($seek_from_bytes !== -1 && $via_header === null) {
             $request .= "/seek_from_bytes/{$seek_from_bytes}";
         }
         requestUtils::sendCdnHeaders("flv", 0);
         header("Location: {$request}" . $flv_extension);
         KExternalErrors::dieGracefully();
     }
     // mp4
     if (!$isFlv) {
         $limit_file_size = 0;
         if ($clip_to != 2147483647) {
             $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) * ($clip_to / $duration) * 1.2);
             }
         }
         KalturaLog::info("serving file [{$path}] entry id [{$entry_id}] limit file size [{$limit_file_size}] clip_to [{$clip_to}]");
         kFileUtils::dumpFile($path, null, null, $limit_file_size);
     }
     $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning");
     if ($audio_only === '0') {
         // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
         $audio_only = true;
     }
     //$start = microtime(true);
     list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only);
     $metadata_size = $flv_wrapper->getMetadataSize($audio_only);
     $this->from_byte = $from_byte;
     $this->to_byte = $to_byte;
     //$end1 = microtime(true);
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]");
     $data_offset = $metadata_size + myFlvHandler::getHeaderSize();
     // if we're returning a partial file adjust the total size:
     // substract the metadata and bytes which are not delivered
     if ($this->dump_from_byte >= $data_offset && !$audio_only) {
         $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset);
     }
     $this->total_length = $data_offset + $bytes;
     //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die;
     $this->cuepoint_time = 0;
     $this->cuepoint_pos = 0;
     if ($streamer == "chunked" && $clip_to != 2147483647) {
         $this->cuepoint_time = $clip_to - 1;
         $this->cuepoint_pos = $cuepoint_pos;
         $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE;
     }
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     $this->flv_wrapper = $flv_wrapper;
     $this->audio_only = $audio_only;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("flvclipperAction: error closing db {$e}");
     }
     KExternalErrors::terminateDispatch();
     return sfView::SUCCESS;
 }
Esempio n. 13
0
 public static function monitorApiStart($cached, $action, $partnerId, $sessionType, $clientTag, $isInMultiRequest = false)
 {
     self::initApiMonitor($cached, $action, $partnerId, $clientTag);
     if (!self::$stream) {
         return;
     }
     self::$basicApiInfo = array(self::FIELD_CACHED => $cached, self::FIELD_KS_TYPE => $sessionType, self::FIELD_MULTIREQUEST => $isInMultiRequest);
     $data = array_merge(self::$basicEventInfo, self::$basicApiInfo, array(self::FIELD_EVENT_TYPE => self::EVENT_API_START));
     self::writeEvent($data);
 }
Esempio n. 14
0
 /**
  * Will forward to the regular swf player according to the widget_id
  */
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $entry_id = $this->getRequestParameter("entry_id");
     $type = $this->getRequestParameter("type");
     $ks = $this->getRequestParameter("ks");
     $file_sync = null;
     $ret_file_name = "name";
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $request_file_name = $this->getRequestParameter("file_name");
     if ($request_file_name) {
         $ret_file_name = $request_file_name;
     }
     $direct_serve = $this->getRequestParameter("direct_serve");
     $entry = null;
     if ($ks) {
         try {
             kCurrentContext::initKsPartnerUser($ks);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             KExternalErrors::dieGracefully();
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entry_id);
         if (!$entry) {
             KExternalErrors::dieGracefully();
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieGracefully();
         }
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.raw', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, ContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     // relocate = did we use the redirect and added the extension to the name
     $relocate = $this->getRequestParameter("relocate");
     if ($ret_file_name == "name") {
         $ret_file_name = $entry->getName();
     }
     if ($ret_file_name) {
         //rawurlencode to content-disposition filename to handle spaces and other characters across different browsers
         //$name = rawurlencode($ret_file_name);
         // 19.04.2009 (Roman) - url encode is not needed when the filename in Content-Disposition header is in quotes
         // IE6/FF3/Chrome - Will show the filename correctly
         // IE7 - Will show the filename with underscores instead of spaces (this is better than showing %20)
         $name = $ret_file_name;
         if ($name) {
             if ($relocate) {
                 // if we have a good file extension (from the first time) - use it in the content-disposition
                 // in some browsers it will be stronger than the URL's extension
                 $file_ext = pathinfo($relocate, PATHINFO_EXTENSION);
                 $name .= ".{$file_ext}";
             }
             $name = kString::removeNewLine($name);
             if (!$direct_serve) {
                 $entry_data = $entry->getData();
                 if (strpos($name, ".") === false && !is_null($entry_data)) {
                     $file_ext = pathinfo($entry_data, PATHINFO_EXTENSION);
                     $image_extensions = kConf::get('image_file_ext');
                     if ($file_ext && in_array($file_ext, $image_extensions)) {
                         $name .= '.' . $file_ext;
                     }
                 }
                 header("Content-Disposition: attachment; filename=\"{$name}\"");
             }
         }
     } else {
         $ret_file_name = $entry_id;
         $name = $ret_file_name;
     }
     $name = str_replace(array("\t", "\r", "\n"), array(' ', '', ' '), $name);
     $format = $this->getRequestParameter("format");
     if ($type == "download" && $format && $entry->getType() != entryType::DOCUMENT) {
         // this is a video for a specifc extension - use the proper flavorAsset
         $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, $format);
         if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
         } else {
             header('KalturaRaw: no flavor asset for extension');
             header("HTTP/1.0 404 Not Found");
             KExternalErrors::dieGracefully();
         }
         $archive_file = $file_sync->getFullPath();
         $mime_type = kFile::mimeType($archive_file);
         kFileUtils::dumpFile($archive_file, $mime_type);
     }
     // TODO - move to a different action - document should be plugin
     if ($entry->getType() == entryType::DOCUMENT) {
         // use the fileSync from the entry
         if ($type == "download" && $format) {
             $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, $format);
         } else {
             $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, true);
         }
         if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
         } else {
             header('KalturaRaw: no flavor asset for extension');
             header("HTTP/1.0 404 Not Found");
             KExternalErrors::dieGracefully();
         }
         // Gonen 2010-08-05 workaround to make sure file name includes correct extension
         // make sure a file extension is added to the downloaded file so browser will identify and
         // allow opening with default program
         // for direct serve we do not want to send content-disposition header
         if (!$direct_serve) {
             $ext = pathinfo($file_sync->getFullPath(), PATHINFO_EXTENSION);
             if ($relocate) {
                 // remove relocate file extension
                 $reloc_ext = pathinfo($relocate, PATHINFO_EXTENSION);
                 $name = str_replace(".{$reloc_ext}", '', $name);
             }
             $name = kString::removeNewLine($name . '.' . $ext);
             header("Content-Disposition: attachment; filename=\"{$name}\"");
         }
         kFileUtils::dumpFile($file_sync->getFullPath());
     } elseif ($entry->getType() == entryType::DATA) {
         $version = $this->getRequestParameter("version");
         $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version);
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if ($local) {
             $path = $fileSync->getFullPath();
         } else {
             $path = kDataCenterMgr::getRedirectExternalUrl($fileSync);
             header("Location: {$path}");
             KExternalErrors::dieGracefully();
         }
         if (!$path) {
             header('KalturaRaw: no data was found available for download');
             header("HTTP/1.0 404 Not Found");
         } else {
             kFileUtils::dumpFile($path);
         }
     }
     //$archive_file = $entry->getArchiveFile();
     $media_type = $entry->getMediaType();
     if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         // image - use data for entry
         $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, null);
         $key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         kFileUtils::dumpFile(kFileSyncUtils::getLocalFilePathForKey($key, true));
     } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) {
         $format = $this->getRequestParameter("format");
         if ($type == "download" && $format) {
             // this is a video for a specifc extension - use the proper flavorAsset
             $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, $format);
             if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, true);
             } else {
                 header('KalturaRaw: no flavor asset for extension');
                 KExternalErrors::dieGracefully();
             }
             $archive_file = $file_sync->getFullPath();
         } else {
             // flavorAsset of the original
             $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, true);
             if ($flavor_asset && $flavor_asset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false);
                 // NOT strict - if there is no archive, get the data version
                 if ($file_sync) {
                     $archive_file = $file_sync->getFullPath();
                 }
             }
             if (!$flavor_asset || !$file_sync || $flavor_asset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
                 // either no archive asset or no fileSync for archive asset
                 // use fallback flavorAsset
                 $flavor_asset = $this->getAllowedFlavorAssets($securyEntryHelper, $entry_id, null, false, true);
                 if (!$flavor_asset) {
                     header('KalturaRaw: no original flavor asset for entry, no best play asset for entry');
                     KExternalErrors::dieGracefully();
                 }
                 $file_sync = $this->redirectIfRemote($flavor_asset, flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, null, false);
                 // NOT strict - if there is no archive, get the data version
                 if (!$file_sync) {
                     header('KalturaRaw: no file sync found for flavor [' . $flavor_asset->getId() . ']');
                     KExternalErrors::dieGracefully();
                 }
                 $archive_file = $file_sync->getFullPath();
             }
         }
     } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_SHOW) {
         // in this case "raw" is a bad name
         // TODO - add the ability to fetch the actual XML by flagging "xml" or something
         $version = $this->getRequestParameter("version");
         // hotfix - links sent after flattening is done look like:
         // http://cdn.kaltura.com/p/387/sp/38700/raw/entry_id/0_ix99151g/version/100001
         // while waiting for flavor-adaptation in flattening, we want to find at least one file to return.
         $try_formats = array('mp4', 'mov', 'avi', 'flv');
         if ($format) {
             $key = array_search($format, $try_formats);
             if ($key !== FALSE) {
                 unset($try_formats[$key]);
             }
             $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $format, false);
         }
         if (!isset($file_sync) || !$file_sync || !file_exists($file_sync->getFullPath())) {
             foreach ($try_formats as $ext) {
                 KalturaLog::log("raw for mix - trying to find filesync for extension: [{$ext}] on entry [{$entry->getId()}]");
                 $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, false);
                 if ($file_sync && file_exists($file_sync->getFullPath())) {
                     KalturaLog::log("raw for mix - found flattened video of extension: [{$ext}] continuing with this file {$file_sync->getFullPath()}");
                     break;
                 }
             }
             if (!$file_sync || !file_exists($file_sync->getFullPath())) {
                 $file_sync = $this->redirectIfRemote($entry, entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD, $ext, true);
             }
         }
         // use fileSync for entry - roughcuts don't have flavors
         //$file_sync =  $this->redirectIfRemote ( $entry ,  entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD , $version , true );  // strict - nothing to do if no flattened version
         // if got to here - fileSync was found for one of the extensions - continue with that file
         $archive_file = $file_sync->getFullPath();
     } else {
         // no archive for this file
         header("HTTP/1.0 404 Not Found");
         KExternalErrors::dieGracefully();
     }
     //		echo "[$archive_file][" . file_exists ( $archive_file ) . "]";
     $mime_type = kFile::mimeType($archive_file);
     //		echo "[[$mime_type]]";
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     if ($shouldProxy || !empty($relocate)) {
         // dump the file
         kFileUtils::dumpFile($archive_file, $mime_type);
         KExternalErrors::dieGracefully();
     }
     // use new Location to add the best extension we can find for the file
     $file_ext = pathinfo($archive_file, PATHINFO_EXTENSION);
     if ($file_ext != "flv") {
         // if the file does not end with "flv" - it is the real extension
         $ext = $file_ext;
     } else {
         // for now - if "flv" return "flv" - // TODO - find the real extension from the file itself
         $ext = "flv";
     }
     // rebuild the URL and redirect to it with extraa parameters
     $url = $_SERVER["REQUEST_URI"];
     $format = $this->getRequestParameter("format");
     if (!$format) {
         $url = str_replace("format", "", $url);
     }
     if (!$ret_file_name) {
         // don't leave the name empty - if it is empty - use the entry id
         $ret_file_name = $entry_id;
     }
     $ret_file_name_safe = str_replace(' ', '-', $ret_file_name);
     // spaces replace with "-"
     $ret_file_name_safe = preg_replace('/[^a-zA-Z0-9-_]/', '', $ret_file_name_safe);
     // only "a-z", "A-Z", "0-9", "-" & "_" are left
     if (strpos($url, "?") > 0) {
         $url = str_replace("?", "/{$ret_file_name_safe}.{$ext}?", $url);
         $url .= "&relocate=f.{$ext}";
         // add the ufname as a query parameter
     } else {
         $url .= "/{$ret_file_name_safe}.{$ext}?relocate=f.{$ext}";
         // add the ufname as a query parameter
     }
     // or redirect if no proxy
     header("Location: {$url}");
     KExternalErrors::dieGracefully();
 }
Esempio n. 15
0
        $responseHeaders = $this->getResponseHeaders();
        foreach ($responseHeaders as $header) {
            if (preg_match('/HTTP\\/?[\\d.]{0,3} ([\\d]{3}) ([^\\n\\r]+)/', $header, $matches)) {
                $errCode = $matches[1];
                continue;
            }
            $parts = explode(':', $header, 2);
            if (count($parts) != 2) {
                continue;
            }
            list($name, $value) = $parts;
            $headers[trim(strtolower($name))] = trim($value);
        }
        $this->resetRequest();
        return $errCode;
    }
}
$config = parse_ini_file(__DIR__ . '/../config.ini', true);
$serviceUrl = $config['client-config']['protocol'] . '://' . $options['service-url'] . ':' . $config['client-config']['port'];
$clientConfig = new KalturaConfiguration();
$clientConfig->serviceUrl = $serviceUrl;
foreach ($config['config'] as $attribute => $value) {
    $clientConfig->{$attribute} = $value;
}
if (isset($options['debug'])) {
    $clientConfig->setLogger(new KalturaMonitorClientLogger());
}
$client = new KalturaMonitorClient($clientConfig);
foreach ($config['client-config'] as $attribute => $value) {
    $client->setClientConfiguration($attribute, $value);
}
Esempio n. 16
0
 public function onRequestEnd($success = true, $errorCode = null, $requestIndex = 0)
 {
     $duration = microtime(true) - $this->requestStart;
     KalturaLog::analytics(array('request_end', 'partnerId' => kCurrentContext::$partner_id, 'masterPartnerId' => kCurrentContext::$master_partner_id, 'ks' => kCurrentContext::$ks, 'isAdmin' => intval(kCurrentContext::$is_admin_session), 'kuserId' => '"' . str_replace('"', '\\"', kCurrentContext::$uid ? kCurrentContext::$uid : kCurrentContext::$ks_uid) . '"', 'duration' => $duration, 'success' => intval($success), 'errorCode' => $errorCode, 'requestIndex' => $requestIndex));
     KalturaMonitorClient::monitorApiEnd($errorCode);
 }
Esempio n. 17
0
 public function query()
 {
     kApiCache::disableConditionalCache();
     $args = func_get_args();
     $sql = $args[0];
     KalturaLog::debug($sql);
     $comment = $this->getCommentWrapped();
     $sql = $comment . $sql;
     $sqlStart = microtime(true);
     try {
         if (version_compare(PHP_VERSION, '5.3', '<')) {
             $result = call_user_func_array(array($this, 'parent::query'), $args);
         } else {
             $result = call_user_func_array('parent::query', $args);
         }
     } catch (PropelException $pex) {
         KalturaLog::alert($pex->getMessage());
         throw new PropelException("Database error");
     }
     $sqlTook = microtime(true) - $sqlStart;
     KalturaLog::debug("Sql took - " . $sqlTook . " seconds");
     KalturaMonitorClient::monitorDatabaseAccess($sql, $sqlTook, $this->hostName);
     return $result;
 }
Esempio n. 18
0
 public static function monitorApiStart($cached, $action, $partnerId, $sessionType, $clientTag, $isInMultiRequest = false)
 {
     if ($partnerId == -1) {
         $splittedClientTag = explode(' ', $clientTag);
         $partnerIdIndex = array_search('partnerId:', $splittedClientTag);
         if ($partnerIdIndex !== false && isset($splittedClientTag[$partnerIdIndex + 1])) {
             $partnerId = $splittedClientTag[$partnerIdIndex + 1];
         }
     }
     self::initApiMonitor($cached, $action, $partnerId, $clientTag);
     if (!self::$stream) {
         return;
     }
     self::$basicApiInfo = array(self::FIELD_CACHED => $cached, self::FIELD_KS_TYPE => $sessionType, self::FIELD_MULTIREQUEST => $isInMultiRequest);
     $data = array_merge(self::$basicEventInfo, self::$basicApiInfo, array(self::FIELD_EVENT_TYPE => self::EVENT_API_START));
     self::writeEvent($data);
 }